Move `org-trim' in "org-macs.el"
[org-mode/org-tableheadings.git] / lisp / org.el
blobaf92fde53f45b13a8c916dc5547591e9cc6bb3a2
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 <https://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-shrink "org-table" (&optional begin end))
178 (declare-function org-table-toggle-column-width "org-table" (&optional arg))
179 (declare-function org-table-wrap-region "org-table" (arg))
180 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
181 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
182 (declare-function orgtbl-mode "org-table" (&optional arg))
183 (declare-function org-export-get-backend "ox" (name))
184 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
185 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
187 (defvar ffap-url-regexp) ;Silence byte-compiler
189 (defsubst org-uniquify (list)
190 "Non-destructively remove duplicate elements from LIST."
191 (let ((res (copy-sequence list))) (delete-dups res)))
193 (defsubst org-get-at-bol (property)
194 "Get text property PROPERTY at the beginning of line."
195 (get-text-property (point-at-bol) property))
197 ;; load languages based on value of `org-babel-load-languages'
198 (defvar org-babel-load-languages)
200 ;;;###autoload
201 (defun org-babel-do-load-languages (sym value)
202 "Load the languages defined in `org-babel-load-languages'."
203 (set-default sym value)
204 (dolist (pair org-babel-load-languages)
205 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
206 (if active
207 (require (intern (concat "ob-" lang)))
208 (funcall 'fmakunbound
209 (intern (concat "org-babel-execute:" lang)))
210 (funcall 'fmakunbound
211 (intern (concat "org-babel-expand-body:" lang)))))))
213 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
214 ;;;###autoload
215 (defun org-babel-load-file (file &optional compile)
216 "Load Emacs Lisp source code blocks in the Org FILE.
217 This function exports the source code using `org-babel-tangle'
218 and then loads the resulting file using `load-file'. With prefix
219 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
220 file to byte-code before it is loaded."
221 (interactive "fFile to load: \nP")
222 (let* ((age (lambda (file)
223 (float-time
224 (time-subtract (current-time)
225 (nth 5 (or (file-attributes (file-truename file))
226 (file-attributes file)))))))
227 (base-name (file-name-sans-extension file))
228 (exported-file (concat base-name ".el")))
229 ;; tangle if the Org file is newer than the elisp file
230 (unless (and (file-exists-p exported-file)
231 (> (funcall age file) (funcall age exported-file)))
232 ;; Tangle-file traversal returns reversed list of tangled files
233 ;; and we want to evaluate the first target.
234 (setq exported-file
235 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
236 (message "%s %s"
237 (if compile
238 (progn (byte-compile-file exported-file 'load)
239 "Compiled and loaded")
240 (progn (load-file exported-file) "Loaded"))
241 exported-file)))
243 (defcustom org-babel-load-languages '((emacs-lisp . t))
244 "Languages which can be evaluated in Org buffers.
245 This list can be used to load support for any of the languages
246 below, note that each language will depend on a different set of
247 system executables and/or Emacs modes. When a language is
248 \"loaded\", then code blocks in that language can be evaluated
249 with `org-babel-execute-src-block' bound by default to C-c
250 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
251 be set to remove code block evaluation from the C-c C-c
252 keybinding. By default only Emacs Lisp (which has no
253 requirements) is loaded."
254 :group 'org-babel
255 :set 'org-babel-do-load-languages
256 :version "24.1"
257 :type '(alist :tag "Babel Languages"
258 :key-type
259 (choice
260 (const :tag "Awk" awk)
261 (const :tag "C" C)
262 (const :tag "R" R)
263 (const :tag "Asymptote" asymptote)
264 (const :tag "Calc" calc)
265 (const :tag "Clojure" clojure)
266 (const :tag "CSS" css)
267 (const :tag "Ditaa" ditaa)
268 (const :tag "Dot" dot)
269 (const :tag "Ebnf2ps" ebnf2ps)
270 (const :tag "Emacs Lisp" emacs-lisp)
271 (const :tag "Forth" forth)
272 (const :tag "Fortran" fortran)
273 (const :tag "Gnuplot" gnuplot)
274 (const :tag "Haskell" haskell)
275 (const :tag "hledger" hledger)
276 (const :tag "IO" io)
277 (const :tag "J" J)
278 (const :tag "Java" java)
279 (const :tag "Javascript" js)
280 (const :tag "LaTeX" latex)
281 (const :tag "Ledger" ledger)
282 (const :tag "Lilypond" lilypond)
283 (const :tag "Lisp" lisp)
284 (const :tag "Makefile" makefile)
285 (const :tag "Maxima" maxima)
286 (const :tag "Matlab" matlab)
287 (const :tag "Mscgen" mscgen)
288 (const :tag "Ocaml" ocaml)
289 (const :tag "Octave" octave)
290 (const :tag "Org" org)
291 (const :tag "Perl" perl)
292 (const :tag "Pico Lisp" picolisp)
293 (const :tag "PlantUML" plantuml)
294 (const :tag "Python" python)
295 (const :tag "Ruby" ruby)
296 (const :tag "Sass" sass)
297 (const :tag "Scala" scala)
298 (const :tag "Scheme" scheme)
299 (const :tag "Screen" screen)
300 (const :tag "Shell Script" shell)
301 (const :tag "Shen" shen)
302 (const :tag "Sql" sql)
303 (const :tag "Sqlite" sqlite)
304 (const :tag "Stan" stan)
305 (const :tag "Vala" vala))
306 :value-type (boolean :tag "Activate" :value t)))
308 ;;;; Customization variables
309 (defcustom org-clone-delete-id nil
310 "Remove ID property of clones of a subtree.
311 When non-nil, clones of a subtree don't inherit the ID property.
312 Otherwise they inherit the ID property with a new unique
313 identifier."
314 :type 'boolean
315 :version "24.1"
316 :group 'org-id)
318 ;;; Version
319 (org-check-version)
321 ;;;###autoload
322 (defun org-version (&optional here full message)
323 "Show the Org version.
324 Interactively, or when MESSAGE is non-nil, show it in echo area.
325 With prefix argument, or when HERE is non-nil, insert it at point.
326 In non-interactive uses, a reduced version string is output unless
327 FULL is given."
328 (interactive (list current-prefix-arg t (not current-prefix-arg)))
329 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
330 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
331 (load-suffixes (list ".el"))
332 (org-install-dir
333 (ignore-errors (org-find-library-dir "org-loaddefs"))))
334 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
335 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
336 (let* ((load-suffixes save-load-suffixes)
337 (release (org-release))
338 (git-version (org-git-version))
339 (version (format "Org mode version %s (%s @ %s)"
340 release
341 git-version
342 (if org-install-dir
343 (if (string= org-dir org-install-dir)
344 org-install-dir
345 (concat "mixed installation! "
346 org-install-dir
347 " and "
348 org-dir))
349 "org-loaddefs.el can not be found!")))
350 (version1 (if full version release)))
351 (when here (insert version1))
352 (when message (message "%s" version1))
353 version1)))
355 (defconst org-version (org-version))
358 ;;; Syntax Constants
360 ;;;; Block
362 (defconst org-block-regexp
363 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
364 "Regular expression for hiding blocks.")
366 (defconst org-dblock-start-re
367 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
368 "Matches the start line of a dynamic block, with parameters.")
370 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
371 "Matches the end of a dynamic block.")
373 ;;;; Clock and Planning
375 (defconst org-clock-string "CLOCK:"
376 "String used as prefix for timestamps clocking work hours on an item.")
378 (defvar org-closed-string "CLOSED:"
379 "String used as the prefix for timestamps logging closing a TODO entry.")
381 (defvar org-deadline-string "DEADLINE:"
382 "String to mark deadline entries.
383 \\<org-mode-map>
384 A deadline is this string, followed by a time stamp. It must be
385 a word, terminated by a colon. You can insert a schedule keyword
386 and a timestamp with `\\[org-deadline]'.")
388 (defvar org-scheduled-string "SCHEDULED:"
389 "String to mark scheduled TODO entries.
390 \\<org-mode-map>
391 A schedule is this string, followed by a time stamp. It must be
392 a word, terminated by a colon. You can insert a schedule keyword
393 and a timestamp with `\\[org-schedule]'.")
395 (defconst org-ds-keyword-length
396 (+ 2
397 (apply #'max
398 (mapcar #'length
399 (list org-deadline-string org-scheduled-string
400 org-clock-string org-closed-string))))
401 "Maximum length of the DEADLINE and SCHEDULED keywords.")
403 (defconst org-planning-line-re
404 (concat "^[ \t]*"
405 (regexp-opt
406 (list org-closed-string org-deadline-string org-scheduled-string)
408 "Matches a line with planning info.
409 Matched keyword is in group 1.")
411 (defconst org-clock-line-re
412 (concat "^[ \t]*" org-clock-string)
413 "Matches a line with clock info.")
415 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
416 "Matches the DEADLINE keyword.")
418 (defconst org-deadline-time-regexp
419 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
420 "Matches the DEADLINE keyword together with a time stamp.")
422 (defconst org-deadline-time-hour-regexp
423 (concat "\\<" org-deadline-string
424 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
425 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
427 (defconst org-deadline-line-regexp
428 (concat "\\<\\(" org-deadline-string "\\).*")
429 "Matches the DEADLINE keyword and the rest of the line.")
431 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
432 "Matches the SCHEDULED keyword.")
434 (defconst org-scheduled-time-regexp
435 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
436 "Matches the SCHEDULED keyword together with a time stamp.")
438 (defconst org-scheduled-time-hour-regexp
439 (concat "\\<" org-scheduled-string
440 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
441 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
443 (defconst org-closed-time-regexp
444 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
445 "Matches the CLOSED keyword together with a time stamp.")
447 (defconst org-keyword-time-regexp
448 (concat "\\<"
449 (regexp-opt
450 (list org-scheduled-string org-deadline-string org-closed-string
451 org-clock-string)
453 " *[[<]\\([^]>]+\\)[]>]")
454 "Matches any of the 4 keywords, together with the time stamp.")
456 (defconst org-keyword-time-not-clock-regexp
457 (concat
458 "\\<"
459 (regexp-opt
460 (list org-scheduled-string org-deadline-string org-closed-string) t)
461 " *[[<]\\([^]>]+\\)[]>]")
462 "Matches any of the 3 keywords, together with the time stamp.")
464 (defconst org-maybe-keyword-time-regexp
465 (concat "\\(\\<"
466 (regexp-opt
467 (list org-scheduled-string org-deadline-string org-closed-string
468 org-clock-string)
470 "\\)?"
471 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
472 "\\|"
473 "<%%([^\r\n>]*>\\)")
474 "Matches a timestamp, possibly preceded by a keyword.")
476 (defconst org-all-time-keywords
477 (mapcar (lambda (w) (substring w 0 -1))
478 (list org-scheduled-string org-deadline-string
479 org-clock-string org-closed-string))
480 "List of time keywords.")
482 ;;;; Drawer
484 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
485 "Matches first or last line of a hidden block.
486 Group 1 contains drawer's name or \"END\".")
488 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
489 "Regular expression matching the first line of a property drawer.")
491 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
492 "Regular expression matching the last line of a property drawer.")
494 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
495 "Regular expression matching the first line of a clock drawer.")
497 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
498 "Regular expression matching the last line of a clock drawer.")
500 (defconst org-property-drawer-re
501 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
502 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
503 "[ \t]*:END:[ \t]*$")
504 "Matches an entire property drawer.")
506 (defconst org-clock-drawer-re
507 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
508 org-clock-drawer-end-re "\\)\n?")
509 "Matches an entire clock drawer.")
511 ;;;; Headline
513 (defconst org-heading-keyword-regexp-format
514 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
515 "Printf format for a regexp matching a headline with some keyword.
516 This regexp will match the headline of any node which has the
517 exact keyword that is put into the format. The keyword isn't in
518 any group by default, but the stars and the body are.")
520 (defconst org-heading-keyword-maybe-regexp-format
521 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
522 "Printf format for a regexp matching a headline, possibly with some keyword.
523 This regexp can match any headline with the specified keyword, or
524 without a keyword. The keyword isn't in any group by default,
525 but the stars and the body are.")
527 (defconst org-archive-tag "ARCHIVE"
528 "The tag that marks a subtree as archived.
529 An archived subtree does not open during visibility cycling, and does
530 not contribute to the agenda listings.")
532 (eval-and-compile
533 (defconst org-comment-string "COMMENT"
534 "Entries starting with this keyword will never be exported.
535 \\<org-mode-map>
536 An entry can be toggled between COMMENT and normal with
537 `\\[org-toggle-comment]'."))
540 ;;;; LaTeX Environments and Fragments
542 (defconst org-latex-regexps
543 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
544 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
545 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
546 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
547 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
548 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
549 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
550 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
551 "Regular expressions for matching embedded LaTeX.")
553 ;;;; Node Property
555 (defconst org-effort-property "Effort"
556 "The property that is being used to keep track of effort estimates.
557 Effort estimates given in this property need to have the format H:MM.")
559 ;;;; Table
561 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
562 "Detect an org-type or table-type table.")
564 (defconst org-table-line-regexp "^[ \t]*|"
565 "Detect an org-type table line.")
567 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
568 "Detect an org-type table line.")
570 (defconst org-table-hline-regexp "^[ \t]*|-"
571 "Detect an org-type table hline.")
573 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
574 "Detect a table-type table hline.")
576 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
577 "Detect the first line outside a table when searching from within it.
578 This works for both table types.")
580 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
581 "Detect a #+TBLFM line.")
583 ;;;; Timestamp
585 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
586 "Regular expression for fast time stamp matching.")
588 (defconst org-ts-regexp-inactive
589 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
590 "Regular expression for fast inactive time stamp matching.")
592 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
593 "Regular expression for fast time stamp matching.")
595 (defconst org-ts-regexp0
596 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
597 "Regular expression matching time strings for analysis.
598 This one does not require the space after the date, so it can be used
599 on a string that terminates immediately after the date.")
601 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
602 "Regular expression matching time strings for analysis.")
604 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
605 "Regular expression matching time stamps, with groups.")
607 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
608 "Regular expression matching time stamps (also [..]), with groups.")
610 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
611 "Regular expression matching a time stamp range.")
613 (defconst org-tr-regexp-both
614 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
615 "Regular expression matching a time stamp range.")
617 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
618 org-ts-regexp "\\)?")
619 "Regular expression matching a time stamp or time stamp range.")
621 (defconst org-tsr-regexp-both
622 (concat org-ts-regexp-both "\\(--?-?"
623 org-ts-regexp-both "\\)?")
624 "Regular expression matching a time stamp or time stamp range.
625 The time stamps may be either active or inactive.")
627 (defconst org-repeat-re
628 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
629 "Regular expression for specifying repeated events.
630 After a match, group 1 contains the repeat expression.")
632 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
633 "Formats for `format-time-string' which are used for time stamps.")
636 ;;; The custom variables
638 (defgroup org nil
639 "Outline-based notes management and organizer."
640 :tag "Org"
641 :group 'outlines
642 :group 'calendar)
644 (defcustom org-mode-hook nil
645 "Mode hook for Org mode, run after the mode was turned on."
646 :group 'org
647 :type 'hook)
649 (defcustom org-load-hook nil
650 "Hook that is run after org.el has been loaded."
651 :group 'org
652 :type 'hook)
654 (defcustom org-log-buffer-setup-hook nil
655 "Hook that is run after an Org log buffer is created."
656 :group 'org
657 :version "24.1"
658 :type 'hook)
660 (defvar org-modules) ; defined below
661 (defvar org-modules-loaded nil
662 "Have the modules been loaded already?")
664 (defun org-load-modules-maybe (&optional force)
665 "Load all extensions listed in `org-modules'."
666 (when (or force (not org-modules-loaded))
667 (dolist (ext org-modules)
668 (condition-case nil (require ext)
669 (error (message "Problems while trying to load feature `%s'" ext))))
670 (setq org-modules-loaded t)))
672 (defun org-set-modules (var value)
673 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
674 (set var value)
675 (when (featurep 'org)
676 (org-load-modules-maybe 'force)
677 (org-element-cache-reset 'all)))
679 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
680 "Modules that should always be loaded together with org.el.
682 If a description starts with <C>, the file is not part of Emacs
683 and loading it will require that you have downloaded and properly
684 installed the Org mode distribution.
686 You can also use this system to load external packages (i.e. neither Org
687 core modules, nor modules from the CONTRIB directory). Just add symbols
688 to the end of the list. If the package is called org-xyz.el, then you need
689 to add the symbol `xyz', and the package must have a call to:
691 (provide \\='org-xyz)
693 For export specific modules, see also `org-export-backends'."
694 :group 'org
695 :set 'org-set-modules
696 :version "24.4"
697 :package-version '(Org . "8.0")
698 :type
699 '(set :greedy t
700 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
701 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
702 (const :tag " crypt: Encryption of subtrees" org-crypt)
703 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
704 (const :tag " docview: Links to doc-view buffers" org-docview)
705 (const :tag " eww: Store link to url of eww" org-eww)
706 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
707 (const :tag " habit: Track your consistency with habits" org-habit)
708 (const :tag " id: Global IDs for identifying entries" org-id)
709 (const :tag " info: Links to Info nodes" org-info)
710 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
711 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
712 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
713 (const :tag " mouse: Additional mouse support" org-mouse)
714 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
715 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
716 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
718 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
719 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
720 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
721 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
722 (const :tag "C collector: Collect properties into tables" org-collector)
723 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
724 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
725 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
726 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
727 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
728 (const :tag "C eval: Include command output as text" org-eval)
729 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
730 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
731 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
732 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
733 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
734 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
735 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
736 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
737 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
738 (const :tag "C man: Support for links to manpages in Org mode" org-man)
739 (const :tag "C mew: Links to Mew folders/messages" org-mew)
740 (const :tag "C mtags: Support for muse-like tags" org-mtags)
741 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
742 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
743 (const :tag "C registry: A registry for Org links" org-registry)
744 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
745 (const :tag "C secretary: Team management with org-mode" org-secretary)
746 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
747 (const :tag "C toc: Table of contents for Org buffer" org-toc)
748 (const :tag "C track: Keep up with Org mode development" org-track)
749 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
750 (const :tag "C vm: Links to VM folders/messages" org-vm)
751 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
752 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
753 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
755 (defvar org-export-registered-backends) ; From ox.el.
756 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
757 (declare-function org-export-backend-name "ox" (backend) t)
758 (defcustom org-export-backends '(ascii html icalendar latex odt)
759 "List of export back-ends that should be always available.
761 If a description starts with <C>, the file is not part of Emacs
762 and loading it will require that you have downloaded and properly
763 installed the Org mode distribution.
765 Unlike to `org-modules', libraries in this list will not be
766 loaded along with Org, but only once the export framework is
767 needed.
769 This variable needs to be set before org.el is loaded. If you
770 need to make a change while Emacs is running, use the customize
771 interface or run the following code, where VAL stands for the new
772 value of the variable, after updating it:
774 (progn
775 (setq org-export-registered-backends
776 (cl-remove-if-not
777 (lambda (backend)
778 (let ((name (org-export-backend-name backend)))
779 (or (memq name val)
780 (catch \\='parentp
781 (dolist (b val)
782 (and (org-export-derived-backend-p b name)
783 (throw \\='parentp t)))))))
784 org-export-registered-backends))
785 (let ((new-list (mapcar #\\='org-export-backend-name
786 org-export-registered-backends)))
787 (dolist (backend val)
788 (cond
789 ((not (load (format \"ox-%s\" backend) t t))
790 (message \"Problems while trying to load export back-end \\=`%s\\='\"
791 backend))
792 ((not (memq backend new-list)) (push backend new-list))))
793 (set-default \\='org-export-backends new-list)))
795 Adding a back-end to this list will also pull the back-end it
796 depends on, if any."
797 :group 'org
798 :group 'org-export
799 :version "26.1"
800 :package-version '(Org . "9.0")
801 :initialize 'custom-initialize-set
802 :set (lambda (var val)
803 (if (not (featurep 'ox)) (set-default var val)
804 ;; Any back-end not required anymore (not present in VAL and not
805 ;; a parent of any back-end in the new value) is removed from the
806 ;; list of registered back-ends.
807 (setq org-export-registered-backends
808 (cl-remove-if-not
809 (lambda (backend)
810 (let ((name (org-export-backend-name backend)))
811 (or (memq name val)
812 (catch 'parentp
813 (dolist (b val)
814 (and (org-export-derived-backend-p b name)
815 (throw 'parentp t)))))))
816 org-export-registered-backends))
817 ;; Now build NEW-LIST of both new back-ends and required
818 ;; parents.
819 (let ((new-list (mapcar #'org-export-backend-name
820 org-export-registered-backends)))
821 (dolist (backend val)
822 (cond
823 ((not (load (format "ox-%s" backend) t t))
824 (message "Problems while trying to load export back-end `%s'"
825 backend))
826 ((not (memq backend new-list)) (push backend new-list))))
827 ;; Set VAR to that list with fixed dependencies.
828 (set-default var new-list))))
829 :type '(set :greedy t
830 (const :tag " ascii Export buffer to ASCII format" ascii)
831 (const :tag " beamer Export buffer to Beamer presentation" beamer)
832 (const :tag " html Export buffer to HTML format" html)
833 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
834 (const :tag " latex Export buffer to LaTeX format" latex)
835 (const :tag " man Export buffer to MAN format" man)
836 (const :tag " md Export buffer to Markdown format" md)
837 (const :tag " odt Export buffer to ODT format" odt)
838 (const :tag " org Export buffer to Org format" org)
839 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
840 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
841 (const :tag "C deck Export buffer to deck.js presentations" deck)
842 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
843 (const :tag "C groff Export buffer to Groff format" groff)
844 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
845 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
846 (const :tag "C s5 Export buffer to s5 presentations" s5)
847 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
849 (eval-after-load 'ox
850 '(dolist (backend org-export-backends)
851 (condition-case nil (require (intern (format "ox-%s" backend)))
852 (error (message "Problems while trying to load export back-end `%s'"
853 backend)))))
855 (defcustom org-support-shift-select nil
856 "Non-nil means make shift-cursor commands select text when possible.
857 \\<org-mode-map>\
859 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
860 start selecting a region, or enlarge regions started in this way.
861 In Org mode, in special contexts, these same keys are used for
862 other purposes, important enough to compete with shift selection.
863 Org tries to balance these needs by supporting `shift-select-mode'
864 outside these special contexts, under control of this variable.
866 The default of this variable is nil, to avoid confusing behavior. Shifted
867 cursor keys will then execute Org commands in the following contexts:
868 - on a headline, changing TODO state (left/right) and priority (up/down)
869 - on a time stamp, changing the time
870 - in a plain list item, changing the bullet type
871 - in a property definition line, switching between allowed values
872 - in the BEGIN line of a clock table (changing the time block).
873 Outside these contexts, the commands will throw an error.
875 When this variable is t and the cursor is not in a special
876 context, Org mode will support shift-selection for making and
877 enlarging regions. To make this more effective, the bullet
878 cycling will no longer happen anywhere in an item line, but only
879 if the cursor is exactly on the bullet.
881 If you set this variable to the symbol `always', then the keys
882 will not be special in headlines, property lines, and item lines,
883 to make shift selection work there as well. If this is what you
884 want, you can use the following alternative commands:
885 `\\[org-todo]' and `\\[org-priority]' \
886 to change TODO state and priority,
887 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
888 can be used to switch TODO sets,
889 `\\[org-ctrl-c-minus]' to cycle item bullet types,
890 and properties can be edited by hand or in column view.
892 However, when the cursor is on a timestamp, shift-cursor commands
893 will still edit the time stamp - this is just too good to give up."
894 :group 'org
895 :type '(choice
896 (const :tag "Never" nil)
897 (const :tag "When outside special context" t)
898 (const :tag "Everywhere except timestamps" always)))
900 (defcustom org-loop-over-headlines-in-active-region nil
901 "Shall some commands act upon headlines in the active region?
903 When set to t, some commands will be performed in all headlines
904 within the active region.
906 When set to `start-level', some commands will be performed in all
907 headlines within the active region, provided that these headlines
908 are of the same level than the first one.
910 When set to a string, those commands will be performed on the
911 matching headlines within the active region. Such string must be
912 a tags/property/todo match as it is used in the agenda tags view.
914 The list of commands is: `org-schedule', `org-deadline',
915 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
916 `org-archive-to-archive-sibling'. The archiving commands skip
917 already archived entries."
918 :type '(choice (const :tag "Don't loop" nil)
919 (const :tag "All headlines in active region" t)
920 (const :tag "In active region, headlines at the same level than the first one" start-level)
921 (string :tag "Tags/Property/Todo matcher"))
922 :version "24.1"
923 :group 'org-todo
924 :group 'org-archive)
926 (defgroup org-startup nil
927 "Options concerning startup of Org mode."
928 :tag "Org Startup"
929 :group 'org)
931 (defcustom org-startup-folded t
932 "Non-nil means entering Org mode will switch to OVERVIEW.
934 This can also be configured on a per-file basis by adding one of
935 the following lines anywhere in the buffer:
937 #+STARTUP: fold (or `overview', this is equivalent)
938 #+STARTUP: nofold (or `showall', this is equivalent)
939 #+STARTUP: content
940 #+STARTUP: showeverything
942 Set `org-agenda-inhibit-startup' to a non-nil value if you want
943 to ignore this option when Org opens agenda files for the first
944 time."
945 :group 'org-startup
946 :type '(choice
947 (const :tag "nofold: show all" nil)
948 (const :tag "fold: overview" t)
949 (const :tag "content: all headlines" content)
950 (const :tag "show everything, even drawers" showeverything)))
952 (defcustom org-startup-truncated t
953 "Non-nil means entering Org mode will set `truncate-lines'.
954 This is useful since some lines containing links can be very long and
955 uninteresting. Also tables look terrible when wrapped.
957 The variable `org-startup-truncated' allows to configure
958 truncation for Org mode different to the other modes that use the
959 variable `truncate-lines' and as a shortcut instead of putting
960 the variable `truncate-lines' into the `org-mode-hook'. If one
961 wants to configure truncation for Org mode not statically but
962 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
963 the variable `truncate-lines' has to be used because in such a
964 case it is too late to set the variable `org-startup-truncated'."
965 :group 'org-startup
966 :type 'boolean)
968 (defcustom org-startup-indented nil
969 "Non-nil means turn on `org-indent-mode' on startup.
970 This can also be configured on a per-file basis by adding one of
971 the following lines anywhere in the buffer:
973 #+STARTUP: indent
974 #+STARTUP: noindent"
975 :group 'org-structure
976 :type '(choice
977 (const :tag "Not" nil)
978 (const :tag "Globally (slow on startup in large files)" t)))
980 (defcustom org-use-sub-superscripts t
981 "Non-nil means interpret \"_\" and \"^\" for display.
983 If you want to control how Org exports those characters, see
984 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
985 used to be an alias for `org-export-with-sub-superscripts' in
986 Org <8.0, it is not anymore.
988 When this option is turned on, you can use TeX-like syntax for
989 sub- and superscripts within the buffer. Several characters after
990 \"_\" or \"^\" will be considered as a single item - so grouping
991 with {} is normally not needed. For example, the following things
992 will be parsed as single sub- or superscripts:
994 10^24 or 10^tau several digits will be considered 1 item.
995 10^-12 or 10^-tau a leading sign with digits or a word
996 x^2-y^3 will be read as x^2 - y^3, because items are
997 terminated by almost any nonword/nondigit char.
998 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1000 Still, ambiguity is possible. So when in doubt, use {} to enclose
1001 the sub/superscript. If you set this variable to the symbol `{}',
1002 the braces are *required* in order to trigger interpretations as
1003 sub/superscript. This can be helpful in documents that need \"_\"
1004 frequently in plain text."
1005 :group 'org-startup
1006 :version "24.4"
1007 :package-version '(Org . "8.0")
1008 :type '(choice
1009 (const :tag "Always interpret" t)
1010 (const :tag "Only with braces" {})
1011 (const :tag "Never interpret" nil)))
1013 (defcustom org-startup-with-beamer-mode nil
1014 "Non-nil means turn on `org-beamer-mode' on startup.
1015 This can also be configured on a per-file basis by adding one of
1016 the following lines anywhere in the buffer:
1018 #+STARTUP: beamer"
1019 :group 'org-startup
1020 :version "24.1"
1021 :type 'boolean)
1023 (defcustom org-startup-align-all-tables nil
1024 "Non-nil means align all tables when visiting a file.
1025 This can also be configured on a per-file basis by adding one of
1026 the following lines anywhere in the buffer:
1027 #+STARTUP: align
1028 #+STARTUP: noalign"
1029 :group 'org-startup
1030 :type 'boolean)
1032 (defcustom org-startup-shrink-all-tables nil
1033 "Non-nil means shrink all table columns with a width cookie.
1034 This can also be configured on a per-file basis by adding one of
1035 the following lines anywhere in the buffer:
1036 #+STARTUP: shrink"
1037 :group 'org-startup
1038 :type 'boolean
1039 :version "26.1"
1040 :package-version '(Org . "9.1")
1041 :safe #'booleanp)
1043 (defcustom org-startup-with-inline-images nil
1044 "Non-nil means show inline images when loading a new Org file.
1045 This can also be configured on a per-file basis by adding one of
1046 the following lines anywhere in the buffer:
1047 #+STARTUP: inlineimages
1048 #+STARTUP: noinlineimages"
1049 :group 'org-startup
1050 :version "24.1"
1051 :type 'boolean)
1053 (defcustom org-startup-with-latex-preview nil
1054 "Non-nil means preview LaTeX fragments when loading a new Org file.
1056 This can also be configured on a per-file basis by adding one of
1057 the following lines anywhere in the buffer:
1058 #+STARTUP: latexpreview
1059 #+STARTUP: nolatexpreview"
1060 :group 'org-startup
1061 :version "24.4"
1062 :package-version '(Org . "8.0")
1063 :type 'boolean)
1065 (defcustom org-insert-mode-line-in-empty-file nil
1066 "Non-nil means insert the first line setting Org mode in empty files.
1067 When the function `org-mode' is called interactively in an empty file, this
1068 normally means that the file name does not automatically trigger Org mode.
1069 To ensure that the file will always be in Org mode in the future, a
1070 line enforcing Org mode will be inserted into the buffer, if this option
1071 has been set."
1072 :group 'org-startup
1073 :type 'boolean)
1075 (defcustom org-replace-disputed-keys nil
1076 "Non-nil means use alternative key bindings for some keys.
1077 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1078 These keys are also used by other packages like shift-selection-mode'
1079 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1080 If you want to use Org mode together with one of these other modes,
1081 or more generally if you would like to move some Org mode commands to
1082 other keys, set this variable and configure the keys with the variable
1083 `org-disputed-keys'.
1085 This option is only relevant at load-time of Org mode, and must be set
1086 *before* org.el is loaded. Changing it requires a restart of Emacs to
1087 become effective."
1088 :group 'org-startup
1089 :type 'boolean)
1091 (defcustom org-use-extra-keys nil
1092 "Non-nil means use extra key sequence definitions for certain commands.
1093 This happens automatically if `window-system' is nil. This
1094 variable lets you do the same manually. You must set it before
1095 loading Org."
1096 :group 'org-startup
1097 :type 'boolean)
1099 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1101 (defcustom org-disputed-keys
1102 '(([(shift up)] . [(meta p)])
1103 ([(shift down)] . [(meta n)])
1104 ([(shift left)] . [(meta -)])
1105 ([(shift right)] . [(meta +)])
1106 ([(control shift right)] . [(meta shift +)])
1107 ([(control shift left)] . [(meta shift -)]))
1108 "Keys for which Org mode and other modes compete.
1109 This is an alist, cars are the default keys, second element specifies
1110 the alternative to use when `org-replace-disputed-keys' is t.
1112 Keys can be specified in any syntax supported by `define-key'.
1113 The value of this option takes effect only at Org mode startup,
1114 therefore you'll have to restart Emacs to apply it after changing."
1115 :group 'org-startup
1116 :type 'alist)
1118 (defun org-key (key)
1119 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1120 Or return the original if not disputed."
1121 (when org-replace-disputed-keys
1122 (let* ((nkey (key-description key))
1123 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1124 org-disputed-keys)))
1125 (setq key (if x (cdr x) key))))
1126 key)
1128 (defun org-defkey (keymap key def)
1129 "Define a key, possibly translated, as returned by `org-key'."
1130 (define-key keymap (org-key key) def))
1132 (defcustom org-ellipsis nil
1133 "The ellipsis to use in the Org mode outline.
1135 When nil, just use the standard three dots. When a non-empty string,
1136 use that string instead.
1138 The change affects only Org mode (which will then use its own display table).
1139 Changing this requires executing `\\[org-mode]' in a buffer to become
1140 effective."
1141 :group 'org-startup
1142 :type '(choice (const :tag "Default" nil)
1143 (string :tag "String" :value "...#"))
1144 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1146 (defvar org-display-table nil
1147 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1149 (defgroup org-keywords nil
1150 "Keywords in Org mode."
1151 :tag "Org Keywords"
1152 :group 'org)
1154 (defcustom org-closed-keep-when-no-todo nil
1155 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1156 :group 'org-todo
1157 :group 'org-keywords
1158 :version "24.4"
1159 :package-version '(Org . "8.0")
1160 :type 'boolean)
1162 (defgroup org-structure nil
1163 "Options concerning the general structure of Org files."
1164 :tag "Org Structure"
1165 :group 'org)
1167 (defgroup org-reveal-location nil
1168 "Options about how to make context of a location visible."
1169 :tag "Org Reveal Location"
1170 :group 'org-structure)
1172 (defcustom org-show-context-detail '((agenda . local)
1173 (bookmark-jump . lineage)
1174 (isearch . lineage)
1175 (default . ancestors))
1176 "Alist between context and visibility span when revealing a location.
1178 \\<org-mode-map>Some actions may move point into invisible
1179 locations. As a consequence, Org always expose a neighborhood
1180 around point. How much is shown depends on the initial action,
1181 or context. Valid contexts are
1183 agenda when exposing an entry from the agenda
1184 org-goto when using the command `org-goto' (`\\[org-goto]')
1185 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1186 tags-tree when constructing a sparse tree based on tags matches
1187 link-search when exposing search matches associated with a link
1188 mark-goto when exposing the jump goal of a mark
1189 bookmark-jump when exposing a bookmark location
1190 isearch when exiting from an incremental search
1191 default default for all contexts not set explicitly
1193 Allowed visibility spans are
1195 minimal show current headline; if point is not on headline,
1196 also show entry
1198 local show current headline, entry and next headline
1200 ancestors show current headline and its direct ancestors; if
1201 point is not on headline, also show entry
1203 lineage show current headline, its direct ancestors and all
1204 their children; if point is not on headline, also show
1205 entry and first child
1207 tree show current headline, its direct ancestors and all
1208 their children; if point is not on headline, also show
1209 entry and all children
1211 canonical show current headline, its direct ancestors along with
1212 their entries and children; if point is not located on
1213 the headline, also show current entry and all children
1215 As special cases, a nil or t value means show all contexts in
1216 `minimal' or `canonical' view, respectively.
1218 Some views can make displayed information very compact, but also
1219 make it harder to edit the location of the match. In such
1220 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1221 more context."
1222 :group 'org-reveal-location
1223 :version "26.1"
1224 :package-version '(Org . "9.0")
1225 :type '(choice
1226 (const :tag "Canonical" t)
1227 (const :tag "Minimal" nil)
1228 (repeat :greedy t :tag "Individual contexts"
1229 (cons
1230 (choice :tag "Context"
1231 (const agenda)
1232 (const org-goto)
1233 (const occur-tree)
1234 (const tags-tree)
1235 (const link-search)
1236 (const mark-goto)
1237 (const bookmark-jump)
1238 (const isearch)
1239 (const default))
1240 (choice :tag "Detail level"
1241 (const minimal)
1242 (const local)
1243 (const ancestors)
1244 (const lineage)
1245 (const tree)
1246 (const canonical))))))
1248 (defcustom org-indirect-buffer-display 'other-window
1249 "How should indirect tree buffers be displayed?
1251 This applies to indirect buffers created with the commands
1252 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1254 Valid values are:
1255 current-window Display in the current window
1256 other-window Just display in another window.
1257 dedicated-frame Create one new frame, and re-use it each time.
1258 new-frame Make a new frame each time. Note that in this case
1259 previously-made indirect buffers are kept, and you need to
1260 kill these buffers yourself."
1261 :group 'org-structure
1262 :group 'org-agenda-windows
1263 :type '(choice
1264 (const :tag "In current window" current-window)
1265 (const :tag "In current frame, other window" other-window)
1266 (const :tag "Each time a new frame" new-frame)
1267 (const :tag "One dedicated frame" dedicated-frame)))
1269 (defcustom org-use-speed-commands nil
1270 "Non-nil means activate single letter commands at beginning of a headline.
1271 This may also be a function to test for appropriate locations where speed
1272 commands should be active.
1274 For example, to activate speed commands when the point is on any
1275 star at the beginning of the headline, you can do this:
1277 (setq org-use-speed-commands
1278 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1279 :group 'org-structure
1280 :type '(choice
1281 (const :tag "Never" nil)
1282 (const :tag "At beginning of headline stars" t)
1283 (function)))
1285 (defcustom org-speed-commands-user nil
1286 "Alist of additional speed commands.
1287 This list will be checked before `org-speed-commands-default'
1288 when the variable `org-use-speed-commands' is non-nil
1289 and when the cursor is at the beginning of a headline.
1290 The car if each entry is a string with a single letter, which must
1291 be assigned to `self-insert-command' in the global map.
1292 The cdr is either a command to be called interactively, a function
1293 to be called, or a form to be evaluated.
1294 An entry that is just a list with a single string will be interpreted
1295 as a descriptive headline that will be added when listing the speed
1296 commands in the Help buffer using the `?' speed command."
1297 :group 'org-structure
1298 :type '(repeat :value ("k" . ignore)
1299 (choice :value ("k" . ignore)
1300 (list :tag "Descriptive Headline" (string :tag "Headline"))
1301 (cons :tag "Letter and Command"
1302 (string :tag "Command letter")
1303 (choice
1304 (function)
1305 (sexp))))))
1307 (defcustom org-bookmark-names-plist
1308 '(:last-capture "org-capture-last-stored"
1309 :last-refile "org-refile-last-stored"
1310 :last-capture-marker "org-capture-last-stored-marker")
1311 "Names for bookmarks automatically set by some Org commands.
1312 This can provide strings as names for a number of bookmarks Org sets
1313 automatically. The following keys are currently implemented:
1314 :last-capture
1315 :last-capture-marker
1316 :last-refile
1317 When a key does not show up in the property list, the corresponding bookmark
1318 is not set."
1319 :group 'org-structure
1320 :type 'plist)
1322 (defgroup org-cycle nil
1323 "Options concerning visibility cycling in Org mode."
1324 :tag "Org Cycle"
1325 :group 'org-structure)
1327 (defcustom org-cycle-skip-children-state-if-no-children t
1328 "Non-nil means skip CHILDREN state in entries that don't have any."
1329 :group 'org-cycle
1330 :type 'boolean)
1332 (defcustom org-cycle-max-level nil
1333 "Maximum level which should still be subject to visibility cycling.
1334 Levels higher than this will, for cycling, be treated as text, not a headline.
1335 When `org-odd-levels-only' is set, a value of N in this variable actually
1336 means 2N-1 stars as the limiting headline.
1337 When nil, cycle all levels.
1338 Note that the limiting level of cycling is also influenced by
1339 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1340 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1341 than its value."
1342 :group 'org-cycle
1343 :type '(choice
1344 (const :tag "No limit" nil)
1345 (integer :tag "Maximum level")))
1347 (defcustom org-hide-block-startup nil
1348 "Non-nil means entering Org mode will fold all blocks.
1349 This can also be set in on a per-file basis with
1351 #+STARTUP: hideblocks
1352 #+STARTUP: showblocks"
1353 :group 'org-startup
1354 :group 'org-cycle
1355 :type 'boolean)
1357 (defcustom org-cycle-global-at-bob nil
1358 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1360 This makes it possible to do global cycling without having to use `S-TAB'
1361 or `\\[universal-argument] TAB'. For this special case to work, the first \
1362 line of the buffer
1363 must not be a headline -- it may be empty or some other text.
1365 When used in this way, `org-cycle-hook' is disabled temporarily to make
1366 sure the cursor stays at the beginning of the buffer.
1368 When this option is nil, don't do anything special at the beginning of
1369 the buffer."
1370 :group 'org-cycle
1371 :type 'boolean)
1373 (defcustom org-cycle-level-after-item/entry-creation t
1374 "Non-nil means cycle entry level or item indentation in new empty entries.
1376 When the cursor is at the end of an empty headline, i.e., with only stars
1377 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1378 and then all possible ancestor states, before returning to the original state.
1379 This makes data entry extremely fast: M-RET to create a new headline,
1380 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1382 When the cursor is at the end of an empty plain list item, one TAB will
1383 make it a subitem, two or more tabs will back up to make this an item
1384 higher up in the item hierarchy."
1385 :group 'org-cycle
1386 :type 'boolean)
1388 (defcustom org-cycle-emulate-tab t
1389 "Where should `org-cycle' emulate TAB.
1390 nil Never
1391 white Only in completely white lines
1392 whitestart Only at the beginning of lines, before the first non-white char
1393 t Everywhere except in headlines
1394 exc-hl-bol Everywhere except at the start of a headline
1395 If TAB is used in a place where it does not emulate TAB, the current subtree
1396 visibility is cycled."
1397 :group 'org-cycle
1398 :type '(choice (const :tag "Never" nil)
1399 (const :tag "Only in completely white lines" white)
1400 (const :tag "Before first char in a line" whitestart)
1401 (const :tag "Everywhere except in headlines" t)
1402 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1404 (defcustom org-cycle-separator-lines 2
1405 "Number of empty lines needed to keep an empty line between collapsed trees.
1406 If you leave an empty line between the end of a subtree and the following
1407 headline, this empty line is hidden when the subtree is folded.
1408 Org mode will leave (exactly) one empty line visible if the number of
1409 empty lines is equal or larger to the number given in this variable.
1410 So the default 2 means at least 2 empty lines after the end of a subtree
1411 are needed to produce free space between a collapsed subtree and the
1412 following headline.
1414 If the number is negative, and the number of empty lines is at least -N,
1415 all empty lines are shown.
1417 Special case: when 0, never leave empty lines in collapsed view."
1418 :group 'org-cycle
1419 :type 'integer)
1420 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1422 (defcustom org-pre-cycle-hook nil
1423 "Hook that is run before visibility cycling is happening.
1424 The function(s) in this hook must accept a single argument which indicates
1425 the new state that will be set right after running this hook. The
1426 argument is a symbol. Before a global state change, it can have the values
1427 `overview', `content', or `all'. Before a local state change, it can have
1428 the values `folded', `children', or `subtree'."
1429 :group 'org-cycle
1430 :type 'hook)
1432 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1433 org-cycle-hide-drawers
1434 org-cycle-show-empty-lines
1435 org-optimize-window-after-visibility-change)
1436 "Hook that is run after `org-cycle' has changed the buffer visibility.
1437 The function(s) in this hook must accept a single argument which indicates
1438 the new state that was set by the most recent `org-cycle' command. The
1439 argument is a symbol. After a global state change, it can have the values
1440 `overview', `contents', or `all'. After a local state change, it can have
1441 the values `folded', `children', or `subtree'."
1442 :group 'org-cycle
1443 :type 'hook
1444 :version "26.1"
1445 :package-version '(Org . "8.3"))
1447 (defgroup org-edit-structure nil
1448 "Options concerning structure editing in Org mode."
1449 :tag "Org Edit Structure"
1450 :group 'org-structure)
1452 (defcustom org-odd-levels-only nil
1453 "Non-nil means skip even levels and only use odd levels for the outline.
1454 This has the effect that two stars are being added/taken away in
1455 promotion/demotion commands. It also influences how levels are
1456 handled by the exporters.
1457 Changing it requires restart of `font-lock-mode' to become effective
1458 for fontification also in regions already fontified.
1459 You may also set this on a per-file basis by adding one of the following
1460 lines to the buffer:
1462 #+STARTUP: odd
1463 #+STARTUP: oddeven"
1464 :group 'org-edit-structure
1465 :group 'org-appearance
1466 :type 'boolean)
1468 (defcustom org-adapt-indentation t
1469 "Non-nil means adapt indentation to outline node level.
1471 When this variable is set, Org assumes that you write outlines by
1472 indenting text in each node to align with the headline (after the
1473 stars). The following issues are influenced by this variable:
1475 - The indentation is increased by one space in a demotion
1476 command, and decreased by one in a promotion command. However,
1477 in the latter case, if shifting some line in the entry body
1478 would alter document structure (e.g., insert a new headline),
1479 indentation is not changed at all.
1481 - Property drawers and planning information is inserted indented
1482 when this variable is set. When nil, they will not be indented.
1484 - TAB indents a line relative to current level. The lines below
1485 a headline will be indented when this variable is set.
1487 Note that this is all about true indentation, by adding and
1488 removing space characters. See also `org-indent.el' which does
1489 level-dependent indentation in a virtual way, i.e. at display
1490 time in Emacs."
1491 :group 'org-edit-structure
1492 :type 'boolean)
1494 (defcustom org-special-ctrl-a/e nil
1495 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1497 When t, `C-a' will bring back the cursor to the beginning of the
1498 headline text, i.e. after the stars and after a possible TODO
1499 keyword. In an item, this will be the position after bullet and
1500 check-box, if any. When the cursor is already at that position,
1501 another `C-a' will bring it to the beginning of the line.
1503 `C-e' will jump to the end of the headline, ignoring the presence
1504 of tags in the headline. A second `C-e' will then jump to the
1505 true end of the line, after any tags. This also means that, when
1506 this variable is non-nil, `C-e' also will never jump beyond the
1507 end of the heading of a folded section, i.e. not after the
1508 ellipses.
1510 When set to the symbol `reversed', the first `C-a' or `C-e' works
1511 normally, going to the true line boundary first. Only a directly
1512 following, identical keypress will bring the cursor to the
1513 special positions.
1515 This may also be a cons cell where the behavior for `C-a' and
1516 `C-e' is set separately."
1517 :group 'org-edit-structure
1518 :type '(choice
1519 (const :tag "off" nil)
1520 (const :tag "on: after stars/bullet and before tags first" t)
1521 (const :tag "reversed: true line boundary first" reversed)
1522 (cons :tag "Set C-a and C-e separately"
1523 (choice :tag "Special C-a"
1524 (const :tag "off" nil)
1525 (const :tag "on: after stars/bullet first" t)
1526 (const :tag "reversed: before stars/bullet first" reversed))
1527 (choice :tag "Special C-e"
1528 (const :tag "off" nil)
1529 (const :tag "on: before tags first" t)
1530 (const :tag "reversed: after tags first" reversed)))))
1531 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1533 (defcustom org-special-ctrl-k nil
1534 "Non-nil means `C-k' will behave specially in headlines.
1535 When nil, `C-k' will call the default `kill-line' command.
1536 When t, the following will happen while the cursor is in the headline:
1538 - When the cursor is at the beginning of a headline, kill the entire
1539 line and possible the folded subtree below the line.
1540 - When in the middle of the headline text, kill the headline up to the tags.
1541 - When after the headline text, kill the tags."
1542 :group 'org-edit-structure
1543 :type 'boolean)
1545 (defcustom org-ctrl-k-protect-subtree nil
1546 "Non-nil means, do not delete a hidden subtree with C-k.
1547 When set to the symbol `error', simply throw an error when C-k is
1548 used to kill (part-of) a headline that has hidden text behind it.
1549 Any other non-nil value will result in a query to the user, if it is
1550 OK to kill that hidden subtree. When nil, kill without remorse."
1551 :group 'org-edit-structure
1552 :version "24.1"
1553 :type '(choice
1554 (const :tag "Do not protect hidden subtrees" nil)
1555 (const :tag "Protect hidden subtrees with a security query" t)
1556 (const :tag "Never kill a hidden subtree with C-k" error)))
1558 (defcustom org-special-ctrl-o t
1559 "Non-nil means, make `C-o' insert a row in tables."
1560 :group 'org-edit-structure
1561 :type 'boolean)
1563 (defcustom org-catch-invisible-edits nil
1564 "Check if in invisible region before inserting or deleting a character.
1565 Valid values are:
1567 nil Do not check, so just do invisible edits.
1568 error Throw an error and do nothing.
1569 show Make point visible, and do the requested edit.
1570 show-and-error Make point visible, then throw an error and abort the edit.
1571 smart Make point visible, and do insertion/deletion if it is
1572 adjacent to visible text and the change feels predictable.
1573 Never delete a previously invisible character or add in the
1574 middle or right after an invisible region. Basically, this
1575 allows insertion and backward-delete right before ellipses.
1576 FIXME: maybe in this case we should not even show?"
1577 :group 'org-edit-structure
1578 :version "24.1"
1579 :type '(choice
1580 (const :tag "Do not check" nil)
1581 (const :tag "Throw error when trying to edit" error)
1582 (const :tag "Unhide, but do not do the edit" show-and-error)
1583 (const :tag "Show invisible part and do the edit" show)
1584 (const :tag "Be smart and do the right thing" smart)))
1586 (defcustom org-yank-folded-subtrees t
1587 "Non-nil means when yanking subtrees, fold them.
1588 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1589 it starts with a heading and all other headings in it are either children
1590 or siblings, then fold all the subtrees. However, do this only if no
1591 text after the yank would be swallowed into a folded tree by this action."
1592 :group 'org-edit-structure
1593 :type 'boolean)
1595 (defcustom org-yank-adjusted-subtrees nil
1596 "Non-nil means when yanking subtrees, adjust the level.
1597 With this setting, `org-paste-subtree' is used to insert the subtree, see
1598 this function for details."
1599 :group 'org-edit-structure
1600 :type 'boolean)
1602 (defcustom org-M-RET-may-split-line '((default . t))
1603 "Non-nil means M-RET will split the line at the cursor position.
1604 When nil, it will go to the end of the line before making a
1605 new line.
1606 You may also set this option in a different way for different
1607 contexts. Valid contexts are:
1609 headline when creating a new headline
1610 item when creating a new item
1611 table in a table field
1612 default the value to be used for all contexts not explicitly
1613 customized"
1614 :group 'org-structure
1615 :group 'org-table
1616 :type '(choice
1617 (const :tag "Always" t)
1618 (const :tag "Never" nil)
1619 (repeat :greedy t :tag "Individual contexts"
1620 (cons
1621 (choice :tag "Context"
1622 (const headline)
1623 (const item)
1624 (const table)
1625 (const default))
1626 (boolean)))))
1629 (defcustom org-insert-heading-respect-content nil
1630 "Non-nil means insert new headings after the current subtree.
1631 \\<org-mode-map>
1632 When nil, the new heading is created directly after the current line.
1633 The commands `\\[org-insert-heading-respect-content]' and \
1634 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1635 for the duration of the command."
1636 :group 'org-structure
1637 :type 'boolean)
1639 (defcustom org-blank-before-new-entry '((heading . auto)
1640 (plain-list-item . auto))
1641 "Should `org-insert-heading' leave a blank line before new heading/item?
1642 The value is an alist, with `heading' and `plain-list-item' as CAR,
1643 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1644 which case Org will look at the surrounding headings/items and try to
1645 make an intelligent decision whether to insert a blank line or not."
1646 :group 'org-edit-structure
1647 :type '(list
1648 (cons (const heading)
1649 (choice (const :tag "Never" nil)
1650 (const :tag "Always" t)
1651 (const :tag "Auto" auto)))
1652 (cons (const plain-list-item)
1653 (choice (const :tag "Never" nil)
1654 (const :tag "Always" t)
1655 (const :tag "Auto" auto)))))
1657 (defcustom org-insert-heading-hook nil
1658 "Hook being run after inserting a new heading."
1659 :group 'org-edit-structure
1660 :type 'hook)
1662 (defcustom org-enable-fixed-width-editor t
1663 "Non-nil means lines starting with \":\" are treated as fixed-width.
1664 This currently only means they are never auto-wrapped.
1665 When nil, such lines will be treated like ordinary lines."
1666 :group 'org-edit-structure
1667 :type 'boolean)
1669 (defcustom org-goto-auto-isearch t
1670 "Non-nil means typing characters in `org-goto' starts incremental search.
1671 When nil, you can use these keybindings to navigate the buffer:
1673 q Quit the org-goto interface
1674 n Go to the next visible heading
1675 p Go to the previous visible heading
1676 f Go one heading forward on same level
1677 b Go one heading backward on same level
1678 u Go one heading up"
1679 :group 'org-edit-structure
1680 :type 'boolean)
1682 (defgroup org-sparse-trees nil
1683 "Options concerning sparse trees in Org mode."
1684 :tag "Org Sparse Trees"
1685 :group 'org-structure)
1687 (defcustom org-highlight-sparse-tree-matches t
1688 "Non-nil means highlight all matches that define a sparse tree.
1689 The highlights will automatically disappear the next time the buffer is
1690 changed by an edit command."
1691 :group 'org-sparse-trees
1692 :type 'boolean)
1694 (defcustom org-remove-highlights-with-change t
1695 "Non-nil means any change to the buffer will remove temporary highlights.
1696 \\<org-mode-map>\
1697 Such highlights are created by `org-occur' and `org-clock-display'.
1698 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1699 to get rid of the highlights.
1700 The highlights created by `org-toggle-latex-fragment' always need
1701 `\\[org-toggle-latex-fragment]' to be removed."
1702 :group 'org-sparse-trees
1703 :group 'org-time
1704 :type 'boolean)
1706 (defcustom org-occur-case-fold-search t
1707 "Non-nil means `org-occur' should be case-insensitive.
1708 If set to `smart' the search will be case-insensitive only if it
1709 doesn't specify any upper case character."
1710 :group 'org-sparse-trees
1711 :version "26.1"
1712 :type '(choice
1713 (const :tag "Case-sensitive" nil)
1714 (const :tag "Case-insensitive" t)
1715 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1717 (defcustom org-occur-hook '(org-first-headline-recenter)
1718 "Hook that is run after `org-occur' has constructed a sparse tree.
1719 This can be used to recenter the window to show as much of the structure
1720 as possible."
1721 :group 'org-sparse-trees
1722 :type 'hook)
1724 (defgroup org-imenu-and-speedbar nil
1725 "Options concerning imenu and speedbar in Org mode."
1726 :tag "Org Imenu and Speedbar"
1727 :group 'org-structure)
1729 (defcustom org-imenu-depth 2
1730 "The maximum level for Imenu access to Org headlines.
1731 This also applied for speedbar access."
1732 :group 'org-imenu-and-speedbar
1733 :type 'integer)
1735 (defgroup org-table nil
1736 "Options concerning tables in Org mode."
1737 :tag "Org Table"
1738 :group 'org)
1740 (defcustom org-self-insert-cluster-for-undo nil
1741 "Non-nil means cluster self-insert commands for undo when possible.
1742 If this is set, then, like in the Emacs command loop, 20 consecutive
1743 characters will be undone together.
1744 This is configurable, because there is some impact on typing performance."
1745 :group 'org-table
1746 :type 'boolean)
1748 (defcustom org-table-tab-recognizes-table.el t
1749 "Non-nil means TAB will automatically notice a table.el table.
1750 When it sees such a table, it moves point into it and - if necessary -
1751 calls `table-recognize-table'."
1752 :group 'org-table-editing
1753 :type 'boolean)
1755 (defgroup org-link nil
1756 "Options concerning links in Org mode."
1757 :tag "Org Link"
1758 :group 'org)
1760 (defvar-local org-link-abbrev-alist-local nil
1761 "Buffer-local version of `org-link-abbrev-alist', which see.
1762 The value of this is taken from the #+LINK lines.")
1764 (defcustom org-link-parameters
1765 '(("doi" :follow org--open-doi-link)
1766 ("elisp" :follow org--open-elisp-link)
1767 ("file" :complete org-file-complete-link)
1768 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1769 ("help" :follow org--open-help-link)
1770 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1771 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1772 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1773 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1774 ("shell" :follow org--open-shell-link))
1775 "An alist of properties that defines all the links in Org mode.
1776 The key in each association is a string of the link type.
1777 Subsequent optional elements make up a p-list of link properties.
1779 :follow - A function that takes the link path as an argument.
1781 :export - A function that takes the link path, description and
1782 export-backend as arguments.
1784 :store - A function responsible for storing the link. See the
1785 function `org-store-link-functions'.
1787 :complete - A function that inserts a link with completion. The
1788 function takes one optional prefix arg.
1790 :face - A face for the link, or a function that returns a face.
1791 The function takes one argument which is the link path. The
1792 default face is `org-link'.
1794 :mouse-face - The mouse-face. The default is `highlight'.
1796 :display - `full' will not fold the link in descriptive
1797 display. Default is `org-link'.
1799 :help-echo - A string or function that takes (window object position)
1800 as arguments and returns a string.
1802 :keymap - A keymap that is active on the link. The default is
1803 `org-mouse-map'.
1805 :htmlize-link - A function for the htmlize-link. Defaults
1806 to (list :uri \"type:path\")
1808 :activate-func - A function to run at the end of font-lock
1809 activation. The function must accept (link-start link-end path bracketp)
1810 as arguments."
1811 :group 'org-link
1812 :type '(alist :tag "Link display parameters"
1813 :value-type plist)
1814 :version "26.1"
1815 :package-version '(Org . "9.1"))
1817 (defun org-link-get-parameter (type key)
1818 "Get TYPE link property for KEY.
1819 TYPE is a string and KEY is a plist keyword."
1820 (plist-get
1821 (cdr (assoc type org-link-parameters))
1822 key))
1824 (defun org-link-set-parameters (type &rest parameters)
1825 "Set link TYPE properties to PARAMETERS.
1826 PARAMETERS should be :key val pairs."
1827 (let ((data (assoc type org-link-parameters)))
1828 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1829 (push (cons type parameters) org-link-parameters)
1830 (org-make-link-regexps)
1831 (org-element-update-syntax))))
1833 (defun org-link-types ()
1834 "Return a list of known link types."
1835 (mapcar #'car org-link-parameters))
1837 (defcustom org-link-abbrev-alist nil
1838 "Alist of link abbreviations.
1839 The car of each element is a string, to be replaced at the start of a link.
1840 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1841 links in Org buffers can have an optional tag after a double colon, e.g.,
1843 [[linkkey:tag][description]]
1845 The `linkkey' must be a single word, starting with a letter, followed
1846 by letters, numbers, `-' or `_'.
1848 If REPLACE is a string, the tag will simply be appended to create the link.
1849 If the string contains \"%s\", the tag will be inserted there. If the string
1850 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1851 at that point (see the function `url-hexify-string'). If the string contains
1852 the specifier \"%(my-function)\", then the custom function `my-function' will
1853 be invoked: this function takes the tag as its only argument and must return
1854 a string.
1856 REPLACE may also be a function that will be called with the tag as the
1857 only argument to create the link, which should be returned as a string.
1859 See the manual for examples."
1860 :group 'org-link
1861 :type '(repeat
1862 (cons
1863 (string :tag "Protocol")
1864 (choice
1865 (string :tag "Format")
1866 (function)))))
1868 (defcustom org-descriptive-links t
1869 "Non-nil means Org will display descriptive links.
1870 E.g. [[http://orgmode.org][Org website]] will be displayed as
1871 \"Org Website\", hiding the link itself and just displaying its
1872 description. When set to nil, Org will display the full links
1873 literally.
1875 You can interactively set the value of this variable by calling
1876 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1877 :group 'org-link
1878 :type 'boolean)
1880 (defcustom org-link-file-path-type 'adaptive
1881 "How the path name in file links should be stored.
1882 Valid values are:
1884 relative Relative to the current directory, i.e. the directory of the file
1885 into which the link is being inserted.
1886 absolute Absolute path, if possible with ~ for home directory.
1887 noabbrev Absolute path, no abbreviation of home directory.
1888 adaptive Use relative path for files in the current directory and sub-
1889 directories of it. For other files, use an absolute path."
1890 :group 'org-link
1891 :type '(choice
1892 (const relative)
1893 (const absolute)
1894 (const noabbrev)
1895 (const adaptive)))
1897 (defvaralias 'org-activate-links 'org-highlight-links)
1898 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1899 "Types of links that should be highlighted in Org files.
1901 This is a list of symbols, each one of them leading to the
1902 highlighting of a certain link type.
1904 You can still open links that are not highlighted.
1906 In principle, it does not hurt to turn on highlighting for all
1907 link types. There may be a small gain when turning off unused
1908 link types. The types are:
1910 bracket The recommended [[link][description]] or [[link]] links with hiding.
1911 angle Links in angular brackets that may contain whitespace like
1912 <bbdb:Carsten Dominik>.
1913 plain Plain links in normal text, no whitespace, like http://google.com.
1914 radio Text that is matched by a radio target, see manual for details.
1915 tag Tag settings in a headline (link to tag search).
1916 date Time stamps (link to calendar).
1917 footnote Footnote labels.
1919 If you set this variable during an Emacs session, use `org-mode-restart'
1920 in the Org buffer so that the change takes effect."
1921 :group 'org-link
1922 :group 'org-appearance
1923 :type '(set :greedy t
1924 (const :tag "Double bracket links" bracket)
1925 (const :tag "Angular bracket links" angle)
1926 (const :tag "Plain text links" plain)
1927 (const :tag "Radio target matches" radio)
1928 (const :tag "Tags" tag)
1929 (const :tag "Timestamps" date)
1930 (const :tag "Footnotes" footnote)))
1932 (defcustom org-make-link-description-function nil
1933 "Function to use for generating link descriptions from links.
1934 This function must take two parameters: the first one is the
1935 link, the second one is the description generated by
1936 `org-insert-link'. The function should return the description to
1937 use."
1938 :group 'org-link
1939 :type '(choice (const nil) (function)))
1941 (defgroup org-link-store nil
1942 "Options concerning storing links in Org mode."
1943 :tag "Org Store Link"
1944 :group 'org-link)
1946 (defcustom org-url-hexify-p t
1947 "When non-nil, hexify URL when creating a link."
1948 :type 'boolean
1949 :version "24.3"
1950 :group 'org-link-store)
1952 (defcustom org-email-link-description-format "Email %c: %.30s"
1953 "Format of the description part of a link to an email or usenet message.
1954 The following %-escapes will be replaced by corresponding information:
1956 %F full \"From\" field
1957 %f name, taken from \"From\" field, address if no name
1958 %T full \"To\" field
1959 %t first name in \"To\" field, address if no name
1960 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1961 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1962 %s subject
1963 %d date
1964 %m message-id.
1966 You may use normal field width specification between the % and the letter.
1967 This is for example useful to limit the length of the subject.
1969 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1970 :group 'org-link-store
1971 :type 'string)
1973 (defcustom org-from-is-user-regexp
1974 (let (r1 r2)
1975 (when (and user-mail-address (not (string= user-mail-address "")))
1976 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1977 (when (and user-full-name (not (string= user-full-name "")))
1978 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1979 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1980 "Regexp matched against the \"From:\" header of an email or usenet message.
1981 It should match if the message is from the user him/herself."
1982 :group 'org-link-store
1983 :type 'regexp)
1985 (defcustom org-context-in-file-links t
1986 "Non-nil means file links from `org-store-link' contain context.
1987 \\<org-mode-map>
1988 A search string will be added to the file name with :: as separator
1989 and used to find the context when the link is activated by the command
1990 `org-open-at-point'. When this option is t, the entire active region
1991 will be placed in the search string of the file link. If set to a
1992 positive integer, only the first n lines of context will be stored.
1994 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1995 \\[org-store-link]')
1996 negates this setting for the duration of the command."
1997 :group 'org-link-store
1998 :type '(choice boolean integer))
2000 (defcustom org-keep-stored-link-after-insertion nil
2001 "Non-nil means keep link in list for entire session.
2002 \\<org-mode-map>
2003 The command `org-store-link' adds a link pointing to the current
2004 location to an internal list. These links accumulate during a session.
2005 The command `org-insert-link' can be used to insert links into any
2006 Org file (offering completion for all stored links).
2008 When this option is nil, every link which has been inserted once using
2009 `\\[org-insert-link]' will be removed from the list, to make completing the \
2010 unused
2011 links more efficient."
2012 :group 'org-link-store
2013 :type 'boolean)
2015 (defgroup org-link-follow nil
2016 "Options concerning following links in Org mode."
2017 :tag "Org Follow Link"
2018 :group 'org-link)
2020 (defcustom org-link-translation-function nil
2021 "Function to translate links with different syntax to Org syntax.
2022 This can be used to translate links created for example by the Planner
2023 or emacs-wiki packages to Org syntax.
2024 The function must accept two parameters, a TYPE containing the link
2025 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2026 which is everything after the link protocol. It should return a cons
2027 with possibly modified values of type and path.
2028 Org contains a function for this, so if you set this variable to
2029 `org-translate-link-from-planner', you should be able follow many
2030 links created by planner."
2031 :group 'org-link-follow
2032 :type '(choice (const nil) (function)))
2034 (defcustom org-follow-link-hook nil
2035 "Hook that is run after a link has been followed."
2036 :group 'org-link-follow
2037 :type 'hook)
2039 (defcustom org-tab-follows-link nil
2040 "Non-nil means on links TAB will follow the link.
2041 Needs to be set before org.el is loaded.
2042 This really should not be used, it does not make sense, and the
2043 implementation is bad."
2044 :group 'org-link-follow
2045 :type 'boolean)
2047 (defcustom org-return-follows-link nil
2048 "Non-nil means on links RET will follow the link.
2049 In tables, the special behavior of RET has precedence."
2050 :group 'org-link-follow
2051 :type 'boolean)
2053 (defcustom org-mouse-1-follows-link
2054 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2055 "Non-nil means mouse-1 on a link will follow the link.
2056 A longer mouse click will still set point. Needs to be set
2057 before org.el is loaded."
2058 :group 'org-link-follow
2059 :version "26.1"
2060 :package-version '(Org . "8.3")
2061 :type '(choice
2062 (const :tag "A double click follows the link" double)
2063 (const :tag "Unconditionally follow the link with mouse-1" t)
2064 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2066 (defcustom org-mark-ring-length 4
2067 "Number of different positions to be recorded in the ring.
2068 Changing this requires a restart of Emacs to work correctly."
2069 :group 'org-link-follow
2070 :type 'integer)
2072 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2073 "Non-nil means internal fuzzy links can only match headlines.
2075 When nil, the a fuzzy link may point to a target or a named
2076 construct in the document. When set to the special value
2077 `query-to-create', offer to create a new headline when none
2078 matched.
2080 Spaces and statistics cookies are ignored during heading searches."
2081 :group 'org-link-follow
2082 :version "24.1"
2083 :type '(choice
2084 (const :tag "Use fuzzy text search" nil)
2085 (const :tag "Match only exact headline" t)
2086 (const :tag "Match exact headline or query to create it"
2087 query-to-create))
2088 :safe #'symbolp)
2090 (defcustom org-link-frame-setup
2091 '((vm . vm-visit-folder-other-frame)
2092 (vm-imap . vm-visit-imap-folder-other-frame)
2093 (gnus . org-gnus-no-new-news)
2094 (file . find-file-other-window)
2095 (wl . wl-other-frame))
2096 "Setup the frame configuration for following links.
2097 When following a link with Emacs, it may often be useful to display
2098 this link in another window or frame. This variable can be used to
2099 set this up for the different types of links.
2100 For VM, use any of
2101 `vm-visit-folder'
2102 `vm-visit-folder-other-window'
2103 `vm-visit-folder-other-frame'
2104 For Gnus, use any of
2105 `gnus'
2106 `gnus-other-frame'
2107 `org-gnus-no-new-news'
2108 For FILE, use any of
2109 `find-file'
2110 `find-file-other-window'
2111 `find-file-other-frame'
2112 For Wanderlust use any of
2113 `wl'
2114 `wl-other-frame'
2115 For the calendar, use the variable `calendar-setup'.
2116 For BBDB, it is currently only possible to display the matches in
2117 another window."
2118 :group 'org-link-follow
2119 :type '(list
2120 (cons (const vm)
2121 (choice
2122 (const vm-visit-folder)
2123 (const vm-visit-folder-other-window)
2124 (const vm-visit-folder-other-frame)))
2125 (cons (const vm-imap)
2126 (choice
2127 (const vm-visit-imap-folder)
2128 (const vm-visit-imap-folder-other-window)
2129 (const vm-visit-imap-folder-other-frame)))
2130 (cons (const gnus)
2131 (choice
2132 (const gnus)
2133 (const gnus-other-frame)
2134 (const org-gnus-no-new-news)))
2135 (cons (const file)
2136 (choice
2137 (const find-file)
2138 (const find-file-other-window)
2139 (const find-file-other-frame)))
2140 (cons (const wl)
2141 (choice
2142 (const wl)
2143 (const wl-other-frame)))))
2145 (defcustom org-display-internal-link-with-indirect-buffer nil
2146 "Non-nil means use indirect buffer to display infile links.
2147 Activating internal links (from one location in a file to another location
2148 in the same file) normally just jumps to the location. When the link is
2149 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2150 is displayed in
2151 another window. When this option is set, the other window actually displays
2152 an indirect buffer clone of the current buffer, to avoid any visibility
2153 changes to the current buffer."
2154 :group 'org-link-follow
2155 :type 'boolean)
2157 (defcustom org-open-non-existing-files nil
2158 "Non-nil means `org-open-file' will open non-existing files.
2159 When nil, an error will be generated.
2160 This variable applies only to external applications because they
2161 might choke on non-existing files. If the link is to a file that
2162 will be opened in Emacs, the variable is ignored."
2163 :group 'org-link-follow
2164 :type 'boolean)
2166 (defcustom org-open-directory-means-index-dot-org nil
2167 "Non-nil means a link to a directory really means to index.org.
2168 When nil, following a directory link will run dired or open a finder/explorer
2169 window on that directory."
2170 :group 'org-link-follow
2171 :type 'boolean)
2173 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2174 "Non-nil means ask for confirmation before executing shell links.
2175 Shell links can be dangerous: just think about a link
2177 [[shell:rm -rf ~/*][Google Search]]
2179 This link would show up in your Org document as \"Google Search\",
2180 but really it would remove your entire home directory.
2181 Therefore we advise against setting this variable to nil.
2182 Just change it to `y-or-n-p' if you want to confirm with a
2183 single keystroke rather than having to type \"yes\"."
2184 :group 'org-link-follow
2185 :type '(choice
2186 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2187 (const :tag "with y-or-n (faster)" y-or-n-p)
2188 (const :tag "no confirmation (dangerous)" nil)))
2189 (put 'org-confirm-shell-link-function
2190 'safe-local-variable
2191 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2193 (defcustom org-confirm-shell-link-not-regexp ""
2194 "A regexp to skip confirmation for shell links."
2195 :group 'org-link-follow
2196 :version "24.1"
2197 :type 'regexp)
2199 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2200 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2201 Elisp links can be dangerous: just think about a link
2203 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2205 This link would show up in your Org document as \"Google Search\",
2206 but really it would remove your entire home directory.
2207 Therefore we advise against setting this variable to nil.
2208 Just change it to `y-or-n-p' if you want to confirm with a
2209 single keystroke rather than having to type \"yes\"."
2210 :group 'org-link-follow
2211 :type '(choice
2212 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2213 (const :tag "with y-or-n (faster)" y-or-n-p)
2214 (const :tag "no confirmation (dangerous)" nil)))
2215 (put 'org-confirm-shell-link-function
2216 'safe-local-variable
2217 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2219 (defcustom org-confirm-elisp-link-not-regexp ""
2220 "A regexp to skip confirmation for Elisp links."
2221 :group 'org-link-follow
2222 :version "24.1"
2223 :type 'regexp)
2225 (defconst org-file-apps-defaults-gnu
2226 '((remote . emacs)
2227 (system . mailcap)
2228 (t . mailcap))
2229 "Default file applications on a UNIX or GNU/Linux system.
2230 See `org-file-apps'.")
2232 (defconst org-file-apps-defaults-macosx
2233 '((remote . emacs)
2234 (system . "open %s")
2235 ("ps.gz" . "gv %s")
2236 ("eps.gz" . "gv %s")
2237 ("dvi" . "xdvi %s")
2238 ("fig" . "xfig %s")
2239 (t . "open %s"))
2240 "Default file applications on a macOS system.
2241 The system \"open\" is known as a default, but we use X11 applications
2242 for some files for which the OS does not have a good default.
2243 See `org-file-apps'.")
2245 (defconst org-file-apps-defaults-windowsnt
2246 (list '(remote . emacs)
2247 (cons 'system (lambda (file _path)
2248 (with-no-warnings (w32-shell-execute "open" file))))
2249 (cons t (lambda (file _path)
2250 (with-no-warnings (w32-shell-execute "open" file)))))
2251 "Default file applications on a Windows NT system.
2252 The system \"open\" is used for most files.
2253 See `org-file-apps'.")
2255 (defcustom org-file-apps
2256 '((auto-mode . emacs)
2257 ("\\.mm\\'" . default)
2258 ("\\.x?html?\\'" . default)
2259 ("\\.pdf\\'" . default))
2260 "External applications for opening `file:path' items in a document.
2261 \\<org-mode-map>\
2263 Org mode uses system defaults for different file types, but
2264 you can use this variable to set the application for a given file
2265 extension. The entries in this list are cons cells where the car identifies
2266 files and the cdr the corresponding command.
2268 Possible values for the file identifier are:
2270 \"string\" A string as a file identifier can be interpreted in different
2271 ways, depending on its contents:
2273 - Alphanumeric characters only:
2274 Match links with this file extension.
2275 Example: (\"pdf\" . \"evince %s\")
2276 to open PDFs with evince.
2278 - Regular expression: Match links where the
2279 filename matches the regexp. If you want to
2280 use groups here, use shy groups.
2282 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2283 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2284 to open *.html and *.xhtml with firefox.
2286 - Regular expression which contains (non-shy) groups:
2287 Match links where the whole link, including \"::\", and
2288 anything after that, matches the regexp.
2289 In a custom command string, %1, %2, etc. are replaced with
2290 the parts of the link that were matched by the groups.
2291 For backwards compatibility, if a command string is given
2292 that does not use any of the group matches, this case is
2293 handled identically to the second one (i.e. match against
2294 file name only).
2295 In a custom function, you can access the group matches with
2296 (match-string n link).
2298 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2299 \"evince -p %1 %s\")
2300 to open [[file:document.pdf::5]] with evince at page 5.
2302 `directory' Matches a directory
2303 `remote' Matches a remote file, accessible through tramp or efs.
2304 Remote files most likely should be visited through Emacs
2305 because external applications cannot handle such paths.
2306 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2307 so all files Emacs knows how to handle. Using this with
2308 command `emacs' will open most files in Emacs. Beware that this
2309 will also open html files inside Emacs, unless you add
2310 (\"html\" . default) to the list as well.
2311 `system' The system command to open files, like `open' on Windows
2312 and macOS, and mailcap under GNU/Linux. This is the command
2313 that will be selected if you call `org-open-at-point' with a
2314 double prefix argument (`\\[universal-argument] \
2315 \\[universal-argument] \\[org-open-at-point]').
2316 t Default for files not matched by any of the other options.
2318 Possible values for the command are:
2320 `emacs' The file will be visited by the current Emacs process.
2321 `default' Use the default application for this file type, which is the
2322 association for t in the list, most likely in the system-specific
2323 part. This can be used to overrule an unwanted setting in the
2324 system-specific variable.
2325 `system' Use the system command for opening files, like \"open\".
2326 This command is specified by the entry whose car is `system'.
2327 Most likely, the system-specific version of this variable
2328 does define this command, but you can overrule/replace it
2329 here.
2330 `mailcap' Use command specified in the mailcaps.
2331 string A command to be executed by a shell; %s will be replaced
2332 by the path to the file.
2333 function A Lisp function, which will be called with two arguments:
2334 the file path and the original link string, without the
2335 \"file:\" prefix.
2337 For more examples, see the system specific constants
2338 `org-file-apps-defaults-macosx'
2339 `org-file-apps-defaults-windowsnt'
2340 `org-file-apps-defaults-gnu'."
2341 :group 'org-link-follow
2342 :type '(repeat
2343 (cons (choice :value ""
2344 (string :tag "Extension")
2345 (const :tag "System command to open files" system)
2346 (const :tag "Default for unrecognized files" t)
2347 (const :tag "Remote file" remote)
2348 (const :tag "Links to a directory" directory)
2349 (const :tag "Any files that have Emacs modes"
2350 auto-mode))
2351 (choice :value ""
2352 (const :tag "Visit with Emacs" emacs)
2353 (const :tag "Use default" default)
2354 (const :tag "Use the system command" system)
2355 (string :tag "Command")
2356 (function :tag "Function")))))
2358 (defcustom org-doi-server-url "http://dx.doi.org/"
2359 "The URL of the DOI server."
2360 :type 'string
2361 :version "24.3"
2362 :group 'org-link-follow)
2364 (defgroup org-refile nil
2365 "Options concerning refiling entries in Org mode."
2366 :tag "Org Refile"
2367 :group 'org)
2369 (defcustom org-directory "~/org"
2370 "Directory with Org files.
2371 This is just a default location to look for Org files. There is no need
2372 at all to put your files into this directory. It is used in the
2373 following situations:
2375 1. When a capture template specifies a target file that is not an
2376 absolute path. The path will then be interpreted relative to
2377 `org-directory'
2378 2. When the value of variable `org-agenda-files' is a single file, any
2379 relative paths in this file will be taken as relative to
2380 `org-directory'."
2381 :group 'org-refile
2382 :group 'org-capture
2383 :type 'directory)
2385 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2386 "Default target for storing notes.
2387 Used as a fall back file for org-capture.el, for templates that
2388 do not specify a target file."
2389 :group 'org-refile
2390 :group 'org-capture
2391 :type 'file)
2393 (defcustom org-goto-interface 'outline
2394 "The default interface to be used for `org-goto'.
2395 Allowed values are:
2396 outline The interface shows an outline of the relevant file
2397 and the correct heading is found by moving through
2398 the outline or by searching with incremental search.
2399 outline-path-completion Headlines in the current buffer are offered via
2400 completion. This is the interface also used by
2401 the refile command."
2402 :group 'org-refile
2403 :type '(choice
2404 (const :tag "Outline" outline)
2405 (const :tag "Outline-path-completion" outline-path-completion)))
2407 (defcustom org-goto-max-level 5
2408 "Maximum target level when running `org-goto' with refile interface."
2409 :group 'org-refile
2410 :type 'integer)
2412 (defcustom org-reverse-note-order nil
2413 "Non-nil means store new notes at the beginning of a file or entry.
2414 When nil, new notes will be filed to the end of a file or entry.
2415 This can also be a list with cons cells of regular expressions that
2416 are matched against file names, and values."
2417 :group 'org-capture
2418 :group 'org-refile
2419 :type '(choice
2420 (const :tag "Reverse always" t)
2421 (const :tag "Reverse never" nil)
2422 (repeat :tag "By file name regexp"
2423 (cons regexp boolean))))
2425 (defcustom org-log-refile nil
2426 "Information to record when a task is refiled.
2428 Possible values are:
2430 nil Don't add anything
2431 time Add a time stamp to the task
2432 note Prompt for a note and add it with template `org-log-note-headings'
2434 This option can also be set with on a per-file-basis with
2436 #+STARTUP: nologrefile
2437 #+STARTUP: logrefile
2438 #+STARTUP: lognoterefile
2440 You can have local logging settings for a subtree by setting the LOGGING
2441 property to one or more of these keywords.
2443 When bulk-refiling from the agenda, the value `note' is forbidden and
2444 will temporarily be changed to `time'."
2445 :group 'org-refile
2446 :group 'org-progress
2447 :version "24.1"
2448 :type '(choice
2449 (const :tag "No logging" nil)
2450 (const :tag "Record timestamp" time)
2451 (const :tag "Record timestamp with note." note)))
2453 (defcustom org-refile-targets nil
2454 "Targets for refiling entries with `\\[org-refile]'.
2455 This is a list of cons cells. Each cell contains:
2456 - a specification of the files to be considered, either a list of files,
2457 or a symbol whose function or variable value will be used to retrieve
2458 a file name or a list of file names. If you use `org-agenda-files' for
2459 that, all agenda files will be scanned for targets. Nil means consider
2460 headings in the current buffer.
2461 - A specification of how to find candidate refile targets. This may be
2462 any of:
2463 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2464 This tag has to be present in all target headlines, inheritance will
2465 not be considered.
2466 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2467 todo keyword.
2468 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2469 headlines that are refiling targets.
2470 - a cons cell (:level . N). Any headline of level N is considered a target.
2471 Note that, when `org-odd-levels-only' is set, level corresponds to
2472 order in hierarchy, not to the number of stars.
2473 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2474 Note that, when `org-odd-levels-only' is set, level corresponds to
2475 order in hierarchy, not to the number of stars.
2477 Each element of this list generates a set of possible targets.
2478 The union of these sets is presented (with completion) to
2479 the user by `org-refile'.
2481 You can set the variable `org-refile-target-verify-function' to a function
2482 to verify each headline found by the simple criteria above.
2484 When this variable is nil, all top-level headlines in the current buffer
2485 are used, equivalent to the value `((nil . (:level . 1))'."
2486 :group 'org-refile
2487 :type '(repeat
2488 (cons
2489 (choice :value org-agenda-files
2490 (const :tag "All agenda files" org-agenda-files)
2491 (const :tag "Current buffer" nil)
2492 (function) (variable) (file))
2493 (choice :tag "Identify target headline by"
2494 (cons :tag "Specific tag" (const :value :tag) (string))
2495 (cons :tag "TODO keyword" (const :value :todo) (string))
2496 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2497 (cons :tag "Level number" (const :value :level) (integer))
2498 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2500 (defcustom org-refile-target-verify-function nil
2501 "Function to verify if the headline at point should be a refile target.
2502 The function will be called without arguments, with point at the
2503 beginning of the headline. It should return t and leave point
2504 where it is if the headline is a valid target for refiling.
2506 If the target should not be selected, the function must return nil.
2507 In addition to this, it may move point to a place from where the search
2508 should be continued. For example, the function may decide that the entire
2509 subtree of the current entry should be excluded and move point to the end
2510 of the subtree."
2511 :group 'org-refile
2512 :type '(choice
2513 (const nil)
2514 (function)))
2516 (defcustom org-refile-use-cache nil
2517 "Non-nil means cache refile targets to speed up the process.
2518 \\<org-mode-map>\
2519 The cache for a particular file will be updated automatically when
2520 the buffer has been killed, or when any of the marker used for flagging
2521 refile targets no longer points at a live buffer.
2522 If you have added new entries to a buffer that might themselves be targets,
2523 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2524 if you find that easier, \
2525 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2526 \\[org-refile]'."
2527 :group 'org-refile
2528 :version "24.1"
2529 :type 'boolean)
2531 (defcustom org-refile-use-outline-path nil
2532 "Non-nil means provide refile targets as paths.
2533 So a level 3 headline will be available as level1/level2/level3.
2535 When the value is `file', also include the file name (without directory)
2536 into the path. In this case, you can also stop the completion after
2537 the file name, to get entries inserted as top level in the file.
2539 When `full-file-path', include the full file path.
2541 When `buffer-name', use the buffer name."
2542 :group 'org-refile
2543 :type '(choice
2544 (const :tag "Not" nil)
2545 (const :tag "Yes" t)
2546 (const :tag "Start with file name" file)
2547 (const :tag "Start with full file path" full-file-path)
2548 (const :tag "Start with buffer name" buffer-name)))
2550 (defcustom org-outline-path-complete-in-steps t
2551 "Non-nil means complete the outline path in hierarchical steps.
2552 When Org uses the refile interface to select an outline path (see
2553 `org-refile-use-outline-path'), the completion of the path can be
2554 done in a single go, or it can be done in steps down the headline
2555 hierarchy. Going in steps is probably the best if you do not use
2556 a special completion package like `ido' or `icicles'. However,
2557 when using these packages, going in one step can be very fast,
2558 while still showing the whole path to the entry."
2559 :group 'org-refile
2560 :type 'boolean)
2562 (defcustom org-refile-allow-creating-parent-nodes nil
2563 "Non-nil means allow the creation of new nodes as refile targets.
2564 New nodes are then created by adding \"/new node name\" to the completion
2565 of an existing node. When the value of this variable is `confirm',
2566 new node creation must be confirmed by the user (recommended).
2567 When nil, the completion must match an existing entry.
2569 Note that, if the new heading is not seen by the criteria
2570 listed in `org-refile-targets', multiple instances of the same
2571 heading would be created by trying again to file under the new
2572 heading."
2573 :group 'org-refile
2574 :type '(choice
2575 (const :tag "Never" nil)
2576 (const :tag "Always" t)
2577 (const :tag "Prompt for confirmation" confirm)))
2579 (defcustom org-refile-active-region-within-subtree nil
2580 "Non-nil means also refile active region within a subtree.
2582 By default `org-refile' doesn't allow refiling regions if they
2583 don't contain a set of subtrees, but it might be convenient to
2584 do so sometimes: in that case, the first line of the region is
2585 converted to a headline before refiling."
2586 :group 'org-refile
2587 :version "24.1"
2588 :type 'boolean)
2590 (defgroup org-todo nil
2591 "Options concerning TODO items in Org mode."
2592 :tag "Org TODO"
2593 :group 'org)
2595 (defgroup org-progress nil
2596 "Options concerning Progress logging in Org mode."
2597 :tag "Org Progress"
2598 :group 'org-time)
2600 (defvar org-todo-interpretation-widgets
2601 '((:tag "Sequence (cycling hits every state)" sequence)
2602 (:tag "Type (cycling directly to DONE)" type))
2603 "The available interpretation symbols for customizing `org-todo-keywords'.
2604 Interested libraries should add to this list.")
2606 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2607 "List of TODO entry keyword sequences and their interpretation.
2608 \\<org-mode-map>This is a list of sequences.
2610 Each sequence starts with a symbol, either `sequence' or `type',
2611 indicating if the keywords should be interpreted as a sequence of
2612 action steps, or as different types of TODO items. The first
2613 keywords are states requiring action - these states will select a headline
2614 for inclusion into the global TODO list Org produces. If one of the
2615 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2616 signify that no further action is necessary. If \"|\" is not found,
2617 the last keyword is treated as the only DONE state of the sequence.
2619 The command `\\[org-todo]' cycles an entry through these states, and one
2620 additional state where no keyword is present. For details about this
2621 cycling, see the manual.
2623 TODO keywords and interpretation can also be set on a per-file basis with
2624 the special #+SEQ_TODO and #+TYP_TODO lines.
2626 Each keyword can optionally specify a character for fast state selection
2627 \(in combination with the variable `org-use-fast-todo-selection')
2628 and specifiers for state change logging, using the same syntax that
2629 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2630 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2631 indicates to record a time stamp each time this state is selected.
2633 Each keyword may also specify if a timestamp or a note should be
2634 recorded when entering or leaving the state, by adding additional
2635 characters in the parenthesis after the keyword. This looks like this:
2636 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2637 record only the time of the state change. With X and Y being either
2638 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2639 Y when leaving the state if and only if the *target* state does not
2640 define X. You may omit any of the fast-selection key or X or /Y,
2641 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2643 For backward compatibility, this variable may also be just a list
2644 of keywords. In this case the interpretation (sequence or type) will be
2645 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2646 :group 'org-todo
2647 :group 'org-keywords
2648 :type '(choice
2649 (repeat :tag "Old syntax, just keywords"
2650 (string :tag "Keyword"))
2651 (repeat :tag "New syntax"
2652 (cons
2653 (choice
2654 :tag "Interpretation"
2655 ;;Quick and dirty way to see
2656 ;;`org-todo-interpretations'. This takes the
2657 ;;place of item arguments
2658 :convert-widget
2659 (lambda (widget)
2660 (widget-put widget
2661 :args (mapcar
2662 (lambda (x)
2663 (widget-convert
2664 (cons 'const x)))
2665 org-todo-interpretation-widgets))
2666 widget))
2667 (repeat
2668 (string :tag "Keyword"))))))
2670 (defvar-local org-todo-keywords-1 nil
2671 "All TODO and DONE keywords active in a buffer.")
2672 (defvar org-todo-keywords-for-agenda nil)
2673 (defvar org-done-keywords-for-agenda nil)
2674 (defvar org-todo-keyword-alist-for-agenda nil)
2675 (defvar org-tag-alist-for-agenda nil
2676 "Alist of all tags from all agenda files.")
2677 (defvar org-tag-groups-alist-for-agenda nil
2678 "Alist of all groups tags from all current agenda files.")
2679 (defvar-local org-tag-groups-alist nil)
2680 (defvar org-agenda-contributing-files nil)
2681 (defvar-local org-current-tag-alist nil
2682 "Alist of all tag groups in current buffer.
2683 This variable takes into consideration `org-tag-alist',
2684 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2685 (defvar-local org-not-done-keywords nil)
2686 (defvar-local org-done-keywords nil)
2687 (defvar-local org-todo-heads nil)
2688 (defvar-local org-todo-sets nil)
2689 (defvar-local org-todo-log-states nil)
2690 (defvar-local org-todo-kwd-alist nil)
2691 (defvar-local org-todo-key-alist nil)
2692 (defvar-local org-todo-key-trigger nil)
2694 (defcustom org-todo-interpretation 'sequence
2695 "Controls how TODO keywords are interpreted.
2696 This variable is in principle obsolete and is only used for
2697 backward compatibility, if the interpretation of todo keywords is
2698 not given already in `org-todo-keywords'. See that variable for
2699 more information."
2700 :group 'org-todo
2701 :group 'org-keywords
2702 :type '(choice (const sequence)
2703 (const type)))
2705 (defcustom org-use-fast-todo-selection t
2706 "\\<org-mode-map>\
2707 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2708 This variable describes if and under what circumstances the cycling
2709 mechanism for TODO keywords will be replaced by a single-key, direct
2710 selection scheme.
2712 When nil, fast selection is never used.
2714 When the symbol `prefix', it will be used when `org-todo' is called
2715 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2716 in an Org buffer, and
2717 `\\[universal-argument] t' in an agenda buffer.
2719 When t, fast selection is used by default. In this case, the prefix
2720 argument forces cycling instead.
2722 In all cases, the special interface is only used if access keys have
2723 actually been assigned by the user, i.e. if keywords in the configuration
2724 are followed by a letter in parenthesis, like TODO(t)."
2725 :group 'org-todo
2726 :type '(choice
2727 (const :tag "Never" nil)
2728 (const :tag "By default" t)
2729 (const :tag "Only with C-u C-c C-t" prefix)))
2731 (defcustom org-provide-todo-statistics t
2732 "Non-nil means update todo statistics after insert and toggle.
2733 ALL-HEADLINES means update todo statistics by including headlines
2734 with no TODO keyword as well, counting them as not done.
2735 A list of TODO keywords means the same, but skip keywords that are
2736 not in this list.
2737 When set to a list of two lists, the first list contains keywords
2738 to consider as TODO keywords, the second list contains keywords
2739 to consider as DONE keywords.
2741 When this is set, todo statistics is updated in the parent of the
2742 current entry each time a todo state is changed."
2743 :group 'org-todo
2744 :type '(choice
2745 (const :tag "Yes, only for TODO entries" t)
2746 (const :tag "Yes, including all entries" all-headlines)
2747 (repeat :tag "Yes, for TODOs in this list"
2748 (string :tag "TODO keyword"))
2749 (list :tag "Yes, for TODOs and DONEs in these lists"
2750 (repeat (string :tag "TODO keyword"))
2751 (repeat (string :tag "DONE keyword")))
2752 (other :tag "No TODO statistics" nil)))
2754 (defcustom org-hierarchical-todo-statistics t
2755 "Non-nil means TODO statistics covers just direct children.
2756 When nil, all entries in the subtree are considered.
2757 This has only an effect if `org-provide-todo-statistics' is set.
2758 To set this to nil for only a single subtree, use a COOKIE_DATA
2759 property and include the word \"recursive\" into the value."
2760 :group 'org-todo
2761 :type 'boolean)
2763 (defcustom org-after-todo-state-change-hook nil
2764 "Hook which is run after the state of a TODO item was changed.
2765 The new state (a string with a TODO keyword, or nil) is available in the
2766 Lisp variable `org-state'."
2767 :group 'org-todo
2768 :type 'hook)
2770 (defvar org-blocker-hook nil
2771 "Hook for functions that are allowed to block a state change.
2773 Functions in this hook should not modify the buffer.
2774 Each function gets as its single argument a property list,
2775 see `org-trigger-hook' for more information about this list.
2777 If any of the functions in this hook returns nil, the state change
2778 is blocked.")
2780 (defvar org-trigger-hook nil
2781 "Hook for functions that are triggered by a state change.
2783 Each function gets as its single argument a property list with at
2784 least the following elements:
2786 (:type type-of-change :position pos-at-entry-start
2787 :from old-state :to new-state)
2789 Depending on the type, more properties may be present.
2791 This mechanism is currently implemented for:
2793 TODO state changes
2794 ------------------
2795 :type todo-state-change
2796 :from previous state (keyword as a string), or nil, or a symbol
2797 `todo' or `done', to indicate the general type of state.
2798 :to new state, like in :from")
2800 (defcustom org-enforce-todo-dependencies nil
2801 "Non-nil means undone TODO entries will block switching the parent to DONE.
2802 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2803 be blocked if any prior sibling is not yet done.
2804 Finally, if the parent is blocked because of ordered siblings of its own,
2805 the child will also be blocked."
2806 :set (lambda (var val)
2807 (set var val)
2808 (if val
2809 (add-hook 'org-blocker-hook
2810 'org-block-todo-from-children-or-siblings-or-parent)
2811 (remove-hook 'org-blocker-hook
2812 'org-block-todo-from-children-or-siblings-or-parent)))
2813 :group 'org-todo
2814 :type 'boolean)
2816 (defcustom org-enforce-todo-checkbox-dependencies nil
2817 "Non-nil means unchecked boxes will block switching the parent to DONE.
2818 When this is nil, checkboxes have no influence on switching TODO states.
2819 When non-nil, you first need to check off all check boxes before the TODO
2820 entry can be switched to DONE.
2821 This variable needs to be set before org.el is loaded, and you need to
2822 restart Emacs after a change to make the change effective. The only way
2823 to change is while Emacs is running is through the customize interface."
2824 :set (lambda (var val)
2825 (set var val)
2826 (if val
2827 (add-hook 'org-blocker-hook
2828 'org-block-todo-from-checkboxes)
2829 (remove-hook 'org-blocker-hook
2830 'org-block-todo-from-checkboxes)))
2831 :group 'org-todo
2832 :type 'boolean)
2834 (defcustom org-treat-insert-todo-heading-as-state-change nil
2835 "Non-nil means inserting a TODO heading is treated as state change.
2836 So when the command `\\[org-insert-todo-heading]' is used, state change
2837 logging will apply if appropriate. When nil, the new TODO item will
2838 be inserted directly, and no logging will take place."
2839 :group 'org-todo
2840 :type 'boolean)
2842 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2843 "Non-nil means switching TODO states with S-cursor counts as state change.
2844 This is the default behavior. However, setting this to nil allows a
2845 convenient way to select a TODO state and bypass any logging associated
2846 with that."
2847 :group 'org-todo
2848 :type 'boolean)
2850 (defcustom org-todo-state-tags-triggers nil
2851 "Tag changes that should be triggered by TODO state changes.
2852 This is a list. Each entry is
2854 (state-change (tag . flag) .......)
2856 State-change can be a string with a state, and empty string to indicate the
2857 state that has no TODO keyword, or it can be one of the symbols `todo'
2858 or `done', meaning any not-done or done state, respectively."
2859 :group 'org-todo
2860 :group 'org-tags
2861 :type '(repeat
2862 (cons (choice :tag "When changing to"
2863 (const :tag "Not-done state" todo)
2864 (const :tag "Done state" done)
2865 (string :tag "State"))
2866 (repeat
2867 (cons :tag "Tag action"
2868 (string :tag "Tag")
2869 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2871 (defcustom org-log-done nil
2872 "Information to record when a task moves to the DONE state.
2874 Possible values are:
2876 nil Don't add anything, just change the keyword
2877 time Add a time stamp to the task
2878 note Prompt for a note and add it with template `org-log-note-headings'
2880 This option can also be set with on a per-file-basis with
2882 #+STARTUP: nologdone
2883 #+STARTUP: logdone
2884 #+STARTUP: lognotedone
2886 You can have local logging settings for a subtree by setting the LOGGING
2887 property to one or more of these keywords."
2888 :group 'org-todo
2889 :group 'org-progress
2890 :type '(choice
2891 (const :tag "No logging" nil)
2892 (const :tag "Record CLOSED timestamp" time)
2893 (const :tag "Record CLOSED timestamp with note." note)))
2895 ;; Normalize old uses of org-log-done.
2896 (cond
2897 ((eq org-log-done t) (setq org-log-done 'time))
2898 ((and (listp org-log-done) (memq 'done org-log-done))
2899 (setq org-log-done 'note)))
2901 (defcustom org-log-reschedule nil
2902 "Information to record when the scheduling date of a tasks is modified.
2904 Possible values are:
2906 nil Don't add anything, just change the date
2907 time Add a time stamp to the task
2908 note Prompt for a note and add it with template `org-log-note-headings'
2910 This option can also be set with on a per-file-basis with
2912 #+STARTUP: nologreschedule
2913 #+STARTUP: logreschedule
2914 #+STARTUP: lognotereschedule"
2915 :group 'org-todo
2916 :group 'org-progress
2917 :type '(choice
2918 (const :tag "No logging" nil)
2919 (const :tag "Record timestamp" time)
2920 (const :tag "Record timestamp with note." note)))
2922 (defcustom org-log-redeadline nil
2923 "Information to record when the deadline date of a tasks is modified.
2925 Possible values are:
2927 nil Don't add anything, just change the date
2928 time Add a time stamp to the task
2929 note Prompt for a note and add it with template `org-log-note-headings'
2931 This option can also be set with on a per-file-basis with
2933 #+STARTUP: nologredeadline
2934 #+STARTUP: logredeadline
2935 #+STARTUP: lognoteredeadline
2937 You can have local logging settings for a subtree by setting the LOGGING
2938 property to one or more of these keywords."
2939 :group 'org-todo
2940 :group 'org-progress
2941 :type '(choice
2942 (const :tag "No logging" nil)
2943 (const :tag "Record timestamp" time)
2944 (const :tag "Record timestamp with note." note)))
2946 (defcustom org-log-note-clock-out nil
2947 "Non-nil means record a note when clocking out of an item.
2948 This can also be configured on a per-file basis by adding one of
2949 the following lines anywhere in the buffer:
2951 #+STARTUP: lognoteclock-out
2952 #+STARTUP: nolognoteclock-out"
2953 :group 'org-todo
2954 :group 'org-progress
2955 :type 'boolean)
2957 (defcustom org-log-done-with-time t
2958 "Non-nil means the CLOSED time stamp will contain date and time.
2959 When nil, only the date will be recorded."
2960 :group 'org-progress
2961 :type 'boolean)
2963 (defcustom org-log-note-headings
2964 '((done . "CLOSING NOTE %t")
2965 (state . "State %-12s from %-12S %t")
2966 (note . "Note taken on %t")
2967 (reschedule . "Rescheduled from %S on %t")
2968 (delschedule . "Not scheduled, was %S on %t")
2969 (redeadline . "New deadline from %S on %t")
2970 (deldeadline . "Removed deadline, was %S on %t")
2971 (refile . "Refiled on %t")
2972 (clock-out . ""))
2973 "Headings for notes added to entries.
2975 The value is an alist, with the car being a symbol indicating the
2976 note context, and the cdr is the heading to be used. The heading
2977 may also be the empty string. The following placeholders can be
2978 used:
2980 %t a time stamp.
2981 %T an active time stamp instead the default inactive one
2982 %d a short-format time stamp.
2983 %D an active short-format time stamp.
2984 %s the new TODO state or time stamp (inactive), in double quotes.
2985 %S the old TODO state or time stamp (inactive), in double quotes.
2986 %u the user name.
2987 %U full user name.
2989 In fact, it is not a good idea to change the `state' entry,
2990 because Agenda Log mode depends on the format of these entries."
2991 :group 'org-todo
2992 :group 'org-progress
2993 :type '(list :greedy t
2994 (cons (const :tag "Heading when closing an item" done) string)
2995 (cons (const :tag
2996 "Heading when changing todo state (todo sequence only)"
2997 state) string)
2998 (cons (const :tag "Heading when just taking a note" note) string)
2999 (cons (const :tag "Heading when rescheduling" reschedule) string)
3000 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3001 (cons (const :tag "Heading when changing deadline" redeadline) string)
3002 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3003 (cons (const :tag "Heading when refiling" refile) string)
3004 (cons (const :tag "Heading when clocking out" clock-out) string)))
3006 (unless (assq 'note org-log-note-headings)
3007 (push '(note . "%t") org-log-note-headings))
3009 (defcustom org-log-into-drawer nil
3010 "Non-nil means insert state change notes and time stamps into a drawer.
3011 When nil, state changes notes will be inserted after the headline and
3012 any scheduling and clock lines, but not inside a drawer.
3014 The value of this variable should be the name of the drawer to use.
3015 LOGBOOK is proposed as the default drawer for this purpose, you can
3016 also set this to a string to define the drawer of your choice.
3018 A value of t is also allowed, representing \"LOGBOOK\".
3020 A value of t or nil can also be set with on a per-file-basis with
3022 #+STARTUP: logdrawer
3023 #+STARTUP: nologdrawer
3025 If this variable is set, `org-log-state-notes-insert-after-drawers'
3026 will be ignored.
3028 You can set the property LOG_INTO_DRAWER to overrule this setting for
3029 a subtree.
3031 Do not check directly this variable in a Lisp program. Call
3032 function `org-log-into-drawer' instead."
3033 :group 'org-todo
3034 :group 'org-progress
3035 :type '(choice
3036 (const :tag "Not into a drawer" nil)
3037 (const :tag "LOGBOOK" t)
3038 (string :tag "Other")))
3040 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3042 (defun org-log-into-drawer ()
3043 "Name of the log drawer, as a string, or nil.
3044 This is the value of `org-log-into-drawer'. However, if the
3045 current entry has or inherits a LOG_INTO_DRAWER property, it will
3046 be used instead of the default value."
3047 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3048 (cond ((equal p "nil") nil)
3049 ((equal p "t") "LOGBOOK")
3050 ((stringp p) p)
3051 (p "LOGBOOK")
3052 ((stringp org-log-into-drawer) org-log-into-drawer)
3053 (org-log-into-drawer "LOGBOOK"))))
3055 (defcustom org-log-state-notes-insert-after-drawers nil
3056 "Non-nil means insert state change notes after any drawers in entry.
3057 Only the drawers that *immediately* follow the headline and the
3058 deadline/scheduled line are skipped.
3059 When nil, insert notes right after the heading and perhaps the line
3060 with deadline/scheduling if present.
3062 This variable will have no effect if `org-log-into-drawer' is
3063 set."
3064 :group 'org-todo
3065 :group 'org-progress
3066 :type 'boolean)
3068 (defcustom org-log-states-order-reversed t
3069 "Non-nil means the latest state note will be directly after heading.
3070 When nil, the state change notes will be ordered according to time.
3072 This option can also be set with on a per-file-basis with
3074 #+STARTUP: logstatesreversed
3075 #+STARTUP: nologstatesreversed"
3076 :group 'org-todo
3077 :group 'org-progress
3078 :type 'boolean)
3080 (defcustom org-todo-repeat-to-state nil
3081 "The TODO state to which a repeater should return the repeating task.
3082 By default this is the first task in a TODO sequence, or the previous state
3083 in a TODO_TYP set. But you can specify another task here.
3084 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3085 :group 'org-todo
3086 :version "24.1"
3087 :type '(choice (const :tag "Head of sequence" nil)
3088 (string :tag "Specific state")))
3090 (defcustom org-log-repeat 'time
3091 "Non-nil means record moving through the DONE state when triggering repeat.
3092 An auto-repeating task is immediately switched back to TODO when
3093 marked DONE. If you are not logging state changes (by adding \"@\"
3094 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3095 record a closing note, there will be no record of the task moving
3096 through DONE. This variable forces taking a note anyway.
3098 nil Don't force a record
3099 time Record a time stamp
3100 note Prompt for a note and add it with template `org-log-note-headings'
3102 This option can also be set with on a per-file-basis with
3104 #+STARTUP: nologrepeat
3105 #+STARTUP: logrepeat
3106 #+STARTUP: lognoterepeat
3108 You can have local logging settings for a subtree by setting the LOGGING
3109 property to one or more of these keywords."
3110 :group 'org-todo
3111 :group 'org-progress
3112 :type '(choice
3113 (const :tag "Don't force a record" nil)
3114 (const :tag "Force recording the DONE state" time)
3115 (const :tag "Force recording a note with the DONE state" note)))
3118 (defgroup org-priorities nil
3119 "Priorities in Org mode."
3120 :tag "Org Priorities"
3121 :group 'org-todo)
3123 (defcustom org-enable-priority-commands t
3124 "Non-nil means priority commands are active.
3125 When nil, these commands will be disabled, so that you never accidentally
3126 set a priority."
3127 :group 'org-priorities
3128 :type 'boolean)
3130 (defcustom org-highest-priority ?A
3131 "The highest priority of TODO items. A character like ?A, ?B etc.
3132 Must have a smaller ASCII number than `org-lowest-priority'."
3133 :group 'org-priorities
3134 :type 'character)
3136 (defcustom org-lowest-priority ?C
3137 "The lowest priority of TODO items. A character like ?A, ?B etc.
3138 Must have a larger ASCII number than `org-highest-priority'."
3139 :group 'org-priorities
3140 :type 'character)
3142 (defcustom org-default-priority ?B
3143 "The default priority of TODO items.
3144 This is the priority an item gets if no explicit priority is given.
3145 When starting to cycle on an empty priority the first step in the cycle
3146 depends on `org-priority-start-cycle-with-default'. The resulting first
3147 step priority must not exceed the range from `org-highest-priority' to
3148 `org-lowest-priority' which means that `org-default-priority' has to be
3149 in this range exclusive or inclusive the range boundaries. Else the
3150 first step refuses to set the default and the second will fall back
3151 to (depending on the command used) the highest or lowest priority."
3152 :group 'org-priorities
3153 :type 'character)
3155 (defcustom org-priority-start-cycle-with-default t
3156 "Non-nil means start with default priority when starting to cycle.
3157 When this is nil, the first step in the cycle will be (depending on the
3158 command used) one higher or lower than the default priority.
3159 See also `org-default-priority'."
3160 :group 'org-priorities
3161 :type 'boolean)
3163 (defcustom org-get-priority-function nil
3164 "Function to extract the priority from a string.
3165 The string is normally the headline. If this is nil Org computes the
3166 priority from the priority cookie like [#A] in the headline. It returns
3167 an integer, increasing by 1000 for each priority level.
3168 The user can set a different function here, which should take a string
3169 as an argument and return the numeric priority."
3170 :group 'org-priorities
3171 :version "24.1"
3172 :type '(choice
3173 (const nil)
3174 (function)))
3176 (defgroup org-time nil
3177 "Options concerning time stamps and deadlines in Org mode."
3178 :tag "Org Time"
3179 :group 'org)
3181 (defcustom org-time-stamp-rounding-minutes '(0 5)
3182 "Number of minutes to round time stamps to.
3183 \\<org-mode-map>\
3184 These are two values, the first applies when first creating a time stamp.
3185 The second applies when changing it with the commands `S-up' and `S-down'.
3186 When changing the time stamp, this means that it will change in steps
3187 of N minutes, as given by the second value.
3189 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3190 numbers should be factors of 60, so for example 5, 10, 15.
3192 When this is larger than 1, you can still force an exact time stamp by using
3193 a double prefix argument to a time stamp command like \
3194 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3195 and by using a prefix arg to `S-up/down' to specify the exact number
3196 of minutes to shift."
3197 :group 'org-time
3198 :get (lambda (var) ; Make sure both elements are there
3199 (if (integerp (default-value var))
3200 (list (default-value var) 5)
3201 (default-value var)))
3202 :type '(list
3203 (integer :tag "when inserting times")
3204 (integer :tag "when modifying times")))
3206 ;; Normalize old customizations of this variable.
3207 (when (integerp org-time-stamp-rounding-minutes)
3208 (setq org-time-stamp-rounding-minutes
3209 (list org-time-stamp-rounding-minutes
3210 org-time-stamp-rounding-minutes)))
3212 (defcustom org-display-custom-times nil
3213 "Non-nil means overlay custom formats over all time stamps.
3214 The formats are defined through the variable `org-time-stamp-custom-formats'.
3215 To turn this on on a per-file basis, insert anywhere in the file:
3216 #+STARTUP: customtime"
3217 :group 'org-time
3218 :set 'set-default
3219 :type 'sexp)
3220 (make-variable-buffer-local 'org-display-custom-times)
3222 (defcustom org-time-stamp-custom-formats
3223 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3224 "Custom formats for time stamps. See `format-time-string' for the syntax.
3225 These are overlaid over the default ISO format if the variable
3226 `org-display-custom-times' is set. Time like %H:%M should be at the
3227 end of the second format. The custom formats are also honored by export
3228 commands, if custom time display is turned on at the time of export."
3229 :group 'org-time
3230 :type 'sexp)
3232 (defun org-time-stamp-format (&optional long inactive)
3233 "Get the right format for a time string."
3234 (let ((f (if long (cdr org-time-stamp-formats)
3235 (car org-time-stamp-formats))))
3236 (if inactive
3237 (concat "[" (substring f 1 -1) "]")
3238 f)))
3240 (defcustom org-deadline-warning-days 14
3241 "Number of days before expiration during which a deadline becomes active.
3242 This variable governs the display in sparse trees and in the agenda.
3243 When 0 or negative, it means use this number (the absolute value of it)
3244 even if a deadline has a different individual lead time specified.
3246 Custom commands can set this variable in the options section."
3247 :group 'org-time
3248 :group 'org-agenda-daily/weekly
3249 :type 'integer)
3251 (defcustom org-scheduled-delay-days 0
3252 "Number of days before a scheduled item becomes active.
3253 This variable governs the display in sparse trees and in the agenda.
3254 The default value (i.e. 0) means: don't delay scheduled item.
3255 When negative, it means use this number (the absolute value of it)
3256 even if a scheduled item has a different individual delay time
3257 specified.
3259 Custom commands can set this variable in the options section."
3260 :group 'org-time
3261 :group 'org-agenda-daily/weekly
3262 :version "24.4"
3263 :package-version '(Org . "8.0")
3264 :type 'integer)
3266 (defcustom org-read-date-prefer-future t
3267 "Non-nil means assume future for incomplete date input from user.
3268 This affects the following situations:
3269 1. The user gives a month but not a year.
3270 For example, if it is April and you enter \"feb 2\", this will be read
3271 as Feb 2, *next* year. \"May 5\", however, will be this year.
3272 2. The user gives a day, but no month.
3273 For example, if today is the 15th, and you enter \"3\", Org will read
3274 this as the third of *next* month. However, if you enter \"17\",
3275 it will be considered as *this* month.
3277 If you set this variable to the symbol `time', then also the following
3278 will work:
3280 3. If the user gives a time.
3281 If the time is before now, it will be interpreted as tomorrow.
3283 Currently none of this works for ISO week specifications.
3285 When this option is nil, the current day, month and year will always be
3286 used as defaults.
3288 See also `org-agenda-jump-prefer-future'."
3289 :group 'org-time
3290 :type '(choice
3291 (const :tag "Never" nil)
3292 (const :tag "Check month and day" t)
3293 (const :tag "Check month, day, and time" time)))
3295 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3296 "Should the agenda jump command prefer the future for incomplete dates?
3297 The default is to do the same as configured in `org-read-date-prefer-future'.
3298 But you can also set a deviating value here.
3299 This may t or nil, or the symbol `org-read-date-prefer-future'."
3300 :group 'org-agenda
3301 :group 'org-time
3302 :version "24.1"
3303 :type '(choice
3304 (const :tag "Use org-read-date-prefer-future"
3305 org-read-date-prefer-future)
3306 (const :tag "Never" nil)
3307 (const :tag "Always" t)))
3309 (defcustom org-read-date-force-compatible-dates t
3310 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3312 Depending on the system Emacs is running on, certain dates cannot
3313 be represented with the type used internally to represent time.
3314 Dates between 1970-1-1 and 2038-1-1 can always be represented
3315 correctly. Some systems allow for earlier dates, some for later,
3316 some for both. One way to find out it to insert any date into an
3317 Org buffer, putting the cursor on the year and hitting S-up and
3318 S-down to test the range.
3320 When this variable is set to t, the date/time prompt will not let
3321 you specify dates outside the 1970-2037 range, so it is certain that
3322 these dates will work in whatever version of Emacs you are
3323 running, and also that you can move a file from one Emacs implementation
3324 to another. WHenever Org is forcing the year for you, it will display
3325 a message and beep.
3327 When this variable is nil, Org will check if the date is
3328 representable in the specific Emacs implementation you are using.
3329 If not, it will force a year, usually the current year, and beep
3330 to remind you. Currently this setting is not recommended because
3331 the likelihood that you will open your Org files in an Emacs that
3332 has limited date range is not negligible.
3334 A workaround for this problem is to use diary sexp dates for time
3335 stamps outside of this range."
3336 :group 'org-time
3337 :version "24.1"
3338 :type 'boolean)
3340 (defcustom org-read-date-display-live t
3341 "Non-nil means display current interpretation of date prompt live.
3342 This display will be in an overlay, in the minibuffer."
3343 :group 'org-time
3344 :type 'boolean)
3346 (defcustom org-read-date-popup-calendar t
3347 "Non-nil means pop up a calendar when prompting for a date.
3348 In the calendar, the date can be selected with mouse-1. However, the
3349 minibuffer will also be active, and you can simply enter the date as well.
3350 When nil, only the minibuffer will be available."
3351 :group 'org-time
3352 :type 'boolean)
3353 (defvaralias 'org-popup-calendar-for-date-prompt
3354 'org-read-date-popup-calendar)
3356 (defcustom org-extend-today-until 0
3357 "The hour when your day really ends. Must be an integer.
3358 This has influence for the following applications:
3359 - When switching the agenda to \"today\". It it is still earlier than
3360 the time given here, the day recognized as TODAY is actually yesterday.
3361 - When a date is read from the user and it is still before the time given
3362 here, the current date and time will be assumed to be yesterday, 23:59.
3363 Also, timestamps inserted in capture templates follow this rule.
3365 IMPORTANT: This is a feature whose implementation is and likely will
3366 remain incomplete. Really, it is only here because past midnight seems to
3367 be the favorite working time of John Wiegley :-)"
3368 :group 'org-time
3369 :type 'integer)
3371 (defcustom org-use-effective-time nil
3372 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3373 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3374 \"effective time\" of any timestamps between midnight and 8am will be
3375 23:59 of the previous day."
3376 :group 'org-time
3377 :version "24.1"
3378 :type 'boolean)
3380 (defcustom org-use-last-clock-out-time-as-effective-time nil
3381 "When non-nil, use the last clock out time for `org-todo'.
3382 Note that this option has precedence over the combined use of
3383 `org-use-effective-time' and `org-extend-today-until'."
3384 :group 'org-time
3385 :version "24.4"
3386 :package-version '(Org . "8.0")
3387 :type 'boolean)
3389 (defcustom org-edit-timestamp-down-means-later nil
3390 "Non-nil means S-down will increase the time in a time stamp.
3391 When nil, S-up will increase."
3392 :group 'org-time
3393 :type 'boolean)
3395 (defcustom org-calendar-follow-timestamp-change t
3396 "Non-nil means make the calendar window follow timestamp changes.
3397 When a timestamp is modified and the calendar window is visible, it will be
3398 moved to the new date."
3399 :group 'org-time
3400 :type 'boolean)
3402 (defgroup org-tags nil
3403 "Options concerning tags in Org mode."
3404 :tag "Org Tags"
3405 :group 'org)
3407 (defcustom org-tag-alist nil
3408 "Default tags available in Org files.
3410 The value of this variable is an alist. Associations either:
3412 (TAG)
3413 (TAG . SELECT)
3414 (SPECIAL)
3416 where TAG is a tag as a string, SELECT is character, used to
3417 select that tag through the fast tag selection interface, and
3418 SPECIAL is one of the following keywords: `:startgroup',
3419 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3420 `:newline'. These keywords are used to define a hierarchy of
3421 tags. See manual for details.
3423 When this variable is nil, Org mode bases tag input on what is
3424 already in the buffer. The value can be overridden locally by
3425 using a TAGS keyword, e.g.,
3427 #+TAGS: tag1 tag2
3429 See also `org-tag-persistent-alist' to sidestep this behavior."
3430 :group 'org-tags
3431 :type '(repeat
3432 (choice
3433 (cons :tag "Tag with key"
3434 (string :tag "Tag name")
3435 (character :tag "Access char"))
3436 (list :tag "Tag" (string :tag "Tag name"))
3437 (const :tag "Start radio group" (:startgroup))
3438 (const :tag "Start tag group, non distinct" (:startgrouptag))
3439 (const :tag "Group tags delimiter" (:grouptags))
3440 (const :tag "End radio group" (:endgroup))
3441 (const :tag "End tag group, non distinct" (:endgrouptag))
3442 (const :tag "New line" (:newline)))))
3444 (defcustom org-tag-persistent-alist nil
3445 "Tags always available in Org files.
3447 The value of this variable is an alist. Associations either:
3449 (TAG)
3450 (TAG . SELECT)
3451 (SPECIAL)
3453 where TAG is a tag as a string, SELECT is a character, used to
3454 select that tag through the fast tag selection interface, and
3455 SPECIAL is one of the following keywords: `:startgroup',
3456 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3457 `:newline'. These keywords are used to define a hierarchy of
3458 tags. See manual for details.
3460 Unlike to `org-tag-alist', tags defined in this variable do not
3461 depend on a local TAGS keyword. Instead, to disable these tags
3462 on a per-file basis, insert anywhere in the file:
3464 #+STARTUP: noptag"
3465 :group 'org-tags
3466 :type '(repeat
3467 (choice
3468 (cons :tag "Tag with key"
3469 (string :tag "Tag name")
3470 (character :tag "Access char"))
3471 (list :tag "Tag" (string :tag "Tag name"))
3472 (const :tag "Start radio group" (:startgroup))
3473 (const :tag "Start tag group, non distinct" (:startgrouptag))
3474 (const :tag "Group tags delimiter" (:grouptags))
3475 (const :tag "End radio group" (:endgroup))
3476 (const :tag "End tag group, non distinct" (:endgrouptag))
3477 (const :tag "New line" (:newline)))))
3479 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3480 "If non-nil, always offer completion for all tags of all agenda files.
3481 Instead of customizing this variable directly, you might want to
3482 set it locally for capture buffers, because there no list of
3483 tags in that file can be created dynamically (there are none).
3485 (add-hook \\='org-capture-mode-hook
3486 (lambda ()
3487 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3488 :group 'org-tags
3489 :version "24.1"
3490 :type 'boolean)
3492 (defvar org-file-tags nil
3493 "List of tags that can be inherited by all entries in the file.
3494 The tags will be inherited if the variable `org-use-tag-inheritance'
3495 says they should be.
3496 This variable is populated from #+FILETAGS lines.")
3498 (defcustom org-use-fast-tag-selection 'auto
3499 "Non-nil means use fast tag selection scheme.
3500 This is a special interface to select and deselect tags with single keys.
3501 When nil, fast selection is never used.
3502 When the symbol `auto', fast selection is used if and only if selection
3503 characters for tags have been configured, either through the variable
3504 `org-tag-alist' or through a #+TAGS line in the buffer.
3505 When t, fast selection is always used and selection keys are assigned
3506 automatically if necessary."
3507 :group 'org-tags
3508 :type '(choice
3509 (const :tag "Always" t)
3510 (const :tag "Never" nil)
3511 (const :tag "When selection characters are configured" auto)))
3513 (defcustom org-fast-tag-selection-single-key nil
3514 "Non-nil means fast tag selection exits after first change.
3515 When nil, you have to press RET to exit it.
3516 During fast tag selection, you can toggle this flag with `C-c'.
3517 This variable can also have the value `expert'. In this case, the window
3518 displaying the tags menu is not even shown, until you press C-c again."
3519 :group 'org-tags
3520 :type '(choice
3521 (const :tag "No" nil)
3522 (const :tag "Yes" t)
3523 (const :tag "Expert" expert)))
3525 (defvar org-fast-tag-selection-include-todo nil
3526 "Non-nil means fast tags selection interface will also offer TODO states.
3527 This is an undocumented feature, you should not rely on it.")
3529 (defcustom org-tags-column -77
3530 "The column to which tags should be indented in a headline.
3531 If this number is positive, it specifies the column. If it is negative,
3532 it means that the tags should be flushright to that column. For example,
3533 -80 works well for a normal 80 character screen.
3534 When 0, place tags directly after headline text, with only one space in
3535 between."
3536 :group 'org-tags
3537 :type 'integer)
3539 (defcustom org-auto-align-tags t
3540 "Non-nil keeps tags aligned when modifying headlines.
3541 Some operations (i.e. demoting) change the length of a headline and
3542 therefore shift the tags around. With this option turned on, after
3543 each such operation the tags are again aligned to `org-tags-column'."
3544 :group 'org-tags
3545 :type 'boolean)
3547 (defcustom org-use-tag-inheritance t
3548 "Non-nil means tags in levels apply also for sublevels.
3549 When nil, only the tags directly given in a specific line apply there.
3550 This may also be a list of tags that should be inherited, or a regexp that
3551 matches tags that should be inherited. Additional control is possible
3552 with the variable `org-tags-exclude-from-inheritance' which gives an
3553 explicit list of tags to be excluded from inheritance, even if the value of
3554 `org-use-tag-inheritance' would select it for inheritance.
3556 If this option is t, a match early-on in a tree can lead to a large
3557 number of matches in the subtree when constructing the agenda or creating
3558 a sparse tree. If you only want to see the first match in a tree during
3559 a search, check out the variable `org-tags-match-list-sublevels'."
3560 :group 'org-tags
3561 :type '(choice
3562 (const :tag "Not" nil)
3563 (const :tag "Always" t)
3564 (repeat :tag "Specific tags" (string :tag "Tag"))
3565 (regexp :tag "Tags matched by regexp")))
3567 (defcustom org-tags-exclude-from-inheritance nil
3568 "List of tags that should never be inherited.
3569 This is a way to exclude a few tags from inheritance. For way to do
3570 the opposite, to actively allow inheritance for selected tags,
3571 see the variable `org-use-tag-inheritance'."
3572 :group 'org-tags
3573 :type '(repeat (string :tag "Tag")))
3575 (defun org-tag-inherit-p (tag)
3576 "Check if TAG is one that should be inherited."
3577 (cond
3578 ((member tag org-tags-exclude-from-inheritance) nil)
3579 ((eq org-use-tag-inheritance t) t)
3580 ((not org-use-tag-inheritance) nil)
3581 ((stringp org-use-tag-inheritance)
3582 (string-match org-use-tag-inheritance tag))
3583 ((listp org-use-tag-inheritance)
3584 (member tag org-use-tag-inheritance))
3585 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3587 (defcustom org-tags-match-list-sublevels t
3588 "Non-nil means list also sublevels of headlines matching a search.
3589 This variable applies to tags/property searches, and also to stuck
3590 projects because this search is based on a tags match as well.
3592 When set to the symbol `indented', sublevels are indented with
3593 leading dots.
3595 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3596 the sublevels of a headline matching a tag search often also match
3597 the same search. Listing all of them can create very long lists.
3598 Setting this variable to nil causes subtrees of a match to be skipped.
3600 This variable is semi-obsolete and probably should always be true. It
3601 is better to limit inheritance to certain tags using the variables
3602 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3603 :group 'org-tags
3604 :type '(choice
3605 (const :tag "No, don't list them" nil)
3606 (const :tag "Yes, do list them" t)
3607 (const :tag "List them, indented with leading dots" indented)))
3609 (defcustom org-tags-sort-function nil
3610 "When set, tags are sorted using this function as a comparator."
3611 :group 'org-tags
3612 :type '(choice
3613 (const :tag "No sorting" nil)
3614 (const :tag "Alphabetical" string<)
3615 (const :tag "Reverse alphabetical" string>)
3616 (function :tag "Custom function" nil)))
3618 (defvar org-tags-history nil
3619 "History of minibuffer reads for tags.")
3620 (defvar org-last-tags-completion-table nil
3621 "The last used completion table for tags.")
3622 (defvar org-after-tags-change-hook nil
3623 "Hook that is run after the tags in a line have changed.")
3625 (defgroup org-properties nil
3626 "Options concerning properties in Org mode."
3627 :tag "Org Properties"
3628 :group 'org)
3630 (defcustom org-property-format "%-10s %s"
3631 "How property key/value pairs should be formatted by `indent-line'.
3632 When `indent-line' hits a property definition, it will format the line
3633 according to this format, mainly to make sure that the values are
3634 lined-up with respect to each other."
3635 :group 'org-properties
3636 :type 'string)
3638 (defcustom org-properties-postprocess-alist nil
3639 "Alist of properties and functions to adjust inserted values.
3640 Elements of this alist must be of the form
3642 ([string] [function])
3644 where [string] must be a property name and [function] must be a
3645 lambda expression: this lambda expression must take one argument,
3646 the value to adjust, and return the new value as a string.
3648 For example, this element will allow the property \"Remaining\"
3649 to be updated wrt the relation between the \"Effort\" property
3650 and the clock summary:
3652 ((\"Remaining\" (lambda(value)
3653 (let ((clocksum (org-clock-sum-current-item))
3654 (effort (org-duration-to-minutes
3655 (org-entry-get (point) \"Effort\"))))
3656 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3657 :group 'org-properties
3658 :version "24.1"
3659 :type '(alist :key-type (string :tag "Property")
3660 :value-type (function :tag "Function")))
3662 (defcustom org-use-property-inheritance nil
3663 "Non-nil means properties apply also for sublevels.
3665 This setting is chiefly used during property searches. Turning it on can
3666 cause significant overhead when doing a search, which is why it is not
3667 on by default.
3669 When nil, only the properties directly given in the current entry count.
3670 When t, every property is inherited. The value may also be a list of
3671 properties that should have inheritance, or a regular expression matching
3672 properties that should be inherited.
3674 However, note that some special properties use inheritance under special
3675 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3676 and the properties ending in \"_ALL\" when they are used as descriptor
3677 for valid values of a property.
3679 Note for programmers:
3680 When querying an entry with `org-entry-get', you can control if inheritance
3681 should be used. By default, `org-entry-get' looks only at the local
3682 properties. You can request inheritance by setting the inherit argument
3683 to t (to force inheritance) or to `selective' (to respect the setting
3684 in this variable)."
3685 :group 'org-properties
3686 :type '(choice
3687 (const :tag "Not" nil)
3688 (const :tag "Always" t)
3689 (repeat :tag "Specific properties" (string :tag "Property"))
3690 (regexp :tag "Properties matched by regexp")))
3692 (defun org-property-inherit-p (property)
3693 "Return a non-nil value if PROPERTY should be inherited."
3694 (cond
3695 ((eq org-use-property-inheritance t) t)
3696 ((not org-use-property-inheritance) nil)
3697 ((stringp org-use-property-inheritance)
3698 (string-match org-use-property-inheritance property))
3699 ((listp org-use-property-inheritance)
3700 (member-ignore-case property org-use-property-inheritance))
3701 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3703 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3704 "The default column format, if no other format has been defined.
3705 This variable can be set on the per-file basis by inserting a line
3707 #+COLUMNS: %25ITEM ....."
3708 :group 'org-properties
3709 :type 'string)
3711 (defcustom org-columns-ellipses ".."
3712 "The ellipses to be used when a field in column view is truncated.
3713 When this is the empty string, as many characters as possible are shown,
3714 but then there will be no visual indication that the field has been truncated.
3715 When this is a string of length N, the last N characters of a truncated
3716 field are replaced by this string. If the column is narrower than the
3717 ellipses string, only part of the ellipses string will be shown."
3718 :group 'org-properties
3719 :type 'string)
3721 (defconst org-global-properties-fixed
3722 '(("VISIBILITY_ALL" . "folded children content all")
3723 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3724 "List of property/value pairs that can be inherited by any entry.
3726 These are fixed values, for the preset properties. The user variable
3727 that can be used to add to this list is `org-global-properties'.
3729 The entries in this list are cons cells where the car is a property
3730 name and cdr is a string with the value. If the value represents
3731 multiple items like an \"_ALL\" property, separate the items by
3732 spaces.")
3734 (defcustom org-global-properties nil
3735 "List of property/value pairs that can be inherited by any entry.
3737 This list will be combined with the constant `org-global-properties-fixed'.
3739 The entries in this list are cons cells where the car is a property
3740 name and cdr is a string with the value.
3742 You can set buffer-local values for the same purpose in the variable
3743 `org-file-properties' this by adding lines like
3745 #+PROPERTY: NAME VALUE"
3746 :group 'org-properties
3747 :type '(repeat
3748 (cons (string :tag "Property")
3749 (string :tag "Value"))))
3751 (defvar-local org-file-properties nil
3752 "List of property/value pairs that can be inherited by any entry.
3753 Valid for the current buffer.
3754 This variable is populated from #+PROPERTY lines.")
3756 (defgroup org-agenda nil
3757 "Options concerning agenda views in Org mode."
3758 :tag "Org Agenda"
3759 :group 'org)
3761 (defvar-local org-category nil
3762 "Variable used by org files to set a category for agenda display.
3763 Such files should use a file variable to set it, for example
3765 # -*- mode: org; org-category: \"ELisp\"
3767 or contain a special line
3769 #+CATEGORY: ELisp
3771 If the file does not specify a category, then file's base name
3772 is used instead.")
3773 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3775 (defcustom org-agenda-files nil
3776 "The files to be used for agenda display.
3778 If an entry is a directory, all files in that directory that are matched
3779 by `org-agenda-file-regexp' will be part of the file list.
3781 If the value of the variable is not a list but a single file name, then
3782 the list of agenda files is actually stored and maintained in that file,
3783 one agenda file per line. In this file paths can be given relative to
3784 `org-directory'. Tilde expansion and environment variable substitution
3785 are also made.
3787 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3788 and removed with `\\[org-remove-file]'."
3789 :group 'org-agenda
3790 :type '(choice
3791 (repeat :tag "List of files and directories" file)
3792 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3794 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3795 "Regular expression to match files for `org-agenda-files'.
3796 If any element in the list in that variable contains a directory instead
3797 of a normal file, all files in that directory that are matched by this
3798 regular expression will be included."
3799 :group 'org-agenda
3800 :type 'regexp)
3802 (defcustom org-agenda-text-search-extra-files nil
3803 "List of extra files to be searched by text search commands.
3804 These files will be searched in addition to the agenda files by the
3805 commands `org-search-view' (`\\[org-agenda] s') \
3806 and `org-occur-in-agenda-files'.
3807 Note that these files will only be searched for text search commands,
3808 not for the other agenda views like todo lists, tag searches or the weekly
3809 agenda. This variable is intended to list notes and possibly archive files
3810 that should also be searched by these two commands.
3811 In fact, if the first element in the list is the symbol `agenda-archives',
3812 then all archive files of all agenda files will be added to the search
3813 scope."
3814 :group 'org-agenda
3815 :type '(set :greedy t
3816 (const :tag "Agenda Archives" agenda-archives)
3817 (repeat :inline t (file))))
3819 (defvaralias 'org-agenda-multi-occur-extra-files
3820 'org-agenda-text-search-extra-files)
3822 (defcustom org-agenda-skip-unavailable-files nil
3823 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3824 A nil value means to remove them, after a query, from the list."
3825 :group 'org-agenda
3826 :type 'boolean)
3828 (defcustom org-calendar-to-agenda-key [?c]
3829 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3830 The command `org-calendar-goto-agenda' will be bound to this key. The
3831 default is the character `c' because then `c' can be used to switch back and
3832 forth between agenda and calendar."
3833 :group 'org-agenda
3834 :type 'sexp)
3836 (defcustom org-calendar-insert-diary-entry-key [?i]
3837 "The key to be installed in `calendar-mode-map' for adding diary entries.
3838 This option is irrelevant until `org-agenda-diary-file' has been configured
3839 to point to an Org file. When that is the case, the command
3840 `org-agenda-diary-entry' will be bound to the key given here, by default
3841 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3842 if you want to continue doing this, you need to change this to a different
3843 key."
3844 :group 'org-agenda
3845 :type 'sexp)
3847 (defcustom org-agenda-diary-file 'diary-file
3848 "File to which to add new entries with the `i' key in agenda and calendar.
3849 When this is the symbol `diary-file', the functionality in the Emacs
3850 calendar will be used to add entries to the `diary-file'. But when this
3851 points to a file, `org-agenda-diary-entry' will be used instead."
3852 :group 'org-agenda
3853 :type '(choice
3854 (const :tag "The standard Emacs diary file" diary-file)
3855 (file :tag "Special Org file diary entries")))
3857 (eval-after-load "calendar"
3858 '(progn
3859 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3860 'org-calendar-goto-agenda)
3861 (add-hook 'calendar-mode-hook
3862 (lambda ()
3863 (unless (eq org-agenda-diary-file 'diary-file)
3864 (define-key calendar-mode-map
3865 org-calendar-insert-diary-entry-key
3866 'org-agenda-diary-entry))))))
3868 (defgroup org-latex nil
3869 "Options for embedding LaTeX code into Org mode."
3870 :tag "Org LaTeX"
3871 :group 'org)
3873 (defcustom org-format-latex-options
3874 '(:foreground default :background default :scale 1.0
3875 :html-foreground "Black" :html-background "Transparent"
3876 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3877 "Options for creating images from LaTeX fragments.
3878 This is a property list with the following properties:
3879 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3880 `default' means use the foreground of the default face.
3881 `auto' means use the foreground from the text face.
3882 :background the background color, or \"Transparent\".
3883 `default' means use the background of the default face.
3884 `auto' means use the background from the text face.
3885 :scale a scaling factor for the size of the images, to get more pixels
3886 :html-foreground, :html-background, :html-scale
3887 the same numbers for HTML export.
3888 :matchers a list indicating which matchers should be used to
3889 find LaTeX fragments. Valid members of this list are:
3890 \"begin\" find environments
3891 \"$1\" find single characters surrounded by $.$
3892 \"$\" find math expressions surrounded by $...$
3893 \"$$\" find math expressions surrounded by $$....$$
3894 \"\\(\" find math expressions surrounded by \\(...\\)
3895 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3896 :group 'org-latex
3897 :type 'plist)
3899 (defcustom org-format-latex-signal-error t
3900 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3901 When nil, just push out a message."
3902 :group 'org-latex
3903 :version "24.1"
3904 :type 'boolean)
3906 (defcustom org-latex-to-mathml-jar-file nil
3907 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3908 Use this to specify additional executable file say a jar file.
3910 When using MathToWeb as the converter, specify the full-path to
3911 your mathtoweb.jar file."
3912 :group 'org-latex
3913 :version "24.1"
3914 :type '(choice
3915 (const :tag "None" nil)
3916 (file :tag "JAR file" :must-match t)))
3918 (defcustom org-latex-to-mathml-convert-command nil
3919 "Command to convert LaTeX fragments to MathML.
3920 Replace format-specifiers in the command as noted below and use
3921 `shell-command' to convert LaTeX to MathML.
3922 %j: Executable file in fully expanded form as specified by
3923 `org-latex-to-mathml-jar-file'.
3924 %I: Input LaTeX file in fully expanded form.
3925 %i: The latex fragment to be converted.
3926 %o: Output MathML file.
3928 This command is used by `org-create-math-formula'.
3930 When using MathToWeb as the converter, set this option to
3931 \"java -jar %j -unicode -force -df %o %I\".
3933 When using LaTeXML set this option to
3934 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3935 :group 'org-latex
3936 :version "24.1"
3937 :type '(choice
3938 (const :tag "None" nil)
3939 (string :tag "\nShell command")))
3941 (defcustom org-preview-latex-default-process 'dvipng
3942 "The default process to convert LaTeX fragments to image files.
3943 All available processes and theirs documents can be found in
3944 `org-preview-latex-process-alist', which see."
3945 :group 'org-latex
3946 :version "26.1"
3947 :package-version '(Org . "9.0")
3948 :type 'symbol)
3950 (defcustom org-preview-latex-process-alist
3951 '((dvipng
3952 :programs ("latex" "dvipng")
3953 :description "dvi > png"
3954 :message "you need to install the programs: latex and dvipng."
3955 :image-input-type "dvi"
3956 :image-output-type "png"
3957 :image-size-adjust (1.0 . 1.0)
3958 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3959 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3960 (dvisvgm
3961 :programs ("latex" "dvisvgm")
3962 :description "dvi > svg"
3963 :message "you need to install the programs: latex and dvisvgm."
3964 :use-xcolor t
3965 :image-input-type "dvi"
3966 :image-output-type "svg"
3967 :image-size-adjust (1.7 . 1.5)
3968 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3969 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3970 (imagemagick
3971 :programs ("latex" "convert")
3972 :description "pdf > png"
3973 :message "you need to install the programs: latex and imagemagick."
3974 :use-xcolor t
3975 :image-input-type "pdf"
3976 :image-output-type "png"
3977 :image-size-adjust (1.0 . 1.0)
3978 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3979 :image-converter
3980 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3981 "Definitions of external processes for LaTeX previewing.
3982 Org mode can use some external commands to generate TeX snippet's images for
3983 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3984 `org-create-formula-image' how to call them.
3986 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3987 PROPERTIES accepts the following attributes:
3989 :programs list of strings, required programs.
3990 :description string, describe the process.
3991 :message string, message it when required programs cannot be found.
3992 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3993 :image-output-type string, output file type of image converter (e.g., \"png\").
3994 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3995 deal with background and foreground color of image.
3996 Otherwise, dvipng style background and foreground color
3997 format are generated. You may then refer to them in
3998 command options with \"%F\" and \"%B\".
3999 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4000 image size showed in buffer and the cdr element is for
4001 HTML file. This option is only useful for process
4002 developers, users should use variable
4003 `org-format-latex-options' instead.
4004 :post-clean list of strings, files matched are to be cleaned up once
4005 the image is generated. When nil, the files with \".dvi\",
4006 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4007 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4008 be cleaned up.
4009 :latex-header list of strings, the LaTeX header of the snippet file.
4010 When nil, the fallback value is used instead, which is
4011 controlled by `org-format-latex-header',
4012 `org-latex-default-packages-alist' and
4013 `org-latex-packages-alist', which see.
4014 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4015 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4016 replaced with values defined below.
4017 :image-converter list of image converter commands strings. Each of them is
4018 given to the shell and supports any of the following
4019 place-holders defined below.
4021 Place-holders used by `:image-converter' and `:latex-compiler':
4023 %f input file name
4024 %b base name of input file
4025 %o base directory of input file
4026 %O absolute output file name
4028 Place-holders only used by `:image-converter':
4030 %F foreground of image
4031 %B background of image
4032 %D dpi, which is used to adjust image size by some processing commands.
4033 %S the image size scale ratio, which is used to adjust image size by some
4034 processing commands."
4035 :group 'org-latex
4036 :version "26.1"
4037 :package-version '(Org . "9.0")
4038 :type '(alist :tag "LaTeX to image backends"
4039 :value-type (plist)))
4041 (defcustom org-preview-latex-image-directory "ltximg/"
4042 "Path to store latex preview images.
4043 A relative path here creates many directories relative to the
4044 processed org files paths. An absolute path puts all preview
4045 images at the same place."
4046 :group 'org-latex
4047 :version "26.1"
4048 :package-version '(Org . "9.0")
4049 :type 'string)
4051 (defun org-format-latex-mathml-available-p ()
4052 "Return t if `org-latex-to-mathml-convert-command' is usable."
4053 (save-match-data
4054 (when (and (boundp 'org-latex-to-mathml-convert-command)
4055 org-latex-to-mathml-convert-command)
4056 (let ((executable (car (split-string
4057 org-latex-to-mathml-convert-command))))
4058 (when (executable-find executable)
4059 (if (string-match
4060 "%j" org-latex-to-mathml-convert-command)
4061 (file-readable-p org-latex-to-mathml-jar-file)
4062 t))))))
4064 (defcustom org-format-latex-header "\\documentclass{article}
4065 \\usepackage[usenames]{color}
4066 \[PACKAGES]
4067 \[DEFAULT-PACKAGES]
4068 \\pagestyle{empty} % do not remove
4069 % The settings below are copied from fullpage.sty
4070 \\setlength{\\textwidth}{\\paperwidth}
4071 \\addtolength{\\textwidth}{-3cm}
4072 \\setlength{\\oddsidemargin}{1.5cm}
4073 \\addtolength{\\oddsidemargin}{-2.54cm}
4074 \\setlength{\\evensidemargin}{\\oddsidemargin}
4075 \\setlength{\\textheight}{\\paperheight}
4076 \\addtolength{\\textheight}{-\\headheight}
4077 \\addtolength{\\textheight}{-\\headsep}
4078 \\addtolength{\\textheight}{-\\footskip}
4079 \\addtolength{\\textheight}{-3cm}
4080 \\setlength{\\topmargin}{1.5cm}
4081 \\addtolength{\\topmargin}{-2.54cm}"
4082 "The document header used for processing LaTeX fragments.
4083 It is imperative that this header make sure that no page number
4084 appears on the page. The package defined in the variables
4085 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4086 will either replace the placeholder \"[PACKAGES]\" in this
4087 header, or they will be appended."
4088 :group 'org-latex
4089 :type 'string)
4091 (defun org-set-packages-alist (var val)
4092 "Set the packages alist and make sure it has 3 elements per entry."
4093 (set var (mapcar (lambda (x)
4094 (if (and (consp x) (= (length x) 2))
4095 (list (car x) (nth 1 x) t)
4097 val)))
4099 (defun org-get-packages-alist (var)
4100 "Get the packages alist and make sure it has 3 elements per entry."
4101 (mapcar (lambda (x)
4102 (if (and (consp x) (= (length x) 2))
4103 (list (car x) (nth 1 x) t)
4105 (default-value var)))
4107 (defcustom org-latex-default-packages-alist
4108 '(("AUTO" "inputenc" t ("pdflatex"))
4109 ("T1" "fontenc" t ("pdflatex"))
4110 ("" "graphicx" t)
4111 ("" "grffile" t)
4112 ("" "longtable" nil)
4113 ("" "wrapfig" nil)
4114 ("" "rotating" nil)
4115 ("normalem" "ulem" t)
4116 ("" "amsmath" t)
4117 ("" "textcomp" t)
4118 ("" "amssymb" t)
4119 ("" "capt-of" nil)
4120 ("" "hyperref" nil))
4121 "Alist of default packages to be inserted in the header.
4123 Change this only if one of the packages here causes an
4124 incompatibility with another package you are using.
4126 The packages in this list are needed by one part or another of
4127 Org mode to function properly:
4129 - inputenc, fontenc: for basic font and character selection
4130 - graphicx: for including images
4131 - grffile: allow periods and spaces in graphics file names
4132 - longtable: For multipage tables
4133 - wrapfig: for figure placement
4134 - rotating: for sideways figures and tables
4135 - ulem: for underline and strike-through
4136 - amsmath: for subscript and superscript and math environments
4137 - textcomp, amssymb: for various symbols used
4138 for interpreting the entities in `org-entities'. You can skip
4139 some of these packages if you don't use any of their symbols.
4140 - capt-of: for captions outside of floats
4141 - hyperref: for cross references
4143 Therefore you should not modify this variable unless you know
4144 what you are doing. The one reason to change it anyway is that
4145 you might be loading some other package that conflicts with one
4146 of the default packages. Each element is either a cell or
4147 a string.
4149 A cell is of the format
4151 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4153 If SNIPPET-FLAG is non-nil, the package also needs to be included
4154 when compiling LaTeX snippets into images for inclusion into
4155 non-LaTeX output. COMPILERS is a list of compilers that should
4156 include the package, see `org-latex-compiler'. If the document
4157 compiler is not in the list, and the list is non-nil, the package
4158 will not be inserted in the final document.
4160 A string will be inserted as-is in the header of the document."
4161 :group 'org-latex
4162 :group 'org-export-latex
4163 :set 'org-set-packages-alist
4164 :get 'org-get-packages-alist
4165 :version "26.1"
4166 :package-version '(Org . "8.3")
4167 :type '(repeat
4168 (choice
4169 (list :tag "options/package pair"
4170 (string :tag "options")
4171 (string :tag "package")
4172 (boolean :tag "Snippet"))
4173 (string :tag "A line of LaTeX"))))
4175 (defcustom org-latex-packages-alist nil
4176 "Alist of packages to be inserted in every LaTeX header.
4178 These will be inserted after `org-latex-default-packages-alist'.
4179 Each element is either a cell or a string.
4181 A cell is of the format:
4183 (\"options\" \"package\" SNIPPET-FLAG)
4185 SNIPPET-FLAG, when non-nil, indicates that this package is also
4186 needed when turning LaTeX snippets into images for inclusion into
4187 non-LaTeX output.
4189 A string will be inserted as-is in the header of the document.
4191 Make sure that you only list packages here which:
4193 - you want in every file;
4194 - do not conflict with the setup in `org-format-latex-header';
4195 - do not conflict with the default packages in
4196 `org-latex-default-packages-alist'."
4197 :group 'org-latex
4198 :group 'org-export-latex
4199 :set 'org-set-packages-alist
4200 :get 'org-get-packages-alist
4201 :type '(repeat
4202 (choice
4203 (list :tag "options/package pair"
4204 (string :tag "options")
4205 (string :tag "package")
4206 (boolean :tag "Snippet"))
4207 (string :tag "A line of LaTeX"))))
4209 (defgroup org-appearance nil
4210 "Settings for Org mode appearance."
4211 :tag "Org Appearance"
4212 :group 'org)
4214 (defcustom org-level-color-stars-only nil
4215 "Non-nil means fontify only the stars in each headline.
4216 When nil, the entire headline is fontified.
4217 Changing it requires restart of `font-lock-mode' to become effective
4218 also in regions already fontified."
4219 :group 'org-appearance
4220 :type 'boolean)
4222 (defcustom org-hide-leading-stars nil
4223 "Non-nil means hide the first N-1 stars in a headline.
4224 This works by using the face `org-hide' for these stars. This
4225 face is white for a light background, and black for a dark
4226 background. You may have to customize the face `org-hide' to
4227 make this work.
4228 Changing it requires restart of `font-lock-mode' to become effective
4229 also in regions already fontified.
4230 You may also set this on a per-file basis by adding one of the following
4231 lines to the buffer:
4233 #+STARTUP: hidestars
4234 #+STARTUP: showstars"
4235 :group 'org-appearance
4236 :type 'boolean)
4238 (defcustom org-hidden-keywords nil
4239 "List of symbols corresponding to keywords to be hidden the org buffer.
4240 For example, a value \\='(title) for this list will make the document's title
4241 appear in the buffer without the initial #+TITLE: keyword."
4242 :group 'org-appearance
4243 :version "24.1"
4244 :type '(set (const :tag "#+AUTHOR" author)
4245 (const :tag "#+DATE" date)
4246 (const :tag "#+EMAIL" email)
4247 (const :tag "#+TITLE" title)))
4249 (defcustom org-custom-properties nil
4250 "List of properties (as strings) with a special meaning.
4251 The default use of these custom properties is to let the user
4252 hide them with `org-toggle-custom-properties-visibility'."
4253 :group 'org-properties
4254 :group 'org-appearance
4255 :version "24.3"
4256 :type '(repeat (string :tag "Property Name")))
4258 (defcustom org-fontify-done-headline nil
4259 "Non-nil means change the face of a headline if it is marked DONE.
4260 Normally, only the TODO/DONE keyword indicates the state of a headline.
4261 When this is non-nil, the headline after the keyword is set to the
4262 `org-headline-done' as an additional indication."
4263 :group 'org-appearance
4264 :type 'boolean)
4266 (defcustom org-fontify-emphasized-text t
4267 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4268 Changing this variable requires a restart of Emacs to take effect."
4269 :group 'org-appearance
4270 :type 'boolean)
4272 (defcustom org-fontify-whole-heading-line nil
4273 "Non-nil means fontify the whole line for headings.
4274 This is useful when setting a background color for the
4275 org-level-* faces."
4276 :group 'org-appearance
4277 :type 'boolean)
4279 (defcustom org-highlight-latex-and-related nil
4280 "Non-nil means highlight LaTeX related syntax in the buffer.
4281 When non nil, the value should be a list containing any of the
4282 following symbols:
4283 `latex' Highlight LaTeX snippets and environments.
4284 `script' Highlight subscript and superscript.
4285 `entities' Highlight entities."
4286 :group 'org-appearance
4287 :version "24.4"
4288 :package-version '(Org . "8.0")
4289 :type '(choice
4290 (const :tag "No highlighting" nil)
4291 (set :greedy t :tag "Highlight"
4292 (const :tag "LaTeX snippets and environments" latex)
4293 (const :tag "Subscript and superscript" script)
4294 (const :tag "Entities" entities))))
4296 (defcustom org-hide-emphasis-markers nil
4297 "Non-nil mean font-lock should hide the emphasis marker characters."
4298 :group 'org-appearance
4299 :type 'boolean)
4301 (defcustom org-hide-macro-markers nil
4302 "Non-nil mean font-lock should hide the brackets marking macro calls."
4303 :group 'org-appearance
4304 :type 'boolean)
4306 (defcustom org-pretty-entities nil
4307 "Non-nil means show entities as UTF8 characters.
4308 When nil, the \\name form remains in the buffer."
4309 :group 'org-appearance
4310 :version "24.1"
4311 :type 'boolean)
4313 (defcustom org-pretty-entities-include-sub-superscripts t
4314 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4315 :group 'org-appearance
4316 :version "24.1"
4317 :type 'boolean)
4319 (defvar org-emph-re nil
4320 "Regular expression for matching emphasis.
4321 After a match, the match groups contain these elements:
4322 0 The match of the full regular expression, including the characters
4323 before and after the proper match
4324 1 The character before the proper match, or empty at beginning of line
4325 2 The proper match, including the leading and trailing markers
4326 3 The leading marker like * or /, indicating the type of highlighting
4327 4 The text between the emphasis markers, not including the markers
4328 5 The character after the match, empty at the end of a line")
4330 (defvar org-verbatim-re nil
4331 "Regular expression for matching verbatim text.")
4333 (defvar org-emphasis-regexp-components) ; defined just below
4334 (defvar org-emphasis-alist) ; defined just below
4335 (defun org-set-emph-re (var val)
4336 "Set variable and compute the emphasis regular expression."
4337 (set var val)
4338 (when (and (boundp 'org-emphasis-alist)
4339 (boundp 'org-emphasis-regexp-components)
4340 org-emphasis-alist org-emphasis-regexp-components)
4341 (pcase-let*
4342 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4343 (body (if (<= nl 0) body
4344 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4345 (template
4346 (format (concat "\\([%s]\\|^\\)" ;before markers
4347 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4348 "\\([%s]\\|$\\)") ;after markers
4349 pre border border body border post)))
4350 (setq org-emph-re (format template "*/_+"))
4351 (setq org-verbatim-re (format template "=~")))))
4353 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4354 ;; set this option proved cumbersome. See this message/thread:
4355 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4356 (defvar org-emphasis-regexp-components
4357 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4358 "Components used to build the regular expression for emphasis.
4359 This is a list with five entries. Terminology: In an emphasis string
4360 like \" *strong word* \", we call the initial space PREMATCH, the final
4361 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4362 and \"trong wor\" is the body. The different components in this variable
4363 specify what is allowed/forbidden in each part:
4365 pre Chars allowed as prematch. Beginning of line will be allowed too.
4366 post Chars allowed as postmatch. End of line will be allowed too.
4367 border The chars *forbidden* as border characters.
4368 body-regexp A regexp like \".\" to match a body character. Don't use
4369 non-shy groups here, and don't allow newline here.
4370 newline The maximum number of newlines allowed in an emphasis exp.
4372 You need to reload Org or to restart Emacs after setting this.")
4374 (defcustom org-emphasis-alist
4375 '(("*" bold)
4376 ("/" italic)
4377 ("_" underline)
4378 ("=" org-verbatim verbatim)
4379 ("~" org-code verbatim)
4380 ("+" (:strike-through t)))
4381 "Alist of characters and faces to emphasize text.
4382 Text starting and ending with a special character will be emphasized,
4383 for example *bold*, _underlined_ and /italic/. This variable sets the
4384 marker characters and the face to be used by font-lock for highlighting
4385 in Org buffers.
4387 You need to reload Org or to restart Emacs after customizing this."
4388 :group 'org-appearance
4389 :set 'org-set-emph-re
4390 :version "24.4"
4391 :package-version '(Org . "8.0")
4392 :type '(repeat
4393 (list
4394 (string :tag "Marker character")
4395 (choice
4396 (face :tag "Font-lock-face")
4397 (plist :tag "Face property list"))
4398 (option (const verbatim)))))
4400 (defvar org-protecting-blocks '("src" "example" "export")
4401 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4402 This is needed for font-lock setup.")
4404 ;;; Functions and variables from their packages
4405 ;; Declared here to avoid compiler warnings
4406 (defvar mark-active)
4408 ;; Various packages
4409 (declare-function calc-eval "calc" (str &optional separator &rest args))
4410 (declare-function calendar-forward-day "cal-move" (arg))
4411 (declare-function calendar-goto-date "cal-move" (date))
4412 (declare-function calendar-goto-today "cal-move" ())
4413 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4414 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4415 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4416 (declare-function cdlatex-tab "ext:cdlatex" ())
4417 (declare-function dired-get-filename
4418 "dired"
4419 (&optional localp no-error-if-not-filep))
4420 (declare-function iswitchb-read-buffer
4421 "iswitchb"
4422 (prompt &optional
4423 default require-match _predicate start matches-set))
4424 (declare-function org-agenda-change-all-lines
4425 "org-agenda"
4426 (newhead hdmarker &optional fixface just-this))
4427 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4428 "org-agenda"
4429 (&optional end))
4430 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4431 (declare-function org-agenda-format-item
4432 "org-agenda"
4433 (extra txt &optional level category tags dotime
4434 remove-re habitp))
4435 (declare-function org-agenda-maybe-redo "org-agenda" ())
4436 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4437 (declare-function org-agenda-save-markers-for-cut-and-paste
4438 "org-agenda"
4439 (beg end))
4440 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4441 (declare-function org-agenda-skip "org-agenda" ())
4442 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4443 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4444 (declare-function org-indent-mode "org-indent" (&optional arg))
4445 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4446 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4447 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4448 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4449 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4450 (declare-function parse-time-string "parse-time" (string))
4451 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4453 (defvar align-mode-rules-list)
4454 (defvar calc-embedded-close-formula)
4455 (defvar calc-embedded-open-formula)
4456 (defvar calc-embedded-open-mode)
4457 (defvar font-lock-unfontify-region-function)
4458 (defvar iswitchb-temp-buflist)
4459 (defvar org-agenda-tags-todo-honor-ignore-options)
4460 (defvar remember-data-file)
4461 (defvar texmathp-why)
4463 ;;;###autoload
4464 (defun turn-on-orgtbl ()
4465 "Unconditionally turn on `orgtbl-mode'."
4466 (require 'org-table)
4467 (orgtbl-mode 1))
4469 (defun org-at-table-p (&optional table-type)
4470 "Non-nil if the cursor is inside an Org table.
4471 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4472 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4473 (or (not (derived-mode-p 'org-mode))
4474 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4475 (and e (or table-type
4476 (eq 'org (org-element-property :type e))))))))
4478 (defun org-at-table.el-p ()
4479 "Non-nil when point is at a table.el table."
4480 (and (org-match-line "[ \t]*[|+]")
4481 (let ((element (org-element-at-point)))
4482 (and (eq (org-element-type element) 'table)
4483 (eq (org-element-property :type element) 'table.el)))))
4485 (defun org-at-table-hline-p ()
4486 "Non-nil when point is inside a hline in a table.
4487 Assume point is already in a table."
4488 (org-match-line org-table-hline-regexp))
4490 (defun org-table-map-tables (function &optional quietly)
4491 "Apply FUNCTION to the start of all tables in the buffer."
4492 (org-with-wide-buffer
4493 (goto-char (point-min))
4494 (while (re-search-forward org-table-any-line-regexp nil t)
4495 (unless quietly
4496 (message "Mapping tables: %d%%"
4497 (floor (* 100.0 (point)) (buffer-size))))
4498 (beginning-of-line 1)
4499 (when (and (looking-at org-table-line-regexp)
4500 ;; Exclude tables in src/example/verbatim/clocktable blocks
4501 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4502 (save-excursion (funcall function))
4503 (or (looking-at org-table-line-regexp)
4504 (forward-char 1)))
4505 (re-search-forward org-table-any-border-regexp nil 1)))
4506 (unless quietly (message "Mapping tables: done")))
4508 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4509 (declare-function org-clock-update-mode-line "org-clock" ())
4510 (declare-function org-resolve-clocks "org-clock"
4511 (&optional also-non-dangling-p prompt last-valid))
4513 (defun org-at-TBLFM-p (&optional pos)
4514 "Non-nil when point (or POS) is in #+TBLFM line."
4515 (save-excursion
4516 (goto-char (or pos (point)))
4517 (beginning-of-line)
4518 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4519 (eq (org-element-type (org-element-at-point)) 'table))))
4521 (defvar org-clock-start-time)
4522 (defvar org-clock-marker (make-marker)
4523 "Marker recording the last clock-in.")
4524 (defvar org-clock-hd-marker (make-marker)
4525 "Marker recording the last clock-in, but the headline position.")
4526 (defvar org-clock-heading ""
4527 "The heading of the current clock entry.")
4528 (defun org-clock-is-active ()
4529 "Return the buffer where the clock is currently running.
4530 Return nil if no clock is running."
4531 (marker-buffer org-clock-marker))
4533 (defun org-check-running-clock ()
4534 "Check if the current buffer contains the running clock.
4535 If yes, offer to stop it and to save the buffer with the changes."
4536 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4537 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4538 (buffer-name))))
4539 (org-clock-out)
4540 (when (y-or-n-p "Save changed buffer?")
4541 (save-buffer))))
4543 (defun org-clocktable-try-shift (dir n)
4544 "Check if this line starts a clock table, if yes, shift the time block."
4545 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4546 (org-clocktable-shift dir n)))
4548 ;;;###autoload
4549 (defun org-clock-persistence-insinuate ()
4550 "Set up hooks for clock persistence."
4551 (require 'org-clock)
4552 (add-hook 'org-mode-hook 'org-clock-load)
4553 (add-hook 'kill-emacs-hook 'org-clock-save))
4555 (defgroup org-archive nil
4556 "Options concerning archiving in Org mode."
4557 :tag "Org Archive"
4558 :group 'org-structure)
4560 (defcustom org-archive-location "%s_archive::"
4561 "The location where subtrees should be archived.
4563 The value of this variable is a string, consisting of two parts,
4564 separated by a double-colon. The first part is a filename and
4565 the second part is a headline.
4567 When the filename is omitted, archiving happens in the same file.
4568 %s in the filename will be replaced by the current file
4569 name (without the directory part). Archiving to a different file
4570 is useful to keep archived entries from contributing to the
4571 Org Agenda.
4573 The archived entries will be filed as subtrees of the specified
4574 headline. When the headline is omitted, the subtrees are simply
4575 filed away at the end of the file, as top-level entries. Also in
4576 the heading you can use %s to represent the file name, this can be
4577 useful when using the same archive for a number of different files.
4579 Here are a few examples:
4580 \"%s_archive::\"
4581 If the current file is Projects.org, archive in file
4582 Projects.org_archive, as top-level trees. This is the default.
4584 \"::* Archived Tasks\"
4585 Archive in the current file, under the top-level headline
4586 \"* Archived Tasks\".
4588 \"~/org/archive.org::\"
4589 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4591 \"~/org/archive.org::* From %s\"
4592 Archive in file ~/org/archive.org (absolute path), under headlines
4593 \"From FILENAME\" where file name is the current file name.
4595 \"~/org/datetree.org::datetree/* Finished Tasks\"
4596 The \"datetree/\" string is special, signifying to archive
4597 items to the datetree. Items are placed in either the CLOSED
4598 date of the item, or the current date if there is no CLOSED date.
4599 The heading will be a subentry to the current date. There doesn't
4600 need to be a heading, but there always needs to be a slash after
4601 datetree. For example, to store archived items directly in the
4602 datetree, use \"~/org/datetree.org::datetree/\".
4604 \"basement::** Finished Tasks\"
4605 Archive in file ./basement (relative path), as level 3 trees
4606 below the level 2 heading \"** Finished Tasks\".
4608 You may set this option on a per-file basis by adding to the buffer a
4609 line like
4611 #+ARCHIVE: basement::** Finished Tasks
4613 You may also define it locally for a subtree by setting an ARCHIVE property
4614 in the entry. If such a property is found in an entry, or anywhere up
4615 the hierarchy, it will be used."
4616 :group 'org-archive
4617 :type 'string)
4619 (defcustom org-agenda-skip-archived-trees t
4620 "Non-nil means the agenda will skip any items located in archived trees.
4621 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4622 variable is no longer recommended, you should leave it at the value t.
4623 Instead, use the key `v' to cycle the archives-mode in the agenda."
4624 :group 'org-archive
4625 :group 'org-agenda-skip
4626 :type 'boolean)
4628 (defcustom org-columns-skip-archived-trees t
4629 "Non-nil means ignore archived trees when creating column view."
4630 :group 'org-archive
4631 :group 'org-properties
4632 :type 'boolean)
4634 (defcustom org-cycle-open-archived-trees nil
4635 "Non-nil means `org-cycle' will open archived trees.
4636 An archived tree is a tree marked with the tag ARCHIVE.
4637 When nil, archived trees will stay folded. You can still open them with
4638 normal outline commands like `show-all', but not with the cycling commands."
4639 :group 'org-archive
4640 :group 'org-cycle
4641 :type 'boolean)
4643 (defcustom org-sparse-tree-open-archived-trees nil
4644 "Non-nil means sparse tree construction shows matches in archived trees.
4645 When nil, matches in these trees are highlighted, but the trees are kept in
4646 collapsed state."
4647 :group 'org-archive
4648 :group 'org-sparse-trees
4649 :type 'boolean)
4651 (defcustom org-sparse-tree-default-date-type nil
4652 "The default date type when building a sparse tree.
4653 When this is nil, a date is a scheduled or a deadline timestamp.
4654 Otherwise, these types are allowed:
4656 all: all timestamps
4657 active: only active timestamps (<...>)
4658 inactive: only inactive timestamps ([...])
4659 scheduled: only scheduled timestamps
4660 deadline: only deadline timestamps"
4661 :type '(choice (const :tag "Scheduled or deadline" nil)
4662 (const :tag "All timestamps" all)
4663 (const :tag "Only active timestamps" active)
4664 (const :tag "Only inactive timestamps" inactive)
4665 (const :tag "Only scheduled timestamps" scheduled)
4666 (const :tag "Only deadline timestamps" deadline)
4667 (const :tag "Only closed timestamps" closed))
4668 :version "26.1"
4669 :package-version '(Org . "8.3")
4670 :group 'org-sparse-trees)
4672 (defun org-cycle-hide-archived-subtrees (state)
4673 "Re-hide all archived subtrees after a visibility state change.
4674 STATE should be one of the symbols listed in the docstring of
4675 `org-cycle-hook'."
4676 (when (and (not org-cycle-open-archived-trees)
4677 (not (memq state '(overview folded))))
4678 (save-excursion
4679 (let* ((globalp (memq state '(contents all)))
4680 (beg (if globalp (point-min) (point)))
4681 (end (if globalp (point-max) (org-end-of-subtree t))))
4682 (org-hide-archived-subtrees beg end)
4683 (goto-char beg)
4684 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4685 (message "%s" (substitute-command-keys
4686 "Subtree is archived and stays closed. Use \
4687 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4689 (defun org-force-cycle-archived ()
4690 "Cycle subtree even if it is archived."
4691 (interactive)
4692 (setq this-command 'org-cycle)
4693 (let ((org-cycle-open-archived-trees t))
4694 (call-interactively 'org-cycle)))
4696 (defun org-hide-archived-subtrees (beg end)
4697 "Re-hide all archived subtrees after a visibility state change."
4698 (org-with-wide-buffer
4699 (let ((case-fold-search nil)
4700 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4701 (goto-char beg)
4702 ;; Include headline point is currently on.
4703 (beginning-of-line)
4704 (while (and (< (point) end) (re-search-forward re end t))
4705 (when (member org-archive-tag (org-get-tags))
4706 (org-flag-subtree t)
4707 (org-end-of-subtree t))))))
4709 (declare-function outline-end-of-heading "outline" ())
4710 (declare-function outline-flag-region "outline" (from to flag))
4711 (defun org-flag-subtree (flag)
4712 (save-excursion
4713 (org-back-to-heading t)
4714 (outline-end-of-heading)
4715 (outline-flag-region (point)
4716 (progn (org-end-of-subtree t) (point))
4717 flag)))
4719 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4721 ;; Declare Column View Code
4723 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4724 (declare-function org-columns-compute "org-colview" (property))
4726 ;; Declare ID code
4728 (declare-function org-id-store-link "org-id")
4729 (declare-function org-id-locations-load "org-id")
4730 (declare-function org-id-locations-save "org-id")
4731 (defvar org-id-track-globally)
4733 ;;; Variables for pre-computed regular expressions, all buffer local
4735 (defvar-local org-todo-regexp nil
4736 "Matches any of the TODO state keywords.
4737 Since TODO keywords are case-sensitive, `case-fold-search' is
4738 expected to be bound to nil when matching against this regexp.")
4740 (defvar-local org-not-done-regexp nil
4741 "Matches any of the TODO state keywords except the last one.
4742 Since TODO keywords are case-sensitive, `case-fold-search' is
4743 expected to be bound to nil when matching against this regexp.")
4745 (defvar-local org-not-done-heading-regexp nil
4746 "Matches a TODO headline that is not done.
4747 Since TODO keywords are case-sensitive, `case-fold-search' is
4748 expected to be bound to nil when matching against this regexp.")
4750 (defvar-local org-todo-line-regexp nil
4751 "Matches a headline and puts TODO state into group 2 if present.
4752 Since TODO keywords are case-sensitive, `case-fold-search' is
4753 expected to be bound to nil when matching against this regexp.")
4755 (defvar-local org-complex-heading-regexp nil
4756 "Matches a headline and puts everything into groups:
4758 group 1: Stars
4759 group 2: The TODO keyword, maybe
4760 group 3: Priority cookie
4761 group 4: True headline
4762 group 5: Tags
4764 Since TODO keywords are case-sensitive, `case-fold-search' is
4765 expected to be bound to nil when matching against this regexp.")
4767 (defvar-local org-complex-heading-regexp-format nil
4768 "Printf format to make regexp to match an exact headline.
4769 This regexp will match the headline of any node which has the
4770 exact headline text that is put into the format, but may have any
4771 TODO state, priority and tags.")
4773 (defvar-local org-todo-line-tags-regexp nil
4774 "Matches a headline and puts TODO state into group 2 if present.
4775 Also put tags into group 4 if tags are present.")
4777 (defconst org-plain-time-of-day-regexp
4778 (concat
4779 "\\(\\<[012]?[0-9]"
4780 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4781 "\\(--?"
4782 "\\(\\<[012]?[0-9]"
4783 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4784 "\\)?")
4785 "Regular expression to match a plain time or time range.
4786 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4787 groups carry important information:
4788 0 the full match
4789 1 the first time, range or not
4790 8 the second time, if it is a range.")
4792 (defconst org-plain-time-extension-regexp
4793 (concat
4794 "\\(\\<[012]?[0-9]"
4795 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4796 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4797 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4798 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4799 groups carry important information:
4800 0 the full match
4801 7 hours of duration
4802 9 minutes of duration")
4804 (defconst org-stamp-time-of-day-regexp
4805 (concat
4806 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4807 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4808 "\\(--?"
4809 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4810 "Regular expression to match a timestamp time or time range.
4811 After a match, the following groups carry important information:
4812 0 the full match
4813 1 date plus weekday, for back referencing to make sure both times are on the same day
4814 2 the first time, range or not
4815 4 the second time, if it is a range.")
4817 (defconst org-startup-options
4818 '(("fold" org-startup-folded t)
4819 ("overview" org-startup-folded t)
4820 ("nofold" org-startup-folded nil)
4821 ("showall" org-startup-folded nil)
4822 ("showeverything" org-startup-folded showeverything)
4823 ("content" org-startup-folded content)
4824 ("indent" org-startup-indented t)
4825 ("noindent" org-startup-indented nil)
4826 ("hidestars" org-hide-leading-stars t)
4827 ("showstars" org-hide-leading-stars nil)
4828 ("odd" org-odd-levels-only t)
4829 ("oddeven" org-odd-levels-only nil)
4830 ("align" org-startup-align-all-tables t)
4831 ("noalign" org-startup-align-all-tables nil)
4832 ("shrink" org-startup-shrink-all-tables t)
4833 ("inlineimages" org-startup-with-inline-images t)
4834 ("noinlineimages" org-startup-with-inline-images nil)
4835 ("latexpreview" org-startup-with-latex-preview t)
4836 ("nolatexpreview" org-startup-with-latex-preview nil)
4837 ("customtime" org-display-custom-times t)
4838 ("logdone" org-log-done time)
4839 ("lognotedone" org-log-done note)
4840 ("nologdone" org-log-done nil)
4841 ("lognoteclock-out" org-log-note-clock-out t)
4842 ("nolognoteclock-out" org-log-note-clock-out nil)
4843 ("logrepeat" org-log-repeat state)
4844 ("lognoterepeat" org-log-repeat note)
4845 ("logdrawer" org-log-into-drawer t)
4846 ("nologdrawer" org-log-into-drawer nil)
4847 ("logstatesreversed" org-log-states-order-reversed t)
4848 ("nologstatesreversed" org-log-states-order-reversed nil)
4849 ("nologrepeat" org-log-repeat nil)
4850 ("logreschedule" org-log-reschedule time)
4851 ("lognotereschedule" org-log-reschedule note)
4852 ("nologreschedule" org-log-reschedule nil)
4853 ("logredeadline" org-log-redeadline time)
4854 ("lognoteredeadline" org-log-redeadline note)
4855 ("nologredeadline" org-log-redeadline nil)
4856 ("logrefile" org-log-refile time)
4857 ("lognoterefile" org-log-refile note)
4858 ("nologrefile" org-log-refile nil)
4859 ("fninline" org-footnote-define-inline t)
4860 ("nofninline" org-footnote-define-inline nil)
4861 ("fnlocal" org-footnote-section nil)
4862 ("fnauto" org-footnote-auto-label t)
4863 ("fnprompt" org-footnote-auto-label nil)
4864 ("fnconfirm" org-footnote-auto-label confirm)
4865 ("fnplain" org-footnote-auto-label plain)
4866 ("fnadjust" org-footnote-auto-adjust t)
4867 ("nofnadjust" org-footnote-auto-adjust nil)
4868 ("constcgs" constants-unit-system cgs)
4869 ("constSI" constants-unit-system SI)
4870 ("noptag" org-tag-persistent-alist nil)
4871 ("hideblocks" org-hide-block-startup t)
4872 ("nohideblocks" org-hide-block-startup nil)
4873 ("beamer" org-startup-with-beamer-mode t)
4874 ("entitiespretty" org-pretty-entities t)
4875 ("entitiesplain" org-pretty-entities nil))
4876 "Variable associated with STARTUP options for org-mode.
4877 Each element is a list of three items: the startup options (as written
4878 in the #+STARTUP line), the corresponding variable, and the value to set
4879 this variable to if the option is found. An optional forth element PUSH
4880 means to push this value onto the list in the variable.")
4882 (defcustom org-group-tags t
4883 "When non-nil (the default), use group tags.
4884 This can be turned on/off through `org-toggle-tags-groups'."
4885 :group 'org-tags
4886 :group 'org-startup
4887 :type 'boolean)
4889 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4891 (defun org-toggle-tags-groups ()
4892 "Toggle support for group tags.
4893 Support for group tags is controlled by the option
4894 `org-group-tags', which is non-nil by default."
4895 (interactive)
4896 (setq org-group-tags (not org-group-tags))
4897 (cond ((and (derived-mode-p 'org-agenda-mode)
4898 org-group-tags)
4899 (org-agenda-redo))
4900 ((derived-mode-p 'org-mode)
4901 (let ((org-inhibit-startup t)) (org-mode))))
4902 (message "Groups tags support has been turned %s"
4903 (if org-group-tags "on" "off")))
4905 (defun org-set-regexps-and-options (&optional tags-only)
4906 "Precompute regular expressions used in the current buffer.
4907 When optional argument TAGS-ONLY is non-nil, only compute tags
4908 related expressions."
4909 (when (derived-mode-p 'org-mode)
4910 (let ((alist (org--setup-collect-keywords
4911 (org-make-options-regexp
4912 (append '("FILETAGS" "TAGS" "SETUPFILE")
4913 (and (not tags-only)
4914 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4915 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4916 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4917 ;; Startup options. Get this early since it does change
4918 ;; behavior for other options (e.g., tags).
4919 (let ((startup (cdr (assq 'startup alist))))
4920 (dolist (option startup)
4921 (let ((entry (assoc-string option org-startup-options t)))
4922 (when entry
4923 (let ((var (nth 1 entry))
4924 (val (nth 2 entry)))
4925 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4926 (unless (listp (symbol-value var))
4927 (set (make-local-variable var) nil))
4928 (add-to-list var val)))))))
4929 (setq-local org-file-tags
4930 (mapcar #'org-add-prop-inherited
4931 (cdr (assq 'filetags alist))))
4932 (setq org-current-tag-alist
4933 (append org-tag-persistent-alist
4934 (let ((tags (cdr (assq 'tags alist))))
4935 (if tags (org-tag-string-to-alist tags)
4936 org-tag-alist))))
4937 (setq org-tag-groups-alist
4938 (org-tag-alist-to-groups org-current-tag-alist))
4939 (unless tags-only
4940 ;; File properties.
4941 (setq-local org-file-properties (cdr (assq 'property alist)))
4942 ;; Archive location.
4943 (let ((archive (cdr (assq 'archive alist))))
4944 (when archive (setq-local org-archive-location archive)))
4945 ;; Category.
4946 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4947 (when cat
4948 (setq-local org-category (intern cat))
4949 (setq-local org-file-properties
4950 (org--update-property-plist
4951 "CATEGORY" cat org-file-properties))))
4952 ;; Columns.
4953 (let ((column (cdr (assq 'columns alist))))
4954 (when column (setq-local org-columns-default-format column)))
4955 ;; Constants.
4956 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4957 ;; Link abbreviations.
4958 (let ((links (cdr (assq 'link alist))))
4959 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4960 ;; Priorities.
4961 (let ((priorities (cdr (assq 'priorities alist))))
4962 (when priorities
4963 (setq-local org-highest-priority (nth 0 priorities))
4964 (setq-local org-lowest-priority (nth 1 priorities))
4965 (setq-local org-default-priority (nth 2 priorities))))
4966 ;; Scripts.
4967 (let ((scripts (assq 'scripts alist)))
4968 (when scripts
4969 (setq-local org-use-sub-superscripts (cdr scripts))))
4970 ;; TODO keywords.
4971 (setq-local org-todo-kwd-alist nil)
4972 (setq-local org-todo-key-alist nil)
4973 (setq-local org-todo-key-trigger nil)
4974 (setq-local org-todo-keywords-1 nil)
4975 (setq-local org-done-keywords nil)
4976 (setq-local org-todo-heads nil)
4977 (setq-local org-todo-sets nil)
4978 (setq-local org-todo-log-states nil)
4979 (let ((todo-sequences
4980 (or (nreverse (cdr (assq 'todo alist)))
4981 (let ((d (default-value 'org-todo-keywords)))
4982 (if (not (stringp (car d))) d
4983 ;; XXX: Backward compatibility code.
4984 (list (cons org-todo-interpretation d)))))))
4985 (dolist (sequence todo-sequences)
4986 (let* ((sequence (or (run-hook-with-args-until-success
4987 'org-todo-setup-filter-hook sequence)
4988 sequence))
4989 (sequence-type (car sequence))
4990 (keywords (cdr sequence))
4991 (sep (member "|" keywords))
4992 names alist)
4993 (dolist (k (remove "|" keywords))
4994 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4996 (error "Invalid TODO keyword %s" k))
4997 (let ((name (match-string 1 k))
4998 (key (match-string 2 k))
4999 (log (org-extract-log-state-settings k)))
5000 (push name names)
5001 (push (cons name (and key (string-to-char key))) alist)
5002 (when log (push log org-todo-log-states))))
5003 (let* ((names (nreverse names))
5004 (done (if sep (org-remove-keyword-keys (cdr sep))
5005 (last names)))
5006 (head (car names))
5007 (tail (list sequence-type head (car done) (org-last done))))
5008 (add-to-list 'org-todo-heads head 'append)
5009 (push names org-todo-sets)
5010 (setq org-done-keywords (append org-done-keywords done nil))
5011 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5012 (setq org-todo-key-alist
5013 (append org-todo-key-alist
5014 (and alist
5015 (append '((:startgroup))
5016 (nreverse alist)
5017 '((:endgroup))))))
5018 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5019 (setq org-todo-sets (nreverse org-todo-sets)
5020 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5021 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5022 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5023 ;; Compute the regular expressions and other local variables.
5024 ;; Using `org-outline-regexp-bol' would complicate them much,
5025 ;; because of the fixed white space at the end of that string.
5026 (unless org-done-keywords
5027 (setq org-done-keywords
5028 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5029 (setq org-not-done-keywords
5030 (org-delete-all org-done-keywords
5031 (copy-sequence org-todo-keywords-1))
5032 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5033 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5034 org-not-done-heading-regexp
5035 (format org-heading-keyword-regexp-format org-not-done-regexp)
5036 org-todo-line-regexp
5037 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5038 org-complex-heading-regexp
5039 (concat "^\\(\\*+\\)"
5040 "\\(?: +" org-todo-regexp "\\)?"
5041 "\\(?: +\\(\\[#.\\]\\)\\)?"
5042 "\\(?: +\\(.*?\\)\\)??"
5043 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5044 "[ \t]*$")
5045 org-complex-heading-regexp-format
5046 (concat "^\\(\\*+\\)"
5047 "\\(?: +" org-todo-regexp "\\)?"
5048 "\\(?: +\\(\\[#.\\]\\)\\)?"
5049 "\\(?: +"
5050 ;; Stats cookies can be stuck to body.
5051 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5052 "\\(%s\\)"
5053 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5054 "\\)"
5055 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5056 "[ \t]*$")
5057 org-todo-line-tags-regexp
5058 (concat "^\\(\\*+\\)"
5059 "\\(?: +" org-todo-regexp "\\)?"
5060 "\\(?: +\\(.*?\\)\\)??"
5061 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5062 "[ \t]*$"))
5063 (org-compute-latex-and-related-regexp)))))
5065 (defun org--setup-collect-keywords (regexp &optional files alist)
5066 "Return setup keywords values as an alist.
5068 REGEXP matches a subset of setup keywords. FILES is a list of
5069 file names already visited. It is used to avoid circular setup
5070 files. ALIST, when non-nil, is the alist computed so far.
5072 Return value contains the following keys: `archive', `category',
5073 `columns', `constants', `filetags', `link', `priorities',
5074 `property', `scripts', `startup', `tags' and `todo'."
5075 (org-with-wide-buffer
5076 (goto-char (point-min))
5077 (let ((case-fold-search t))
5078 (while (re-search-forward regexp nil t)
5079 (let ((element (org-element-at-point)))
5080 (when (eq (org-element-type element) 'keyword)
5081 (let ((key (org-element-property :key element))
5082 (value (org-element-property :value element)))
5083 (cond
5084 ((equal key "ARCHIVE")
5085 (when (org-string-nw-p value)
5086 (push (cons 'archive value) alist)))
5087 ((equal key "CATEGORY") (push (cons 'category value) alist))
5088 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5089 ((equal key "CONSTANTS")
5090 (let* ((constants (assq 'constants alist))
5091 (store (cdr constants)))
5092 (dolist (pair (split-string value))
5093 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5094 pair)
5095 (let* ((name (match-string 1 pair))
5096 (value (match-string 2 pair))
5097 (old (assoc name store)))
5098 (if old (setcdr old value)
5099 (push (cons name value) store)))))
5100 (if constants (setcdr constants store)
5101 (push (cons 'constants store) alist))))
5102 ((equal key "FILETAGS")
5103 (when (org-string-nw-p value)
5104 (let ((old (assq 'filetags alist))
5105 (new (apply #'nconc
5106 (mapcar (lambda (x) (org-split-string x ":"))
5107 (split-string value)))))
5108 (if old (setcdr old (append new (cdr old)))
5109 (push (cons 'filetags new) alist)))))
5110 ((equal key "LINK")
5111 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5112 (let ((links (assq 'link alist))
5113 (pair (cons (match-string-no-properties 1 value)
5114 (match-string-no-properties 2 value))))
5115 (if links (push pair (cdr links))
5116 (push (list 'link pair) alist)))))
5117 ((equal key "OPTIONS")
5118 (when (and (org-string-nw-p value)
5119 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5120 (push (cons 'scripts (read (match-string 1 value))) alist)))
5121 ((equal key "PRIORITIES")
5122 (push (cons 'priorities
5123 (let ((prio (split-string value)))
5124 (if (< (length prio) 3) '(?A ?C ?B)
5125 (mapcar #'string-to-char prio))))
5126 alist))
5127 ((equal key "PROPERTY")
5128 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5129 (let* ((property (assq 'property alist))
5130 (value (org--update-property-plist
5131 (match-string-no-properties 1 value)
5132 (match-string-no-properties 2 value)
5133 (cdr property))))
5134 (if property (setcdr property value)
5135 (push (cons 'property value) alist)))))
5136 ((equal key "STARTUP")
5137 (let ((startup (assq 'startup alist)))
5138 (if startup
5139 (setcdr startup
5140 (append (cdr startup) (split-string value)))
5141 (push (cons 'startup (split-string value)) alist))))
5142 ((equal key "TAGS")
5143 (let ((tag-cell (assq 'tags alist)))
5144 (if tag-cell
5145 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5146 (push (cons 'tags value) alist))))
5147 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5148 (let ((todo (assq 'todo alist))
5149 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5150 (split-string value))))
5151 (if todo (push value (cdr todo))
5152 (push (list 'todo value) alist))))
5153 ((equal key "SETUPFILE")
5154 (unless buffer-read-only ; Do not check in Gnus messages.
5155 (let ((f (and (org-string-nw-p value)
5156 (expand-file-name
5157 (org-unbracket-string "\"" "\"" value)))))
5158 (when (and f (file-readable-p f) (not (member f files)))
5159 (with-temp-buffer
5160 (setq default-directory (file-name-directory f))
5161 (insert-file-contents f)
5162 (setq alist
5163 ;; Fake Org mode to benefit from cache
5164 ;; without recurring needlessly.
5165 (let ((major-mode 'org-mode))
5166 (org--setup-collect-keywords
5167 regexp (cons f files) alist)))))))))))))))
5168 alist)
5170 (defun org-tag-string-to-alist (s)
5171 "Return tag alist associated to string S.
5172 S is a value for TAGS keyword or produced with
5173 `org-tag-alist-to-string'. Return value is an alist suitable for
5174 `org-tag-alist' or `org-tag-persistent-alist'."
5175 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5176 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5177 "\\|{.+?}\\)" ; regular expression
5178 "\\(?:(\\(.\\))\\)?\\'"))
5179 alist group-flag)
5180 (dolist (tokens lines (cdr (nreverse alist)))
5181 (push '(:newline) alist)
5182 (while tokens
5183 (let ((token (pop tokens)))
5184 (pcase token
5185 ("{"
5186 (push '(:startgroup) alist)
5187 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5188 ("}"
5189 (push '(:endgroup) alist)
5190 (setq group-flag nil))
5191 ("["
5192 (push '(:startgrouptag) alist)
5193 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5194 ("]"
5195 (push '(:endgrouptag) alist)
5196 (setq group-flag nil))
5197 (":"
5198 (push '(:grouptags) alist))
5199 ((guard (string-match tag-re token))
5200 (let ((tag (match-string 1 token))
5201 (key (and (match-beginning 2)
5202 (string-to-char (match-string 2 token)))))
5203 ;; Push all tags in groups, no matter if they already
5204 ;; appear somewhere else in the list.
5205 (when (or group-flag (not (assoc tag alist)))
5206 (push (cons tag key) alist))))))))))
5208 (defun org-tag-alist-to-string (alist &optional skip-key)
5209 "Return tag string associated to ALIST.
5211 ALIST is an alist, as defined in `org-tag-alist' or
5212 `org-tag-persistent-alist', or produced with
5213 `org-tag-string-to-alist'.
5215 Return value is a string suitable as a value for \"TAGS\"
5216 keyword.
5218 When optional argument SKIP-KEY is non-nil, skip selection keys
5219 next to tags."
5220 (mapconcat (lambda (token)
5221 (pcase token
5222 (`(:startgroup) "{")
5223 (`(:endgroup) "}")
5224 (`(:startgrouptag) "[")
5225 (`(:endgrouptag) "]")
5226 (`(:grouptags) ":")
5227 (`(:newline) "\\n")
5228 ((and
5229 (guard (not skip-key))
5230 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5231 (format "%s(%c)" tag key))
5232 (`(,(and tag (pred stringp)) . ,_) tag)
5233 (_ (user-error "Invalid tag token: %S" token))))
5234 alist
5235 " "))
5237 (defun org-tag-alist-to-groups (alist)
5238 "Return group alist from tag ALIST.
5239 ALIST is an alist, as defined in `org-tag-alist' or
5240 `org-tag-persistent-alist', or produced with
5241 `org-tag-string-to-alist'. Return value is an alist following
5242 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5243 a string, summarizing TAGS, as a list of strings."
5244 (let (groups group-status current-group)
5245 (dolist (token alist (nreverse groups))
5246 (pcase token
5247 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5248 (`(,(or :endgroup :endgrouptag))
5249 (when (eq group-status 'append)
5250 (push (nreverse current-group) groups))
5251 (setq group-status nil))
5252 (`(:grouptags) (setq group-status 'append))
5253 ((and `(,tag . ,_) (guard group-status))
5254 (if (eq group-status 'append) (push tag current-group)
5255 (setq current-group (list tag))))
5256 (_ nil)))))
5258 (defvar org--file-cache (make-hash-table :test #'equal)
5259 "Hash table to store contents of files referenced via a URL.
5260 This is the cache of file URLs read using `org-file-contents'.")
5262 (defun org-reset-file-cache ()
5263 "Reset the cache of files downloaded by `org-file-contents'."
5264 (clrhash org--file-cache))
5266 (defun org-file-url-p (file)
5267 "Non-nil if FILE is a URL."
5268 (require 'ffap)
5269 (string-match-p ffap-url-regexp file))
5271 (defun org-file-contents (file &optional noerror nocache)
5272 "Return the contents of FILE, as a string.
5274 FILE can be a file name or URL.
5276 If FILE is a URL, download the contents. If the URL contents are
5277 already cached in the `org--file-cache' hash table, the download step
5278 is skipped.
5280 If NOERROR is non-nil, ignore the error when unable to read the FILE
5281 from file or URL.
5283 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5284 is available. This option applies only if FILE is a URL."
5285 (let* ((is-url (org-file-url-p file))
5286 (cache (and is-url
5287 (not nocache)
5288 (gethash file org--file-cache))))
5289 (cond
5290 (cache)
5291 (is-url
5292 (with-current-buffer (url-retrieve-synchronously file)
5293 (goto-char (point-min))
5294 ;; Move point to after the url-retrieve header.
5295 (search-forward "\n\n" nil :move)
5296 ;; Search for the success code only in the url-retrieve header.
5297 (if (save-excursion (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5298 ;; Update the cache `org--file-cache' and return contents.
5299 (puthash file
5300 (buffer-substring-no-properties (point) (point-max))
5301 org--file-cache)
5302 (funcall (if noerror #'message #'user-error)
5303 "Unable to fetch file from %S"
5304 file))))
5306 (with-temp-buffer
5307 (condition-case err
5308 (progn
5309 (insert-file-contents file)
5310 (buffer-string))
5311 (file-error
5312 (funcall (if noerror #'message #'user-error)
5313 (error-message-string err)))))))))
5315 (defun org-extract-log-state-settings (x)
5316 "Extract the log state setting from a TODO keyword string.
5317 This will extract info from a string like \"WAIT(w@/!)\"."
5318 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5319 (let ((kw (match-string 1 x))
5320 (log1 (and (match-end 3) (match-string 3 x)))
5321 (log2 (and (match-end 4) (match-string 4 x))))
5322 (and (or log1 log2)
5323 (list kw
5324 (and log1 (if (equal log1 "!") 'time 'note))
5325 (and log2 (if (equal log2 "!") 'time 'note)))))))
5327 (defun org-remove-keyword-keys (list)
5328 "Remove a pair of parenthesis at the end of each string in LIST."
5329 (mapcar (lambda (x)
5330 (if (string-match "(.*)$" x)
5331 (substring x 0 (match-beginning 0))
5333 list))
5335 (defun org-assign-fast-keys (alist)
5336 "Assign fast keys to a keyword-key alist.
5337 Respect keys that are already there."
5338 (let (new e (alt ?0))
5339 (while (setq e (pop alist))
5340 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5341 (cdr e)) ;; Key already assigned.
5342 (push e new)
5343 (let ((clist (string-to-list (downcase (car e))))
5344 (used (append new alist)))
5345 (when (= (car clist) ?@)
5346 (pop clist))
5347 (while (and clist (rassoc (car clist) used))
5348 (pop clist))
5349 (unless clist
5350 (while (rassoc alt used)
5351 (cl-incf alt)))
5352 (push (cons (car e) (or (car clist) alt)) new))))
5353 (nreverse new)))
5355 ;;; Some variables used in various places
5357 (defvar org-window-configuration nil
5358 "Used in various places to store a window configuration.")
5359 (defvar org-selected-window nil
5360 "Used in various places to store a window configuration.")
5361 (defvar org-finish-function nil
5362 "Function to be called when `C-c C-c' is used.
5363 This is for getting out of special buffers like capture.")
5364 (defvar org-last-state)
5366 ;; Defined somewhere in this file, but used before definition.
5367 (defvar org-entities) ;; defined in org-entities.el
5368 (defvar org-struct-menu)
5369 (defvar org-org-menu)
5370 (defvar org-tbl-menu)
5372 ;;;; Define the Org mode
5374 ;; We use a before-change function to check if a table might need
5375 ;; an update.
5376 (defvar org-table-may-need-update t
5377 "Indicates that a table might need an update.
5378 This variable is set by `org-before-change-function'.
5379 `org-table-align' sets it back to nil.")
5380 (defun org-before-change-function (_beg _end)
5381 "Every change indicates that a table might need an update."
5382 (setq org-table-may-need-update t))
5383 (defvar org-mode-map)
5384 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5385 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5386 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5387 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5388 (defvar org-table-buffer-is-an nil)
5390 (defvar bidi-paragraph-direction)
5391 (defvar buffer-face-mode-face)
5393 (require 'outline)
5395 ;; Other stuff we need.
5396 (require 'time-date)
5397 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5398 (require 'easymenu)
5399 (autoload 'easy-menu-add "easymenu")
5400 (require 'overlay)
5402 ;; (require 'org-macs) moved higher up in the file before it is first used
5403 (require 'org-entities)
5404 ;; (require 'org-compat) moved higher up in the file before it is first used
5405 (require 'org-faces)
5406 (require 'org-list)
5407 (require 'org-pcomplete)
5408 (require 'org-src)
5409 (require 'org-footnote)
5410 (require 'org-macro)
5412 ;; babel
5413 (require 'ob)
5415 ;;;###autoload
5416 (define-derived-mode org-mode outline-mode "Org"
5417 "Outline-based notes management and organizer, alias
5418 \"Carsten's outline-mode for keeping track of everything.\"
5420 Org mode develops organizational tasks around a NOTES file which
5421 contains information about projects as plain text. Org mode is
5422 implemented on top of Outline mode, which is ideal to keep the content
5423 of large files well structured. It supports ToDo items, deadlines and
5424 time stamps, which magically appear in the diary listing of the Emacs
5425 calendar. Tables are easily created with a built-in table editor.
5426 Plain text URL-like links connect to websites, emails (VM), Usenet
5427 messages (Gnus), BBDB entries, and any files related to the project.
5428 For printing and sharing of notes, an Org file (or a part of it)
5429 can be exported as a structured ASCII or HTML file.
5431 The following commands are available:
5433 \\{org-mode-map}"
5435 ;; Get rid of Outline menus, they are not needed
5436 ;; Need to do this here because define-derived-mode sets up
5437 ;; the keymap so late. Still, it is a waste to call this each time
5438 ;; we switch another buffer into Org mode.
5439 (define-key org-mode-map [menu-bar headings] 'undefined)
5440 (define-key org-mode-map [menu-bar hide] 'undefined)
5441 (define-key org-mode-map [menu-bar show] 'undefined)
5443 (org-load-modules-maybe)
5444 (org-install-agenda-files-menu)
5445 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5446 (add-to-invisibility-spec '(org-hide-block . t))
5447 (setq-local outline-regexp org-outline-regexp)
5448 (setq-local outline-level 'org-outline-level)
5449 (setq bidi-paragraph-direction 'left-to-right)
5450 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5451 (unless org-display-table
5452 (setq org-display-table (make-display-table)))
5453 (set-display-table-slot
5454 org-display-table 4
5455 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5456 org-ellipsis)))
5457 (setq buffer-display-table org-display-table))
5458 (org-set-regexps-and-options)
5459 (org-set-font-lock-defaults)
5460 (when (and org-tag-faces (not org-tags-special-faces-re))
5461 ;; tag faces set outside customize.... force initialization.
5462 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5463 ;; Calc embedded
5464 (setq-local calc-embedded-open-mode "# ")
5465 ;; Modify a few syntax entries
5466 (modify-syntax-entry ?@ "w")
5467 (modify-syntax-entry ?\" "\"")
5468 (modify-syntax-entry ?\\ "_")
5469 (modify-syntax-entry ?~ "_")
5470 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5471 ;; Activate before-change-function
5472 (setq-local org-table-may-need-update t)
5473 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5474 ;; Check for running clock before killing a buffer
5475 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5476 ;; Initialize macros templates.
5477 (org-macro-initialize-templates)
5478 ;; Initialize radio targets.
5479 (org-update-radio-target-regexp)
5480 ;; Indentation.
5481 (setq-local indent-line-function 'org-indent-line)
5482 (setq-local indent-region-function 'org-indent-region)
5483 ;; Filling and auto-filling.
5484 (org-setup-filling)
5485 ;; Comments.
5486 (org-setup-comments-handling)
5487 ;; Initialize cache.
5488 (org-element-cache-reset)
5489 ;; Beginning/end of defun
5490 (setq-local beginning-of-defun-function 'org-backward-element)
5491 (setq-local end-of-defun-function
5492 (lambda ()
5493 (if (not (org-at-heading-p))
5494 (org-forward-element)
5495 (org-forward-element)
5496 (forward-char -1))))
5497 ;; Next error for sparse trees
5498 (setq-local next-error-function 'org-occur-next-match)
5499 ;; Make sure dependence stuff works reliably, even for users who set it
5500 ;; too late :-(
5501 (if org-enforce-todo-dependencies
5502 (add-hook 'org-blocker-hook
5503 'org-block-todo-from-children-or-siblings-or-parent)
5504 (remove-hook 'org-blocker-hook
5505 'org-block-todo-from-children-or-siblings-or-parent))
5506 (if org-enforce-todo-checkbox-dependencies
5507 (add-hook 'org-blocker-hook
5508 'org-block-todo-from-checkboxes)
5509 (remove-hook 'org-blocker-hook
5510 'org-block-todo-from-checkboxes))
5512 ;; Align options lines
5513 (setq-local
5514 align-mode-rules-list
5515 '((org-in-buffer-settings
5516 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5517 (modes . '(org-mode)))))
5519 ;; Imenu
5520 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5522 ;; Make isearch reveal context
5523 (setq-local outline-isearch-open-invisible-function
5524 (lambda (&rest _) (org-show-context 'isearch)))
5526 ;; Setup the pcomplete hooks
5527 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5528 (setq-local pcomplete-command-name-function 'org-command-at-point)
5529 (setq-local pcomplete-default-completion-function 'ignore)
5530 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5531 (setq-local pcomplete-termination-string "")
5532 (setq-local buffer-face-mode-face 'org-default)
5534 ;; If empty file that did not turn on Org mode automatically, make
5535 ;; it to.
5536 (when (and org-insert-mode-line-in-empty-file
5537 (called-interactively-p 'any)
5538 (= (point-min) (point-max)))
5539 (insert "# -*- mode: org -*-\n\n"))
5540 (unless org-inhibit-startup
5541 (org-unmodified
5542 (when org-startup-with-beamer-mode (org-beamer-mode))
5543 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5544 (org-table-map-tables
5545 (cond ((and org-startup-align-all-tables
5546 org-startup-shrink-all-tables)
5547 (lambda () (org-table-align) (org-table-shrink)))
5548 (org-startup-align-all-tables #'org-table-align)
5549 (t #'org-table-shrink))
5551 (when org-startup-with-inline-images (org-display-inline-images))
5552 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5553 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5554 (when org-startup-truncated (setq truncate-lines t))
5555 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5556 (org-refresh-effort-properties)))
5557 ;; Try to set `org-hide' face correctly.
5558 (let ((foreground (org-find-invisible-foreground)))
5559 (when foreground
5560 (set-face-foreground 'org-hide foreground))))
5562 ;; Update `customize-package-emacs-version-alist'
5563 (add-to-list 'customize-package-emacs-version-alist
5564 '(Org ("8.0" . "24.4")
5565 ("8.1" . "24.4")
5566 ("8.2" . "24.4")
5567 ("8.2.7" . "24.4")
5568 ("8.3" . "26.1")
5569 ("9.0" . "26.1")
5570 ("9.1" . "26.1")))
5572 (defvar org-mode-transpose-word-syntax-table
5573 (let ((st (make-syntax-table text-mode-syntax-table)))
5574 (dolist (c org-emphasis-alist st)
5575 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5577 (when (fboundp 'abbrev-table-put)
5578 (abbrev-table-put org-mode-abbrev-table
5579 :parents (list text-mode-abbrev-table)))
5581 (defun org-find-invisible-foreground ()
5582 (let ((candidates (remove
5583 "unspecified-bg"
5584 (nconc
5585 (list (face-background 'default)
5586 (face-background 'org-default))
5587 (mapcar
5588 (lambda (alist)
5589 (when (boundp alist)
5590 (cdr (assq 'background-color (symbol-value alist)))))
5591 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5592 (list (face-foreground 'org-hide))))))
5593 (car (remove nil candidates))))
5595 (defun org-current-time (&optional rounding-minutes past)
5596 "Current time, possibly rounded to ROUNDING-MINUTES.
5597 When ROUNDING-MINUTES is not an integer, fall back on the car of
5598 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5599 the rounding returns a past time."
5600 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5601 (car org-time-stamp-rounding-minutes)))
5602 (time (decode-time)) res)
5603 (if (< r 1)
5604 (current-time)
5605 (setq res
5606 (apply 'encode-time
5607 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5608 (nthcdr 2 time))))
5609 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5610 (seconds-to-time (- (float-time res) (* r 60)))
5611 res))))
5613 (defun org-today ()
5614 "Return today date, considering `org-extend-today-until'."
5615 (time-to-days
5616 (time-subtract (current-time)
5617 (list 0 (* 3600 org-extend-today-until) 0))))
5619 ;;;; Font-Lock stuff, including the activators
5621 (defvar org-mouse-map (make-sparse-keymap))
5622 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5623 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5624 (when org-mouse-1-follows-link
5625 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5626 (when org-tab-follows-link
5627 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5628 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5630 (require 'font-lock)
5632 (defconst org-non-link-chars "]\t\n\r<>")
5633 (defvar org-link-types-re nil
5634 "Matches a link that has a url-like prefix like \"http:\"")
5635 (defvar org-link-re-with-space nil
5636 "Matches a link with spaces, optional angular brackets around it.")
5637 (defvar org-link-re-with-space2 nil
5638 "Matches a link with spaces, optional angular brackets around it.")
5639 (defvar org-link-re-with-space3 nil
5640 "Matches a link with spaces, only for internal part in bracket links.")
5641 (defvar org-angle-link-re nil
5642 "Matches link with angular brackets, spaces are allowed.")
5643 (defvar org-plain-link-re nil
5644 "Matches plain link, without spaces.")
5645 (defvar org-bracket-link-regexp nil
5646 "Matches a link in double brackets.")
5647 (defvar org-bracket-link-analytic-regexp nil
5648 "Regular expression used to analyze links.
5649 Here is what the match groups contain after a match:
5650 1: http:
5651 2: http
5652 3: path
5653 4: [desc]
5654 5: desc")
5655 (defvar org-bracket-link-analytic-regexp++ nil
5656 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5657 (defvar org-any-link-re nil
5658 "Regular expression matching any link.")
5660 (defconst org-match-sexp-depth 3
5661 "Number of stacked braces for sub/superscript matching.")
5663 (defun org-create-multibrace-regexp (left right n)
5664 "Create a regular expression which will match a balanced sexp.
5665 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5666 as single character strings.
5667 The regexp returned will match the entire expression including the
5668 delimiters. It will also define a single group which contains the
5669 match except for the outermost delimiters. The maximum depth of
5670 stacked delimiters is N. Escaping delimiters is not possible."
5671 (let* ((nothing (concat "[^" left right "]*?"))
5672 (or "\\|")
5673 (re nothing)
5674 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5675 (while (> n 1)
5676 (setq n (1- n)
5677 re (concat re or next)
5678 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5679 (concat left "\\(" re "\\)" right)))
5681 (defconst org-match-substring-regexp
5682 (concat
5683 "\\(\\S-\\)\\([_^]\\)\\("
5684 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5685 "\\|"
5686 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5687 "\\|"
5688 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5689 "The regular expression matching a sub- or superscript.")
5691 (defconst org-match-substring-with-braces-regexp
5692 (concat
5693 "\\(\\S-\\)\\([_^]\\)"
5694 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5695 "The regular expression matching a sub- or superscript, forcing braces.")
5697 (defun org-make-link-regexps ()
5698 "Update the link regular expressions.
5699 This should be called after the variable `org-link-parameters' has changed."
5700 (let ((types-re (regexp-opt (org-link-types) t)))
5701 (setq org-link-types-re
5702 (concat "\\`" types-re ":")
5703 org-link-re-with-space
5704 (concat "<?" types-re ":"
5705 "\\([^" org-non-link-chars " ]"
5706 "[^" org-non-link-chars "]*"
5707 "[^" org-non-link-chars " ]\\)>?")
5708 org-link-re-with-space2
5709 (concat "<?" types-re ":"
5710 "\\([^" org-non-link-chars " ]"
5711 "[^\t\n\r]*"
5712 "[^" org-non-link-chars " ]\\)>?")
5713 org-link-re-with-space3
5714 (concat "<?" types-re ":"
5715 "\\([^" org-non-link-chars " ]"
5716 "[^\t\n\r]*\\)")
5717 org-angle-link-re
5718 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5719 types-re)
5720 org-plain-link-re
5721 (concat
5722 "\\<" types-re ":"
5723 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5724 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5725 org-bracket-link-regexp
5726 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5727 org-bracket-link-analytic-regexp
5728 (concat
5729 "\\[\\["
5730 "\\(" types-re ":\\)?"
5731 "\\([^]]+\\)"
5732 "\\]"
5733 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5734 "\\]")
5735 org-bracket-link-analytic-regexp++
5736 (concat
5737 "\\[\\["
5738 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5739 "\\([^]]+\\)"
5740 "\\]"
5741 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5742 "\\]")
5743 org-any-link-re
5744 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5745 org-angle-link-re "\\)\\|\\("
5746 org-plain-link-re "\\)"))))
5748 (org-make-link-regexps)
5750 (defvar org-emph-face nil)
5752 (defun org-do-emphasis-faces (limit)
5753 "Run through the buffer and emphasize strings."
5754 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5755 (car org-emphasis-regexp-components))))
5756 (catch :exit
5757 (while (re-search-forward quick-re limit t)
5758 (let* ((marker (match-string 2))
5759 (verbatim? (member marker '("~" "="))))
5760 (when (save-excursion
5761 (goto-char (match-beginning 0))
5762 ;; Do not match headline stars. Do not consider
5763 ;; stars of a headline as closing marker for bold
5764 ;; markup either. Do not match table hlines.
5765 (and
5766 (not (looking-at-p org-outline-regexp-bol))
5767 (not (and (equal marker "+")
5768 (org-match-line
5769 "^[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5770 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5771 (not (string-match-p
5772 (concat org-outline-regexp-bol "\\'")
5773 (match-string 0)))))
5774 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5775 (font-lock-prepend-text-property
5776 (match-beginning 2) (match-end 2) 'face face)
5777 (when verbatim?
5778 (org-remove-flyspell-overlays-in
5779 (match-beginning 0) (match-end 0)))
5780 (add-text-properties (match-beginning 2) (match-end 2)
5781 '(font-lock-multiline t org-emphasis t))
5782 (when org-hide-emphasis-markers
5783 (add-text-properties (match-end 4) (match-beginning 5)
5784 '(invisible org-link))
5785 (add-text-properties (match-beginning 3) (match-end 3)
5786 '(invisible org-link)))
5787 (throw :exit t))))))))
5789 (defun org-emphasize (&optional char)
5790 "Insert or change an emphasis, i.e. a font like bold or italic.
5791 If there is an active region, change that region to a new emphasis.
5792 If there is no region, just insert the marker characters and position
5793 the cursor between them.
5794 CHAR should be the marker character. If it is a space, it means to
5795 remove the emphasis of the selected region.
5796 If CHAR is not given (for example in an interactive call) it will be
5797 prompted for."
5798 (interactive)
5799 (let ((erc org-emphasis-regexp-components)
5800 (string "") beg end move s)
5801 (if (org-region-active-p)
5802 (setq beg (region-beginning)
5803 end (region-end)
5804 string (buffer-substring beg end))
5805 (setq move t))
5807 (unless char
5808 (message "Emphasis marker or tag: [%s]"
5809 (mapconcat #'car org-emphasis-alist ""))
5810 (setq char (read-char-exclusive)))
5811 (if (equal char ?\s)
5812 (setq s ""
5813 move nil)
5814 (unless (assoc (char-to-string char) org-emphasis-alist)
5815 (user-error "No such emphasis marker: \"%c\"" char))
5816 (setq s (char-to-string char)))
5817 (while (and (> (length string) 1)
5818 (equal (substring string 0 1) (substring string -1))
5819 (assoc (substring string 0 1) org-emphasis-alist))
5820 (setq string (substring string 1 -1)))
5821 (setq string (concat s string s))
5822 (when beg (delete-region beg end))
5823 (unless (or (bolp)
5824 (string-match (concat "[" (nth 0 erc) "\n]")
5825 (char-to-string (char-before (point)))))
5826 (insert " "))
5827 (unless (or (eobp)
5828 (string-match (concat "[" (nth 1 erc) "\n]")
5829 (char-to-string (char-after (point)))))
5830 (insert " ") (backward-char 1))
5831 (insert string)
5832 (and move (backward-char 1))))
5834 (defconst org-nonsticky-props
5835 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5837 (defsubst org-rear-nonsticky-at (pos)
5838 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5840 (defun org-activate-links (limit)
5841 "Add link properties to links.
5842 This includes angle, plain, and bracket links."
5843 (catch :exit
5844 (while (re-search-forward org-any-link-re limit t)
5845 (let* ((start (match-beginning 0))
5846 (end (match-end 0))
5847 (style (cond ((eq ?< (char-after start)) 'angle)
5848 ((eq ?\[ (char-after (1+ start))) 'bracket)
5849 (t 'plain))))
5850 (when (and (memq style org-highlight-links)
5851 ;; Do not confuse plain links with tags.
5852 (not (and (eq style 'plain)
5853 (let ((face (get-text-property
5854 (max (1- start) (point-min)) 'face)))
5855 (if (consp face) (memq 'org-tag face)
5856 (eq 'org-tag face))))))
5857 (let* ((link-object (save-excursion
5858 (goto-char start)
5859 (save-match-data (org-element-link-parser))))
5860 (link (org-element-property :raw-link link-object))
5861 (type (org-element-property :type link-object))
5862 (path (org-element-property :path link-object))
5863 (properties ;for link's visible part
5864 (list
5865 'face (pcase (org-link-get-parameter type :face)
5866 ((and (pred functionp) face) (funcall face path))
5867 ((and (pred facep) face) face)
5868 ((and (pred consp) face) face) ;anonymous
5869 (_ 'org-link))
5870 'mouse-face (or (org-link-get-parameter type :mouse-face)
5871 'highlight)
5872 'keymap (or (org-link-get-parameter type :keymap)
5873 org-mouse-map)
5874 'help-echo (pcase (org-link-get-parameter type :help-echo)
5875 ((and (pred stringp) echo) echo)
5876 ((and (pred functionp) echo) echo)
5877 (_ (concat "LINK: " link)))
5878 'htmlize-link (pcase (org-link-get-parameter type
5879 :htmlize-link)
5880 ((and (pred functionp) f) (funcall f))
5881 (_ `(:uri ,link)))
5882 'font-lock-multiline t)))
5883 (org-remove-flyspell-overlays-in start end)
5884 (org-rear-nonsticky-at end)
5885 (if (not (eq 'bracket style))
5886 (add-text-properties start end properties)
5887 ;; Handle invisible parts in bracket links.
5888 (remove-text-properties start end '(invisible nil))
5889 (let ((hidden
5890 (append `(invisible
5891 ,(or (org-link-get-parameter type :display)
5892 'org-link))
5893 properties))
5894 (visible-start (or (match-beginning 4) (match-beginning 2)))
5895 (visible-end (or (match-end 4) (match-end 2))))
5896 (add-text-properties start visible-start hidden)
5897 (add-text-properties visible-start visible-end properties)
5898 (add-text-properties visible-end end hidden)
5899 (org-rear-nonsticky-at visible-start)
5900 (org-rear-nonsticky-at visible-end)))
5901 (let ((f (org-link-get-parameter type :activate-func)))
5902 (when (functionp f)
5903 (funcall f start end path (eq style 'bracket))))
5904 (throw :exit t))))) ;signal success
5905 nil))
5907 (defun org-activate-code (limit)
5908 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5909 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5910 (remove-text-properties (match-beginning 0) (match-end 0)
5911 '(display t invisible t intangible t))
5914 (defcustom org-src-fontify-natively t
5915 "When non-nil, fontify code in code blocks.
5916 See also the `org-block' face."
5917 :type 'boolean
5918 :version "26.1"
5919 :package-version '(Org . "8.3")
5920 :group 'org-appearance
5921 :group 'org-babel)
5923 (defcustom org-allow-promoting-top-level-subtree nil
5924 "When non-nil, allow promoting a top level subtree.
5925 The leading star of the top level headline will be replaced
5926 by a #."
5927 :type 'boolean
5928 :version "24.1"
5929 :group 'org-appearance)
5931 (defun org-fontify-meta-lines-and-blocks (limit)
5932 (condition-case nil
5933 (org-fontify-meta-lines-and-blocks-1 limit)
5934 (error (message "org-mode fontification error in %S at %d"
5935 (current-buffer)
5936 (line-number-at-pos)))))
5938 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5939 "Fontify #+ lines and blocks."
5940 (let ((case-fold-search t))
5941 (when (re-search-forward
5942 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5943 limit t)
5944 (let ((beg (match-beginning 0))
5945 (block-start (match-end 0))
5946 (block-end nil)
5947 (lang (match-string 7))
5948 (beg1 (line-beginning-position 2))
5949 (dc1 (downcase (match-string 2)))
5950 (dc3 (downcase (match-string 3)))
5951 end end1 quoting block-type)
5952 (cond
5953 ((and (match-end 4) (equal dc3 "+begin"))
5954 ;; Truly a block
5955 (setq block-type (downcase (match-string 5))
5956 quoting (member block-type org-protecting-blocks))
5957 (when (re-search-forward
5958 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5959 nil t) ;; on purpose, we look further than LIMIT
5960 (setq end (min (point-max) (match-end 0))
5961 end1 (min (point-max) (1- (match-beginning 0))))
5962 (setq block-end (match-beginning 0))
5963 (when quoting
5964 (org-remove-flyspell-overlays-in beg1 end1)
5965 (remove-text-properties beg end
5966 '(display t invisible t intangible t)))
5967 (add-text-properties
5968 beg end '(font-lock-fontified t font-lock-multiline t))
5969 (add-text-properties beg beg1 '(face org-meta-line))
5970 (org-remove-flyspell-overlays-in beg beg1)
5971 (add-text-properties ; For end_src
5972 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5973 (org-remove-flyspell-overlays-in end1 end)
5974 (cond
5975 ((and lang (not (string= lang "")) org-src-fontify-natively)
5976 (org-src-font-lock-fontify-block lang block-start block-end)
5977 (add-text-properties beg1 block-end '(src-block t)))
5978 (quoting
5979 (add-text-properties beg1 (min (point-max) (1+ end1))
5980 (list 'face
5981 (list :inherit
5982 (let ((face-name
5983 (intern (format "org-block-%s" lang))))
5984 (append (and (facep face-name) (list face-name))
5985 '(org-block))))))) ; end of source block
5986 ((not org-fontify-quote-and-verse-blocks))
5987 ((string= block-type "quote")
5988 (add-face-text-property
5989 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5990 ((string= block-type "verse")
5991 (add-face-text-property
5992 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5993 (add-text-properties beg beg1 '(face org-block-begin-line))
5994 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5995 '(face org-block-end-line))
5997 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5998 (org-remove-flyspell-overlays-in
5999 (match-beginning 0)
6000 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6001 (add-text-properties
6002 beg (match-end 3)
6003 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6004 '(font-lock-fontified t invisible t)
6005 '(font-lock-fontified t face org-document-info-keyword)))
6006 (add-text-properties
6007 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6008 (if (string-equal dc1 "+title:")
6009 '(font-lock-fontified t face org-document-title)
6010 '(font-lock-fontified t face org-document-info))))
6011 ((string-prefix-p "+caption" dc1)
6012 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6013 (remove-text-properties (match-beginning 0) (match-end 0)
6014 '(display t invisible t intangible t))
6015 ;; Handle short captions.
6016 (save-excursion
6017 (beginning-of-line)
6018 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6019 (add-text-properties (line-beginning-position) (match-end 1)
6020 '(font-lock-fontified t face org-meta-line))
6021 (add-text-properties (match-end 0) (line-end-position)
6022 '(font-lock-fontified t face org-block))
6024 ((member dc3 '(" " ""))
6025 (org-remove-flyspell-overlays-in beg (match-end 0))
6026 (add-text-properties
6027 beg (match-end 0)
6028 '(font-lock-fontified t face font-lock-comment-face)))
6029 (t ;; just any other in-buffer setting, but not indented
6030 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6031 (remove-text-properties (match-beginning 0) (match-end 0)
6032 '(display t invisible t intangible t))
6033 (add-text-properties beg (match-end 0)
6034 '(font-lock-fontified t face org-meta-line))
6035 t))))))
6037 (defun org-fontify-drawers (limit)
6038 "Fontify drawers."
6039 (when (re-search-forward org-drawer-regexp limit t)
6040 (add-text-properties
6041 (match-beginning 0) (match-end 0)
6042 '(font-lock-fontified t face org-special-keyword))
6043 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6046 (defun org-fontify-macros (limit)
6047 "Fontify macros."
6048 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6049 (add-text-properties
6050 (match-beginning 0) (match-end 0)
6051 '(font-lock-fontified t face org-macro))
6052 (when org-hide-macro-markers
6053 (add-text-properties (match-end 2) (match-beginning 2)
6054 '(invisible t))
6055 (add-text-properties (match-beginning 1) (match-end 1)
6056 '(invisible t)))
6057 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6060 (defun org-activate-footnote-links (limit)
6061 "Add text properties for footnotes."
6062 (let ((fn (org-footnote-next-reference-or-definition limit)))
6063 (when fn
6064 (let* ((beg (nth 1 fn))
6065 (end (nth 2 fn))
6066 (label (car fn))
6067 (referencep (/= (line-beginning-position) beg)))
6068 (when (and referencep (nth 3 fn))
6069 (save-excursion
6070 (goto-char beg)
6071 (search-forward (or label "fn:"))
6072 (org-remove-flyspell-overlays-in beg (match-end 0))))
6073 (add-text-properties beg end
6074 (list 'mouse-face 'highlight
6075 'keymap org-mouse-map
6076 'help-echo
6077 (if referencep "Footnote reference"
6078 "Footnote definition")
6079 'font-lock-fontified t
6080 'font-lock-multiline t
6081 'face 'org-footnote))))))
6083 (defun org-activate-dates (limit)
6084 "Add text properties for dates."
6085 (when (and (re-search-forward org-tsr-regexp-both limit t)
6086 (not (equal (char-before (match-beginning 0)) 91)))
6087 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6088 (add-text-properties (match-beginning 0) (match-end 0)
6089 (list 'mouse-face 'highlight
6090 'keymap org-mouse-map))
6091 (org-rear-nonsticky-at (match-end 0))
6092 (when org-display-custom-times
6093 ;; If it's a date range, activate custom time for second date.
6094 (when (match-end 3)
6095 (org-display-custom-time (match-beginning 3) (match-end 3)))
6096 (org-display-custom-time (match-beginning 1) (match-end 1)))
6099 (defvar-local org-target-link-regexp nil
6100 "Regular expression matching radio targets in plain text.")
6102 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6103 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6104 border border border))
6105 "Regular expression matching a link target.")
6107 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6108 "Regular expression matching a radio target.")
6110 (defconst org-any-target-regexp
6111 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6112 "Regular expression matching any target.")
6114 (defun org-activate-target-links (limit)
6115 "Add text properties for target matches."
6116 (when org-target-link-regexp
6117 (let ((case-fold-search t))
6118 (when (re-search-forward org-target-link-regexp limit t)
6119 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6120 (add-text-properties (match-beginning 1) (match-end 1)
6121 (list 'mouse-face 'highlight
6122 'keymap org-mouse-map
6123 'help-echo "Radio target link"
6124 'org-linked-text t))
6125 (org-rear-nonsticky-at (match-end 1))
6126 t))))
6128 (defun org-update-radio-target-regexp ()
6129 "Find all radio targets in this file and update the regular expression.
6130 Also refresh fontification if needed."
6131 (interactive)
6132 (let ((old-regexp org-target-link-regexp)
6133 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6134 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6135 (targets
6136 (org-with-wide-buffer
6137 (goto-char (point-min))
6138 (let (rtn)
6139 (while (re-search-forward org-radio-target-regexp nil t)
6140 ;; Make sure point is really within the object.
6141 (backward-char)
6142 (let ((obj (org-element-context)))
6143 (when (eq (org-element-type obj) 'radio-target)
6144 (cl-pushnew (org-element-property :value obj) rtn
6145 :test #'equal))))
6146 rtn))))
6147 (setq org-target-link-regexp
6148 (and targets
6149 (concat before-re
6150 (mapconcat
6151 (lambda (x)
6152 (replace-regexp-in-string
6153 " +" "\\s-+" (regexp-quote x) t t))
6154 targets
6155 "\\|")
6156 after-re)))
6157 (unless (equal old-regexp org-target-link-regexp)
6158 ;; Clean-up cache.
6159 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6160 ((not org-target-link-regexp) old-regexp)
6162 (concat before-re
6163 (mapconcat
6164 (lambda (re)
6165 (substring re (length before-re)
6166 (- (length after-re))))
6167 (list old-regexp org-target-link-regexp)
6168 "\\|")
6169 after-re)))))
6170 (org-with-wide-buffer
6171 (goto-char (point-min))
6172 (while (re-search-forward regexp nil t)
6173 (org-element-cache-refresh (match-beginning 1)))))
6174 ;; Re fontify buffer.
6175 (when (memq 'radio org-highlight-links)
6176 (org-restart-font-lock)))))
6178 (defvar org-latex-and-related-regexp nil
6179 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6181 (defun org-compute-latex-and-related-regexp ()
6182 "Compute regular expression for LaTeX, entities and sub/superscript.
6183 Result depends on variable `org-highlight-latex-and-related'."
6184 (setq-local
6185 org-latex-and-related-regexp
6186 (let* ((re-sub
6187 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6188 ((eq org-use-sub-superscripts '{})
6189 (list org-match-substring-with-braces-regexp))
6190 (org-use-sub-superscripts (list org-match-substring-regexp))))
6191 (re-latex
6192 (when (memq 'latex org-highlight-latex-and-related)
6193 (let ((matchers (plist-get org-format-latex-options :matchers)))
6194 (delq nil
6195 (mapcar (lambda (x)
6196 (and (member (car x) matchers) (nth 1 x)))
6197 org-latex-regexps)))))
6198 (re-entities
6199 (when (memq 'entities org-highlight-latex-and-related)
6200 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6201 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6203 (defun org-do-latex-and-related (limit)
6204 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6205 LIMIT bounds the search for syntax to highlight. Stop at first
6206 highlighted object, if any. Return t if some highlighting was
6207 done, nil otherwise."
6208 (when (org-string-nw-p org-latex-and-related-regexp)
6209 (catch 'found
6210 (while (re-search-forward org-latex-and-related-regexp limit t)
6211 (unless
6212 (cl-some
6213 (lambda (f)
6214 (memq f '(org-code org-verbatim underline org-special-keyword)))
6215 (save-excursion
6216 (goto-char (1+ (match-beginning 0)))
6217 (face-at-point nil t)))
6218 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6219 '(?_ ?^))
6221 0)))
6222 (font-lock-prepend-text-property
6223 (+ offset (match-beginning 0)) (match-end 0)
6224 'face 'org-latex-and-related)
6225 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6226 '(font-lock-multiline t)))
6227 (throw 'found t)))
6228 nil)))
6230 (defun org-restart-font-lock ()
6231 "Restart `font-lock-mode', to force refontification."
6232 (when (and (boundp 'font-lock-mode) font-lock-mode)
6233 (font-lock-mode -1)
6234 (font-lock-mode 1)))
6236 (defun org-activate-tags (limit)
6237 (when (re-search-forward
6238 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6239 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6240 (add-text-properties (match-beginning 1) (match-end 1)
6241 (list 'mouse-face 'highlight
6242 'keymap org-mouse-map))
6243 (org-rear-nonsticky-at (match-end 1))
6246 (defun org-outline-level ()
6247 "Compute the outline level of the heading at point.
6249 If this is called at a normal headline, the level is the number
6250 of stars. Use `org-reduced-level' to remove the effect of
6251 `org-odd-levels'. Unlike to `org-current-level', this function
6252 takes into consideration inlinetasks."
6253 (org-with-wide-buffer
6254 (end-of-line)
6255 (if (re-search-backward org-outline-regexp-bol nil t)
6256 (1- (- (match-end 0) (match-beginning 0)))
6257 0)))
6259 (defvar org-font-lock-keywords nil)
6261 (defsubst org-re-property (property &optional literal allow-null value)
6262 "Return a regexp matching a PROPERTY line.
6264 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6265 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6266 non-nil, match properties even without a value.
6268 Match group 3 is set to the value when it exists. If there is no
6269 value and ALLOW-NULL is non-nil, it is set to the empty string.
6271 With optional argument VALUE, match only property lines with
6272 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6273 unless LITERAL is non-nil."
6274 (concat
6275 "^\\(?4:[ \t]*\\)"
6276 (format "\\(?1::\\(?2:%s\\):\\)"
6277 (if literal property (regexp-quote property)))
6278 (cond (value
6279 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6280 (if literal value (regexp-quote value))))
6281 (allow-null
6282 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6284 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6286 (defconst org-property-re
6287 (org-re-property "\\S-+" 'literal t)
6288 "Regular expression matching a property line.
6289 There are four matching groups:
6290 1: :PROPKEY: including the leading and trailing colon,
6291 2: PROPKEY without the leading and trailing colon,
6292 3: PROPVAL without leading or trailing spaces,
6293 4: the indentation of the current line,
6294 5: trailing whitespace.")
6296 (defvar org-font-lock-hook nil
6297 "Functions to be called for special font lock stuff.")
6299 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6301 (defvar org-font-lock-set-keywords-hook nil
6302 "Functions that can manipulate `org-font-lock-extra-keywords'.
6303 This is called after `org-font-lock-extra-keywords' is defined, but before
6304 it is installed to be used by font lock. This can be useful if something
6305 needs to be inserted at a specific position in the font-lock sequence.")
6307 (defun org-font-lock-hook (limit)
6308 "Run `org-font-lock-hook' within LIMIT."
6309 (run-hook-with-args 'org-font-lock-hook limit))
6311 (defun org-set-font-lock-defaults ()
6312 "Set font lock defaults for the current buffer."
6313 (let* ((em org-fontify-emphasized-text)
6314 (lk org-highlight-links)
6315 (org-font-lock-extra-keywords
6316 (list
6317 ;; Call the hook
6318 '(org-font-lock-hook)
6319 ;; Headlines
6320 `(,(if org-fontify-whole-heading-line
6321 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6322 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6323 (1 (org-get-level-face 1))
6324 (2 (org-get-level-face 2))
6325 (3 (org-get-level-face 3)))
6326 ;; Table lines
6327 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6328 (1 'org-table t))
6329 ;; Table internals
6330 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6331 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6332 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6333 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6334 ;; Drawers
6335 '(org-fontify-drawers)
6336 ;; Properties
6337 (list org-property-re
6338 '(1 'org-special-keyword t)
6339 '(3 'org-property-value t))
6340 ;; Link related fontification.
6341 '(org-activate-links)
6342 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6343 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6344 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6345 (when (memq 'footnote lk) '(org-activate-footnote-links))
6346 ;; Targets.
6347 (list org-any-target-regexp '(0 'org-target t))
6348 ;; Diary sexps.
6349 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6350 ;; Macro
6351 '(org-fontify-macros)
6352 ;; TODO keyword
6353 (list (format org-heading-keyword-regexp-format
6354 org-todo-regexp)
6355 '(2 (org-get-todo-face 2) t))
6356 ;; DONE
6357 (if org-fontify-done-headline
6358 (list (format org-heading-keyword-regexp-format
6359 (concat
6360 "\\(?:"
6361 (mapconcat 'regexp-quote org-done-keywords "\\|")
6362 "\\)"))
6363 '(2 'org-headline-done t))
6364 nil)
6365 ;; Priorities
6366 '(org-font-lock-add-priority-faces)
6367 ;; Tags
6368 '(org-font-lock-add-tag-faces)
6369 ;; Tags groups
6370 (when (and org-group-tags org-tag-groups-alist)
6371 (list (concat org-outline-regexp-bol ".+\\(:"
6372 (regexp-opt (mapcar 'car org-tag-groups-alist))
6373 ":\\).*$")
6374 '(1 'org-tag-group prepend)))
6375 ;; Special keywords
6376 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6377 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6378 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6379 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6380 ;; Emphasis
6381 (when em '(org-do-emphasis-faces))
6382 ;; Checkboxes
6383 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6384 1 'org-checkbox prepend)
6385 (when (cdr (assq 'checkbox org-list-automatic-rules))
6386 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6387 (0 (org-get-checkbox-statistics-face) t)))
6388 ;; Description list items
6389 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6390 1 'org-list-dt prepend)
6391 ;; ARCHIVEd headings
6392 (list (concat
6393 org-outline-regexp-bol
6394 "\\(.*:" org-archive-tag ":.*\\)")
6395 '(1 'org-archived prepend))
6396 ;; Specials
6397 '(org-do-latex-and-related)
6398 '(org-fontify-entities)
6399 '(org-raise-scripts)
6400 ;; Code
6401 '(org-activate-code (1 'org-code t))
6402 ;; COMMENT
6403 (list (format
6404 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6405 org-todo-regexp
6406 org-comment-string)
6407 '(9 'org-special-keyword t))
6408 ;; Blocks and meta lines
6409 '(org-fontify-meta-lines-and-blocks))))
6410 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6411 (run-hooks 'org-font-lock-set-keywords-hook)
6412 ;; Now set the full font-lock-keywords
6413 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6414 (setq-local font-lock-defaults
6415 '(org-font-lock-keywords t nil nil backward-paragraph))
6416 (kill-local-variable 'font-lock-keywords)
6417 nil))
6419 (defun org-toggle-pretty-entities ()
6420 "Toggle the composition display of entities as UTF8 characters."
6421 (interactive)
6422 (setq-local org-pretty-entities (not org-pretty-entities))
6423 (org-restart-font-lock)
6424 (if org-pretty-entities
6425 (message "Entities are now displayed as UTF8 characters")
6426 (save-restriction
6427 (widen)
6428 (decompose-region (point-min) (point-max))
6429 (message "Entities are now displayed as plain text"))))
6431 (defvar-local org-custom-properties-overlays nil
6432 "List of overlays used for custom properties.")
6434 (defun org-toggle-custom-properties-visibility ()
6435 "Display or hide properties in `org-custom-properties'."
6436 (interactive)
6437 (if org-custom-properties-overlays
6438 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6439 (setq org-custom-properties-overlays nil))
6440 (when org-custom-properties
6441 (org-with-wide-buffer
6442 (goto-char (point-min))
6443 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6444 (while (re-search-forward regexp nil t)
6445 (let ((end (cdr (save-match-data (org-get-property-block)))))
6446 (when (and end (< (point) end))
6447 ;; Hide first custom property in current drawer.
6448 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6449 (overlay-put o 'invisible t)
6450 (overlay-put o 'org-custom-property t)
6451 (push o org-custom-properties-overlays))
6452 ;; Hide additional custom properties in the same drawer.
6453 (while (re-search-forward regexp end t)
6454 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6455 (overlay-put o 'invisible t)
6456 (overlay-put o 'org-custom-property t)
6457 (push o org-custom-properties-overlays)))))
6458 ;; Each entry is limited to a single property drawer.
6459 (outline-next-heading)))))))
6461 (defun org-fontify-entities (limit)
6462 "Find an entity to fontify."
6463 (let (ee)
6464 (when org-pretty-entities
6465 (catch 'match
6466 ;; "\_ "-family is left out on purpose. Only the first one,
6467 ;; i.e., "\_ ", could be fontified anyway, and it would be
6468 ;; confusing when adding a second white space character.
6469 (while (re-search-forward
6470 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6471 limit t)
6472 (when (and (not (org-at-comment-p))
6473 (setq ee (org-entity-get (match-string 1)))
6474 (= (length (nth 6 ee)) 1))
6475 (let* ((end (if (equal (match-string 2) "{}")
6476 (match-end 2)
6477 (match-end 1))))
6478 (add-text-properties
6479 (match-beginning 0) end
6480 (list 'font-lock-fontified t))
6481 (compose-region (match-beginning 0) end
6482 (nth 6 ee) nil)
6483 (backward-char 1)
6484 (throw 'match t))))
6485 nil))))
6487 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6488 "Fontify string S like in Org mode."
6489 (with-temp-buffer
6490 (insert s)
6491 (let ((org-odd-levels-only odd-levels))
6492 (org-mode)
6493 (org-font-lock-ensure)
6494 (buffer-string))))
6496 (defvar org-m nil)
6497 (defvar org-l nil)
6498 (defvar org-f nil)
6499 (defun org-get-level-face (n)
6500 "Get the right face for match N in font-lock matching of headlines."
6501 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6502 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6503 (if org-cycle-level-faces
6504 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6505 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6506 (cond
6507 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6508 ((eq n 2) org-f)
6509 (t (unless org-level-color-stars-only org-f))))
6511 (defun org-face-from-face-or-color (context inherit face-or-color)
6512 "Create a face list that inherits INHERIT, but sets the foreground color.
6513 When FACE-OR-COLOR is not a string, just return it."
6514 (if (stringp face-or-color)
6515 (list :inherit inherit
6516 (cdr (assoc context org-faces-easy-properties))
6517 face-or-color)
6518 face-or-color))
6520 (defun org-get-todo-face (kwd)
6521 "Get the right face for a TODO keyword KWD.
6522 If KWD is a number, get the corresponding match group."
6523 (when (numberp kwd) (setq kwd (match-string kwd)))
6524 (or (org-face-from-face-or-color
6525 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6526 (and (member kwd org-done-keywords) 'org-done)
6527 'org-todo))
6529 (defun org-get-priority-face (priority)
6530 "Get the right face for PRIORITY.
6531 PRIORITY is a character."
6532 (or (org-face-from-face-or-color
6533 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6534 'org-priority))
6536 (defun org-get-tag-face (tag)
6537 "Get the right face for TAG.
6538 If TAG is a number, get the corresponding match group."
6539 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6540 (or (org-face-from-face-or-color
6541 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6542 'org-tag)))
6544 (defun org-font-lock-add-priority-faces (limit)
6545 "Add the special priority faces."
6546 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6547 (add-text-properties
6548 (match-beginning 1) (match-end 1)
6549 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6550 'font-lock-fontified t))))
6552 (defun org-font-lock-add-tag-faces (limit)
6553 "Add the special tag faces."
6554 (when (and org-tag-faces org-tags-special-faces-re)
6555 (while (re-search-forward org-tags-special-faces-re limit t)
6556 (add-text-properties (match-beginning 1) (match-end 1)
6557 (list 'face (org-get-tag-face 1)
6558 'font-lock-fontified t))
6559 (backward-char 1))))
6561 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6562 "Remove fontification and activation overlays from links."
6563 (font-lock-default-unfontify-region beg end)
6564 (let* ((buffer-undo-list t)
6565 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6566 (inhibit-modification-hooks t)
6567 deactivate-mark buffer-file-name buffer-file-truename)
6568 (decompose-region beg end)
6569 (remove-text-properties beg end
6570 '(mouse-face t keymap t org-linked-text t
6571 invisible t intangible t
6572 org-emphasis t))
6573 (org-remove-font-lock-display-properties beg end)))
6575 (defconst org-script-display '(((raise -0.3) (height 0.7))
6576 ((raise 0.3) (height 0.7))
6577 ((raise -0.5))
6578 ((raise 0.5)))
6579 "Display properties for showing superscripts and subscripts.")
6581 (defun org-remove-font-lock-display-properties (beg end)
6582 "Remove specific display properties that have been added by font lock.
6583 The will remove the raise properties that are used to show superscripts
6584 and subscripts."
6585 (let (next prop)
6586 (while (< beg end)
6587 (setq next (next-single-property-change beg 'display nil end)
6588 prop (get-text-property beg 'display))
6589 (when (member prop org-script-display)
6590 (put-text-property beg next 'display nil))
6591 (setq beg next))))
6593 (defun org-raise-scripts (limit)
6594 "Add raise properties to sub/superscripts."
6595 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6596 (re-search-forward
6597 (if (eq org-use-sub-superscripts t)
6598 org-match-substring-regexp
6599 org-match-substring-with-braces-regexp)
6600 limit t))
6601 (let* ((pos (point)) table-p comment-p
6602 (mpos (match-beginning 3))
6603 (emph-p (get-text-property mpos 'org-emphasis))
6604 (link-p (get-text-property mpos 'mouse-face))
6605 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6606 (goto-char (point-at-bol))
6607 (setq table-p (looking-at-p org-table-dataline-regexp)
6608 comment-p (looking-at-p "^[ \t]*#[ +]"))
6609 (goto-char pos)
6610 ;; Handle a_b^c
6611 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6612 (unless (or comment-p emph-p link-p keyw-p)
6613 (put-text-property (match-beginning 3) (match-end 0)
6614 'display
6615 (if (equal (char-after (match-beginning 2)) ?^)
6616 (nth (if table-p 3 1) org-script-display)
6617 (nth (if table-p 2 0) org-script-display)))
6618 (add-text-properties (match-beginning 2) (match-end 2)
6619 (list 'invisible t))
6620 (when (and (eq (char-after (match-beginning 3)) ?{)
6621 (eq (char-before (match-end 3)) ?}))
6622 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6623 (list 'invisible t))
6624 (add-text-properties (1- (match-end 3)) (match-end 3)
6625 (list 'invisible t))))
6626 t)))
6628 ;;;; Visibility cycling, including org-goto and indirect buffer
6630 ;;; Cycling
6632 (defvar-local org-cycle-global-status nil)
6633 (put 'org-cycle-global-status 'org-state t)
6634 (defvar-local org-cycle-subtree-status nil)
6635 (put 'org-cycle-subtree-status 'org-state t)
6637 (defvar org-inlinetask-min-level)
6639 (defun org-unlogged-message (&rest args)
6640 "Display a message, but avoid logging it in the *Messages* buffer."
6641 (let ((message-log-max nil))
6642 (apply 'message args)))
6644 ;;;###autoload
6645 (defun org-cycle (&optional arg)
6646 "TAB-action and visibility cycling for Org mode.
6648 This is the command invoked in Org mode by the `TAB' key. Its main
6649 purpose is outline visibility cycling, but it also invokes other actions
6650 in special contexts.
6652 When this function is called with a `\\[universal-argument]' prefix, rotate \
6653 the entire
6654 buffer through 3 states (global cycling)
6655 1. OVERVIEW: Show only top-level headlines.
6656 2. CONTENTS: Show all headlines of all levels, but no body text.
6657 3. SHOW ALL: Show everything.
6659 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6660 switch to the startup visibility,
6661 determined by the variable `org-startup-folded', and by any VISIBILITY
6662 properties in the buffer.
6664 With a `\\[universal-argument] \\[universal-argument] \
6665 \\[universal-argument]' prefix argument, show the entire buffer, including
6666 any drawers.
6668 When inside a table, re-align the table and move to the next field.
6670 When point is at the beginning of a headline, rotate the subtree started
6671 by this line through 3 different states (local cycling)
6672 1. FOLDED: Only the main headline is shown.
6673 2. CHILDREN: The main headline and the direct children are shown.
6674 From this state, you can move to one of the children
6675 and zoom in further.
6676 3. SUBTREE: Show the entire subtree, including body text.
6677 If there is no subtree, switch directly from CHILDREN to FOLDED.
6679 When point is at the beginning of an empty headline and the variable
6680 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6681 of the headline by demoting and promoting it to likely levels. This
6682 speeds up creation document structure by pressing `TAB' once or several
6683 times right after creating a new headline.
6685 When there is a numeric prefix, go up to a heading with level ARG, do
6686 a `show-subtree' and return to the previous cursor position. If ARG
6687 is negative, go up that many levels.
6689 When point is not at the beginning of a headline, execute the global
6690 binding for `TAB', which is re-indenting the line. See the option
6691 `org-cycle-emulate-tab' for details.
6693 As a special case, if point is at the beginning of the buffer and there is
6694 no headline in line 1, this function will act as if called with prefix arg
6695 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6696 prefix arg, but only
6697 if the variable `org-cycle-global-at-bob' is t."
6698 (interactive "P")
6699 (org-load-modules-maybe)
6700 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6701 (and org-cycle-level-after-item/entry-creation
6702 (or (org-cycle-level)
6703 (org-cycle-item-indentation))))
6704 (let* ((limit-level
6705 (or org-cycle-max-level
6706 (and (boundp 'org-inlinetask-min-level)
6707 org-inlinetask-min-level
6708 (1- org-inlinetask-min-level))))
6709 (nstars (and limit-level
6710 (if org-odd-levels-only
6711 (and limit-level (1- (* limit-level 2)))
6712 limit-level)))
6713 (org-outline-regexp
6714 (if (not (derived-mode-p 'org-mode))
6715 outline-regexp
6716 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6717 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6718 (not (looking-at org-outline-regexp))))
6719 (org-cycle-hook
6720 (if bob-special
6721 (delq 'org-optimize-window-after-visibility-change
6722 (copy-sequence org-cycle-hook))
6723 org-cycle-hook))
6724 (pos (point)))
6726 (cond
6728 ((equal arg '(16))
6729 (setq last-command 'dummy)
6730 (org-set-startup-visibility)
6731 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6733 ((equal arg '(64))
6734 (outline-show-all)
6735 (org-unlogged-message "Entire buffer visible, including drawers"))
6737 ((equal arg '(4)) (org-cycle-internal-global))
6739 ;; Try hiding block at point.
6740 ((org-hide-block-toggle-maybe))
6742 ;; Try cdlatex TAB completion
6743 ((org-try-cdlatex-tab))
6745 ;; Table: enter it or move to the next field.
6746 ((org-at-table-p 'any)
6747 (if (org-at-table.el-p)
6748 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6749 Use `\\[org-edit-special]' to edit table.el tables"))
6750 (if arg (org-table-edit-field t)
6751 (org-table-justify-field-maybe)
6752 (call-interactively 'org-table-next-field))))
6754 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6756 ;; Global cycling: delegate to `org-cycle-internal-global'.
6757 (bob-special (org-cycle-internal-global))
6759 ;; Drawers: delegate to `org-flag-drawer'.
6760 ((save-excursion
6761 (beginning-of-line 1)
6762 (looking-at org-drawer-regexp))
6763 (org-flag-drawer ; toggle block visibility
6764 (not (get-char-property (match-end 0) 'invisible))))
6766 ;; Show-subtree, ARG levels up from here.
6767 ((integerp arg)
6768 (save-excursion
6769 (org-back-to-heading)
6770 (outline-up-heading (if (< arg 0) (- arg)
6771 (- (funcall outline-level) arg)))
6772 (org-show-subtree)))
6774 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6775 ((and (featurep 'org-inlinetask)
6776 (org-inlinetask-at-task-p)
6777 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6778 (org-inlinetask-toggle-visibility))
6780 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6781 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6782 (save-excursion (move-beginning-of-line 1)
6783 (looking-at org-outline-regexp)))
6784 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6785 (org-cycle-internal-local))
6787 ;; From there: TAB emulation and template completion.
6788 (buffer-read-only (org-back-to-heading))
6790 ((run-hook-with-args-until-success
6791 'org-tab-after-check-for-cycling-hook))
6793 ((org-try-structure-completion))
6795 ((run-hook-with-args-until-success
6796 'org-tab-before-tab-emulation-hook))
6798 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6799 (or (not (bolp))
6800 (not (looking-at org-outline-regexp))))
6801 (call-interactively (global-key-binding "\t")))
6803 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6804 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6805 (or (and (eq org-cycle-emulate-tab 'white)
6806 (= (match-end 0) (point-at-eol)))
6807 (and (eq org-cycle-emulate-tab 'whitestart)
6808 (>= (match-end 0) pos))))
6810 (eq org-cycle-emulate-tab t))
6811 (call-interactively (global-key-binding "\t")))
6813 (t (save-excursion
6814 (org-back-to-heading)
6815 (org-cycle)))))))
6817 (defun org-cycle-internal-global ()
6818 "Do the global cycling action."
6819 ;; Hack to avoid display of messages for .org attachments in Gnus
6820 (let ((ga (string-match "\\*fontification" (buffer-name))))
6821 (cond
6822 ((and (eq last-command this-command)
6823 (eq org-cycle-global-status 'overview))
6824 ;; We just created the overview - now do table of contents
6825 ;; This can be slow in very large buffers, so indicate action
6826 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6827 (unless ga (org-unlogged-message "CONTENTS..."))
6828 (org-content)
6829 (unless ga (org-unlogged-message "CONTENTS...done"))
6830 (setq org-cycle-global-status 'contents)
6831 (run-hook-with-args 'org-cycle-hook 'contents))
6833 ((and (eq last-command this-command)
6834 (eq org-cycle-global-status 'contents))
6835 ;; We just showed the table of contents - now show everything
6836 (run-hook-with-args 'org-pre-cycle-hook 'all)
6837 (outline-show-all)
6838 (unless ga (org-unlogged-message "SHOW ALL"))
6839 (setq org-cycle-global-status 'all)
6840 (run-hook-with-args 'org-cycle-hook 'all))
6843 ;; Default action: go to overview
6844 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6845 (org-overview)
6846 (unless ga (org-unlogged-message "OVERVIEW"))
6847 (setq org-cycle-global-status 'overview)
6848 (run-hook-with-args 'org-cycle-hook 'overview)))))
6850 (defvar org-called-with-limited-levels nil
6851 "Non-nil when `org-with-limited-levels' is currently active.")
6853 (defun org-invisible-p (&optional pos)
6854 "Non-nil if the character after POS is invisible.
6855 If POS is nil, use `point' instead."
6856 (get-char-property (or pos (point)) 'invisible))
6858 (defun org-cycle-internal-local ()
6859 "Do the local cycling action."
6860 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6861 ;; First, determine end of headline (EOH), end of subtree or item
6862 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6863 (save-excursion
6864 (if (org-at-item-p)
6865 (progn
6866 (beginning-of-line)
6867 (setq struct (org-list-struct))
6868 (setq eoh (point-at-eol))
6869 (setq eos (org-list-get-item-end-before-blank (point) struct))
6870 (setq has-children (org-list-has-child-p (point) struct)))
6871 (org-back-to-heading)
6872 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6873 (setq eos (save-excursion (org-end-of-subtree t t)
6874 (when (bolp) (backward-char)) (point)))
6875 (setq has-children
6876 (or (save-excursion
6877 (let ((level (funcall outline-level)))
6878 (outline-next-heading)
6879 (and (org-at-heading-p t)
6880 (> (funcall outline-level) level))))
6881 (save-excursion
6882 (org-list-search-forward (org-item-beginning-re) eos t)))))
6883 ;; Determine end invisible part of buffer (EOL)
6884 (beginning-of-line 2)
6885 (while (and (not (eobp)) ;This is like `next-line'.
6886 (get-char-property (1- (point)) 'invisible))
6887 (goto-char (next-single-char-property-change (point) 'invisible))
6888 (and (eolp) (beginning-of-line 2)))
6889 (setq eol (point)))
6890 ;; Find out what to do next and set `this-command'
6891 (cond
6892 ((= eos eoh)
6893 ;; Nothing is hidden behind this heading
6894 (unless (org-before-first-heading-p)
6895 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6896 (org-unlogged-message "EMPTY ENTRY")
6897 (setq org-cycle-subtree-status nil)
6898 (save-excursion
6899 (goto-char eos)
6900 (outline-next-heading)
6901 (when (org-invisible-p) (org-flag-heading nil))))
6902 ((and (or (>= eol eos)
6903 (not (string-match "\\S-" (buffer-substring eol eos))))
6904 (or has-children
6905 (not (setq children-skipped
6906 org-cycle-skip-children-state-if-no-children))))
6907 ;; Entire subtree is hidden in one line: children view
6908 (unless (org-before-first-heading-p)
6909 (run-hook-with-args 'org-pre-cycle-hook 'children))
6910 (if (org-at-item-p)
6911 (org-list-set-item-visibility (point-at-bol) struct 'children)
6912 (org-show-entry)
6913 (org-with-limited-levels (org-show-children))
6914 ;; FIXME: This slows down the func way too much.
6915 ;; How keep drawers hidden in subtree anyway?
6916 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6917 ;; (org-cycle-hide-drawers 'subtree))
6919 ;; Fold every list in subtree to top-level items.
6920 (when (eq org-cycle-include-plain-lists 'integrate)
6921 (save-excursion
6922 (org-back-to-heading)
6923 (while (org-list-search-forward (org-item-beginning-re) eos t)
6924 (beginning-of-line 1)
6925 (let* ((struct (org-list-struct))
6926 (prevs (org-list-prevs-alist struct))
6927 (end (org-list-get-bottom-point struct)))
6928 (dolist (e (org-list-get-all-items (point) struct prevs))
6929 (org-list-set-item-visibility e struct 'folded))
6930 (goto-char (if (< end eos) end eos)))))))
6931 (org-unlogged-message "CHILDREN")
6932 (save-excursion
6933 (goto-char eos)
6934 (outline-next-heading)
6935 (when (org-invisible-p) (org-flag-heading nil)))
6936 (setq org-cycle-subtree-status 'children)
6937 (unless (org-before-first-heading-p)
6938 (run-hook-with-args 'org-cycle-hook 'children)))
6939 ((or children-skipped
6940 (and (eq last-command this-command)
6941 (eq org-cycle-subtree-status 'children)))
6942 ;; We just showed the children, or no children are there,
6943 ;; now show everything.
6944 (unless (org-before-first-heading-p)
6945 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6946 (outline-flag-region eoh eos nil)
6947 (org-unlogged-message
6948 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6949 (setq org-cycle-subtree-status 'subtree)
6950 (unless (org-before-first-heading-p)
6951 (run-hook-with-args 'org-cycle-hook 'subtree)))
6953 ;; Default action: hide the subtree.
6954 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6955 (outline-flag-region eoh eos t)
6956 (org-unlogged-message "FOLDED")
6957 (setq org-cycle-subtree-status 'folded)
6958 (unless (org-before-first-heading-p)
6959 (run-hook-with-args 'org-cycle-hook 'folded))))))
6961 ;;;###autoload
6962 (defun org-global-cycle (&optional arg)
6963 "Cycle the global visibility. For details see `org-cycle'.
6964 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6965 With a numeric prefix, show all headlines up to that level."
6966 (interactive "P")
6967 (let ((org-cycle-include-plain-lists
6968 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6969 (cond
6970 ((integerp arg)
6971 (outline-show-all)
6972 (outline-hide-sublevels arg)
6973 (setq org-cycle-global-status 'contents))
6974 ((equal arg '(4))
6975 (org-set-startup-visibility)
6976 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6978 (org-cycle '(4))))))
6980 (defun org-set-startup-visibility ()
6981 "Set the visibility required by startup options and properties."
6982 (cond
6983 ((eq org-startup-folded t)
6984 (org-overview))
6985 ((eq org-startup-folded 'content)
6986 (org-content))
6987 ((or (eq org-startup-folded 'showeverything)
6988 (eq org-startup-folded nil))
6989 (outline-show-all)))
6990 (unless (eq org-startup-folded 'showeverything)
6991 (when org-hide-block-startup (org-hide-block-all))
6992 (org-set-visibility-according-to-property 'no-cleanup)
6993 (org-cycle-hide-archived-subtrees 'all)
6994 (org-cycle-hide-drawers 'all)
6995 (org-cycle-show-empty-lines t)))
6997 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6998 "Switch subtree visibilities according to :VISIBILITY: property."
6999 (interactive)
7000 (org-with-wide-buffer
7001 (goto-char (point-min))
7002 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7003 (if (not (org-at-property-p)) (outline-next-heading)
7004 (let ((state (match-string 3)))
7005 (save-excursion
7006 (org-back-to-heading t)
7007 (outline-hide-subtree)
7008 (org-reveal)
7009 (cond
7010 ((equal state "folded")
7011 (outline-hide-subtree))
7012 ((equal state "children")
7013 (org-show-hidden-entry)
7014 (org-show-children))
7015 ((equal state "content")
7016 (save-excursion
7017 (save-restriction
7018 (org-narrow-to-subtree)
7019 (org-content))))
7020 ((member state '("all" "showall"))
7021 (outline-show-subtree)))))))
7022 (unless no-cleanup
7023 (org-cycle-hide-archived-subtrees 'all)
7024 (org-cycle-hide-drawers 'all)
7025 (org-cycle-show-empty-lines 'all))))
7027 ;; This function uses outline-regexp instead of the more fundamental
7028 ;; org-outline-regexp so that org-cycle-global works outside of Org
7029 ;; buffers, where outline-regexp is needed.
7030 (defun org-overview ()
7031 "Switch to overview mode, showing only top-level headlines.
7032 This shows all headlines with a level equal or greater than the level
7033 of the first headline in the buffer. This is important, because if the
7034 first headline is not level one, then (hide-sublevels 1) gives confusing
7035 results."
7036 (interactive)
7037 (save-excursion
7038 (let ((level
7039 (save-excursion
7040 (goto-char (point-min))
7041 (when (re-search-forward (concat "^" outline-regexp) nil t)
7042 (goto-char (match-beginning 0))
7043 (funcall outline-level)))))
7044 (and level (outline-hide-sublevels level)))))
7046 (defun org-content (&optional arg)
7047 "Show all headlines in the buffer, like a table of contents.
7048 With numerical argument N, show content up to level N."
7049 (interactive "P")
7050 (org-overview)
7051 (save-excursion
7052 ;; Visit all headings and show their offspring
7053 (and (integerp arg) (org-overview))
7054 (goto-char (point-max))
7055 (catch 'exit
7056 (while (and (progn (condition-case nil
7057 (outline-previous-visible-heading 1)
7058 (error (goto-char (point-min))))
7060 (looking-at org-outline-regexp))
7061 (if (integerp arg)
7062 (org-show-children (1- arg))
7063 (outline-show-branches))
7064 (when (bobp) (throw 'exit nil))))))
7066 (defun org-optimize-window-after-visibility-change (state)
7067 "Adjust the window after a change in outline visibility.
7068 This function is the default value of the hook `org-cycle-hook'."
7069 (when (get-buffer-window (current-buffer))
7070 (cond
7071 ((eq state 'content) nil)
7072 ((eq state 'all) nil)
7073 ((eq state 'folded) nil)
7074 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7075 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7077 (defun org-remove-empty-overlays-at (pos)
7078 "Remove outline overlays that do not contain non-white stuff."
7079 (dolist (o (overlays-at pos))
7080 (and (eq 'outline (overlay-get o 'invisible))
7081 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7082 (overlay-end o))))
7083 (delete-overlay o))))
7085 (defun org-clean-visibility-after-subtree-move ()
7086 "Fix visibility issues after moving a subtree."
7087 ;; First, find a reasonable region to look at:
7088 ;; Start two siblings above, end three below
7089 (let* ((beg (save-excursion
7090 (and (org-get-last-sibling)
7091 (org-get-last-sibling))
7092 (point)))
7093 (end (save-excursion
7094 (and (org-get-next-sibling)
7095 (org-get-next-sibling)
7096 (org-get-next-sibling))
7097 (if (org-at-heading-p)
7098 (point-at-eol)
7099 (point))))
7100 (level (looking-at "\\*+"))
7101 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7102 (save-excursion
7103 (save-restriction
7104 (narrow-to-region beg end)
7105 (when re
7106 ;; Properly fold already folded siblings
7107 (goto-char (point-min))
7108 (while (re-search-forward re nil t)
7109 (when (and (not (org-invisible-p))
7110 (save-excursion
7111 (goto-char (point-at-eol)) (org-invisible-p)))
7112 (outline-hide-entry))))
7113 (org-cycle-show-empty-lines 'overview)
7114 (org-cycle-hide-drawers 'overview)))))
7116 (defun org-cycle-show-empty-lines (state)
7117 "Show empty lines above all visible headlines.
7118 The region to be covered depends on STATE when called through
7119 `org-cycle-hook'. Lisp program can use t for STATE to get the
7120 entire buffer covered. Note that an empty line is only shown if there
7121 are at least `org-cycle-separator-lines' empty lines before the headline."
7122 (when (/= org-cycle-separator-lines 0)
7123 (save-excursion
7124 (let* ((n (abs org-cycle-separator-lines))
7125 (re (cond
7126 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7127 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7128 (t (let ((ns (number-to-string (- n 2))))
7129 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7130 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7131 beg end)
7132 (cond
7133 ((memq state '(overview contents t))
7134 (setq beg (point-min) end (point-max)))
7135 ((memq state '(children folded))
7136 (setq beg (point)
7137 end (progn (org-end-of-subtree t t)
7138 (line-beginning-position 2)))))
7139 (when beg
7140 (goto-char beg)
7141 (while (re-search-forward re end t)
7142 (unless (get-char-property (match-end 1) 'invisible)
7143 (let ((e (match-end 1))
7144 (b (if (>= org-cycle-separator-lines 0)
7145 (match-beginning 1)
7146 (save-excursion
7147 (goto-char (match-beginning 0))
7148 (skip-chars-backward " \t\n")
7149 (line-end-position)))))
7150 (outline-flag-region b e nil))))))))
7151 ;; Never hide empty lines at the end of the file.
7152 (save-excursion
7153 (goto-char (point-max))
7154 (outline-previous-heading)
7155 (outline-end-of-heading)
7156 (when (and (looking-at "[ \t\n]+")
7157 (= (match-end 0) (point-max)))
7158 (outline-flag-region (point) (match-end 0) nil))))
7160 (defun org-show-empty-lines-in-parent ()
7161 "Move to the parent and re-show empty lines before visible headlines."
7162 (save-excursion
7163 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7164 (org-cycle-show-empty-lines context))))
7166 (defun org-files-list ()
7167 "Return `org-agenda-files' list, plus all open Org files.
7168 This is useful for operations that need to scan all of a user's
7169 open and agenda-wise Org files."
7170 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7171 (dolist (buf (buffer-list))
7172 (with-current-buffer buf
7173 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7174 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7175 files))
7177 (defsubst org-entry-beginning-position ()
7178 "Return the beginning position of the current entry."
7179 (save-excursion (org-back-to-heading t) (point)))
7181 (defsubst org-entry-end-position ()
7182 "Return the end position of the current entry."
7183 (save-excursion (outline-next-heading) (point)))
7185 (defun org-cycle-hide-drawers (state &optional exceptions)
7186 "Re-hide all drawers after a visibility state change.
7187 STATE should be one of the symbols listed in the docstring of
7188 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7189 a list of strings specifying which drawers should not be hidden."
7190 (when (and (derived-mode-p 'org-mode)
7191 (not (memq state '(overview folded contents))))
7192 (save-excursion
7193 (let* ((globalp (eq state 'all))
7194 (beg (if globalp (point-min) (point)))
7195 (end (if globalp (point-max)
7196 (if (eq state 'children)
7197 (save-excursion (outline-next-heading) (point))
7198 (org-end-of-subtree t)))))
7199 (goto-char beg)
7200 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7201 (unless (member-ignore-case (match-string 1) exceptions)
7202 (let ((drawer (org-element-at-point)))
7203 (when (memq (org-element-type drawer) '(drawer property-drawer))
7204 (org-flag-drawer t drawer)
7205 ;; Make sure to skip drawer entirely or we might flag
7206 ;; it another time when matching its ending line with
7207 ;; `org-drawer-regexp'.
7208 (goto-char (org-element-property :end drawer))))))))))
7210 (defun org-flag-drawer (flag &optional element)
7211 "When FLAG is non-nil, hide the drawer we are at.
7212 Otherwise make it visible. When optional argument ELEMENT is
7213 a parsed drawer, as returned by `org-element-at-point', hide or
7214 show that drawer instead."
7215 (let ((drawer (or element
7216 (and (save-excursion
7217 (beginning-of-line)
7218 (looking-at-p org-drawer-regexp))
7219 (org-element-at-point)))))
7220 (when (memq (org-element-type drawer) '(drawer property-drawer))
7221 (let ((post (org-element-property :post-affiliated drawer)))
7222 (save-excursion
7223 (outline-flag-region
7224 (progn (goto-char post) (line-end-position))
7225 (progn (goto-char (org-element-property :end drawer))
7226 (skip-chars-backward " \r\t\n")
7227 (line-end-position))
7228 flag))
7229 ;; When the drawer is hidden away, make sure point lies in
7230 ;; a visible part of the buffer.
7231 (when (and flag (> (line-beginning-position) post))
7232 (goto-char post))))))
7234 (defun org-subtree-end-visible-p ()
7235 "Is the end of the current subtree visible?"
7236 (pos-visible-in-window-p
7237 (save-excursion (org-end-of-subtree t) (point))))
7239 (defun org-first-headline-recenter ()
7240 "Move cursor to the first headline and recenter the headline."
7241 (let ((window (get-buffer-window)))
7242 (when window
7243 (goto-char (point-min))
7244 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7245 (set-window-start window (line-beginning-position))))))
7247 ;;; Saving and restoring visibility
7249 (defun org-outline-overlay-data (&optional use-markers)
7250 "Return a list of the locations of all outline overlays.
7251 These are overlays with the `invisible' property value `outline'.
7252 The return value is a list of cons cells, with start and stop
7253 positions for each overlay.
7254 If USE-MARKERS is set, return the positions as markers."
7255 (let (beg end)
7256 (org-with-wide-buffer
7257 (delq nil
7258 (mapcar (lambda (o)
7259 (when (eq (overlay-get o 'invisible) 'outline)
7260 (setq beg (overlay-start o)
7261 end (overlay-end o))
7262 (and beg end (> end beg)
7263 (if use-markers
7264 (cons (copy-marker beg)
7265 (copy-marker end t))
7266 (cons beg end)))))
7267 (overlays-in (point-min) (point-max)))))))
7269 (defun org-set-outline-overlay-data (data)
7270 "Create visibility overlays for all positions in DATA.
7271 DATA should have been made by `org-outline-overlay-data'."
7272 (org-with-wide-buffer
7273 (outline-show-all)
7274 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7276 ;;; Folding of blocks
7278 (defvar-local org-hide-block-overlays nil
7279 "Overlays hiding blocks.")
7281 (defun org-block-map (function &optional start end)
7282 "Call FUNCTION at the head of all source blocks in the current buffer.
7283 Optional arguments START and END can be used to limit the range."
7284 (let ((start (or start (point-min)))
7285 (end (or end (point-max))))
7286 (save-excursion
7287 (goto-char start)
7288 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7289 (save-excursion
7290 (save-match-data
7291 (goto-char (match-beginning 0))
7292 (funcall function)))))))
7294 (defun org-hide-block-toggle-all ()
7295 "Toggle the visibility of all blocks in the current buffer."
7296 (org-block-map 'org-hide-block-toggle))
7298 (defun org-hide-block-all ()
7299 "Fold all blocks in the current buffer."
7300 (interactive)
7301 (org-show-block-all)
7302 (org-block-map 'org-hide-block-toggle-maybe))
7304 (defun org-show-block-all ()
7305 "Unfold all blocks in the current buffer."
7306 (interactive)
7307 (mapc #'delete-overlay org-hide-block-overlays)
7308 (setq org-hide-block-overlays nil))
7310 (defun org-hide-block-toggle-maybe ()
7311 "Toggle visibility of block at point.
7312 Unlike to `org-hide-block-toggle', this function does not throw
7313 an error. Return a non-nil value when toggling is successful."
7314 (interactive)
7315 (ignore-errors (org-hide-block-toggle)))
7317 (defun org-hide-block-toggle (&optional force)
7318 "Toggle the visibility of the current block.
7319 When optional argument FORCE is `off', make block visible. If it
7320 is non-nil, hide it unconditionally. Throw an error when not at
7321 a block. Return a non-nil value when toggling is successful."
7322 (interactive)
7323 (let ((element (org-element-at-point)))
7324 (unless (memq (org-element-type element)
7325 '(center-block comment-block dynamic-block example-block
7326 export-block quote-block special-block
7327 src-block verse-block))
7328 (user-error "Not at a block"))
7329 (let* ((start (save-excursion
7330 (goto-char (org-element-property :post-affiliated element))
7331 (line-end-position)))
7332 (end (save-excursion
7333 (goto-char (org-element-property :end element))
7334 (skip-chars-backward " \r\t\n")
7335 (line-end-position)))
7336 (overlays (overlays-at start)))
7337 (cond
7338 ;; Do nothing when not before or at the block opening line or
7339 ;; at the block closing line.
7340 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7341 ((and (not (eq force 'off))
7342 (not (memq t (mapcar
7343 (lambda (o)
7344 (eq (overlay-get o 'invisible) 'org-hide-block))
7345 overlays))))
7346 (let ((ov (make-overlay start end)))
7347 (overlay-put ov 'invisible 'org-hide-block)
7348 ;; Make the block accessible to `isearch'.
7349 (overlay-put
7350 ov 'isearch-open-invisible
7351 (lambda (ov)
7352 (when (memq ov org-hide-block-overlays)
7353 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7354 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7355 (delete-overlay ov))))
7356 (push ov org-hide-block-overlays)
7357 ;; When the block is hidden away, make sure point is left in
7358 ;; a visible part of the buffer.
7359 (when (> (line-beginning-position) start)
7360 (goto-char start)
7361 (beginning-of-line))
7362 ;; Signal successful toggling.
7364 ((or (not force) (eq force 'off))
7365 (dolist (ov overlays t)
7366 (when (memq ov org-hide-block-overlays)
7367 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7368 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7369 (delete-overlay ov))))))))
7371 ;; Remove overlays when changing major mode
7372 (add-hook 'org-mode-hook
7373 (lambda () (add-hook 'change-major-mode-hook
7374 'org-show-block-all 'append 'local)))
7376 ;;; Org-goto
7378 (defvar org-goto-window-configuration nil)
7379 (defvar org-goto-marker nil)
7380 (defvar org-goto-map)
7381 (defun org-goto-map ()
7382 "Set the keymap `org-goto'."
7383 (setq org-goto-map
7384 (let ((map (make-sparse-keymap)))
7385 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7386 mouse-drag-region universal-argument org-occur)))
7387 (dolist (cmd cmds)
7388 (substitute-key-definition cmd cmd map global-map)))
7389 (suppress-keymap map)
7390 (org-defkey map "\C-m" 'org-goto-ret)
7391 (org-defkey map [(return)] 'org-goto-ret)
7392 (org-defkey map [(left)] 'org-goto-left)
7393 (org-defkey map [(right)] 'org-goto-right)
7394 (org-defkey map [(control ?g)] 'org-goto-quit)
7395 (org-defkey map "\C-i" 'org-cycle)
7396 (org-defkey map [(tab)] 'org-cycle)
7397 (org-defkey map [(down)] 'outline-next-visible-heading)
7398 (org-defkey map [(up)] 'outline-previous-visible-heading)
7399 (if org-goto-auto-isearch
7400 (if (fboundp 'define-key-after)
7401 (define-key-after map [t] 'org-goto-local-auto-isearch)
7402 nil)
7403 (org-defkey map "q" 'org-goto-quit)
7404 (org-defkey map "n" 'outline-next-visible-heading)
7405 (org-defkey map "p" 'outline-previous-visible-heading)
7406 (org-defkey map "f" 'outline-forward-same-level)
7407 (org-defkey map "b" 'outline-backward-same-level)
7408 (org-defkey map "u" 'outline-up-heading))
7409 (org-defkey map "/" 'org-occur)
7410 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7411 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7412 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7413 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7414 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7415 map)))
7417 (defconst org-goto-help
7418 "Browse buffer copy, to find location or copy text.%s
7419 RET=jump to location C-g=quit and return to previous location
7420 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7422 (defvar org-goto-start-pos) ; dynamically scoped parameter
7424 (defun org-goto (&optional alternative-interface)
7425 "Look up a different location in the current file, keeping current visibility.
7427 When you want look-up or go to a different location in a
7428 document, the fastest way is often to fold the entire buffer and
7429 then dive into the tree. This method has the disadvantage, that
7430 the previous location will be folded, which may not be what you
7431 want.
7433 This command works around this by showing a copy of the current
7434 buffer in an indirect buffer, in overview mode. You can dive
7435 into the tree in that copy, use org-occur and incremental search
7436 to find a location. When pressing RET or `Q', the command
7437 returns to the original buffer in which the visibility is still
7438 unchanged. After RET it will also jump to the location selected
7439 in the indirect buffer and expose the headline hierarchy above.
7441 With a prefix argument, use the alternative interface: e.g., if
7442 `org-goto-interface' is `outline' use `outline-path-completion'."
7443 (interactive "P")
7444 (org-goto-map)
7445 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7446 (org-refile-use-outline-path t)
7447 (org-refile-target-verify-function nil)
7448 (interface
7449 (if (not alternative-interface)
7450 org-goto-interface
7451 (if (eq org-goto-interface 'outline)
7452 'outline-path-completion
7453 'outline)))
7454 (org-goto-start-pos (point))
7455 (selected-point
7456 (if (eq interface 'outline)
7457 (car (org-get-location (current-buffer) org-goto-help))
7458 (let ((pa (org-refile-get-location "Goto")))
7459 (org-refile-check-position pa)
7460 (nth 3 pa)))))
7461 (if selected-point
7462 (progn
7463 (org-mark-ring-push org-goto-start-pos)
7464 (goto-char selected-point)
7465 (when (or (org-invisible-p) (org-invisible-p2))
7466 (org-show-context 'org-goto)))
7467 (message "Quit"))))
7469 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7470 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7471 (defvar org-goto-local-auto-isearch-map) ; defined below
7473 (defun org-get-location (_buf help)
7474 "Let the user select a location in current buffer.
7475 This function uses a recursive edit. It returns the selected position
7476 or nil."
7477 (org-no-popups
7478 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7479 (isearch-hide-immediately nil)
7480 (isearch-search-fun-function
7481 (lambda () 'org-goto-local-search-headings))
7482 (org-goto-selected-point org-goto-exit-command))
7483 (save-excursion
7484 (save-window-excursion
7485 (delete-other-windows)
7486 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7487 (pop-to-buffer-same-window
7488 (condition-case nil
7489 (make-indirect-buffer (current-buffer) "*org-goto*")
7490 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7491 (with-output-to-temp-buffer "*Org Help*"
7492 (princ (format help (if org-goto-auto-isearch
7493 " Just type for auto-isearch."
7494 " n/p/f/b/u to navigate, q to quit."))))
7495 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7496 (setq buffer-read-only nil)
7497 (let ((org-startup-truncated t)
7498 (org-startup-folded nil)
7499 (org-startup-align-all-tables nil))
7500 (org-mode)
7501 (org-overview))
7502 (setq buffer-read-only t)
7503 (if (and (boundp 'org-goto-start-pos)
7504 (integer-or-marker-p org-goto-start-pos))
7505 (progn (goto-char org-goto-start-pos)
7506 (when (org-invisible-p)
7507 (org-show-set-visibility 'lineage)))
7508 (goto-char (point-min)))
7509 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7510 (message "Select location and press RET")
7511 (use-local-map org-goto-map)
7512 (recursive-edit)))
7513 (kill-buffer "*org-goto*")
7514 (cons org-goto-selected-point org-goto-exit-command))))
7516 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7517 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7518 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7519 (if (fboundp 'isearch-other-control-char)
7520 (progn
7521 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7522 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7523 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7524 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7525 (define-key org-goto-local-auto-isearch-map [return] nil))
7527 (defun org-goto-local-search-headings (string bound noerror)
7528 "Search and make sure that any matches are in headlines."
7529 (catch 'return
7530 (while (if isearch-forward
7531 (search-forward string bound noerror)
7532 (search-backward string bound noerror))
7533 (when (save-match-data
7534 (and (save-excursion
7535 (beginning-of-line)
7536 (looking-at org-complex-heading-regexp))
7537 (or (not (match-beginning 5))
7538 (< (point) (match-beginning 5)))))
7539 (throw 'return (point))))))
7541 (defun org-goto-local-auto-isearch ()
7542 "Start isearch."
7543 (interactive)
7544 (goto-char (point-min))
7545 (let ((keys (this-command-keys)))
7546 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7547 (isearch-mode t)
7548 (isearch-process-search-char (string-to-char keys)))))
7550 (defun org-goto-ret (&optional _arg)
7551 "Finish `org-goto' by going to the new location."
7552 (interactive "P")
7553 (setq org-goto-selected-point (point))
7554 (setq org-goto-exit-command 'return)
7555 (throw 'exit nil))
7557 (defun org-goto-left ()
7558 "Finish `org-goto' by going to the new location."
7559 (interactive)
7560 (if (org-at-heading-p)
7561 (progn
7562 (beginning-of-line 1)
7563 (setq org-goto-selected-point (point)
7564 org-goto-exit-command 'left)
7565 (throw 'exit nil))
7566 (user-error "Not on a heading")))
7568 (defun org-goto-right ()
7569 "Finish `org-goto' by going to the new location."
7570 (interactive)
7571 (if (org-at-heading-p)
7572 (progn
7573 (setq org-goto-selected-point (point)
7574 org-goto-exit-command 'right)
7575 (throw 'exit nil))
7576 (user-error "Not on a heading")))
7578 (defun org-goto-quit ()
7579 "Finish `org-goto' without cursor motion."
7580 (interactive)
7581 (setq org-goto-selected-point nil)
7582 (setq org-goto-exit-command 'quit)
7583 (throw 'exit nil))
7585 ;;; Indirect buffer display of subtrees
7587 (defvar org-indirect-dedicated-frame nil
7588 "This is the frame being used for indirect tree display.")
7589 (defvar org-last-indirect-buffer nil)
7591 (defun org-tree-to-indirect-buffer (&optional arg)
7592 "Create indirect buffer and narrow it to current subtree.
7594 With a numerical prefix ARG, go up to this level and then take that tree.
7595 If ARG is negative, go up that many levels.
7597 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7598 indirect buffer previously made with this command, to avoid proliferation of
7599 indirect buffers. However, when you call the command with a \
7600 `\\[universal-argument]' prefix, or
7601 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7602 so that you can work with several indirect buffers at the same time. If
7603 `org-indirect-buffer-display' is `dedicated-frame', the \
7604 `\\[universal-argument]' prefix also
7605 requests that a new frame be made for the new buffer, so that the dedicated
7606 frame is not changed."
7607 (interactive "P")
7608 (let ((cbuf (current-buffer))
7609 (cwin (selected-window))
7610 (pos (point))
7611 beg end level heading ibuf)
7612 (save-excursion
7613 (org-back-to-heading t)
7614 (when (numberp arg)
7615 (setq level (org-outline-level))
7616 (when (< arg 0) (setq arg (+ level arg)))
7617 (while (> (setq level (org-outline-level)) arg)
7618 (org-up-heading-safe)))
7619 (setq beg (point)
7620 heading (org-get-heading 'no-tags))
7621 (org-end-of-subtree t t)
7622 (when (org-at-heading-p) (backward-char 1))
7623 (setq end (point)))
7624 (when (and (buffer-live-p org-last-indirect-buffer)
7625 (not (eq org-indirect-buffer-display 'new-frame))
7626 (not arg))
7627 (kill-buffer org-last-indirect-buffer))
7628 (setq ibuf (org-get-indirect-buffer cbuf heading)
7629 org-last-indirect-buffer ibuf)
7630 (cond
7631 ((or (eq org-indirect-buffer-display 'new-frame)
7632 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7633 (select-frame (make-frame))
7634 (delete-other-windows)
7635 (pop-to-buffer-same-window ibuf)
7636 (org-set-frame-title heading))
7637 ((eq org-indirect-buffer-display 'dedicated-frame)
7638 (raise-frame
7639 (select-frame (or (and org-indirect-dedicated-frame
7640 (frame-live-p org-indirect-dedicated-frame)
7641 org-indirect-dedicated-frame)
7642 (setq org-indirect-dedicated-frame (make-frame)))))
7643 (delete-other-windows)
7644 (pop-to-buffer-same-window ibuf)
7645 (org-set-frame-title (concat "Indirect: " heading)))
7646 ((eq org-indirect-buffer-display 'current-window)
7647 (pop-to-buffer-same-window ibuf))
7648 ((eq org-indirect-buffer-display 'other-window)
7649 (pop-to-buffer ibuf))
7650 (t (error "Invalid value")))
7651 (narrow-to-region beg end)
7652 (outline-show-all)
7653 (goto-char pos)
7654 (run-hook-with-args 'org-cycle-hook 'all)
7655 (and (window-live-p cwin) (select-window cwin))))
7657 (defun org-get-indirect-buffer (&optional buffer heading)
7658 (setq buffer (or buffer (current-buffer)))
7659 (let ((n 1) (base (buffer-name buffer)) bname)
7660 (while (buffer-live-p
7661 (get-buffer
7662 (setq bname
7663 (concat base "-"
7664 (if heading (concat heading "-" (number-to-string n))
7665 (number-to-string n))))))
7666 (setq n (1+ n)))
7667 (condition-case nil
7668 (make-indirect-buffer buffer bname 'clone)
7669 (error (make-indirect-buffer buffer bname)))))
7671 (defun org-set-frame-title (title)
7672 "Set the title of the current frame to the string TITLE."
7673 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7675 ;;;; Structure editing
7677 ;;; Inserting headlines
7679 (defun org--line-empty-p (n)
7680 "Is the Nth next line empty?
7682 Counts the current line as N = 1 and the previous line as N = 0;
7683 see `beginning-of-line'."
7684 (save-excursion
7685 (and (not (bobp))
7686 (or (beginning-of-line n) t)
7687 (save-match-data
7688 (looking-at "[ \t]*$")))))
7690 (defun org-previous-line-empty-p ()
7691 "Is the previous line a blank line?
7692 When NEXT is non-nil, check the next line instead."
7693 (org--line-empty-p 0))
7695 (defun org-next-line-empty-p ()
7696 "Is the previous line a blank line?
7697 When NEXT is non-nil, check the next line instead."
7698 (org--line-empty-p 2))
7700 (defun org--blank-before-heading-p (&optional parent)
7701 "Non-nil when an empty line should precede a new heading here.
7702 When optional argument PARENT is non-nil, consider parent
7703 headline instead of current one."
7704 (pcase (assq 'heading org-blank-before-new-entry)
7705 (`(heading . auto)
7706 (save-excursion
7707 (org-with-limited-levels
7708 (unless (and (org-before-first-heading-p)
7709 (not (outline-next-heading)))
7710 (org-back-to-heading t)
7711 (when parent (org-up-heading-safe))
7712 (cond ((not (bobp))
7713 (org-previous-line-empty-p))
7714 ((outline-next-heading)
7715 (org-previous-line-empty-p))
7716 ;; Ignore trailing spaces on last buffer line.
7717 ((progn (skip-chars-backward " \t") (bolp))
7718 (org-previous-line-empty-p))
7719 (t nil))))))
7720 (`(heading . ,value) value)
7721 (_ nil)))
7723 (defun org-insert-heading (&optional arg invisible-ok top)
7724 "Insert a new heading or an item with the same depth at point.
7726 If point is at the beginning of a heading, insert a new heading
7727 or a new headline above the current one. When at the beginning
7728 of a regular line of text, turn it into a heading.
7730 If point is in the middle of a line, split it and create a new
7731 headline with the text in the current line after point (see
7732 `org-M-RET-may-split-line' on how to modify this behavior). As
7733 a special case, on a headline, splitting can only happen on the
7734 title itself. E.g., this excludes breaking stars or tags.
7736 With a `\\[universal-argument]' prefix, set \
7737 `org-insert-heading-respect-content' to
7738 a non-nil value for the duration of the command. This forces the
7739 insertion of a heading after the current subtree, independently
7740 on the location of point.
7742 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7743 insert the heading at the end of the tree
7744 above the current heading. For example, if point is within a
7745 2nd-level heading, then it will insert a 2nd-level heading at
7746 the end of the 1st-level parent subtree.
7748 When INVISIBLE-OK is set, stop at invisible headlines when going
7749 back. This is important for non-interactive uses of the
7750 command.
7752 When optional argument TOP is non-nil, insert a level 1 heading,
7753 unconditionally."
7754 (interactive "P")
7755 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7756 (level (org-current-level))
7757 (stars (make-string (if (and level (not top)) level 1) ?*)))
7758 (cond
7759 ((or org-insert-heading-respect-content
7760 (member arg '((4) (16)))
7761 (and (not invisible-ok)
7762 (invisible-p (max (1- (point)) (point-min)))))
7763 ;; Position point at the location of insertion.
7764 (if (not level) ;before first headline
7765 (org-with-limited-levels (outline-next-heading))
7766 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7767 ;; is nil.
7768 (org-with-limited-levels (org-back-to-heading invisible-ok))
7769 (cond ((equal arg '(16))
7770 (org-up-heading-safe)
7771 (org-end-of-subtree t t))
7773 (org-end-of-subtree t t))))
7774 (unless (bolp) (insert "\n")) ;ensure final newline
7775 (unless (and blank? (org-previous-line-empty-p))
7776 (org-N-empty-lines-before-current (if blank? 1 0)))
7777 (insert stars " \n")
7778 (forward-char -1))
7779 ;; At a headline...
7780 ((org-at-heading-p)
7781 (cond ((bolp)
7782 (when blank? (save-excursion (insert "\n")))
7783 (save-excursion (insert stars " \n"))
7784 (unless (and blank? (org-previous-line-empty-p))
7785 (org-N-empty-lines-before-current (if blank? 1 0)))
7786 (end-of-line))
7787 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7788 (org-match-line org-complex-heading-regexp)
7789 (org-pos-in-match-range (point) 4))
7790 ;; Grab the text that should moved to the new headline.
7791 ;; Preserve tags.
7792 (let ((split (delete-and-extract-region (point) (match-end 4))))
7793 (if (looking-at "[ \t]*$") (replace-match "")
7794 (org-set-tags nil t))
7795 (end-of-line)
7796 (when blank? (insert "\n"))
7797 (insert "\n" stars " ")
7798 (when (org-string-nw-p split) (insert split))
7799 (when (eobp) (save-excursion (insert "\n")))))
7801 (end-of-line)
7802 (when blank? (insert "\n"))
7803 (insert "\n" stars " ")
7804 (when (eobp) (save-excursion (insert "\n"))))))
7805 ;; On regular text, turn line into a headline or split, if
7806 ;; appropriate.
7807 ((bolp)
7808 (insert stars " ")
7809 (unless (and blank? (org-previous-line-empty-p))
7810 (org-N-empty-lines-before-current (if blank? 1 0))))
7812 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7813 (end-of-line))
7814 (insert "\n" stars " ")
7815 (unless (and blank? (org-previous-line-empty-p))
7816 (org-N-empty-lines-before-current (if blank? 1 0))))))
7817 (run-hooks 'org-insert-heading-hook))
7819 (defun org-N-empty-lines-before-current (n)
7820 "Make the number of empty lines before current exactly N.
7821 So this will delete or add empty lines."
7822 (let ((column (current-column)))
7823 (beginning-of-line)
7824 (unless (bobp)
7825 (let ((start (save-excursion
7826 (skip-chars-backward " \r\t\n")
7827 (line-end-position))))
7828 (delete-region start (line-end-position 0))))
7829 (insert (make-string n ?\n))
7830 (move-to-column column)))
7832 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7833 "Return the heading of the current entry, without the stars.
7834 When NO-TAGS is non-nil, don't include tags.
7835 When NO-TODO is non-nil, don't include TODO keywords.
7836 When NO-PRIORITY is non-nil, don't include priority cookie.
7837 When NO-COMMENT is non-nil, don't include COMMENT string."
7838 (save-excursion
7839 (org-back-to-heading t)
7840 (let ((case-fold-search nil))
7841 (looking-at org-complex-heading-regexp)
7842 (let ((todo (and (not no-todo) (match-string 2)))
7843 (priority (and (not no-priority) (match-string 3)))
7844 (headline (pcase (match-string 4)
7845 (`nil "")
7846 ((and (guard no-comment) h)
7847 (replace-regexp-in-string
7848 (eval-when-compile
7849 (format "\\`%s[ \t]+" org-comment-string))
7850 "" h))
7851 (h h)))
7852 (tags (and (not no-tags) (match-string 5))))
7853 (mapconcat #'identity
7854 (delq nil (list todo priority headline tags))
7855 " ")))))
7857 (defvar orgstruct-mode) ; defined below
7859 (defun org-heading-components ()
7860 "Return the components of the current heading.
7861 This is a list with the following elements:
7862 - the level as an integer
7863 - the reduced level, different if `org-odd-levels-only' is set.
7864 - the TODO keyword, or nil
7865 - the priority character, like ?A, or nil if no priority is given
7866 - the headline text itself, or the tags string if no headline text
7867 - the tags string, or nil."
7868 (save-excursion
7869 (org-back-to-heading t)
7870 (when (let (case-fold-search)
7871 (looking-at
7872 (if orgstruct-mode
7873 org-heading-regexp
7874 org-complex-heading-regexp)))
7875 (if orgstruct-mode
7876 (list (length (match-string 1))
7877 (org-reduced-level (length (match-string 1)))
7880 (match-string 2)
7881 nil)
7882 (list (length (match-string 1))
7883 (org-reduced-level (length (match-string 1)))
7884 (match-string-no-properties 2)
7885 (and (match-end 3) (aref (match-string 3) 2))
7886 (match-string-no-properties 4)
7887 (match-string-no-properties 5))))))
7889 (defun org-get-entry ()
7890 "Get the entry text, after heading, entire subtree."
7891 (save-excursion
7892 (org-back-to-heading t)
7893 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7895 (defun org-edit-headline (&optional heading)
7896 "Edit the current headline.
7897 Set it to HEADING when provided."
7898 (interactive)
7899 (org-with-wide-buffer
7900 (org-back-to-heading t)
7901 (let ((case-fold-search nil))
7902 (when (looking-at org-complex-heading-regexp)
7903 (let* ((old (match-string-no-properties 4))
7904 (new (save-match-data
7905 (org-trim (or heading (read-string "Edit: " old))))))
7906 (unless (equal old new)
7907 (if old (replace-match new t t nil 4)
7908 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7909 (insert " " new))
7910 (org-set-tags nil t)
7911 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7913 (defun org-insert-heading-after-current ()
7914 "Insert a new heading with same level as current, after current subtree."
7915 (interactive)
7916 (org-back-to-heading)
7917 (org-insert-heading)
7918 (org-move-subtree-down)
7919 (end-of-line 1))
7921 (defun org-insert-heading-respect-content (&optional invisible-ok)
7922 "Insert heading with `org-insert-heading-respect-content' set to t."
7923 (interactive)
7924 (org-insert-heading '(4) invisible-ok))
7926 (defun org-insert-todo-heading-respect-content (&optional force-state)
7927 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7928 (interactive)
7929 (org-insert-todo-heading force-state '(4)))
7931 (defun org-insert-todo-heading (arg &optional force-heading)
7932 "Insert a new heading with the same level and TODO state as current heading.
7934 If the heading has no TODO state, or if the state is DONE, use
7935 the first state (TODO by default). Also with one prefix arg,
7936 force first state. With two prefix args, force inserting at the
7937 end of the parent subtree.
7939 When called at a plain list item, insert a new item with an
7940 unchecked check box."
7941 (interactive "P")
7942 (when (or force-heading (not (org-insert-item 'checkbox)))
7943 (org-insert-heading (or (and (equal arg '(16)) '(16))
7944 force-heading))
7945 (save-excursion
7946 (org-back-to-heading)
7947 (outline-previous-heading)
7948 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7949 (let* ((new-mark-x
7950 (if (or (equal arg '(4))
7951 (not (match-beginning 2))
7952 (member (match-string 2) org-done-keywords))
7953 (car org-todo-keywords-1)
7954 (match-string 2)))
7955 (new-mark
7957 (run-hook-with-args-until-success
7958 'org-todo-get-default-hook new-mark-x nil)
7959 new-mark-x)))
7960 (beginning-of-line 1)
7961 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7962 (if org-treat-insert-todo-heading-as-state-change
7963 (org-todo new-mark)
7964 (insert new-mark " "))))
7965 (when org-provide-todo-statistics
7966 (org-update-parent-todo-statistics))))
7968 (defun org-insert-subheading (arg)
7969 "Insert a new subheading and demote it.
7970 Works for outline headings and for plain lists alike."
7971 (interactive "P")
7972 (org-insert-heading arg)
7973 (cond
7974 ((org-at-heading-p) (org-do-demote))
7975 ((org-at-item-p) (org-indent-item))))
7977 (defun org-insert-todo-subheading (arg)
7978 "Insert a new subheading with TODO keyword or checkbox and demote it.
7979 Works for outline headings and for plain lists alike."
7980 (interactive "P")
7981 (org-insert-todo-heading arg)
7982 (cond
7983 ((org-at-heading-p) (org-do-demote))
7984 ((org-at-item-p) (org-indent-item))))
7986 ;;; Promotion and Demotion
7988 (defvar org-after-demote-entry-hook nil
7989 "Hook run after an entry has been demoted.
7990 The cursor will be at the beginning of the entry.
7991 When a subtree is being demoted, the hook will be called for each node.")
7993 (defvar org-after-promote-entry-hook nil
7994 "Hook run after an entry has been promoted.
7995 The cursor will be at the beginning of the entry.
7996 When a subtree is being promoted, the hook will be called for each node.")
7998 (defun org-promote-subtree ()
7999 "Promote the entire subtree.
8000 See also `org-promote'."
8001 (interactive)
8002 (save-excursion
8003 (org-with-limited-levels (org-map-tree 'org-promote)))
8004 (org-fix-position-after-promote))
8006 (defun org-demote-subtree ()
8007 "Demote the entire subtree.
8008 See `org-demote' and `org-promote'."
8009 (interactive)
8010 (save-excursion
8011 (org-with-limited-levels (org-map-tree 'org-demote)))
8012 (org-fix-position-after-promote))
8014 (defun org-do-promote ()
8015 "Promote the current heading higher up the tree.
8016 If the region is active in `transient-mark-mode', promote all
8017 headings in the region."
8018 (interactive)
8019 (save-excursion
8020 (if (org-region-active-p)
8021 (org-map-region 'org-promote (region-beginning) (region-end))
8022 (org-promote)))
8023 (org-fix-position-after-promote))
8025 (defun org-do-demote ()
8026 "Demote the current heading lower down the tree.
8027 If the region is active in `transient-mark-mode', demote all
8028 headings in the region."
8029 (interactive)
8030 (save-excursion
8031 (if (org-region-active-p)
8032 (org-map-region 'org-demote (region-beginning) (region-end))
8033 (org-demote)))
8034 (org-fix-position-after-promote))
8036 (defun org-fix-position-after-promote ()
8037 "Fix cursor position and indentation after demoting/promoting."
8038 (let ((pos (point)))
8039 (when (save-excursion
8040 (beginning-of-line)
8041 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8042 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8043 (cond ((eobp) (insert " "))
8044 ((eolp) (insert " "))
8045 ((equal (char-after) ?\s) (forward-char 1))))))
8047 (defun org-current-level ()
8048 "Return the level of the current entry, or nil if before the first headline.
8049 The level is the number of stars at the beginning of the
8050 headline. Use `org-reduced-level' to remove the effect of
8051 `org-odd-levels'. Unlike to `org-outline-level', this function
8052 ignores inlinetasks."
8053 (let ((level (org-with-limited-levels (org-outline-level))))
8054 (and (> level 0) level)))
8056 (defun org-get-previous-line-level ()
8057 "Return the outline depth of the last headline before the current line.
8058 Returns 0 for the first headline in the buffer, and nil if before the
8059 first headline."
8060 (and (org-current-level)
8061 (or (and (/= (line-beginning-position) (point-min))
8062 (save-excursion (beginning-of-line 0) (org-current-level)))
8063 0)))
8065 (defun org-reduced-level (l)
8066 "Compute the effective level of a heading.
8067 This takes into account the setting of `org-odd-levels-only'."
8068 (cond
8069 ((zerop l) 0)
8070 (org-odd-levels-only (1+ (floor (/ l 2))))
8071 (t l)))
8073 (defun org-level-increment ()
8074 "Return the number of stars that will be added or removed at a
8075 time to headlines when structure editing, based on the value of
8076 `org-odd-levels-only'."
8077 (if org-odd-levels-only 2 1))
8079 (defun org-get-valid-level (level &optional change)
8080 "Rectify a level change under the influence of `org-odd-levels-only'.
8081 LEVEL is a current level, CHANGE is by how much the level should
8082 be modified. Even if CHANGE is nil, LEVEL may be returned
8083 modified because even level numbers will become the next higher
8084 odd number. Returns values greater than 0."
8085 (if org-odd-levels-only
8086 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8087 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8088 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8089 (max 1 (+ level (or change 0)))))
8091 (defun org-promote ()
8092 "Promote the current heading higher up the tree."
8093 (org-with-wide-buffer
8094 (org-back-to-heading t)
8095 (let* ((after-change-functions (remq 'flyspell-after-change-function
8096 after-change-functions))
8097 (level (save-match-data (funcall outline-level)))
8098 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8099 (diff (abs (- level (length up-head) -1))))
8100 (cond
8101 ((and (= level 1) org-allow-promoting-top-level-subtree)
8102 (replace-match "# " nil t))
8103 ((= level 1)
8104 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8105 (t (replace-match up-head nil t)))
8106 (unless (= level 1)
8107 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8108 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8109 (run-hooks 'org-after-promote-entry-hook))))
8111 (defun org-demote ()
8112 "Demote the current heading lower down the tree."
8113 (org-with-wide-buffer
8114 (org-back-to-heading t)
8115 (let* ((after-change-functions (remq 'flyspell-after-change-function
8116 after-change-functions))
8117 (level (save-match-data (funcall outline-level)))
8118 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8119 (diff (abs (- level (length down-head) -1))))
8120 (replace-match down-head nil t)
8121 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8122 (when org-adapt-indentation (org-fixup-indentation diff))
8123 (run-hooks 'org-after-demote-entry-hook))))
8125 (defun org-cycle-level ()
8126 "Cycle the level of an empty headline through possible states.
8127 This goes first to child, then to parent, level, then up the hierarchy.
8128 After top level, it switches back to sibling level."
8129 (interactive)
8130 (let ((org-adapt-indentation nil))
8131 (when (org-point-at-end-of-empty-headline)
8132 (setq this-command 'org-cycle-level) ; Only needed for caching
8133 (let ((cur-level (org-current-level))
8134 (prev-level (org-get-previous-line-level)))
8135 (cond
8136 ;; If first headline in file, promote to top-level.
8137 ((= prev-level 0)
8138 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8139 do (org-do-promote)))
8140 ;; If same level as prev, demote one.
8141 ((= prev-level cur-level)
8142 (org-do-demote))
8143 ;; If parent is top-level, promote to top level if not already.
8144 ((= prev-level 1)
8145 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8146 do (org-do-promote)))
8147 ;; If top-level, return to prev-level.
8148 ((= cur-level 1)
8149 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8150 do (org-do-demote)))
8151 ;; If less than prev-level, promote one.
8152 ((< cur-level prev-level)
8153 (org-do-promote))
8154 ;; If deeper than prev-level, promote until higher than
8155 ;; prev-level.
8156 ((> cur-level prev-level)
8157 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8158 do (org-do-promote))))
8159 t))))
8161 (defun org-map-tree (fun)
8162 "Call FUN for every heading underneath the current one."
8163 (org-back-to-heading t)
8164 (let ((level (funcall outline-level)))
8165 (save-excursion
8166 (funcall fun)
8167 (while (and (progn
8168 (outline-next-heading)
8169 (> (funcall outline-level) level))
8170 (not (eobp)))
8171 (funcall fun)))))
8173 (defun org-map-region (fun beg end)
8174 "Call FUN for every heading between BEG and END."
8175 (let ((org-ignore-region t))
8176 (save-excursion
8177 (setq end (copy-marker end))
8178 (goto-char beg)
8179 (when (and (re-search-forward org-outline-regexp-bol nil t)
8180 (< (point) end))
8181 (funcall fun))
8182 (while (and (progn
8183 (outline-next-heading)
8184 (< (point) end))
8185 (not (eobp)))
8186 (funcall fun)))))
8188 (defun org-fixup-indentation (diff)
8189 "Change the indentation in the current entry by DIFF.
8191 DIFF is an integer. Indentation is done according to the
8192 following rules:
8194 - Planning information and property drawers are always indented
8195 according to the new level of the headline;
8197 - Footnote definitions and their contents are ignored;
8199 - Inlinetasks' boundaries are not shifted;
8201 - Empty lines are ignored;
8203 - Other lines' indentation are shifted by DIFF columns, unless
8204 it would introduce a structural change in the document, in
8205 which case no shifting is done at all.
8207 Assume point is at a heading or an inlinetask beginning."
8208 (org-with-wide-buffer
8209 (narrow-to-region (line-beginning-position)
8210 (save-excursion
8211 (if (org-with-limited-levels (org-at-heading-p))
8212 (org-with-limited-levels (outline-next-heading))
8213 (org-inlinetask-goto-end))
8214 (point)))
8215 (forward-line)
8216 ;; Indent properly planning info and property drawer.
8217 (when (looking-at-p org-planning-line-re)
8218 (org-indent-line)
8219 (forward-line))
8220 (when (looking-at org-property-drawer-re)
8221 (goto-char (match-end 0))
8222 (forward-line)
8223 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8224 (catch 'no-shift
8225 (when (zerop diff) (throw 'no-shift nil))
8226 ;; If DIFF is negative, first check if a shift is possible at all
8227 ;; (e.g., it doesn't break structure). This can only happen if
8228 ;; some contents are not properly indented.
8229 (let ((case-fold-search t))
8230 (when (< diff 0)
8231 (let ((diff (- diff))
8232 (forbidden-re (concat org-outline-regexp
8233 "\\|"
8234 (substring org-footnote-definition-re 1))))
8235 (save-excursion
8236 (while (not (eobp))
8237 (cond
8238 ((looking-at-p "[ \t]*$") (forward-line))
8239 ((and (looking-at-p org-footnote-definition-re)
8240 (let ((e (org-element-at-point)))
8241 (and (eq (org-element-type e) 'footnote-definition)
8242 (goto-char (org-element-property :end e))))))
8243 ((looking-at-p org-outline-regexp) (forward-line))
8244 ;; Give up if shifting would move before column 0 or
8245 ;; if it would introduce a headline or a footnote
8246 ;; definition.
8248 (skip-chars-forward " \t")
8249 (let ((ind (current-column)))
8250 (when (or (< ind diff)
8251 (and (= ind diff) (looking-at-p forbidden-re)))
8252 (throw 'no-shift nil)))
8253 ;; Ignore contents of example blocks and source
8254 ;; blocks if their indentation is meant to be
8255 ;; preserved. Jump to block's closing line.
8256 (beginning-of-line)
8257 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8258 (let ((e (org-element-at-point)))
8259 (and (memq (org-element-type e)
8260 '(example-block src-block))
8261 (or org-src-preserve-indentation
8262 (org-element-property :preserve-indent e))
8263 (goto-char (org-element-property :end e))
8264 (progn (skip-chars-backward " \r\t\n")
8265 (beginning-of-line)
8266 t))))
8267 (forward-line))))))))
8268 ;; Shift lines but footnote definitions, inlinetasks boundaries
8269 ;; by DIFF. Also skip contents of source or example blocks
8270 ;; when indentation is meant to be preserved.
8271 (while (not (eobp))
8272 (cond
8273 ((and (looking-at-p org-footnote-definition-re)
8274 (let ((e (org-element-at-point)))
8275 (and (eq (org-element-type e) 'footnote-definition)
8276 (goto-char (org-element-property :end e))))))
8277 ((looking-at-p org-outline-regexp) (forward-line))
8278 ((looking-at-p "[ \t]*$") (forward-line))
8280 (indent-line-to (+ (org-get-indentation) diff))
8281 (beginning-of-line)
8282 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8283 (let ((e (org-element-at-point)))
8284 (and (memq (org-element-type e)
8285 '(example-block src-block))
8286 (or org-src-preserve-indentation
8287 (org-element-property :preserve-indent e))
8288 (goto-char (org-element-property :end e))
8289 (progn (skip-chars-backward " \r\t\n")
8290 (beginning-of-line)
8291 t))))
8292 (forward-line)))))))))
8294 (defun org-convert-to-odd-levels ()
8295 "Convert an Org file with all levels allowed to one with odd levels.
8296 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8297 level 5 etc."
8298 (interactive)
8299 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8300 (let ((outline-level 'org-outline-level)
8301 (org-odd-levels-only nil) n)
8302 (save-excursion
8303 (goto-char (point-min))
8304 (while (re-search-forward "^\\*\\*+ " nil t)
8305 (setq n (- (length (match-string 0)) 2))
8306 (while (>= (setq n (1- n)) 0)
8307 (org-demote))
8308 (end-of-line 1))))))
8310 (defun org-convert-to-oddeven-levels ()
8311 "Convert an Org file with only odd levels to one with odd/even levels.
8312 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8313 file contains a section with an even level, conversion would
8314 destroy the structure of the file. An error is signaled in this
8315 case."
8316 (interactive)
8317 (goto-char (point-min))
8318 ;; First check if there are no even levels
8319 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8320 (org-show-set-visibility 'canonical)
8321 (error "Not all levels are odd in this file. Conversion not possible"))
8322 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8323 (let ((outline-regexp org-outline-regexp)
8324 (outline-level 'org-outline-level)
8325 (org-odd-levels-only nil) n)
8326 (save-excursion
8327 (goto-char (point-min))
8328 (while (re-search-forward "^\\*\\*+ " nil t)
8329 (setq n (/ (1- (length (match-string 0))) 2))
8330 (while (>= (setq n (1- n)) 0)
8331 (org-promote))
8332 (end-of-line 1))))))
8334 (defun org-tr-level (n)
8335 "Make N odd if required."
8336 (if org-odd-levels-only (1+ (/ n 2)) n))
8338 ;;; Vertical tree motion, cutting and pasting of subtrees
8340 (defun org-move-subtree-up (&optional arg)
8341 "Move the current subtree up past ARG headlines of the same level."
8342 (interactive "p")
8343 (org-move-subtree-down (- (prefix-numeric-value arg))))
8345 (defun org-move-subtree-down (&optional arg)
8346 "Move the current subtree down past ARG headlines of the same level."
8347 (interactive "p")
8348 (setq arg (prefix-numeric-value arg))
8349 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8350 'org-get-last-sibling))
8351 (ins-point (make-marker))
8352 (cnt (abs arg))
8353 (col (current-column))
8354 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8355 ;; Select the tree
8356 (org-back-to-heading)
8357 (setq beg0 (point))
8358 (save-excursion
8359 (setq ne-beg (org-back-over-empty-lines))
8360 (setq beg (point)))
8361 (save-match-data
8362 (save-excursion (outline-end-of-heading)
8363 (setq folded (org-invisible-p)))
8364 (progn (org-end-of-subtree nil t)
8365 (unless (eobp) (backward-char))))
8366 (outline-next-heading)
8367 (setq ne-end (org-back-over-empty-lines))
8368 (setq end (point))
8369 (goto-char beg0)
8370 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8371 ;; include less whitespace
8372 (save-excursion
8373 (goto-char beg)
8374 (forward-line (- ne-beg ne-end))
8375 (setq beg (point))))
8376 ;; Find insertion point, with error handling
8377 (while (> cnt 0)
8378 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8379 (progn (goto-char beg0)
8380 (user-error "Cannot move past superior level or buffer limit")))
8381 (setq cnt (1- cnt)))
8382 (when (> arg 0)
8383 ;; Moving forward - still need to move over subtree
8384 (org-end-of-subtree t t)
8385 (save-excursion
8386 (org-back-over-empty-lines)
8387 (or (bolp) (newline))))
8388 (setq ne-ins (org-back-over-empty-lines))
8389 (move-marker ins-point (point))
8390 (setq txt (buffer-substring beg end))
8391 (org-save-markers-in-region beg end)
8392 (delete-region beg end)
8393 (org-remove-empty-overlays-at beg)
8394 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8395 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8396 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8397 (let ((bbb (point)))
8398 (insert-before-markers txt)
8399 (org-reinstall-markers-in-region bbb)
8400 (move-marker ins-point bbb))
8401 (or (bolp) (insert "\n"))
8402 (setq ins-end (point))
8403 (goto-char ins-point)
8404 (org-skip-whitespace)
8405 (when (and (< arg 0)
8406 (org-first-sibling-p)
8407 (> ne-ins ne-beg))
8408 ;; Move whitespace back to beginning
8409 (save-excursion
8410 (goto-char ins-end)
8411 (let ((kill-whole-line t))
8412 (kill-line (- ne-ins ne-beg)) (point)))
8413 (insert (make-string (- ne-ins ne-beg) ?\n)))
8414 (move-marker ins-point nil)
8415 (if folded
8416 (outline-hide-subtree)
8417 (org-show-entry)
8418 (org-show-children)
8419 (org-cycle-hide-drawers 'children))
8420 (org-clean-visibility-after-subtree-move)
8421 ;; move back to the initial column we were at
8422 (move-to-column col)))
8424 (defvar org-subtree-clip ""
8425 "Clipboard for cut and paste of subtrees.
8426 This is actually only a copy of the kill, because we use the normal kill
8427 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8429 (defvar org-subtree-clip-folded nil
8430 "Was the last copied subtree folded?
8431 This is used to fold the tree back after pasting.")
8433 (defun org-cut-subtree (&optional n)
8434 "Cut the current subtree into the clipboard.
8435 With prefix arg N, cut this many sequential subtrees.
8436 This is a short-hand for marking the subtree and then cutting it."
8437 (interactive "p")
8438 (org-copy-subtree n 'cut))
8440 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8441 "Copy the current subtree it in the clipboard.
8442 With prefix arg N, copy this many sequential subtrees.
8443 This is a short-hand for marking the subtree and then copying it.
8444 If CUT is non-nil, actually cut the subtree.
8445 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8446 of some markers in the region, even if CUT is non-nil. This is
8447 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8448 (interactive "p")
8449 (let (beg end folded (beg0 (point)))
8450 (if (called-interactively-p 'any)
8451 (org-back-to-heading nil) ; take what looks like a subtree
8452 (org-back-to-heading t)) ; take what is really there
8453 (setq beg (point))
8454 (skip-chars-forward " \t\r\n")
8455 (save-match-data
8456 (if nosubtrees
8457 (outline-next-heading)
8458 (save-excursion (outline-end-of-heading)
8459 (setq folded (org-invisible-p)))
8460 (ignore-errors (org-forward-heading-same-level (1- n) t))
8461 (org-end-of-subtree t t)))
8462 ;; Include the end of an inlinetask
8463 (when (and (featurep 'org-inlinetask)
8464 (looking-at-p (concat (org-inlinetask-outline-regexp)
8465 "END[ \t]*$")))
8466 (end-of-line))
8467 (setq end (point))
8468 (goto-char beg0)
8469 (when (> end beg)
8470 (setq org-subtree-clip-folded folded)
8471 (when (or cut force-store-markers)
8472 (org-save-markers-in-region beg end))
8473 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8474 (setq org-subtree-clip (current-kill 0))
8475 (message "%s: Subtree(s) with %d characters"
8476 (if cut "Cut" "Copied")
8477 (length org-subtree-clip)))))
8479 (defun org-paste-subtree (&optional level tree for-yank remove)
8480 "Paste the clipboard as a subtree, with modification of headline level.
8481 The entire subtree is promoted or demoted in order to match a new headline
8482 level.
8484 If the cursor is at the beginning of a headline, the same level as
8485 that headline is used to paste the tree.
8487 If not, the new level is derived from the *visible* headings
8488 before and after the insertion point, and taken to be the inferior headline
8489 level of the two. So if the previous visible heading is level 3 and the
8490 next is level 4 (or vice versa), level 4 will be used for insertion.
8491 This makes sure that the subtree remains an independent subtree and does
8492 not swallow low level entries.
8494 You can also force a different level, either by using a numeric prefix
8495 argument, or by inserting the heading marker by hand. For example, if the
8496 cursor is after \"*****\", then the tree will be shifted to level 5.
8498 If optional TREE is given, use this text instead of the kill ring.
8500 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8501 move back over whitespace before inserting, and move point to the end of
8502 the inserted text when done.
8504 When REMOVE is non-nil, remove the subtree from the clipboard."
8505 (interactive "P")
8506 (setq tree (or tree (and kill-ring (current-kill 0))))
8507 (unless (org-kill-is-subtree-p tree)
8508 (user-error "%s"
8509 (substitute-command-keys
8510 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8511 (org-with-limited-levels
8512 (let* ((visp (not (org-invisible-p)))
8513 (txt tree)
8514 (^re_ "\\(\\*+\\)[ \t]*")
8515 (old-level (if (string-match org-outline-regexp-bol txt)
8516 (- (match-end 0) (match-beginning 0) 1)
8517 -1))
8518 (force-level (cond (level (prefix-numeric-value level))
8519 ((and (looking-at "[ \t]*$")
8520 (string-match
8521 "^\\*+$" (buffer-substring
8522 (point-at-bol) (point))))
8523 (- (match-end 0) (match-beginning 0)))
8524 ((and (bolp)
8525 (looking-at org-outline-regexp))
8526 (- (match-end 0) (point) 1))))
8527 (previous-level (save-excursion
8528 (condition-case nil
8529 (progn
8530 (outline-previous-visible-heading 1)
8531 (if (looking-at ^re_)
8532 (- (match-end 0) (match-beginning 0) 1)
8534 (error 1))))
8535 (next-level (save-excursion
8536 (condition-case nil
8537 (progn
8538 (or (looking-at org-outline-regexp)
8539 (outline-next-visible-heading 1))
8540 (if (looking-at ^re_)
8541 (- (match-end 0) (match-beginning 0) 1)
8543 (error 1))))
8544 (new-level (or force-level (max previous-level next-level)))
8545 (shift (if (or (= old-level -1)
8546 (= new-level -1)
8547 (= old-level new-level))
8549 (- new-level old-level)))
8550 (delta (if (> shift 0) -1 1))
8551 (func (if (> shift 0) 'org-demote 'org-promote))
8552 (org-odd-levels-only nil)
8553 beg end newend)
8554 ;; Remove the forced level indicator
8555 (when force-level
8556 (delete-region (point-at-bol) (point)))
8557 ;; Paste
8558 (beginning-of-line (if (bolp) 1 2))
8559 (setq beg (point))
8560 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8561 (insert-before-markers txt)
8562 (unless (string-suffix-p "\n" txt) (insert "\n"))
8563 (setq newend (point))
8564 (org-reinstall-markers-in-region beg)
8565 (setq end (point))
8566 (goto-char beg)
8567 (skip-chars-forward " \t\n\r")
8568 (setq beg (point))
8569 (when (and (org-invisible-p) visp)
8570 (save-excursion (outline-show-heading)))
8571 ;; Shift if necessary
8572 (unless (= shift 0)
8573 (save-restriction
8574 (narrow-to-region beg end)
8575 (while (not (= shift 0))
8576 (org-map-region func (point-min) (point-max))
8577 (setq shift (+ delta shift)))
8578 (goto-char (point-min))
8579 (setq newend (point-max))))
8580 (when (or (called-interactively-p 'interactive) for-yank)
8581 (message "Clipboard pasted as level %d subtree" new-level))
8582 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8583 kill-ring
8584 (eq org-subtree-clip (current-kill 0))
8585 org-subtree-clip-folded)
8586 ;; The tree was folded before it was killed/copied
8587 (outline-hide-subtree))
8588 (and for-yank (goto-char newend))
8589 (and remove (setq kill-ring (cdr kill-ring))))))
8591 (defun org-kill-is-subtree-p (&optional txt)
8592 "Check if the current kill is an outline subtree, or a set of trees.
8593 Returns nil if kill does not start with a headline, or if the first
8594 headline level is not the largest headline level in the tree.
8595 So this will actually accept several entries of equal levels as well,
8596 which is OK for `org-paste-subtree'.
8597 If optional TXT is given, check this string instead of the current kill."
8598 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8599 (re (org-get-limited-outline-regexp))
8600 (^re (concat "^" re))
8601 (start-level (and kill
8602 (string-match
8603 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8604 kill)
8605 (- (match-end 2) (match-beginning 2) 1)))
8606 (start (1+ (or (match-beginning 2) -1))))
8607 (if (not start-level)
8608 (progn
8609 nil) ;; does not even start with a heading
8610 (catch 'exit
8611 (while (setq start (string-match ^re kill (1+ start)))
8612 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8613 (throw 'exit nil)))
8614 t))))
8616 (defvar org-markers-to-move nil
8617 "Markers that should be moved with a cut-and-paste operation.
8618 Those markers are stored together with their positions relative to
8619 the start of the region.")
8621 (defun org-save-markers-in-region (beg end)
8622 "Check markers in region.
8623 If these markers are between BEG and END, record their position relative
8624 to BEG, so that after moving the block of text, we can put the markers back
8625 into place.
8626 This function gets called just before an entry or tree gets cut from the
8627 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8628 called immediately, to move the markers with the entries."
8629 (setq org-markers-to-move nil)
8630 (when (featurep 'org-clock)
8631 (org-clock-save-markers-for-cut-and-paste beg end))
8632 (when (featurep 'org-agenda)
8633 (org-agenda-save-markers-for-cut-and-paste beg end)))
8635 (defun org-check-and-save-marker (marker beg end)
8636 "Check if MARKER is between BEG and END.
8637 If yes, remember the marker and the distance to BEG."
8638 (when (and (marker-buffer marker)
8639 (equal (marker-buffer marker) (current-buffer))
8640 (>= marker beg) (< marker end))
8641 (push (cons marker (- marker beg)) org-markers-to-move)))
8643 (defun org-reinstall-markers-in-region (beg)
8644 "Move all remembered markers to their position relative to BEG."
8645 (dolist (x org-markers-to-move)
8646 (move-marker (car x) (+ beg (cdr x))))
8647 (setq org-markers-to-move nil))
8649 (defun org-narrow-to-subtree ()
8650 "Narrow buffer to the current subtree."
8651 (interactive)
8652 (save-excursion
8653 (save-match-data
8654 (org-with-limited-levels
8655 (narrow-to-region
8656 (progn (org-back-to-heading t) (point))
8657 (progn (org-end-of-subtree t t)
8658 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8659 (point)))))))
8661 (defun org-narrow-to-block ()
8662 "Narrow buffer to the current block."
8663 (interactive)
8664 (let* ((case-fold-search t)
8665 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8666 "^[ \t]*#\\+end_.*")))
8667 (if blockp
8668 (narrow-to-region (car blockp) (cdr blockp))
8669 (user-error "Not in a block"))))
8671 (defun org-clone-subtree-with-time-shift (n &optional shift)
8672 "Clone the task (subtree) at point N times.
8673 The clones will be inserted as siblings.
8675 In interactive use, the user will be prompted for the number of
8676 clones to be produced. If the entry has a timestamp, the user
8677 will also be prompted for a time shift, which may be a repeater
8678 as used in time stamps, for example `+3d'. To disable this,
8679 you can call the function with a universal prefix argument.
8681 When a valid repeater is given and the entry contains any time
8682 stamps, the clones will become a sequence in time, with time
8683 stamps in the subtree shifted for each clone produced. If SHIFT
8684 is nil or the empty string, time stamps will be left alone. The
8685 ID property of the original subtree is removed.
8687 In each clone, all the CLOCK entries will be removed. This
8688 prevents Org from considering that the clocked times overlap.
8690 If the original subtree did contain time stamps with a repeater,
8691 the following will happen:
8692 - the repeater will be removed in each clone
8693 - an additional clone will be produced, with the current, unshifted
8694 date(s) in the entry.
8695 - the original entry will be placed *after* all the clones, with
8696 repeater intact.
8697 - the start days in the repeater in the original entry will be shifted
8698 to past the last clone.
8699 In this way you can spell out a number of instances of a repeating task,
8700 and still retain the repeater to cover future instances of the task.
8702 As described above, N+1 clones are produced when the original
8703 subtree has a repeater. Setting N to 0, then, can be used to
8704 remove the repeater from a subtree and create a shifted clone
8705 with the original repeater."
8706 (interactive "nNumber of clones to produce: ")
8707 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8708 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8709 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8710 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8711 (shift
8712 (or shift
8713 (if (and (not (equal current-prefix-arg '(4)))
8714 (save-excursion
8715 (goto-char beg)
8716 (re-search-forward org-ts-regexp-both end-of-tree t)))
8717 (read-from-minibuffer
8718 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8719 ""))) ;No time shift
8720 (doshift
8721 (and (org-string-nw-p shift)
8722 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8723 shift)
8724 (user-error "Invalid shift specification %s" shift)))))
8725 (goto-char end-of-tree)
8726 (unless (bolp) (insert "\n"))
8727 (let* ((end (point))
8728 (template (buffer-substring beg end))
8729 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8730 (shift-what (pcase (and doshift (match-string 2 shift))
8731 (`nil nil)
8732 ("d" 'day)
8733 ("w" (setq shift-n (* 7 shift-n)) 'day)
8734 ("m" 'month)
8735 ("y" 'year)
8736 (_ (error "Unsupported time unit"))))
8737 (nmin 1)
8738 (nmax n)
8739 (n-no-remove -1)
8740 (idprop (org-entry-get nil "ID")))
8741 (when (and doshift
8742 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8743 template))
8744 (delete-region beg end)
8745 (setq end beg)
8746 (setq nmin 0)
8747 (setq nmax (1+ nmax))
8748 (setq n-no-remove nmax))
8749 (goto-char end)
8750 (cl-loop for n from nmin to nmax do
8751 (insert
8752 ;; Prepare clone.
8753 (with-temp-buffer
8754 (insert template)
8755 (org-mode)
8756 (goto-char (point-min))
8757 (org-show-subtree)
8758 (and idprop (if org-clone-delete-id
8759 (org-entry-delete nil "ID")
8760 (org-id-get-create t)))
8761 (unless (= n 0)
8762 (while (re-search-forward org-clock-line-re nil t)
8763 (delete-region (line-beginning-position)
8764 (line-beginning-position 2)))
8765 (goto-char (point-min))
8766 (while (re-search-forward org-drawer-regexp nil t)
8767 (org-remove-empty-drawer-at (point))))
8768 (goto-char (point-min))
8769 (when doshift
8770 (while (re-search-forward org-ts-regexp-both nil t)
8771 (org-timestamp-change (* n shift-n) shift-what))
8772 (unless (= n n-no-remove)
8773 (goto-char (point-min))
8774 (while (re-search-forward org-ts-regexp nil t)
8775 (save-excursion
8776 (goto-char (match-beginning 0))
8777 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8778 (delete-region (match-beginning 1) (match-end 1)))))))
8779 (buffer-string)))))
8780 (goto-char beg)))
8782 ;;; Outline Sorting
8784 (defun org-sort (&optional with-case)
8785 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8786 Optional argument WITH-CASE means sort case-sensitively."
8787 (interactive "P")
8788 (org-call-with-arg
8789 (cond ((org-at-table-p) #'org-table-sort-lines)
8790 ((org-at-item-p) #'org-sort-list)
8791 (t #'org-sort-entries))
8792 with-case))
8794 (defun org-sort-remove-invisible (s)
8795 "Remove invisible part of links and emphasis markers from string S."
8796 (remove-text-properties 0 (length s) org-rm-props s)
8797 (replace-regexp-in-string
8798 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8799 (replace-regexp-in-string
8800 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8801 (org-link-display-format s)
8802 t t) t t))
8804 (defvar org-priority-regexp) ; defined later in the file
8806 (defvar org-after-sorting-entries-or-items-hook nil
8807 "Hook that is run after a bunch of entries or items have been sorted.
8808 When children are sorted, the cursor is in the parent line when this
8809 hook gets called. When a region or a plain list is sorted, the cursor
8810 will be in the first entry of the sorted region/list.")
8812 (defun org-sort-entries
8813 (&optional with-case sorting-type getkey-func compare-func property
8814 interactive?)
8815 "Sort entries on a certain level of an outline tree.
8816 If there is an active region, the entries in the region are sorted.
8817 Else, if the cursor is before the first entry, sort the top-level items.
8818 Else, the children of the entry at point are sorted.
8820 Sorting can be alphabetically, numerically, by date/time as given by
8821 a time stamp, by a property, by priority order, or by a custom function.
8823 The command prompts for the sorting type unless it has been given to the
8824 function through the SORTING-TYPE argument, which needs to be a character,
8825 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8826 the precise meaning of each character:
8828 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8829 c By creation time, which is assumed to be the first inactive time stamp
8830 at the beginning of a line.
8831 d By deadline date/time.
8832 k By clocking time.
8833 n Numerically, by converting the beginning of the entry/item to a number.
8834 o By order of TODO keywords.
8835 p By priority according to the cookie.
8836 r By the value of a property.
8837 s By scheduled date/time.
8838 t By date/time, either the first active time stamp in the entry, or, if
8839 none exist, by the first inactive one.
8841 Capital letters will reverse the sort order.
8843 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8844 called with point at the beginning of the record. It must return a
8845 value that is compatible with COMPARE-FUNC, the function used to
8846 compare entries.
8848 Comparing entries ignores case by default. However, with an optional argument
8849 WITH-CASE, the sorting considers case as well.
8851 Sorting is done against the visible part of the headlines, it ignores hidden
8852 links.
8854 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8856 A non-nil value for INTERACTIVE? is used to signal that this
8857 function is being called interactively."
8858 (interactive (list current-prefix-arg nil nil nil nil t))
8859 (let ((case-func (if with-case 'identity 'downcase))
8860 start beg end stars re re2
8861 txt what tmp)
8862 ;; Find beginning and end of region to sort
8863 (cond
8864 ((org-region-active-p)
8865 ;; we will sort the region
8866 (setq end (region-end)
8867 what "region")
8868 (goto-char (region-beginning))
8869 (unless (org-at-heading-p) (outline-next-heading))
8870 (setq start (point)))
8871 ((or (org-at-heading-p)
8872 (ignore-errors (progn (org-back-to-heading) t)))
8873 ;; we will sort the children of the current headline
8874 (org-back-to-heading)
8875 (setq start (point)
8876 end (progn (org-end-of-subtree t t)
8877 (or (bolp) (insert "\n"))
8878 (when (>= (org-back-over-empty-lines) 1)
8879 (forward-line 1))
8880 (point))
8881 what "children")
8882 (goto-char start)
8883 (outline-show-subtree)
8884 (outline-next-heading))
8886 ;; we will sort the top-level entries in this file
8887 (goto-char (point-min))
8888 (or (org-at-heading-p) (outline-next-heading))
8889 (setq start (point))
8890 (goto-char (point-max))
8891 (beginning-of-line 1)
8892 (when (looking-at ".*?\\S-")
8893 ;; File ends in a non-white line
8894 (end-of-line 1)
8895 (insert "\n"))
8896 (setq end (point-max))
8897 (setq what "top-level")
8898 (goto-char start)
8899 (outline-show-all)))
8901 (setq beg (point))
8902 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8904 (looking-at "\\(\\*+\\)")
8905 (setq stars (match-string 1)
8906 re (concat "^" (regexp-quote stars) " +")
8907 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8908 txt (buffer-substring beg end))
8909 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8910 (when (and (not (equal stars "*")) (string-match re2 txt))
8911 (user-error "Region to sort contains a level above the first entry"))
8913 (unless sorting-type
8914 (message
8915 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8916 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8917 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8918 what)
8919 (setq sorting-type (read-char-exclusive)))
8921 (unless getkey-func
8922 (and (= (downcase sorting-type) ?f)
8923 (setq getkey-func
8924 (or (and interactive?
8925 (org-read-function
8926 "Function for extracting keys: "))
8927 (error "Missing key extractor")))))
8929 (and (= (downcase sorting-type) ?r)
8930 (not property)
8931 (setq property
8932 (completing-read "Property: "
8933 (mapcar #'list (org-buffer-property-keys t))
8934 nil t)))
8936 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8937 (message "Sorting entries...")
8939 (save-restriction
8940 (narrow-to-region start end)
8941 (let ((restore-clock?
8942 ;; The clock marker is lost when using `sort-subr'; mark
8943 ;; the clock with temporary `:org-clock-marker-backup'
8944 ;; text property.
8945 (when (and (eq (org-clock-is-active) (current-buffer))
8946 (<= start (marker-position org-clock-marker))
8947 (>= end (marker-position org-clock-marker)))
8948 (org-with-silent-modifications
8949 (put-text-property (1- org-clock-marker) org-clock-marker
8950 :org-clock-marker-backup t))
8952 (dcst (downcase sorting-type))
8953 (case-fold-search nil)
8954 (now (current-time)))
8955 (sort-subr
8956 (/= dcst sorting-type)
8957 ;; This function moves to the beginning character of the "record" to
8958 ;; be sorted.
8959 (lambda nil
8960 (if (re-search-forward re nil t)
8961 (goto-char (match-beginning 0))
8962 (goto-char (point-max))))
8963 ;; This function moves to the last character of the "record" being
8964 ;; sorted.
8965 (lambda nil
8966 (save-match-data
8967 (condition-case nil
8968 (outline-forward-same-level 1)
8969 (error
8970 (goto-char (point-max))))))
8971 ;; This function returns the value that gets sorted against.
8972 (lambda nil
8973 (cond
8974 ((= dcst ?n)
8975 (if (looking-at org-complex-heading-regexp)
8976 (string-to-number (org-sort-remove-invisible (match-string 4)))
8977 nil))
8978 ((= dcst ?a)
8979 (if (looking-at org-complex-heading-regexp)
8980 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8981 nil))
8982 ((= dcst ?k)
8983 (or (get-text-property (point) :org-clock-minutes) 0))
8984 ((= dcst ?t)
8985 (let ((end (save-excursion (outline-next-heading) (point))))
8986 (if (or (re-search-forward org-ts-regexp end t)
8987 (re-search-forward org-ts-regexp-both end t))
8988 (org-time-string-to-seconds (match-string 0))
8989 (float-time now))))
8990 ((= dcst ?c)
8991 (let ((end (save-excursion (outline-next-heading) (point))))
8992 (if (re-search-forward
8993 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8994 end t)
8995 (org-time-string-to-seconds (match-string 0))
8996 (float-time now))))
8997 ((= dcst ?s)
8998 (let ((end (save-excursion (outline-next-heading) (point))))
8999 (if (re-search-forward org-scheduled-time-regexp end t)
9000 (org-time-string-to-seconds (match-string 1))
9001 (float-time now))))
9002 ((= dcst ?d)
9003 (let ((end (save-excursion (outline-next-heading) (point))))
9004 (if (re-search-forward org-deadline-time-regexp end t)
9005 (org-time-string-to-seconds (match-string 1))
9006 (float-time now))))
9007 ((= dcst ?p)
9008 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9009 (string-to-char (match-string 2))
9010 org-default-priority))
9011 ((= dcst ?r)
9012 (or (org-entry-get nil property) ""))
9013 ((= dcst ?o)
9014 (when (looking-at org-complex-heading-regexp)
9015 (let* ((m (match-string 2))
9016 (s (if (member m org-done-keywords) '- '+)))
9017 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9018 ((= dcst ?f)
9019 (if getkey-func
9020 (progn
9021 (setq tmp (funcall getkey-func))
9022 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9023 tmp)
9024 (error "Invalid key function `%s'" getkey-func)))
9025 (t (error "Invalid sorting type `%c'" sorting-type))))
9027 (cond
9028 ((= dcst ?a) 'string<)
9029 ((= dcst ?f)
9030 (or compare-func
9031 (and interactive?
9032 (org-read-function
9033 (concat "Function for comparing keys "
9034 "(empty for default `sort-subr' predicate): ")
9035 'allow-empty))))
9036 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
9037 (when restore-clock?
9038 (move-marker org-clock-marker
9039 (1+ (next-single-property-change
9040 start :org-clock-marker-backup)))
9041 (remove-text-properties (1- org-clock-marker) org-clock-marker
9042 '(:org-clock-marker-backup t)))))
9043 (run-hooks 'org-after-sorting-entries-or-items-hook)
9044 (message "Sorting entries...done")))
9046 ;;; The orgstruct minor mode
9048 ;; Define a minor mode which can be used in other modes in order to
9049 ;; integrate the Org mode structure editing commands.
9051 ;; This is really a hack, because the Org mode structure commands use
9052 ;; keys which normally belong to the major mode. Here is how it
9053 ;; works: The minor mode defines all the keys necessary to operate the
9054 ;; structure commands, but wraps the commands into a function which
9055 ;; tests if the cursor is currently at a headline or a plain list
9056 ;; item. If that is the case, the structure command is used,
9057 ;; temporarily setting many Org mode variables like regular
9058 ;; expressions for filling etc. However, when any of those keys is
9059 ;; used at a different location, function uses `key-binding' to look
9060 ;; up if the key has an associated command in another currently active
9061 ;; keymap (minor modes, major mode, global), and executes that
9062 ;; command. There might be problems if any of the keys is otherwise
9063 ;; used as a prefix key.
9065 (defcustom orgstruct-heading-prefix-regexp ""
9066 "Regexp that matches the custom prefix of Org headlines in
9067 orgstruct(++)-mode."
9068 :group 'org
9069 :version "26.1"
9070 :package-version '(Org . "8.3")
9071 :type 'regexp)
9072 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9074 (defcustom orgstruct-setup-hook nil
9075 "Hook run after orgstruct-mode-map is filled."
9076 :group 'org
9077 :version "24.4"
9078 :package-version '(Org . "8.0")
9079 :type 'hook)
9081 (defvar orgstruct-initialized nil)
9083 (defvar org-local-vars nil
9084 "List of local variables, for use by `orgstruct-mode'.")
9086 ;;;###autoload
9087 (define-minor-mode orgstruct-mode
9088 "Toggle the minor mode `orgstruct-mode'.
9089 This mode is for using Org mode structure commands in other
9090 modes. The following keys behave as if Org mode were active, if
9091 the cursor is on a headline, or on a plain list item (both as
9092 defined by Org mode)."
9093 nil " OrgStruct" (make-sparse-keymap)
9094 (funcall (if orgstruct-mode
9095 'add-to-invisibility-spec
9096 'remove-from-invisibility-spec)
9097 '(outline . t))
9098 (when orgstruct-mode
9099 (org-load-modules-maybe)
9100 (unless orgstruct-initialized
9101 (orgstruct-setup)
9102 (setq orgstruct-initialized t))))
9104 ;;;###autoload
9105 (defun turn-on-orgstruct ()
9106 "Unconditionally turn on `orgstruct-mode'."
9107 (orgstruct-mode 1))
9109 (defvar-local orgstruct-is-++ nil
9110 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9111 (defvar-local org-fb-vars nil)
9112 (defun orgstruct++-mode (&optional arg)
9113 "Toggle `orgstruct-mode', the enhanced version of it.
9114 In addition to setting orgstruct-mode, this also exports all
9115 indentation and autofilling variables from Org mode into the
9116 buffer. It will also recognize item context in multiline items."
9117 (interactive "P")
9118 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9119 (if (< arg 1)
9120 (progn (orgstruct-mode -1)
9121 (dolist (v org-fb-vars)
9122 (set (make-local-variable (car v))
9123 (if (eq (car-safe (cadr v)) 'quote)
9124 (cl-cadadr v)
9125 (nth 1 v)))))
9126 (orgstruct-mode 1)
9127 (setq org-fb-vars nil)
9128 (unless org-local-vars
9129 (setq org-local-vars (org-get-local-variables)))
9130 (let (var val)
9131 (dolist (x org-local-vars)
9132 (when (string-match
9133 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9134 \\|fill-prefix\\|indent-\\)"
9135 (symbol-name (car x)))
9136 (setq var (car x) val (nth 1 x))
9137 (push (list var `(quote ,(eval var))) org-fb-vars)
9138 (set (make-local-variable var)
9139 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9140 (setq-local orgstruct-is-++ t))))
9142 ;;;###autoload
9143 (defun turn-on-orgstruct++ ()
9144 "Unconditionally turn on `orgstruct++-mode'."
9145 (orgstruct++-mode 1))
9147 (defun orgstruct-error ()
9148 "Error when there is no default binding for a structure key."
9149 (interactive)
9150 (funcall (if (fboundp 'user-error)
9151 'user-error
9152 'error)
9153 "This key has no function outside structure elements"))
9155 (defun orgstruct-setup ()
9156 "Setup orgstruct keymap."
9157 (dolist (cell '((org-demote . t)
9158 (org-metaleft . t)
9159 (org-metaright . t)
9160 (org-promote . t)
9161 (org-shiftmetaleft . t)
9162 (org-shiftmetaright . t)
9163 org-backward-element
9164 org-backward-heading-same-level
9165 org-ctrl-c-ret
9166 org-ctrl-c-minus
9167 org-ctrl-c-star
9168 org-cycle
9169 org-force-cycle-archived
9170 org-forward-heading-same-level
9171 org-insert-heading
9172 org-insert-heading-respect-content
9173 org-kill-note-or-show-branches
9174 org-mark-subtree
9175 org-meta-return
9176 org-metadown
9177 org-metaup
9178 org-narrow-to-subtree
9179 org-promote-subtree
9180 org-reveal
9181 org-shiftdown
9182 org-shiftleft
9183 org-shiftmetadown
9184 org-shiftmetaup
9185 org-shiftright
9186 org-shifttab
9187 org-shifttab
9188 org-shiftup
9189 org-show-children
9190 org-show-subtree
9191 org-sort
9192 org-up-element
9193 outline-demote
9194 outline-next-visible-heading
9195 outline-previous-visible-heading
9196 outline-promote
9197 outline-up-heading))
9198 (let ((f (or (car-safe cell) cell))
9199 (disable-when-heading-prefix (cdr-safe cell)))
9200 (when (fboundp f)
9201 (let ((new-bindings))
9202 (dolist (binding (nconc (where-is-internal f org-mode-map)
9203 (where-is-internal f outline-mode-map)))
9204 (push binding new-bindings)
9205 ;; TODO use local-function-key-map
9206 (dolist (rep '(("<tab>" . "TAB")
9207 ("<return>" . "RET")
9208 ("<escape>" . "ESC")
9209 ("<delete>" . "DEL")))
9210 (setq binding (read-kbd-macro
9211 (let ((case-fold-search))
9212 (replace-regexp-in-string
9213 (regexp-quote (cdr rep))
9214 (car rep)
9215 (key-description binding)))))
9216 (cl-pushnew binding new-bindings :test 'equal)))
9217 (dolist (binding new-bindings)
9218 (let ((key (lookup-key orgstruct-mode-map binding)))
9219 (when (or (not key) (numberp key))
9220 (ignore-errors
9221 (org-defkey orgstruct-mode-map
9222 binding
9223 (orgstruct-make-binding
9224 f binding disable-when-heading-prefix))))))))))
9225 (run-hooks 'orgstruct-setup-hook))
9227 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9228 "Create a function for binding in the structure minor mode.
9229 FUN is the command to call inside a table. KEY is the key that
9230 should be checked in for a command to execute outside of tables.
9231 Non-nil `disable-when-heading-prefix' means to disable the command
9232 if `orgstruct-heading-prefix-regexp' is not empty."
9233 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9234 (let ((nname name)
9235 (i 0))
9236 (while (fboundp (intern nname))
9237 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9238 (setq name (intern nname)))
9239 (eval
9240 (let ((bindings '((org-heading-regexp
9241 (concat "^"
9242 orgstruct-heading-prefix-regexp
9243 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9244 (org-outline-regexp
9245 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9246 (org-outline-regexp-bol
9247 (concat "^" org-outline-regexp))
9248 (outline-regexp org-outline-regexp)
9249 (outline-heading-end-regexp "\n")
9250 (outline-level 'org-outline-level)
9251 (outline-heading-alist))))
9252 `(defun ,name (arg)
9253 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9254 "Outside of structure, run the binding of `"
9255 (key-description key) "'."
9256 (when disable-when-heading-prefix
9257 (concat
9258 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9259 "back to the default binding due to limitations of Org's implementation of\n"
9260 "`" (symbol-name fun) "'.")))
9261 (interactive "p")
9262 (let* ((disable
9263 ,(and disable-when-heading-prefix
9264 '(not (string= orgstruct-heading-prefix-regexp ""))))
9265 (fallback
9266 (or disable
9267 (not
9268 (let* ,bindings
9269 (org-context-p 'headline 'item
9270 ,(when (memq fun
9271 '(org-insert-heading
9272 org-insert-heading-respect-content
9273 org-meta-return))
9274 '(when orgstruct-is-++
9275 'item-body))))))))
9276 (if fallback
9277 (let* ((orgstruct-mode)
9278 (binding
9279 (let ((key ,key))
9280 (catch 'exit
9281 (dolist
9282 (rep
9283 '(nil
9284 ("<\\([^>]*\\)tab>" . "\\1TAB")
9285 ("<\\([^>]*\\)return>" . "\\1RET")
9286 ("<\\([^>]*\\)escape>" . "\\1ESC")
9287 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9288 nil)
9289 (when rep
9290 (setq key (read-kbd-macro
9291 (let ((case-fold-search))
9292 (replace-regexp-in-string
9293 (car rep)
9294 (cdr rep)
9295 (key-description key))))))
9296 (when (key-binding key)
9297 (throw 'exit (key-binding key))))))))
9298 (if (keymapp binding)
9299 (org-set-transient-map binding)
9300 (let ((func (or binding
9301 (unless disable
9302 'orgstruct-error))))
9303 (when func
9304 (call-interactively func)))))
9305 (org-run-like-in-org-mode
9306 (lambda ()
9307 (interactive)
9308 (let* ,bindings
9309 (call-interactively ',fun)))))))))
9310 name))
9312 (defun org-contextualize-keys (alist contexts)
9313 "Return valid elements in ALIST depending on CONTEXTS.
9315 `org-agenda-custom-commands' or `org-capture-templates' are the
9316 values used for ALIST, and `org-agenda-custom-commands-contexts'
9317 or `org-capture-templates-contexts' are the associated contexts
9318 definitions."
9319 (let ((contexts
9320 ;; normalize contexts
9321 (mapcar
9322 (lambda(c) (cond ((listp (cadr c))
9323 (list (car c) (car c) (nth 1 c)))
9324 ((string= "" (cadr c))
9325 (list (car c) (car c) (nth 2 c)))
9326 (t c)))
9327 contexts))
9328 (a alist) r s)
9329 ;; loop over all commands or templates
9330 (dolist (c a)
9331 (let (vrules repl)
9332 (cond
9333 ((not (assoc (car c) contexts))
9334 (push c r))
9335 ((and (assoc (car c) contexts)
9336 (setq vrules (org-contextualize-validate-key
9337 (car c) contexts)))
9338 (mapc (lambda (vr)
9339 (unless (equal (car vr) (cadr vr))
9340 (setq repl vr)))
9341 vrules)
9342 (if (not repl) (push c r)
9343 (push (cadr repl) s)
9344 (push
9345 (cons (car c)
9346 (cdr (or (assoc (cadr repl) alist)
9347 (error "Undefined key `%s' as contextual replacement for `%s'"
9348 (cadr repl) (car c)))))
9349 r))))))
9350 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9351 (delq
9353 (delete-dups
9354 (mapcar (lambda (x)
9355 (let ((tpl (car x)))
9356 (unless (delq
9358 (mapcar (lambda (y)
9359 (equal y tpl))
9361 x)))
9362 (reverse r))))))
9364 (defun org-contextualize-validate-key (key contexts)
9365 "Check CONTEXTS for agenda or capture KEY."
9366 (let (res)
9367 (dolist (r contexts)
9368 (dolist (rr (car (last r)))
9369 (when
9370 (and (equal key (car r))
9371 (if (functionp rr) (funcall rr)
9372 (or (and (eq (car rr) 'in-file)
9373 (buffer-file-name)
9374 (string-match (cdr rr) (buffer-file-name)))
9375 (and (eq (car rr) 'in-mode)
9376 (string-match (cdr rr) (symbol-name major-mode)))
9377 (and (eq (car rr) 'in-buffer)
9378 (string-match (cdr rr) (buffer-name)))
9379 (when (and (eq (car rr) 'not-in-file)
9380 (buffer-file-name))
9381 (not (string-match (cdr rr) (buffer-file-name))))
9382 (when (eq (car rr) 'not-in-mode)
9383 (not (string-match (cdr rr) (symbol-name major-mode))))
9384 (when (eq (car rr) 'not-in-buffer)
9385 (not (string-match (cdr rr) (buffer-name)))))))
9386 (push r res))))
9387 (delete-dups (delq nil res))))
9389 (defun org-context-p (&rest contexts)
9390 "Check if local context is any of CONTEXTS.
9391 Possible values in the list of contexts are `table', `headline', and `item'."
9392 (let ((pos (point)))
9393 (goto-char (point-at-bol))
9394 (prog1 (or (and (memq 'table contexts)
9395 (looking-at "[ \t]*|"))
9396 (and (memq 'headline contexts)
9397 (looking-at org-outline-regexp))
9398 (and (memq 'item contexts)
9399 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9400 (and (memq 'item-body contexts)
9401 (org-in-item-p)))
9402 (goto-char pos))))
9404 ;;;###autoload
9405 (defun org-run-like-in-org-mode (cmd)
9406 "Run a command, pretending that the current buffer is in Org mode.
9407 This will temporarily bind local variables that are typically bound in
9408 Org mode to the values they have in Org mode, and then interactively
9409 call CMD."
9410 (org-load-modules-maybe)
9411 (unless org-local-vars
9412 (setq org-local-vars (org-get-local-variables)))
9413 (let (binds)
9414 (dolist (var org-local-vars)
9415 (when (or (not (boundp (car var)))
9416 (eq (symbol-value (car var))
9417 (default-value (car var))))
9418 (push (list (car var) `(quote ,(cadr var))) binds)))
9419 (eval `(let ,binds
9420 (call-interactively (quote ,cmd))))))
9422 (defun org-get-category (&optional pos force-refresh)
9423 "Get the category applying to position POS."
9424 (save-match-data
9425 (when force-refresh (org-refresh-category-properties))
9426 (let ((pos (or pos (point))))
9427 (or (get-text-property pos 'org-category)
9428 (progn (org-refresh-category-properties)
9429 (get-text-property pos 'org-category))))))
9431 ;;; Refresh properties
9433 (defun org-refresh-properties (dprop tprop)
9434 "Refresh buffer text properties.
9435 DPROP is the drawer property and TPROP is either the
9436 corresponding text property to set, or an alist with each element
9437 being a text property (as a symbol) and a function to apply to
9438 the value of the drawer property."
9439 (let* ((case-fold-search t)
9440 (inhibit-read-only t)
9441 (inherit? (org-property-inherit-p dprop))
9442 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9443 (global (and inherit? (org--property-global-value dprop nil))))
9444 (org-with-silent-modifications
9445 (org-with-point-at 1
9446 ;; Set global values (e.g., values defined through
9447 ;; "#+PROPERTY:" keywords) to the whole buffer.
9448 (when global (put-text-property (point-min) (point-max) tprop global))
9449 ;; Set local values.
9450 (while (re-search-forward property-re nil t)
9451 (when (org-at-property-p)
9452 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9453 (outline-next-heading))))))
9455 (defun org-refresh-property (tprop p &optional inherit)
9456 "Refresh the buffer text property TPROP from the drawer property P.
9457 The refresh happens only for the current headline, or the whole
9458 sub-tree if optional argument INHERIT is non-nil."
9459 (unless (org-before-first-heading-p)
9460 (save-excursion
9461 (org-back-to-heading t)
9462 (let ((start (point))
9463 (end (save-excursion
9464 (if inherit (org-end-of-subtree t t)
9465 (or (outline-next-heading) (point-max))))))
9466 (if (symbolp tprop)
9467 ;; TPROP is a text property symbol.
9468 (put-text-property start end tprop p)
9469 ;; TPROP is an alist with (property . function) elements.
9470 (pcase-dolist (`(,prop . ,f) tprop)
9471 (put-text-property start end prop (funcall f p))))))))
9473 (defun org-refresh-category-properties ()
9474 "Refresh category text properties in the buffer."
9475 (let ((case-fold-search t)
9476 (inhibit-read-only t)
9477 (default-category
9478 (cond ((null org-category)
9479 (if buffer-file-name
9480 (file-name-sans-extension
9481 (file-name-nondirectory buffer-file-name))
9482 "???"))
9483 ((symbolp org-category) (symbol-name org-category))
9484 (t org-category))))
9485 (org-with-silent-modifications
9486 (org-with-wide-buffer
9487 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9488 ;; This is the default category for the buffer. If none is
9489 ;; found, fall-back to `org-category' or buffer file name.
9490 (put-text-property
9491 (point-min) (point-max)
9492 'org-category
9493 (catch 'buffer-category
9494 (goto-char (point-max))
9495 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9496 (let ((element (org-element-at-point)))
9497 (when (eq (org-element-type element) 'keyword)
9498 (throw 'buffer-category
9499 (org-element-property :value element)))))
9500 default-category))
9501 ;; Set sub-tree specific categories.
9502 (goto-char (point-min))
9503 (let ((regexp (org-re-property "CATEGORY")))
9504 (while (re-search-forward regexp nil t)
9505 (let ((value (match-string-no-properties 3)))
9506 (when (org-at-property-p)
9507 (put-text-property
9508 (save-excursion (org-back-to-heading t) (point))
9509 (save-excursion (org-end-of-subtree t t) (point))
9510 'org-category
9511 value)))))))))
9513 (defun org-refresh-stats-properties ()
9514 "Refresh stats text properties in the buffer."
9515 (org-with-silent-modifications
9516 (org-with-point-at 1
9517 (let ((regexp (concat org-outline-regexp-bol
9518 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9519 (while (re-search-forward regexp nil t)
9520 (let* ((numerator (string-to-number (match-string 1)))
9521 (denominator (and (match-end 2)
9522 (string-to-number (match-string 2))))
9523 (stats (cond ((not denominator) numerator) ;percent
9524 ((= denominator 0) 0)
9525 (t (/ (* numerator 100) denominator)))))
9526 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9527 'org-stats stats)))))))
9529 (defun org-refresh-effort-properties ()
9530 "Refresh effort properties"
9531 (org-refresh-properties
9532 org-effort-property
9533 '((effort . identity)
9534 (effort-minutes . org-duration-to-minutes))))
9536 ;;;; Link Stuff
9538 ;;; Link abbreviations
9540 (defun org-link-expand-abbrev (link)
9541 "Apply replacements as defined in `org-link-abbrev-alist'."
9542 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9543 (let* ((key (match-string 1 link))
9544 (as (or (assoc key org-link-abbrev-alist-local)
9545 (assoc key org-link-abbrev-alist)))
9546 (tag (and (match-end 2) (match-string 3 link)))
9547 rpl)
9548 (if (not as)
9549 link
9550 (setq rpl (cdr as))
9551 (cond
9552 ((symbolp rpl) (funcall rpl tag))
9553 ((string-match "%(\\([^)]+\\))" rpl)
9554 (replace-match
9555 (save-match-data
9556 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9557 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9558 ((string-match "%h" rpl)
9559 (replace-match (url-hexify-string (or tag "")) t t rpl))
9560 (t (concat rpl tag)))))
9561 link))
9563 ;;; Storing and inserting links
9565 (defvar org-insert-link-history nil
9566 "Minibuffer history for links inserted with `org-insert-link'.")
9568 (defvar org-stored-links nil
9569 "Contains the links stored with `org-store-link'.")
9571 (defvar org-store-link-plist nil
9572 "Plist with info about the most recently link created with `org-store-link'.")
9574 (defun org-store-link-functions ()
9575 "Return a list of functions that are called to create and store a link.
9576 The functions defined in the :store property of
9577 `org-link-parameters'.
9579 Each function will be called in turn until one returns a non-nil
9580 value. Each function should check if it is responsible for
9581 creating this link (for example by looking at the major mode).
9582 If not, it must exit and return nil. If yes, it should return
9583 a non-nil value after calling `org-store-link-props' with a list
9584 of properties and values. Special properties are:
9586 :type The link prefix, like \"http\". This must be given.
9587 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9588 This is obligatory as well.
9589 :description Optional default description for the second pair
9590 of brackets in an Org mode link. The user can still change
9591 this when inserting this link into an Org mode buffer.
9593 In addition to these, any additional properties can be specified
9594 and then used in capture templates."
9595 (cl-loop for link in org-link-parameters
9596 with store-func
9597 do (setq store-func (org-link-get-parameter (car link) :store))
9598 if store-func
9599 collect store-func))
9601 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9602 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9604 ;;;###autoload
9605 (defun org-store-link (arg)
9606 "Store an org-link to the current location.
9607 \\<org-mode-map>
9608 This link is added to `org-stored-links' and can later be inserted
9609 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9611 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9612 A single
9613 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9614 `org-gnus-prefer-web-links' for links to Usenet articles.
9616 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9617 skipping storing functions that are not
9618 part of Org core.
9620 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9621 prefix ARG forces storing a link for each line in the
9622 active region."
9623 (interactive "P")
9624 (org-load-modules-maybe)
9625 (if (and (equal arg '(64)) (org-region-active-p))
9626 (save-excursion
9627 (let ((end (region-end)))
9628 (goto-char (region-beginning))
9629 (set-mark (point))
9630 (while (< (point-at-eol) end)
9631 (move-end-of-line 1) (activate-mark)
9632 (let (current-prefix-arg)
9633 (call-interactively 'org-store-link))
9634 (move-beginning-of-line 2)
9635 (set-mark (point)))))
9636 (setq org-store-link-plist nil)
9637 (let (link cpltxt desc description search
9638 txt custom-id agenda-link sfuns sfunsn)
9639 (cond
9641 ;; Store a link using an external link type
9642 ((and (not (equal arg '(16)))
9643 (setq sfuns
9644 (delq
9645 nil (mapcar (lambda (f)
9646 (let (fs) (if (funcall f) (push f fs))))
9647 (org-store-link-functions)))
9648 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9649 (or (and (cdr sfuns)
9650 (funcall (intern
9651 (completing-read
9652 "Which function for creating the link? "
9653 sfunsn nil t (car sfunsn)))))
9654 (funcall (caar sfuns)))
9655 (setq link (plist-get org-store-link-plist :link)
9656 desc (or (plist-get org-store-link-plist
9657 :description)
9658 link))))
9660 ;; Store a link from a source code buffer.
9661 ((org-src-edit-buffer-p)
9662 (let ((coderef-format (org-src-coderef-format)))
9663 (cond ((save-excursion
9664 (beginning-of-line)
9665 (looking-at (org-src-coderef-regexp coderef-format)))
9666 (setq link (format "(%s)" (match-string-no-properties 3))))
9667 ((called-interactively-p 'any)
9668 (let ((label (read-string "Code line label: ")))
9669 (end-of-line)
9670 (setq link (format coderef-format label))
9671 (let ((gc (- 79 (length link))))
9672 (if (< (current-column) gc)
9673 (org-move-to-column gc t)
9674 (insert " ")))
9675 (insert link)
9676 (setq link (concat "(" label ")"))
9677 (setq desc nil)))
9678 (t (setq link nil)))))
9680 ;; We are in the agenda, link to referenced location
9681 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9682 (let ((m (or (get-text-property (point) 'org-hd-marker)
9683 (get-text-property (point) 'org-marker))))
9684 (when m
9685 (org-with-point-at m
9686 (setq agenda-link
9687 (if (called-interactively-p 'any)
9688 (call-interactively 'org-store-link)
9689 (org-store-link nil)))))))
9691 ((eq major-mode 'calendar-mode)
9692 (let ((cd (calendar-cursor-to-date)))
9693 (setq link
9694 (format-time-string
9695 (car org-time-stamp-formats)
9696 (apply 'encode-time
9697 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9698 nil nil nil))))
9699 (org-store-link-props :type "calendar" :date cd)))
9701 ((eq major-mode 'help-mode)
9702 (setq link (concat "help:" (save-excursion
9703 (goto-char (point-min))
9704 (looking-at "^[^ ]+")
9705 (match-string 0))))
9706 (org-store-link-props :type "help"))
9708 ((eq major-mode 'w3-mode)
9709 (setq cpltxt (if (and (buffer-name)
9710 (not (string-match "Untitled" (buffer-name))))
9711 (buffer-name)
9712 (url-view-url t))
9713 link (url-view-url t))
9714 (org-store-link-props :type "w3" :url (url-view-url t)))
9716 ((eq major-mode 'image-mode)
9717 (setq cpltxt (concat "file:"
9718 (abbreviate-file-name buffer-file-name))
9719 link cpltxt)
9720 (org-store-link-props :type "image" :file buffer-file-name))
9722 ;; In dired, store a link to the file of the current line
9723 ((derived-mode-p 'dired-mode)
9724 (let ((file (dired-get-filename nil t)))
9725 (setq file (if file
9726 (abbreviate-file-name
9727 (expand-file-name (dired-get-filename nil t)))
9728 ;; otherwise, no file so use current directory.
9729 default-directory))
9730 (setq cpltxt (concat "file:" file)
9731 link cpltxt)))
9733 ((setq search (run-hook-with-args-until-success
9734 'org-create-file-search-functions))
9735 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9736 "::" search))
9737 (setq cpltxt (or description link)))
9739 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9740 (org-with-limited-levels
9741 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9742 (cond
9743 ;; Store a link using the target at point
9744 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9745 (setq cpltxt
9746 (concat "file:"
9747 (abbreviate-file-name
9748 (buffer-file-name (buffer-base-buffer)))
9749 "::" (match-string 1))
9750 link cpltxt))
9751 ((and (featurep 'org-id)
9752 (or (eq org-id-link-to-org-use-id t)
9753 (and (called-interactively-p 'any)
9754 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9755 (and (eq org-id-link-to-org-use-id
9756 'create-if-interactive-and-no-custom-id)
9757 (not custom-id))))
9758 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9759 ;; Store a link using the ID at point
9760 (setq link (condition-case nil
9761 (prog1 (org-id-store-link)
9762 (setq desc (or (plist-get org-store-link-plist
9763 :description)
9764 "")))
9765 (error
9766 ;; Probably before first headline, link only to file
9767 (concat "file:"
9768 (abbreviate-file-name
9769 (buffer-file-name (buffer-base-buffer))))))))
9771 ;; Just link to current headline
9772 (setq cpltxt (concat "file:"
9773 (abbreviate-file-name
9774 (buffer-file-name (buffer-base-buffer)))))
9775 ;; Add a context search string
9776 (when (org-xor org-context-in-file-links
9777 (equal arg '(4)))
9778 (let* ((element (org-element-at-point))
9779 (name (org-element-property :name element)))
9780 (setq txt (cond
9781 ((org-at-heading-p) nil)
9782 (name)
9783 ((org-region-active-p)
9784 (buffer-substring (region-beginning) (region-end)))))
9785 (when (or (null txt) (string-match "\\S-" txt))
9786 (setq cpltxt
9787 (concat cpltxt "::"
9788 (condition-case nil
9789 (org-make-org-heading-search-string txt)
9790 (error "")))
9791 desc (or name
9792 (nth 4 (ignore-errors (org-heading-components)))
9793 "NONE")))))
9794 (when (string-match "::\\'" cpltxt)
9795 (setq cpltxt (substring cpltxt 0 -2)))
9796 (setq link cpltxt)))))
9798 ((buffer-file-name (buffer-base-buffer))
9799 ;; Just link to this file here.
9800 (setq cpltxt (concat "file:"
9801 (abbreviate-file-name
9802 (buffer-file-name (buffer-base-buffer)))))
9803 ;; Add a context string.
9804 (when (org-xor org-context-in-file-links
9805 (equal arg '(4)))
9806 (setq txt (if (org-region-active-p)
9807 (buffer-substring (region-beginning) (region-end))
9808 (buffer-substring (point-at-bol) (point-at-eol))))
9809 ;; Only use search option if there is some text.
9810 (when (string-match "\\S-" txt)
9811 (setq cpltxt
9812 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9813 desc "NONE")))
9814 (setq link cpltxt))
9816 ((called-interactively-p 'interactive)
9817 (user-error "No method for storing a link from this buffer"))
9819 (t (setq link nil)))
9821 ;; We're done setting link and desc, clean up
9822 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9823 (setq link (or link cpltxt)
9824 desc (or desc cpltxt))
9825 (cond ((not desc))
9826 ((equal desc "NONE") (setq desc nil))
9827 (t (setq desc
9828 (replace-regexp-in-string
9829 org-bracket-link-analytic-regexp
9830 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9831 desc))))
9832 ;; Return the link
9833 (if (not (and (or (called-interactively-p 'any)
9834 executing-kbd-macro)
9835 link))
9836 (or agenda-link (and link (org-make-link-string link desc)))
9837 (push (list link desc) org-stored-links)
9838 (message "Stored: %s" (or desc link))
9839 (when custom-id
9840 (setq link (concat "file:" (abbreviate-file-name
9841 (buffer-file-name)) "::#" custom-id))
9842 (push (list link desc) org-stored-links))
9843 (car org-stored-links)))))
9845 (defun org-store-link-props (&rest plist)
9846 "Store link properties, extract names, addresses and dates."
9847 (let ((x (plist-get plist :from)))
9848 (when x
9849 (let ((adr (mail-extract-address-components x)))
9850 (setq plist (plist-put plist :fromname (car adr)))
9851 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9852 (let ((x (plist-get plist :to)))
9853 (when x
9854 (let ((adr (mail-extract-address-components x)))
9855 (setq plist (plist-put plist :toname (car adr)))
9856 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9857 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9858 (when x
9859 (setq plist (plist-put plist :date-timestamp
9860 (format-time-string
9861 (org-time-stamp-format t) x)))
9862 (setq plist (plist-put plist :date-timestamp-inactive
9863 (format-time-string
9864 (org-time-stamp-format t t) x)))))
9865 (let ((from (plist-get plist :from))
9866 (to (plist-get plist :to)))
9867 (when (and from to org-from-is-user-regexp)
9868 (setq plist
9869 (plist-put plist :fromto
9870 (if (string-match org-from-is-user-regexp from)
9871 (concat "to %t")
9872 (concat "from %f"))))))
9873 (setq org-store-link-plist plist))
9875 (defun org-add-link-props (&rest plist)
9876 "Add these properties to the link property list."
9877 (let (key value)
9878 (while plist
9879 (setq key (pop plist) value (pop plist))
9880 (setq org-store-link-plist
9881 (plist-put org-store-link-plist key value)))))
9883 (defun org-email-link-description (&optional fmt)
9884 "Return the description part of an email link.
9885 This takes information from `org-store-link-plist' and formats it
9886 according to FMT (default from `org-email-link-description-format')."
9887 (setq fmt (or fmt org-email-link-description-format))
9888 (let* ((p org-store-link-plist)
9889 (to (plist-get p :toaddress))
9890 (from (plist-get p :fromaddress))
9891 (table
9892 (list
9893 (cons "%c" (plist-get p :fromto))
9894 (cons "%F" (plist-get p :from))
9895 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9896 (cons "%T" (plist-get p :to))
9897 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9898 (cons "%s" (plist-get p :subject))
9899 (cons "%d" (plist-get p :date))
9900 (cons "%m" (plist-get p :message-id)))))
9901 (when (string-match "%c" fmt)
9902 ;; Check if the user wrote this message
9903 (if (and org-from-is-user-regexp from to
9904 (save-match-data (string-match org-from-is-user-regexp from)))
9905 (setq fmt (replace-match "to %t" t t fmt))
9906 (setq fmt (replace-match "from %f" t t fmt))))
9907 (org-replace-escapes fmt table)))
9909 (defun org-make-org-heading-search-string (&optional string)
9910 "Make search string for the current headline or STRING."
9911 (let ((s (or string
9912 (and (derived-mode-p 'org-mode)
9913 (save-excursion
9914 (org-back-to-heading t)
9915 (org-element-property :raw-value (org-element-at-point))))))
9916 (lines org-context-in-file-links))
9917 (unless string (setq s (concat "*" s))) ;Add * for headlines
9918 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9919 (when (and string (integerp lines) (> lines 0))
9920 (let ((slines (org-split-string s "\n")))
9921 (when (< lines (length slines))
9922 (setq s (mapconcat
9923 'identity
9924 (reverse (nthcdr (- (length slines) lines)
9925 (reverse slines))) "\n")))))
9926 (mapconcat #'identity (split-string s) " ")))
9928 (defun org-make-link-string (link &optional description)
9929 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9930 (unless (org-string-nw-p link) (error "Empty link"))
9931 (let ((uri (cond ((string-match org-link-types-re link)
9932 (concat (match-string 1 link)
9933 (org-link-escape (substring link (match-end 1)))))
9934 ;; For readability, url-encode internal links only
9935 ;; when absolutely needed (i.e, when they contain
9936 ;; square brackets). File links however, are
9937 ;; encoded since, e.g., spaces are significant.
9938 ((or (file-name-absolute-p link)
9939 (string-match-p "\\`\\.\\.?/\\|[][]" link))
9940 (org-link-escape link))
9941 (t link)))
9942 (description
9943 (and (org-string-nw-p description)
9944 ;; Remove brackets from description, as they are fatal.
9945 (replace-regexp-in-string
9946 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9947 (org-trim description)))))
9948 (format "[[%s]%s]"
9950 (if description (format "[%s]" description) ""))))
9952 (defconst org-link-escape-chars
9953 ;;%20 %5B %5D %25
9954 '(?\s ?\[ ?\] ?%)
9955 "List of characters that should be escaped in a link when stored to Org.
9956 This is the list that is used for internal purposes.")
9958 (defun org-link-escape (text &optional table merge)
9959 "Return percent escaped representation of TEXT.
9960 TEXT is a string with the text to escape.
9961 Optional argument TABLE is a list with characters that should be
9962 escaped. When nil, `org-link-escape-chars' is used.
9963 If optional argument MERGE is set, merge TABLE into
9964 `org-link-escape-chars'."
9965 (let ((characters-to-encode
9966 (cond ((null table) org-link-escape-chars)
9967 (merge (append org-link-escape-chars table))
9968 (t table))))
9969 (mapconcat
9970 (lambda (c)
9971 (if (or (memq c characters-to-encode)
9972 (and org-url-hexify-p (or (< c 32) (> c 126))))
9973 (mapconcat (lambda (e) (format "%%%.2X" e))
9974 (or (encode-coding-char c 'utf-8)
9975 (error "Unable to percent escape character: %c" c))
9977 (char-to-string c)))
9978 text "")))
9980 (defun org-link-unescape (str)
9981 "Unhex hexified Unicode parts in string STR.
9982 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9983 reciprocal of `org-link-escape', which see."
9984 (if (org-string-nw-p str)
9985 (replace-regexp-in-string
9986 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9987 str))
9989 (defun org-link-unescape-compound (hex)
9990 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9991 Note: this function also decodes single byte encodings like
9992 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9993 (save-match-data
9994 (let* ((bytes (cdr (split-string hex "%")))
9995 (ret "")
9996 (eat 0)
9997 (sum 0))
9998 (while bytes
9999 (let* ((val (string-to-number (pop bytes) 16))
10000 (shift-xor
10001 (if (= 0 eat)
10002 (cond
10003 ((>= val 252) (cons 6 252))
10004 ((>= val 248) (cons 5 248))
10005 ((>= val 240) (cons 4 240))
10006 ((>= val 224) (cons 3 224))
10007 ((>= val 192) (cons 2 192))
10008 (t (cons 0 0)))
10009 (cons 6 128))))
10010 (when (>= val 192) (setq eat (car shift-xor)))
10011 (setq val (logxor val (cdr shift-xor)))
10012 (setq sum (+ (lsh sum (car shift-xor)) val))
10013 (when (> eat 0) (setq eat (- eat 1)))
10014 (cond
10015 ((= 0 eat) ;multi byte
10016 (setq ret (concat ret (char-to-string sum)))
10017 (setq sum 0))
10018 ((not bytes) ; single byte(s)
10019 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10020 ret)))
10022 (defun org-link-unescape-single-byte-sequence (hex)
10023 "Unhexify hex-encoded single byte character sequences."
10024 (mapconcat (lambda (byte)
10025 (char-to-string (string-to-number byte 16)))
10026 (cdr (split-string hex "%")) ""))
10028 (defun org-xor (a b)
10029 "Exclusive or."
10030 (if a (not b) b))
10032 (defun org-fixup-message-id-for-http (s)
10033 "Replace special characters in a message id, so it can be used in an http query."
10034 (when (string-match "%" s)
10035 (setq s (mapconcat (lambda (c)
10036 (if (eq c ?%)
10037 "%25"
10038 (char-to-string c)))
10039 s "")))
10040 (while (string-match "<" s)
10041 (setq s (replace-match "%3C" t t s)))
10042 (while (string-match ">" s)
10043 (setq s (replace-match "%3E" t t s)))
10044 (while (string-match "@" s)
10045 (setq s (replace-match "%40" t t s)))
10048 (defun org-link-prettify (link)
10049 "Return a human-readable representation of LINK.
10050 The car of LINK must be a raw link.
10051 The cdr of LINK must be either a link description or nil."
10052 (let ((desc (or (cadr link) "<no description>")))
10053 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10054 "<" (car link) ">")))
10056 ;;;###autoload
10057 (defun org-insert-link-global ()
10058 "Insert a link like Org mode does.
10059 This command can be called in any mode to insert a link in Org syntax."
10060 (interactive)
10061 (org-load-modules-maybe)
10062 (org-run-like-in-org-mode 'org-insert-link))
10064 (defun org-insert-all-links (arg &optional pre post)
10065 "Insert all links in `org-stored-links'.
10066 When a universal prefix, do not delete the links from `org-stored-links'.
10067 When `ARG' is a number, insert the last N link(s).
10068 `PRE' and `POST' are optional arguments to define a string to
10069 prepend or to append."
10070 (interactive "P")
10071 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10072 (links (copy-sequence org-stored-links))
10073 (pr (or pre "- "))
10074 (po (or post "\n"))
10075 (cnt 1) l)
10076 (if (null org-stored-links)
10077 (message "No link to insert")
10078 (while (and (or (listp arg) (>= arg cnt))
10079 (setq l (if (listp arg)
10080 (pop links)
10081 (pop org-stored-links))))
10082 (setq cnt (1+ cnt))
10083 (insert pr)
10084 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10085 (insert po)))))
10087 (defun org-insert-last-stored-link (arg)
10088 "Insert the last link stored in `org-stored-links'."
10089 (interactive "p")
10090 (org-insert-all-links arg "" "\n"))
10092 (defun org-link-fontify-links-to-this-file ()
10093 "Fontify links to the current file in `org-stored-links'."
10094 (let ((f (buffer-file-name)) a b)
10095 (setq a (mapcar (lambda(l)
10096 (let ((ll (car l)))
10097 (when (and (string-match "^file:\\(.+\\)::" ll)
10098 (equal f (expand-file-name (match-string 1 ll))))
10099 ll)))
10100 org-stored-links))
10101 (when (featurep 'org-id)
10102 (setq b (mapcar (lambda(l)
10103 (let ((ll (car l)))
10104 (when (and (string-match "^id:\\(.+\\)$" ll)
10105 (equal f (expand-file-name
10106 (or (org-id-find-id-file
10107 (match-string 1 ll)) ""))))
10108 ll)))
10109 org-stored-links)))
10110 (mapcar (lambda(l)
10111 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10112 (delq nil (append a b)))))
10114 (defvar org--links-history nil)
10115 (defun org-insert-link (&optional complete-file link-location default-description)
10116 "Insert a link. At the prompt, enter the link.
10118 Completion can be used to insert any of the link protocol prefixes in use.
10120 The history can be used to select a link previously stored with
10121 `org-store-link'. When the empty string is entered (i.e. if you just
10122 press `RET' at the prompt), the link defaults to the most recently
10123 stored link. As `SPC' triggers completion in the minibuffer, you need to
10124 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10126 You will also be prompted for a description, and if one is given, it will
10127 be displayed in the buffer instead of the link.
10129 If there is already a link at point, this command will allow you to edit
10130 link and description parts.
10132 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10133 file name can be
10134 selected using completion. The path to the file will be relative to the
10135 current directory if the file is in the current directory or a subdirectory.
10136 Otherwise, the link will be the absolute path as completed in the minibuffer
10137 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10138 option `org-link-file-path-type'.
10140 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10141 absolute path even if the file is in
10142 the current directory or below.
10144 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10145 prefix negates `org-keep-stored-link-after-insertion'.
10147 If the LINK-LOCATION parameter is non-nil, this value will be used as
10148 the link location instead of reading one interactively.
10150 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10151 be used as the default description. Otherwise, if
10152 `org-make-link-description-function' is non-nil, this function
10153 will be called with the link target, and the result will be the
10154 default link description."
10155 (interactive "P")
10156 (let* ((wcf (current-window-configuration))
10157 (origbuf (current-buffer))
10158 (region (when (org-region-active-p)
10159 (buffer-substring (region-beginning) (region-end))))
10160 (remove (and region (list (region-beginning) (region-end))))
10161 (desc region)
10162 (link link-location)
10163 (abbrevs org-link-abbrev-alist-local)
10164 entry all-prefixes auto-desc)
10165 (cond
10166 (link-location) ; specified by arg, just use it.
10167 ((org-in-regexp org-bracket-link-regexp 1)
10168 ;; We do have a link at point, and we are going to edit it.
10169 (setq remove (list (match-beginning 0) (match-end 0)))
10170 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10171 (setq link (read-string "Link: "
10172 (org-link-unescape
10173 (match-string-no-properties 1)))))
10174 ((or (org-in-regexp org-angle-link-re)
10175 (org-in-regexp org-plain-link-re))
10176 ;; Convert to bracket link
10177 (setq remove (list (match-beginning 0) (match-end 0))
10178 link (read-string "Link: "
10179 (org-unbracket-string "<" ">" (match-string 0)))))
10180 ((member complete-file '((4) (16)))
10181 ;; Completing read for file names.
10182 (setq link (org-file-complete-link complete-file)))
10184 ;; Read link, with completion for stored links.
10185 (org-link-fontify-links-to-this-file)
10186 (org-switch-to-buffer-other-window "*Org Links*")
10187 (with-current-buffer "*Org Links*"
10188 (erase-buffer)
10189 (insert "Insert a link.
10190 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10191 (when org-stored-links
10192 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10193 (insert (mapconcat 'org-link-prettify
10194 (reverse org-stored-links) "\n")))
10195 (goto-char (point-min)))
10196 (let ((cw (selected-window)))
10197 (select-window (get-buffer-window "*Org Links*" 'visible))
10198 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10199 (unless (pos-visible-in-window-p (point-max))
10200 (org-fit-window-to-buffer))
10201 (and (window-live-p cw) (select-window cw)))
10202 (setq all-prefixes (append (mapcar 'car abbrevs)
10203 (mapcar 'car org-link-abbrev-alist)
10204 (org-link-types)))
10205 (unwind-protect
10206 ;; Fake a link history, containing the stored links.
10207 (let ((org--links-history
10208 (append (mapcar #'car org-stored-links)
10209 org-insert-link-history)))
10210 (setq link
10211 (org-completing-read
10212 "Link: "
10213 (append
10214 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10215 (mapcar #'car org-stored-links))
10216 nil nil nil
10217 'org--links-history
10218 (caar org-stored-links)))
10219 (unless (org-string-nw-p link) (user-error "No link selected"))
10220 (dolist (l org-stored-links)
10221 (when (equal link (cadr l))
10222 (setq link (car l))
10223 (setq auto-desc t)))
10224 (when (or (member link all-prefixes)
10225 (and (equal ":" (substring link -1))
10226 (member (substring link 0 -1) all-prefixes)
10227 (setq link (substring link 0 -1))))
10228 (setq link (with-current-buffer origbuf
10229 (org-link-try-special-completion link)))))
10230 (set-window-configuration wcf)
10231 (kill-buffer "*Org Links*"))
10232 (setq entry (assoc link org-stored-links))
10233 (or entry (push link org-insert-link-history))
10234 (setq desc (or desc (nth 1 entry)))))
10236 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10237 (not org-keep-stored-link-after-insertion))
10238 (setq org-stored-links (delq (assoc link org-stored-links)
10239 org-stored-links)))
10241 (when (and (string-match org-plain-link-re link)
10242 (not (string-match org-ts-regexp link)))
10243 ;; URL-like link, normalize the use of angular brackets.
10244 (setq link (org-unbracket-string "<" ">" link)))
10246 ;; Check if we are linking to the current file with a search
10247 ;; option If yes, simplify the link by using only the search
10248 ;; option.
10249 (when (and buffer-file-name
10250 (let ((case-fold-search nil))
10251 (string-match "\\`file:\\(.+?\\)::" link)))
10252 (let ((path (match-string-no-properties 1 link))
10253 (search (substring-no-properties link (match-end 0))))
10254 (save-match-data
10255 (when (equal (file-truename buffer-file-name) (file-truename path))
10256 ;; We are linking to this same file, with a search option
10257 (setq link search)))))
10259 ;; Check if we can/should use a relative path. If yes, simplify the link
10260 (let ((case-fold-search nil))
10261 (when (string-match "\\`\\(file\\|docview\\):" link)
10262 (let* ((type (match-string-no-properties 0 link))
10263 (path (substring-no-properties link (match-end 0)))
10264 (origpath path))
10265 (cond
10266 ((or (eq org-link-file-path-type 'absolute)
10267 (equal complete-file '(16)))
10268 (setq path (abbreviate-file-name (expand-file-name path))))
10269 ((eq org-link-file-path-type 'noabbrev)
10270 (setq path (expand-file-name path)))
10271 ((eq org-link-file-path-type 'relative)
10272 (setq path (file-relative-name path)))
10274 (save-match-data
10275 (if (string-match (concat "^" (regexp-quote
10276 (expand-file-name
10277 (file-name-as-directory
10278 default-directory))))
10279 (expand-file-name path))
10280 ;; We are linking a file with relative path name.
10281 (setq path (substring (expand-file-name path)
10282 (match-end 0)))
10283 (setq path (abbreviate-file-name (expand-file-name path)))))))
10284 (setq link (concat type path))
10285 (when (equal desc origpath)
10286 (setq desc path)))))
10288 (unless auto-desc
10289 (let ((initial-input
10290 (cond
10291 (default-description)
10292 ((not org-make-link-description-function) desc)
10293 (t (condition-case nil
10294 (funcall org-make-link-description-function link desc)
10295 (error
10296 (message "Can't get link description from `%s'"
10297 (symbol-name org-make-link-description-function))
10298 (sit-for 2)
10299 nil))))))
10300 (setq desc (read-string "Description: " initial-input))))
10302 (unless (string-match "\\S-" desc) (setq desc nil))
10303 (when remove (apply 'delete-region remove))
10304 (insert (org-make-link-string link desc))
10305 ;; Redisplay so as the new link has proper invisible characters.
10306 (sit-for 0)))
10308 (defun org-link-try-special-completion (type)
10309 "If there is completion support for link type TYPE, offer it."
10310 (let ((fun (org-link-get-parameter type :complete)))
10311 (if (functionp fun)
10312 (funcall fun)
10313 (read-string "Link (no completion support): " (concat type ":")))))
10315 (defun org-file-complete-link (&optional arg)
10316 "Create a file link using completion."
10317 (let ((file (read-file-name "File: "))
10318 (pwd (file-name-as-directory (expand-file-name ".")))
10319 (pwd1 (file-name-as-directory (abbreviate-file-name
10320 (expand-file-name ".")))))
10321 (cond ((equal arg '(16))
10322 (concat "file:"
10323 (abbreviate-file-name (expand-file-name file))))
10324 ((string-match
10325 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10326 (concat "file:" (match-string 1 file)))
10327 ((string-match
10328 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10329 (expand-file-name file))
10330 (concat "file:"
10331 (match-string 1 (expand-file-name file))))
10332 (t (concat "file:" file)))))
10334 (defun org-completing-read (&rest args)
10335 "Completing-read with SPACE being a normal character."
10336 (let ((enable-recursive-minibuffers t)
10337 (minibuffer-local-completion-map
10338 (copy-keymap minibuffer-local-completion-map)))
10339 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10340 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10341 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10342 'org-time-stamp-inactive)
10343 (apply #'completing-read args)))
10345 ;;; Opening/following a link
10347 (defvar org-link-search-failed nil)
10349 (defvar org-open-link-functions nil
10350 "Hook for functions finding a plain text link.
10351 These functions must take a single argument, the link content.
10352 They will be called for links that look like [[link text][description]]
10353 when LINK TEXT does not have a protocol like \"http:\" and does not look
10354 like a filename (e.g. \"./blue.png\").
10356 These functions will be called *before* Org attempts to resolve the
10357 link by doing text searches in the current buffer - so if you want a
10358 link \"[[target]]\" to still find \"<<target>>\", your function should
10359 handle this as a special case.
10361 When the function does handle the link, it must return a non-nil value.
10362 If it decides that it is not responsible for this link, it must return
10363 nil to indicate that that Org can continue with other options like
10364 exact and fuzzy text search.")
10366 (defun org-next-link (&optional search-backward)
10367 "Move forward to the next link.
10368 If the link is in hidden text, expose it."
10369 (interactive "P")
10370 (when (and org-link-search-failed (eq this-command last-command))
10371 (goto-char (point-min))
10372 (message "Link search wrapped back to beginning of buffer"))
10373 (setq org-link-search-failed nil)
10374 (let* ((pos (point))
10375 (ct (org-context))
10376 (a (assq :link ct))
10377 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10378 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10379 ((looking-at org-any-link-re)
10380 ;; Don't stay stuck at link without an org-link face
10381 (forward-char (if search-backward -1 1))))
10382 (if (funcall srch-fun org-any-link-re nil t)
10383 (progn
10384 (goto-char (match-beginning 0))
10385 (when (org-invisible-p) (org-show-context)))
10386 (goto-char pos)
10387 (setq org-link-search-failed t)
10388 (message "No further link found"))))
10390 (defun org-previous-link ()
10391 "Move backward to the previous link.
10392 If the link is in hidden text, expose it."
10393 (interactive)
10394 (funcall 'org-next-link t))
10396 (defun org-translate-link (s)
10397 "Translate a link string if a translation function has been defined."
10398 (with-temp-buffer
10399 (insert (org-trim s))
10400 (org-trim (org-element-interpret-data (org-element-context)))))
10402 (defun org-translate-link-from-planner (type path)
10403 "Translate a link from Emacs Planner syntax so that Org can follow it.
10404 This is still an experimental function, your mileage may vary."
10405 (cond
10406 ((member type '("http" "https" "news" "ftp"))
10407 ;; standard Internet links are the same.
10408 nil)
10409 ((and (equal type "irc") (string-match "^//" path))
10410 ;; Planner has two / at the beginning of an irc link, we have 1.
10411 ;; We should have zero, actually....
10412 (setq path (substring path 1)))
10413 ((and (equal type "lisp") (string-match "^/" path))
10414 ;; Planner has a slash, we do not.
10415 (setq type "elisp" path (substring path 1)))
10416 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10417 ;; A typical message link. Planner has the id after the final slash,
10418 ;; we separate it with a hash mark
10419 (setq path (concat (match-string 1 path) "#"
10420 (org-unbracket-string "<" ">" (match-string 2 path))))))
10421 (cons type path))
10423 (defun org-find-file-at-mouse (ev)
10424 "Open file link or URL at mouse."
10425 (interactive "e")
10426 (mouse-set-point ev)
10427 (org-open-at-point 'in-emacs))
10429 (defun org-open-at-mouse (ev)
10430 "Open file link or URL at mouse.
10431 See the docstring of `org-open-file' for details."
10432 (interactive "e")
10433 (mouse-set-point ev)
10434 (when (eq major-mode 'org-agenda-mode)
10435 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10436 (org-open-at-point))
10438 (defvar org-window-config-before-follow-link nil
10439 "The window configuration before following a link.
10440 This is saved in case the need arises to restore it.")
10442 ;;;###autoload
10443 (defun org-open-at-point-global ()
10444 "Follow a link or time-stamp like Org mode does.
10445 This command can be called in any mode to follow an external link
10446 or a time-stamp that has Org mode syntax. Its behavior is
10447 undefined when called on internal links (e.g., fuzzy links).
10448 Raise an error when there is nothing to follow. "
10449 (interactive)
10450 (cond ((org-in-regexp org-any-link-re)
10451 (org-open-link-from-string (match-string-no-properties 0)))
10452 ((or (org-in-regexp org-ts-regexp-both nil t)
10453 (org-in-regexp org-tsr-regexp-both nil t))
10454 (org-follow-timestamp-link))
10455 (t (user-error "No link found"))))
10457 ;;;###autoload
10458 (defun org-open-link-from-string (s &optional arg reference-buffer)
10459 "Open a link in the string S, as if it was in Org mode."
10460 (interactive "sLink: \nP")
10461 (let ((reference-buffer (or reference-buffer (current-buffer))))
10462 (with-temp-buffer
10463 (let ((org-inhibit-startup (not reference-buffer)))
10464 (org-mode)
10465 (insert s)
10466 (goto-char (point-min))
10467 (when reference-buffer
10468 (setq org-link-abbrev-alist-local
10469 (with-current-buffer reference-buffer
10470 org-link-abbrev-alist-local)))
10471 (org-open-at-point arg reference-buffer)))))
10473 (defvar org-open-at-point-functions nil
10474 "Hook that is run when following a link at point.
10476 Functions in this hook must return t if they identify and follow
10477 a link at point. If they don't find anything interesting at point,
10478 they must return nil.")
10480 (defvar org-link-search-inhibit-query nil)
10481 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10482 (defun org--open-doi-link (path)
10483 "Open a \"doi\" type link.
10484 PATH is a the path to search for, as a string."
10485 (browse-url (url-encode-url (concat org-doi-server-url path))))
10487 (defun org--open-elisp-link (path)
10488 "Open a \"elisp\" type link.
10489 PATH is the sexp to evaluate, as a string."
10490 (let ((cmd path))
10491 (if (or (and (org-string-nw-p
10492 org-confirm-elisp-link-not-regexp)
10493 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10494 (not org-confirm-elisp-link-function)
10495 (funcall org-confirm-elisp-link-function
10496 (format "Execute \"%s\" as elisp? "
10497 (org-add-props cmd nil 'face 'org-warning))))
10498 (message "%s => %s" cmd
10499 (if (eq (string-to-char cmd) ?\()
10500 (eval (read cmd))
10501 (call-interactively (read cmd))))
10502 (user-error "Abort"))))
10504 (defun org--open-help-link (path)
10505 "Open a \"help\" type link.
10506 PATH is a symbol name, as a string."
10507 (pcase (intern path)
10508 ((and (pred fboundp) variable) (describe-function variable))
10509 ((and (pred boundp) function) (describe-variable function))
10510 (name (user-error "Unknown function or variable: %s" name))))
10512 (defun org--open-shell-link (path)
10513 "Open a \"shell\" type link.
10514 PATH is the command to execute, as a string."
10515 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10516 (cmd path))
10517 (if (or (and (org-string-nw-p
10518 org-confirm-shell-link-not-regexp)
10519 (string-match
10520 org-confirm-shell-link-not-regexp cmd))
10521 (not org-confirm-shell-link-function)
10522 (funcall org-confirm-shell-link-function
10523 (format "Execute \"%s\" in shell? "
10524 (org-add-props cmd nil
10525 'face 'org-warning))))
10526 (progn
10527 (message "Executing %s" cmd)
10528 (shell-command cmd buf)
10529 (when (featurep 'midnight)
10530 (setq clean-buffer-list-kill-buffer-names
10531 (cons (buffer-name buf)
10532 clean-buffer-list-kill-buffer-names))))
10533 (user-error "Abort"))))
10535 (defun org-open-at-point (&optional arg reference-buffer)
10536 "Open link, timestamp, footnote or tags at point.
10538 When point is on a link, follow it. Normally, files will be
10539 opened by an appropriate application. If the optional prefix
10540 argument ARG is non-nil, Emacs will visit the file. With
10541 a double prefix argument, try to open outside of Emacs, in the
10542 application the system uses for this file type.
10544 When point is on a timestamp, open the agenda at the day
10545 specified.
10547 When point is a footnote definition, move to the first reference
10548 found. If it is on a reference, move to the associated
10549 definition.
10551 When point is on a headline, display a list of every link in the
10552 entry, so it is possible to pick one, or all, of them. If point
10553 is on a tag, call `org-tags-view' instead.
10555 When optional argument REFERENCE-BUFFER is non-nil, it should
10556 specify a buffer from where the link search should happen. This
10557 is used internally by `org-open-link-from-string'.
10559 On top of syntactically correct links, this function will also
10560 try to open links and time-stamps in comments, example
10561 blocks... i.e., whenever point is on something looking like
10562 a timestamp or a link."
10563 (interactive "P")
10564 ;; On a code block, open block's results.
10565 (unless (call-interactively 'org-babel-open-src-block-result)
10566 (org-load-modules-maybe)
10567 (setq org-window-config-before-follow-link (current-window-configuration))
10568 (org-remove-occur-highlights nil nil t)
10569 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10570 (let* ((context
10571 ;; Only consider supported types, even if they are not
10572 ;; the closest one.
10573 (org-element-lineage
10574 (org-element-context)
10575 '(clock footnote-definition footnote-reference headline
10576 inlinetask link timestamp)
10578 (type (org-element-type context))
10579 (value (org-element-property :value context)))
10580 (cond
10581 ;; On a headline or an inlinetask, but not on a timestamp,
10582 ;; a link, a footnote reference.
10583 ((memq type '(headline inlinetask))
10584 (org-match-line org-complex-heading-regexp)
10585 (if (and (match-beginning 5)
10586 (>= (point) (match-beginning 5))
10587 (< (point) (match-end 5)))
10588 ;; On tags.
10589 (org-tags-view arg (substring (match-string 5) 0 -1))
10590 ;; Not on tags.
10591 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10592 (`(nil . ,_)
10593 (require 'org-attach)
10594 (org-attach-reveal 'if-exists))
10595 (`(,links . ,links-end)
10596 (dolist (link (if (stringp links) (list links) links))
10597 (search-forward link nil links-end)
10598 (goto-char (match-beginning 0))
10599 (org-open-at-point))))))
10600 ;; On a footnote reference or at definition's label.
10601 ((or (eq type 'footnote-reference)
10602 (and (eq type 'footnote-definition)
10603 (save-excursion
10604 ;; Do not validate action when point is on the
10605 ;; spaces right after the footnote label, in
10606 ;; order to be on par with behaviour on links.
10607 (skip-chars-forward " \t")
10608 (let ((begin
10609 (org-element-property :contents-begin context)))
10610 (if begin (< (point) begin)
10611 (= (org-element-property :post-affiliated context)
10612 (line-beginning-position)))))))
10613 (org-footnote-action))
10614 ;; No valid context. Ignore catch-all types like `headline'.
10615 ;; If point is on something looking like a link or
10616 ;; a time-stamp, try opening it. It may be useful in
10617 ;; comments, example blocks...
10618 ((memq type '(footnote-definition headline inlinetask nil))
10619 (call-interactively #'org-open-at-point-global))
10620 ;; On a clock line, make sure point is on the timestamp
10621 ;; before opening it.
10622 ((and (eq type 'clock)
10623 value
10624 (>= (point) (org-element-property :begin value))
10625 (<= (point) (org-element-property :end value)))
10626 (org-follow-timestamp-link))
10627 ;; Do nothing on white spaces after an object.
10628 ((>= (point)
10629 (save-excursion
10630 (goto-char (org-element-property :end context))
10631 (skip-chars-backward " \t")
10632 (point)))
10633 (user-error "No link found"))
10634 ((eq type 'timestamp) (org-follow-timestamp-link))
10635 ((eq type 'link)
10636 (let ((type (org-element-property :type context))
10637 (path (org-link-unescape (org-element-property :path context))))
10638 ;; Switch back to REFERENCE-BUFFER needed when called in
10639 ;; a temporary buffer through `org-open-link-from-string'.
10640 (with-current-buffer (or reference-buffer (current-buffer))
10641 (cond
10642 ((equal type "file")
10643 (if (string-match "[*?{]" (file-name-nondirectory path))
10644 (dired path)
10645 ;; Look into `org-link-parameters' in order to find
10646 ;; a DEDICATED-FUNCTION to open file. The function
10647 ;; will be applied on raw link instead of parsed
10648 ;; link due to the limitation in `org-add-link-type'
10649 ;; ("open" function called with a single argument).
10650 ;; If no such function is found, fallback to
10651 ;; `org-open-file'.
10652 (let* ((option (org-element-property :search-option context))
10653 (app (org-element-property :application context))
10654 (dedicated-function
10655 (org-link-get-parameter
10656 (if app (concat type "+" app) type)
10657 :follow)))
10658 (if dedicated-function
10659 (funcall dedicated-function
10660 (concat path
10661 (and option (concat "::" option))))
10662 (apply #'org-open-file
10663 path
10664 (cond (arg)
10665 ((equal app "emacs") 'emacs)
10666 ((equal app "sys") 'system))
10667 (cond ((not option) nil)
10668 ((string-match-p "\\`[0-9]+\\'" option)
10669 (list (string-to-number option)))
10670 (t (list nil
10671 (org-link-unescape option)))))))))
10672 ((functionp (org-link-get-parameter type :follow))
10673 (funcall (org-link-get-parameter type :follow) path))
10674 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10675 (unless (run-hook-with-args-until-success
10676 'org-open-link-functions path)
10677 (if (not arg) (org-mark-ring-push)
10678 (switch-to-buffer-other-window
10679 (org-get-buffer-for-internal-link (current-buffer))))
10680 (let ((destination
10681 (org-with-wide-buffer
10682 (if (equal type "radio")
10683 (org-search-radio-target
10684 (org-element-property :path context))
10685 (org-link-search
10686 (if (member type '("custom-id" "coderef"))
10687 (org-element-property :raw-link context)
10688 path)
10689 ;; Prevent fuzzy links from matching
10690 ;; themselves.
10691 (and (equal type "fuzzy")
10692 (+ 2 (org-element-property :begin context)))))
10693 (point))))
10694 (unless (and (<= (point-min) destination)
10695 (>= (point-max) destination))
10696 (widen))
10697 (goto-char destination))))
10698 (t (browse-url-at-point))))))
10699 (t (user-error "No link found")))))
10700 (run-hook-with-args 'org-follow-link-hook)))
10702 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10703 "Offer links in the current entry and return the selected link.
10704 If there is only one link, return it.
10705 If NTH is an integer, return the NTH link found.
10706 If ZERO is a string, check also this string for a link, and if
10707 there is one, return it."
10708 (with-current-buffer buffer
10709 (org-with-wide-buffer
10710 (goto-char marker)
10711 (let ((cnt ?0)
10712 have-zero end links link c)
10713 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10714 (push (match-string 0 zero) links)
10715 (setq cnt (1- cnt) have-zero t))
10716 (save-excursion
10717 (org-back-to-heading t)
10718 (setq end (save-excursion (outline-next-heading) (point)))
10719 (while (re-search-forward org-any-link-re end t)
10720 (push (match-string 0) links))
10721 (setq links (org-uniquify (reverse links))))
10722 (cond
10723 ((null links)
10724 (message "No links"))
10725 ((equal (length links) 1)
10726 (setq link (car links)))
10727 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10728 (setq link (nth (if have-zero nth (1- nth)) links)))
10729 (t ; we have to select a link
10730 (save-excursion
10731 (save-window-excursion
10732 (delete-other-windows)
10733 (with-output-to-temp-buffer "*Select Link*"
10734 (dolist (l links)
10735 (cond
10736 ((not (string-match org-bracket-link-regexp l))
10737 (princ (format "[%c] %s\n" (cl-incf cnt)
10738 (org-unbracket-string "<" ">" l))))
10739 ((match-end 3)
10740 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10741 (match-string 3 l) (match-string 1 l))))
10742 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10743 (match-string 1 l)))))))
10744 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10745 (message "Select link to open, RET to open all:")
10746 (setq c (read-char-exclusive))
10747 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10748 (when (equal c ?q) (user-error "Abort"))
10749 (if (equal c ?\C-m)
10750 (setq link links)
10751 (setq nth (- c ?0))
10752 (when have-zero (setq nth (1+ nth)))
10753 (unless (and (integerp nth) (>= (length links) nth))
10754 (user-error "Invalid link selection"))
10755 (setq link (nth (1- nth) links)))))
10756 (cons link end)))))
10758 ;; TODO: These functions are deprecated since `org-open-at-point'
10759 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10760 (defun org-open-file-with-system (path)
10761 "Open file at PATH using the system way of opening it."
10762 (org-open-file path 'system))
10763 (defun org-open-file-with-emacs (path)
10764 "Open file at PATH in Emacs."
10765 (org-open-file path 'emacs))
10768 ;;; File search
10770 (defvar org-create-file-search-functions nil
10771 "List of functions to construct the right search string for a file link.
10772 These functions are called in turn with point at the location to
10773 which the link should point.
10775 A function in the hook should first test if it would like to
10776 handle this file type, for example by checking the `major-mode'
10777 or the file extension. If it decides not to handle this file, it
10778 should just return nil to give other functions a chance. If it
10779 does handle the file, it must return the search string to be used
10780 when following the link. The search string will be part of the
10781 file link, given after a double colon, and `org-open-at-point'
10782 will automatically search for it. If special measures must be
10783 taken to make the search successful, another function should be
10784 added to the companion hook `org-execute-file-search-functions',
10785 which see.
10787 A function in this hook may also use `setq' to set the variable
10788 `description' to provide a suggestion for the descriptive text to
10789 be used for this link when it gets inserted into an Org buffer
10790 with \\[org-insert-link].")
10792 (defvar org-execute-file-search-functions nil
10793 "List of functions to execute a file search triggered by a link.
10795 Functions added to this hook must accept a single argument, the
10796 search string that was part of the file link, the part after the
10797 double colon. The function must first check if it would like to
10798 handle this search, for example by checking the `major-mode' or
10799 the file extension. If it decides not to handle this search, it
10800 should just return nil to give other functions a chance. If it
10801 does handle the search, it must return a non-nil value to keep
10802 other functions from trying.
10804 Each function can access the current prefix argument through the
10805 variable `current-prefix-arg'. Note that a single prefix is used
10806 to force opening a link in Emacs, so it may be good to only use a
10807 numeric or double prefix to guide the search function.
10809 In case this is needed, a function in this hook can also restore
10810 the window configuration before `org-open-at-point' was called using:
10812 (set-window-configuration org-window-config-before-follow-link)")
10814 (defun org-search-radio-target (target)
10815 "Search a radio target matching TARGET in current buffer.
10816 White spaces are not significant."
10817 (let ((re (format "<<<%s>>>"
10818 (mapconcat #'regexp-quote
10819 (split-string target)
10820 "[ \t]+\\(?:\n[ \t]*\\)?")))
10821 (origin (point)))
10822 (goto-char (point-min))
10823 (catch :radio-match
10824 (while (re-search-forward re nil t)
10825 (backward-char)
10826 (let ((object (org-element-context)))
10827 (when (eq (org-element-type object) 'radio-target)
10828 (goto-char (org-element-property :begin object))
10829 (org-show-context 'link-search)
10830 (throw :radio-match nil))))
10831 (goto-char origin)
10832 (user-error "No match for radio target: %s" target))))
10834 (defun org-link-search (s &optional avoid-pos stealth)
10835 "Search for a search string S.
10837 If S starts with \"#\", it triggers a custom ID search.
10839 If S is enclosed within parenthesis, it initiates a coderef
10840 search.
10842 If S is surrounded by forward slashes, it is interpreted as
10843 a regular expression. In Org mode files, this will create an
10844 `org-occur' sparse tree. In ordinary files, `occur' will be used
10845 to list matches. If the current buffer is in `dired-mode', grep
10846 will be used to search in all files.
10848 When AVOID-POS is given, ignore matches near that position.
10850 When optional argument STEALTH is non-nil, do not modify
10851 visibility around point, thus ignoring `org-show-context-detail'
10852 variable.
10854 Search is case-insensitive and ignores white spaces. Return type
10855 of matched result, which is either `dedicated' or `fuzzy'."
10856 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10857 (let* ((case-fold-search t)
10858 (origin (point))
10859 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10860 (starred (eq (string-to-char normalized) ?*))
10861 (words (split-string (if starred (substring s 1) s)))
10862 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10863 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10864 type)
10865 (cond
10866 ;; Check if there are any special search functions.
10867 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10868 ((eq (string-to-char s) ?#)
10869 ;; Look for a custom ID S if S starts with "#".
10870 (let* ((id (substring normalized 1))
10871 (match (org-find-property "CUSTOM_ID" id)))
10872 (if match (progn (goto-char match) (setf type 'dedicated))
10873 (error "No match for custom ID: %s" id))))
10874 ((string-match "\\`(\\(.*\\))\\'" normalized)
10875 ;; Look for coderef targets if S is enclosed within parenthesis.
10876 (let ((coderef (match-string-no-properties 1 normalized))
10877 (re (substring s-single-re 1 -1)))
10878 (goto-char (point-min))
10879 (catch :coderef-match
10880 (while (re-search-forward re nil t)
10881 (let ((element (org-element-at-point)))
10882 (when (and (memq (org-element-type element)
10883 '(example-block src-block))
10884 ;; Build proper regexp according to current
10885 ;; block's label format.
10886 (let ((label-fmt
10887 (regexp-quote
10888 (or (org-element-property :label-fmt element)
10889 org-coderef-label-format))))
10890 (save-excursion
10891 (beginning-of-line)
10892 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10893 (format label-fmt coderef))))))
10894 (setq type 'dedicated)
10895 (goto-char (match-beginning 1))
10896 (throw :coderef-match nil))))
10897 (goto-char origin)
10898 (error "No match for coderef: %s" coderef))))
10899 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10900 ;; Look for a regular expression.
10901 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10902 (match-string 1 s)))
10903 ;; From here, we handle fuzzy links.
10905 ;; Look for targets, only if not in a headline search.
10906 ((and (not starred)
10907 (let ((target (format "<<%s>>" s-multi-re)))
10908 (catch :target-match
10909 (goto-char (point-min))
10910 (while (re-search-forward target nil t)
10911 (backward-char)
10912 (let ((context (org-element-context)))
10913 (when (eq (org-element-type context) 'target)
10914 (setq type 'dedicated)
10915 (goto-char (org-element-property :begin context))
10916 (throw :target-match t))))
10917 nil))))
10918 ;; Look for elements named after S, only if not in a headline
10919 ;; search.
10920 ((and (not starred)
10921 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10922 (catch :name-match
10923 (goto-char (point-min))
10924 (while (re-search-forward name nil t)
10925 (let ((element (org-element-at-point)))
10926 (when (equal words
10927 (split-string
10928 (org-element-property :name element)))
10929 (setq type 'dedicated)
10930 (beginning-of-line)
10931 (throw :name-match t))))
10932 nil))))
10933 ;; Regular text search. Prefer headlines in Org mode buffers.
10934 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10935 ;; statistics cookies and tags.
10936 ((and (derived-mode-p 'org-mode)
10937 (let ((title-re
10938 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10939 org-outline-regexp-bol
10940 org-comment-string
10941 (mapconcat #'regexp-quote words ".+")))
10942 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10943 (comment-re (eval-when-compile
10944 (format "\\`%s[ \t]+" org-comment-string))))
10945 (goto-char (point-min))
10946 (catch :found
10947 (while (re-search-forward title-re nil t)
10948 (when (equal words
10949 (split-string
10950 (replace-regexp-in-string
10951 cookie-re ""
10952 (replace-regexp-in-string
10953 comment-re "" (org-get-heading t t t)))))
10954 (throw :found t)))
10955 nil)))
10956 (beginning-of-line)
10957 (setq type 'dedicated))
10958 ;; Offer to create non-existent headline depending on
10959 ;; `org-link-search-must-match-exact-headline'.
10960 ((and (derived-mode-p 'org-mode)
10961 (not org-link-search-inhibit-query)
10962 (eq org-link-search-must-match-exact-headline 'query-to-create)
10963 (yes-or-no-p "No match - create this as a new heading? "))
10964 (goto-char (point-max))
10965 (unless (bolp) (newline))
10966 (org-insert-heading nil t t)
10967 (insert s "\n")
10968 (beginning-of-line 0))
10969 ;; Only headlines are looked after. No need to process
10970 ;; further: throw an error.
10971 ((and (derived-mode-p 'org-mode)
10972 (or starred org-link-search-must-match-exact-headline))
10973 (goto-char origin)
10974 (error "No match for fuzzy expression: %s" normalized))
10975 ;; Regular text search.
10976 ((catch :fuzzy-match
10977 (goto-char (point-min))
10978 (while (re-search-forward s-multi-re nil t)
10979 ;; Skip match if it contains AVOID-POS or it is included in
10980 ;; a link with a description but outside the description.
10981 (unless (or (and avoid-pos
10982 (<= (match-beginning 0) avoid-pos)
10983 (> (match-end 0) avoid-pos))
10984 (and (save-match-data
10985 (org-in-regexp org-bracket-link-regexp))
10986 (match-beginning 3)
10987 (or (> (match-beginning 3) (point))
10988 (<= (match-end 3) (point)))
10989 (org-element-lineage
10990 (save-match-data (org-element-context))
10991 '(link) t)))
10992 (goto-char (match-beginning 0))
10993 (setq type 'fuzzy)
10994 (throw :fuzzy-match t)))
10995 nil))
10996 ;; All failed. Throw an error.
10997 (t (goto-char origin)
10998 (error "No match for fuzzy expression: %s" normalized)))
10999 ;; Disclose surroundings of match, if appropriate.
11000 (when (and (derived-mode-p 'org-mode) (not stealth))
11001 (org-show-context 'link-search))
11002 type))
11004 (defun org-get-buffer-for-internal-link (buffer)
11005 "Return a buffer to be used for displaying the link target of internal links."
11006 (cond
11007 ((not org-display-internal-link-with-indirect-buffer)
11008 buffer)
11009 ((string-suffix-p "(Clone)" (buffer-name buffer))
11010 (message "Buffer is already a clone, not making another one")
11011 ;; we also do not modify visibility in this case
11012 buffer)
11013 (t ; make a new indirect buffer for displaying the link
11014 (let* ((bn (buffer-name buffer))
11015 (ibn (concat bn "(Clone)"))
11016 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11017 (with-current-buffer ib (org-overview))
11018 ib))))
11020 (defun org-do-occur (regexp &optional cleanup)
11021 "Call the Emacs command `occur'.
11022 If CLEANUP is non-nil, remove the printout of the regular expression
11023 in the *Occur* buffer. This is useful if the regex is long and not useful
11024 to read."
11025 (occur regexp)
11026 (when cleanup
11027 (let ((cwin (selected-window)) win beg end)
11028 (when (setq win (get-buffer-window "*Occur*"))
11029 (select-window win))
11030 (goto-char (point-min))
11031 (when (re-search-forward "match[a-z]+" nil t)
11032 (setq beg (match-end 0))
11033 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11034 (setq end (1- (match-beginning 0)))))
11035 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11036 (goto-char (point-min))
11037 (select-window cwin))))
11039 ;;; The mark ring for links jumps
11041 (defvar org-mark-ring nil
11042 "Mark ring for positions before jumps in Org mode.")
11043 (defvar org-mark-ring-last-goto nil
11044 "Last position in the mark ring used to go back.")
11045 ;; Fill and close the ring
11046 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11047 (dotimes (_ org-mark-ring-length)
11048 (push (make-marker) org-mark-ring))
11049 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11050 org-mark-ring)
11052 (defun org-mark-ring-push (&optional pos buffer)
11053 "Put the current position or POS into the mark ring and rotate it."
11054 (interactive)
11055 (setq pos (or pos (point)))
11056 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11057 (move-marker (car org-mark-ring)
11058 (or pos (point))
11059 (or buffer (current-buffer)))
11060 (message "%s"
11061 (substitute-command-keys
11062 "Position saved to mark ring, go back with \
11063 `\\[org-mark-ring-goto]'.")))
11065 (defun org-mark-ring-goto (&optional n)
11066 "Jump to the previous position in the mark ring.
11067 With prefix arg N, jump back that many stored positions. When
11068 called several times in succession, walk through the entire ring.
11069 Org mode commands jumping to a different position in the current file,
11070 or to another Org file, automatically push the old position onto the ring."
11071 (interactive "p")
11072 (let (p m)
11073 (if (eq last-command this-command)
11074 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11075 (setq p org-mark-ring))
11076 (setq org-mark-ring-last-goto p)
11077 (setq m (car p))
11078 (pop-to-buffer-same-window (marker-buffer m))
11079 (goto-char m)
11080 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11082 (defun org-add-angle-brackets (s)
11083 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11084 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11087 ;;; Following specific links
11089 (defvar org-agenda-buffer-tmp-name)
11090 (defvar org-agenda-start-on-weekday)
11091 (defun org-follow-timestamp-link ()
11092 "Open an agenda view for the time-stamp date/range at point."
11093 (cond
11094 ((org-at-date-range-p t)
11095 (let ((org-agenda-start-on-weekday)
11096 (t1 (match-string 1))
11097 (t2 (match-string 2)) tt1 tt2)
11098 (setq tt1 (time-to-days (org-time-string-to-time t1))
11099 tt2 (time-to-days (org-time-string-to-time t2)))
11100 (let ((org-agenda-buffer-tmp-name
11101 (format "*Org Agenda(a:%s)"
11102 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11103 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11104 ((org-at-timestamp-p 'lax)
11105 (let ((org-agenda-buffer-tmp-name
11106 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11107 (org-agenda-list nil (time-to-days (org-time-string-to-time
11108 (substring (match-string 1) 0 10)))
11109 1)))
11110 (t (error "This should not happen"))))
11113 ;;; Following file links
11114 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11115 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11116 (declare-function mailcap-mime-info
11117 "mailcap" (string &optional request no-decode))
11118 (defvar org-wait nil)
11119 (defun org-open-file (path &optional in-emacs line search)
11120 "Open the file at PATH.
11121 First, this expands any special file name abbreviations. Then the
11122 configuration variable `org-file-apps' is checked if it contains an
11123 entry for this file type, and if yes, the corresponding command is launched.
11125 If no application is found, Emacs simply visits the file.
11127 With optional prefix argument IN-EMACS, Emacs will visit the file.
11128 With a double \\[universal-argument] \\[universal-argument] \
11129 prefix arg, Org tries to avoid opening in Emacs
11130 and to use an external application to visit the file.
11132 Optional LINE specifies a line to go to, optional SEARCH a string
11133 to search for. If LINE or SEARCH is given, the file will be
11134 opened in Emacs, unless an entry from org-file-apps that makes
11135 use of groups in a regexp matches.
11137 If you want to change the way frames are used when following a
11138 link, please customize `org-link-frame-setup'.
11140 If the file does not exist, an error is thrown."
11141 (let* ((file (if (equal path "")
11142 buffer-file-name
11143 (substitute-in-file-name (expand-file-name path))))
11144 (file-apps (append org-file-apps (org-default-apps)))
11145 (apps (cl-remove-if
11146 'org-file-apps-entry-match-against-dlink-p file-apps))
11147 (apps-dlink (cl-remove-if-not
11148 'org-file-apps-entry-match-against-dlink-p file-apps))
11149 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11150 (dirp (unless remp (file-directory-p file)))
11151 (file (if (and dirp org-open-directory-means-index-dot-org)
11152 (concat (file-name-as-directory file) "index.org")
11153 file))
11154 (a-m-a-p (assq 'auto-mode apps))
11155 (dfile (downcase file))
11156 ;; Reconstruct the original link from the PATH, LINE and
11157 ;; SEARCH args.
11158 (link (cond (line (concat file "::" (number-to-string line)))
11159 (search (concat file "::" search))
11160 (t file)))
11161 (dlink (downcase link))
11162 (ext
11163 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11164 (match-string 1 dfile)))
11165 (save-position-maybe
11166 (let ((old-buffer (current-buffer))
11167 (old-pos (point))
11168 (old-mode major-mode))
11169 (lambda ()
11170 (and (derived-mode-p 'org-mode)
11171 (eq old-mode 'org-mode)
11172 (or (not (eq old-buffer (current-buffer)))
11173 (not (eq old-pos (point))))
11174 (org-mark-ring-push old-pos old-buffer)))))
11175 cmd link-match-data)
11176 (cond
11177 ((member in-emacs '((16) system))
11178 (setq cmd (cdr (assq 'system apps))))
11179 (in-emacs (setq cmd 'emacs))
11181 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11182 (and dirp (cdr (assq 'directory apps)))
11183 ;; First, try matching against apps-dlink if we
11184 ;; get a match here, store the match data for
11185 ;; later.
11186 (let ((match (assoc-default dlink apps-dlink
11187 'string-match)))
11188 (if match
11189 (progn (setq link-match-data (match-data))
11190 match)
11191 (progn (setq in-emacs (or in-emacs line search))
11192 nil))) ; if we have no match in apps-dlink,
11193 ; always open the file in emacs if line or search
11194 ; is given (for backwards compatibility)
11195 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11196 'string-match)
11197 (cdr (assoc ext apps))
11198 (cdr (assq t apps))))))
11199 (when (eq cmd 'system)
11200 (setq cmd (cdr (assq 'system apps))))
11201 (when (eq cmd 'default)
11202 (setq cmd (cdr (assoc t apps))))
11203 (when (eq cmd 'mailcap)
11204 (require 'mailcap)
11205 (mailcap-parse-mailcaps)
11206 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11207 (command (mailcap-mime-info mime-type)))
11208 (if (stringp command)
11209 (setq cmd command)
11210 (setq cmd 'emacs))))
11211 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11212 (not (file-exists-p file))
11213 (not org-open-non-existing-files))
11214 (user-error "No such file: %s" file))
11215 (cond
11216 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11217 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11218 (while (string-match "['\"]%s['\"]" cmd)
11219 (setq cmd (replace-match "%s" t t cmd)))
11220 (setq cmd (replace-regexp-in-string
11221 "%s"
11222 (shell-quote-argument (convert-standard-filename file))
11224 nil t))
11226 ;; Replace "%1", "%2" etc. in command with group matches from regex
11227 (save-match-data
11228 (let ((match-index 1)
11229 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11230 (set-match-data link-match-data)
11231 (while (<= match-index number-of-groups)
11232 (let ((regex (concat "%" (number-to-string match-index)))
11233 (replace-with (match-string match-index dlink)))
11234 (while (string-match regex cmd)
11235 (setq cmd (replace-match replace-with t t cmd))))
11236 (setq match-index (+ match-index 1)))))
11238 (save-window-excursion
11239 (message "Running %s...done" cmd)
11240 (start-process-shell-command cmd nil cmd)
11241 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11242 ((or (stringp cmd)
11243 (eq cmd 'emacs))
11244 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11245 (widen)
11246 (cond (line (org-goto-line line)
11247 (when (derived-mode-p 'org-mode) (org-reveal)))
11248 (search (condition-case err
11249 (org-link-search search)
11250 ;; Save position before error-ing out so user
11251 ;; can easily move back to the original buffer.
11252 (error (funcall save-position-maybe)
11253 (error (nth 1 err)))))))
11254 ((functionp cmd)
11255 (save-match-data
11256 (set-match-data link-match-data)
11257 (condition-case nil
11258 (funcall cmd file link)
11259 ;; FIXME: Remove this check when most default installations
11260 ;; of Emacs have at least Org 9.0.
11261 ((debug wrong-number-of-arguments wrong-type-argument
11262 invalid-function)
11263 (user-error "Please see Org News for version 9.0 about \
11264 `org-file-apps'--Lisp error: %S" cmd)))))
11265 ((consp cmd)
11266 ;; FIXME: Remove this check when most default installations of
11267 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11268 ;; fall back to `org-link-frame-setup' for an old usage of
11269 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11270 (user-error "Please see Org News for version 9.0 about \
11271 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11272 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11273 (funcall save-position-maybe)))
11275 (defun org-file-apps-entry-match-against-dlink-p (entry)
11276 "This function returns non-nil if `entry' uses a regular
11277 expression which should be matched against the whole link by
11278 org-open-file.
11280 It assumes that is the case when the entry uses a regular
11281 expression which has at least one grouping construct and the
11282 action is either a lisp form or a command string containing
11283 `%1', i.e. using at least one subexpression match as a
11284 parameter."
11285 (let ((selector (car entry))
11286 (action (cdr entry)))
11287 (if (stringp selector)
11288 (and (> (regexp-opt-depth selector) 0)
11289 (or (and (stringp action)
11290 (string-match "%[0-9]" action))
11291 (consp action)))
11292 nil)))
11294 (defun org-default-apps ()
11295 "Return the default applications for this operating system."
11296 (cond
11297 ((eq system-type 'darwin)
11298 org-file-apps-defaults-macosx)
11299 ((eq system-type 'windows-nt)
11300 org-file-apps-defaults-windowsnt)
11301 (t org-file-apps-defaults-gnu)))
11303 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11304 "Convert extensions to regular expressions in the cars of LIST.
11305 Also, weed out any non-string entries, because the return value is used
11306 only for regexp matching.
11307 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11308 point to the symbol `emacs', indicating that the file should
11309 be opened in Emacs."
11310 (append
11311 (delq nil
11312 (mapcar (lambda (x)
11313 (unless (not (stringp (car x)))
11314 (if (string-match "\\W" (car x))
11316 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11317 list))
11318 (when add-auto-mode
11319 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11321 (defvar ange-ftp-name-format)
11322 (defun org-file-remote-p (file)
11323 "Test whether FILE specifies a location on a remote system.
11324 Return non-nil if the location is indeed remote.
11326 For example, the filename \"/user@host:/foo\" specifies a location
11327 on the system \"/user@host:\"."
11328 (cond ((fboundp 'file-remote-p)
11329 (file-remote-p file))
11330 ((fboundp 'tramp-handle-file-remote-p)
11331 (tramp-handle-file-remote-p file))
11332 ((and (boundp 'ange-ftp-name-format)
11333 (string-match (car ange-ftp-name-format) file))
11334 t)))
11337 ;;;; Refiling
11339 (defun org-get-org-file ()
11340 "Read a filename, with default directory `org-directory'."
11341 (let ((default (or org-default-notes-file remember-data-file)))
11342 (read-file-name (format "File name [%s]: " default)
11343 (file-name-as-directory org-directory)
11344 default)))
11346 (defun org-notes-order-reversed-p ()
11347 "Check if the current file should receive notes in reversed order."
11348 (cond
11349 ((not org-reverse-note-order) nil)
11350 ((eq t org-reverse-note-order) t)
11351 ((not (listp org-reverse-note-order)) nil)
11352 (t (catch 'exit
11353 (dolist (entry org-reverse-note-order)
11354 (when (string-match (car entry) buffer-file-name)
11355 (throw 'exit (cdr entry))))))))
11357 (defvar org-refile-target-table nil
11358 "The list of refile targets, created by `org-refile'.")
11360 (defvar org-agenda-new-buffers nil
11361 "Buffers created to visit agenda files.")
11363 (defvar org-refile-cache nil
11364 "Cache for refile targets.")
11366 (defvar org-refile-markers nil
11367 "All the markers used for caching refile locations.")
11369 (defun org-refile-marker (pos)
11370 "Get a new refile marker, but only if caching is in use."
11371 (if (not org-refile-use-cache)
11373 (let ((m (make-marker)))
11374 (move-marker m pos)
11375 (push m org-refile-markers)
11376 m)))
11378 (defun org-refile-cache-clear ()
11379 "Clear the refile cache and disable all the markers."
11380 (dolist (m org-refile-markers) (move-marker m nil))
11381 (setq org-refile-markers nil)
11382 (setq org-refile-cache nil)
11383 (message "Refile cache has been cleared"))
11385 (defun org-refile-cache-check-set (set)
11386 "Check if all the markers in the cache still have live buffers."
11387 (let (marker)
11388 (catch 'exit
11389 (while (and set (setq marker (nth 3 (pop set))))
11390 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11391 (when (and marker (null (marker-buffer marker)))
11392 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11393 (sit-for 3)
11394 (throw 'exit nil)))
11395 t)))
11397 (defun org-refile-cache-put (set &rest identifiers)
11398 "Push the refile targets SET into the cache, under IDENTIFIERS."
11399 (let* ((key (sha1 (prin1-to-string identifiers)))
11400 (entry (assoc key org-refile-cache)))
11401 (if entry
11402 (setcdr entry set)
11403 (push (cons key set) org-refile-cache))))
11405 (defun org-refile-cache-get (&rest identifiers)
11406 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11407 (cond
11408 ((not org-refile-cache) nil)
11409 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11411 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11412 org-refile-cache))))
11413 (and set (org-refile-cache-check-set set) set)))))
11415 (defvar org-outline-path-cache nil
11416 "Alist between buffer positions and outline paths.
11417 It value is an alist (POSITION . PATH) where POSITION is the
11418 buffer position at the beginning of an entry and PATH is a list
11419 of strings describing the outline path for that entry, in reverse
11420 order.")
11422 (defun org-refile-get-targets (&optional default-buffer)
11423 "Produce a table with refile targets."
11424 (let ((case-fold-search nil)
11425 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11426 (entries (or org-refile-targets '((nil . (:level . 1)))))
11427 targets tgs files desc descre)
11428 (message "Getting targets...")
11429 (with-current-buffer (or default-buffer (current-buffer))
11430 (dolist (entry entries)
11431 (setq files (car entry) desc (cdr entry))
11432 (cond
11433 ((null files) (setq files (list (current-buffer))))
11434 ((eq files 'org-agenda-files)
11435 (setq files (org-agenda-files 'unrestricted)))
11436 ((and (symbolp files) (fboundp files))
11437 (setq files (funcall files)))
11438 ((and (symbolp files) (boundp files))
11439 (setq files (symbol-value files))))
11440 (when (stringp files) (setq files (list files)))
11441 (cond
11442 ((eq (car desc) :tag)
11443 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11444 ((eq (car desc) :todo)
11445 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11446 ((eq (car desc) :regexp)
11447 (setq descre (cdr desc)))
11448 ((eq (car desc) :level)
11449 (setq descre (concat "^\\*\\{" (number-to-string
11450 (if org-odd-levels-only
11451 (1- (* 2 (cdr desc)))
11452 (cdr desc)))
11453 "\\}[ \t]")))
11454 ((eq (car desc) :maxlevel)
11455 (setq descre (concat "^\\*\\{1," (number-to-string
11456 (if org-odd-levels-only
11457 (1- (* 2 (cdr desc)))
11458 (cdr desc)))
11459 "\\}[ \t]")))
11460 (t (error "Bad refiling target description %s" desc)))
11461 (dolist (f files)
11462 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11464 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11465 (progn
11466 (when (bufferp f)
11467 (setq f (buffer-file-name (buffer-base-buffer f))))
11468 (setq f (and f (expand-file-name f)))
11469 (when (eq org-refile-use-outline-path 'file)
11470 (push (list (file-name-nondirectory f) f nil nil) tgs))
11471 (when (eq org-refile-use-outline-path 'buffer-name)
11472 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11473 (when (eq org-refile-use-outline-path 'full-file-path)
11474 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11475 (org-with-wide-buffer
11476 (goto-char (point-min))
11477 (setq org-outline-path-cache nil)
11478 (while (re-search-forward descre nil t)
11479 (beginning-of-line)
11480 (let ((case-fold-search nil))
11481 (looking-at org-complex-heading-regexp))
11482 (let ((begin (point))
11483 (heading (match-string-no-properties 4)))
11484 (unless (or (and
11485 org-refile-target-verify-function
11486 (not
11487 (funcall org-refile-target-verify-function)))
11488 (not heading))
11489 (let ((re (format org-complex-heading-regexp-format
11490 (regexp-quote heading)))
11491 (target
11492 (if (not org-refile-use-outline-path) heading
11493 (mapconcat
11494 #'identity
11495 (append
11496 (pcase org-refile-use-outline-path
11497 (`file (list (file-name-nondirectory
11498 (buffer-file-name
11499 (buffer-base-buffer)))))
11500 (`full-file-path
11501 (list (buffer-file-name
11502 (buffer-base-buffer))))
11503 (`buffer-name
11504 (list (buffer-name
11505 (buffer-base-buffer))))
11506 (_ nil))
11507 (mapcar (lambda (s) (replace-regexp-in-string
11508 "/" "\\/" s nil t))
11509 (org-get-outline-path t t)))
11510 "/"))))
11511 (push (list target f re (org-refile-marker (point)))
11512 tgs)))
11513 (when (= (point) begin)
11514 ;; Verification function has not moved point.
11515 (end-of-line)))))))
11516 (when org-refile-use-cache
11517 (org-refile-cache-put tgs (buffer-file-name) descre))
11518 (setq targets (append tgs targets))))))
11519 (message "Getting targets...done")
11520 (delete-dups (nreverse targets))))
11522 (defun org--get-outline-path-1 (&optional use-cache)
11523 "Return outline path to current headline.
11525 Outline path is a list of strings, in reverse order. When
11526 optional argument USE-CACHE is non-nil, make use of a cache. See
11527 `org-get-outline-path' for details.
11529 Assume buffer is widened and point is on a headline."
11530 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11531 (let ((p (point))
11532 (heading (let ((case-fold-search nil))
11533 (looking-at org-complex-heading-regexp)
11534 (if (not (match-end 4)) ""
11535 ;; Remove statistics cookies.
11536 (org-trim
11537 (org-link-display-format
11538 (replace-regexp-in-string
11539 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11540 (match-string-no-properties 4))))))))
11541 (if (org-up-heading-safe)
11542 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11543 (when use-cache
11544 (push (cons p path) org-outline-path-cache))
11545 path)
11546 ;; This is a new root node. Since we assume we are moving
11547 ;; forward, we can drop previous cache so as to limit number
11548 ;; of associations there.
11549 (let ((path (list heading)))
11550 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11551 path)))))
11553 (defun org-get-outline-path (&optional with-self use-cache)
11554 "Return the outline path to the current entry.
11556 An outline path is a list of ancestors for current headline, as
11557 a list of strings. Statistics cookies are removed and links are
11558 replaced with their description, if any, or their path otherwise.
11560 When optional argument WITH-SELF is non-nil, the path also
11561 includes the current headline.
11563 When optional argument USE-CACHE is non-nil, cache outline paths
11564 between calls to this function so as to avoid backtracking. This
11565 argument is useful when planning to find more than one outline
11566 path in the same document. In that case, there are two
11567 conditions to satisfy:
11568 - `org-outline-path-cache' is set to nil before starting the
11569 process;
11570 - outline paths are computed by increasing buffer positions."
11571 (org-with-wide-buffer
11572 (and (or (and with-self (org-back-to-heading t))
11573 (org-up-heading-safe))
11574 (reverse (org--get-outline-path-1 use-cache)))))
11576 (defun org-format-outline-path (path &optional width prefix separator)
11577 "Format the outline path PATH for display.
11578 WIDTH is the maximum number of characters that is available.
11579 PREFIX is a prefix to be included in the returned string,
11580 such as the file name.
11581 SEPARATOR is inserted between the different parts of the path,
11582 the default is \"/\"."
11583 (setq width (or width 79))
11584 (setq path (delq nil path))
11585 (unless (> width 0)
11586 (user-error "Argument `width' must be positive"))
11587 (setq separator (or separator "/"))
11588 (let* ((org-odd-levels-only nil)
11589 (fpath (concat
11590 prefix (and prefix path separator)
11591 (mapconcat
11592 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11593 (cl-loop for head in path
11594 for n from 0
11595 collect (org-add-props
11596 head nil 'face
11597 (nth (% n org-n-level-faces) org-level-faces)))
11598 separator))))
11599 (when (> (length fpath) width)
11600 (if (< width 7)
11601 ;; It's unlikely that `width' will be this small, but don't
11602 ;; waste characters by adding ".." if it is.
11603 (setq fpath (substring fpath 0 width))
11604 (setf (substring fpath (- width 2)) "..")))
11605 fpath))
11607 (defun org-display-outline-path (&optional file current separator just-return-string)
11608 "Display the current outline path in the echo area.
11610 If FILE is non-nil, prepend the output with the file name.
11611 If CURRENT is non-nil, append the current heading to the output.
11612 SEPARATOR is passed through to `org-format-outline-path'. It separates
11613 the different parts of the path and defaults to \"/\".
11614 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11615 (interactive "P")
11616 (let* (case-fold-search
11617 (bfn (buffer-file-name (buffer-base-buffer)))
11618 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11619 res)
11620 (when current (setq path (append path
11621 (save-excursion
11622 (org-back-to-heading t)
11623 (when (looking-at org-complex-heading-regexp)
11624 (list (match-string 4)))))))
11625 (setq res
11626 (org-format-outline-path
11627 path
11628 (1- (frame-width))
11629 (and file bfn (concat (file-name-nondirectory bfn) separator))
11630 separator))
11631 (if just-return-string
11632 (org-no-properties res)
11633 (org-unlogged-message "%s" res))))
11635 (defvar org-refile-history nil
11636 "History for refiling operations.")
11638 (defvar org-after-refile-insert-hook nil
11639 "Hook run after `org-refile' has inserted its stuff at the new location.
11640 Note that this is still *before* the stuff will be removed from
11641 the *old* location.")
11643 (defvar org-capture-last-stored-marker)
11644 (defvar org-refile-keep nil
11645 "Non-nil means `org-refile' will copy instead of refile.")
11647 (defun org-copy ()
11648 "Like `org-refile', but copy."
11649 (interactive)
11650 (let ((org-refile-keep t))
11651 (funcall 'org-refile nil nil nil "Copy")))
11653 (defun org-refile (&optional arg default-buffer rfloc msg)
11654 "Move the entry or entries at point to another heading.
11656 The list of target headings is compiled using the information in
11657 `org-refile-targets', which see.
11659 At the target location, the entry is filed as a subitem of the
11660 target heading. Depending on `org-reverse-note-order', the new
11661 subitem will either be the first or the last subitem.
11663 If there is an active region, all entries in that region will be
11664 refiled. However, the region must fulfill the requirement that
11665 the first heading sets the top-level of the moved text.
11667 With a `\\[universal-argument]' ARG, the command will only visit the target \
11668 location
11669 and not actually move anything.
11671 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11672 location where the last
11673 refiling operation has put the subtree.
11675 With a numeric prefix argument of `2', refile to the running clock.
11677 With a numeric prefix argument of `3', emulate `org-refile-keep'
11678 being set to t and copy to the target location, don't move it.
11679 Beware that keeping refiled entries may result in duplicated ID
11680 properties.
11682 RFLOC can be a refile location obtained in a different way.
11684 MSG is a string to replace \"Refile\" in the default prompt with
11685 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11687 See also `org-refile-use-outline-path'.
11689 If you are using target caching (see `org-refile-use-cache'), you
11690 have to clear the target cache in order to find new targets.
11691 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11692 prefix argument (`C-u C-u C-u C-c C-w')."
11693 (interactive "P")
11694 (if (member arg '(0 (64)))
11695 (org-refile-cache-clear)
11696 (let* ((actionmsg (cond (msg msg)
11697 ((equal arg 3) "Refile (and keep)")
11698 (t "Refile")))
11699 (regionp (org-region-active-p))
11700 (region-start (and regionp (region-beginning)))
11701 (region-end (and regionp (region-end)))
11702 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11703 pos it nbuf file level reversed)
11704 (setq last-command nil)
11705 (when regionp
11706 (goto-char region-start)
11707 (or (bolp) (goto-char (point-at-bol)))
11708 (setq region-start (point))
11709 (unless (or (org-kill-is-subtree-p
11710 (buffer-substring region-start region-end))
11711 (prog1 org-refile-active-region-within-subtree
11712 (let ((s (point-at-eol)))
11713 (org-toggle-heading)
11714 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11715 (user-error "The region is not a (sequence of) subtree(s)")))
11716 (if (equal arg '(16))
11717 (org-refile-goto-last-stored)
11718 (when (or
11719 (and (equal arg 2)
11720 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11721 (prog1
11722 (setq it (list (or org-clock-heading "running clock")
11723 (buffer-file-name
11724 (marker-buffer org-clock-hd-marker))
11726 (marker-position org-clock-hd-marker)))
11727 (setq arg nil)))
11728 (setq it
11729 (or rfloc
11730 (let (heading-text)
11731 (save-excursion
11732 (unless (and arg (listp arg))
11733 (org-back-to-heading t)
11734 (setq heading-text
11735 (replace-regexp-in-string
11736 org-bracket-link-regexp
11737 "\\3"
11738 (or (nth 4 (org-heading-components))
11739 ""))))
11740 (org-refile-get-location
11741 (cond ((and arg (listp arg)) "Goto")
11742 (regionp (concat actionmsg " region to"))
11743 (t (concat actionmsg " subtree \""
11744 heading-text "\" to")))
11745 default-buffer
11746 (and (not (equal '(4) arg))
11747 org-refile-allow-creating-parent-nodes)))))))
11748 (setq file (nth 1 it)
11749 pos (nth 3 it))
11750 (when (and (not arg)
11752 (equal (buffer-file-name) file)
11753 (if regionp
11754 (and (>= pos region-start)
11755 (<= pos region-end))
11756 (and (>= pos (point))
11757 (< pos (save-excursion
11758 (org-end-of-subtree t t))))))
11759 (error "Cannot refile to position inside the tree or region"))
11760 (setq nbuf (or (find-buffer-visiting file)
11761 (find-file-noselect file)))
11762 (if (and arg (not (equal arg 3)))
11763 (progn
11764 (pop-to-buffer-same-window nbuf)
11765 (goto-char (cond (pos)
11766 ((org-notes-order-reversed-p) (point-min))
11767 (t (point-max))))
11768 (org-show-context 'org-goto))
11769 (if regionp
11770 (progn
11771 (org-kill-new (buffer-substring region-start region-end))
11772 (org-save-markers-in-region region-start region-end))
11773 (org-copy-subtree 1 nil t))
11774 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11775 (find-file-noselect file)))
11776 (setq reversed (org-notes-order-reversed-p))
11777 (org-with-wide-buffer
11778 (if pos
11779 (progn
11780 (goto-char pos)
11781 (setq level (org-get-valid-level (funcall outline-level) 1))
11782 (goto-char
11783 (if reversed
11784 (or (outline-next-heading) (point-max))
11785 (or (save-excursion (org-get-next-sibling))
11786 (org-end-of-subtree t t)
11787 (point-max)))))
11788 (setq level 1)
11789 (if (not reversed)
11790 (goto-char (point-max))
11791 (goto-char (point-min))
11792 (or (outline-next-heading) (goto-char (point-max)))))
11793 (unless (bolp) (newline))
11794 (org-paste-subtree level nil nil t)
11795 (when org-log-refile
11796 (org-add-log-setup 'refile nil nil org-log-refile)
11797 (unless (eq org-log-refile 'note)
11798 (save-excursion (org-add-log-note))))
11799 (and org-auto-align-tags
11800 (let ((org-loop-over-headlines-in-active-region nil))
11801 (org-set-tags nil t)))
11802 (let ((bookmark-name (plist-get org-bookmark-names-plist
11803 :last-refile)))
11804 (when bookmark-name
11805 (with-demoted-errors
11806 (bookmark-set bookmark-name))))
11807 ;; If we are refiling for capture, make sure that the
11808 ;; last-capture pointers point here
11809 (when (bound-and-true-p org-capture-is-refiling)
11810 (let ((bookmark-name (plist-get org-bookmark-names-plist
11811 :last-capture-marker)))
11812 (when bookmark-name
11813 (with-demoted-errors
11814 (bookmark-set bookmark-name))))
11815 (move-marker org-capture-last-stored-marker (point)))
11816 (when (fboundp 'deactivate-mark) (deactivate-mark))
11817 (run-hooks 'org-after-refile-insert-hook)))
11818 (unless org-refile-keep
11819 (if regionp
11820 (delete-region (point) (+ (point) (- region-end region-start)))
11821 (delete-region
11822 (and (org-back-to-heading t) (point))
11823 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11824 (when (featurep 'org-inlinetask)
11825 (org-inlinetask-remove-END-maybe))
11826 (setq org-markers-to-move nil)
11827 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11829 (defun org-refile-goto-last-stored ()
11830 "Go to the location where the last refile was stored."
11831 (interactive)
11832 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11833 (message "This is the location of the last refile"))
11835 (defun org-refile--get-location (refloc tbl)
11836 "When user refile to REFLOC, find the associated target in TBL.
11837 Also check `org-refile-target-table'."
11838 (car (delq
11840 (mapcar
11841 (lambda (r) (or (assoc r tbl)
11842 (assoc r org-refile-target-table)))
11843 (list (replace-regexp-in-string "/$" "" refloc)
11844 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11846 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11847 "Prompt the user for a refile location, using PROMPT.
11848 PROMPT should not be suffixed with a colon and a space, because
11849 this function appends the default value from
11850 `org-refile-history' automatically, if that is not empty."
11851 (let ((org-refile-targets org-refile-targets)
11852 (org-refile-use-outline-path org-refile-use-outline-path))
11853 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11854 (unless org-refile-target-table
11855 (user-error "No refile targets"))
11856 (let* ((cbuf (current-buffer))
11857 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11858 (cfunc (if (and org-refile-use-outline-path
11859 org-outline-path-complete-in-steps)
11860 #'org-olpath-completing-read
11861 #'completing-read))
11862 (extra (if org-refile-use-outline-path "/" ""))
11863 (cbnex (concat (buffer-name) extra))
11864 (filename (and cfn (expand-file-name cfn)))
11865 (tbl (mapcar
11866 (lambda (x)
11867 (if (and (not (member org-refile-use-outline-path
11868 '(file full-file-path)))
11869 (not (equal filename (nth 1 x))))
11870 (cons (concat (car x) extra " ("
11871 (file-name-nondirectory (nth 1 x)) ")")
11872 (cdr x))
11873 (cons (concat (car x) extra) (cdr x))))
11874 org-refile-target-table))
11875 (completion-ignore-case t)
11876 cdef
11877 (prompt (concat prompt
11878 (or (and (car org-refile-history)
11879 (concat " (default " (car org-refile-history) ")"))
11880 (and (assoc cbnex tbl) (setq cdef cbnex)
11881 (concat " (default " cbnex ")"))) ": "))
11882 pa answ parent-target child parent old-hist)
11883 (setq old-hist org-refile-history)
11884 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11885 nil 'org-refile-history (or cdef (car org-refile-history))))
11886 (if (setq pa (org-refile--get-location answ tbl))
11887 (progn
11888 (org-refile-check-position pa)
11889 (when (or (not org-refile-history)
11890 (not (eq old-hist org-refile-history))
11891 (not (equal (car pa) (car org-refile-history))))
11892 (setq org-refile-history
11893 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11894 org-refile-history
11895 (cdr org-refile-history))))
11896 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11897 (pop org-refile-history)))
11899 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11900 (progn
11901 (setq parent (match-string 1 answ)
11902 child (match-string 2 answ))
11903 (setq parent-target (org-refile--get-location parent tbl))
11904 (when (and parent-target
11905 (or (eq new-nodes t)
11906 (and (eq new-nodes 'confirm)
11907 (y-or-n-p (format "Create new node \"%s\"? "
11908 child)))))
11909 (org-refile-new-child parent-target child)))
11910 (user-error "Invalid target location")))))
11912 (declare-function org-string-nw-p "org-macs" (s))
11913 (defun org-refile-check-position (refile-pointer)
11914 "Check if the refile pointer matches the headline to which it points."
11915 (let* ((file (nth 1 refile-pointer))
11916 (re (nth 2 refile-pointer))
11917 (pos (nth 3 refile-pointer))
11918 buffer)
11919 (if (and (not (markerp pos)) (not file))
11920 (user-error "Please indicate a target file in the refile path")
11921 (when (org-string-nw-p re)
11922 (setq buffer (if (markerp pos)
11923 (marker-buffer pos)
11924 (or (find-buffer-visiting file)
11925 (find-file-noselect file))))
11926 (with-current-buffer buffer
11927 (org-with-wide-buffer
11928 (goto-char pos)
11929 (beginning-of-line 1)
11930 (unless (looking-at-p re)
11931 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11933 (defun org-refile-new-child (parent-target child)
11934 "Use refile target PARENT-TARGET to add new CHILD below it."
11935 (unless parent-target
11936 (error "Cannot find parent for new node"))
11937 (let ((file (nth 1 parent-target))
11938 (pos (nth 3 parent-target))
11939 level)
11940 (with-current-buffer (or (find-buffer-visiting file)
11941 (find-file-noselect file))
11942 (org-with-wide-buffer
11943 (if pos
11944 (goto-char pos)
11945 (goto-char (point-max))
11946 (unless (bolp) (newline)))
11947 (when (looking-at org-outline-regexp)
11948 (setq level (funcall outline-level))
11949 (org-end-of-subtree t t))
11950 (org-back-over-empty-lines)
11951 (insert "\n" (make-string
11952 (if pos (org-get-valid-level level 1) 1) ?*)
11953 " " child "\n")
11954 (beginning-of-line 0)
11955 (list (concat (car parent-target) "/" child) file "" (point))))))
11957 (defun org-olpath-completing-read (prompt collection &rest args)
11958 "Read an outline path like a file name."
11959 (let ((thetable collection))
11960 (apply #'completing-read
11961 prompt
11962 (lambda (string predicate &optional flag)
11963 (cond
11964 ((eq flag nil) (try-completion string thetable))
11965 ((eq flag t)
11966 (let ((l (length string)))
11967 (mapcar (lambda (x)
11968 (let ((r (substring x l))
11969 (f (if (string-match " ([^)]*)$" x)
11970 (match-string 0 x)
11971 "")))
11972 (if (string-match "/" r)
11973 (concat string (substring r 0 (match-end 0)) f)
11974 x)))
11975 (all-completions string thetable predicate))))
11976 ;; Exact match?
11977 ((eq flag 'lambda) (assoc string thetable))))
11978 args)))
11980 ;;;; Dynamic blocks
11982 (defun org-find-dblock (name)
11983 "Find the first dynamic block with name NAME in the buffer.
11984 If not found, stay at current position and return nil."
11985 (let ((case-fold-search t) pos)
11986 (save-excursion
11987 (goto-char (point-min))
11988 (setq pos (and (re-search-forward
11989 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11990 (match-beginning 0))))
11991 (when pos (goto-char pos))
11992 pos))
11994 (defun org-create-dblock (plist)
11995 "Create a dynamic block section, with parameters taken from PLIST.
11996 PLIST must contain a :name entry which is used as the name of the block."
11997 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11998 (end-of-line 1)
11999 (newline))
12000 (let ((col (current-column))
12001 (name (plist-get plist :name)))
12002 (insert "#+BEGIN: " name)
12003 (while plist
12004 (if (eq (car plist) :name)
12005 (setq plist (cddr plist))
12006 (insert " " (prin1-to-string (pop plist)))))
12007 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12008 (beginning-of-line -2)))
12010 (defun org-prepare-dblock ()
12011 "Prepare dynamic block for refresh.
12012 This empties the block, puts the cursor at the insert position and returns
12013 the property list including an extra property :name with the block name."
12014 (unless (looking-at org-dblock-start-re)
12015 (user-error "Not at a dynamic block"))
12016 (let* ((begdel (1+ (match-end 0)))
12017 (name (org-no-properties (match-string 1)))
12018 (params (append (list :name name)
12019 (read (concat "(" (match-string 3) ")")))))
12020 (save-excursion
12021 (beginning-of-line 1)
12022 (skip-chars-forward " \t")
12023 (setq params (plist-put params :indentation-column (current-column))))
12024 (unless (re-search-forward org-dblock-end-re nil t)
12025 (error "Dynamic block not terminated"))
12026 (setq params
12027 (append params
12028 (list :content (buffer-substring
12029 begdel (match-beginning 0)))))
12030 (delete-region begdel (match-beginning 0))
12031 (goto-char begdel)
12032 (open-line 1)
12033 params))
12035 (defun org-map-dblocks (&optional command)
12036 "Apply COMMAND to all dynamic blocks in the current buffer.
12037 If COMMAND is not given, use `org-update-dblock'."
12038 (let ((cmd (or command 'org-update-dblock)))
12039 (save-excursion
12040 (goto-char (point-min))
12041 (while (re-search-forward org-dblock-start-re nil t)
12042 (goto-char (match-beginning 0))
12043 (save-excursion
12044 (condition-case nil
12045 (funcall cmd)
12046 (error (message "Error during update of dynamic block"))))
12047 (unless (re-search-forward org-dblock-end-re nil t)
12048 (error "Dynamic block not terminated"))))))
12050 (defun org-dblock-update (&optional arg)
12051 "User command for updating dynamic blocks.
12052 Update the dynamic block at point. With prefix ARG, update all dynamic
12053 blocks in the buffer."
12054 (interactive "P")
12055 (if arg
12056 (org-update-all-dblocks)
12057 (or (looking-at org-dblock-start-re)
12058 (org-beginning-of-dblock))
12059 (org-update-dblock)))
12061 (defun org-update-dblock ()
12062 "Update the dynamic block at point.
12063 This means to empty the block, parse for parameters and then call
12064 the correct writing function."
12065 (interactive)
12066 (save-excursion
12067 (let* ((win (selected-window))
12068 (pos (point))
12069 (line (org-current-line))
12070 (params (org-prepare-dblock))
12071 (name (plist-get params :name))
12072 (indent (plist-get params :indentation-column))
12073 (cmd (intern (concat "org-dblock-write:" name))))
12074 (message "Updating dynamic block `%s' at line %d..." name line)
12075 (funcall cmd params)
12076 (message "Updating dynamic block `%s' at line %d...done" name line)
12077 (goto-char pos)
12078 (when (and indent (> indent 0))
12079 (setq indent (make-string indent ?\ ))
12080 (save-excursion
12081 (select-window win)
12082 (org-beginning-of-dblock)
12083 (forward-line 1)
12084 (while (not (looking-at org-dblock-end-re))
12085 (insert indent)
12086 (beginning-of-line 2))
12087 (when (looking-at org-dblock-end-re)
12088 (and (looking-at "[ \t]+")
12089 (replace-match ""))
12090 (insert indent)))))))
12092 (defun org-beginning-of-dblock ()
12093 "Find the beginning of the dynamic block at point.
12094 Error if there is no such block at point."
12095 (let ((pos (point))
12096 beg)
12097 (end-of-line 1)
12098 (if (and (re-search-backward org-dblock-start-re nil t)
12099 (setq beg (match-beginning 0))
12100 (re-search-forward org-dblock-end-re nil t)
12101 (> (match-end 0) pos))
12102 (goto-char beg)
12103 (goto-char pos)
12104 (error "Not in a dynamic block"))))
12106 (defun org-update-all-dblocks ()
12107 "Update all dynamic blocks in the buffer.
12108 This function can be used in a hook."
12109 (interactive)
12110 (when (derived-mode-p 'org-mode)
12111 (org-map-dblocks 'org-update-dblock)))
12114 ;;;; Completion
12116 (declare-function org-export-backend-options "ox" (cl-x) t)
12117 (defun org-get-export-keywords ()
12118 "Return a list of all currently understood export keywords.
12119 Export keywords include options, block names, attributes and
12120 keywords relative to each registered export back-end."
12121 (let (keywords)
12122 (dolist (backend
12123 (bound-and-true-p org-export-registered-backends)
12124 (delq nil keywords))
12125 ;; Back-end name (for keywords, like #+LATEX:)
12126 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12127 (dolist (option-entry (org-export-backend-options backend))
12128 ;; Back-end options.
12129 (push (nth 1 option-entry) keywords)))))
12131 (defconst org-options-keywords
12132 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12133 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12134 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12135 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12136 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12138 (defcustom org-structure-template-alist
12139 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12140 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12141 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12142 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12143 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12144 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12145 ("C" "#+BEGIN_COMMENT\n?\n#+END_COMMENT")
12146 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12147 ("L" "#+LaTeX: ")
12148 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12149 ("H" "#+HTML: ")
12150 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12151 ("A" "#+ASCII: ")
12152 ("i" "#+INDEX: ?")
12153 ("I" "#+INCLUDE: %file ?"))
12154 "Structure completion elements.
12155 This is a list of abbreviation keys and values. The value gets inserted
12156 if you type `<' followed by the key and then press the completion key,
12157 usually `TAB'. %file will be replaced by a file name after prompting
12158 for the file using completion. The cursor will be placed at the position
12159 of the `?' in the template.
12160 There are two templates for each key, the first uses the original Org syntax,
12161 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12162 the default when the /org-mtags.el/ module has been loaded. See also the
12163 variable `org-mtags-prefer-muse-templates'."
12164 :group 'org-completion
12165 :type '(repeat
12166 (list
12167 (string :tag "Key")
12168 (string :tag "Template")))
12169 :version "26.1"
12170 :package-version '(Org . "8.3"))
12172 (defun org-try-structure-completion ()
12173 "Try to complete a structure template before point.
12174 This looks for strings like \"<e\" on an otherwise empty line and
12175 expands them."
12176 (let ((l (buffer-substring (point-at-bol) (point)))
12178 (when (and (looking-at "[ \t]*$")
12179 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12180 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12181 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12182 (match-beginning 1)) a)
12183 t)))
12185 (defun org-complete-expand-structure-template (start cell)
12186 "Expand a structure template."
12187 (let ((rpl (nth 1 cell))
12188 (ind ""))
12189 (delete-region start (point))
12190 (when (string-match "\\`[ \t]*#\\+" rpl)
12191 (cond
12192 ((bolp))
12193 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12194 (setq ind (buffer-substring (point-at-bol) (point))))
12195 (t (newline))))
12196 (setq start (point))
12197 (when (string-match "%file" rpl)
12198 (setq rpl (replace-match
12199 (concat
12200 "\""
12201 (save-match-data
12202 (abbreviate-file-name (read-file-name "Include file: ")))
12203 "\"")
12204 t t rpl)))
12205 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12206 (concat "\n" ind)))
12207 (insert rpl)
12208 (when (re-search-backward "\\?" start t) (delete-char 1))))
12210 ;;;; TODO, DEADLINE, Comments
12212 (defun org-toggle-comment ()
12213 "Change the COMMENT state of an entry."
12214 (interactive)
12215 (save-excursion
12216 (org-back-to-heading)
12217 (let ((case-fold-search nil))
12218 (looking-at org-complex-heading-regexp))
12219 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12220 (skip-chars-forward " \t")
12221 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12222 (if (org-in-commented-heading-p t)
12223 (delete-region (point)
12224 (progn (search-forward " " (line-end-position) 'move)
12225 (skip-chars-forward " \t")
12226 (point)))
12227 (insert org-comment-string)
12228 (unless (eolp) (insert " ")))))
12230 (defvar org-last-todo-state-is-todo nil
12231 "This is non-nil when the last TODO state change led to a TODO state.
12232 If the last change removed the TODO tag or switched to DONE, then
12233 this is nil.")
12235 (defvar org-setting-tags nil) ; dynamically skipped
12237 (defvar org-todo-setup-filter-hook nil
12238 "Hook for functions that pre-filter todo specs.
12239 Each function takes a todo spec and returns either nil or the spec
12240 transformed into canonical form." )
12242 (defvar org-todo-get-default-hook nil
12243 "Hook for functions that get a default item for todo.
12244 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12245 nil or a string to be used for the todo mark." )
12247 (defvar org-agenda-headline-snapshot-before-repeat)
12249 (defun org-current-effective-time ()
12250 "Return current time adjusted for `org-extend-today-until' variable."
12251 (let* ((ct (org-current-time))
12252 (dct (decode-time ct))
12253 (ct1
12254 (cond
12255 (org-use-last-clock-out-time-as-effective-time
12256 (or (org-clock-get-last-clock-out-time) ct))
12257 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12258 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12259 (t ct))))
12260 ct1))
12262 (defun org-todo-yesterday (&optional arg)
12263 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12264 (interactive "P")
12265 (if (eq major-mode 'org-agenda-mode)
12266 (apply 'org-agenda-todo-yesterday arg)
12267 (let* ((org-use-effective-time t)
12268 (hour (nth 2 (decode-time (org-current-time))))
12269 (org-extend-today-until (1+ hour)))
12270 (org-todo arg))))
12272 (defvar org-block-entry-blocking ""
12273 "First entry preventing the TODO state change.")
12275 (defun org-cancel-repeater ()
12276 "Cancel a repeater by setting its numeric value to zero."
12277 (interactive)
12278 (save-excursion
12279 (org-back-to-heading t)
12280 (let ((bound1 (point))
12281 (bound0 (save-excursion (outline-next-heading) (point))))
12282 (when (and (re-search-forward
12283 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12284 org-deadline-time-regexp "\\)\\|\\("
12285 org-ts-regexp "\\)")
12286 bound0 t)
12287 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12288 bound1 t))
12289 (replace-match "0" t nil nil 1)))))
12291 (defvar org-state)
12292 (defvar org-blocked-by-checkboxes)
12293 (defun org-todo (&optional arg)
12294 "Change the TODO state of an item.
12296 The state of an item is given by a keyword at the start of the heading,
12297 like
12298 *** TODO Write paper
12299 *** DONE Call mom
12301 The different keywords are specified in the variable `org-todo-keywords'.
12302 By default the available states are \"TODO\" and \"DONE\". So, for this
12303 example: when the item starts with TODO, it is changed to DONE.
12304 When it starts with DONE, the DONE is removed. And when neither TODO nor
12305 DONE are present, add TODO at the beginning of the heading.
12307 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12308 state.
12309 With numeric prefix ARG, switch to that state.
12310 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12311 next set of TODO \
12312 keywords (nextset).
12313 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12314 prefix, circumvent any state blocking.
12315 With a numeric prefix arg of 0, inhibit note taking for the change.
12316 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12318 When called through ELisp, arg is also interpreted in the following way:
12319 `none' -> empty state
12320 \"\" -> switch to empty state
12321 `done' -> switch to DONE
12322 `nextset' -> switch to the next set of keywords
12323 `previousset' -> switch to the previous set of keywords
12324 \"WAITING\" -> switch to the specified keyword, but only if it
12325 really is a member of `org-todo-keywords'."
12326 (interactive "P")
12327 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12328 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12329 'region-start-level 'region))
12330 org-loop-over-headlines-in-active-region)
12331 (org-map-entries
12332 `(org-todo ,arg)
12333 org-loop-over-headlines-in-active-region
12334 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12335 (when (equal arg '(16)) (setq arg 'nextset))
12336 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12337 (let ((org-blocker-hook org-blocker-hook)
12338 commentp
12339 case-fold-search)
12340 (when (equal arg '(64))
12341 (setq arg nil org-blocker-hook nil))
12342 (when (and org-blocker-hook
12343 (or org-inhibit-blocking
12344 (org-entry-get nil "NOBLOCKING")))
12345 (setq org-blocker-hook nil))
12346 (save-excursion
12347 (catch 'exit
12348 (org-back-to-heading t)
12349 (when (org-in-commented-heading-p t)
12350 (org-toggle-comment)
12351 (setq commentp t))
12352 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12353 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12354 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12355 (let* ((match-data (match-data))
12356 (startpos (point-at-bol))
12357 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12358 (org-log-done org-log-done)
12359 (org-log-repeat org-log-repeat)
12360 (org-todo-log-states org-todo-log-states)
12361 (org-inhibit-logging
12362 (if (equal arg 0)
12363 (progn (setq arg nil) 'note) org-inhibit-logging))
12364 (this (match-string 1))
12365 (hl-pos (match-beginning 0))
12366 (head (org-get-todo-sequence-head this))
12367 (ass (assoc head org-todo-kwd-alist))
12368 (interpret (nth 1 ass))
12369 (done-word (nth 3 ass))
12370 (final-done-word (nth 4 ass))
12371 (org-last-state (or this ""))
12372 (completion-ignore-case t)
12373 (member (member this org-todo-keywords-1))
12374 (tail (cdr member))
12375 (org-state (cond
12376 ((and org-todo-key-trigger
12377 (or (and (equal arg '(4))
12378 (eq org-use-fast-todo-selection 'prefix))
12379 (and (not arg) org-use-fast-todo-selection
12380 (not (eq org-use-fast-todo-selection
12381 'prefix)))))
12382 ;; Use fast selection.
12383 (org-fast-todo-selection))
12384 ((and (equal arg '(4))
12385 (or (not org-use-fast-todo-selection)
12386 (not org-todo-key-trigger)))
12387 ;; Read a state with completion.
12388 (completing-read
12389 "State: " (mapcar #'list org-todo-keywords-1)
12390 nil t))
12391 ((eq arg 'right)
12392 (if this
12393 (if tail (car tail) nil)
12394 (car org-todo-keywords-1)))
12395 ((eq arg 'left)
12396 (unless (equal member org-todo-keywords-1)
12397 (if this
12398 (nth (- (length org-todo-keywords-1)
12399 (length tail) 2)
12400 org-todo-keywords-1)
12401 (org-last org-todo-keywords-1))))
12402 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12403 (setq arg nil))) ;hack to fall back to cycling
12404 (arg
12405 ;; User or caller requests a specific state.
12406 (cond
12407 ((equal arg "") nil)
12408 ((eq arg 'none) nil)
12409 ((eq arg 'done) (or done-word (car org-done-keywords)))
12410 ((eq arg 'nextset)
12411 (or (car (cdr (member head org-todo-heads)))
12412 (car org-todo-heads)))
12413 ((eq arg 'previousset)
12414 (let ((org-todo-heads (reverse org-todo-heads)))
12415 (or (car (cdr (member head org-todo-heads)))
12416 (car org-todo-heads))))
12417 ((car (member arg org-todo-keywords-1)))
12418 ((stringp arg)
12419 (user-error "State `%s' not valid in this file" arg))
12420 ((nth (1- (prefix-numeric-value arg))
12421 org-todo-keywords-1))))
12422 ((null member) (or head (car org-todo-keywords-1)))
12423 ((equal this final-done-word) nil) ;-> make empty
12424 ((null tail) nil) ;-> first entry
12425 ((memq interpret '(type priority))
12426 (if (eq this-command last-command)
12427 (car tail)
12428 (if (> (length tail) 0)
12429 (or done-word (car org-done-keywords))
12430 nil)))
12432 (car tail))))
12433 (org-state (or
12434 (run-hook-with-args-until-success
12435 'org-todo-get-default-hook org-state org-last-state)
12436 org-state))
12437 (next (if org-state (concat " " org-state " ") " "))
12438 (change-plist (list :type 'todo-state-change :from this :to org-state
12439 :position startpos))
12440 dolog now-done-p)
12441 (when org-blocker-hook
12442 (let (org-blocked-by-checkboxes block-reason)
12443 (setq org-last-todo-state-is-todo
12444 (not (member this org-done-keywords)))
12445 (unless (save-excursion
12446 (save-match-data
12447 (org-with-wide-buffer
12448 (run-hook-with-args-until-failure
12449 'org-blocker-hook change-plist))))
12450 (setq block-reason (if org-blocked-by-checkboxes
12451 "contained checkboxes"
12452 (format "\"%s\"" org-block-entry-blocking)))
12453 (if (called-interactively-p 'interactive)
12454 (user-error "TODO state change from %s to %s blocked (by %s)"
12455 this org-state block-reason)
12456 ;; Fail silently.
12457 (message "TODO state change from %s to %s blocked (by %s)"
12458 this org-state block-reason)
12459 (throw 'exit nil)))))
12460 (store-match-data match-data)
12461 (replace-match next t t)
12462 (cond ((equal this org-state)
12463 (message "TODO state was already %s" (org-trim next)))
12464 ((not (pos-visible-in-window-p hl-pos))
12465 (message "TODO state changed to %s" (org-trim next))))
12466 (unless head
12467 (setq head (org-get-todo-sequence-head org-state)
12468 ass (assoc head org-todo-kwd-alist)
12469 interpret (nth 1 ass)
12470 done-word (nth 3 ass)
12471 final-done-word (nth 4 ass)))
12472 (when (memq arg '(nextset previousset))
12473 (message "Keyword-Set %d/%d: %s"
12474 (- (length org-todo-sets) -1
12475 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12476 (length org-todo-sets)
12477 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12478 (setq org-last-todo-state-is-todo
12479 (not (member org-state org-done-keywords)))
12480 (setq now-done-p (and (member org-state org-done-keywords)
12481 (not (member this org-done-keywords))))
12482 (and logging (org-local-logging logging))
12483 (when (and (or org-todo-log-states org-log-done)
12484 (not (eq org-inhibit-logging t))
12485 (not (memq arg '(nextset previousset))))
12486 ;; We need to look at recording a time and note.
12487 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12488 (nth 2 (assoc this org-todo-log-states))))
12489 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12490 (setq dolog 'time))
12491 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12492 (and org-state
12493 (member org-state org-not-done-keywords)
12494 (not (member this org-not-done-keywords))))
12495 ;; This is now a todo state and was not one before
12496 ;; If there was a CLOSED time stamp, get rid of it.
12497 (org-add-planning-info nil nil 'closed))
12498 (when (and now-done-p org-log-done)
12499 ;; It is now done, and it was not done before.
12500 (org-add-planning-info 'closed (org-current-effective-time))
12501 (when (and (not dolog) (eq 'note org-log-done))
12502 (org-add-log-setup 'done org-state this 'note)))
12503 (when (and org-state dolog)
12504 ;; This is a non-nil state, and we need to log it.
12505 (org-add-log-setup 'state org-state this dolog)))
12506 ;; Fixup tag positioning.
12507 (org-todo-trigger-tag-changes org-state)
12508 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12509 (when org-provide-todo-statistics
12510 (org-update-parent-todo-statistics))
12511 (run-hooks 'org-after-todo-state-change-hook)
12512 (when (and arg (not (member org-state org-done-keywords)))
12513 (setq head (org-get-todo-sequence-head org-state)))
12514 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12515 ;; Do we need to trigger a repeat?
12516 (when now-done-p
12517 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12518 ;; This is for the agenda, take a snapshot of the headline.
12519 (save-match-data
12520 (setq org-agenda-headline-snapshot-before-repeat
12521 (org-get-heading))))
12522 (org-auto-repeat-maybe org-state))
12523 ;; Fixup cursor location if close to the keyword.
12524 (when (and (outline-on-heading-p)
12525 (not (bolp))
12526 (save-excursion (beginning-of-line 1)
12527 (looking-at org-todo-line-regexp))
12528 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12529 (goto-char (or (match-end 2) (match-end 1)))
12530 (and (looking-at " ") (just-one-space)))
12531 (when org-trigger-hook
12532 (save-excursion
12533 (run-hook-with-args 'org-trigger-hook change-plist)))
12534 (when commentp (org-toggle-comment))))))))
12536 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12537 "Block turning an entry into a TODO, using the hierarchy.
12538 This checks whether the current task should be blocked from state
12539 changes. Such blocking occurs when:
12541 1. The task has children which are not all in a completed state.
12543 2. A task has a parent with the property :ORDERED:, and there
12544 are siblings prior to the current task with incomplete
12545 status.
12547 3. The parent of the task is blocked because it has siblings that should
12548 be done first, or is child of a block grandparent TODO entry."
12550 (if (not org-enforce-todo-dependencies)
12551 t ; if locally turned off don't block
12552 (catch 'dont-block
12553 ;; If this is not a todo state change, or if this entry is already DONE,
12554 ;; do not block
12555 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12556 (member (plist-get change-plist :from)
12557 (cons 'done org-done-keywords))
12558 (member (plist-get change-plist :to)
12559 (cons 'todo org-not-done-keywords))
12560 (not (plist-get change-plist :to)))
12561 (throw 'dont-block t))
12562 ;; If this task has children, and any are undone, it's blocked
12563 (save-excursion
12564 (org-back-to-heading t)
12565 (let ((this-level (funcall outline-level)))
12566 (outline-next-heading)
12567 (let ((child-level (funcall outline-level)))
12568 (while (and (not (eobp))
12569 (> child-level this-level))
12570 ;; this todo has children, check whether they are all
12571 ;; completed
12572 (when (and (not (org-entry-is-done-p))
12573 (org-entry-is-todo-p))
12574 (setq org-block-entry-blocking (org-get-heading))
12575 (throw 'dont-block nil))
12576 (outline-next-heading)
12577 (setq child-level (funcall outline-level))))))
12578 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12579 ;; any previous siblings are undone, it's blocked
12580 (save-excursion
12581 (org-back-to-heading t)
12582 (let* ((pos (point))
12583 (parent-pos (and (org-up-heading-safe) (point)))
12584 (case-fold-search nil))
12585 (unless parent-pos (throw 'dont-block t)) ; no parent
12586 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12587 (forward-line 1)
12588 (re-search-forward org-not-done-heading-regexp pos t))
12589 (setq org-block-entry-blocking (match-string 0))
12590 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12591 ;; Search further up the hierarchy, to see if an ancestor is blocked
12592 (while t
12593 (goto-char parent-pos)
12594 (unless (looking-at org-not-done-heading-regexp)
12595 (throw 'dont-block t)) ; do not block, parent is not a TODO
12596 (setq pos (point))
12597 (setq parent-pos (and (org-up-heading-safe) (point)))
12598 (unless parent-pos (throw 'dont-block t)) ; no parent
12599 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12600 (forward-line 1)
12601 (re-search-forward org-not-done-heading-regexp pos t)
12602 (setq org-block-entry-blocking (org-get-heading)))
12603 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12605 (defcustom org-track-ordered-property-with-tag nil
12606 "Should the ORDERED property also be shown as a tag?
12607 The ORDERED property decides if an entry should require subtasks to be
12608 completed in sequence. Since a property is not very visible, setting
12609 this option means that toggling the ORDERED property with the command
12610 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12611 not relevant for the behavior, but it makes things more visible.
12613 Note that toggling the tag with tags commands will not change the property
12614 and therefore not influence behavior!
12616 This can be t, meaning the tag ORDERED should be used, It can also be a
12617 string to select a different tag for this task."
12618 :group 'org-todo
12619 :type '(choice
12620 (const :tag "No tracking" nil)
12621 (const :tag "Track with ORDERED tag" t)
12622 (string :tag "Use other tag")))
12624 (defun org-toggle-ordered-property ()
12625 "Toggle the ORDERED property of the current entry.
12626 For better visibility, you can track the value of this property with a tag.
12627 See variable `org-track-ordered-property-with-tag'."
12628 (interactive)
12629 (let* ((t1 org-track-ordered-property-with-tag)
12630 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12631 (save-excursion
12632 (org-back-to-heading)
12633 (if (org-entry-get nil "ORDERED")
12634 (progn
12635 (org-delete-property "ORDERED")
12636 (and tag (org-toggle-tag tag 'off))
12637 (message "Subtasks can be completed in arbitrary order"))
12638 (org-entry-put nil "ORDERED" "t")
12639 (and tag (org-toggle-tag tag 'on))
12640 (message "Subtasks must be completed in sequence")))))
12642 (defun org-block-todo-from-checkboxes (change-plist)
12643 "Block turning an entry into a TODO, using checkboxes.
12644 This checks whether the current task should be blocked from state
12645 changes because there are unchecked boxes in this entry."
12646 (if (not org-enforce-todo-checkbox-dependencies)
12647 t ; if locally turned off don't block
12648 (catch 'dont-block
12649 ;; If this is not a todo state change, or if this entry is already DONE,
12650 ;; do not block
12651 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12652 (member (plist-get change-plist :from)
12653 (cons 'done org-done-keywords))
12654 (member (plist-get change-plist :to)
12655 (cons 'todo org-not-done-keywords))
12656 (not (plist-get change-plist :to)))
12657 (throw 'dont-block t))
12658 ;; If this task has checkboxes that are not checked, it's blocked
12659 (save-excursion
12660 (org-back-to-heading t)
12661 (let ((beg (point)) end)
12662 (outline-next-heading)
12663 (setq end (point))
12664 (goto-char beg)
12665 (when (org-list-search-forward
12666 (concat (org-item-beginning-re)
12667 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12668 "\\[[- ]\\]")
12669 end t)
12670 (when (boundp 'org-blocked-by-checkboxes)
12671 (setq org-blocked-by-checkboxes t))
12672 (throw 'dont-block nil))))
12673 t))) ; do not block
12675 (defun org-entry-blocked-p ()
12676 "Non-nil if entry at point is blocked."
12677 (and (not (org-entry-get nil "NOBLOCKING"))
12678 (member (org-entry-get nil "TODO") org-not-done-keywords)
12679 (not (run-hook-with-args-until-failure
12680 'org-blocker-hook
12681 (list :type 'todo-state-change
12682 :position (point)
12683 :from 'todo
12684 :to 'done)))))
12686 (defun org-update-statistics-cookies (all)
12687 "Update the statistics cookie, either from TODO or from checkboxes.
12688 This should be called with the cursor in a line with a statistics
12689 cookie. When called with a \\[universal-argument] prefix, update
12690 all statistics cookies in the buffer."
12691 (interactive "P")
12692 (if all
12693 (progn
12694 (org-update-checkbox-count 'all)
12695 (org-map-entries 'org-update-parent-todo-statistics))
12696 (if (not (org-at-heading-p))
12697 (org-update-checkbox-count)
12698 (let ((pos (point-marker))
12699 end l1 l2)
12700 (ignore-errors (org-back-to-heading t))
12701 (if (not (org-at-heading-p))
12702 (org-update-checkbox-count)
12703 (setq l1 (org-outline-level))
12704 (setq end (save-excursion
12705 (outline-next-heading)
12706 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12707 (point)))
12708 (if (and (save-excursion
12709 (re-search-forward
12710 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12711 (not (save-excursion (re-search-forward
12712 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12713 (org-update-checkbox-count)
12714 (if (and l2 (> l2 l1))
12715 (progn
12716 (goto-char end)
12717 (org-update-parent-todo-statistics))
12718 (goto-char pos)
12719 (beginning-of-line 1)
12720 (while (re-search-forward
12721 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12722 (point-at-eol) t)
12723 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12724 (goto-char pos)
12725 (move-marker pos nil)))))
12727 (defvar org-entry-property-inherited-from) ;; defined below
12728 (defun org-update-parent-todo-statistics ()
12729 "Update any statistics cookie in the parent of the current headline.
12730 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12731 the entire subtree and this will travel up the hierarchy and update
12732 statistics everywhere."
12733 (let* ((prop (save-excursion (org-up-heading-safe)
12734 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12735 (recursive (or (not org-hierarchical-todo-statistics)
12736 (and prop (string-match "\\<recursive\\>" prop))))
12737 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12739 (first t)
12740 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12741 level ltoggle l1 new ndel
12742 (cnt-all 0) (cnt-done 0) is-percent kwd
12743 checkbox-beg cookie-present)
12744 (catch 'exit
12745 (save-excursion
12746 (beginning-of-line 1)
12747 (setq ltoggle (funcall outline-level))
12748 ;; Three situations are to consider:
12750 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12751 ;; to the top-level ancestor on the headline;
12753 ;; 2. If parent has "recursive" property, repeat up to the
12754 ;; headline setting that property, taking inheritance into
12755 ;; account;
12757 ;; 3. Else, move up to direct parent and proceed only once.
12758 (while (and (setq level (org-up-heading-safe))
12759 (or recursive first)
12760 (>= (point) lim))
12761 (setq first nil cookie-present nil)
12762 (unless (and level
12763 (not (string-match
12764 "\\<checkbox\\>"
12765 (downcase (or (org-entry-get nil "COOKIE_DATA")
12766 "")))))
12767 (throw 'exit nil))
12768 (while (re-search-forward box-re (point-at-eol) t)
12769 (setq cnt-all 0 cnt-done 0 cookie-present t)
12770 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12771 (save-match-data
12772 (unless (outline-next-heading) (throw 'exit nil))
12773 (while (and (looking-at org-complex-heading-regexp)
12774 (> (setq l1 (length (match-string 1))) level))
12775 (setq kwd (and (or recursive (= l1 ltoggle))
12776 (match-string 2)))
12777 (if (or (eq org-provide-todo-statistics 'all-headlines)
12778 (and (eq org-provide-todo-statistics t)
12779 (or (member kwd org-done-keywords)))
12780 (and (listp org-provide-todo-statistics)
12781 (stringp (car org-provide-todo-statistics))
12782 (or (member kwd org-provide-todo-statistics)
12783 (member kwd org-done-keywords)))
12784 (and (listp org-provide-todo-statistics)
12785 (listp (car org-provide-todo-statistics))
12786 (or (member kwd (car org-provide-todo-statistics))
12787 (and (member kwd org-done-keywords)
12788 (member kwd (cadr org-provide-todo-statistics))))))
12789 (setq cnt-all (1+ cnt-all))
12790 (and (eq org-provide-todo-statistics t)
12792 (setq cnt-all (1+ cnt-all))))
12793 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12794 (member kwd org-done-keywords))
12795 (and (listp org-provide-todo-statistics)
12796 (listp (car org-provide-todo-statistics))
12797 (member kwd org-done-keywords)
12798 (member kwd (cadr org-provide-todo-statistics)))
12799 (and (listp org-provide-todo-statistics)
12800 (stringp (car org-provide-todo-statistics))
12801 (member kwd org-done-keywords)))
12802 (setq cnt-done (1+ cnt-done)))
12803 (outline-next-heading)))
12804 (setq new
12805 (if is-percent
12806 (format "[%d%%]" (floor (* 100.0 cnt-done)
12807 (max 1 cnt-all)))
12808 (format "[%d/%d]" cnt-done cnt-all))
12809 ndel (- (match-end 0) checkbox-beg))
12810 (goto-char checkbox-beg)
12811 (insert new)
12812 (delete-region (point) (+ (point) ndel))
12813 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12814 (when cookie-present
12815 (run-hook-with-args 'org-after-todo-statistics-hook
12816 cnt-done (- cnt-all cnt-done))))))
12817 (run-hooks 'org-todo-statistics-hook)))
12819 (defvar org-after-todo-statistics-hook nil
12820 "Hook that is called after a TODO statistics cookie has been updated.
12821 Each function is called with two arguments: the number of not-done entries
12822 and the number of done entries.
12824 For example, the following function, when added to this hook, will switch
12825 an entry to DONE when all children are done, and back to TODO when new
12826 entries are set to a TODO status. Note that this hook is only called
12827 when there is a statistics cookie in the headline!
12829 (defun org-summary-todo (n-done n-not-done)
12830 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12831 (let (org-log-done org-log-states) ; turn off logging
12832 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12835 (defvar org-todo-statistics-hook nil
12836 "Hook that is run whenever Org thinks TODO statistics should be updated.
12837 This hook runs even if there is no statistics cookie present, in which case
12838 `org-after-todo-statistics-hook' would not run.")
12840 (defun org-todo-trigger-tag-changes (state)
12841 "Apply the changes defined in `org-todo-state-tags-triggers'."
12842 (let ((l org-todo-state-tags-triggers)
12843 changes)
12844 (when (or (not state) (equal state ""))
12845 (setq changes (append changes (cdr (assoc "" l)))))
12846 (when (and (stringp state) (> (length state) 0))
12847 (setq changes (append changes (cdr (assoc state l)))))
12848 (when (member state org-not-done-keywords)
12849 (setq changes (append changes (cdr (assq 'todo l)))))
12850 (when (member state org-done-keywords)
12851 (setq changes (append changes (cdr (assq 'done l)))))
12852 (dolist (c changes)
12853 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12855 (defun org-local-logging (value)
12856 "Get logging settings from a property VALUE."
12857 ;; Directly set the variables, they are already local.
12858 (setq org-log-done nil
12859 org-log-repeat nil
12860 org-todo-log-states nil)
12861 (dolist (w (split-string value))
12862 (let (a)
12863 (cond
12864 ((setq a (assoc w org-startup-options))
12865 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12866 (set (nth 1 a) (nth 2 a))))
12867 ((setq a (org-extract-log-state-settings w))
12868 (and (member (car a) org-todo-keywords-1)
12869 (push a org-todo-log-states)))))))
12871 (defun org-get-todo-sequence-head (kwd)
12872 "Return the head of the TODO sequence to which KWD belongs.
12873 If KWD is not set, check if there is a text property remembering the
12874 right sequence."
12875 (let (p)
12876 (cond
12877 ((not kwd)
12878 (or (get-text-property (point-at-bol) 'org-todo-head)
12879 (progn
12880 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12881 nil (point-at-eol)))
12882 (get-text-property p 'org-todo-head))))
12883 ((not (member kwd org-todo-keywords-1))
12884 (car org-todo-keywords-1))
12885 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12887 (defun org-fast-todo-selection ()
12888 "Fast TODO keyword selection with single keys.
12889 Returns the new TODO keyword, or nil if no state change should occur."
12890 (let* ((fulltable org-todo-key-alist)
12891 (done-keywords org-done-keywords) ;; needed for the faces.
12892 (maxlen (apply 'max (mapcar
12893 (lambda (x)
12894 (if (stringp (car x)) (string-width (car x)) 0))
12895 fulltable)))
12896 (expert nil)
12897 (fwidth (+ maxlen 3 1 3))
12898 (ncol (/ (- (window-width) 4) fwidth))
12899 tg cnt e c tbl
12900 groups ingroup)
12901 (save-excursion
12902 (save-window-excursion
12903 (if expert
12904 (set-buffer (get-buffer-create " *Org todo*"))
12905 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12906 (erase-buffer)
12907 (setq-local org-done-keywords done-keywords)
12908 (setq tbl fulltable cnt 0)
12909 (while (setq e (pop tbl))
12910 (cond
12911 ((equal e '(:startgroup))
12912 (push '() groups) (setq ingroup t)
12913 (unless (= cnt 0)
12914 (setq cnt 0)
12915 (insert "\n"))
12916 (insert "{ "))
12917 ((equal e '(:endgroup))
12918 (setq ingroup nil cnt 0)
12919 (insert "}\n"))
12920 ((equal e '(:newline))
12921 (unless (= cnt 0)
12922 (setq cnt 0)
12923 (insert "\n")
12924 (setq e (car tbl))
12925 (while (equal (car tbl) '(:newline))
12926 (insert "\n")
12927 (setq tbl (cdr tbl)))))
12929 (setq tg (car e) c (cdr e))
12930 (when ingroup (push tg (car groups)))
12931 (setq tg (org-add-props tg nil 'face
12932 (org-get-todo-face tg)))
12933 (when (and (= cnt 0) (not ingroup)) (insert " "))
12934 (insert "[" c "] " tg (make-string
12935 (- fwidth 4 (length tg)) ?\ ))
12936 (when (= (setq cnt (1+ cnt)) ncol)
12937 (insert "\n")
12938 (when ingroup (insert " "))
12939 (setq cnt 0)))))
12940 (insert "\n")
12941 (goto-char (point-min))
12942 (unless expert (org-fit-window-to-buffer))
12943 (message "[a-z..]:Set [SPC]:clear")
12944 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12945 (cond
12946 ((or (= c ?\C-g)
12947 (and (= c ?q) (not (rassoc c fulltable))))
12948 (setq quit-flag t))
12949 ((= c ?\ ) nil)
12950 ((setq e (rassoc c fulltable) tg (car e))
12952 (t (setq quit-flag t)))))))
12954 (defun org-entry-is-todo-p ()
12955 (member (org-get-todo-state) org-not-done-keywords))
12957 (defun org-entry-is-done-p ()
12958 (member (org-get-todo-state) org-done-keywords))
12960 (defun org-get-todo-state ()
12961 "Return the TODO keyword of the current subtree."
12962 (save-excursion
12963 (org-back-to-heading t)
12964 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12965 (match-end 2)
12966 (match-string 2))))
12968 (defun org-at-date-range-p (&optional inactive-ok)
12969 "Non-nil if point is inside a date range.
12971 When optional argument INACTIVE-OK is non-nil, also consider
12972 inactive time ranges.
12974 When this function returns a non-nil value, match data is set
12975 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12976 on INACTIVE-OK."
12977 (interactive)
12978 (save-excursion
12979 (catch 'exit
12980 (let ((pos (point)))
12981 (skip-chars-backward "^[<\r\n")
12982 (skip-chars-backward "<[")
12983 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12984 (>= (match-end 0) pos)
12985 (throw 'exit t))
12986 (skip-chars-backward "^<[\r\n")
12987 (skip-chars-backward "<[")
12988 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12989 (>= (match-end 0) pos)
12990 (throw 'exit t)))
12991 nil)))
12993 (defun org-get-repeat (&optional timestamp)
12994 "Check if there is a time-stamp with repeater in this entry.
12996 Return the repeater, as a string, or nil. Also return nil when
12997 this function is called before first heading.
12999 When optional argument TIMESTAMP is a string, extract the
13000 repeater from there instead."
13001 (save-match-data
13002 (cond (timestamp
13003 (and (string-match org-repeat-re timestamp)
13004 (match-string-no-properties 1 timestamp)))
13005 ((org-before-first-heading-p) nil)
13007 (save-excursion
13008 (org-back-to-heading t)
13009 (let ((end (org-entry-end-position)))
13010 (catch :repeat
13011 (while (re-search-forward org-repeat-re end t)
13012 (when (save-match-data (org-at-timestamp-p 'agenda))
13013 (throw :repeat (match-string-no-properties 1)))))))))))
13015 (defvar org-last-changed-timestamp)
13016 (defvar org-last-inserted-timestamp)
13017 (defvar org-log-post-message)
13018 (defvar org-log-note-purpose)
13019 (defvar org-log-note-how nil)
13020 (defvar org-log-note-extra)
13021 (defun org-auto-repeat-maybe (done-word)
13022 "Check if the current headline contains a repeated time-stamp.
13024 If yes, set TODO state back to what it was and change the base date
13025 of repeating deadline/scheduled time stamps to new date.
13027 This function is run automatically after each state change to a DONE state."
13028 (let* ((repeat (org-get-repeat))
13029 (aa (assoc org-last-state org-todo-kwd-alist))
13030 (interpret (nth 1 aa))
13031 (head (nth 2 aa))
13032 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13033 (msg "Entry repeats: ")
13034 (org-log-done nil)
13035 (org-todo-log-states nil)
13036 (end (copy-marker (org-entry-end-position))))
13037 (unwind-protect
13038 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13039 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13040 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13041 org-todo-repeat-to-state)))
13042 (org-todo (cond
13043 ((and to-state (member to-state org-todo-keywords-1))
13044 to-state)
13045 ((eq interpret 'type) org-last-state)
13046 (head)
13047 (t 'none))))
13048 (org-back-to-heading t)
13049 (org-add-planning-info nil nil 'closed)
13050 ;; When `org-log-repeat' is non-nil or entry contains
13051 ;; a clock, set LAST_REPEAT property.
13052 (when (or org-log-repeat
13053 (catch :clock
13054 (save-excursion
13055 (while (re-search-forward org-clock-line-re end t)
13056 (when (org-at-clock-log-p) (throw :clock t))))))
13057 (org-entry-put nil "LAST_REPEAT" (format-time-string
13058 (org-time-stamp-format t t)
13059 (current-time))))
13060 (when org-log-repeat
13061 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13062 (memq 'org-add-log-note post-command-hook))
13063 ;; We are already setup for some record.
13064 (when (eq org-log-repeat 'note)
13065 ;; Make sure we take a note, not only a time stamp.
13066 (setq org-log-note-how 'note))
13067 ;; Set up for taking a record.
13068 (org-add-log-setup 'state
13069 (or done-word (car org-done-keywords))
13070 org-last-state
13071 org-log-repeat)))
13072 (let ((planning-re (regexp-opt
13073 (list org-scheduled-string org-deadline-string))))
13074 (while (re-search-forward org-ts-regexp end t)
13075 (let* ((ts (match-string 0))
13076 (planning? (org-at-planning-p))
13077 (type (if (not planning?) "Plain:"
13078 (save-excursion
13079 (re-search-backward
13080 planning-re (line-beginning-position) t)
13081 (match-string 0)))))
13082 (cond
13083 ;; Ignore fake time-stamps (e.g., within comments).
13084 ((not (org-at-timestamp-p 'agenda)))
13085 ;; Time-stamps without a repeater are usually
13086 ;; skipped. However, a SCHEDULED time-stamp without
13087 ;; one is removed, as they are no longer relevant.
13088 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13089 ts))
13090 (when (equal type org-scheduled-string)
13091 (org-remove-timestamp-with-keyword type)))
13093 (let ((n (string-to-number (match-string 2 ts)))
13094 (what (match-string 3 ts)))
13095 (when (equal what "w") (setq n (* n 7) what "d"))
13096 (when (and (equal what "h")
13097 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13098 ts)))
13099 (user-error
13100 "Cannot repeat in Repeat in %d hour(s) because no hour \
13101 has been set"
13103 ;; Preparation, see if we need to modify the start
13104 ;; date for the change.
13105 (when (match-end 1)
13106 (let ((time (save-match-data
13107 (org-time-string-to-time ts))))
13108 (cond
13109 ((equal (match-string 1 ts) ".")
13110 ;; Shift starting date to today
13111 (org-timestamp-change
13112 (- (org-today) (time-to-days time))
13113 'day))
13114 ((equal (match-string 1 ts) "+")
13115 (let ((nshiftmax 10)
13116 (nshift 0))
13117 (while (or (= nshift 0)
13118 (not (time-less-p (current-time) time)))
13119 (when (= (cl-incf nshift) nshiftmax)
13120 (or (y-or-n-p
13121 (format "%d repeater intervals were not \
13122 enough to shift date past today. Continue? "
13123 nshift))
13124 (user-error "Abort")))
13125 (org-timestamp-change n (cdr (assoc what whata)))
13126 (org-in-regexp org-ts-regexp3)
13127 (setq ts (match-string 1))
13128 (setq time
13129 (save-match-data
13130 (org-time-string-to-time ts)))))
13131 (org-timestamp-change (- n) (cdr (assoc what whata)))
13132 ;; Rematch, so that we have everything in place
13133 ;; for the real shift.
13134 (org-in-regexp org-ts-regexp3)
13135 (setq ts (match-string 1))
13136 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13137 ts)))))
13138 (save-excursion
13139 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13140 (setq msg
13141 (concat
13142 msg type " " org-last-changed-timestamp " "))))))))
13143 (setq org-log-post-message msg)
13144 (message "%s" msg))
13145 (set-marker end nil))))
13147 (defun org-show-todo-tree (arg)
13148 "Make a compact tree which shows all headlines marked with TODO.
13149 The tree will show the lines where the regexp matches, and all higher
13150 headlines above the match.
13151 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13152 With a numeric prefix N, construct a sparse tree for the Nth element
13153 of `org-todo-keywords-1'."
13154 (interactive "P")
13155 (let ((case-fold-search nil)
13156 (kwd-re
13157 (cond ((null arg) org-not-done-regexp)
13158 ((equal arg '(4))
13159 (let ((kwd
13160 (completing-read "Keyword (or KWD1|KWD2|...): "
13161 (mapcar #'list org-todo-keywords-1))))
13162 (concat "\\("
13163 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13164 "\\)\\>")))
13165 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13166 (regexp-quote (nth (1- (prefix-numeric-value arg))
13167 org-todo-keywords-1)))
13168 (t (user-error "Invalid prefix argument: %s" arg)))))
13169 (message "%d TODO entries found"
13170 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13172 (defun org--deadline-or-schedule (arg type time)
13173 "Insert DEADLINE or SCHEDULE information in current entry.
13174 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13175 `org-schedule' for information about ARG and TIME arguments."
13176 (let* ((deadline? (eq type 'deadline))
13177 (keyword (if deadline? org-deadline-string org-scheduled-string))
13178 (log (if deadline? org-log-redeadline org-log-reschedule))
13179 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13180 (old-date-time (and old-date (org-time-string-to-time old-date)))
13181 ;; Save repeater cookie from either TIME or current scheduled
13182 ;; time stamp. We are going to insert it back at the end of
13183 ;; the process.
13184 (repeater (or (and (org-string-nw-p time)
13185 ;; We use `org-repeat-re' because we need
13186 ;; to tell the difference between a real
13187 ;; repeater and a time delta, e.g. "+2d".
13188 (string-match org-repeat-re time)
13189 (match-string 1 time))
13190 (and (org-string-nw-p old-date)
13191 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13192 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13193 old-date)
13194 (match-string 1 old-date)))))
13195 (pcase arg
13196 (`(4)
13197 (when (and old-date log)
13198 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13199 nil old-date log))
13200 (org-remove-timestamp-with-keyword keyword)
13201 (message (if deadline? "Item no longer has a deadline."
13202 "Item is no longer scheduled.")))
13203 (`(16)
13204 (save-excursion
13205 (org-back-to-heading t)
13206 (let ((regexp (if deadline? org-deadline-time-regexp
13207 org-scheduled-time-regexp)))
13208 (if (not (re-search-forward regexp (line-end-position 2) t))
13209 (user-error (if deadline? "No deadline information to update"
13210 "No scheduled information to update"))
13211 (let* ((rpl0 (match-string 1))
13212 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13213 (msg (if deadline? "Warn starting from" "Delay until")))
13214 (replace-match
13215 (concat keyword
13216 " <" rpl
13217 (format " -%dd"
13218 (abs (- (time-to-days
13219 (save-match-data
13220 (org-read-date
13221 nil t nil msg old-date-time)))
13222 (time-to-days old-date-time))))
13223 ">") t t))))))
13225 (org-add-planning-info type time 'closed)
13226 (when (and old-date
13228 (not (equal old-date org-last-inserted-timestamp)))
13229 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13230 org-last-inserted-timestamp
13231 old-date
13232 log))
13233 (when repeater
13234 (save-excursion
13235 (org-back-to-heading t)
13236 (when (re-search-forward
13237 (concat keyword " " org-last-inserted-timestamp)
13238 (line-end-position 2)
13240 (goto-char (1- (match-end 0)))
13241 (insert " " repeater)
13242 (setq org-last-inserted-timestamp
13243 (concat (substring org-last-inserted-timestamp 0 -1)
13244 " " repeater
13245 (substring org-last-inserted-timestamp -1))))))
13246 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13247 org-last-inserted-timestamp)))))
13249 (defun org-deadline (arg &optional time)
13250 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13251 With one universal prefix argument, remove any deadline from the item.
13252 With two universal prefix arguments, prompt for a warning delay.
13253 With argument TIME, set the deadline at the corresponding date. TIME
13254 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13255 (interactive "P")
13256 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13257 (org-map-entries
13258 (lambda () (org--deadline-or-schedule arg 'deadline time))
13260 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13261 'region-start-level
13262 'region)
13263 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13264 (org--deadline-or-schedule arg 'deadline time)))
13266 (defun org-schedule (arg &optional time)
13267 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13268 With one universal prefix argument, remove any scheduling date from the item.
13269 With two universal prefix arguments, prompt for a delay cookie.
13270 With argument TIME, scheduled at the corresponding date. TIME can
13271 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13272 (interactive "P")
13273 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13274 (org-map-entries
13275 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13277 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13278 'region-start-level
13279 'region)
13280 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13281 (org--deadline-or-schedule arg 'scheduled time)))
13283 (defun org-get-scheduled-time (pom &optional inherit)
13284 "Get the scheduled time as a time tuple, of a format suitable
13285 for calling org-schedule with, or if there is no scheduling,
13286 returns nil."
13287 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13288 (when time
13289 (apply 'encode-time (org-parse-time-string time)))))
13291 (defun org-get-deadline-time (pom &optional inherit)
13292 "Get the deadline as a time tuple, of a format suitable for
13293 calling org-deadline with, or if there is no scheduling, returns
13294 nil."
13295 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13296 (when time
13297 (apply 'encode-time (org-parse-time-string time)))))
13299 (defun org-remove-timestamp-with-keyword (keyword)
13300 "Remove all time stamps with KEYWORD in the current entry."
13301 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13302 beg)
13303 (save-excursion
13304 (org-back-to-heading t)
13305 (setq beg (point))
13306 (outline-next-heading)
13307 (while (re-search-backward re beg t)
13308 (replace-match "")
13309 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13310 (equal (char-before) ?\ ))
13311 (backward-delete-char 1)
13312 (when (string-match "^[ \t]*$" (buffer-substring
13313 (point-at-bol) (point-at-eol)))
13314 (delete-region (point-at-bol)
13315 (min (point-max) (1+ (point-at-eol))))))))))
13317 (defvar org-time-was-given) ; dynamically scoped parameter
13318 (defvar org-end-time-was-given) ; dynamically scoped parameter
13320 (defun org-at-planning-p ()
13321 "Non-nil when point is on a planning info line."
13322 ;; This is as accurate and faster than `org-element-at-point' since
13323 ;; planning info location is fixed in the section.
13324 (org-with-wide-buffer
13325 (beginning-of-line)
13326 (and (looking-at-p org-planning-line-re)
13327 (eq (point)
13328 (ignore-errors
13329 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13330 (org-back-to-heading t)
13331 (org-with-limited-levels (org-back-to-heading t)))
13332 (line-beginning-position 2))))))
13334 (defun org-add-planning-info (what &optional time &rest remove)
13335 "Insert new timestamp with keyword in the planning line.
13336 WHAT indicates what kind of time stamp to add. It is a symbol
13337 among `closed', `deadline', `scheduled' and nil. TIME indicates
13338 the time to use. If none is given, the user is prompted for
13339 a date. REMOVE indicates what kind of entries to remove. An old
13340 WHAT entry will also be removed."
13341 (let (org-time-was-given org-end-time-was-given default-time default-input)
13342 (catch 'exit
13343 (when (and (memq what '(scheduled deadline))
13344 (or (not time)
13345 (and (stringp time)
13346 (string-match "^[-+]+[0-9]" time))))
13347 ;; Try to get a default date/time from existing timestamp
13348 (save-excursion
13349 (org-back-to-heading t)
13350 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13351 (when (re-search-forward (if (eq what 'scheduled)
13352 org-scheduled-time-regexp
13353 org-deadline-time-regexp)
13354 end t)
13355 (setq ts (match-string 1)
13356 default-time (apply 'encode-time (org-parse-time-string ts))
13357 default-input (and ts (org-get-compact-tod ts)))))))
13358 (when what
13359 (setq time
13360 (if (stringp time)
13361 ;; This is a string (relative or absolute), set
13362 ;; proper date.
13363 (apply #'encode-time
13364 (org-read-date-analyze
13365 time default-time (decode-time default-time)))
13366 ;; If necessary, get the time from the user
13367 (or time (org-read-date nil 'to-time nil nil
13368 default-time default-input)))))
13370 (org-with-wide-buffer
13371 (org-back-to-heading t)
13372 (forward-line)
13373 (unless (bolp) (insert "\n"))
13374 (cond ((looking-at-p org-planning-line-re)
13375 ;; Move to current indentation.
13376 (skip-chars-forward " \t")
13377 ;; Check if we have to remove something.
13378 (dolist (type (if what (cons what remove) remove))
13379 (save-excursion
13380 (when (re-search-forward
13381 (cl-case type
13382 (closed org-closed-time-regexp)
13383 (deadline org-deadline-time-regexp)
13384 (scheduled org-scheduled-time-regexp)
13385 (otherwise
13386 (error "Invalid planning type: %s" type)))
13387 (line-end-position) t)
13388 ;; Delete until next keyword or end of line.
13389 (delete-region
13390 (match-beginning 0)
13391 (if (re-search-forward org-keyword-time-not-clock-regexp
13392 (line-end-position)
13394 (match-beginning 0)
13395 (line-end-position))))))
13396 ;; If there is nothing more to add and no more keyword
13397 ;; is left, remove the line completely.
13398 (if (and (looking-at-p "[ \t]*$") (not what))
13399 (delete-region (line-beginning-position)
13400 (line-beginning-position 2))
13401 ;; If we removed last keyword, do not leave trailing
13402 ;; white space at the end of line.
13403 (let ((p (point)))
13404 (save-excursion
13405 (end-of-line)
13406 (unless (= (skip-chars-backward " \t" p) 0)
13407 (delete-region (point) (line-end-position)))))))
13408 ((not what) (throw 'exit nil)) ; Nothing to do.
13409 (t (insert-before-markers "\n")
13410 (backward-char 1)
13411 (when org-adapt-indentation
13412 (indent-to-column (1+ (org-outline-level))))))
13413 (when what
13414 ;; Insert planning keyword.
13415 (insert (cl-case what
13416 (closed org-closed-string)
13417 (deadline org-deadline-string)
13418 (scheduled org-scheduled-string)
13419 (otherwise (error "Invalid planning type: %s" what)))
13420 " ")
13421 ;; Insert associated timestamp.
13422 (let ((ts (org-insert-time-stamp
13423 time
13424 (or org-time-was-given
13425 (and (eq what 'closed) org-log-done-with-time))
13426 (eq what 'closed)
13427 nil nil (list org-end-time-was-given))))
13428 (unless (eolp) (insert " "))
13429 ts))))))
13431 (defvar org-log-note-marker (make-marker)
13432 "Marker pointing at the entry where the note is to be inserted.")
13433 (defvar org-log-note-purpose nil)
13434 (defvar org-log-note-state nil)
13435 (defvar org-log-note-previous-state nil)
13436 (defvar org-log-note-extra nil)
13437 (defvar org-log-note-window-configuration nil)
13438 (defvar org-log-note-return-to (make-marker))
13439 (defvar org-log-note-effective-time nil
13440 "Remembered current time so that dynamically scoped
13441 `org-extend-today-until' affects timestamps in state change log")
13443 (defvar org-log-post-message nil
13444 "Message to be displayed after a log note has been stored.
13445 The auto-repeater uses this.")
13447 (defun org-add-note ()
13448 "Add a note to the current entry.
13449 This is done in the same way as adding a state change note."
13450 (interactive)
13451 (org-add-log-setup 'note))
13453 (defun org-log-beginning (&optional create)
13454 "Return expected start of log notes in current entry.
13455 When optional argument CREATE is non-nil, the function creates
13456 a drawer to store notes, if necessary. Returned position ignores
13457 narrowing."
13458 (org-with-wide-buffer
13459 (let ((drawer (org-log-into-drawer)))
13460 (cond
13461 (drawer
13462 (org-end-of-meta-data)
13463 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13464 (end (if (org-at-heading-p) (point)
13465 (save-excursion (outline-next-heading) (point))))
13466 (case-fold-search t))
13467 (catch 'exit
13468 ;; Try to find existing drawer.
13469 (while (re-search-forward regexp end t)
13470 (let ((element (org-element-at-point)))
13471 (when (eq (org-element-type element) 'drawer)
13472 (let ((cend (org-element-property :contents-end element)))
13473 (when (and (not org-log-states-order-reversed) cend)
13474 (goto-char cend)))
13475 (throw 'exit nil))))
13476 ;; No drawer found. Create one, if permitted.
13477 (when create
13478 (unless (bolp) (insert "\n"))
13479 (let ((beg (point)))
13480 (insert ":" drawer ":\n:END:\n")
13481 (org-indent-region beg (point)))
13482 (end-of-line -1)))))
13484 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13485 (skip-chars-forward " \t\n")
13486 (beginning-of-line)
13487 (unless org-log-states-order-reversed
13488 (org-skip-over-state-notes)
13489 (skip-chars-backward " \t\n")
13490 (forward-line)))))
13491 (if (bolp) (point) (line-beginning-position 2))))
13493 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13494 "Set up the post command hook to take a note.
13495 If this is about to TODO state change, the new state is expected in STATE.
13496 HOW is an indicator what kind of note should be created.
13497 EXTRA is additional text that will be inserted into the notes buffer."
13498 (move-marker org-log-note-marker (point))
13499 (setq org-log-note-purpose purpose
13500 org-log-note-state state
13501 org-log-note-previous-state prev-state
13502 org-log-note-how how
13503 org-log-note-extra extra
13504 org-log-note-effective-time (org-current-effective-time))
13505 (add-hook 'post-command-hook 'org-add-log-note 'append))
13507 (defun org-skip-over-state-notes ()
13508 "Skip past the list of State notes in an entry."
13509 (when (ignore-errors (goto-char (org-in-item-p)))
13510 (let* ((struct (org-list-struct))
13511 (prevs (org-list-prevs-alist struct))
13512 (regexp
13513 (concat "[ \t]*- +"
13514 (replace-regexp-in-string
13515 " +" " +"
13516 (org-replace-escapes
13517 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13518 `(("%d" . ,org-ts-regexp-inactive)
13519 ("%D" . ,org-ts-regexp)
13520 ("%s" . "\"\\S-+\"")
13521 ("%S" . "\"\\S-+\"")
13522 ("%t" . ,org-ts-regexp-inactive)
13523 ("%T" . ,org-ts-regexp)
13524 ("%u" . ".*?")
13525 ("%U" . ".*?")))))))
13526 (while (looking-at-p regexp)
13527 (goto-char (or (org-list-get-next-item (point) struct prevs)
13528 (org-list-get-item-end (point) struct)))))))
13530 (defun org-add-log-note (&optional _purpose)
13531 "Pop up a window for taking a note, and add this note later."
13532 (remove-hook 'post-command-hook 'org-add-log-note)
13533 (setq org-log-note-window-configuration (current-window-configuration))
13534 (delete-other-windows)
13535 (move-marker org-log-note-return-to (point))
13536 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13537 (goto-char org-log-note-marker)
13538 (org-switch-to-buffer-other-window "*Org Note*")
13539 (erase-buffer)
13540 (if (memq org-log-note-how '(time state))
13541 (org-store-log-note)
13542 (let ((org-inhibit-startup t)) (org-mode))
13543 (insert (format "# Insert note for %s.
13544 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13545 (cond
13546 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13547 ((eq org-log-note-purpose 'done) "closed todo item")
13548 ((eq org-log-note-purpose 'state)
13549 (format "state change from \"%s\" to \"%s\""
13550 (or org-log-note-previous-state "")
13551 (or org-log-note-state "")))
13552 ((eq org-log-note-purpose 'reschedule)
13553 "rescheduling")
13554 ((eq org-log-note-purpose 'delschedule)
13555 "no longer scheduled")
13556 ((eq org-log-note-purpose 'redeadline)
13557 "changing deadline")
13558 ((eq org-log-note-purpose 'deldeadline)
13559 "removing deadline")
13560 ((eq org-log-note-purpose 'refile)
13561 "refiling")
13562 ((eq org-log-note-purpose 'note)
13563 "this entry")
13564 (t (error "This should not happen")))))
13565 (when org-log-note-extra (insert org-log-note-extra))
13566 (setq-local org-finish-function 'org-store-log-note)
13567 (run-hooks 'org-log-buffer-setup-hook)))
13569 (defvar org-note-abort nil) ; dynamically scoped
13570 (defun org-store-log-note ()
13571 "Finish taking a log note, and insert it to where it belongs."
13572 (let ((txt (prog1 (buffer-string)
13573 (kill-buffer)))
13574 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13575 lines)
13576 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13577 (setq txt (replace-match "" t t txt)))
13578 (when (string-match "\\s-+\\'" txt)
13579 (setq txt (replace-match "" t t txt)))
13580 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13581 (when (org-string-nw-p note)
13582 (setq note
13583 (org-replace-escapes
13584 note
13585 (list (cons "%u" (user-login-name))
13586 (cons "%U" user-full-name)
13587 (cons "%t" (format-time-string
13588 (org-time-stamp-format 'long 'inactive)
13589 org-log-note-effective-time))
13590 (cons "%T" (format-time-string
13591 (org-time-stamp-format 'long nil)
13592 org-log-note-effective-time))
13593 (cons "%d" (format-time-string
13594 (org-time-stamp-format nil 'inactive)
13595 org-log-note-effective-time))
13596 (cons "%D" (format-time-string
13597 (org-time-stamp-format nil nil)
13598 org-log-note-effective-time))
13599 (cons "%s" (cond
13600 ((not org-log-note-state) "")
13601 ((string-match-p org-ts-regexp
13602 org-log-note-state)
13603 (format "\"[%s]\""
13604 (substring org-log-note-state 1 -1)))
13605 (t (format "\"%s\"" org-log-note-state))))
13606 (cons "%S"
13607 (cond
13608 ((not org-log-note-previous-state) "")
13609 ((string-match-p org-ts-regexp
13610 org-log-note-previous-state)
13611 (format "\"[%s]\""
13612 (substring
13613 org-log-note-previous-state 1 -1)))
13614 (t (format "\"%s\""
13615 org-log-note-previous-state)))))))
13616 (when lines (setq note (concat note " \\\\")))
13617 (push note lines))
13618 (when (and lines (not org-note-abort))
13619 (with-current-buffer (marker-buffer org-log-note-marker)
13620 (org-with-wide-buffer
13621 ;; Find location for the new note.
13622 (goto-char org-log-note-marker)
13623 (set-marker org-log-note-marker nil)
13624 ;; Note associated to a clock is to be located right after
13625 ;; the clock. Do not move point.
13626 (unless (eq org-log-note-purpose 'clock-out)
13627 (goto-char (org-log-beginning t)))
13628 ;; Make sure point is at the beginning of an empty line.
13629 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13630 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13631 ;; In an existing list, add a new item at the top level.
13632 ;; Otherwise, indent line like a regular one.
13633 (let ((itemp (org-in-item-p)))
13634 (if itemp
13635 (indent-line-to
13636 (let ((struct (save-excursion
13637 (goto-char itemp) (org-list-struct))))
13638 (org-list-get-ind (org-list-get-top-point struct) struct)))
13639 (org-indent-line)))
13640 (insert (org-list-bullet-string "-") (pop lines))
13641 (let ((ind (org-list-item-body-column (line-beginning-position))))
13642 (dolist (line lines)
13643 (insert "\n")
13644 (indent-line-to ind)
13645 (insert line)))
13646 (message "Note stored")
13647 (org-back-to-heading t)
13648 (org-cycle-hide-drawers 'children))
13649 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13650 ;; from within `org-add-log-note' because `buffer-undo-list'
13651 ;; is then modified outside of `org-with-remote-undo'.
13652 (when (eq this-command 'org-agenda-todo)
13653 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13654 ;; Don't add undo information when called from `org-agenda-todo'.
13655 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13656 (set-window-configuration org-log-note-window-configuration)
13657 (with-current-buffer (marker-buffer org-log-note-return-to)
13658 (goto-char org-log-note-return-to))
13659 (move-marker org-log-note-return-to nil)
13660 (when org-log-post-message (message "%s" org-log-post-message))))
13662 (defun org-remove-empty-drawer-at (pos)
13663 "Remove an empty drawer at position POS.
13664 POS may also be a marker."
13665 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13666 (org-with-wide-buffer
13667 (goto-char pos)
13668 (let ((drawer (org-element-at-point)))
13669 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13670 (not (org-element-property :contents-begin drawer)))
13671 (delete-region (org-element-property :begin drawer)
13672 (progn (goto-char (org-element-property :end drawer))
13673 (skip-chars-backward " \r\t\n")
13674 (forward-line)
13675 (point))))))))
13677 (defvar org-ts-type nil)
13678 (defun org-sparse-tree (&optional arg type)
13679 "Create a sparse tree, prompt for the details.
13680 This command can create sparse trees. You first need to select the type
13681 of match used to create the tree:
13683 t Show all TODO entries.
13684 T Show entries with a specific TODO keyword.
13685 m Show entries selected by a tags/property match.
13686 p Enter a property name and its value (both with completion on existing
13687 names/values) and show entries with that property.
13688 r Show entries matching a regular expression (`/' can be used as well).
13689 b Show deadlines and scheduled items before a date.
13690 a Show deadlines and scheduled items after a date.
13691 d Show deadlines due within `org-deadline-warning-days'.
13692 D Show deadlines and scheduled items between a date range."
13693 (interactive "P")
13694 (setq type (or type org-sparse-tree-default-date-type))
13695 (setq org-ts-type type)
13696 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13697 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13698 \[c]ycle through date types: %s"
13699 (cl-case type
13700 (all "all timestamps")
13701 (scheduled "only scheduled")
13702 (deadline "only deadline")
13703 (active "only active timestamps")
13704 (inactive "only inactive timestamps")
13705 (closed "with a closed time-stamp")
13706 (otherwise "scheduled/deadline")))
13707 (let ((answer (read-char-exclusive)))
13708 (cl-case answer
13710 (org-sparse-tree
13712 (cadr
13713 (memq type '(nil all scheduled deadline active inactive closed)))))
13714 (?d (call-interactively 'org-check-deadlines))
13715 (?b (call-interactively 'org-check-before-date))
13716 (?a (call-interactively 'org-check-after-date))
13717 (?D (call-interactively 'org-check-dates-range))
13718 (?t (call-interactively 'org-show-todo-tree))
13719 (?T (org-show-todo-tree '(4)))
13720 (?m (call-interactively 'org-match-sparse-tree))
13721 ((?p ?P)
13722 (let* ((kwd (completing-read
13723 "Property: " (mapcar #'list (org-buffer-property-keys))))
13724 (value (completing-read
13725 "Value: " (mapcar #'list (org-property-values kwd)))))
13726 (unless (string-match "\\`{.*}\\'" value)
13727 (setq value (concat "\"" value "\"")))
13728 (org-match-sparse-tree arg (concat kwd "=" value))))
13729 ((?r ?R ?/) (call-interactively 'org-occur))
13730 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13732 (defvar-local org-occur-highlights nil
13733 "List of overlays used for occur matches.")
13734 (defvar-local org-occur-parameters nil
13735 "Parameters of the active org-occur calls.
13736 This is a list, each call to org-occur pushes as cons cell,
13737 containing the regular expression and the callback, onto the list.
13738 The list can contain several entries if `org-occur' has been called
13739 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13740 will only contain one set of parameters. When the highlights are
13741 removed (for example with `C-c C-c', or with the next edit (depending
13742 on `org-remove-highlights-with-change'), this variable is emptied
13743 as well.")
13745 (defun org-occur (regexp &optional keep-previous callback)
13746 "Make a compact tree which shows all matches of REGEXP.
13748 The tree will show the lines where the regexp matches, and any other context
13749 defined in `org-show-context-detail', which see.
13751 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13752 done by a previous call to `org-occur' will be kept, to allow stacking of
13753 calls to this command.
13755 Optional argument CALLBACK can be a function of no argument. In this case,
13756 it is called with point at the end of the match, match data being set
13757 accordingly. Current match is shown only if the return value is non-nil.
13758 The function must neither move point nor alter narrowing."
13759 (interactive "sRegexp: \nP")
13760 (when (equal regexp "")
13761 (user-error "Regexp cannot be empty"))
13762 (unless keep-previous
13763 (org-remove-occur-highlights nil nil t))
13764 (push (cons regexp callback) org-occur-parameters)
13765 (let ((cnt 0))
13766 (save-excursion
13767 (goto-char (point-min))
13768 (when (or (not keep-previous) ; do not want to keep
13769 (not org-occur-highlights)) ; no previous matches
13770 ;; hide everything
13771 (org-overview))
13772 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13773 (isearch-no-upper-case-p regexp t)
13774 org-occur-case-fold-search)))
13775 (while (re-search-forward regexp nil t)
13776 (when (or (not callback)
13777 (save-match-data (funcall callback)))
13778 (setq cnt (1+ cnt))
13779 (when org-highlight-sparse-tree-matches
13780 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13781 (org-show-context 'occur-tree)))))
13782 (when org-remove-highlights-with-change
13783 (add-hook 'before-change-functions 'org-remove-occur-highlights
13784 nil 'local))
13785 (unless org-sparse-tree-open-archived-trees
13786 (org-hide-archived-subtrees (point-min) (point-max)))
13787 (run-hooks 'org-occur-hook)
13788 (when (called-interactively-p 'interactive)
13789 (message "%d match(es) for regexp %s" cnt regexp))
13790 cnt))
13792 (defun org-occur-next-match (&optional n _reset)
13793 "Function for `next-error-function' to find sparse tree matches.
13794 N is the number of matches to move, when negative move backwards.
13795 This function always goes back to the starting point when no
13796 match is found."
13797 (let* ((limit (if (< n 0) (point-min) (point-max)))
13798 (search-func (if (< n 0)
13799 'previous-single-char-property-change
13800 'next-single-char-property-change))
13801 (n (abs n))
13802 (pos (point))
13804 (catch 'exit
13805 (while (setq p1 (funcall search-func (point) 'org-type))
13806 (when (equal p1 limit)
13807 (goto-char pos)
13808 (user-error "No more matches"))
13809 (when (equal (get-char-property p1 'org-type) 'org-occur)
13810 (setq n (1- n))
13811 (when (= n 0)
13812 (goto-char p1)
13813 (throw 'exit (point))))
13814 (goto-char p1))
13815 (goto-char p1)
13816 (user-error "No more matches"))))
13818 (defun org-show-context (&optional key)
13819 "Make sure point and context are visible.
13820 Optional argument KEY, when non-nil, is a symbol. See
13821 `org-show-context-detail' for allowed values and how much is to
13822 be shown."
13823 (org-show-set-visibility
13824 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13825 ((cdr (assq key org-show-context-detail)))
13826 (t (cdr (assq 'default org-show-context-detail))))))
13828 (defun org-show-set-visibility (detail)
13829 "Set visibility around point according to DETAIL.
13830 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13831 `tree', `canonical' or t. See `org-show-context-detail' for more
13832 information."
13833 ;; Show current heading and possibly its entry, following headline
13834 ;; or all children.
13835 (if (and (org-at-heading-p) (not (eq detail 'local)))
13836 (org-flag-heading nil)
13837 (org-show-entry)
13838 ;; If point is hidden within a drawer or a block, make sure to
13839 ;; expose it.
13840 (dolist (o (overlays-at (point)))
13841 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13842 (delete-overlay o)))
13843 (unless (org-before-first-heading-p)
13844 (org-with-limited-levels
13845 (cl-case detail
13846 ((tree canonical t) (org-show-children))
13847 ((nil minimal ancestors))
13848 (t (save-excursion
13849 (outline-next-heading)
13850 (org-flag-heading nil)))))))
13851 ;; Show all siblings.
13852 (when (eq detail 'lineage) (org-show-siblings))
13853 ;; Show ancestors, possibly with their children.
13854 (when (memq detail '(ancestors lineage tree canonical t))
13855 (save-excursion
13856 (while (org-up-heading-safe)
13857 (org-flag-heading nil)
13858 (when (memq detail '(canonical t)) (org-show-entry))
13859 (when (memq detail '(tree canonical t)) (org-show-children))))))
13861 (defvar org-reveal-start-hook nil
13862 "Hook run before revealing a location.")
13864 (defun org-reveal (&optional siblings)
13865 "Show current entry, hierarchy above it, and the following headline.
13867 This can be used to show a consistent set of context around
13868 locations exposed with `org-show-context'.
13870 With optional argument SIBLINGS, on each level of the hierarchy all
13871 siblings are shown. This repairs the tree structure to what it would
13872 look like when opened with hierarchical calls to `org-cycle'.
13874 With a \\[universal-argument] \\[universal-argument] prefix, \
13875 go to the parent and show the entire tree."
13876 (interactive "P")
13877 (run-hooks 'org-reveal-start-hook)
13878 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13879 ((equal siblings '(16))
13880 (save-excursion
13881 (when (org-up-heading-safe)
13882 (org-show-subtree)
13883 (run-hook-with-args 'org-cycle-hook 'subtree))))
13884 (t (org-show-set-visibility 'lineage))))
13886 (defun org-highlight-new-match (beg end)
13887 "Highlight from BEG to END and mark the highlight is an occur headline."
13888 (let ((ov (make-overlay beg end)))
13889 (overlay-put ov 'face 'secondary-selection)
13890 (overlay-put ov 'org-type 'org-occur)
13891 (push ov org-occur-highlights)))
13893 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13894 "Remove the occur highlights from the buffer.
13895 BEG and END are ignored. If NOREMOVE is nil, remove this function
13896 from the `before-change-functions' in the current buffer."
13897 (interactive)
13898 (unless org-inhibit-highlight-removal
13899 (mapc #'delete-overlay org-occur-highlights)
13900 (setq org-occur-highlights nil)
13901 (setq org-occur-parameters nil)
13902 (unless noremove
13903 (remove-hook 'before-change-functions
13904 'org-remove-occur-highlights 'local))))
13906 ;;;; Priorities
13908 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13909 "Regular expression matching the priority indicator.")
13911 (defvar org-remove-priority-next-time nil)
13913 (defun org-priority-up ()
13914 "Increase the priority of the current item."
13915 (interactive)
13916 (org-priority 'up))
13918 (defun org-priority-down ()
13919 "Decrease the priority of the current item."
13920 (interactive)
13921 (org-priority 'down))
13923 (defun org-priority (&optional action _show)
13924 "Change the priority of an item.
13925 ACTION can be `set', `up', `down', or a character."
13926 (interactive "P")
13927 (if (equal action '(4))
13928 (org-show-priority)
13929 (unless org-enable-priority-commands
13930 (user-error "Priority commands are disabled"))
13931 (setq action (or action 'set))
13932 (let (current new news have remove)
13933 (save-excursion
13934 (org-back-to-heading t)
13935 (when (looking-at org-priority-regexp)
13936 (setq current (string-to-char (match-string 2))
13937 have t))
13938 (cond
13939 ((eq action 'remove)
13940 (setq remove t new ?\ ))
13941 ((or (eq action 'set)
13942 (integerp action))
13943 (if (not (eq action 'set))
13944 (setq new action)
13945 (message "Priority %c-%c, SPC to remove: "
13946 org-highest-priority org-lowest-priority)
13947 (save-match-data
13948 (setq new (read-char-exclusive))))
13949 (when (and (= (upcase org-highest-priority) org-highest-priority)
13950 (= (upcase org-lowest-priority) org-lowest-priority))
13951 (setq new (upcase new)))
13952 (cond ((equal new ?\ ) (setq remove t))
13953 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13954 (user-error "Priority must be between `%c' and `%c'"
13955 org-highest-priority org-lowest-priority))))
13956 ((eq action 'up)
13957 (setq new (if have
13958 (1- current) ; normal cycling
13959 ;; last priority was empty
13960 (if (eq last-command this-command)
13961 org-lowest-priority ; wrap around empty to lowest
13962 ;; default
13963 (if org-priority-start-cycle-with-default
13964 org-default-priority
13965 (1- org-default-priority))))))
13966 ((eq action 'down)
13967 (setq new (if have
13968 (1+ current) ; normal cycling
13969 ;; last priority was empty
13970 (if (eq last-command this-command)
13971 org-highest-priority ; wrap around empty to highest
13972 ;; default
13973 (if org-priority-start-cycle-with-default
13974 org-default-priority
13975 (1+ org-default-priority))))))
13976 (t (user-error "Invalid action")))
13977 (when (or (< (upcase new) org-highest-priority)
13978 (> (upcase new) org-lowest-priority))
13979 (if (and (memq action '(up down))
13980 (not have) (not (eq last-command this-command)))
13981 ;; `new' is from default priority
13982 (error
13983 "The default can not be set, see `org-default-priority' why")
13984 ;; normal cycling: `new' is beyond highest/lowest priority
13985 ;; and is wrapped around to the empty priority
13986 (setq remove t)))
13987 (setq news (format "%c" new))
13988 (if have
13989 (if remove
13990 (replace-match "" t t nil 1)
13991 (replace-match news t t nil 2))
13992 (if remove
13993 (user-error "No priority cookie found in line")
13994 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13995 (if (match-end 2)
13996 (progn
13997 (goto-char (match-end 2))
13998 (insert " [#" news "]"))
13999 (goto-char (match-beginning 3))
14000 (insert "[#" news "] "))))
14001 (org-set-tags nil 'align))
14002 (if remove
14003 (message "Priority removed")
14004 (message "Priority of current item set to %s" news)))))
14006 (defun org-show-priority ()
14007 "Show the priority of the current item.
14008 This priority is composed of the main priority given with the [#A] cookies,
14009 and by additional input from the age of a schedules or deadline entry."
14010 (interactive)
14011 (let ((pri (if (eq major-mode 'org-agenda-mode)
14012 (org-get-at-bol 'priority)
14013 (save-excursion
14014 (save-match-data
14015 (beginning-of-line)
14016 (and (looking-at org-heading-regexp)
14017 (org-get-priority (match-string 0))))))))
14018 (message "Priority is %d" (if pri pri -1000))))
14020 (defun org-get-priority (s)
14021 "Find priority cookie and return priority."
14022 (save-match-data
14023 (if (functionp org-get-priority-function)
14024 (funcall org-get-priority-function)
14025 (if (not (string-match org-priority-regexp s))
14026 (* 1000 (- org-lowest-priority org-default-priority))
14027 (* 1000 (- org-lowest-priority
14028 (string-to-char (match-string 2 s))))))))
14030 ;;;; Tags
14032 (defvar org-agenda-archives-mode)
14033 (defvar org-map-continue-from nil
14034 "Position from where mapping should continue.
14035 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14037 (defvar org-scanner-tags nil
14038 "The current tag list while the tags scanner is running.")
14040 (defvar org-trust-scanner-tags nil
14041 "Should `org-get-tags-at' use the tags for the scanner.
14042 This is for internal dynamical scoping only.
14043 When this is non-nil, the function `org-get-tags-at' will return the value
14044 of `org-scanner-tags' instead of building the list by itself. This
14045 can lead to large speed-ups when the tags scanner is used in a file with
14046 many entries, and when the list of tags is retrieved, for example to
14047 obtain a list of properties. Building the tags list for each entry in such
14048 a file becomes an N^2 operation - but with this variable set, it scales
14049 as N.")
14051 (defvar org--matcher-tags-todo-only nil)
14053 (defun org-scan-tags (action matcher todo-only &optional start-level)
14054 "Scan headline tags with inheritance and produce output ACTION.
14056 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14057 or `agenda' to produce an entry list for an agenda view. It can also be
14058 a Lisp form or a function that should be called at each matched headline, in
14059 this case the return value is a list of all return values from these calls.
14061 MATCHER is a function accepting three arguments, returning
14062 a non-nil value whenever a given set of tags qualifies a headline
14063 for inclusion. See `org-make-tags-matcher' for more information.
14064 As a special case, it can also be set to t (respectively nil) in
14065 order to match all (respectively none) headline.
14067 When TODO-ONLY is non-nil, only lines with a TODO keyword are
14068 included in the output.
14070 START-LEVEL can be a string with asterisks, reducing the scope to
14071 headlines matching this string."
14072 (require 'org-agenda)
14073 (let* ((re (concat "^"
14074 (if start-level
14075 ;; Get the correct level to match
14076 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14077 org-outline-regexp)
14078 " *\\(\\<\\("
14079 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14080 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14081 (props (list 'face 'default
14082 'done-face 'org-agenda-done
14083 'undone-face 'default
14084 'mouse-face 'highlight
14085 'org-not-done-regexp org-not-done-regexp
14086 'org-todo-regexp org-todo-regexp
14087 'org-complex-heading-regexp org-complex-heading-regexp
14088 'help-echo
14089 (format "mouse-2 or RET jump to org file %s"
14090 (abbreviate-file-name
14091 (or (buffer-file-name (buffer-base-buffer))
14092 (buffer-name (buffer-base-buffer)))))))
14093 (org-map-continue-from nil)
14094 lspos tags tags-list
14095 (tags-alist (list (cons 0 org-file-tags)))
14096 (llast 0) rtn rtn1 level category i txt
14097 todo marker entry priority
14098 ts-date ts-date-type ts-date-pair)
14099 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14100 (setq action (list 'lambda nil action)))
14101 (save-excursion
14102 (goto-char (point-min))
14103 (when (eq action 'sparse-tree)
14104 (org-overview)
14105 (org-remove-occur-highlights))
14106 (while (let (case-fold-search)
14107 (re-search-forward re nil t))
14108 (setq org-map-continue-from nil)
14109 (catch :skip
14110 (setq todo
14111 ;; TODO: is the 1-2 difference a bug?
14112 (when (match-end 1) (match-string-no-properties 2))
14113 tags (when (match-end 4) (match-string-no-properties 4)))
14114 (goto-char (setq lspos (match-beginning 0)))
14115 (setq level (org-reduced-level (org-outline-level))
14116 category (org-get-category))
14117 (when (eq action 'agenda)
14118 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14119 ts-date (car ts-date-pair)
14120 ts-date-type (cdr ts-date-pair)))
14121 (setq i llast llast level)
14122 ;; remove tag lists from same and sublevels
14123 (while (>= i level)
14124 (when (setq entry (assoc i tags-alist))
14125 (setq tags-alist (delete entry tags-alist)))
14126 (setq i (1- i)))
14127 ;; add the next tags
14128 (when tags
14129 (setq tags (org-split-string tags ":")
14130 tags-alist
14131 (cons (cons level tags) tags-alist)))
14132 ;; compile tags for current headline
14133 (setq tags-list
14134 (if org-use-tag-inheritance
14135 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14136 tags)
14137 org-scanner-tags tags-list)
14138 (when org-use-tag-inheritance
14139 (setcdr (car tags-alist)
14140 (mapcar (lambda (x)
14141 (setq x (copy-sequence x))
14142 (org-add-prop-inherited x))
14143 (cdar tags-alist))))
14144 (when (and tags org-use-tag-inheritance
14145 (or (not (eq t org-use-tag-inheritance))
14146 org-tags-exclude-from-inheritance))
14147 ;; Selective inheritance, remove uninherited ones.
14148 (setcdr (car tags-alist)
14149 (org-remove-uninherited-tags (cdar tags-alist))))
14150 (when (and
14152 ;; eval matcher only when the todo condition is OK
14153 (and (or (not todo-only) (member todo org-todo-keywords-1))
14154 (if (functionp matcher)
14155 (let ((case-fold-search t) (org-trust-scanner-tags t))
14156 (funcall matcher todo tags-list level))
14157 matcher))
14159 ;; Call the skipper, but return t if it does not
14160 ;; skip, so that the `and' form continues evaluating.
14161 (progn
14162 (unless (eq action 'sparse-tree) (org-agenda-skip))
14165 ;; Check if timestamps are deselecting this entry
14166 (or (not todo-only)
14167 (and (member todo org-todo-keywords-1)
14168 (or (not org-agenda-tags-todo-honor-ignore-options)
14169 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14171 ;; select this headline
14172 (cond
14173 ((eq action 'sparse-tree)
14174 (and org-highlight-sparse-tree-matches
14175 (org-get-heading) (match-end 0)
14176 (org-highlight-new-match
14177 (match-beginning 1) (match-end 1)))
14178 (org-show-context 'tags-tree))
14179 ((eq action 'agenda)
14180 (setq txt (org-agenda-format-item
14182 (concat
14183 (if (eq org-tags-match-list-sublevels 'indented)
14184 (make-string (1- level) ?.) "")
14185 (org-get-heading))
14186 (make-string level ?\s)
14187 category
14188 tags-list)
14189 priority (org-get-priority txt))
14190 (goto-char lspos)
14191 (setq marker (org-agenda-new-marker))
14192 (org-add-props txt props
14193 'org-marker marker 'org-hd-marker marker 'org-category category
14194 'todo-state todo
14195 'ts-date ts-date
14196 'priority priority
14197 'type (concat "tagsmatch" ts-date-type))
14198 (push txt rtn))
14199 ((functionp action)
14200 (setq org-map-continue-from nil)
14201 (save-excursion
14202 (setq rtn1 (funcall action))
14203 (push rtn1 rtn)))
14204 (t (user-error "Invalid action")))
14206 ;; if we are to skip sublevels, jump to end of subtree
14207 (unless org-tags-match-list-sublevels
14208 (org-end-of-subtree t)
14209 (backward-char 1))))
14210 ;; Get the correct position from where to continue
14211 (if org-map-continue-from
14212 (goto-char org-map-continue-from)
14213 (and (= (point) lspos) (end-of-line 1)))))
14214 (when (and (eq action 'sparse-tree)
14215 (not org-sparse-tree-open-archived-trees))
14216 (org-hide-archived-subtrees (point-min) (point-max)))
14217 (nreverse rtn)))
14219 (defun org-remove-uninherited-tags (tags)
14220 "Remove all tags that are not inherited from the list TAGS."
14221 (cond
14222 ((eq org-use-tag-inheritance t)
14223 (if org-tags-exclude-from-inheritance
14224 (org-delete-all org-tags-exclude-from-inheritance tags)
14225 tags))
14226 ((not org-use-tag-inheritance) nil)
14227 ((stringp org-use-tag-inheritance)
14228 (delq nil (mapcar
14229 (lambda (x)
14230 (if (and (string-match org-use-tag-inheritance x)
14231 (not (member x org-tags-exclude-from-inheritance)))
14232 x nil))
14233 tags)))
14234 ((listp org-use-tag-inheritance)
14235 (delq nil (mapcar
14236 (lambda (x)
14237 (if (member x org-use-tag-inheritance) x nil))
14238 tags)))))
14240 (defun org-match-sparse-tree (&optional todo-only match)
14241 "Create a sparse tree according to tags string MATCH.
14243 MATCH is a string with match syntax. It can contain a selection
14244 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14245 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14246 those. See the manual for details.
14248 If optional argument TODO-ONLY is non-nil, only select lines that
14249 are also TODO tasks."
14250 (interactive "P")
14251 (org-agenda-prepare-buffers (list (current-buffer)))
14252 (let ((org--matcher-tags-todo-only todo-only))
14253 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14254 org--matcher-tags-todo-only)))
14256 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14258 (defvar org-cached-props nil)
14259 (defun org-cached-entry-get (pom property)
14260 (if (or (eq t org-use-property-inheritance)
14261 (and (stringp org-use-property-inheritance)
14262 (let ((case-fold-search t))
14263 (string-match-p org-use-property-inheritance property)))
14264 (and (listp org-use-property-inheritance)
14265 (member-ignore-case property org-use-property-inheritance)))
14266 ;; Caching is not possible, check it directly.
14267 (org-entry-get pom property 'inherit)
14268 ;; Get all properties, so we can do complicated checks easily.
14269 (cdr (assoc-string property
14270 (or org-cached-props
14271 (setq org-cached-props (org-entry-properties pom)))
14272 t))))
14274 (defun org-global-tags-completion-table (&optional files)
14275 "Return the list of all tags in all agenda buffer/files.
14276 Optional FILES argument is a list of files which can be used
14277 instead of the agenda files."
14278 (save-excursion
14279 (org-uniquify
14280 (delq nil
14281 (apply #'append
14282 (mapcar
14283 (lambda (file)
14284 (set-buffer (find-file-noselect file))
14285 (mapcar (lambda (x)
14286 (and (stringp (car-safe x))
14287 (list (car-safe x))))
14288 (or org-current-tag-alist (org-get-buffer-tags))))
14289 (if (car-safe files) files
14290 (org-agenda-files))))))))
14292 (defun org-make-tags-matcher (match)
14293 "Create the TAGS/TODO matcher form for the selection string MATCH.
14295 Returns a cons of the selection string MATCH and a function
14296 implementing the matcher.
14298 The matcher is to be called at an Org entry, with point on the
14299 headline, and returns non-nil if the entry matches the selection
14300 string MATCH. It must be called with three arguments: the TODO
14301 keyword at the entry (or nil if none), the list of all tags at
14302 the entry including inherited ones and the reduced level of the
14303 headline. Additionally, the category of the entry, if any, must
14304 be specified as the text property `org-category' on the headline.
14306 This function sets the variable `org--matcher-tags-todo-only' to
14307 a non-nil value if the matcher restricts matching to TODO
14308 entries, otherwise it is not touched.
14310 See also `org-scan-tags'."
14311 (unless match
14312 ;; Get a new match request, with completion against the global
14313 ;; tags table and the local tags in current buffer.
14314 (let ((org-last-tags-completion-table
14315 (org-uniquify
14316 (delq nil (append (org-get-buffer-tags)
14317 (org-global-tags-completion-table))))))
14318 (setq match
14319 (completing-read
14320 "Match: "
14321 'org-tags-completion-function nil nil nil 'org-tags-history))))
14323 (let ((match0 match)
14324 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14325 (start 0)
14326 tagsmatch todomatch tagsmatcher todomatcher)
14328 ;; Expand group tags.
14329 (setq match (org-tags-expand match))
14331 ;; Check if there is a TODO part of this match, which would be the
14332 ;; part after a "/". To make sure that this slash is not part of
14333 ;; a property value to be matched against, we also check that
14334 ;; there is no / after that slash. First, find the last slash.
14335 (let ((s 0))
14336 (while (string-match "/+" match s)
14337 (setq start (match-beginning 0))
14338 (setq s (match-end 0))))
14339 (if (and (string-match "/+" match start)
14340 (not (string-match-p "\"" match start)))
14341 ;; Match contains also a TODO-matching request.
14342 (progn
14343 (setq tagsmatch (substring match 0 (match-beginning 0)))
14344 (setq todomatch (substring match (match-end 0)))
14345 (when (string-prefix-p "!" todomatch)
14346 (setq org--matcher-tags-todo-only t)
14347 (setq todomatch (substring todomatch 1)))
14348 (when (string-match "\\`\\s-*\\'" todomatch)
14349 (setq todomatch nil)))
14350 ;; Only matching tags.
14351 (setq tagsmatch match)
14352 (setq todomatch nil))
14354 ;; Make the tags matcher.
14355 (when (org-string-nw-p tagsmatch)
14356 (let ((orlist nil)
14357 (orterms (org-split-string tagsmatch "|"))
14358 term)
14359 (while (setq term (pop orterms))
14360 (while (and (equal (substring term -1) "\\") orterms)
14361 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14362 (while (string-match re term)
14363 (let* ((rest (substring term (match-end 0)))
14364 (minus (and (match-end 1)
14365 (equal (match-string 1 term) "-")))
14366 (tag (save-match-data
14367 (replace-regexp-in-string
14368 "\\\\-" "-" (match-string 2 term))))
14369 (regexp (eq (string-to-char tag) ?{))
14370 (levelp (match-end 4))
14371 (propp (match-end 5))
14373 (cond
14374 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14375 (levelp
14376 `(,(org-op-to-function (match-string 3 term))
14377 level
14378 ,(string-to-number (match-string 4 term))))
14379 (propp
14380 (let* ((gv (pcase (upcase (match-string 5 term))
14381 ("CATEGORY"
14382 '(get-text-property (point) 'org-category))
14383 ("TODO" 'todo)
14384 (p `(org-cached-entry-get nil ,p))))
14385 (pv (match-string 7 term))
14386 (regexp (eq (string-to-char pv) ?{))
14387 (strp (eq (string-to-char pv) ?\"))
14388 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14389 (po (org-op-to-function (match-string 6 term)
14390 (if timep 'time strp))))
14391 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14392 (when timep (setq pv (org-matcher-time pv)))
14393 (cond ((and regexp (eq po 'org<>))
14394 `(not (string-match ,pv (or ,gv ""))))
14395 (regexp `(string-match ,pv (or ,gv "")))
14396 (strp `(,po (or ,gv "") ,pv))
14398 `(,po
14399 (string-to-number (or ,gv ""))
14400 ,(string-to-number pv))))))
14401 (t `(member ,tag tags-list)))))
14402 (push (if minus `(not ,mm) mm) tagsmatcher)
14403 (setq term rest)))
14404 (push `(and ,@tagsmatcher) orlist)
14405 (setq tagsmatcher nil))
14406 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14408 ;; Make the TODO matcher.
14409 (when (org-string-nw-p todomatch)
14410 (let ((orlist nil))
14411 (dolist (term (org-split-string todomatch "|"))
14412 (while (string-match re term)
14413 (let* ((minus (and (match-end 1)
14414 (equal (match-string 1 term) "-")))
14415 (kwd (match-string 2 term))
14416 (regexp (eq (string-to-char kwd) ?{))
14417 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14418 `(equal todo ,kwd))))
14419 (push (if minus `(not ,mm) mm) todomatcher))
14420 (setq term (substring term (match-end 0))))
14421 (push (if (> (length todomatcher) 1)
14422 (cons 'and todomatcher)
14423 (car todomatcher))
14424 orlist)
14425 (setq todomatcher nil))
14426 (setq todomatcher (cons 'or orlist))))
14428 ;; Return the string and function of the matcher. If no
14429 ;; tags-specific or todo-specific matcher exists, match
14430 ;; everything.
14431 (let ((matcher (if (and tagsmatcher todomatcher)
14432 `(and ,tagsmatcher ,todomatcher)
14433 (or tagsmatcher todomatcher t))))
14434 (when org--matcher-tags-todo-only
14435 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14436 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14438 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14439 "Expand group tags in MATCH.
14441 This replaces every group tag in MATCH with a regexp tag search.
14442 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14443 will be replaced like this:
14445 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14446 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14447 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14449 Replacing by a regexp preserves the structure of the match.
14450 E.g., this expansion
14452 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14454 will match anything tagged with \"Lab\" and \"Home\", or tagged
14455 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14457 A group tag in MATCH can contain regular expressions of its own.
14458 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14459 will be replaced like this:
14461 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14463 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14464 assumed to be a single group tag, and the function will return
14465 the list of tags in this group.
14467 When DOWNCASE is non-nil, expand downcased TAGS."
14468 (if org-group-tags
14469 (let* ((case-fold-search t)
14470 (stable org-mode-syntax-table)
14471 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14472 (taggroups (if downcased
14473 (mapcar (lambda (tg) (mapcar #'downcase tg))
14474 taggroups)
14475 taggroups))
14476 (taggroups-keys (mapcar #'car taggroups))
14477 (return-match (if downcased (downcase match) match))
14478 (count 0)
14479 (work-already-expanded tags-already-expanded)
14480 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14481 ;; @ and _ are allowed as word-components in tags.
14482 (modify-syntax-entry ?@ "w" stable)
14483 (modify-syntax-entry ?_ "w" stable)
14484 ;; Temporarily replace regexp-expressions in the match-expression.
14485 (while (string-match "{.+?}" return-match)
14486 (cl-incf count)
14487 (push (match-string 0 return-match) regexps-in-match)
14488 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14489 (while (and taggroups-keys
14490 (with-syntax-table stable
14491 (string-match
14492 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14493 (regexp-opt taggroups-keys) "\\>\\)")
14494 return-match)))
14495 (let* ((dir (match-string 1 return-match))
14496 (tag (match-string 2 return-match))
14497 (tag (if downcased (downcase tag) tag)))
14498 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14499 (member tag work-already-expanded))
14500 (setq tags-in-group (assoc tag taggroups))
14501 (push tag work-already-expanded)
14502 ;; Recursively expand each tag in the group, if the tag hasn't
14503 ;; already been expanded. Restore the match-data after all recursive calls.
14504 (save-match-data
14505 (let (tags-expanded)
14506 (dolist (x (cdr tags-in-group))
14507 (if (and (member x taggroups-keys)
14508 (not (member x work-already-expanded)))
14509 (setq tags-expanded
14510 (delete-dups
14511 (append
14512 (org-tags-expand x t downcased
14513 work-already-expanded)
14514 tags-expanded)))
14515 (setq tags-expanded
14516 (append (list x) tags-expanded)))
14517 (setq work-already-expanded
14518 (delete-dups
14519 (append tags-expanded
14520 work-already-expanded))))
14521 (setq tags-in-group
14522 (delete-dups (cons (car tags-in-group)
14523 tags-expanded)))))
14524 ;; Filter tag-regexps from tags.
14525 (setq regexp-in-group-escaped
14526 (delq nil (mapcar (lambda (x)
14527 (if (stringp x)
14528 (and (equal "{" (substring x 0 1))
14529 (equal "}" (substring x -1))
14532 tags-in-group))
14533 regexp-in-group
14534 (mapcar (lambda (x)
14535 (substring x 1 -1))
14536 regexp-in-group-escaped)
14537 tags-in-group
14538 (delq nil (mapcar (lambda (x)
14539 (if (stringp x)
14540 (and (not (equal "{" (substring x 0 1)))
14541 (not (equal "}" (substring x -1)))
14544 tags-in-group)))
14545 ;; If single-as-list, do no more in the while-loop.
14546 (if (not single-as-list)
14547 (progn
14548 (when regexp-in-group
14549 (setq regexp-in-group
14550 (concat "\\|"
14551 (mapconcat 'identity regexp-in-group
14552 "\\|"))))
14553 (setq tags-in-group
14554 (concat dir
14555 "{\\<"
14556 (regexp-opt tags-in-group)
14557 "\\>"
14558 regexp-in-group
14559 "}"))
14560 (when (stringp tags-in-group)
14561 (org-add-props tags-in-group '(grouptag t)))
14562 (setq return-match
14563 (replace-match tags-in-group t t return-match)))
14564 (setq tags-in-group
14565 (append regexp-in-group-escaped tags-in-group))))
14566 (setq taggroups-keys (delete tag taggroups-keys))))
14567 ;; Add the regular expressions back into the match-expression again.
14568 (while regexps-in-match
14569 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14570 (pop regexps-in-match)
14571 return-match t t))
14572 (cl-decf count))
14573 (if single-as-list
14574 (if tags-in-group tags-in-group (list return-match))
14575 return-match))
14576 (if single-as-list
14577 (list (if downcased (downcase match) match))
14578 match)))
14580 (defun org-op-to-function (op &optional stringp)
14581 "Turn an operator into the appropriate function."
14582 (setq op
14583 (cond
14584 ((equal op "<" ) '(< string< org-time<))
14585 ((equal op ">" ) '(> org-string> org-time>))
14586 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14587 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14588 ((member op '("=" "==")) '(= string= org-time=))
14589 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14590 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14592 (defun org<> (a b) (not (= a b)))
14593 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14594 (defun org-string>= (a b) (not (string< a b)))
14595 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14596 (defun org-string<> (a b) (not (string= a b)))
14597 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14598 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14599 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14600 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14601 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14602 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14603 (defun org-2ft (s)
14604 "Convert S to a floating point time.
14605 If S is already a number, just return it. If it is a string, parse
14606 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14607 (cond
14608 ((numberp s) s)
14609 ((stringp s)
14610 (condition-case nil
14611 (float-time (apply #'encode-time (org-parse-time-string s nil t)))
14612 (error 0.)))
14613 (t 0.)))
14615 (defun org-time-today ()
14616 "Time in seconds today at 0:00.
14617 Returns the float number of seconds since the beginning of the
14618 epoch to the beginning of today (00:00)."
14619 (float-time (apply 'encode-time
14620 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14622 (defun org-matcher-time (s)
14623 "Interpret a time comparison value."
14624 (save-match-data
14625 (cond
14626 ((string= s "<now>") (float-time))
14627 ((string= s "<today>") (org-time-today))
14628 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14629 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14630 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14631 (+ (org-time-today)
14632 (* (string-to-number (match-string 1 s))
14633 (cdr (assoc (match-string 2 s)
14634 '(("d" . 86400.0) ("w" . 604800.0)
14635 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14636 (t (org-2ft s)))))
14638 (defun org-match-any-p (re list)
14639 "Does re match any element of list?"
14640 (setq list (mapcar (lambda (x) (string-match re x)) list))
14641 (delq nil list))
14643 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14644 (defvar org-tags-overlay (make-overlay 1 1))
14645 (delete-overlay org-tags-overlay)
14647 (defun org-get-local-tags-at (&optional pos)
14648 "Get a list of tags defined in the current headline."
14649 (org-get-tags-at pos 'local))
14651 (defun org-get-local-tags ()
14652 "Get a list of tags defined in the current headline."
14653 (org-get-tags-at nil 'local))
14655 (defun org-get-tags-at (&optional pos local)
14656 "Get a list of all headline tags applicable at POS.
14657 POS defaults to point. If tags are inherited, the list contains
14658 the targets in the same sequence as the headlines appear, i.e.
14659 the tags of the current headline come last.
14660 When LOCAL is non-nil, only return tags from the current headline,
14661 ignore inherited ones."
14662 (interactive)
14663 (if (and org-trust-scanner-tags
14664 (or (not pos) (equal pos (point)))
14665 (not local))
14666 org-scanner-tags
14667 (let (tags ltags lastpos parent)
14668 (save-excursion
14669 (save-restriction
14670 (widen)
14671 (goto-char (or pos (point)))
14672 (save-match-data
14673 (catch 'done
14674 (condition-case nil
14675 (progn
14676 (org-back-to-heading t)
14677 (while (not (equal lastpos (point)))
14678 (setq lastpos (point))
14679 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14680 (setq ltags (org-split-string
14681 (match-string-no-properties 1) ":"))
14682 (when parent
14683 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14684 (setq tags (append
14685 (if parent
14686 (org-remove-uninherited-tags ltags)
14687 ltags)
14688 tags)))
14689 (or org-use-tag-inheritance (throw 'done t))
14690 (when local (throw 'done t))
14691 (or (org-up-heading-safe) (error nil))
14692 (setq parent t)))
14693 (error nil)))))
14694 (if local
14695 tags
14696 (reverse (delete-dups
14697 (reverse (append
14698 (org-remove-uninherited-tags
14699 org-file-tags)
14700 tags)))))))))
14702 (defun org-add-prop-inherited (s)
14703 (add-text-properties 0 (length s) '(inherited t) s)
14706 (defun org-toggle-tag (tag &optional onoff)
14707 "Toggle the tag TAG for the current line.
14708 If ONOFF is `on' or `off', don't toggle but set to this state."
14709 (save-excursion
14710 (org-back-to-heading t)
14711 (let ((current
14712 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14713 (line-end-position) t)
14714 (let ((tags (match-string 1)))
14715 ;; Clear current tags.
14716 (replace-match "")
14717 ;; Reverse the tags list so any new tag is appended to
14718 ;; the current list of tags.
14719 (nreverse (org-split-string tags ":")))))
14720 res)
14721 (pcase onoff
14722 (`off (setq current (delete tag current)))
14723 ((or `on (guard (not (member tag current))))
14724 (setq res t)
14725 (cl-pushnew tag current :test #'equal))
14726 (_ (setq current (delete tag current))))
14727 (end-of-line)
14728 (if current
14729 (progn
14730 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14731 (org-set-tags nil t))
14732 (delete-horizontal-space))
14733 (run-hooks 'org-after-tags-change-hook)
14734 res)))
14736 (defun org--align-tags-here (to-col)
14737 "Align tags on the current headline to TO-COL.
14738 Assume point is on a headline."
14739 (let ((pos (point)))
14740 (beginning-of-line)
14741 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14742 (>= pos (match-beginning 2)))
14743 ;; No tags or point within tags: do not align.
14744 (goto-char pos)
14745 (goto-char (match-beginning 1))
14746 (let ((shift (max (- (if (>= to-col 0) to-col
14747 (- (abs to-col) (string-width (match-string 2))))
14748 (current-column))
14749 1)))
14750 (replace-match (make-string shift ?\s) nil nil nil 1)
14751 ;; Preserve initial position, if possible. In any case, stop
14752 ;; before tags.
14753 (when (< pos (point)) (goto-char pos))))))
14755 (defun org-set-tags-command (&optional arg just-align)
14756 "Call the set-tags command for the current entry."
14757 (interactive "P")
14758 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14759 (org-set-tags arg just-align)
14760 (save-excursion
14761 (unless (and (org-region-active-p)
14762 org-loop-over-headlines-in-active-region)
14763 (org-back-to-heading t))
14764 (org-set-tags arg just-align))))
14766 (defun org-set-tags-to (data)
14767 "Set the tags of the current entry to DATA, replacing the current tags.
14768 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14769 If DATA is nil or the empty string, any tags will be removed."
14770 (interactive "sTags: ")
14771 (setq data
14772 (cond
14773 ((eq data nil) "")
14774 ((equal data "") "")
14775 ((stringp data)
14776 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14777 ":"))
14778 ((listp data)
14779 (concat ":" (mapconcat 'identity data ":") ":"))))
14780 (when data
14781 (save-excursion
14782 (org-back-to-heading t)
14783 (when (let ((case-fold-search nil))
14784 (looking-at org-complex-heading-regexp))
14785 (if (match-end 5)
14786 (progn
14787 (goto-char (match-beginning 5))
14788 (insert data)
14789 (delete-region (point) (point-at-eol))
14790 (org-set-tags nil 'align))
14791 (goto-char (point-at-eol))
14792 (insert " " data)
14793 (org-set-tags nil 'align)))
14794 (beginning-of-line 1)
14795 (when (looking-at ".*?\\([ \t]+\\)$")
14796 (delete-region (match-beginning 1) (match-end 1))))))
14798 (defun org-align-all-tags ()
14799 "Align the tags in all headings."
14800 (interactive)
14801 (save-excursion
14802 (or (ignore-errors (org-back-to-heading t))
14803 (outline-next-heading))
14804 (if (org-at-heading-p)
14805 (org-set-tags t)
14806 (message "No headings"))))
14808 (defvar org-indent-indentation-per-level)
14809 (defun org-set-tags (&optional arg just-align)
14810 "Set the tags for the current headline.
14811 With prefix ARG, realign all tags in headings in the current buffer.
14812 When JUST-ALIGN is non-nil, only align tags."
14813 (interactive "P")
14814 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14815 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14816 'region-start-level
14817 'region))
14818 org-loop-over-headlines-in-active-region)
14819 (org-map-entries
14820 ;; We don't use ARG and JUST-ALIGN here because these args
14821 ;; are not useful when looping over headlines.
14822 #'org-set-tags
14823 org-loop-over-headlines-in-active-region
14825 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14826 (let ((org-setting-tags t))
14827 (if arg
14828 (save-excursion
14829 (goto-char (point-min))
14830 (while (re-search-forward org-outline-regexp-bol nil t)
14831 (org-set-tags nil t)
14832 (end-of-line))
14833 (message "All tags realigned to column %d" org-tags-column))
14834 (let* ((current (org-get-tags-string))
14835 (tags
14836 (if just-align current
14837 ;; Get a new set of tags from the user.
14838 (save-excursion
14839 (let* ((seen)
14840 (table
14841 (setq
14842 org-last-tags-completion-table
14843 ;; Uniquify tags in alists, yet preserve
14844 ;; structure (i.e., keywords).
14845 (delq nil
14846 (mapcar
14847 (lambda (pair)
14848 (let ((head (car pair)))
14849 (cond ((symbolp head) pair)
14850 ((member head seen) nil)
14851 (t (push head seen)
14852 pair))))
14853 (append
14854 (or org-current-tag-alist
14855 (org-get-buffer-tags))
14856 (and
14857 org-complete-tags-always-offer-all-agenda-tags
14858 (org-global-tags-completion-table
14859 (org-agenda-files))))))))
14860 (current-tags (org-split-string current ":"))
14861 (inherited-tags
14862 (nreverse (nthcdr (length current-tags)
14863 (nreverse (org-get-tags-at))))))
14864 (replace-regexp-in-string
14865 "\\([-+&]+\\|,\\)"
14867 (if (or (eq t org-use-fast-tag-selection)
14868 (and org-use-fast-tag-selection
14869 (delq nil (mapcar #'cdr table))))
14870 (org-fast-tag-selection
14871 current-tags inherited-tags table
14872 (and org-fast-tag-selection-include-todo
14873 org-todo-key-alist))
14874 (let ((org-add-colon-after-tag-completion
14875 (< 1 (length table))))
14876 (org-trim
14877 (completing-read
14878 "Tags: "
14879 #'org-tags-completion-function
14880 nil nil current 'org-tags-history))))))))))
14882 (when org-tags-sort-function
14883 (setq tags
14884 (mapconcat
14885 #'identity
14886 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14887 org-tags-sort-function)
14888 ":")))
14890 (if (or (string= ":" tags)
14891 (string= "::" tags))
14892 (setq tags ""))
14893 (if (not (org-string-nw-p tags)) (setq tags "")
14894 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14895 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14897 ;; Insert new tags at the correct column.
14898 (unless (equal current tags)
14899 (save-excursion
14900 (beginning-of-line)
14901 (let ((case-fold-search nil))
14902 (looking-at org-complex-heading-regexp))
14903 ;; Remove current tags, if any.
14904 (when (match-end 5) (replace-match "" nil nil nil 5))
14905 ;; Insert new tags, if any. Otherwise, remove trailing
14906 ;; white spaces.
14907 (end-of-line)
14908 (if (not (equal tags ""))
14909 ;; When text is being inserted on an invisible
14910 ;; region boundary, it can be inadvertently sucked
14911 ;; into invisibility.
14912 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14913 (skip-chars-backward " \t")
14914 (delete-region (point) (line-end-position)))))
14915 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14916 ;; is on.
14917 (unless (equal tags "")
14918 (let* ((level (save-excursion
14919 (beginning-of-line)
14920 (skip-chars-forward "\\*")))
14921 (offset (if (bound-and-true-p org-indent-mode)
14922 (* (1- org-indent-indentation-per-level)
14923 (1- level))
14925 (tags-column
14926 (+ org-tags-column
14927 (if (> org-tags-column 0) (- offset) offset))))
14928 (org--align-tags-here tags-column))))
14929 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14931 (defun org-change-tag-in-region (beg end tag off)
14932 "Add or remove TAG for each entry in the region.
14933 This works in the agenda, and also in an Org buffer."
14934 (interactive
14935 (list (region-beginning) (region-end)
14936 (let ((org-last-tags-completion-table
14937 (if (derived-mode-p 'org-mode)
14938 (org-uniquify
14939 (delq nil (append (org-get-buffer-tags)
14940 (org-global-tags-completion-table))))
14941 (org-global-tags-completion-table))))
14942 (completing-read
14943 "Tag: " 'org-tags-completion-function nil nil nil
14944 'org-tags-history))
14945 (progn
14946 (message "[s]et or [r]emove? ")
14947 (equal (read-char-exclusive) ?r))))
14948 (when (fboundp 'deactivate-mark) (deactivate-mark))
14949 (let ((agendap (equal major-mode 'org-agenda-mode))
14950 l1 l2 m buf pos newhead (cnt 0))
14951 (goto-char end)
14952 (setq l2 (1- (org-current-line)))
14953 (goto-char beg)
14954 (setq l1 (org-current-line))
14955 (cl-loop for l from l1 to l2 do
14956 (org-goto-line l)
14957 (setq m (get-text-property (point) 'org-hd-marker))
14958 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14959 (and agendap m))
14960 (setq buf (if agendap (marker-buffer m) (current-buffer))
14961 pos (if agendap m (point)))
14962 (with-current-buffer buf
14963 (save-excursion
14964 (save-restriction
14965 (goto-char pos)
14966 (setq cnt (1+ cnt))
14967 (org-toggle-tag tag (if off 'off 'on))
14968 (setq newhead (org-get-heading)))))
14969 (and agendap (org-agenda-change-all-lines newhead m))))
14970 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14972 (defun org-tags-completion-function (string _predicate &optional flag)
14973 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14974 (confirm (lambda (x) (stringp (car x)))))
14975 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14976 (setq s1 (match-string 1 string)
14977 s2 (match-string 2 string))
14978 (setq s1 "" s2 string))
14979 (cond
14980 ((eq flag nil)
14981 ;; try completion
14982 (setq rtn (try-completion s2 ctable confirm))
14983 (when (stringp rtn)
14984 (setq rtn
14985 (concat s1 s2 (substring rtn (length s2))
14986 (if (and org-add-colon-after-tag-completion
14987 (assoc rtn ctable))
14988 ":" ""))))
14989 rtn)
14990 ((eq flag t)
14991 ;; all-completions
14992 (all-completions s2 ctable confirm))
14993 ((eq flag 'lambda)
14994 ;; exact match?
14995 (assoc s2 ctable)))))
14997 (defun org-fast-tag-insert (kwd tags face &optional end)
14998 "Insert KDW, and the TAGS, the latter with face FACE.
14999 Also insert END."
15000 (insert (format "%-12s" (concat kwd ":"))
15001 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15002 (or end "")))
15004 (defun org-fast-tag-show-exit (flag)
15005 (save-excursion
15006 (org-goto-line 3)
15007 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15008 (replace-match ""))
15009 (when flag
15010 (end-of-line 1)
15011 (org-move-to-column (- (window-width) 19) t)
15012 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15014 (defun org-set-current-tags-overlay (current prefix)
15015 "Add an overlay to CURRENT tag with PREFIX."
15016 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15017 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15018 (org-overlay-display org-tags-overlay (concat prefix s))))
15020 (defvar org-last-tag-selection-key nil)
15021 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15022 "Fast tag selection with single keys.
15023 CURRENT is the current list of tags in the headline, INHERITED is the
15024 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15025 possibly with grouping information. TODO-TABLE is a similar table with
15026 TODO keywords, should these have keys assigned to them.
15027 If the keys are nil, a-z are automatically assigned.
15028 Returns the new tags string, or nil to not change the current settings."
15029 (let* ((fulltable (append table todo-table))
15030 (maxlen (apply 'max (mapcar
15031 (lambda (x)
15032 (if (stringp (car x)) (string-width (car x)) 0))
15033 fulltable)))
15034 (buf (current-buffer))
15035 (expert (eq org-fast-tag-selection-single-key 'expert))
15036 (buffer-tags nil)
15037 (fwidth (+ maxlen 3 1 3))
15038 (ncol (/ (- (window-width) 4) fwidth))
15039 (i-face 'org-done)
15040 (c-face 'org-todo)
15041 tg cnt e c char c1 c2 ntable tbl rtn
15042 ov-start ov-end ov-prefix
15043 (exit-after-next org-fast-tag-selection-single-key)
15044 (done-keywords org-done-keywords)
15045 groups ingroup intaggroup)
15046 (save-excursion
15047 (beginning-of-line 1)
15048 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15049 (setq ov-start (match-beginning 1)
15050 ov-end (match-end 1)
15051 ov-prefix "")
15052 (setq ov-start (1- (point-at-eol))
15053 ov-end (1+ ov-start))
15054 (skip-chars-forward "^\n\r")
15055 (setq ov-prefix
15056 (concat
15057 (buffer-substring (1- (point)) (point))
15058 (if (> (current-column) org-tags-column)
15060 (make-string (- org-tags-column (current-column)) ?\ ))))))
15061 (move-overlay org-tags-overlay ov-start ov-end)
15062 (save-window-excursion
15063 (if expert
15064 (set-buffer (get-buffer-create " *Org tags*"))
15065 (delete-other-windows)
15066 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15067 (org-switch-to-buffer-other-window " *Org tags*"))
15068 (erase-buffer)
15069 (setq-local org-done-keywords done-keywords)
15070 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15071 (org-fast-tag-insert "Current" current c-face "\n\n")
15072 (org-fast-tag-show-exit exit-after-next)
15073 (org-set-current-tags-overlay current ov-prefix)
15074 (setq tbl fulltable char ?a cnt 0)
15075 (while (setq e (pop tbl))
15076 (cond
15077 ((eq (car e) :startgroup)
15078 (push '() groups) (setq ingroup t)
15079 (unless (zerop cnt)
15080 (setq cnt 0)
15081 (insert "\n"))
15082 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15083 ((eq (car e) :endgroup)
15084 (setq ingroup nil cnt 0)
15085 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15086 ((eq (car e) :startgrouptag)
15087 (setq intaggroup t)
15088 (unless (zerop cnt)
15089 (setq cnt 0)
15090 (insert "\n"))
15091 (insert "[ "))
15092 ((eq (car e) :endgrouptag)
15093 (setq intaggroup nil cnt 0)
15094 (insert "]\n"))
15095 ((equal e '(:newline))
15096 (unless (zerop cnt)
15097 (setq cnt 0)
15098 (insert "\n")
15099 (setq e (car tbl))
15100 (while (equal (car tbl) '(:newline))
15101 (insert "\n")
15102 (setq tbl (cdr tbl)))))
15103 ((equal e '(:grouptags)) (insert " : "))
15105 (setq tg (copy-sequence (car e)) c2 nil)
15106 (if (cdr e)
15107 (setq c (cdr e))
15108 ;; automatically assign a character.
15109 (setq c1 (string-to-char
15110 (downcase (substring
15111 tg (if (= (string-to-char tg) ?@) 1 0)))))
15112 (if (or (rassoc c1 ntable) (rassoc c1 table))
15113 (while (or (rassoc char ntable) (rassoc char table))
15114 (setq char (1+ char)))
15115 (setq c2 c1))
15116 (setq c (or c2 char)))
15117 (when ingroup (push tg (car groups)))
15118 (setq tg (org-add-props tg nil 'face
15119 (cond
15120 ((not (assoc tg table))
15121 (org-get-todo-face tg))
15122 ((member tg current) c-face)
15123 ((member tg inherited) i-face))))
15124 (when (equal (caar tbl) :grouptags)
15125 (org-add-props tg nil 'face 'org-tag-group))
15126 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15127 (insert "[" c "] " tg (make-string
15128 (- fwidth 4 (length tg)) ?\ ))
15129 (push (cons tg c) ntable)
15130 (when (= (cl-incf cnt) ncol)
15131 (insert "\n")
15132 (when (or ingroup intaggroup) (insert " "))
15133 (setq cnt 0)))))
15134 (setq ntable (nreverse ntable))
15135 (insert "\n")
15136 (goto-char (point-min))
15137 (unless expert (org-fit-window-to-buffer))
15138 (setq rtn
15139 (catch 'exit
15140 (while t
15141 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
15142 (if (not groups) "no " "")
15143 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15144 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15145 (setq org-last-tag-selection-key c)
15146 (cond
15147 ((= c ?\r) (throw 'exit t))
15148 ((= c ?!)
15149 (setq groups (not groups))
15150 (goto-char (point-min))
15151 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15152 ((= c ?\C-c)
15153 (if (not expert)
15154 (org-fast-tag-show-exit
15155 (setq exit-after-next (not exit-after-next)))
15156 (setq expert nil)
15157 (delete-other-windows)
15158 (set-window-buffer (split-window-vertically) " *Org tags*")
15159 (org-switch-to-buffer-other-window " *Org tags*")
15160 (org-fit-window-to-buffer)))
15161 ((or (= c ?\C-g)
15162 (and (= c ?q) (not (rassoc c ntable))))
15163 (delete-overlay org-tags-overlay)
15164 (setq quit-flag t))
15165 ((= c ?\ )
15166 (setq current nil)
15167 (when exit-after-next (setq exit-after-next 'now)))
15168 ((= c ?\t)
15169 (condition-case nil
15170 (setq tg (completing-read
15171 "Tag: "
15172 (or buffer-tags
15173 (with-current-buffer buf
15174 (setq buffer-tags
15175 (org-get-buffer-tags))))))
15176 (quit (setq tg "")))
15177 (when (string-match "\\S-" tg)
15178 (cl-pushnew (list tg) buffer-tags :test #'equal)
15179 (if (member tg current)
15180 (setq current (delete tg current))
15181 (push tg current)))
15182 (when exit-after-next (setq exit-after-next 'now)))
15183 ((setq e (rassoc c todo-table) tg (car e))
15184 (with-current-buffer buf
15185 (save-excursion (org-todo tg)))
15186 (when exit-after-next (setq exit-after-next 'now)))
15187 ((setq e (rassoc c ntable) tg (car e))
15188 (if (member tg current)
15189 (setq current (delete tg current))
15190 (cl-loop for g in groups do
15191 (when (member tg g)
15192 (dolist (x g) (setq current (delete x current)))))
15193 (push tg current))
15194 (when exit-after-next (setq exit-after-next 'now))))
15196 ;; Create a sorted list
15197 (setq current
15198 (sort current
15199 (lambda (a b)
15200 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15201 (when (eq exit-after-next 'now) (throw 'exit t))
15202 (goto-char (point-min))
15203 (beginning-of-line 2)
15204 (delete-region (point) (point-at-eol))
15205 (org-fast-tag-insert "Current" current c-face)
15206 (org-set-current-tags-overlay current ov-prefix)
15207 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15208 (setq tg (match-string 1))
15209 (add-text-properties
15210 (match-beginning 1) (match-end 1)
15211 (list 'face
15212 (cond
15213 ((member tg current) c-face)
15214 ((member tg inherited) i-face)
15215 (t (get-text-property (match-beginning 1) 'face))))))
15216 (goto-char (point-min)))))
15217 (delete-overlay org-tags-overlay)
15218 (if rtn
15219 (mapconcat 'identity current ":")
15220 nil))))
15222 (defun org-get-tags-string ()
15223 "Get the TAGS string in the current headline."
15224 (unless (org-at-heading-p t)
15225 (user-error "Not on a heading"))
15226 (save-excursion
15227 (beginning-of-line 1)
15228 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15229 (match-string-no-properties 1)
15230 "")))
15232 (defun org-get-tags ()
15233 "Get the list of tags specified in the current headline."
15234 (org-split-string (org-get-tags-string) ":"))
15236 (defun org-get-buffer-tags ()
15237 "Get a table of all tags used in the buffer, for completion."
15238 (org-with-wide-buffer
15239 (goto-char (point-min))
15240 (let ((tag-re (concat org-outline-regexp-bol
15241 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15242 tags)
15243 (while (re-search-forward tag-re nil t)
15244 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15245 (push tag tags)))
15246 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15248 ;;;; The mapping API
15250 (defvar org-agenda-skip-comment-trees)
15251 (defvar org-agenda-skip-function)
15252 (defun org-map-entries (func &optional match scope &rest skip)
15253 "Call FUNC at each headline selected by MATCH in SCOPE.
15255 FUNC is a function or a lisp form. The function will be called without
15256 arguments, with the cursor positioned at the beginning of the headline.
15257 The return values of all calls to the function will be collected and
15258 returned as a list.
15260 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15261 does not need to preserve point. After evaluation, the cursor will be
15262 moved to the end of the line (presumably of the headline of the
15263 processed entry) and search continues from there. Under some
15264 circumstances, this may not produce the wanted results. For example,
15265 if you have removed (e.g. archived) the current (sub)tree it could
15266 mean that the next entry will be skipped entirely. In such cases, you
15267 can specify the position from where search should continue by making
15268 FUNC set the variable `org-map-continue-from' to the desired buffer
15269 position.
15271 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15272 Only headlines that are matched by this query will be considered during
15273 the iteration. When MATCH is nil or t, all headlines will be
15274 visited by the iteration.
15276 SCOPE determines the scope of this command. It can be any of:
15278 nil The current buffer, respecting the restriction if any
15279 tree The subtree started with the entry at point
15280 region The entries within the active region, if any
15281 region-start-level
15282 The entries within the active region, but only those at
15283 the same level than the first one.
15284 file The current buffer, without restriction
15285 file-with-archives
15286 The current buffer, and any archives associated with it
15287 agenda All agenda files
15288 agenda-with-archives
15289 All agenda files with any archive files associated with them
15290 \(file1 file2 ...)
15291 If this is a list, all files in the list will be scanned
15293 The remaining args are treated as settings for the skipping facilities of
15294 the scanner. The following items can be given here:
15296 archive skip trees with the archive tag
15297 comment skip trees with the COMMENT keyword
15298 function or Emacs Lisp form:
15299 will be used as value for `org-agenda-skip-function', so
15300 whenever the function returns a position, FUNC will not be
15301 called for that entry and search will continue from the
15302 position returned
15304 If your function needs to retrieve the tags including inherited tags
15305 at the *current* entry, you can use the value of the variable
15306 `org-scanner-tags' which will be much faster than getting the value
15307 with `org-get-tags-at'. If your function gets properties with
15308 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15309 to t around the call to `org-entry-properties' to get the same speedup.
15310 Note that if your function moves around to retrieve tags and properties at
15311 a *different* entry, you cannot use these techniques."
15312 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15313 (not (org-region-active-p)))
15314 (let* ((org-agenda-archives-mode nil) ; just to make sure
15315 (org-agenda-skip-archived-trees (memq 'archive skip))
15316 (org-agenda-skip-comment-trees (memq 'comment skip))
15317 (org-agenda-skip-function
15318 (car (org-delete-all '(comment archive) skip)))
15319 (org-tags-match-list-sublevels t)
15320 (start-level (eq scope 'region-start-level))
15321 matcher res
15322 org-todo-keywords-for-agenda
15323 org-done-keywords-for-agenda
15324 org-todo-keyword-alist-for-agenda
15325 org-tag-alist-for-agenda
15326 org--matcher-tags-todo-only)
15328 (cond
15329 ((eq match t) (setq matcher t))
15330 ((eq match nil) (setq matcher t))
15331 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15333 (save-excursion
15334 (save-restriction
15335 (cond ((eq scope 'tree)
15336 (org-back-to-heading t)
15337 (org-narrow-to-subtree)
15338 (setq scope nil))
15339 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15340 (org-region-active-p))
15341 ;; If needed, set start-level to a string like "2"
15342 (when start-level
15343 (save-excursion
15344 (goto-char (region-beginning))
15345 (unless (org-at-heading-p) (outline-next-heading))
15346 (setq start-level (org-current-level))))
15347 (narrow-to-region (region-beginning)
15348 (save-excursion
15349 (goto-char (region-end))
15350 (unless (and (bolp) (org-at-heading-p))
15351 (outline-next-heading))
15352 (point)))
15353 (setq scope nil)))
15355 (if (not scope)
15356 (progn
15357 (org-agenda-prepare-buffers
15358 (and buffer-file-name (list buffer-file-name)))
15359 (setq res
15360 (org-scan-tags
15361 func matcher org--matcher-tags-todo-only start-level)))
15362 ;; Get the right scope
15363 (cond
15364 ((and scope (listp scope) (symbolp (car scope)))
15365 (setq scope (eval scope)))
15366 ((eq scope 'agenda)
15367 (setq scope (org-agenda-files t)))
15368 ((eq scope 'agenda-with-archives)
15369 (setq scope (org-agenda-files t))
15370 (setq scope (org-add-archive-files scope)))
15371 ((eq scope 'file)
15372 (setq scope (and buffer-file-name (list buffer-file-name))))
15373 ((eq scope 'file-with-archives)
15374 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15375 (org-agenda-prepare-buffers scope)
15376 (dolist (file scope)
15377 (with-current-buffer (org-find-base-buffer-visiting file)
15378 (org-with-wide-buffer
15379 (goto-char (point-min))
15380 (setq res
15381 (append
15383 (org-scan-tags
15384 func matcher org--matcher-tags-todo-only)))))))))
15385 res)))
15387 ;;; Properties API
15389 (defconst org-special-properties
15390 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15391 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15392 "The special properties valid in Org mode.
15393 These are properties that are not defined in the property drawer,
15394 but in some other way.")
15396 (defconst org-default-properties
15397 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15398 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15399 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15400 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15401 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15402 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15403 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15404 "Some properties that are used by Org mode for various purposes.
15405 Being in this list makes sure that they are offered for completion.")
15407 (defun org--valid-property-p (property)
15408 "Non nil when string PROPERTY is a valid property name."
15409 (not
15410 (or (equal property "")
15411 (string-match-p "\\s-" property))))
15413 (defun org--update-property-plist (key val props)
15414 "Associate KEY to VAL in alist PROPS.
15415 Modifications are made by side-effect. Return new alist."
15416 (let* ((appending (string= (substring key -1) "+"))
15417 (key (if appending (substring key 0 -1) key))
15418 (old (assoc-string key props t)))
15419 (if (not old) (cons (cons key val) props)
15420 (setcdr old (if appending (concat (cdr old) " " val) val))
15421 props)))
15423 (defun org-get-property-block (&optional beg force)
15424 "Return the (beg . end) range of the body of the property drawer.
15425 BEG is the beginning of the current subtree, or of the part
15426 before the first headline. If it is not given, it will be found.
15427 If the drawer does not exist, create it if FORCE is non-nil, or
15428 return nil."
15429 (org-with-wide-buffer
15430 (when beg (goto-char beg))
15431 (unless (org-before-first-heading-p)
15432 (let ((beg (cond (beg)
15433 ((or (not (featurep 'org-inlinetask))
15434 (org-inlinetask-in-task-p))
15435 (org-back-to-heading t))
15436 (t (org-with-limited-levels (org-back-to-heading t))))))
15437 (forward-line)
15438 (when (looking-at-p org-planning-line-re) (forward-line))
15439 (cond ((looking-at org-property-drawer-re)
15440 (forward-line)
15441 (cons (point) (progn (goto-char (match-end 0))
15442 (line-beginning-position))))
15443 (force
15444 (goto-char beg)
15445 (org-insert-property-drawer)
15446 (let ((pos (save-excursion (search-forward ":END:")
15447 (line-beginning-position))))
15448 (cons pos pos))))))))
15450 (defun org-at-property-p ()
15451 "Non-nil when point is inside a property drawer.
15452 See `org-property-re' for match data, if applicable."
15453 (save-excursion
15454 (beginning-of-line)
15455 (and (looking-at org-property-re)
15456 (let ((property-drawer (save-match-data (org-get-property-block))))
15457 (and property-drawer
15458 (>= (point) (car property-drawer))
15459 (< (point) (cdr property-drawer)))))))
15461 (defun org-property-action ()
15462 "Do an action on properties."
15463 (interactive)
15464 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15465 (let ((c (read-char-exclusive)))
15466 (cl-case c
15467 (?s (call-interactively #'org-set-property))
15468 (?d (call-interactively #'org-delete-property))
15469 (?D (call-interactively #'org-delete-property-globally))
15470 (?c (call-interactively #'org-compute-property-at-point))
15471 (otherwise (user-error "No such property action %c" c)))))
15473 (defun org-inc-effort ()
15474 "Increment the value of the effort property in the current entry."
15475 (interactive)
15476 (org-set-effort nil t))
15478 (defvar org-clock-effort) ; Defined in org-clock.el.
15479 (defvar org-clock-current-task) ; Defined in org-clock.el.
15480 (defun org-set-effort (&optional value increment)
15481 "Set the effort property of the current entry.
15482 With numerical prefix arg, use the nth allowed value, 0 stands for the
15483 10th allowed value.
15485 When INCREMENT is non-nil, set the property to the next allowed value."
15486 (interactive "P")
15487 (when (equal value 0) (setq value 10))
15488 (let* ((completion-ignore-case t)
15489 (prop org-effort-property)
15490 (cur (org-entry-get nil prop))
15491 (allowed (org-property-get-allowed-values nil prop 'table))
15492 (existing (mapcar 'list (org-property-values prop)))
15493 (heading (nth 4 (org-heading-components)))
15495 (val (cond
15496 ((stringp value) value)
15497 ((and allowed (integerp value))
15498 (or (car (nth (1- value) allowed))
15499 (car (org-last allowed))))
15500 ((and allowed increment)
15501 (or (cl-caadr (member (list cur) allowed))
15502 (user-error "Allowed effort values are not set")))
15503 (allowed
15504 (message "Select 1-9,0, [RET%s]: %s"
15505 (if cur (concat "=" cur) "")
15506 (mapconcat 'car allowed " "))
15507 (setq rpl (read-char-exclusive))
15508 (if (equal rpl ?\r)
15510 (setq rpl (- rpl ?0))
15511 (when (equal rpl 0) (setq rpl 10))
15512 (if (and (> rpl 0) (<= rpl (length allowed)))
15513 (car (nth (1- rpl) allowed))
15514 (org-completing-read "Effort: " allowed nil))))
15516 (org-completing-read
15517 (concat "Effort" (and cur (string-match "\\S-" cur)
15518 (concat " [" cur "]"))
15519 ": ")
15520 existing nil nil "" nil cur)))))
15521 (unless (equal (org-entry-get nil prop) val)
15522 (org-entry-put nil prop val))
15523 (org-refresh-property
15524 '((effort . identity)
15525 (effort-minutes . org-duration-to-minutes))
15526 val)
15527 (when (equal heading (bound-and-true-p org-clock-current-task))
15528 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15529 (org-clock-update-mode-line))
15530 (message "%s is now %s" prop val)))
15532 (defun org-entry-properties (&optional pom which)
15533 "Get all properties of the current entry.
15535 When POM is a buffer position, get all properties from the entry
15536 there instead.
15538 This includes the TODO keyword, the tags, time strings for
15539 deadline, scheduled, and clocking, and any additional properties
15540 defined in the entry.
15542 If WHICH is nil or `all', get all properties. If WHICH is
15543 `special' or `standard', only get that subclass. If WHICH is
15544 a string, only get that property.
15546 Return value is an alist. Keys are properties, as upcased
15547 strings."
15548 (org-with-point-at pom
15549 (when (and (derived-mode-p 'org-mode)
15550 (ignore-errors (org-back-to-heading t)))
15551 (catch 'exit
15552 (let* ((beg (point))
15553 (specific (and (stringp which) (upcase which)))
15554 (which (cond ((not specific) which)
15555 ((member specific org-special-properties) 'special)
15556 (t 'standard)))
15557 props)
15558 ;; Get the special properties, like TODO and TAGS.
15559 (when (memq which '(nil all special))
15560 (when (or (not specific) (string= specific "CLOCKSUM"))
15561 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15562 (when clocksum
15563 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15564 props)))
15565 (when specific (throw 'exit props)))
15566 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15567 (let ((clocksumt (get-text-property (point)
15568 :org-clock-minutes-today)))
15569 (when clocksumt
15570 (push (cons "CLOCKSUM_T"
15571 (org-duration-from-minutes clocksumt))
15572 props)))
15573 (when specific (throw 'exit props)))
15574 (when (or (not specific) (string= specific "ITEM"))
15575 (let ((case-fold-search nil))
15576 (when (looking-at org-complex-heading-regexp)
15577 (push (cons "ITEM"
15578 (let ((title (match-string-no-properties 4)))
15579 (if (org-string-nw-p title)
15580 (org-remove-tabs title)
15581 "")))
15582 props)))
15583 (when specific (throw 'exit props)))
15584 (when (or (not specific) (string= specific "TODO"))
15585 (let ((case-fold-search nil))
15586 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15587 (push (cons "TODO" (match-string-no-properties 2)) props)))
15588 (when specific (throw 'exit props)))
15589 (when (or (not specific) (string= specific "PRIORITY"))
15590 (push (cons "PRIORITY"
15591 (if (looking-at org-priority-regexp)
15592 (match-string-no-properties 2)
15593 (char-to-string org-default-priority)))
15594 props)
15595 (when specific (throw 'exit props)))
15596 (when (or (not specific) (string= specific "FILE"))
15597 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15598 props)
15599 (when specific (throw 'exit props)))
15600 (when (or (not specific) (string= specific "TAGS"))
15601 (let ((value (org-string-nw-p (org-get-tags-string))))
15602 (when value (push (cons "TAGS" value) props)))
15603 (when specific (throw 'exit props)))
15604 (when (or (not specific) (string= specific "ALLTAGS"))
15605 (let ((value (org-get-tags-at)))
15606 (when value
15607 (push (cons "ALLTAGS"
15608 (format ":%s:" (mapconcat #'identity value ":")))
15609 props)))
15610 (when specific (throw 'exit props)))
15611 (when (or (not specific) (string= specific "BLOCKED"))
15612 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15613 (when specific (throw 'exit props)))
15614 (when (or (not specific)
15615 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15616 (forward-line)
15617 (when (looking-at-p org-planning-line-re)
15618 (end-of-line)
15619 (let ((bol (line-beginning-position))
15620 ;; Backward compatibility: time keywords used to
15621 ;; be configurable (before 8.3). Make sure we
15622 ;; get the correct keyword.
15623 (key-assoc `(("CLOSED" . ,org-closed-string)
15624 ("DEADLINE" . ,org-deadline-string)
15625 ("SCHEDULED" . ,org-scheduled-string))))
15626 (dolist (pair (if specific (list (assoc specific key-assoc))
15627 key-assoc))
15628 (save-excursion
15629 (when (search-backward (cdr pair) bol t)
15630 (goto-char (match-end 0))
15631 (skip-chars-forward " \t")
15632 (and (looking-at org-ts-regexp-both)
15633 (push (cons (car pair)
15634 (match-string-no-properties 0))
15635 props)))))))
15636 (when specific (throw 'exit props)))
15637 (when (or (not specific)
15638 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15639 (let ((find-ts
15640 (lambda (end ts)
15641 ;; Fix next time-stamp before END. TS is the
15642 ;; list of time-stamps found so far.
15643 (let ((ts ts)
15644 (regexp (cond
15645 ((string= specific "TIMESTAMP")
15646 org-ts-regexp)
15647 ((string= specific "TIMESTAMP_IA")
15648 org-ts-regexp-inactive)
15649 ((assoc "TIMESTAMP_IA" ts)
15650 org-ts-regexp)
15651 ((assoc "TIMESTAMP" ts)
15652 org-ts-regexp-inactive)
15653 (t org-ts-regexp-both))))
15654 (catch 'next
15655 (while (re-search-forward regexp end t)
15656 (backward-char)
15657 (let ((object (org-element-context)))
15658 ;; Accept to match timestamps in node
15659 ;; properties, too.
15660 (when (memq (org-element-type object)
15661 '(node-property timestamp))
15662 (let ((type
15663 (org-element-property :type object)))
15664 (cond
15665 ((and (memq type '(active active-range))
15666 (not (equal specific "TIMESTAMP_IA")))
15667 (unless (assoc "TIMESTAMP" ts)
15668 (push (cons "TIMESTAMP"
15669 (org-element-property
15670 :raw-value object))
15672 (when specific (throw 'exit ts))))
15673 ((and (memq type '(inactive inactive-range))
15674 (not (string= specific "TIMESTAMP")))
15675 (unless (assoc "TIMESTAMP_IA" ts)
15676 (push (cons "TIMESTAMP_IA"
15677 (org-element-property
15678 :raw-value object))
15680 (when specific (throw 'exit ts))))))
15681 ;; Both timestamp types are found,
15682 ;; move to next part.
15683 (when (= (length ts) 2) (throw 'next ts)))))
15684 ts)))))
15685 (goto-char beg)
15686 ;; First look for timestamps within headline.
15687 (let ((ts (funcall find-ts (line-end-position) nil)))
15688 (if (= (length ts) 2) (setq props (nconc ts props))
15689 ;; Then find timestamps in the section, skipping
15690 ;; planning line.
15691 (let ((end (save-excursion (outline-next-heading))))
15692 (forward-line)
15693 (when (looking-at-p org-planning-line-re) (forward-line))
15694 (setq props (nconc (funcall find-ts end ts) props))))))))
15695 ;; Get the standard properties, like :PROP:.
15696 (when (memq which '(nil all standard))
15697 ;; If we are looking after a specific property, delegate
15698 ;; to `org-entry-get', which is faster. However, make an
15699 ;; exception for "CATEGORY", since it can be also set
15700 ;; through keywords (i.e. #+CATEGORY).
15701 (if (and specific (not (equal specific "CATEGORY")))
15702 (let ((value (org-entry-get beg specific nil t)))
15703 (throw 'exit (and value (list (cons specific value)))))
15704 (let ((range (org-get-property-block beg)))
15705 (when range
15706 (let ((end (cdr range)) seen-base)
15707 (goto-char (car range))
15708 ;; Unlike to `org--update-property-plist', we
15709 ;; handle the case where base values is found
15710 ;; after its extension. We also forbid standard
15711 ;; properties to be named as special properties.
15712 (while (re-search-forward org-property-re end t)
15713 (let* ((key (upcase (match-string-no-properties 2)))
15714 (extendp (string-match-p "\\+\\'" key))
15715 (key-base (if extendp (substring key 0 -1) key))
15716 (value (match-string-no-properties 3)))
15717 (cond
15718 ((member-ignore-case key-base org-special-properties))
15719 (extendp
15720 (setq props
15721 (org--update-property-plist key value props)))
15722 ((member key seen-base))
15723 (t (push key seen-base)
15724 (let ((p (assoc-string key props t)))
15725 (if p (setcdr p (concat value " " (cdr p)))
15726 (push (cons key value) props))))))))))))
15727 (unless (assoc "CATEGORY" props)
15728 (push (cons "CATEGORY" (org-get-category beg)) props)
15729 (when (string= specific "CATEGORY") (throw 'exit props)))
15730 ;; Return value.
15731 props)))))
15733 (defun org--property-local-values (property literal-nil)
15734 "Return value for PROPERTY in current entry.
15735 Value is a list whose car is the base value for PROPERTY and cdr
15736 a list of accumulated values. Return nil if neither is found in
15737 the entry. Also return nil when PROPERTY is set to \"nil\",
15738 unless LITERAL-NIL is non-nil."
15739 (let ((range (org-get-property-block)))
15740 (when range
15741 (goto-char (car range))
15742 (let* ((case-fold-search t)
15743 (end (cdr range))
15744 (value
15745 ;; Base value.
15746 (save-excursion
15747 (let ((v (and (re-search-forward
15748 (org-re-property property nil t) end t)
15749 (match-string-no-properties 3))))
15750 (list (if literal-nil v (org-not-nil v)))))))
15751 ;; Find additional values.
15752 (let* ((property+ (org-re-property (concat property "+") nil t)))
15753 (while (re-search-forward property+ end t)
15754 (push (match-string-no-properties 3) value)))
15755 ;; Return final values.
15756 (and (not (equal value '(nil))) (nreverse value))))))
15758 (defun org--property-global-value (property literal-nil)
15759 "Return value for PROPERTY in current buffer.
15760 Return value is a string. Return nil if property is not set
15761 globally. Also return nil when PROPERTY is set to \"nil\",
15762 unless LITERAL-NIL is non-nil."
15763 (let ((global
15764 (cdr (or (assoc-string property org-file-properties t)
15765 (assoc-string property org-global-properties t)
15766 (assoc-string property org-global-properties-fixed t)))))
15767 (if literal-nil global (org-not-nil global))))
15769 (defun org-entry-get (pom property &optional inherit literal-nil)
15770 "Get value of PROPERTY for entry or content at point-or-marker POM.
15772 If INHERIT is non-nil and the entry does not have the property,
15773 then also check higher levels of the hierarchy. If INHERIT is
15774 the symbol `selective', use inheritance only if the setting in
15775 `org-use-property-inheritance' selects PROPERTY for inheritance.
15777 If the property is present but empty, the return value is the
15778 empty string. If the property is not present at all, nil is
15779 returned. In any other case, return the value as a string.
15780 Search is case-insensitive.
15782 If LITERAL-NIL is set, return the string value \"nil\" as
15783 a string, do not interpret it as the list atom nil. This is used
15784 for inheritance when a \"nil\" value can supersede a non-nil
15785 value higher up the hierarchy."
15786 (org-with-point-at pom
15787 (cond
15788 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15789 ;; We need a special property. Use `org-entry-properties' to
15790 ;; retrieve it, but specify the wanted property.
15791 (cdr (assoc-string property (org-entry-properties nil property))))
15792 ((and inherit
15793 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15794 (org-entry-get-with-inheritance property literal-nil))
15796 (let* ((local (org--property-local-values property literal-nil))
15797 (value (and local (mapconcat #'identity (delq nil local) " "))))
15798 (if literal-nil value (org-not-nil value)))))))
15800 (defun org-property-or-variable-value (var &optional inherit)
15801 "Check if there is a property fixing the value of VAR.
15802 If yes, return this value. If not, return the current value of the variable."
15803 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15804 (if (and prop (stringp prop) (string-match "\\S-" prop))
15805 (read prop)
15806 (symbol-value var))))
15808 (defun org-entry-delete (pom property)
15809 "Delete PROPERTY from entry at point-or-marker POM.
15810 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15811 non-nil when a property was removed."
15812 (org-with-point-at pom
15813 (pcase (org-get-property-block)
15814 (`(,begin . ,origin)
15815 (let* ((end (copy-marker origin))
15816 (re (org-re-property
15817 (concat (regexp-quote property) "\\+?") t t)))
15818 (goto-char begin)
15819 (while (re-search-forward re end t)
15820 (delete-region (match-beginning 0) (line-beginning-position 2)))
15821 ;; If drawer is empty, remove it altogether.
15822 (when (= begin end)
15823 (delete-region (line-beginning-position 0)
15824 (line-beginning-position 2)))
15825 ;; Return non-nil if some property was removed.
15826 (prog1 (/= end origin) (set-marker end nil))))
15827 (_ nil))))
15829 ;; Multi-values properties are properties that contain multiple values
15830 ;; These values are assumed to be single words, separated by whitespace.
15831 (defun org-entry-add-to-multivalued-property (pom property value)
15832 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15833 (let* ((old (org-entry-get pom property))
15834 (values (and old (split-string old))))
15835 (setq value (org-entry-protect-space value))
15836 (unless (member value values)
15837 (setq values (append values (list value)))
15838 (org-entry-put pom property (mapconcat #'identity values " ")))))
15840 (defun org-entry-remove-from-multivalued-property (pom property value)
15841 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15842 (let* ((old (org-entry-get pom property))
15843 (values (and old (split-string old))))
15844 (setq value (org-entry-protect-space value))
15845 (when (member value values)
15846 (setq values (delete value values))
15847 (org-entry-put pom property (mapconcat #'identity values " ")))))
15849 (defun org-entry-member-in-multivalued-property (pom property value)
15850 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15851 (let* ((old (org-entry-get pom property))
15852 (values (and old (split-string old))))
15853 (setq value (org-entry-protect-space value))
15854 (member value values)))
15856 (defun org-entry-get-multivalued-property (pom property)
15857 "Return a list of values in a multivalued property."
15858 (let* ((value (org-entry-get pom property))
15859 (values (and value (split-string value))))
15860 (mapcar #'org-entry-restore-space values)))
15862 (defun org-entry-put-multivalued-property (pom property &rest values)
15863 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15864 VALUES should be a list of strings. Spaces will be protected."
15865 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15866 (let* ((value (org-entry-get pom property))
15867 (values (and value (split-string value))))
15868 (mapcar #'org-entry-restore-space values)))
15870 (defun org-entry-protect-space (s)
15871 "Protect spaces and newline in string S."
15872 (while (string-match " " s)
15873 (setq s (replace-match "%20" t t s)))
15874 (while (string-match "\n" s)
15875 (setq s (replace-match "%0A" t t s)))
15878 (defun org-entry-restore-space (s)
15879 "Restore spaces and newline in string S."
15880 (while (string-match "%20" s)
15881 (setq s (replace-match " " t t s)))
15882 (while (string-match "%0A" s)
15883 (setq s (replace-match "\n" t t s)))
15886 (defvar org-entry-property-inherited-from (make-marker)
15887 "Marker pointing to the entry from where a property was inherited.
15888 Each call to `org-entry-get-with-inheritance' will set this marker to the
15889 location of the entry where the inheritance search matched. If there was
15890 no match, the marker will point nowhere.
15891 Note that also `org-entry-get' calls this function, if the INHERIT flag
15892 is set.")
15894 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15895 "Get PROPERTY of entry or content at point, search higher levels if needed.
15896 The search will stop at the first ancestor which has the property defined.
15897 If the value found is \"nil\", return nil to show that the property
15898 should be considered as undefined (this is the meaning of nil here).
15899 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15900 (move-marker org-entry-property-inherited-from nil)
15901 (org-with-wide-buffer
15902 (let (value)
15903 (catch 'exit
15904 (while t
15905 (let ((v (org--property-local-values property literal-nil)))
15906 (when v
15907 (setq value
15908 (concat (mapconcat #'identity (delq nil v) " ")
15909 (and value " ")
15910 value)))
15911 (cond
15912 ((car v)
15913 (org-back-to-heading t)
15914 (move-marker org-entry-property-inherited-from (point))
15915 (throw 'exit nil))
15916 ((org-up-heading-safe))
15918 (let ((global (org--property-global-value property literal-nil)))
15919 (cond ((not global))
15920 (value (setq value (concat global " " value)))
15921 (t (setq value global))))
15922 (throw 'exit nil))))))
15923 (if literal-nil value (org-not-nil value)))))
15925 (defvar org-property-changed-functions nil
15926 "Hook called when the value of a property has changed.
15927 Each hook function should accept two arguments, the name of the property
15928 and the new value.")
15930 (defun org-entry-put (pom property value)
15931 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15933 If the value is nil, it is converted to the empty string. If it
15934 is not a string, an error is raised. Also raise an error on
15935 invalid property names.
15937 PROPERTY can be any regular property (see
15938 `org-special-properties'). It can also be \"TODO\",
15939 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15941 For the last two properties, VALUE may have any of the special
15942 values \"earlier\" and \"later\". The function then increases or
15943 decreases scheduled or deadline date by one day."
15944 (cond ((null value) (setq value ""))
15945 ((not (stringp value)) (error "Properties values should be strings"))
15946 ((not (org--valid-property-p property))
15947 (user-error "Invalid property name: \"%s\"" property)))
15948 (org-with-point-at pom
15949 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15950 (org-back-to-heading t)
15951 (org-with-limited-levels (org-back-to-heading t)))
15952 (let ((beg (point)))
15953 (cond
15954 ((equal property "TODO")
15955 (cond ((not (org-string-nw-p value)) (setq value 'none))
15956 ((not (member value org-todo-keywords-1))
15957 (user-error "\"%s\" is not a valid TODO state" value)))
15958 (org-todo value)
15959 (org-set-tags nil 'align))
15960 ((equal property "PRIORITY")
15961 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15962 (org-set-tags nil 'align))
15963 ((equal property "SCHEDULED")
15964 (forward-line)
15965 (if (and (looking-at-p org-planning-line-re)
15966 (re-search-forward
15967 org-scheduled-time-regexp (line-end-position) t))
15968 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15969 ((string= value "later") (org-timestamp-change 1 'day))
15970 ((string= value "") (org-schedule '(4)))
15971 (t (org-schedule nil value)))
15972 (if (member value '("earlier" "later" ""))
15973 (call-interactively #'org-schedule)
15974 (org-schedule nil value))))
15975 ((equal property "DEADLINE")
15976 (forward-line)
15977 (if (and (looking-at-p org-planning-line-re)
15978 (re-search-forward
15979 org-deadline-time-regexp (line-end-position) t))
15980 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15981 ((string= value "later") (org-timestamp-change 1 'day))
15982 ((string= value "") (org-deadline '(4)))
15983 (t (org-deadline nil value)))
15984 (if (member value '("earlier" "later" ""))
15985 (call-interactively #'org-deadline)
15986 (org-deadline nil value))))
15987 ((member property org-special-properties)
15988 (error "The %s property cannot be set with `org-entry-put'" property))
15990 (let* ((range (org-get-property-block beg 'force))
15991 (end (cdr range))
15992 (case-fold-search t))
15993 (goto-char (car range))
15994 (if (re-search-forward (org-re-property property nil t) end t)
15995 (progn (delete-region (match-beginning 0) (match-end 0))
15996 (goto-char (match-beginning 0)))
15997 (goto-char end)
15998 (insert "\n")
15999 (backward-char))
16000 (insert ":" property ":")
16001 (when value (insert " " value))
16002 (org-indent-line)))))
16003 (run-hook-with-args 'org-property-changed-functions property value)))
16005 (defun org-buffer-property-keys (&optional specials defaults columns)
16006 "Get all property keys in the current buffer.
16008 When SPECIALS is non-nil, also list the special properties that
16009 reflect things like tags and TODO state.
16011 When DEFAULTS is non-nil, also include properties that has
16012 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16013 DESCRIPTION, LOCATION, and LOGGING and others.
16015 When COLUMNS in non-nil, also include property names given in
16016 COLUMN formats in the current buffer."
16017 (let ((case-fold-search t)
16018 (props (append
16019 (and specials org-special-properties)
16020 (and defaults (cons org-effort-property org-default-properties))
16021 nil)))
16022 (org-with-wide-buffer
16023 (goto-char (point-min))
16024 (while (re-search-forward org-property-start-re nil t)
16025 (catch :skip
16026 (let ((range (org-get-property-block)))
16027 (unless range (throw :skip nil))
16028 (goto-char (car range))
16029 (let ((begin (car range))
16030 (end (cdr range)))
16031 ;; Make sure that found property block is not located
16032 ;; before current point, as it would generate an infloop.
16033 ;; It can happen, for example, in the following
16034 ;; situation:
16036 ;; * Headline
16037 ;; :PROPERTIES:
16038 ;; ...
16039 ;; :END:
16040 ;; *************** Inlinetask
16041 ;; #+BEGIN_EXAMPLE
16042 ;; :PROPERTIES:
16043 ;; #+END_EXAMPLE
16045 (if (< begin (point)) (throw :skip nil) (goto-char begin))
16046 (while (< (point) end)
16047 (let ((p (progn (looking-at org-property-re)
16048 (match-string-no-properties 2))))
16049 ;; Only add true property name, not extension symbol.
16050 (push (if (not (string-match-p "\\+\\'" p)) p
16051 (substring p 0 -1))
16052 props))
16053 (forward-line))))
16054 (outline-next-heading)))
16055 (when columns
16056 (goto-char (point-min))
16057 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16058 (let ((element (org-element-at-point)))
16059 (when (memq (org-element-type element) '(keyword node-property))
16060 (let ((value (org-element-property :value element))
16061 (start 0))
16062 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16063 (setq start (match-end 0))
16064 (let ((p (match-string-no-properties 1 value)))
16065 (unless (member-ignore-case p org-special-properties)
16066 (push p props))))))))))
16067 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16069 (defun org-property-values (key)
16070 "List all non-nil values of property KEY in current buffer."
16071 (org-with-wide-buffer
16072 (goto-char (point-min))
16073 (let ((case-fold-search t)
16074 (re (org-re-property key))
16075 values)
16076 (while (re-search-forward re nil t)
16077 (push (org-entry-get (point) key) values))
16078 (delete-dups values))))
16080 (defun org-insert-property-drawer ()
16081 "Insert a property drawer into the current entry."
16082 (org-with-wide-buffer
16083 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16084 (org-back-to-heading t)
16085 (org-with-limited-levels (org-back-to-heading t)))
16086 (forward-line)
16087 (when (looking-at-p org-planning-line-re) (forward-line))
16088 (unless (looking-at-p org-property-drawer-re)
16089 ;; Make sure we start editing a line from current entry, not from
16090 ;; next one. It prevents extending text properties or overlays
16091 ;; belonging to the latter.
16092 (when (bolp) (backward-char))
16093 (let ((begin (1+ (point)))
16094 (inhibit-read-only t))
16095 (insert "\n:PROPERTIES:\n:END:")
16096 (when (eobp) (insert "\n"))
16097 (org-indent-region begin (point))))))
16099 (defun org-insert-drawer (&optional arg drawer)
16100 "Insert a drawer at point.
16102 When optional argument ARG is non-nil, insert a property drawer.
16104 Optional argument DRAWER, when non-nil, is a string representing
16105 drawer's name. Otherwise, the user is prompted for a name.
16107 If a region is active, insert the drawer around that region
16108 instead.
16110 Point is left between drawer's boundaries."
16111 (interactive "P")
16112 (let* ((drawer (if arg "PROPERTIES"
16113 (or drawer (read-from-minibuffer "Drawer: ")))))
16114 (cond
16115 ;; With C-u, fall back on `org-insert-property-drawer'
16116 (arg (org-insert-property-drawer))
16117 ;; Check validity of suggested drawer's name.
16118 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16119 (user-error "Invalid drawer name"))
16120 ;; With an active region, insert a drawer at point.
16121 ((not (org-region-active-p))
16122 (progn
16123 (unless (bolp) (insert "\n"))
16124 (insert (format ":%s:\n\n:END:\n" drawer))
16125 (forward-line -2)))
16126 ;; Otherwise, insert the drawer at point
16128 (let ((rbeg (region-beginning))
16129 (rend (copy-marker (region-end))))
16130 (unwind-protect
16131 (progn
16132 (goto-char rbeg)
16133 (beginning-of-line)
16134 (when (save-excursion
16135 (re-search-forward org-outline-regexp-bol rend t))
16136 (user-error "Drawers cannot contain headlines"))
16137 ;; Position point at the beginning of the first
16138 ;; non-blank line in region. Insert drawer's opening
16139 ;; there, then indent it.
16140 (org-skip-whitespace)
16141 (beginning-of-line)
16142 (insert ":" drawer ":\n")
16143 (forward-line -1)
16144 (indent-for-tab-command)
16145 ;; Move point to the beginning of the first blank line
16146 ;; after the last non-blank line in region. Insert
16147 ;; drawer's closing, then indent it.
16148 (goto-char rend)
16149 (skip-chars-backward " \r\t\n")
16150 (insert "\n:END:")
16151 (deactivate-mark t)
16152 (indent-for-tab-command)
16153 (unless (eolp) (insert "\n")))
16154 ;; Clear marker, whatever the outcome of insertion is.
16155 (set-marker rend nil)))))))
16157 (defvar org-property-set-functions-alist nil
16158 "Property set function alist.
16159 Each entry should have the following format:
16161 (PROPERTY . READ-FUNCTION)
16163 The read function will be called with the same argument as
16164 `org-completing-read'.")
16166 (defun org-set-property-function (property)
16167 "Get the function that should be used to set PROPERTY.
16168 This is computed according to `org-property-set-functions-alist'."
16169 (or (cdr (assoc property org-property-set-functions-alist))
16170 'org-completing-read))
16172 (defun org-read-property-value (property)
16173 "Read PROPERTY value from user."
16174 (let* ((completion-ignore-case t)
16175 (allowed (org-property-get-allowed-values nil property 'table))
16176 (cur (org-entry-get nil property))
16177 (prompt (concat property " value"
16178 (if (and cur (string-match "\\S-" cur))
16179 (concat " [" cur "]") "") ": "))
16180 (set-function (org-set-property-function property))
16181 (val (if allowed
16182 (funcall set-function prompt allowed nil
16183 (not (get-text-property 0 'org-unrestricted
16184 (caar allowed))))
16185 (funcall set-function prompt
16186 (mapcar 'list (org-property-values property))
16187 nil nil "" nil cur))))
16188 (org-trim val)))
16190 (defvar org-last-set-property nil)
16191 (defvar org-last-set-property-value nil)
16192 (defun org-read-property-name ()
16193 "Read a property name."
16194 (let ((completion-ignore-case t)
16195 (default-prop (or (and (org-at-property-p)
16196 (match-string-no-properties 2))
16197 org-last-set-property)))
16198 (org-completing-read
16199 (concat "Property"
16200 (if default-prop (concat " [" default-prop "]") "")
16201 ": ")
16202 (mapcar #'list (org-buffer-property-keys nil t t))
16203 nil nil nil nil default-prop)))
16205 (defun org-set-property-and-value (use-last)
16206 "Allow to set [PROPERTY]: [value] direction from prompt.
16207 When use-default, don't even ask, just use the last
16208 \"[PROPERTY]: [value]\" string from the history."
16209 (interactive "P")
16210 (let* ((completion-ignore-case t)
16211 (pv (or (and use-last org-last-set-property-value)
16212 (org-completing-read
16213 "Enter a \"[Property]: [value]\" pair: "
16214 nil nil nil nil nil
16215 org-last-set-property-value)))
16216 prop val)
16217 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16218 (setq prop (match-string 1 pv)
16219 val (match-string 2 pv))
16220 (org-set-property prop val))))
16222 (defun org-set-property (property value)
16223 "In the current entry, set PROPERTY to VALUE.
16225 When called interactively, this will prompt for a property name, offering
16226 completion on existing and default properties. And then it will prompt
16227 for a value, offering completion either on allowed values (via an inherited
16228 xxx_ALL property) or on existing values in other instances of this property
16229 in the current file.
16231 Throw an error when trying to set a property with an invalid name."
16232 (interactive (list nil nil))
16233 (let ((property (or property (org-read-property-name))))
16234 ;; `org-entry-put' also makes the following check, but this one
16235 ;; avoids polluting `org-last-set-property' and
16236 ;; `org-last-set-property-value' needlessly.
16237 (unless (org--valid-property-p property)
16238 (user-error "Invalid property name: \"%s\"" property))
16239 (let ((value (or value (org-read-property-value property)))
16240 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16241 (setq org-last-set-property property)
16242 (setq org-last-set-property-value (concat property ": " value))
16243 ;; Possibly postprocess the inserted value:
16244 (when fn (setq value (funcall fn value)))
16245 (unless (equal (org-entry-get nil property) value)
16246 (org-entry-put nil property value)))))
16248 (defun org-find-property (property &optional value)
16249 "Find first entry in buffer that sets PROPERTY.
16251 When optional argument VALUE is non-nil, only consider an entry
16252 if it contains PROPERTY set to this value. If PROPERTY should be
16253 explicitly set to nil, use string \"nil\" for VALUE.
16255 Return position where the entry begins, or nil if there is no
16256 such entry. If narrowing is in effect, only search the visible
16257 part of the buffer."
16258 (save-excursion
16259 (goto-char (point-min))
16260 (let ((case-fold-search t)
16261 (re (org-re-property property nil (not value) value)))
16262 (catch 'exit
16263 (while (re-search-forward re nil t)
16264 (when (if value (org-at-property-p)
16265 (org-entry-get (point) property nil t))
16266 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16268 (defun org-delete-property (property)
16269 "In the current entry, delete PROPERTY."
16270 (interactive
16271 (let* ((completion-ignore-case t)
16272 (cat (org-entry-get (point) "CATEGORY"))
16273 (props0 (org-entry-properties nil 'standard))
16274 (props (if cat props0
16275 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16276 (prop (if (< 1 (length props))
16277 (completing-read "Property: " props nil t)
16278 (caar props))))
16279 (list prop)))
16280 (if (not property)
16281 (message "No property to delete in this entry")
16282 (org-entry-delete nil property)
16283 (message "Property \"%s\" deleted" property)))
16285 (defun org-delete-property-globally (property)
16286 "Remove PROPERTY globally, from all entries.
16287 This function ignores narrowing, if any."
16288 (interactive
16289 (let* ((completion-ignore-case t)
16290 (prop (completing-read
16291 "Globally remove property: "
16292 (mapcar #'list (org-buffer-property-keys)))))
16293 (list prop)))
16294 (org-with-wide-buffer
16295 (goto-char (point-min))
16296 (let ((count 0)
16297 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16298 (while (re-search-forward re nil t)
16299 (when (org-entry-delete (point) property) (cl-incf count)))
16300 (message "Property \"%s\" removed from %d entries" property count))))
16302 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16304 (defun org-compute-property-at-point ()
16305 "Compute the property at point.
16306 This looks for an enclosing column format, extracts the operator and
16307 then applies it to the property in the column format's scope."
16308 (interactive)
16309 (unless (org-at-property-p)
16310 (user-error "Not at a property"))
16311 (let ((prop (match-string-no-properties 2)))
16312 (org-columns-get-format-and-top-level)
16313 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16314 (user-error "No operator defined for property %s" prop))
16315 (org-columns-compute prop)))
16317 (defvar org-property-allowed-value-functions nil
16318 "Hook for functions supplying allowed values for a specific property.
16319 The functions must take a single argument, the name of the property, and
16320 return a flat list of allowed values. If \":ETC\" is one of
16321 the values, this means that these values are intended as defaults for
16322 completion, but that other values should be allowed too.
16323 The functions must return nil if they are not responsible for this
16324 property.")
16326 (defun org-property-get-allowed-values (pom property &optional table)
16327 "Get allowed values for the property PROPERTY.
16328 When TABLE is non-nil, return an alist that can directly be used for
16329 completion."
16330 (let (vals)
16331 (cond
16332 ((equal property "TODO")
16333 (setq vals (org-with-point-at pom
16334 (append org-todo-keywords-1 '("")))))
16335 ((equal property "PRIORITY")
16336 (let ((n org-lowest-priority))
16337 (while (>= n org-highest-priority)
16338 (push (char-to-string n) vals)
16339 (setq n (1- n)))))
16340 ((equal property "CATEGORY"))
16341 ((member property org-special-properties))
16342 ((setq vals (run-hook-with-args-until-success
16343 'org-property-allowed-value-functions property)))
16345 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16346 (when (and vals (string-match "\\S-" vals))
16347 (setq vals (car (read-from-string (concat "(" vals ")"))))
16348 (setq vals (mapcar (lambda (x)
16349 (cond ((stringp x) x)
16350 ((numberp x) (number-to-string x))
16351 ((symbolp x) (symbol-name x))
16352 (t "???")))
16353 vals)))))
16354 (when (member ":ETC" vals)
16355 (setq vals (remove ":ETC" vals))
16356 (org-add-props (car vals) '(org-unrestricted t)))
16357 (if table (mapcar 'list vals) vals)))
16359 (defun org-property-previous-allowed-value (&optional _previous)
16360 "Switch to the next allowed value for this property."
16361 (interactive)
16362 (org-property-next-allowed-value t))
16364 (defun org-property-next-allowed-value (&optional previous)
16365 "Switch to the next allowed value for this property."
16366 (interactive)
16367 (unless (org-at-property-p)
16368 (user-error "Not at a property"))
16369 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16370 (key (match-string 2))
16371 (value (match-string 3))
16372 (allowed (or (org-property-get-allowed-values (point) key)
16373 (and (member value '("[ ]" "[-]" "[X]"))
16374 '("[ ]" "[X]"))))
16375 (heading (save-match-data (nth 4 (org-heading-components))))
16376 nval)
16377 (unless allowed
16378 (user-error "Allowed values for this property have not been defined"))
16379 (when previous (setq allowed (reverse allowed)))
16380 (when (member value allowed)
16381 (setq nval (car (cdr (member value allowed)))))
16382 (setq nval (or nval (car allowed)))
16383 (when (equal nval value)
16384 (user-error "Only one allowed value for this property"))
16385 (org-at-property-p)
16386 (replace-match (concat " :" key ": " nval) t t)
16387 (org-indent-line)
16388 (beginning-of-line 1)
16389 (skip-chars-forward " \t")
16390 (when (equal prop org-effort-property)
16391 (org-refresh-property
16392 '((effort . identity)
16393 (effort-minutes . org-duration-to-minutes))
16394 nval)
16395 (when (string= org-clock-current-task heading)
16396 (setq org-clock-effort nval)
16397 (org-clock-update-mode-line)))
16398 (run-hook-with-args 'org-property-changed-functions key nval)))
16400 (defun org-find-olp (path &optional this-buffer)
16401 "Return a marker pointing to the entry at outline path OLP.
16402 If anything goes wrong, throw an error.
16403 You can wrap this call to catch the error like this:
16405 (condition-case msg
16406 (org-mobile-locate-entry (match-string 4))
16407 (error (nth 1 msg)))
16409 The return value will then be either a string with the error message,
16410 or a marker if everything is OK.
16412 If THIS-BUFFER is set, the outline path does not contain a file,
16413 only headings."
16414 (let* ((file (if this-buffer buffer-file-name (pop path)))
16415 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16416 (level 1)
16417 (lmin 1)
16418 (lmax 1)
16419 end found flevel)
16420 (unless buffer (error "File not found :%s" file))
16421 (with-current-buffer buffer
16422 (unless (derived-mode-p 'org-mode)
16423 (error "Buffer %s needs to be in Org mode" buffer))
16424 (org-with-wide-buffer
16425 (goto-char (point-min))
16426 (dolist (heading path)
16427 (let ((re (format org-complex-heading-regexp-format
16428 (regexp-quote heading)))
16429 (cnt 0))
16430 (while (re-search-forward re end t)
16431 (setq level (- (match-end 1) (match-beginning 1)))
16432 (when (and (>= level lmin) (<= level lmax))
16433 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16434 (when (= cnt 0)
16435 (error "Heading not found on level %d: %s" lmax heading))
16436 (when (> cnt 1)
16437 (error "Heading not unique on level %d: %s" lmax heading))
16438 (goto-char found)
16439 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16440 (setq end (save-excursion (org-end-of-subtree t t)))))
16441 (when (org-at-heading-p)
16442 (point-marker))))))
16444 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16445 "Find node HEADING in BUFFER.
16446 Return a marker to the heading if it was found, or nil if not.
16447 If POS-ONLY is set, return just the position instead of a marker.
16449 The heading text must match exact, but it may have a TODO keyword,
16450 a priority cookie and tags in the standard locations."
16451 (with-current-buffer (or buffer (current-buffer))
16452 (org-with-wide-buffer
16453 (goto-char (point-min))
16454 (let (case-fold-search)
16455 (when (re-search-forward
16456 (format org-complex-heading-regexp-format
16457 (regexp-quote heading)) nil t)
16458 (if pos-only
16459 (match-beginning 0)
16460 (move-marker (make-marker) (match-beginning 0))))))))
16462 (defun org-find-exact-heading-in-directory (heading &optional dir)
16463 "Find Org node headline HEADING in all .org files in directory DIR.
16464 When the target headline is found, return a marker to this location."
16465 (let ((files (directory-files (or dir default-directory)
16466 t "\\`[^.#].*\\.org\\'"))
16467 visiting m buffer)
16468 (catch 'found
16469 (dolist (file files)
16470 (message "trying %s" file)
16471 (setq visiting (org-find-base-buffer-visiting file))
16472 (setq buffer (or visiting (find-file-noselect file)))
16473 (setq m (org-find-exact-headline-in-buffer
16474 heading buffer))
16475 (when (and (not m) (not visiting)) (kill-buffer buffer))
16476 (and m (throw 'found m))))))
16478 (defun org-find-entry-with-id (ident)
16479 "Locate the entry that contains the ID property with exact value IDENT.
16480 IDENT can be a string, a symbol or a number, this function will search for
16481 the string representation of it.
16482 Return the position where this entry starts, or nil if there is no such entry."
16483 (interactive "sID: ")
16484 (let ((id (cond
16485 ((stringp ident) ident)
16486 ((symbolp ident) (symbol-name ident))
16487 ((numberp ident) (number-to-string ident))
16488 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16489 (org-with-wide-buffer (org-find-property "ID" id))))
16491 ;;;; Timestamps
16493 (defvar org-last-changed-timestamp nil)
16494 (defvar org-last-inserted-timestamp nil
16495 "The last time stamp inserted with `org-insert-time-stamp'.")
16497 (defun org-time-stamp (arg &optional inactive)
16498 "Prompt for a date/time and insert a time stamp.
16500 If the user specifies a time like HH:MM or if this command is
16501 called with at least one prefix argument, the time stamp contains
16502 the date and the time. Otherwise, only the date is included.
16504 All parts of a date not specified by the user are filled in from
16505 the timestamp at point, if any, or the current date/time
16506 otherwise.
16508 If there is already a timestamp at the cursor, it is replaced.
16510 With two universal prefix arguments, insert an active timestamp
16511 with the current time without prompting the user.
16513 When called from lisp, the timestamp is inactive if INACTIVE is
16514 non-nil."
16515 (interactive "P")
16516 (let* ((ts (cond
16517 ((org-at-date-range-p t)
16518 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16519 ((org-at-timestamp-p 'lax) (match-string 0))))
16520 ;; Default time is either the timestamp at point or today.
16521 ;; When entering a range, only the range start is considered.
16522 (default-time (if (not ts) (current-time)
16523 (apply #'encode-time (org-parse-time-string ts))))
16524 (default-input (and ts (org-get-compact-tod ts)))
16525 (repeater (and ts
16526 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16527 (match-string 0 ts)))
16528 org-time-was-given
16529 org-end-time-was-given
16530 (time
16531 (and (if (equal arg '(16)) (current-time)
16532 ;; Preserve `this-command' and `last-command'.
16533 (let ((this-command this-command)
16534 (last-command last-command))
16535 (org-read-date
16536 arg 'totime nil nil default-time default-input
16537 inactive))))))
16538 (cond
16539 ((and ts
16540 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16541 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16542 (insert "--")
16543 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16545 ;; Make sure we're on a timestamp. When in the middle of a date
16546 ;; range, move arbitrarily to range end.
16547 (unless (org-at-timestamp-p 'lax)
16548 (skip-chars-forward "-")
16549 (org-at-timestamp-p 'lax))
16550 (replace-match "")
16551 (setq org-last-changed-timestamp
16552 (org-insert-time-stamp
16553 time (or org-time-was-given arg)
16554 inactive nil nil (list org-end-time-was-given)))
16555 (when repeater
16556 (backward-char)
16557 (insert " " repeater)
16558 (setq org-last-changed-timestamp
16559 (concat (substring org-last-inserted-timestamp 0 -1)
16560 " " repeater ">")))
16561 (message "Timestamp updated"))
16562 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16563 (t (org-insert-time-stamp
16564 time (or org-time-was-given arg) inactive nil nil
16565 (list org-end-time-was-given))))))
16567 ;; FIXME: can we use this for something else, like computing time differences?
16568 (defun org-get-compact-tod (s)
16569 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16570 (let* ((t1 (match-string 1 s))
16571 (h1 (string-to-number (match-string 2 s)))
16572 (m1 (string-to-number (match-string 3 s)))
16573 (t2 (and (match-end 4) (match-string 5 s)))
16574 (h2 (and t2 (string-to-number (match-string 6 s))))
16575 (m2 (and t2 (string-to-number (match-string 7 s))))
16576 dh dm)
16577 (if (not t2)
16579 (setq dh (- h2 h1) dm (- m2 m1))
16580 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16581 (concat t1 "+" (number-to-string dh)
16582 (and (/= 0 dm) (format ":%02d" dm)))))))
16584 (defun org-time-stamp-inactive (&optional arg)
16585 "Insert an inactive time stamp.
16586 An inactive time stamp is enclosed in square brackets instead of angle
16587 brackets. It is inactive in the sense that it does not trigger agenda entries,
16588 does not link to the calendar and cannot be changed with the S-cursor keys.
16589 So these are more for recording a certain time/date."
16590 (interactive "P")
16591 (org-time-stamp arg 'inactive))
16593 (defvar org-date-ovl (make-overlay 1 1))
16594 (overlay-put org-date-ovl 'face 'org-date-selected)
16595 (delete-overlay org-date-ovl)
16597 (defvar org-ans1) ; dynamically scoped parameter
16598 (defvar org-ans2) ; dynamically scoped parameter
16600 (defvar org-plain-time-of-day-regexp) ; defined below
16602 (defvar org-overriding-default-time nil) ; dynamically scoped
16603 (defvar org-read-date-overlay nil)
16604 (defvar org-dcst nil) ; dynamically scoped
16605 (defvar org-read-date-history nil)
16606 (defvar org-read-date-final-answer nil)
16607 (defvar org-read-date-analyze-futurep nil)
16608 (defvar org-read-date-analyze-forced-year nil)
16609 (defvar org-read-date-inactive)
16611 (defvar org-read-date-minibuffer-local-map
16612 (let* ((map (make-sparse-keymap)))
16613 (set-keymap-parent map minibuffer-local-map)
16614 (org-defkey map (kbd ".")
16615 (lambda () (interactive)
16616 ;; Are we at the beginning of the prompt?
16617 (if (looking-back "^[^:]+: "
16618 (let ((inhibit-field-text-motion t))
16619 (line-beginning-position)))
16620 (org-eval-in-calendar '(calendar-goto-today))
16621 (insert "."))))
16622 (org-defkey map (kbd "C-.")
16623 (lambda () (interactive)
16624 (org-eval-in-calendar '(calendar-goto-today))))
16625 (org-defkey map [(meta shift left)]
16626 (lambda () (interactive)
16627 (org-eval-in-calendar '(calendar-backward-month 1))))
16628 (org-defkey map [(meta shift right)]
16629 (lambda () (interactive)
16630 (org-eval-in-calendar '(calendar-forward-month 1))))
16631 (org-defkey map [(meta shift up)]
16632 (lambda () (interactive)
16633 (org-eval-in-calendar '(calendar-backward-year 1))))
16634 (org-defkey map [(meta shift down)]
16635 (lambda () (interactive)
16636 (org-eval-in-calendar '(calendar-forward-year 1))))
16637 (org-defkey map [?\e (shift left)]
16638 (lambda () (interactive)
16639 (org-eval-in-calendar '(calendar-backward-month 1))))
16640 (org-defkey map [?\e (shift right)]
16641 (lambda () (interactive)
16642 (org-eval-in-calendar '(calendar-forward-month 1))))
16643 (org-defkey map [?\e (shift up)]
16644 (lambda () (interactive)
16645 (org-eval-in-calendar '(calendar-backward-year 1))))
16646 (org-defkey map [?\e (shift down)]
16647 (lambda () (interactive)
16648 (org-eval-in-calendar '(calendar-forward-year 1))))
16649 (org-defkey map [(shift up)]
16650 (lambda () (interactive)
16651 (org-eval-in-calendar '(calendar-backward-week 1))))
16652 (org-defkey map [(shift down)]
16653 (lambda () (interactive)
16654 (org-eval-in-calendar '(calendar-forward-week 1))))
16655 (org-defkey map [(shift left)]
16656 (lambda () (interactive)
16657 (org-eval-in-calendar '(calendar-backward-day 1))))
16658 (org-defkey map [(shift right)]
16659 (lambda () (interactive)
16660 (org-eval-in-calendar '(calendar-forward-day 1))))
16661 (org-defkey map "!"
16662 (lambda () (interactive)
16663 (org-eval-in-calendar '(diary-view-entries))
16664 (message "")))
16665 (org-defkey map ">"
16666 (lambda () (interactive)
16667 (org-eval-in-calendar '(calendar-scroll-left 1))))
16668 (org-defkey map "<"
16669 (lambda () (interactive)
16670 (org-eval-in-calendar '(calendar-scroll-right 1))))
16671 (org-defkey map "\C-v"
16672 (lambda () (interactive)
16673 (org-eval-in-calendar
16674 '(calendar-scroll-left-three-months 1))))
16675 (org-defkey map "\M-v"
16676 (lambda () (interactive)
16677 (org-eval-in-calendar
16678 '(calendar-scroll-right-three-months 1))))
16679 map)
16680 "Keymap for minibuffer commands when using `org-read-date'.")
16682 (defvar org-def)
16683 (defvar org-defdecode)
16684 (defvar org-with-time)
16686 (defvar calendar-setup) ; Dynamically scoped.
16687 (defun org-read-date (&optional with-time to-time from-string prompt
16688 default-time default-input inactive)
16689 "Read a date, possibly a time, and make things smooth for the user.
16690 The prompt will suggest to enter an ISO date, but you can also enter anything
16691 which will at least partially be understood by `parse-time-string'.
16692 Unrecognized parts of the date will default to the current day, month, year,
16693 hour and minute. If this command is called to replace a timestamp at point,
16694 or to enter the second timestamp of a range, the default time is taken
16695 from the existing stamp. Furthermore, the command prefers the future,
16696 so if you are giving a date where the year is not given, and the day-month
16697 combination is already past in the current year, it will assume you
16698 mean next year. For details, see the manual. A few examples:
16700 3-2-5 --> 2003-02-05
16701 feb 15 --> currentyear-02-15
16702 2/15 --> currentyear-02-15
16703 sep 12 9 --> 2009-09-12
16704 12:45 --> today 12:45
16705 22 sept 0:34 --> currentyear-09-22 0:34
16706 12 --> currentyear-currentmonth-12
16707 Fri --> nearest Friday after today
16708 -Tue --> last Tuesday
16709 etc.
16711 Furthermore you can specify a relative date by giving, as the *first* thing
16712 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16713 change in days weeks, months, years.
16714 With a single plus or minus, the date is relative to today. With a double
16715 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16716 +4d --> four days from today
16717 +4 --> same as above
16718 +2w --> two weeks from today
16719 ++5 --> five days from default date
16721 The function understands only English month and weekday abbreviations.
16723 While prompting, a calendar is popped up - you can also select the
16724 date with the mouse (button 1). The calendar shows a period of three
16725 months. To scroll it to other months, use the keys `>' and `<'.
16726 If you don't like the calendar, turn it off with
16727 (setq org-read-date-popup-calendar nil)
16729 With optional argument TO-TIME, the date will immediately be converted
16730 to an internal time.
16731 With an optional argument WITH-TIME, the prompt will suggest to
16732 also insert a time. Note that when WITH-TIME is not set, you can
16733 still enter a time, and this function will inform the calling routine
16734 about this change. The calling routine may then choose to change the
16735 format used to insert the time stamp into the buffer to include the time.
16736 With optional argument FROM-STRING, read from this string instead from
16737 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16738 the time/date that is used for everything that is not specified by the
16739 user."
16740 (require 'parse-time)
16741 (let* ((org-with-time with-time)
16742 (org-time-stamp-rounding-minutes
16743 (if (equal org-with-time '(16))
16744 '(0 0)
16745 org-time-stamp-rounding-minutes))
16746 (org-dcst org-display-custom-times)
16747 (ct (org-current-time))
16748 (org-def (or org-overriding-default-time default-time ct))
16749 (org-defdecode (decode-time org-def))
16750 (cur-frame (selected-frame))
16751 (mouse-autoselect-window nil) ; Don't let the mouse jump
16752 (calendar-setup
16753 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16754 (calendar-move-hook nil)
16755 (calendar-view-diary-initially-flag nil)
16756 (calendar-view-holidays-initially-flag nil)
16757 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16758 ;; Rationalize `org-def' and `org-defdecode', if required.
16759 (when (< (nth 2 org-defdecode) org-extend-today-until)
16760 (setf (nth 2 org-defdecode) -1)
16761 (setf (nth 1 org-defdecode) 59)
16762 (setq org-def (apply #'encode-time org-defdecode))
16763 (setq org-defdecode (decode-time org-def)))
16764 (let* ((timestr (format-time-string
16765 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16766 org-def))
16767 (prompt (concat (if prompt (concat prompt " ") "")
16768 (format "Date+time [%s]: " timestr))))
16769 (cond
16770 (from-string (setq ans from-string))
16771 (org-read-date-popup-calendar
16772 (save-excursion
16773 (save-window-excursion
16774 (calendar)
16775 (when (eq calendar-setup 'calendar-only)
16776 (setq cal-frame
16777 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16778 (select-frame cal-frame))
16779 (org-eval-in-calendar '(setq cursor-type nil) t)
16780 (unwind-protect
16781 (progn
16782 (calendar-forward-day (- (time-to-days org-def)
16783 (calendar-absolute-from-gregorian
16784 (calendar-current-date))))
16785 (org-eval-in-calendar nil t)
16786 (let* ((old-map (current-local-map))
16787 (map (copy-keymap calendar-mode-map))
16788 (minibuffer-local-map
16789 (copy-keymap org-read-date-minibuffer-local-map)))
16790 (org-defkey map (kbd "RET") 'org-calendar-select)
16791 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16792 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16793 (unwind-protect
16794 (progn
16795 (use-local-map map)
16796 (setq org-read-date-inactive inactive)
16797 (add-hook 'post-command-hook 'org-read-date-display)
16798 (setq org-ans0
16799 (read-string prompt
16800 default-input
16801 'org-read-date-history
16802 nil))
16803 ;; org-ans0: from prompt
16804 ;; org-ans1: from mouse click
16805 ;; org-ans2: from calendar motion
16806 (setq ans
16807 (concat org-ans0 " " (or org-ans1 org-ans2))))
16808 (remove-hook 'post-command-hook 'org-read-date-display)
16809 (use-local-map old-map)
16810 (when org-read-date-overlay
16811 (delete-overlay org-read-date-overlay)
16812 (setq org-read-date-overlay nil)))))
16813 (bury-buffer "*Calendar*")
16814 (when cal-frame
16815 (delete-frame cal-frame)
16816 (select-frame-set-input-focus cur-frame))))))
16818 (t ; Naked prompt only
16819 (unwind-protect
16820 (setq ans (read-string prompt default-input
16821 'org-read-date-history timestr))
16822 (when org-read-date-overlay
16823 (delete-overlay org-read-date-overlay)
16824 (setq org-read-date-overlay nil))))))
16826 (setq final (org-read-date-analyze ans org-def org-defdecode))
16828 (when org-read-date-analyze-forced-year
16829 (message "Year was forced into %s"
16830 (if org-read-date-force-compatible-dates
16831 "compatible range (1970-2037)"
16832 "range representable on this machine"))
16833 (ding))
16835 ;; One round trip to get rid of 34th of August and stuff like that....
16836 (setq final (decode-time (apply 'encode-time final)))
16838 (setq org-read-date-final-answer ans)
16840 (if to-time
16841 (apply 'encode-time final)
16842 (if (and (boundp 'org-time-was-given) org-time-was-given)
16843 (format "%04d-%02d-%02d %02d:%02d"
16844 (nth 5 final) (nth 4 final) (nth 3 final)
16845 (nth 2 final) (nth 1 final))
16846 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16848 (defun org-read-date-display ()
16849 "Display the current date prompt interpretation in the minibuffer."
16850 (when org-read-date-display-live
16851 (when org-read-date-overlay
16852 (delete-overlay org-read-date-overlay))
16853 (when (minibufferp (current-buffer))
16854 (save-excursion
16855 (end-of-line 1)
16856 (while (not (equal (buffer-substring
16857 (max (point-min) (- (point) 4)) (point))
16858 " "))
16859 (insert " ")))
16860 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16861 " " (or org-ans1 org-ans2)))
16862 (org-end-time-was-given nil)
16863 (f (org-read-date-analyze ans org-def org-defdecode))
16864 (fmts (if org-dcst
16865 org-time-stamp-custom-formats
16866 org-time-stamp-formats))
16867 (fmt (if (or org-with-time
16868 (and (boundp 'org-time-was-given) org-time-was-given))
16869 (cdr fmts)
16870 (car fmts)))
16871 (txt (format-time-string fmt (apply 'encode-time f)))
16872 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16873 (txt (concat "=> " txt)))
16874 (when (and org-end-time-was-given
16875 (string-match org-plain-time-of-day-regexp txt))
16876 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16877 org-end-time-was-given
16878 (substring txt (match-end 0)))))
16879 (when org-read-date-analyze-futurep
16880 (setq txt (concat txt " (=>F)")))
16881 (setq org-read-date-overlay
16882 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16883 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16885 (defun org-read-date-analyze (ans def defdecode)
16886 "Analyze the combined answer of the date prompt."
16887 ;; FIXME: cleanup and comment
16888 ;; Pass `current-time' result to `decode-time' (instead of calling
16889 ;; without arguments) so that only `current-time' has to be
16890 ;; overridden in tests.
16891 (let ((org-def def)
16892 (org-defdecode defdecode)
16893 (nowdecode (decode-time (current-time)))
16894 delta deltan deltaw deltadef year month day
16895 hour minute second wday pm h2 m2 tl wday1
16896 iso-year iso-weekday iso-week iso-date futurep kill-year)
16897 (setq org-read-date-analyze-futurep nil
16898 org-read-date-analyze-forced-year nil)
16899 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16900 (setq ans "+0"))
16902 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16903 (setq ans (replace-match "" t t ans)
16904 deltan (car delta)
16905 deltaw (nth 1 delta)
16906 deltadef (nth 2 delta)))
16908 ;; Check if there is an iso week date in there. If yes, store the
16909 ;; info and postpone interpreting it until the rest of the parsing
16910 ;; is done.
16911 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16912 (setq iso-year (when (match-end 1)
16913 (org-small-year-to-year
16914 (string-to-number (match-string 1 ans))))
16915 iso-weekday (when (match-end 3)
16916 (string-to-number (match-string 3 ans)))
16917 iso-week (string-to-number (match-string 2 ans)))
16918 (setq ans (replace-match "" t t ans)))
16920 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16921 (when (string-match
16922 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16923 (setq year (if (match-end 2)
16924 (string-to-number (match-string 2 ans))
16925 (progn (setq kill-year t)
16926 (string-to-number (format-time-string "%Y"))))
16927 month (string-to-number (match-string 3 ans))
16928 day (string-to-number (match-string 4 ans)))
16929 (setq year (org-small-year-to-year year))
16930 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16931 t nil ans)))
16933 ;; Help matching dotted european dates
16934 (when (string-match
16935 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16936 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16937 (setq kill-year t)
16938 (string-to-number (format-time-string "%Y")))
16939 day (string-to-number (match-string 1 ans))
16940 month (string-to-number (match-string 2 ans))
16941 ans (replace-match (format "%04d-%02d-%02d" year month day)
16942 t nil ans)))
16944 ;; Help matching american dates, like 5/30 or 5/30/7
16945 (when (string-match
16946 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16947 (setq year (if (match-end 4)
16948 (string-to-number (match-string 4 ans))
16949 (progn (setq kill-year t)
16950 (string-to-number (format-time-string "%Y"))))
16951 month (string-to-number (match-string 1 ans))
16952 day (string-to-number (match-string 2 ans)))
16953 (setq year (org-small-year-to-year year))
16954 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16955 t nil ans)))
16956 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16957 ;; If there is a time with am/pm, and *no* time without it, we convert
16958 ;; so that matching will be successful.
16959 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16960 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16961 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16962 (setq hour (string-to-number (match-string 1 ans))
16963 minute (if (match-end 3)
16964 (string-to-number (match-string 3 ans))
16966 pm (equal ?p
16967 (string-to-char (downcase (match-string 4 ans)))))
16968 (if (and (= hour 12) (not pm))
16969 (setq hour 0)
16970 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16971 (setq ans (replace-match (format "%02d:%02d" hour minute)
16972 t t ans))))
16974 ;; Check if a time range is given as a duration
16975 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16976 (setq hour (string-to-number (match-string 1 ans))
16977 h2 (+ hour (string-to-number (match-string 3 ans)))
16978 minute (string-to-number (match-string 2 ans))
16979 m2 (+ minute (if (match-end 5) (string-to-number
16980 (match-string 5 ans))0)))
16981 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16982 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16983 t t ans)))
16985 ;; Check if there is a time range
16986 (when (boundp 'org-end-time-was-given)
16987 (setq org-time-was-given nil)
16988 (when (and (string-match org-plain-time-of-day-regexp ans)
16989 (match-end 8))
16990 (setq org-end-time-was-given (match-string 8 ans))
16991 (setq ans (concat (substring ans 0 (match-beginning 7))
16992 (substring ans (match-end 7))))))
16994 (setq tl (parse-time-string ans)
16995 day (or (nth 3 tl) (nth 3 org-defdecode))
16996 month
16997 (cond ((nth 4 tl))
16998 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16999 ;; Day was specified. Make sure DAY+MONTH
17000 ;; combination happens in the future.
17001 ((nth 3 tl)
17002 (setq futurep t)
17003 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17004 (nth 4 nowdecode)))
17005 (t (nth 4 org-defdecode)))
17006 year
17007 (cond ((and (not kill-year) (nth 5 tl)))
17008 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17009 ;; Month was guessed in the future and is at least
17010 ;; equal to NOWDECODE's. Fix year accordingly.
17011 (futurep
17012 (if (or (> month (nth 4 nowdecode))
17013 (>= day (nth 3 nowdecode)))
17014 (nth 5 nowdecode)
17015 (1+ (nth 5 nowdecode))))
17016 ;; Month was specified. Make sure MONTH+YEAR
17017 ;; combination happens in the future.
17018 ((nth 4 tl)
17019 (setq futurep t)
17020 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17021 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17022 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17023 (t (nth 5 nowdecode))))
17024 (t (nth 5 org-defdecode)))
17025 hour (or (nth 2 tl) (nth 2 org-defdecode))
17026 minute (or (nth 1 tl) (nth 1 org-defdecode))
17027 second (or (nth 0 tl) 0)
17028 wday (nth 6 tl))
17030 (when (and (eq org-read-date-prefer-future 'time)
17031 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17032 (equal day (nth 3 nowdecode))
17033 (equal month (nth 4 nowdecode))
17034 (equal year (nth 5 nowdecode))
17035 (nth 2 tl)
17036 (or (< (nth 2 tl) (nth 2 nowdecode))
17037 (and (= (nth 2 tl) (nth 2 nowdecode))
17038 (nth 1 tl)
17039 (< (nth 1 tl) (nth 1 nowdecode)))))
17040 (setq day (1+ day)
17041 futurep t))
17043 ;; Special date definitions below
17044 (cond
17045 (iso-week
17046 ;; There was an iso week
17047 (require 'cal-iso)
17048 (setq futurep nil)
17049 (setq year (or iso-year year)
17050 day (or iso-weekday wday 1)
17051 wday nil ; to make sure that the trigger below does not match
17052 iso-date (calendar-gregorian-from-absolute
17053 (calendar-iso-to-absolute
17054 (list iso-week day year))))
17055 ; FIXME: Should we also push ISO weeks into the future?
17056 ; (when (and org-read-date-prefer-future
17057 ; (not iso-year)
17058 ; (< (calendar-absolute-from-gregorian iso-date)
17059 ; (time-to-days (current-time))))
17060 ; (setq year (1+ year)
17061 ; iso-date (calendar-gregorian-from-absolute
17062 ; (calendar-iso-to-absolute
17063 ; (list iso-week day year)))))
17064 (setq month (car iso-date)
17065 year (nth 2 iso-date)
17066 day (nth 1 iso-date)))
17067 (deltan
17068 (setq futurep nil)
17069 (unless deltadef
17070 ;; Pass `current-time' result to `decode-time' (instead of
17071 ;; calling without arguments) so that only `current-time' has
17072 ;; to be overridden in tests.
17073 (let ((now (decode-time (current-time))))
17074 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17075 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17076 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17077 ((equal deltaw "m") (setq month (+ month deltan)))
17078 ((equal deltaw "y") (setq year (+ year deltan)))))
17079 ((and wday (not (nth 3 tl)))
17080 ;; Weekday was given, but no day, so pick that day in the week
17081 ;; on or after the derived date.
17082 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17083 (unless (equal wday wday1)
17084 (setq day (+ day (% (- wday wday1 -7) 7))))))
17085 (when (and (boundp 'org-time-was-given)
17086 (nth 2 tl))
17087 (setq org-time-was-given t))
17088 (when (< year 100) (setq year (+ 2000 year)))
17089 ;; Check of the date is representable
17090 (if org-read-date-force-compatible-dates
17091 (progn
17092 (when (< year 1970)
17093 (setq year 1970 org-read-date-analyze-forced-year t))
17094 (when (> year 2037)
17095 (setq year 2037 org-read-date-analyze-forced-year t)))
17096 (condition-case nil
17097 (ignore (encode-time second minute hour day month year))
17098 (error
17099 (setq year (nth 5 org-defdecode))
17100 (setq org-read-date-analyze-forced-year t))))
17101 (setq org-read-date-analyze-futurep futurep)
17102 (list second minute hour day month year)))
17104 (defvar parse-time-weekdays)
17105 (defun org-read-date-get-relative (s today default)
17106 "Check string S for special relative date string.
17107 TODAY and DEFAULT are internal times, for today and for a default.
17108 Return shift list (N what def-flag)
17109 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17110 N is the number of WHATs to shift.
17111 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17112 the DEFAULT date rather than TODAY."
17113 (require 'parse-time)
17114 (when (and
17115 (string-match
17116 (concat
17117 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17118 "\\([0-9]+\\)?"
17119 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17120 "\\([ \t]\\|$\\)") s)
17121 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17122 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17123 (string-to-char (substring (match-string 1 s) -1))
17124 ?+))
17125 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17126 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17127 (what (if (match-end 3) (match-string 3 s) "d"))
17128 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17129 (date (if rel default today))
17130 (wday (nth 6 (decode-time date)))
17131 delta)
17132 (if wday1
17133 (progn
17134 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17135 (when (= delta 0) (setq delta 7))
17136 (when (= dir ?-)
17137 (setq delta (- delta 7))
17138 (when (= delta 0) (setq delta -7)))
17139 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17140 (list delta "d" rel))
17141 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17143 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17144 "Turn a user-specified date into the internal representation.
17145 The internal representation needed by the calendar is (month day year).
17146 This is a wrapper to handle the brain-dead convention in calendar that
17147 user function argument order change dependent on argument order."
17148 (pcase calendar-date-style
17149 (`american (list arg1 arg2 arg3))
17150 (`european (list arg2 arg1 arg3))
17151 (`iso (list arg2 arg3 arg1))))
17153 (defun org-eval-in-calendar (form &optional keepdate)
17154 "Eval FORM in the calendar window and return to current window.
17155 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17156 (let ((sf (selected-frame))
17157 (sw (selected-window)))
17158 (select-window (get-buffer-window "*Calendar*" t))
17159 (eval form)
17160 (when (and (not keepdate) (calendar-cursor-to-date))
17161 (let* ((date (calendar-cursor-to-date))
17162 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17163 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17164 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17165 (select-window sw)
17166 (select-frame-set-input-focus sf)))
17168 (defun org-calendar-select ()
17169 "Return to `org-read-date' with the date currently selected.
17170 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17171 (interactive)
17172 (when (calendar-cursor-to-date)
17173 (let* ((date (calendar-cursor-to-date))
17174 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17175 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17176 (when (active-minibuffer-window) (exit-minibuffer))))
17178 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17179 "Insert a date stamp for the date given by the internal TIME.
17180 See `format-time-string' for the format of TIME.
17181 WITH-HM means use the stamp format that includes the time of the day.
17182 INACTIVE means use square brackets instead of angular ones, so that the
17183 stamp will not contribute to the agenda.
17184 PRE and POST are optional strings to be inserted before and after the
17185 stamp.
17186 The command returns the inserted time stamp."
17187 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17188 stamp)
17189 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17190 (insert-before-markers (or pre ""))
17191 (when (listp extra)
17192 (setq extra (car extra))
17193 (if (and (stringp extra)
17194 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17195 (setq extra (format "-%02d:%02d"
17196 (string-to-number (match-string 1 extra))
17197 (string-to-number (match-string 2 extra))))
17198 (setq extra nil)))
17199 (when extra
17200 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17201 (insert-before-markers (setq stamp (format-time-string fmt time)))
17202 (insert-before-markers (or post ""))
17203 (setq org-last-inserted-timestamp stamp)))
17205 (defun org-toggle-time-stamp-overlays ()
17206 "Toggle the use of custom time stamp formats."
17207 (interactive)
17208 (setq org-display-custom-times (not org-display-custom-times))
17209 (unless org-display-custom-times
17210 (let ((p (point-min)) (bmp (buffer-modified-p)))
17211 (while (setq p (next-single-property-change p 'display))
17212 (when (and (get-text-property p 'display)
17213 (eq (get-text-property p 'face) 'org-date))
17214 (remove-text-properties
17215 p (setq p (next-single-property-change p 'display))
17216 '(display t))))
17217 (set-buffer-modified-p bmp)))
17218 (org-restart-font-lock)
17219 (setq org-table-may-need-update t)
17220 (if org-display-custom-times
17221 (message "Time stamps are overlaid with custom format")
17222 (message "Time stamp overlays removed")))
17224 (defun org-display-custom-time (beg end)
17225 "Overlay modified time stamp format over timestamp between BEG and END."
17226 (let* ((ts (buffer-substring beg end))
17227 t1 with-hm tf time str (off 0))
17228 (save-match-data
17229 (setq t1 (org-parse-time-string ts t))
17230 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17231 (setq off (- (match-end 0) (match-beginning 0)))))
17232 (setq end (- end off))
17233 (setq with-hm (and (nth 1 t1) (nth 2 t1))
17234 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17235 time (org-fix-decoded-time t1)
17236 str (org-add-props
17237 (format-time-string
17238 (substring tf 1 -1) (apply 'encode-time time))
17239 nil 'mouse-face 'highlight))
17240 (put-text-property beg end 'display str)))
17242 (defun org-fix-decoded-time (time)
17243 "Set 0 instead of nil for the first 6 elements of time.
17244 Don't touch the rest."
17245 (let ((n 0))
17246 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17248 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17249 "Difference between TIMESTAMP-STRING and now in days.
17250 If SECONDS is non-nil, return the difference in seconds."
17251 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17252 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17253 (funcall fdiff (current-time)))))
17255 (defun org-deadline-close-p (timestamp-string &optional ndays)
17256 "Is the time in TIMESTAMP-STRING close to the current date?"
17257 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17258 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17259 (not (org-entry-is-done-p))))
17261 (defun org-get-wdays (ts &optional delay zero-delay)
17262 "Get the deadline lead time appropriate for timestring TS.
17263 When DELAY is non-nil, get the delay time for scheduled items
17264 instead of the deadline lead time. When ZERO-DELAY is non-nil
17265 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17266 don't try to find the delay cookie in the scheduled timestamp."
17267 (let ((tv (if delay org-scheduled-delay-days
17268 org-deadline-warning-days)))
17269 (cond
17270 ((or (and delay (< tv 0))
17271 (and delay zero-delay (<= tv 0))
17272 (and (not delay) (<= tv 0)))
17273 ;; Enforce this value no matter what
17274 (- tv))
17275 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17276 ;; lead time is specified.
17277 (floor (* (string-to-number (match-string 1 ts))
17278 (cdr (assoc (match-string 2 ts)
17279 '(("d" . 1) ("w" . 7)
17280 ("m" . 30.4) ("y" . 365.25)
17281 ("h" . 0.041667)))))))
17282 ;; go for the default.
17283 (t tv))))
17285 (defun org-calendar-select-mouse (ev)
17286 "Return to `org-read-date' with the date currently selected.
17287 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17288 (interactive "e")
17289 (mouse-set-point ev)
17290 (when (calendar-cursor-to-date)
17291 (let* ((date (calendar-cursor-to-date))
17292 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17293 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17294 (when (active-minibuffer-window) (exit-minibuffer))))
17296 (defun org-check-deadlines (ndays)
17297 "Check if there are any deadlines due or past due.
17298 A deadline is considered due if it happens within `org-deadline-warning-days'
17299 days from today's date. If the deadline appears in an entry marked DONE,
17300 it is not shown. A numeric prefix argument NDAYS can be used to test that
17301 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17302 are shown."
17303 (interactive "P")
17304 (let* ((org-warn-days
17305 (cond
17306 ((equal ndays '(4)) 100000)
17307 (ndays (prefix-numeric-value ndays))
17308 (t (abs org-deadline-warning-days))))
17309 (case-fold-search nil)
17310 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17311 (callback
17312 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17313 (message "%d deadlines past-due or due within %d days"
17314 (org-occur regexp nil callback)
17315 org-warn-days)))
17317 (defsubst org-re-timestamp (type)
17318 "Return a regexp for timestamp TYPE.
17319 Allowed values for TYPE are:
17321 all: all timestamps
17322 active: only active timestamps (<...>)
17323 inactive: only inactive timestamps ([...])
17324 scheduled: only scheduled timestamps
17325 deadline: only deadline timestamps
17326 closed: only closed time-stamps
17328 When TYPE is nil, fall back on returning a regexp that matches
17329 both scheduled and deadline timestamps."
17330 (cl-case type
17331 (all org-ts-regexp-both)
17332 (active org-ts-regexp)
17333 (inactive org-ts-regexp-inactive)
17334 (scheduled org-scheduled-time-regexp)
17335 (deadline org-deadline-time-regexp)
17336 (closed org-closed-time-regexp)
17337 (otherwise
17338 (concat "\\<"
17339 (regexp-opt (list org-deadline-string org-scheduled-string))
17340 " *<\\([^>]+\\)>"))))
17342 (defun org-check-before-date (d)
17343 "Check if there are deadlines or scheduled entries before date D."
17344 (interactive (list (org-read-date)))
17345 (let* ((case-fold-search nil)
17346 (regexp (org-re-timestamp org-ts-type))
17347 (ts-type org-ts-type)
17348 (callback
17349 (lambda ()
17350 (let ((match (match-string 1)))
17351 (and (if (memq ts-type '(active inactive all))
17352 (eq (org-element-type (save-excursion
17353 (backward-char)
17354 (org-element-context)))
17355 'timestamp)
17356 (org-at-planning-p))
17357 (time-less-p
17358 (org-time-string-to-time match t)
17359 (org-time-string-to-time d t)))))))
17360 (message "%d entries before %s"
17361 (org-occur regexp nil callback)
17362 d)))
17364 (defun org-check-after-date (d)
17365 "Check if there are deadlines or scheduled entries after date D."
17366 (interactive (list (org-read-date)))
17367 (let* ((case-fold-search nil)
17368 (regexp (org-re-timestamp org-ts-type))
17369 (ts-type org-ts-type)
17370 (callback
17371 (lambda ()
17372 (let ((match (match-string 1)))
17373 (and (if (memq ts-type '(active inactive all))
17374 (eq (org-element-type (save-excursion
17375 (backward-char)
17376 (org-element-context)))
17377 'timestamp)
17378 (org-at-planning-p))
17379 (not (time-less-p
17380 (org-time-string-to-time match t)
17381 (org-time-string-to-time d t))))))))
17382 (message "%d entries after %s"
17383 (org-occur regexp nil callback)
17384 d)))
17386 (defun org-check-dates-range (start-date end-date)
17387 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17388 (interactive (list (org-read-date nil nil nil "Range starts")
17389 (org-read-date nil nil nil "Range end")))
17390 (let ((case-fold-search nil)
17391 (regexp (org-re-timestamp org-ts-type))
17392 (callback
17393 (let ((type org-ts-type))
17394 (lambda ()
17395 (let ((match (match-string 1)))
17396 (and
17397 (if (memq type '(active inactive all))
17398 (eq (org-element-type (save-excursion
17399 (backward-char)
17400 (org-element-context)))
17401 'timestamp)
17402 (org-at-planning-p))
17403 (not (time-less-p
17404 (org-time-string-to-time match t)
17405 (org-time-string-to-time start-date t)))
17406 (time-less-p
17407 (org-time-string-to-time match t)
17408 (org-time-string-to-time end-date t))))))))
17409 (message "%d entries between %s and %s"
17410 (org-occur regexp nil callback) start-date end-date)))
17412 (defun org-evaluate-time-range (&optional to-buffer)
17413 "Evaluate a time range by computing the difference between start and end.
17414 Normally the result is just printed in the echo area, but with prefix arg
17415 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17416 If the time range is actually in a table, the result is inserted into the
17417 next column.
17418 For time difference computation, a year is assumed to be exactly 365
17419 days in order to avoid rounding problems."
17420 (interactive "P")
17422 (org-clock-update-time-maybe)
17423 (save-excursion
17424 (unless (org-at-date-range-p t)
17425 (goto-char (point-at-bol))
17426 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17427 (unless (org-at-date-range-p t)
17428 (user-error "Not at a time-stamp range, and none found in current line")))
17429 (let* ((ts1 (match-string 1))
17430 (ts2 (match-string 2))
17431 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17432 (match-end (match-end 0))
17433 (time1 (org-time-string-to-time ts1))
17434 (time2 (org-time-string-to-time ts2))
17435 (t1 (float-time time1))
17436 (t2 (float-time time2))
17437 (diff (abs (- t2 t1)))
17438 (negative (< (- t2 t1) 0))
17439 ;; (ys (floor (* 365 24 60 60)))
17440 (ds (* 24 60 60))
17441 (hs (* 60 60))
17442 (fy "%dy %dd %02d:%02d")
17443 (fy1 "%dy %dd")
17444 (fd "%dd %02d:%02d")
17445 (fd1 "%dd")
17446 (fh "%02d:%02d")
17447 y d h m align)
17448 (if havetime
17449 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17451 d (floor (/ diff ds)) diff (mod diff ds)
17452 h (floor (/ diff hs)) diff (mod diff hs)
17453 m (floor (/ diff 60)))
17454 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17456 d (floor (+ (/ diff ds) 0.5))
17457 h 0 m 0))
17458 (if (not to-buffer)
17459 (message "%s" (org-make-tdiff-string y d h m))
17460 (if (org-at-table-p)
17461 (progn
17462 (goto-char match-end)
17463 (setq align t)
17464 (and (looking-at " *|") (goto-char (match-end 0))))
17465 (goto-char match-end))
17466 (when (looking-at
17467 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17468 (replace-match ""))
17469 (when negative (insert " -"))
17470 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17471 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17472 (insert " " (format fh h m))))
17473 (when align (org-table-align))
17474 (message "Time difference inserted")))))
17476 (defun org-make-tdiff-string (y d h m)
17477 (let ((fmt "")
17478 (l nil))
17479 (when (> y 0)
17480 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17481 (push y l))
17482 (when (> d 0)
17483 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17484 (push d l))
17485 (when (> h 0)
17486 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17487 (push h l))
17488 (when (> m 0)
17489 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17490 (push m l))
17491 (apply 'format fmt (nreverse l))))
17493 (defun org-time-string-to-time (s &optional zone)
17494 "Convert timestamp string S into internal time.
17495 The optional ZONE is omitted or nil for Emacs local time, t for
17496 Universal Time, ‘wall’ for system wall clock time, or a string as
17497 in the TZ environment variable."
17498 (apply #'encode-time (org-parse-time-string s nil zone)))
17500 (defun org-time-string-to-seconds (s &optional zone)
17501 "Convert a timestamp string S into a number of seconds.
17502 The optional ZONE is omitted or nil for Emacs local time, t for
17503 Universal Time, ‘wall’ for system wall clock time, or a string as
17504 in the TZ environment variable."
17505 (float-time (org-time-string-to-time s zone)))
17507 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17509 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17510 "Convert time stamp S to an absolute day number.
17512 If DAYNR in non-nil, and there is a specifier for a cyclic time
17513 stamp, get the closest date to DAYNR. If PREFER is
17514 `past' (respectively `future') return a date past (respectively
17515 after) or equal to DAYNR.
17517 POS is the location of time stamp S, as a buffer position in
17518 BUFFER.
17520 Diary sexp timestamps are matched against DAYNR, when non-nil.
17521 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17522 signaled."
17523 (cond
17524 ((string-match "\\`%%\\((.*)\\)" s)
17525 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17526 ;; only able to match individual dates. If it fails, raise an
17527 ;; error.
17528 (if (and daynr
17529 (org-diary-sexp-entry
17530 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17531 daynr
17532 (signal 'org-diary-sexp-no-match (list s))))
17533 (daynr (org-closest-date s daynr prefer))
17534 (t (time-to-days
17535 (condition-case errdata
17536 (apply #'encode-time (org-parse-time-string s))
17537 (error (error "Bad timestamp `%s'%s\nError was: %s"
17539 (if (not (and buffer pos)) ""
17540 (format-message " at %d in buffer `%s'" pos buffer))
17541 (cdr errdata))))))))
17543 (defun org-days-to-iso-week (days)
17544 "Return the iso week number."
17545 (require 'cal-iso)
17546 (car (calendar-iso-from-absolute days)))
17548 (defun org-small-year-to-year (year)
17549 "Convert 2-digit years into 4-digit years.
17550 YEAR is expanded into one of the 30 next years, if possible, or
17551 into a past one. Any year larger than 99 is returned unchanged."
17552 (if (>= year 100) year
17553 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17554 (century (/ current 100))
17555 (offset (- year (% current 100))))
17556 (cond ((> offset 30) (+ (* (1- century) 100) year))
17557 ((> offset -70) (+ (* century 100) year))
17558 (t (+ (* (1+ century) 100) year))))))
17560 (defun org-time-from-absolute (d)
17561 "Return the time corresponding to date D.
17562 D may be an absolute day number, or a calendar-type list (month day year)."
17563 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17564 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17566 (defvar org-agenda-current-date)
17567 (defun org-calendar-holiday ()
17568 "List of holidays, for Diary display in Org mode."
17569 (require 'holidays)
17570 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17571 (and hl (mapconcat #'identity hl "; "))))
17573 (defun org-diary-sexp-entry (sexp entry d)
17574 "Process a SEXP diary ENTRY for date D."
17575 (require 'diary-lib)
17576 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17577 ;; dynamically.
17578 (let* ((sexp `(let ((entry ,entry)
17579 (date ',d))
17580 ,(car (read-from-string sexp))))
17581 (result (if calendar-debug-sexp (eval sexp)
17582 (condition-case nil
17583 (eval sexp)
17584 (error
17585 (beep)
17586 (message "Bad sexp at line %d in %s: %s"
17587 (org-current-line)
17588 (buffer-file-name) sexp)
17589 (sleep-for 2))))))
17590 (cond ((stringp result) (split-string result "; "))
17591 ((and (consp result)
17592 (not (consp (cdr result)))
17593 (stringp (cdr result))) (cdr result))
17594 ((and (consp result)
17595 (stringp (car result))) result)
17596 (result entry))))
17598 (defun org-diary-to-ical-string (frombuf)
17599 "Get iCalendar entries from diary entries in buffer FROMBUF.
17600 This uses the icalendar.el library."
17601 (let* ((tmpdir temporary-file-directory)
17602 (tmpfile (make-temp-name
17603 (expand-file-name "orgics" tmpdir)))
17604 buf rtn b e)
17605 (with-current-buffer frombuf
17606 (icalendar-export-region (point-min) (point-max) tmpfile)
17607 (setq buf (find-buffer-visiting tmpfile))
17608 (set-buffer buf)
17609 (goto-char (point-min))
17610 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17611 (setq b (match-beginning 0)))
17612 (goto-char (point-max))
17613 (when (re-search-backward "^END:VEVENT" nil t)
17614 (setq e (match-end 0)))
17615 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17616 (kill-buffer buf)
17617 (delete-file tmpfile)
17618 rtn))
17620 (defun org-closest-date (start current prefer)
17621 "Return closest date to CURRENT starting from START.
17623 CURRENT and START are both time stamps.
17625 When PREFER is `past', return a date that is either CURRENT or
17626 past. When PREFER is `future', return a date that is either
17627 CURRENT or future.
17629 Only time stamps with a repeater are modified. Any other time
17630 stamp stay unchanged. In any case, return value is an absolute
17631 day number."
17632 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17633 ;; No repeater. Do not shift time stamp.
17634 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17635 (let ((value (string-to-number (match-string 1 start)))
17636 (type (match-string 2 start)))
17637 (if (= 0 value)
17638 ;; Repeater with a 0-value is considered as void.
17639 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17640 (let* ((base (org-date-to-gregorian start))
17641 (target (org-date-to-gregorian current))
17642 (sday (calendar-absolute-from-gregorian base))
17643 (cday (calendar-absolute-from-gregorian target))
17644 n1 n2)
17645 ;; If START is already past CURRENT, just return START.
17646 (if (<= cday sday) sday
17647 ;; Compute closest date before (N1) and closest date past
17648 ;; (N2) CURRENT.
17649 (pcase type
17650 ("h"
17651 (let ((missing-hours
17652 (mod (+ (- (* 24 (- cday sday))
17653 (nth 2 (org-parse-time-string start)))
17654 org-extend-today-until)
17655 value)))
17656 (setf n1 (if (= missing-hours 0) cday
17657 (- cday (1+ (/ missing-hours 24)))))
17658 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17659 ((or "d" "w")
17660 (let ((value (if (equal type "w") (* 7 value) value)))
17661 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17662 (setf n2 (+ n1 value))))
17663 ("m"
17664 (let* ((add-months
17665 (lambda (d n)
17666 ;; Add N months to gregorian date D, i.e.,
17667 ;; a list (MONTH DAY YEAR). Return a valid
17668 ;; gregorian date.
17669 (let ((m (+ (nth 0 d) n)))
17670 (list (mod m 12)
17671 (nth 1 d)
17672 (+ (/ m 12) (nth 2 d))))))
17673 (months ; Complete months to TARGET.
17674 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17675 (- (nth 0 target) (nth 0 base))
17676 ;; If START's day is greater than
17677 ;; TARGET's, remove incomplete month.
17678 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17679 value)
17680 value))
17681 (before (funcall add-months base months)))
17682 (setf n1 (calendar-absolute-from-gregorian before))
17683 (setf n2
17684 (calendar-absolute-from-gregorian
17685 (funcall add-months before value)))))
17687 (let* ((d (nth 1 base))
17688 (m (nth 0 base))
17689 (y (nth 2 base))
17690 (years ; Complete years to TARGET.
17691 (* (/ (- (nth 2 target)
17693 ;; If START's month and day are
17694 ;; greater than TARGET's, remove
17695 ;; incomplete year.
17696 (if (or (> (nth 0 target) m)
17697 (and (= (nth 0 target) m)
17698 (> (nth 1 target) d)))
17701 value)
17702 value))
17703 (before (list m d (+ y years))))
17704 (setf n1 (calendar-absolute-from-gregorian before))
17705 (setf n2 (calendar-absolute-from-gregorian
17706 (list m d (+ (nth 2 before) value)))))))
17707 ;; Handle PREFER parameter, if any.
17708 (cond
17709 ((eq prefer 'past) (if (= cday n2) n2 n1))
17710 ((eq prefer 'future) (if (= cday n1) n1 n2))
17711 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17713 (defun org-date-to-gregorian (d)
17714 "Turn any specification of date D into a Gregorian date for the calendar."
17715 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17716 ((and (listp d) (= (length d) 3)) d)
17717 ((stringp d)
17718 (let ((d (org-parse-time-string d)))
17719 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17720 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17722 (defun org-parse-time-string (s &optional nodefault zone)
17723 "Parse the standard Org time string.
17725 This should be a lot faster than the normal `parse-time-string'.
17727 If time is not given, defaults to 0:00. However, with optional
17728 NODEFAULT, hour and minute fields will be nil if not given.
17730 The optional ZONE is omitted or nil for Emacs local time, t for
17731 Universal Time, ‘wall’ for system wall clock time, or a string as
17732 in the TZ environment variable."
17733 (cond ((string-match org-ts-regexp0 s)
17734 (list 0
17735 (when (or (match-beginning 8) (not nodefault))
17736 (string-to-number (or (match-string 8 s) "0")))
17737 (when (or (match-beginning 7) (not nodefault))
17738 (string-to-number (or (match-string 7 s) "0")))
17739 (string-to-number (match-string 4 s))
17740 (string-to-number (match-string 3 s))
17741 (string-to-number (match-string 2 s))
17742 nil nil zone))
17743 ((string-match "^<[^>]+>$" s)
17744 ;; FIXME: `decode-time' needs to be called with ZONE as its
17745 ;; second argument. However, this requires at least Emacs
17746 ;; 25.1. We can do it when we switch to this version as our
17747 ;; minimal requirement.
17748 (decode-time (seconds-to-time (org-matcher-time s))))
17749 (t (error "Not a standard Org time string: %s" s))))
17751 (defun org-timestamp-up (&optional arg)
17752 "Increase the date item at the cursor by one.
17753 If the cursor is on the year, change the year. If it is on the month,
17754 the day or the time, change that.
17755 With prefix ARG, change by that many units."
17756 (interactive "p")
17757 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17759 (defun org-timestamp-down (&optional arg)
17760 "Decrease the date item at the cursor by one.
17761 If the cursor is on the year, change the year. If it is on the month,
17762 the day or the time, change that.
17763 With prefix ARG, change by that many units."
17764 (interactive "p")
17765 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17767 (defun org-timestamp-up-day (&optional arg)
17768 "Increase the date in the time stamp by one day.
17769 With prefix ARG, change that many days."
17770 (interactive "p")
17771 (if (and (not (org-at-timestamp-p 'lax))
17772 (org-at-heading-p))
17773 (org-todo 'up)
17774 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17776 (defun org-timestamp-down-day (&optional arg)
17777 "Decrease the date in the time stamp by one day.
17778 With prefix ARG, change that many days."
17779 (interactive "p")
17780 (if (and (not (org-at-timestamp-p 'lax))
17781 (org-at-heading-p))
17782 (org-todo 'down)
17783 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17785 (defun org-at-timestamp-p (&optional extended)
17786 "Non-nil if point is inside a timestamp.
17788 By default, the function only consider syntactically valid active
17789 timestamps. However, the caller may have a broader definition
17790 for timestamps. As a consequence, optional argument EXTENDED can
17791 be set to the following values
17793 `inactive'
17795 Include also syntactically valid inactive timestamps.
17797 `agenda'
17799 Include timestamps allowed in Agenda, i.e., those in
17800 properties drawers, planning lines and clock lines.
17802 `lax'
17804 Ignore context. The function matches any part of the
17805 document looking like a timestamp. This includes comments,
17806 example blocks...
17808 For backward-compatibility with Org 9.0, every other non-nil
17809 value is equivalent to `inactive'.
17811 When at a timestamp, return the position of the point as a symbol
17812 among `bracket', `after', `year', `month', `hour', `minute',
17813 `day' or a number of character from the last know part of the
17814 time stamp.
17816 When matching, the match groups are the following:
17817 group 1: year
17818 group 2: month
17819 group 3: day number
17820 group 4: day name
17821 group 5: hours, if any
17822 group 6: minutes, if any"
17823 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17824 (pos (point))
17825 (match?
17826 (let ((boundaries (org-in-regexp regexp)))
17827 (save-match-data
17828 (cond ((null boundaries) nil)
17829 ((eq extended 'lax) t)
17831 (or (and (eq extended 'agenda)
17832 (or (org-at-planning-p)
17833 (org-at-property-p)
17834 (and (bound-and-true-p
17835 org-agenda-include-inactive-timestamps)
17836 (org-at-clock-log-p))))
17837 (eq 'timestamp
17838 (save-excursion
17839 (when (= pos (cdr boundaries)) (forward-char -1))
17840 (org-element-type (org-element-context)))))))))))
17841 (cond
17842 ((not match?) nil)
17843 ((= pos (match-beginning 0)) 'bracket)
17844 ;; Distinguish location right before the closing bracket from
17845 ;; right after it.
17846 ((= pos (1- (match-end 0))) 'bracket)
17847 ((= pos (match-end 0)) 'after)
17848 ((org-pos-in-match-range pos 2) 'year)
17849 ((org-pos-in-match-range pos 3) 'month)
17850 ((org-pos-in-match-range pos 7) 'hour)
17851 ((org-pos-in-match-range pos 8) 'minute)
17852 ((or (org-pos-in-match-range pos 4)
17853 (org-pos-in-match-range pos 5)) 'day)
17854 ((and (> pos (or (match-end 8) (match-end 5)))
17855 (< pos (match-end 0)))
17856 (- pos (or (match-end 8) (match-end 5))))
17857 (t 'day))))
17859 (defun org-toggle-timestamp-type ()
17860 "Toggle the type (<active> or [inactive]) of a time stamp."
17861 (interactive)
17862 (when (org-at-timestamp-p 'lax)
17863 (let ((beg (match-beginning 0)) (end (match-end 0))
17864 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17865 (save-excursion
17866 (goto-char beg)
17867 (while (re-search-forward "[][<>]" end t)
17868 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17869 t t)))
17870 (message "Timestamp is now %sactive"
17871 (if (equal (char-after beg) ?<) "" "in")))))
17873 (defun org-at-clock-log-p ()
17874 "Non-nil if point is on a clock log line."
17875 (and (org-match-line org-clock-line-re)
17876 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17878 (defvar org-clock-history) ; defined in org-clock.el
17879 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17880 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17881 "Change the date in the time stamp at point.
17882 The date will be changed by N times WHAT. WHAT can be `day', `month',
17883 `year', `minute', `second'. If WHAT is not given, the cursor position
17884 in the timestamp determines what will be changed.
17885 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17886 (let ((origin (point))
17887 (timestamp? (org-at-timestamp-p 'lax))
17888 origin-cat
17889 with-hm inactive
17890 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17891 extra rem
17892 ts time time0 fixnext clrgx)
17893 (unless timestamp? (user-error "Not at a timestamp"))
17894 (if (and (not what) (eq timestamp? 'bracket))
17895 (org-toggle-timestamp-type)
17896 ;; Point isn't on brackets. Remember the part of the time-stamp
17897 ;; the point was in. Indeed, size of time-stamps may change,
17898 ;; but point must be kept in the same category nonetheless.
17899 (setq origin-cat timestamp?)
17900 (when (and (not what) (not (eq timestamp? 'day))
17901 org-display-custom-times
17902 (get-text-property (point) 'display)
17903 (not (get-text-property (1- (point)) 'display)))
17904 (setq timestamp? 'day))
17905 (setq timestamp? (or what timestamp?)
17906 inactive (= (char-after (match-beginning 0)) ?\[)
17907 ts (match-string 0))
17908 (replace-match "")
17909 (when (string-match
17910 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17912 (setq extra (match-string 1 ts))
17913 (when suppress-tmp-delay
17914 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17915 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17916 (setq with-hm t))
17917 (setq time0 (org-parse-time-string ts))
17918 (when (and updown
17919 (eq timestamp? 'minute)
17920 (not current-prefix-arg))
17921 ;; This looks like s-up and s-down. Change by one rounding step.
17922 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17923 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17924 (setcar (cdr time0) (+ (nth 1 time0)
17925 (if (> n 0) (- rem) (- dm rem))))))
17926 (setq time
17927 (apply #'encode-time
17928 (or (car time0) 0)
17929 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17930 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17931 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17932 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17933 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17934 (nthcdr 6 time0)))
17935 (when (and (memq timestamp? '(hour minute))
17936 extra
17937 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17938 (setq extra (org-modify-ts-extra
17939 extra
17940 (if (eq timestamp? 'hour) 2 5)
17941 n dm)))
17942 (when (integerp timestamp?)
17943 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17944 (when (eq what 'calendar)
17945 (let ((cal-date (org-get-date-from-calendar)))
17946 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17947 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17948 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17949 (setcar time0 (or (car time0) 0))
17950 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17951 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17952 (setq time (apply 'encode-time time0))))
17953 ;; Insert the new time-stamp, and ensure point stays in the same
17954 ;; category as before (i.e. not after the last position in that
17955 ;; category).
17956 (let ((pos (point)))
17957 ;; Stay before inserted string. `save-excursion' is of no use.
17958 (setq org-last-changed-timestamp
17959 (org-insert-time-stamp time with-hm inactive nil nil extra))
17960 (goto-char pos))
17961 (save-match-data
17962 (looking-at org-ts-regexp3)
17963 (goto-char
17964 (pcase origin-cat
17965 ;; `day' category ends before `hour' if any, or at the end
17966 ;; of the day name.
17967 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17968 (`hour (min (match-end 7) origin))
17969 (`minute (min (1- (match-end 8)) origin))
17970 ((pred integerp) (min (1- (match-end 0)) origin))
17971 ;; Point was right after the time-stamp. However, the
17972 ;; time-stamp length might have changed, so refer to
17973 ;; (match-end 0) instead.
17974 (`after (match-end 0))
17975 ;; `year' and `month' have both fixed size: point couldn't
17976 ;; have moved into another part.
17977 (_ origin))))
17978 ;; Update clock if on a CLOCK line.
17979 (org-clock-update-time-maybe)
17980 ;; Maybe adjust the closest clock in `org-clock-history'
17981 (when org-clock-adjust-closest
17982 (if (not (and (org-at-clock-log-p)
17983 (< 1 (length (delq nil (mapcar 'marker-position
17984 org-clock-history))))))
17985 (message "No clock to adjust")
17986 (cond ((save-excursion ; fix previous clock?
17987 (re-search-backward org-ts-regexp0 nil t)
17988 (looking-back (concat org-clock-string " \\[")
17989 (line-beginning-position)))
17990 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17991 ((save-excursion ; fix next clock?
17992 (re-search-backward org-ts-regexp0 nil t)
17993 (looking-at (concat org-ts-regexp0 "\\] =>")))
17994 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17995 (save-window-excursion
17996 ;; Find closest clock to point, adjust the previous/next one in history
17997 (let* ((p (save-excursion (org-back-to-heading t)))
17998 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17999 (clfixnth
18000 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18001 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18002 (if (not clfixpos)
18003 (message "No clock to adjust")
18004 (save-excursion
18005 (org-goto-marker-or-bmk clfixpos)
18006 (org-show-subtree)
18007 (when (re-search-forward clrgx nil t)
18008 (goto-char (match-beginning 1))
18009 (let (org-clock-adjust-closest)
18010 (org-timestamp-change n timestamp? updown))
18011 (message "Clock adjusted in %s for heading: %s"
18012 (file-name-nondirectory (buffer-file-name))
18013 (org-get-heading t t)))))))))
18014 ;; Try to recenter the calendar window, if any.
18015 (when (and org-calendar-follow-timestamp-change
18016 (get-buffer-window "*Calendar*" t)
18017 (memq timestamp? '(day month year)))
18018 (org-recenter-calendar (time-to-days time))))))
18020 (defun org-modify-ts-extra (s pos n dm)
18021 "Change the different parts of the lead-time and repeat fields in timestamp."
18022 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18023 ng h m new rem)
18024 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18025 (cond
18026 ((or (org-pos-in-match-range pos 2)
18027 (org-pos-in-match-range pos 3))
18028 (setq m (string-to-number (match-string 3 s))
18029 h (string-to-number (match-string 2 s)))
18030 (if (org-pos-in-match-range pos 2)
18031 (setq h (+ h n))
18032 (setq n (* dm (with-no-warnings (signum n))))
18033 (unless (= 0 (setq rem (% m dm)))
18034 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18035 (setq m (+ m n)))
18036 (when (< m 0) (setq m (+ m 60) h (1- h)))
18037 (when (> m 59) (setq m (- m 60) h (1+ h)))
18038 (setq h (mod h 24))
18039 (setq ng 1 new (format "-%02d:%02d" h m)))
18040 ((org-pos-in-match-range pos 6)
18041 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18042 ((org-pos-in-match-range pos 5)
18043 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18045 ((org-pos-in-match-range pos 9)
18046 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18047 ((org-pos-in-match-range pos 8)
18048 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18050 (when ng
18051 (setq s (concat
18052 (substring s 0 (match-beginning ng))
18054 (substring s (match-end ng))))))
18057 (defun org-recenter-calendar (d)
18058 "If the calendar is visible, recenter it to date D."
18059 (let ((cwin (get-buffer-window "*Calendar*" t)))
18060 (when cwin
18061 (let ((calendar-move-hook nil))
18062 (with-selected-window cwin
18063 (calendar-goto-date
18064 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18066 (defun org-goto-calendar (&optional arg)
18067 "Go to the Emacs calendar at the current date.
18068 If there is a time stamp in the current line, go to that date.
18069 A prefix ARG can be used to force the current date."
18070 (interactive "P")
18071 (let ((calendar-move-hook nil)
18072 (calendar-view-holidays-initially-flag nil)
18073 (calendar-view-diary-initially-flag nil)
18074 diff)
18075 (when (or (org-at-timestamp-p 'lax)
18076 (org-match-line (concat ".*" org-ts-regexp)))
18077 (let ((d1 (time-to-days (current-time)))
18078 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
18079 (setq diff (- d2 d1))))
18080 (calendar)
18081 (calendar-goto-today)
18082 (when (and diff (not arg)) (calendar-forward-day diff))))
18084 (defun org-get-date-from-calendar ()
18085 "Return a list (month day year) of date at point in calendar."
18086 (with-current-buffer "*Calendar*"
18087 (save-match-data
18088 (calendar-cursor-to-date))))
18090 (defun org-date-from-calendar ()
18091 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18092 If there is already a time stamp at the cursor position, update it."
18093 (interactive)
18094 (if (org-at-timestamp-p 'lax)
18095 (org-timestamp-change 0 'calendar)
18096 (let ((cal-date (org-get-date-from-calendar)))
18097 (org-insert-time-stamp
18098 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18100 (defcustom org-effort-durations
18101 `(("min" . 1)
18102 ("h" . 60)
18103 ("d" . ,(* 60 8))
18104 ("w" . ,(* 60 8 5))
18105 ("m" . ,(* 60 8 5 4))
18106 ("y" . ,(* 60 8 5 40)))
18107 "Conversion factor to minutes for an effort modifier.
18109 Each entry has the form (MODIFIER . MINUTES).
18111 In an effort string, a number followed by MODIFIER is multiplied
18112 by the specified number of MINUTES to obtain an effort in
18113 minutes.
18115 For example, if the value of this variable is ((\"hours\" . 60)), then an
18116 effort string \"2hours\" is equivalent to 120 minutes."
18117 :group 'org-agenda
18118 :version "26.1"
18119 :package-version '(Org . "8.3")
18120 :type '(alist :key-type (string :tag "Modifier")
18121 :value-type (number :tag "Minutes")))
18123 (defcustom org-image-actual-width t
18124 "Should we use the actual width of images when inlining them?
18126 When set to t, always use the image width.
18128 When set to a number, use imagemagick (when available) to set
18129 the image's width to this value.
18131 When set to a number in a list, try to get the width from any
18132 #+ATTR.* keyword if it matches a width specification like
18134 #+ATTR_HTML: :width 300px
18136 and fall back on that number if none is found.
18138 When set to nil, try to get the width from an #+ATTR.* keyword
18139 and fall back on the original width if none is found.
18141 This requires Emacs >= 24.1, build with imagemagick support."
18142 :group 'org-appearance
18143 :version "24.4"
18144 :package-version '(Org . "8.0")
18145 :type '(choice
18146 (const :tag "Use the image width" t)
18147 (integer :tag "Use a number of pixels")
18148 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18149 (const :tag "Use #+ATTR* or don't resize" nil)))
18151 (defcustom org-agenda-inhibit-startup nil
18152 "Inhibit startup when preparing agenda buffers.
18153 When this variable is t, the initialization of the Org agenda
18154 buffers is inhibited: e.g. the visibility state is not set, the
18155 tables are not re-aligned, etc."
18156 :type 'boolean
18157 :version "24.3"
18158 :group 'org-agenda)
18160 (defcustom org-agenda-ignore-properties nil
18161 "Avoid updating text properties when building the agenda.
18162 Properties are used to prepare buffers for effort estimates,
18163 appointments, statistics and subtree-local categories.
18164 If you don't use these in the agenda, you can add them to this
18165 list and agenda building will be a bit faster.
18166 The value is a list, with zero or more of the symbols `effort', `appt',
18167 `stats' or `category'."
18168 :type '(set :greedy t
18169 (const effort)
18170 (const appt)
18171 (const stats)
18172 (const category))
18173 :version "26.1"
18174 :package-version '(Org . "8.3")
18175 :group 'org-agenda)
18177 ;;;; Files
18179 (defun org-save-all-org-buffers ()
18180 "Save all Org buffers without user confirmation."
18181 (interactive)
18182 (message "Saving all Org buffers...")
18183 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18184 (when (featurep 'org-id) (org-id-locations-save))
18185 (message "Saving all Org buffers... done"))
18187 (defun org-revert-all-org-buffers ()
18188 "Revert all Org buffers.
18189 Prompt for confirmation when there are unsaved changes.
18190 Be sure you know what you are doing before letting this function
18191 overwrite your changes.
18193 This function is useful in a setup where one tracks org files
18194 with a version control system, to revert on one machine after pulling
18195 changes from another. I believe the procedure must be like this:
18197 1. M-x org-save-all-org-buffers
18198 2. Pull changes from the other machine, resolve conflicts
18199 3. M-x org-revert-all-org-buffers"
18200 (interactive)
18201 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18202 (user-error "Abort"))
18203 (save-excursion
18204 (save-window-excursion
18205 (dolist (b (buffer-list))
18206 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18207 (with-current-buffer b buffer-file-name))
18208 (pop-to-buffer-same-window b)
18209 (revert-buffer t 'no-confirm)))
18210 (when (and (featurep 'org-id) org-id-track-globally)
18211 (org-id-locations-load)))))
18213 ;;;; Agenda files
18215 ;;;###autoload
18216 (defun org-switchb (&optional arg)
18217 "Switch between Org buffers.
18219 With `\\[universal-argument]' prefix, restrict available buffers to files.
18221 With `\\[universal-argument] \\[universal-argument]' \
18222 prefix, restrict available buffers to agenda files."
18223 (interactive "P")
18224 (let ((blist (org-buffer-list
18225 (cond ((equal arg '(4)) 'files)
18226 ((equal arg '(16)) 'agenda)))))
18227 (pop-to-buffer-same-window
18228 (completing-read "Org buffer: "
18229 (mapcar #'list (mapcar #'buffer-name blist))
18230 nil t))))
18232 (defun org-buffer-list (&optional predicate exclude-tmp)
18233 "Return a list of Org buffers.
18234 PREDICATE can be `export', `files' or `agenda'.
18236 export restrict the list to Export buffers.
18237 files restrict the list to buffers visiting Org files.
18238 agenda restrict the list to buffers visiting agenda files.
18240 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18241 (let* ((bfn nil)
18242 (agenda-files (and (eq predicate 'agenda)
18243 (mapcar 'file-truename (org-agenda-files t))))
18244 (filter
18245 (cond
18246 ((eq predicate 'files)
18247 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18248 ((eq predicate 'export)
18249 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18250 ((eq predicate 'agenda)
18251 (lambda (b)
18252 (with-current-buffer b
18253 (and (derived-mode-p 'org-mode)
18254 (setq bfn (buffer-file-name b))
18255 (member (file-truename bfn) agenda-files)))))
18256 (t (lambda (b) (with-current-buffer b
18257 (or (derived-mode-p 'org-mode)
18258 (string-match "\\*Org .*Export"
18259 (buffer-name b)))))))))
18260 (delq nil
18261 (mapcar
18262 (lambda(b)
18263 (if (and (funcall filter b)
18264 (or (not exclude-tmp)
18265 (not (string-match "tmp" (buffer-name b)))))
18267 nil))
18268 (buffer-list)))))
18270 (defun org-agenda-files (&optional unrestricted archives)
18271 "Get the list of agenda files.
18272 Optional UNRESTRICTED means return the full list even if a restriction
18273 is currently in place.
18274 When ARCHIVES is t, include all archive files that are really being
18275 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18276 `org-agenda-archives-mode' is t."
18277 (let ((files
18278 (cond
18279 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18280 ((stringp org-agenda-files) (org-read-agenda-file-list))
18281 ((listp org-agenda-files) org-agenda-files)
18282 (t (error "Invalid value of `org-agenda-files'")))))
18283 (setq files (apply 'append
18284 (mapcar (lambda (f)
18285 (if (file-directory-p f)
18286 (directory-files
18287 f t org-agenda-file-regexp)
18288 (list f)))
18289 files)))
18290 (when org-agenda-skip-unavailable-files
18291 (setq files (delq nil
18292 (mapcar (function
18293 (lambda (file)
18294 (and (file-readable-p file) file)))
18295 files))))
18296 (when (or (eq archives t)
18297 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18298 (setq files (org-add-archive-files files)))
18299 files))
18301 (defun org-agenda-file-p (&optional file)
18302 "Return non-nil, if FILE is an agenda file.
18303 If FILE is omitted, use the file associated with the current
18304 buffer."
18305 (let ((fname (or file (buffer-file-name))))
18306 (and fname
18307 (member (file-truename fname)
18308 (mapcar #'file-truename (org-agenda-files t))))))
18310 (defun org-edit-agenda-file-list ()
18311 "Edit the list of agenda files.
18312 Depending on setup, this either uses customize to edit the variable
18313 `org-agenda-files', or it visits the file that is holding the list. In the
18314 latter case, the buffer is set up in a way that saving it automatically kills
18315 the buffer and restores the previous window configuration."
18316 (interactive)
18317 (if (stringp org-agenda-files)
18318 (let ((cw (current-window-configuration)))
18319 (find-file org-agenda-files)
18320 (setq-local org-window-configuration cw)
18321 (add-hook 'after-save-hook
18322 (lambda ()
18323 (set-window-configuration
18324 (prog1 org-window-configuration
18325 (kill-buffer (current-buffer))))
18326 (org-install-agenda-files-menu)
18327 (message "New agenda file list installed"))
18328 nil 'local)
18329 (message "%s" (substitute-command-keys
18330 "Edit list and finish with \\[save-buffer]")))
18331 (customize-variable 'org-agenda-files)))
18333 (defun org-store-new-agenda-file-list (list)
18334 "Set new value for the agenda file list and save it correctly."
18335 (if (stringp org-agenda-files)
18336 (let ((fe (org-read-agenda-file-list t)) b u)
18337 (while (setq b (find-buffer-visiting org-agenda-files))
18338 (kill-buffer b))
18339 (with-temp-file org-agenda-files
18340 (insert
18341 (mapconcat
18342 (lambda (f) ;; Keep un-expanded entries.
18343 (if (setq u (assoc f fe))
18344 (cdr u)
18346 list "\n")
18347 "\n")))
18348 (let ((org-mode-hook nil) (org-inhibit-startup t)
18349 (org-insert-mode-line-in-empty-file nil))
18350 (setq org-agenda-files list)
18351 (customize-save-variable 'org-agenda-files org-agenda-files))))
18353 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18354 "Read the list of agenda files from a file.
18355 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18356 filenames, used by `org-store-new-agenda-file-list' to write back
18357 un-expanded file names."
18358 (when (file-directory-p org-agenda-files)
18359 (error "`org-agenda-files' cannot be a single directory"))
18360 (when (stringp org-agenda-files)
18361 (with-temp-buffer
18362 (insert-file-contents org-agenda-files)
18363 (mapcar
18364 (lambda (f)
18365 (let ((e (expand-file-name (substitute-in-file-name f)
18366 org-directory)))
18367 (if pair-with-expansion
18368 (cons e f)
18369 e)))
18370 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18372 ;;;###autoload
18373 (defun org-cycle-agenda-files ()
18374 "Cycle through the files in `org-agenda-files'.
18375 If the current buffer visits an agenda file, find the next one in the list.
18376 If the current buffer does not, find the first agenda file."
18377 (interactive)
18378 (let* ((fs (or (org-agenda-files t)
18379 (user-error "No agenda files")))
18380 (files (copy-sequence fs))
18381 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18382 file)
18383 (when tcf
18384 (while (and (setq file (pop files))
18385 (not (equal (file-truename file) tcf)))))
18386 (find-file (car (or files fs)))
18387 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18389 (defun org-agenda-file-to-front (&optional to-end)
18390 "Move/add the current file to the top of the agenda file list.
18391 If the file is not present in the list, it is added to the front. If it is
18392 present, it is moved there. With optional argument TO-END, add/move to the
18393 end of the list."
18394 (interactive "P")
18395 (let ((org-agenda-skip-unavailable-files nil)
18396 (file-alist (mapcar (lambda (x)
18397 (cons (file-truename x) x))
18398 (org-agenda-files t)))
18399 (ctf (file-truename
18400 (or buffer-file-name
18401 (user-error "Please save the current buffer to a file"))))
18402 x had)
18403 (setq x (assoc ctf file-alist) had x)
18405 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18406 (if to-end
18407 (setq file-alist (append (delq x file-alist) (list x)))
18408 (setq file-alist (cons x (delq x file-alist))))
18409 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18410 (org-install-agenda-files-menu)
18411 (message "File %s to %s of agenda file list"
18412 (if had "moved" "added") (if to-end "end" "front"))))
18414 (defun org-remove-file (&optional file)
18415 "Remove current file from the list of files in variable `org-agenda-files'.
18416 These are the files which are being checked for agenda entries.
18417 Optional argument FILE means use this file instead of the current."
18418 (interactive)
18419 (let* ((org-agenda-skip-unavailable-files nil)
18420 (file (or file buffer-file-name
18421 (user-error "Current buffer does not visit a file")))
18422 (true-file (file-truename file))
18423 (afile (abbreviate-file-name file))
18424 (files (delq nil (mapcar
18425 (lambda (x)
18426 (unless (equal true-file
18427 (file-truename x))
18429 (org-agenda-files t)))))
18430 (if (not (= (length files) (length (org-agenda-files t))))
18431 (progn
18432 (org-store-new-agenda-file-list files)
18433 (org-install-agenda-files-menu)
18434 (message "Removed from Org Agenda list: %s" afile))
18435 (message "File was not in list: %s (not removed)" afile))))
18437 (defun org-file-menu-entry (file)
18438 (vector file (list 'find-file file) t))
18440 (defun org-check-agenda-file (file)
18441 "Make sure FILE exists. If not, ask user what to do."
18442 (unless (file-exists-p file)
18443 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18444 (abbreviate-file-name file))
18445 (let ((r (downcase (read-char-exclusive))))
18446 (cond
18447 ((equal r ?r)
18448 (org-remove-file file)
18449 (throw 'nextfile t))
18450 (t (user-error "Abort"))))))
18452 (defun org-get-agenda-file-buffer (file)
18453 "Get an agenda buffer visiting FILE.
18454 If the buffer needs to be created, add it to the list of buffers
18455 which might be released later."
18456 (let ((buf (org-find-base-buffer-visiting file)))
18457 (if buf
18458 buf ; just return it
18459 ;; Make a new buffer and remember it
18460 (setq buf (find-file-noselect file))
18461 (when buf (push buf org-agenda-new-buffers))
18462 buf)))
18464 (defun org-release-buffers (blist)
18465 "Release all buffers in list, asking the user for confirmation when needed.
18466 When a buffer is unmodified, it is just killed. When modified, it is saved
18467 \(if the user agrees) and then killed."
18468 (let (file)
18469 (dolist (buf blist)
18470 (setq file (buffer-file-name buf))
18471 (when (and (buffer-modified-p buf)
18472 file
18473 (y-or-n-p (format "Save file %s? " file)))
18474 (with-current-buffer buf (save-buffer)))
18475 (kill-buffer buf))))
18477 (defun org-agenda-prepare-buffers (files)
18478 "Create buffers for all agenda files, protect archived trees and comments."
18479 (interactive)
18480 (let ((pa '(:org-archived t))
18481 (pc '(:org-comment t))
18482 (pall '(:org-archived t :org-comment t))
18483 (inhibit-read-only t)
18484 (org-inhibit-startup org-agenda-inhibit-startup)
18485 (rea (concat ":" org-archive-tag ":"))
18486 re pos)
18487 (setq org-tag-alist-for-agenda nil
18488 org-tag-groups-alist-for-agenda nil)
18489 (save-excursion
18490 (save-restriction
18491 (dolist (file files)
18492 (catch 'nextfile
18493 (if (bufferp file)
18494 (set-buffer file)
18495 (org-check-agenda-file file)
18496 (set-buffer (org-get-agenda-file-buffer file)))
18497 (widen)
18498 (org-set-regexps-and-options 'tags-only)
18499 (setq pos (point))
18500 (or (memq 'category org-agenda-ignore-properties)
18501 (org-refresh-category-properties))
18502 (or (memq 'stats org-agenda-ignore-properties)
18503 (org-refresh-stats-properties))
18504 (or (memq 'effort org-agenda-ignore-properties)
18505 (org-refresh-effort-properties))
18506 (or (memq 'appt org-agenda-ignore-properties)
18507 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18508 (setq org-todo-keywords-for-agenda
18509 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18510 (setq org-done-keywords-for-agenda
18511 (append org-done-keywords-for-agenda org-done-keywords))
18512 (setq org-todo-keyword-alist-for-agenda
18513 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18514 (setq org-tag-alist-for-agenda
18515 (org-uniquify
18516 (append org-tag-alist-for-agenda
18517 org-current-tag-alist)))
18518 ;; Merge current file's tag groups into global
18519 ;; `org-tag-groups-alist-for-agenda'.
18520 (when org-group-tags
18521 (dolist (alist org-tag-groups-alist)
18522 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18523 (if old
18524 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18525 (push alist org-tag-groups-alist-for-agenda)))))
18526 (org-with-silent-modifications
18527 (save-excursion
18528 (remove-text-properties (point-min) (point-max) pall)
18529 (when org-agenda-skip-archived-trees
18530 (goto-char (point-min))
18531 (while (re-search-forward rea nil t)
18532 (when (org-at-heading-p t)
18533 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18534 (goto-char (point-min))
18535 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18536 (while (re-search-forward re nil t)
18537 (when (save-match-data (org-in-commented-heading-p t))
18538 (add-text-properties
18539 (match-beginning 0) (org-end-of-subtree t) pc)))))
18540 (goto-char pos)))))
18541 (setq org-todo-keywords-for-agenda
18542 (org-uniquify org-todo-keywords-for-agenda))
18543 (setq org-todo-keyword-alist-for-agenda
18544 (org-uniquify org-todo-keyword-alist-for-agenda))))
18547 ;;;; CDLaTeX minor mode
18549 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18550 "Keymap for the minor `org-cdlatex-mode'.")
18552 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18553 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18554 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18555 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18556 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18558 (defvar org-cdlatex-texmathp-advice-is-done nil
18559 "Flag remembering if we have applied the advice to texmathp already.")
18561 (define-minor-mode org-cdlatex-mode
18562 "Toggle the minor `org-cdlatex-mode'.
18563 This mode supports entering LaTeX environment and math in LaTeX fragments
18564 in Org mode.
18565 \\{org-cdlatex-mode-map}"
18566 nil " OCDL" nil
18567 (when org-cdlatex-mode
18568 (require 'cdlatex)
18569 (run-hooks 'cdlatex-mode-hook)
18570 (cdlatex-compute-tables))
18571 (unless org-cdlatex-texmathp-advice-is-done
18572 (setq org-cdlatex-texmathp-advice-is-done t)
18573 (defadvice texmathp (around org-math-always-on activate)
18574 "Always return t in Org buffers.
18575 This is because we want to insert math symbols without dollars even outside
18576 the LaTeX math segments. If Org mode thinks that point is actually inside
18577 an embedded LaTeX fragment, let `texmathp' do its job.
18578 `\\[org-cdlatex-mode-map]'"
18579 (interactive)
18580 (let (p)
18581 (cond
18582 ((not (derived-mode-p 'org-mode)) ad-do-it)
18583 ((eq this-command 'cdlatex-math-symbol)
18584 (setq ad-return-value t
18585 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18587 (let ((p (org-inside-LaTeX-fragment-p)))
18588 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18589 (setq ad-return-value t
18590 texmathp-why '("Org mode embedded math" . 0))
18591 (when p ad-do-it)))))))))
18593 (defun turn-on-org-cdlatex ()
18594 "Unconditionally turn on `org-cdlatex-mode'."
18595 (org-cdlatex-mode 1))
18597 (defun org-try-cdlatex-tab ()
18598 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18599 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18600 - inside a LaTeX fragment, or
18601 - after the first word in a line, where an abbreviation expansion could
18602 insert a LaTeX environment."
18603 (when org-cdlatex-mode
18604 (cond
18605 ;; Before any word on the line: No expansion possible.
18606 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18607 ;; Just after first word on the line: Expand it. Make sure it
18608 ;; cannot happen on headlines, though.
18609 ((save-excursion
18610 (skip-chars-backward "a-zA-Z0-9*")
18611 (skip-chars-backward " \t")
18612 (and (bolp) (not (org-at-heading-p))))
18613 (cdlatex-tab) t)
18614 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18616 (defun org-cdlatex-underscore-caret (&optional _arg)
18617 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18618 Revert to the normal definition outside of these fragments."
18619 (interactive "P")
18620 (if (org-inside-LaTeX-fragment-p)
18621 (call-interactively 'cdlatex-sub-superscript)
18622 (let (org-cdlatex-mode)
18623 (call-interactively (key-binding (vector last-input-event))))))
18625 (defun org-cdlatex-math-modify (&optional _arg)
18626 "Execute `cdlatex-math-modify' in LaTeX fragments.
18627 Revert to the normal definition outside of these fragments."
18628 (interactive "P")
18629 (if (org-inside-LaTeX-fragment-p)
18630 (call-interactively 'cdlatex-math-modify)
18631 (let (org-cdlatex-mode)
18632 (call-interactively (key-binding (vector last-input-event))))))
18634 (defun org-cdlatex-environment-indent (&optional environment item)
18635 "Execute `cdlatex-environment' and indent the inserted environment.
18637 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18639 The inserted environment is indented to current indentation
18640 unless point is at the beginning of the line, in which the
18641 environment remains unintended."
18642 (interactive)
18643 ;; cdlatex-environment always return nil. Therefore, capture output
18644 ;; first and determine if an environment was selected.
18645 (let* ((beg (point-marker))
18646 (end (copy-marker (point) t))
18647 (inserted (progn
18648 (ignore-errors (cdlatex-environment environment item))
18649 (< beg end)))
18650 ;; Figure out how many lines to move forward after the
18651 ;; environment has been inserted.
18652 (lines (when inserted
18653 (save-excursion
18654 (- (cl-loop while (< beg (point))
18655 with x = 0
18656 do (forward-line -1)
18657 (cl-incf x)
18658 finally return x)
18659 (if (progn (goto-char beg)
18660 (and (progn (skip-chars-forward " \t") (eolp))
18661 (progn (skip-chars-backward " \t") (bolp))))
18662 1 0)))))
18663 (env (org-trim (delete-and-extract-region beg end))))
18664 (when inserted
18665 ;; Get indentation of next line unless at column 0.
18666 (let ((ind (if (bolp) 0
18667 (save-excursion
18668 (org-return-indent)
18669 (prog1 (org-get-indentation)
18670 (when (progn (skip-chars-forward " \t") (eolp))
18671 (delete-region beg (point)))))))
18672 (bol (progn (skip-chars-backward " \t") (bolp))))
18673 ;; Insert a newline before environment unless at column zero
18674 ;; to "escape" the current line. Insert a newline if
18675 ;; something is one the same line as \end{ENVIRONMENT}.
18676 (insert
18677 (concat (unless bol "\n") env
18678 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18679 (unless (zerop ind)
18680 (save-excursion
18681 (goto-char beg)
18682 (while (< (point) end)
18683 (unless (eolp) (indent-line-to ind))
18684 (forward-line))))
18685 (goto-char beg)
18686 (forward-line lines)
18687 (indent-line-to ind)))
18688 (set-marker beg nil)
18689 (set-marker end nil)))
18692 ;;;; LaTeX fragments
18694 (defun org-inside-LaTeX-fragment-p ()
18695 "Test if point is inside a LaTeX fragment.
18696 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18697 sequence appearing also before point.
18698 Even though the matchers for math are configurable, this function assumes
18699 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18700 delimiters are skipped when they have been removed by customization.
18701 The return value is nil, or a cons cell with the delimiter and the
18702 position of this delimiter.
18704 This function does a reasonably good job, but can locally be fooled by
18705 for example currency specifications. For example it will assume being in
18706 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18707 fragments that are properly closed, but during editing, we have to live
18708 with the uncertainty caused by missing closing delimiters. This function
18709 looks only before point, not after."
18710 (catch 'exit
18711 (let ((pos (point))
18712 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18713 (lim (save-excursion (org-backward-paragraph) (point)))
18714 dd-on str (start 0) m re)
18715 (goto-char pos)
18716 (when dodollar
18717 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18718 re (nth 1 (assoc "$" org-latex-regexps)))
18719 (while (string-match re str start)
18720 (cond
18721 ((= (match-end 0) (length str))
18722 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18723 ((= (match-end 0) (- (length str) 5))
18724 (throw 'exit nil))
18725 (t (setq start (match-end 0))))))
18726 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18727 (goto-char pos)
18728 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18729 (and (match-beginning 2) (throw 'exit nil))
18730 ;; count $$
18731 (while (re-search-backward "\\$\\$" lim t)
18732 (setq dd-on (not dd-on)))
18733 (goto-char pos)
18734 (when dd-on (cons "$$" m))))))
18736 (defun org-inside-latex-macro-p ()
18737 "Is point inside a LaTeX macro or its arguments?"
18738 (save-match-data
18739 (org-in-regexp
18740 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18742 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18743 "Build an overlay between BEG and END using IMAGE file.
18744 Argument IMAGETYPE is the extension of the displayed image,
18745 as a string. It defaults to \"png\"."
18746 (let ((ov (make-overlay beg end))
18747 (imagetype (or (intern imagetype) 'png)))
18748 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18749 (overlay-put ov 'evaporate t)
18750 (overlay-put ov
18751 'modification-hooks
18752 (list (lambda (o _flag _beg _end &optional _l)
18753 (delete-overlay o))))
18754 (overlay-put ov
18755 'display
18756 (list 'image :type imagetype :file image :ascent 'center))))
18758 (defun org--list-latex-overlays (&optional beg end)
18759 "List all Org LaTeX overlays in current buffer.
18760 Limit to overlays between BEG and END when those are provided."
18761 (cl-remove-if-not
18762 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18763 (overlays-in (or beg (point-min)) (or end (point-max)))))
18765 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18766 "Remove all overlays with LaTeX fragment images in current buffer.
18767 When optional arguments BEG and END are non-nil, remove all
18768 overlays between them instead. Return a non-nil value when some
18769 overlays were removed, nil otherwise."
18770 (let ((overlays (org--list-latex-overlays beg end)))
18771 (mapc #'delete-overlay overlays)
18772 overlays))
18774 (defun org-toggle-latex-fragment (&optional arg)
18775 "Preview the LaTeX fragment at point, or all locally or globally.
18777 If the cursor is on a LaTeX fragment, create the image and overlay
18778 it over the source code, if there is none. Remove it otherwise.
18779 If there is no fragment at point, display all fragments in the
18780 current section.
18782 With prefix ARG, preview or clear image for all fragments in the
18783 current subtree or in the whole buffer when used before the first
18784 headline. With a prefix ARG `\\[universal-argument] \
18785 \\[universal-argument]' preview or clear images
18786 for all fragments in the buffer."
18787 (interactive "P")
18788 (when (display-graphic-p)
18789 (catch 'exit
18790 (save-excursion
18791 (let (beg end msg)
18792 (cond
18793 ((or (equal arg '(16))
18794 (and (equal arg '(4))
18795 (org-with-limited-levels (org-before-first-heading-p))))
18796 (if (org-remove-latex-fragment-image-overlays)
18797 (progn (message "LaTeX fragments images removed from buffer")
18798 (throw 'exit nil))
18799 (setq msg "Creating images for buffer...")))
18800 ((equal arg '(4))
18801 (org-with-limited-levels (org-back-to-heading t))
18802 (setq beg (point))
18803 (setq end (progn (org-end-of-subtree t) (point)))
18804 (if (org-remove-latex-fragment-image-overlays beg end)
18805 (progn
18806 (message "LaTeX fragment images removed from subtree")
18807 (throw 'exit nil))
18808 (setq msg "Creating images for subtree...")))
18809 ((let ((datum (org-element-context)))
18810 (when (memq (org-element-type datum)
18811 '(latex-environment latex-fragment))
18812 (setq beg (org-element-property :begin datum))
18813 (setq end (org-element-property :end datum))
18814 (if (org-remove-latex-fragment-image-overlays beg end)
18815 (progn (message "LaTeX fragment image removed")
18816 (throw 'exit nil))
18817 (setq msg "Creating image...")))))
18819 (org-with-limited-levels
18820 (setq beg (if (org-at-heading-p) (line-beginning-position)
18821 (outline-previous-heading)
18822 (point)))
18823 (setq end (progn (outline-next-heading) (point)))
18824 (if (org-remove-latex-fragment-image-overlays beg end)
18825 (progn
18826 (message "LaTeX fragment images removed from section")
18827 (throw 'exit nil))
18828 (setq msg "Creating images for section...")))))
18829 (let ((file (buffer-file-name (buffer-base-buffer))))
18830 (org-format-latex
18831 (concat org-preview-latex-image-directory "org-ltximg")
18832 beg end
18833 ;; Emacs cannot overlay images from remote hosts. Create
18834 ;; it in `temporary-file-directory' instead.
18835 (if (or (not file) (file-remote-p file))
18836 temporary-file-directory
18837 default-directory)
18838 'overlays msg 'forbuffer org-preview-latex-default-process))
18839 (message (concat msg "done")))))))
18841 (defun org-format-latex
18842 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18843 "Replace LaTeX fragments with links to an image.
18845 The function takes care of creating the replacement image.
18847 Only consider fragments between BEG and END when those are
18848 provided.
18850 When optional argument OVERLAYS is non-nil, display the image on
18851 top of the fragment instead of replacing it.
18853 PROCESSING-TYPE is the conversion method to use, as a symbol.
18855 Some of the options can be changed using the variable
18856 `org-format-latex-options', which see."
18857 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18858 (unless (eq processing-type 'verbatim)
18859 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18860 (cnt 0)
18861 checkdir-flag)
18862 (goto-char (or beg (point-min)))
18863 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18864 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18865 (overlay-recenter (or end (point-max))))
18866 (while (re-search-forward math-regexp end t)
18867 (unless (and overlays
18868 (eq (get-char-property (point) 'org-overlay-type)
18869 'org-latex-overlay))
18870 (let* ((context (org-element-context))
18871 (type (org-element-type context)))
18872 (when (memq type '(latex-environment latex-fragment))
18873 (let ((block-type (eq type 'latex-environment))
18874 (value (org-element-property :value context))
18875 (beg (org-element-property :begin context))
18876 (end (save-excursion
18877 (goto-char (org-element-property :end context))
18878 (skip-chars-backward " \r\t\n")
18879 (point))))
18880 (cond
18881 ((eq processing-type 'mathjax)
18882 ;; Prepare for MathJax processing.
18883 (if (not (string-match "\\`\\$\\$?" value))
18884 (goto-char end)
18885 (delete-region beg end)
18886 (if (string= (match-string 0 value) "$$")
18887 (insert "\\[" (substring value 2 -2) "\\]")
18888 (insert "\\(" (substring value 1 -1) "\\)"))))
18889 ((assq processing-type org-preview-latex-process-alist)
18890 ;; Process to an image.
18891 (cl-incf cnt)
18892 (goto-char beg)
18893 (let* ((processing-info
18894 (cdr (assq processing-type org-preview-latex-process-alist)))
18895 (face (face-at-point))
18896 ;; Get the colors from the face at point.
18898 (let ((color (plist-get org-format-latex-options
18899 :foreground)))
18900 (if (and forbuffer (eq color 'auto))
18901 (face-attribute face :foreground nil 'default)
18902 color)))
18904 (let ((color (plist-get org-format-latex-options
18905 :background)))
18906 (if (and forbuffer (eq color 'auto))
18907 (face-attribute face :background nil 'default)
18908 color)))
18909 (hash (sha1 (prin1-to-string
18910 (list org-format-latex-header
18911 org-latex-default-packages-alist
18912 org-latex-packages-alist
18913 org-format-latex-options
18914 forbuffer value fg bg))))
18915 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18916 (absprefix (expand-file-name prefix dir))
18917 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18918 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18919 (sep (and block-type "\n\n"))
18920 (link (concat sep "[[file:" linkfile "]]" sep))
18921 (options
18922 (org-combine-plists
18923 org-format-latex-options
18924 `(:foreground ,fg :background ,bg))))
18925 (when msg (message msg cnt))
18926 (unless checkdir-flag ; Ensure the directory exists.
18927 (setq checkdir-flag t)
18928 (let ((todir (file-name-directory absprefix)))
18929 (unless (file-directory-p todir)
18930 (make-directory todir t))))
18931 (unless (file-exists-p movefile)
18932 (org-create-formula-image
18933 value movefile options forbuffer processing-type))
18934 (if overlays
18935 (progn
18936 (dolist (o (overlays-in beg end))
18937 (when (eq (overlay-get o 'org-overlay-type)
18938 'org-latex-overlay)
18939 (delete-overlay o)))
18940 (org--format-latex-make-overlay beg end movefile imagetype)
18941 (goto-char end))
18942 (delete-region beg end)
18943 (insert
18944 (org-add-props link
18945 (list 'org-latex-src
18946 (replace-regexp-in-string "\"" "" value)
18947 'org-latex-src-embed-type
18948 (if block-type 'paragraph 'character)))))))
18949 ((eq processing-type 'mathml)
18950 ;; Process to MathML.
18951 (unless (org-format-latex-mathml-available-p)
18952 (user-error "LaTeX to MathML converter not configured"))
18953 (cl-incf cnt)
18954 (when msg (message msg cnt))
18955 (goto-char beg)
18956 (delete-region beg end)
18957 (insert (org-format-latex-as-mathml
18958 value block-type prefix dir)))
18960 (error "Unknown conversion process %s for LaTeX fragments"
18961 processing-type)))))))))))
18963 (defun org-create-math-formula (latex-frag &optional mathml-file)
18964 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18965 Use `org-latex-to-mathml-convert-command'. If the conversion is
18966 sucessful, return the portion between \"<math...> </math>\"
18967 elements otherwise return nil. When MATHML-FILE is specified,
18968 write the results in to that file. When invoked as an
18969 interactive command, prompt for LATEX-FRAG, with initial value
18970 set to the current active region and echo the results for user
18971 inspection."
18972 (interactive (list (let ((frag (when (org-region-active-p)
18973 (buffer-substring-no-properties
18974 (region-beginning) (region-end)))))
18975 (read-string "LaTeX Fragment: " frag nil frag))))
18976 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18977 (let* ((tmp-in-file
18978 (let ((file (file-relative-name
18979 (make-temp-name (expand-file-name "ltxmathml-in")))))
18980 (write-region latex-frag nil file)
18981 file))
18982 (tmp-out-file (file-relative-name
18983 (make-temp-name (expand-file-name "ltxmathml-out"))))
18984 (cmd (format-spec
18985 org-latex-to-mathml-convert-command
18986 `((?j . ,(and org-latex-to-mathml-jar-file
18987 (shell-quote-argument
18988 (expand-file-name
18989 org-latex-to-mathml-jar-file))))
18990 (?I . ,(shell-quote-argument tmp-in-file))
18991 (?i . ,latex-frag)
18992 (?o . ,(shell-quote-argument tmp-out-file)))))
18993 mathml shell-command-output)
18994 (when (called-interactively-p 'any)
18995 (unless (org-format-latex-mathml-available-p)
18996 (user-error "LaTeX to MathML converter not configured")))
18997 (message "Running %s" cmd)
18998 (setq shell-command-output (shell-command-to-string cmd))
18999 (setq mathml
19000 (when (file-readable-p tmp-out-file)
19001 (with-current-buffer (find-file-noselect tmp-out-file t)
19002 (goto-char (point-min))
19003 (when (re-search-forward
19004 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19005 (regexp-quote
19006 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19007 nil t)
19008 (prog1 (match-string 0) (kill-buffer))))))
19009 (cond
19010 (mathml
19011 (setq mathml
19012 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19013 (when mathml-file
19014 (write-region mathml nil mathml-file))
19015 (when (called-interactively-p 'any)
19016 (message mathml)))
19017 ((message "LaTeX to MathML conversion failed")
19018 (message shell-command-output)))
19019 (delete-file tmp-in-file)
19020 (when (file-exists-p tmp-out-file)
19021 (delete-file tmp-out-file))
19022 mathml))
19024 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19025 prefix &optional dir)
19026 "Use `org-create-math-formula' but check local cache first."
19027 (let* ((absprefix (expand-file-name prefix dir))
19028 (print-length nil) (print-level nil)
19029 (formula-id (concat
19030 "formula-"
19031 (sha1
19032 (prin1-to-string
19033 (list latex-frag
19034 org-latex-to-mathml-convert-command)))))
19035 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19036 (formula-cache-dir (file-name-directory formula-cache)))
19038 (unless (file-directory-p formula-cache-dir)
19039 (make-directory formula-cache-dir t))
19041 (unless (file-exists-p formula-cache)
19042 (org-create-math-formula latex-frag formula-cache))
19044 (if (file-exists-p formula-cache)
19045 ;; Successful conversion. Return the link to MathML file.
19046 (org-add-props
19047 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19048 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19049 'org-latex-src-embed-type (if latex-frag-type
19050 'paragraph 'character)))
19051 ;; Failed conversion. Return the LaTeX fragment verbatim
19052 latex-frag)))
19054 (defun org--get-display-dpi ()
19055 "Get the DPI of the display.
19056 The function assumes that the display has the same pixel width in
19057 the horizontal and vertical directions."
19058 (if (display-graphic-p)
19059 (round (/ (display-pixel-height)
19060 (/ (display-mm-height) 25.4)))
19061 (error "Attempt to calculate the dpi of a non-graphic display")))
19063 (defun org-create-formula-image
19064 (string tofile options buffer &optional processing-type)
19065 "Create an image from LaTeX source using external processes.
19067 The LaTeX STRING is saved to a temporary LaTeX file, then
19068 converted to an image file by process PROCESSING-TYPE defined in
19069 `org-preview-latex-process-alist'. A nil value defaults to
19070 `org-preview-latex-default-process'.
19072 The generated image file is eventually moved to TOFILE.
19074 The OPTIONS argument controls the size, foreground color and
19075 background color of the generated image.
19077 When BUFFER non-nil, this function is used for LaTeX previewing.
19078 Otherwise, it is used to deal with LaTeX snippets showed in
19079 a HTML file."
19080 (let* ((processing-type (or processing-type
19081 org-preview-latex-default-process))
19082 (processing-info
19083 (cdr (assq processing-type org-preview-latex-process-alist)))
19084 (programs (plist-get processing-info :programs))
19085 (error-message (or (plist-get processing-info :message) ""))
19086 (use-xcolor (plist-get processing-info :use-xcolor))
19087 (image-input-type (plist-get processing-info :image-input-type))
19088 (image-output-type (plist-get processing-info :image-output-type))
19089 (post-clean (or (plist-get processing-info :post-clean)
19090 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19091 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19092 (latex-header
19093 (or (plist-get processing-info :latex-header)
19094 (org-latex-make-preamble
19095 (org-export-get-environment (org-export-get-backend 'latex))
19096 org-format-latex-header
19097 'snippet)))
19098 (latex-compiler (plist-get processing-info :latex-compiler))
19099 (image-converter (plist-get processing-info :image-converter))
19100 (tmpdir temporary-file-directory)
19101 (texfilebase (make-temp-name
19102 (expand-file-name "orgtex" tmpdir)))
19103 (texfile (concat texfilebase ".tex"))
19104 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19105 '(1.0 . 1.0)))
19106 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19107 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19108 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19109 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19110 "Black"))
19111 (bg (or (plist-get options (if buffer :background :html-background))
19112 "Transparent"))
19113 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19114 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19115 (dolist (program programs)
19116 (org-check-external-command program error-message))
19117 (if use-xcolor
19118 (progn (if (eq fg 'default)
19119 (setq fg (org-latex-color :foreground))
19120 (setq fg (org-latex-color-format fg)))
19121 (if (eq bg 'default)
19122 (setq bg (org-latex-color :background))
19123 (setq bg (org-latex-color-format
19124 (if (string= bg "Transparent") "white" bg))))
19125 (with-temp-file texfile
19126 (insert latex-header)
19127 (insert "\n\\begin{document}\n"
19128 "\\definecolor{fg}{rgb}{" fg "}\n"
19129 "\\definecolor{bg}{rgb}{" bg "}\n"
19130 "\n\\pagecolor{bg}\n"
19131 "\n{\\color{fg}\n"
19132 string
19133 "\n}\n"
19134 "\n\\end{document}\n")))
19135 (if (eq fg 'default)
19136 (setq fg (org-dvipng-color :foreground))
19137 (unless (string= fg "Transparent")
19138 (setq fg (org-dvipng-color-format fg))))
19139 (if (eq bg 'default)
19140 (setq bg (org-dvipng-color :background))
19141 (unless (string= bg "Transparent")
19142 (setq bg (org-dvipng-color-format bg))))
19143 (with-temp-file texfile
19144 (insert latex-header)
19145 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19147 (let* ((err-msg (format "Please adjust `%s' part of \
19148 `org-preview-latex-process-alist'."
19149 processing-type))
19150 (image-input-file
19151 (org-compile-file
19152 texfile latex-compiler image-input-type err-msg log-buf))
19153 (image-output-file
19154 (org-compile-file
19155 image-input-file image-converter image-output-type err-msg log-buf
19156 `((?F . ,(shell-quote-argument fg))
19157 (?B . ,(shell-quote-argument bg))
19158 (?D . ,(shell-quote-argument (format "%s" dpi)))
19159 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19160 (copy-file image-output-file tofile 'replace)
19161 (dolist (e post-clean)
19162 (when (file-exists-p (concat texfilebase e))
19163 (delete-file (concat texfilebase e))))
19164 image-output-file)))
19166 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19167 "Fill a LaTeX header template TPL.
19168 In the template, the following place holders will be recognized:
19170 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19171 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19172 [PACKAGES] \\usepackage statements for PKG
19173 [NO-PACKAGES] do not include PKG
19174 [EXTRA] the string EXTRA
19175 [NO-EXTRA] do not include EXTRA
19177 For backward compatibility, if both the positive and the negative place
19178 holder is missing, the positive one (without the \"NO-\") will be
19179 assumed to be present at the end of the template.
19180 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19181 EXTRA is a string.
19182 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19183 (let (rpl (end ""))
19184 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19185 (setq rpl (if (or (match-end 1) (not def-pkg))
19186 "" (org-latex-packages-to-string def-pkg snippets-p t))
19187 tpl (replace-match rpl t t tpl))
19188 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19190 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19191 (setq rpl (if (or (match-end 1) (not pkg))
19192 "" (org-latex-packages-to-string pkg snippets-p t))
19193 tpl (replace-match rpl t t tpl))
19194 (when pkg (setq end
19195 (concat end "\n"
19196 (org-latex-packages-to-string pkg snippets-p)))))
19198 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19199 (setq rpl (if (or (match-end 1) (not extra))
19200 "" (concat extra "\n"))
19201 tpl (replace-match rpl t t tpl))
19202 (when (and extra (string-match "\\S-" extra))
19203 (setq end (concat end "\n" extra))))
19205 (if (string-match "\\S-" end)
19206 (concat tpl "\n" end)
19207 tpl)))
19209 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19210 "Turn an alist of packages into a string with the \\usepackage macros."
19211 (setq pkg (mapconcat (lambda(p)
19212 (cond
19213 ((stringp p) p)
19214 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19215 (format "%% Package %s omitted" (cadr p)))
19216 ((equal "" (car p))
19217 (format "\\usepackage{%s}" (cadr p)))
19219 (format "\\usepackage[%s]{%s}"
19220 (car p) (cadr p)))))
19222 "\n"))
19223 (if newline (concat pkg "\n") pkg))
19225 (defun org-dvipng-color (attr)
19226 "Return a RGB color specification for dvipng."
19227 (org-dvipng-color-format (face-attribute 'default attr nil)))
19229 (defun org-dvipng-color-format (color-name)
19230 "Convert COLOR-NAME to a RGB color value for dvipng."
19231 (apply #'format "rgb %s %s %s"
19232 (mapcar 'org-normalize-color
19233 (color-values color-name))))
19235 (defun org-latex-color (attr)
19236 "Return a RGB color for the LaTeX color package."
19237 (org-latex-color-format (face-attribute 'default attr nil)))
19239 (defun org-latex-color-format (color-name)
19240 "Convert COLOR-NAME to a RGB color value."
19241 (apply #'format "%s,%s,%s"
19242 (mapcar 'org-normalize-color
19243 (color-values color-name))))
19245 (defun org-normalize-color (value)
19246 "Return string to be used as color value for an RGB component."
19247 (format "%g" (/ value 65535.0)))
19251 ;; Image display
19253 (defvar-local org-inline-image-overlays nil)
19255 (defun org-toggle-inline-images (&optional include-linked)
19256 "Toggle the display of inline images.
19257 INCLUDE-LINKED is passed to `org-display-inline-images'."
19258 (interactive "P")
19259 (if org-inline-image-overlays
19260 (progn
19261 (org-remove-inline-images)
19262 (when (called-interactively-p 'interactive)
19263 (message "Inline image display turned off")))
19264 (org-display-inline-images include-linked)
19265 (when (called-interactively-p 'interactive)
19266 (message (if org-inline-image-overlays
19267 (format "%d images displayed inline"
19268 (length org-inline-image-overlays))
19269 "No images to display inline")))))
19271 (defun org-redisplay-inline-images ()
19272 "Refresh the display of inline images."
19273 (interactive)
19274 (if (not org-inline-image-overlays)
19275 (org-toggle-inline-images)
19276 (org-toggle-inline-images)
19277 (org-toggle-inline-images)))
19279 (defun org-display-inline-images (&optional include-linked refresh beg end)
19280 "Display inline images.
19282 An inline image is a link which follows either of these
19283 conventions:
19285 1. Its path is a file with an extension matching return value
19286 from `image-file-name-regexp' and it has no contents.
19288 2. Its description consists in a single link of the previous
19289 type.
19291 When optional argument INCLUDE-LINKED is non-nil, also links with
19292 a text description part will be inlined. This can be nice for
19293 a quick look at those images, but it does not reflect what
19294 exported files will look like.
19296 When optional argument REFRESH is non-nil, refresh existing
19297 images between BEG and END. This will create new image displays
19298 only if necessary. BEG and END default to the buffer
19299 boundaries."
19300 (interactive "P")
19301 (when (display-graphic-p)
19302 (unless refresh
19303 (org-remove-inline-images)
19304 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19305 (org-with-wide-buffer
19306 (goto-char (or beg (point-min)))
19307 (let* ((case-fold-search t)
19308 (file-extension-re (image-file-name-regexp))
19309 (link-abbrevs (mapcar #'car
19310 (append org-link-abbrev-alist-local
19311 org-link-abbrev-alist)))
19312 ;; Check absolute, relative file names and explicit
19313 ;; "file:" links. Also check link abbreviations since
19314 ;; some might expand to "file" links.
19315 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19316 (and link-abbrevs
19317 (format "\\|\\(?:%s:\\)"
19318 (regexp-opt link-abbrevs))))))
19319 (while (re-search-forward file-types-re end t)
19320 (let ((link (save-match-data (org-element-context))))
19321 ;; Check if we're at an inline image, i.e., an image file
19322 ;; link without a description (unless INCLUDE-LINKED is
19323 ;; non-nil).
19324 (when (and (equal "file" (org-element-property :type link))
19325 (or include-linked
19326 (null (org-element-contents link)))
19327 (string-match-p file-extension-re
19328 (org-element-property :path link)))
19329 (let ((file (expand-file-name
19330 (org-link-unescape
19331 (org-element-property :path link)))))
19332 (when (file-exists-p file)
19333 (let ((width
19334 ;; Apply `org-image-actual-width' specifications.
19335 (cond
19336 ((not (image-type-available-p 'imagemagick)) nil)
19337 ((eq org-image-actual-width t) nil)
19338 ((listp org-image-actual-width)
19340 ;; First try to find a width among
19341 ;; attributes associated to the paragraph
19342 ;; containing link.
19343 (let ((paragraph
19344 (let ((e link))
19345 (while (and (setq e (org-element-property
19346 :parent e))
19347 (not (eq (org-element-type e)
19348 'paragraph))))
19349 e)))
19350 (when paragraph
19351 (save-excursion
19352 (goto-char (org-element-property :begin paragraph))
19353 (when
19354 (re-search-forward
19355 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19356 (org-element-property
19357 :post-affiliated paragraph)
19359 (string-to-number (match-string 1))))))
19360 ;; Otherwise, fall-back to provided number.
19361 (car org-image-actual-width)))
19362 ((numberp org-image-actual-width)
19363 org-image-actual-width)))
19364 (old (get-char-property-and-overlay
19365 (org-element-property :begin link)
19366 'org-image-overlay)))
19367 (if (and (car-safe old) refresh)
19368 (image-refresh (overlay-get (cdr old) 'display))
19369 (let ((image (create-image file
19370 (and width 'imagemagick)
19372 :width width)))
19373 (when image
19374 (let ((ov (make-overlay
19375 (org-element-property :begin link)
19376 (progn
19377 (goto-char
19378 (org-element-property :end link))
19379 (skip-chars-backward " \t")
19380 (point)))))
19381 (overlay-put ov 'display image)
19382 (overlay-put ov 'face 'default)
19383 (overlay-put ov 'org-image-overlay t)
19384 (overlay-put
19385 ov 'modification-hooks
19386 (list 'org-display-inline-remove-overlay))
19387 (push ov org-inline-image-overlays)))))))))))))))
19389 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19390 "Remove inline-display overlay if a corresponding region is modified."
19391 (let ((inhibit-modification-hooks t))
19392 (when (and ov after)
19393 (delete ov org-inline-image-overlays)
19394 (delete-overlay ov))))
19396 (defun org-remove-inline-images ()
19397 "Remove inline display of images."
19398 (interactive)
19399 (mapc #'delete-overlay org-inline-image-overlays)
19400 (setq org-inline-image-overlays nil))
19402 ;;;; Key bindings
19404 (defun org-remap (map &rest commands)
19405 "In MAP, remap the functions given in COMMANDS.
19406 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19407 (let (new old)
19408 (while commands
19409 (setq old (pop commands) new (pop commands))
19410 (org-defkey map (vector 'remap old) new))))
19412 ;; Outline functions from `outline-mode-prefix-map'
19413 ;; that can be remapped in Org:
19414 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19415 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19416 (define-key org-mode-map [remap outline-forward-same-level]
19417 'org-forward-heading-same-level)
19418 (define-key org-mode-map [remap outline-backward-same-level]
19419 'org-backward-heading-same-level)
19420 (define-key org-mode-map [remap outline-show-branches]
19421 'org-kill-note-or-show-branches)
19422 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19423 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19424 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19425 (define-key org-mode-map [remap outline-next-visible-heading]
19426 'org-next-visible-heading)
19427 (define-key org-mode-map [remap outline-previous-visible-heading]
19428 'org-previous-visible-heading)
19429 (define-key org-mode-map [remap show-children] 'org-show-children)
19431 ;; Outline functions from `outline-mode-prefix-map' that can not
19432 ;; be remapped in Org:
19434 ;; - the column "key binding" shows whether the Outline function is still
19435 ;; available in Org mode on the same key that it has been bound to in
19436 ;; Outline mode:
19437 ;; - "overridden": key used for a different functionality in Org mode
19438 ;; - else: key still bound to the same Outline function in Org mode
19440 ;; | Outline function | key binding | Org replacement |
19441 ;; |------------------------------------+-------------+--------------------------|
19442 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19443 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19444 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19445 ;; | `show-entry' | overridden | no replacement |
19446 ;; | `show-branches' | `C-c C-k' | still same function |
19447 ;; | `show-subtree' | overridden | visibility cycling |
19448 ;; | `show-all' | overridden | no replacement |
19449 ;; | `hide-subtree' | overridden | visibility cycling |
19450 ;; | `hide-body' | overridden | no replacement |
19451 ;; | `hide-entry' | overridden | visibility cycling |
19452 ;; | `hide-leaves' | overridden | no replacement |
19453 ;; | `hide-sublevels' | overridden | no replacement |
19454 ;; | `hide-other' | overridden | no replacement |
19456 ;; Make `C-c C-x' a prefix key
19457 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19459 ;; TAB key with modifiers
19460 (org-defkey org-mode-map "\C-i" 'org-cycle)
19461 (org-defkey org-mode-map [(tab)] 'org-cycle)
19462 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19463 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19465 ;; The following line is necessary under Suse GNU/Linux
19466 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19467 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19468 (define-key org-mode-map [backtab] 'org-shifttab)
19470 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19471 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19472 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
19474 ;; Cursor keys with modifiers
19475 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19476 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19477 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19478 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19480 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19481 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19482 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19483 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19484 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19485 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19487 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19488 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19489 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19490 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19492 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19493 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19494 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19495 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19497 ;; Babel keys
19498 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19499 (dolist (pair org-babel-key-bindings)
19500 (define-key org-babel-map (car pair) (cdr pair)))
19502 ;;; Extra keys for tty access.
19503 ;; We only set them when really needed because otherwise the
19504 ;; menus don't show the simple keys
19506 (when (or org-use-extra-keys (not window-system))
19507 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19508 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19509 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19510 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19511 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19512 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19513 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19514 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19515 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19516 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19517 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19518 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19519 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19520 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19521 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19522 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19523 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19524 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19525 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19526 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19527 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19528 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19529 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19530 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19531 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19532 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19533 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19534 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19536 ;; All the other keys
19537 (org-remap org-mode-map
19538 'self-insert-command 'org-self-insert-command
19539 'delete-char 'org-delete-char
19540 'delete-backward-char 'org-delete-backward-char)
19541 (org-defkey org-mode-map "|" 'org-force-self-insert)
19543 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19544 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19545 (if (boundp 'narrow-map)
19546 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19547 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19548 (if (boundp 'narrow-map)
19549 (org-defkey narrow-map "b" 'org-narrow-to-block)
19550 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19551 (if (boundp 'narrow-map)
19552 (org-defkey narrow-map "e" 'org-narrow-to-element)
19553 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19554 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19555 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19556 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19557 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19558 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19559 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19560 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19561 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19562 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19563 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19564 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19565 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19566 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19567 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19568 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19569 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19570 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19571 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19572 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19573 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19574 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19575 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19576 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19577 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19578 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19579 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19580 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19581 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19582 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19583 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19584 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19585 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19586 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19587 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19588 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19589 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19590 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19591 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19592 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19593 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19594 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19595 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19596 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19597 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19598 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19599 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19600 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19601 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19602 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19603 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19604 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19605 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19606 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19607 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19608 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19609 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19610 (org-defkey org-mode-map "\C-c^" 'org-sort)
19611 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19612 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19613 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19614 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19615 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19616 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19617 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19618 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19619 (org-defkey org-mode-map "\C-m" 'org-return)
19620 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19621 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19622 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19623 (org-defkey org-mode-map (kbd "C-c TAB") #'org-table-toggle-column-width)
19624 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19625 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19626 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19627 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19628 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19629 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19630 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19631 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19632 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19633 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19634 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19635 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19636 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19637 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19638 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19639 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19640 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19641 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19642 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19643 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19644 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19645 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19647 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19648 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19649 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19651 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19652 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19653 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19654 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19655 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19656 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19657 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19658 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19659 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19660 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19661 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19662 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19663 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19664 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19665 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19666 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19667 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19668 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19669 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19670 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19671 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19672 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19674 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19675 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19676 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19677 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19678 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19680 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19682 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19684 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19685 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19687 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19690 (defconst org-speed-commands-default
19692 ("Outline Navigation")
19693 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19694 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19695 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19696 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19697 ("F" . org-next-block)
19698 ("B" . org-previous-block)
19699 ("u" . (org-speed-move-safe 'outline-up-heading))
19700 ("j" . org-goto)
19701 ("g" . (org-refile t))
19702 ("Outline Visibility")
19703 ("c" . org-cycle)
19704 ("C" . org-shifttab)
19705 (" " . org-display-outline-path)
19706 ("s" . org-narrow-to-subtree)
19707 ("=" . org-columns)
19708 ("Outline Structure Editing")
19709 ("U" . org-metaup)
19710 ("D" . org-metadown)
19711 ("r" . org-metaright)
19712 ("l" . org-metaleft)
19713 ("R" . org-shiftmetaright)
19714 ("L" . org-shiftmetaleft)
19715 ("i" . (progn (forward-char 1) (call-interactively
19716 'org-insert-heading-respect-content)))
19717 ("^" . org-sort)
19718 ("w" . org-refile)
19719 ("a" . org-archive-subtree-default-with-confirmation)
19720 ("@" . org-mark-subtree)
19721 ("#" . org-toggle-comment)
19722 ("Clock Commands")
19723 ("I" . org-clock-in)
19724 ("O" . org-clock-out)
19725 ("Meta Data Editing")
19726 ("t" . org-todo)
19727 ("," . (org-priority))
19728 ("0" . (org-priority ?\ ))
19729 ("1" . (org-priority ?A))
19730 ("2" . (org-priority ?B))
19731 ("3" . (org-priority ?C))
19732 (":" . org-set-tags-command)
19733 ("e" . org-set-effort)
19734 ("E" . org-inc-effort)
19735 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19736 (org-entry-put (point) "APPT_WARNTIME" m)))
19737 ("Agenda Views etc")
19738 ("v" . org-agenda)
19739 ("/" . org-sparse-tree)
19740 ("Misc")
19741 ("o" . org-open-at-point)
19742 ("?" . org-speed-command-help)
19743 ("<" . (org-agenda-set-restriction-lock 'subtree))
19744 (">" . (org-agenda-remove-restriction-lock))
19746 "The default speed commands.")
19748 (defun org-print-speed-command (e)
19749 (if (> (length (car e)) 1)
19750 (progn
19751 (princ "\n")
19752 (princ (car e))
19753 (princ "\n")
19754 (princ (make-string (length (car e)) ?-))
19755 (princ "\n"))
19756 (princ (car e))
19757 (princ " ")
19758 (if (symbolp (cdr e))
19759 (princ (symbol-name (cdr e)))
19760 (prin1 (cdr e)))
19761 (princ "\n")))
19763 (defun org-speed-command-help ()
19764 "Show the available speed commands."
19765 (interactive)
19766 (if (not org-use-speed-commands)
19767 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19768 (with-output-to-temp-buffer "*Help*"
19769 (princ "User-defined Speed commands\n===========================\n")
19770 (mapc #'org-print-speed-command org-speed-commands-user)
19771 (princ "\n")
19772 (princ "Built-in Speed commands\n=======================\n")
19773 (mapc #'org-print-speed-command org-speed-commands-default))
19774 (with-current-buffer "*Help*"
19775 (setq truncate-lines t))))
19777 (defun org-speed-move-safe (cmd)
19778 "Execute CMD, but make sure that the cursor always ends up in a headline.
19779 If not, return to the original position and throw an error."
19780 (interactive)
19781 (let ((pos (point)))
19782 (call-interactively cmd)
19783 (unless (and (bolp) (org-at-heading-p))
19784 (goto-char pos)
19785 (error "Boundary reached while executing %s" cmd))))
19787 (defvar org-self-insert-command-undo-counter 0)
19789 (defvar org-table-auto-blank-field) ; defined in org-table.el
19790 (defvar org-speed-command nil)
19792 (defun org-speed-command-activate (keys)
19793 "Hook for activating single-letter speed commands.
19794 `org-speed-commands-default' specifies a minimal command set.
19795 Use `org-speed-commands-user' for further customization."
19796 (when (or (and (bolp) (looking-at org-outline-regexp))
19797 (and (functionp org-use-speed-commands)
19798 (funcall org-use-speed-commands)))
19799 (cdr (assoc keys (append org-speed-commands-user
19800 org-speed-commands-default)))))
19802 (defun org-babel-speed-command-activate (keys)
19803 "Hook for activating single-letter code block commands."
19804 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19805 (cdr (assoc keys org-babel-key-bindings))))
19807 (defcustom org-speed-command-hook
19808 '(org-speed-command-activate org-babel-speed-command-activate)
19809 "Hook for activating speed commands at strategic locations.
19810 Hook functions are called in sequence until a valid handler is
19811 found.
19813 Each hook takes a single argument, a user-pressed command key
19814 which is also a `self-insert-command' from the global map.
19816 Within the hook, examine the cursor position and the command key
19817 and return nil or a valid handler as appropriate. Handler could
19818 be one of an interactive command, a function, or a form.
19820 Set `org-use-speed-commands' to non-nil value to enable this
19821 hook. The default setting is `org-speed-command-activate'."
19822 :group 'org-structure
19823 :version "24.1"
19824 :type 'hook)
19826 (defun org-self-insert-command (N)
19827 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19828 If the cursor is in a table looking at whitespace, the whitespace is
19829 overwritten, and the table is not marked as requiring realignment."
19830 (interactive "p")
19831 (org-check-before-invisible-edit 'insert)
19832 (cond
19833 ((and org-use-speed-commands
19834 (let ((kv (this-command-keys-vector)))
19835 (setq org-speed-command
19836 (run-hook-with-args-until-success
19837 'org-speed-command-hook
19838 (make-string 1 (aref kv (1- (length kv))))))))
19839 (cond
19840 ((commandp org-speed-command)
19841 (setq this-command org-speed-command)
19842 (call-interactively org-speed-command))
19843 ((functionp org-speed-command)
19844 (funcall org-speed-command))
19845 ((and org-speed-command (listp org-speed-command))
19846 (eval org-speed-command))
19847 (t (let (org-use-speed-commands)
19848 (call-interactively 'org-self-insert-command)))))
19849 ((and
19850 (org-at-table-p)
19851 (eq N 1)
19852 (not (org-region-active-p))
19853 (progn
19854 ;; Check if we blank the field, and if that triggers align.
19855 (and (featurep 'org-table) org-table-auto-blank-field
19856 (memq last-command
19857 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19858 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19859 ;; Got extra space, this field does not determine
19860 ;; column width.
19861 (let (org-table-may-need-update) (org-table-blank-field))
19862 ;; No extra space, this field may determine column
19863 ;; width.
19864 (org-table-blank-field)))
19866 (looking-at "[^|\n]* \\( \\)|"))
19867 ;; There is room for insertion without re-aligning the table.
19868 (delete-region (match-beginning 1) (match-end 1))
19869 (self-insert-command N))
19871 (setq org-table-may-need-update t)
19872 (self-insert-command N)
19873 (org-fix-tags-on-the-fly)
19874 (when org-self-insert-cluster-for-undo
19875 (if (not (eq last-command 'org-self-insert-command))
19876 (setq org-self-insert-command-undo-counter 1)
19877 (if (>= org-self-insert-command-undo-counter 20)
19878 (setq org-self-insert-command-undo-counter 1)
19879 (and (> org-self-insert-command-undo-counter 0)
19880 buffer-undo-list (listp buffer-undo-list)
19881 (not (cadr buffer-undo-list)) ; remove nil entry
19882 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19883 (setq org-self-insert-command-undo-counter
19884 (1+ org-self-insert-command-undo-counter))))))))
19886 (defun org-check-before-invisible-edit (kind)
19887 "Check is editing if kind KIND would be dangerous with invisible text around.
19888 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19889 ;; First, try to get out of here as quickly as possible, to reduce overhead
19890 (when (and org-catch-invisible-edits
19891 (or (not (boundp 'visible-mode)) (not visible-mode))
19892 (or (get-char-property (point) 'invisible)
19893 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19894 ;; OK, we need to take a closer look. Do not consider
19895 ;; invisibility obtained through text properties (e.g., link
19896 ;; fontification), as it cannot be toggled.
19897 (let* ((invisible-at-point
19898 (pcase (get-char-property-and-overlay (point) 'invisible)
19899 (`(,_ . ,(and (pred overlayp) o)) o)))
19900 ;; Assume that point cannot land in the middle of an
19901 ;; overlay, or between two overlays.
19902 (invisible-before-point
19903 (and (not invisible-at-point)
19904 (not (bobp))
19905 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19906 (`(,_ . ,(and (pred overlayp) o)) o))))
19907 (border-and-ok-direction
19909 ;; Check if we are acting predictably before invisible
19910 ;; text.
19911 (and invisible-at-point
19912 (memq kind '(insert delete-backward)))
19913 ;; Check if we are acting predictably after invisible text
19914 ;; This works not well, and I have turned it off. It seems
19915 ;; better to always show and stop after invisible text.
19916 ;; (and (not invisible-at-point) invisible-before-point
19917 ;; (memq kind '(insert delete)))
19919 (when (or invisible-at-point invisible-before-point)
19920 (when (eq org-catch-invisible-edits 'error)
19921 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19922 (if (and org-custom-properties-overlays
19923 (y-or-n-p "Display invisible properties in this buffer? "))
19924 (org-toggle-custom-properties-visibility)
19925 ;; Make the area visible
19926 (save-excursion
19927 (when invisible-before-point
19928 (goto-char
19929 (previous-single-char-property-change (point) 'invisible)))
19930 ;; Remove whatever overlay is currently making yet-to-be
19931 ;; edited text invisible. Also remove nested invisibility
19932 ;; related overlays.
19933 (delete-overlay (or invisible-at-point invisible-before-point))
19934 (let ((origin (if invisible-at-point (point) (1- (point)))))
19935 (while (pcase (get-char-property-and-overlay origin 'invisible)
19936 (`(,_ . ,(and (pred overlayp) o))
19937 (delete-overlay o)
19938 t)))))
19939 (cond
19940 ((eq org-catch-invisible-edits 'show)
19941 ;; That's it, we do the edit after showing
19942 (message
19943 "Unfolding invisible region around point before editing")
19944 (sit-for 1))
19945 ((and (eq org-catch-invisible-edits 'smart)
19946 border-and-ok-direction)
19947 (message "Unfolding invisible region around point before editing"))
19949 ;; Don't do the edit, make the user repeat it in full visibility
19950 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19952 (defun org-fix-tags-on-the-fly ()
19953 "Align tags in headline at point.
19954 Unlike to `org-set-tags', it ignores region and sorting."
19955 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19956 (org-at-heading-p))
19957 (let ((org-ignore-region t)
19958 (org-tags-sort-function nil))
19959 (org-set-tags nil t))))
19961 (defun org-delete-backward-char (N)
19962 "Like `delete-backward-char', insert whitespace at field end in tables.
19963 When deleting backwards, in tables this function will insert whitespace in
19964 front of the next \"|\" separator, to keep the table aligned. The table will
19965 still be marked for re-alignment if the field did fill the entire column,
19966 because, in this case the deletion might narrow the column."
19967 (interactive "p")
19968 (save-match-data
19969 (org-check-before-invisible-edit 'delete-backward)
19970 (if (and (org-at-table-p)
19971 (eq N 1)
19972 (not (org-region-active-p))
19973 (string-match "|" (buffer-substring (point-at-bol) (point)))
19974 (looking-at ".*?|"))
19975 (let ((pos (point))
19976 (noalign (looking-at "[^|\n\r]* |"))
19977 (c org-table-may-need-update))
19978 (backward-delete-char N)
19979 (unless overwrite-mode
19980 (skip-chars-forward "^|")
19981 (insert " ")
19982 (goto-char (1- pos)))
19983 ;; noalign: if there were two spaces at the end, this field
19984 ;; does not determine the width of the column.
19985 (when noalign (setq org-table-may-need-update c)))
19986 (backward-delete-char N)
19987 (org-fix-tags-on-the-fly))))
19989 (defun org-delete-char (N)
19990 "Like `delete-char', but insert whitespace at field end in tables.
19991 When deleting characters, in tables this function will insert whitespace in
19992 front of the next \"|\" separator, to keep the table aligned. The table will
19993 still be marked for re-alignment if the field did fill the entire column,
19994 because, in this case the deletion might narrow the column."
19995 (interactive "p")
19996 (save-match-data
19997 (org-check-before-invisible-edit 'delete)
19998 (if (and (org-at-table-p)
19999 (not (bolp))
20000 (not (= (char-after) ?|))
20001 (eq N 1))
20002 (if (looking-at ".*?|")
20003 (let ((pos (point))
20004 (noalign (looking-at "[^|\n\r]* |"))
20005 (c org-table-may-need-update))
20006 (replace-match
20007 (concat (substring (match-string 0) 1 -1) " |") nil t)
20008 (goto-char pos)
20009 ;; noalign: if there were two spaces at the end, this field
20010 ;; does not determine the width of the column.
20011 (when noalign (setq org-table-may-need-update c)))
20012 (delete-char N))
20013 (delete-char N)
20014 (org-fix-tags-on-the-fly))))
20016 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20017 (put 'org-self-insert-command 'delete-selection
20018 (lambda ()
20019 (not (run-hook-with-args-until-success
20020 'self-insert-uses-region-functions))))
20021 (put 'orgtbl-self-insert-command 'delete-selection
20022 (lambda ()
20023 (not (run-hook-with-args-until-success
20024 'self-insert-uses-region-functions))))
20025 (put 'org-delete-char 'delete-selection 'supersede)
20026 (put 'org-delete-backward-char 'delete-selection 'supersede)
20027 (put 'org-yank 'delete-selection 'yank)
20029 ;; Make `flyspell-mode' delay after some commands
20030 (put 'org-self-insert-command 'flyspell-delayed t)
20031 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20032 (put 'org-delete-char 'flyspell-delayed t)
20033 (put 'org-delete-backward-char 'flyspell-delayed t)
20035 ;; Make pabbrev-mode expand after Org mode commands
20036 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20037 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20039 (defun org-transpose-words ()
20040 "Transpose words for Org.
20041 This uses the `org-mode-transpose-word-syntax-table' syntax
20042 table, which interprets characters in `org-emphasis-alist' as
20043 word constituents."
20044 (interactive)
20045 (with-syntax-table org-mode-transpose-word-syntax-table
20046 (call-interactively 'transpose-words)))
20047 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20049 (defvar org-ctrl-c-ctrl-c-hook nil
20050 "Hook for functions attaching themselves to `C-c C-c'.
20052 This can be used to add additional functionality to the C-c C-c
20053 key which executes context-dependent commands. This hook is run
20054 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20055 run after the last test.
20057 Each function will be called with no arguments. The function
20058 must check if the context is appropriate for it to act. If yes,
20059 it should do its thing and then return a non-nil value. If the
20060 context is wrong, just do nothing and return nil.")
20062 (defvar org-ctrl-c-ctrl-c-final-hook nil
20063 "Hook for functions attaching themselves to `C-c C-c'.
20065 This can be used to add additional functionality to the C-c C-c
20066 key which executes context-dependent commands. This hook is run
20067 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20068 before the first test.
20070 Each function will be called with no arguments. The function
20071 must check if the context is appropriate for it to act. If yes,
20072 it should do its thing and then return a non-nil value. If the
20073 context is wrong, just do nothing and return nil.")
20075 (defvar org-tab-first-hook nil
20076 "Hook for functions to attach themselves to TAB.
20077 See `org-ctrl-c-ctrl-c-hook' for more information.
20078 This hook runs as the first action when TAB is pressed, even before
20079 `org-cycle' messes around with the `outline-regexp' to cater for
20080 inline tasks and plain list item folding.
20081 If any function in this hook returns t, any other actions that
20082 would have been caused by TAB (such as table field motion or visibility
20083 cycling) will not occur.")
20085 (defvar org-tab-after-check-for-table-hook nil
20086 "Hook for functions to attach themselves to TAB.
20087 See `org-ctrl-c-ctrl-c-hook' for more information.
20088 This hook runs after it has been established that the cursor is not in a
20089 table, but before checking if the cursor is in a headline or if global cycling
20090 should be done.
20091 If any function in this hook returns t, not other actions like visibility
20092 cycling will be done.")
20094 (defvar org-tab-after-check-for-cycling-hook nil
20095 "Hook for functions to attach themselves to TAB.
20096 See `org-ctrl-c-ctrl-c-hook' for more information.
20097 This hook runs after it has been established that not table field motion and
20098 not visibility should be done because of current context. This is probably
20099 the place where a package like yasnippets can hook in.")
20101 (defvar org-tab-before-tab-emulation-hook nil
20102 "Hook for functions to attach themselves to TAB.
20103 See `org-ctrl-c-ctrl-c-hook' for more information.
20104 This hook runs after every other options for TAB have been exhausted, but
20105 before indentation and \t insertion takes place.")
20107 (defvar org-metaleft-hook nil
20108 "Hook for functions attaching themselves to `M-left'.
20109 See `org-ctrl-c-ctrl-c-hook' for more information.")
20110 (defvar org-metaright-hook nil
20111 "Hook for functions attaching themselves to `M-right'.
20112 See `org-ctrl-c-ctrl-c-hook' for more information.")
20113 (defvar org-metaup-hook nil
20114 "Hook for functions attaching themselves to `M-up'.
20115 See `org-ctrl-c-ctrl-c-hook' for more information.")
20116 (defvar org-metadown-hook nil
20117 "Hook for functions attaching themselves to `M-down'.
20118 See `org-ctrl-c-ctrl-c-hook' for more information.")
20119 (defvar org-shiftmetaleft-hook nil
20120 "Hook for functions attaching themselves to `M-S-left'.
20121 See `org-ctrl-c-ctrl-c-hook' for more information.")
20122 (defvar org-shiftmetaright-hook nil
20123 "Hook for functions attaching themselves to `M-S-right'.
20124 See `org-ctrl-c-ctrl-c-hook' for more information.")
20125 (defvar org-shiftmetaup-hook nil
20126 "Hook for functions attaching themselves to `M-S-up'.
20127 See `org-ctrl-c-ctrl-c-hook' for more information.")
20128 (defvar org-shiftmetadown-hook nil
20129 "Hook for functions attaching themselves to `M-S-down'.
20130 See `org-ctrl-c-ctrl-c-hook' for more information.")
20131 (defvar org-metareturn-hook nil
20132 "Hook for functions attaching themselves to `M-RET'.
20133 See `org-ctrl-c-ctrl-c-hook' for more information.")
20134 (defvar org-shiftup-hook nil
20135 "Hook for functions attaching themselves to `S-up'.
20136 See `org-ctrl-c-ctrl-c-hook' for more information.")
20137 (defvar org-shiftup-final-hook nil
20138 "Hook for functions attaching themselves to `S-up'.
20139 This one runs after all other options except shift-select have been excluded.
20140 See `org-ctrl-c-ctrl-c-hook' for more information.")
20141 (defvar org-shiftdown-hook nil
20142 "Hook for functions attaching themselves to `S-down'.
20143 See `org-ctrl-c-ctrl-c-hook' for more information.")
20144 (defvar org-shiftdown-final-hook nil
20145 "Hook for functions attaching themselves to `S-down'.
20146 This one runs after all other options except shift-select have been excluded.
20147 See `org-ctrl-c-ctrl-c-hook' for more information.")
20148 (defvar org-shiftleft-hook nil
20149 "Hook for functions attaching themselves to `S-left'.
20150 See `org-ctrl-c-ctrl-c-hook' for more information.")
20151 (defvar org-shiftleft-final-hook nil
20152 "Hook for functions attaching themselves to `S-left'.
20153 This one runs after all other options except shift-select have been excluded.
20154 See `org-ctrl-c-ctrl-c-hook' for more information.")
20155 (defvar org-shiftright-hook nil
20156 "Hook for functions attaching themselves to `S-right'.
20157 See `org-ctrl-c-ctrl-c-hook' for more information.")
20158 (defvar org-shiftright-final-hook nil
20159 "Hook for functions attaching themselves to `S-right'.
20160 This one runs after all other options except shift-select have been excluded.
20161 See `org-ctrl-c-ctrl-c-hook' for more information.")
20163 (defun org-modifier-cursor-error ()
20164 "Throw an error, a modified cursor command was applied in wrong context."
20165 (user-error "This command is active in special context like tables, headlines or items"))
20167 (defun org-shiftselect-error ()
20168 "Throw an error because Shift-Cursor command was applied in wrong context."
20169 (if (and (boundp 'shift-select-mode) shift-select-mode)
20170 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20171 (user-error "This command works only in special context like headlines or timestamps")))
20173 (defun org-call-for-shift-select (cmd)
20174 (let ((this-command-keys-shift-translated t))
20175 (call-interactively cmd)))
20177 (defun org-shifttab (&optional arg)
20178 "Global visibility cycling or move to previous table field.
20179 Call `org-table-previous-field' within a table.
20180 When ARG is nil, cycle globally through visibility states.
20181 When ARG is a numeric prefix, show contents of this level."
20182 (interactive "P")
20183 (cond
20184 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20185 ((integerp arg)
20186 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20187 (message "Content view to level: %d" arg)
20188 (org-content (prefix-numeric-value arg2))
20189 (org-cycle-show-empty-lines t)
20190 (setq org-cycle-global-status 'overview)))
20191 (t (call-interactively 'org-global-cycle))))
20193 (defun org-shiftmetaleft ()
20194 "Promote subtree or delete table column.
20195 Calls `org-promote-subtree', `org-outdent-item-tree', or
20196 `org-table-delete-column', depending on context. See the
20197 individual commands for more information."
20198 (interactive)
20199 (cond
20200 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20201 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20202 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20203 ((if (not (org-region-active-p)) (org-at-item-p)
20204 (save-excursion (goto-char (region-beginning))
20205 (org-at-item-p)))
20206 (call-interactively 'org-outdent-item-tree))
20207 (t (org-modifier-cursor-error))))
20209 (defun org-shiftmetaright ()
20210 "Demote subtree or insert table column.
20211 Calls `org-demote-subtree', `org-indent-item-tree', or
20212 `org-table-insert-column', depending on context. See the
20213 individual commands for more information."
20214 (interactive)
20215 (cond
20216 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20217 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20218 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20219 ((if (not (org-region-active-p)) (org-at-item-p)
20220 (save-excursion (goto-char (region-beginning))
20221 (org-at-item-p)))
20222 (call-interactively 'org-indent-item-tree))
20223 (t (org-modifier-cursor-error))))
20225 (defun org-shiftmetaup (&optional _arg)
20226 "Drag the line at point up.
20227 In a table, kill the current row.
20228 On a clock timestamp, update the value of the timestamp like `S-<up>'
20229 but also adjust the previous clocked item in the clock history.
20230 Everywhere else, drag the line at point up."
20231 (interactive "P")
20232 (cond
20233 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20234 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20235 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20236 (call-interactively 'org-timestamp-up)))
20237 (t (call-interactively 'org-drag-line-backward))))
20239 (defun org-shiftmetadown (&optional _arg)
20240 "Drag the line at point down.
20241 In a table, insert an empty row at the current line.
20242 On a clock timestamp, update the value of the timestamp like `S-<down>'
20243 but also adjust the previous clocked item in the clock history.
20244 Everywhere else, drag the line at point down."
20245 (interactive "P")
20246 (cond
20247 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20248 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20249 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20250 (call-interactively 'org-timestamp-down)))
20251 (t (call-interactively 'org-drag-line-forward))))
20253 (defsubst org-hidden-tree-error ()
20254 (user-error
20255 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20257 (defun org-metaleft (&optional _arg)
20258 "Promote heading, list item at point or move table column left.
20260 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20261 depending on context. With no specific context, calls the Emacs
20262 default `backward-word'. See the individual commands for more
20263 information.
20265 This function runs the hook `org-metaleft-hook' as a first step,
20266 and returns at first non-nil value."
20267 (interactive "P")
20268 (cond
20269 ((run-hook-with-args-until-success 'org-metaleft-hook))
20270 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20271 ((org-with-limited-levels
20272 (or (org-at-heading-p)
20273 (and (org-region-active-p)
20274 (save-excursion
20275 (goto-char (region-beginning))
20276 (org-at-heading-p)))))
20277 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20278 (call-interactively 'org-do-promote))
20279 ;; At an inline task.
20280 ((org-at-heading-p)
20281 (call-interactively 'org-inlinetask-promote))
20282 ((or (org-at-item-p)
20283 (and (org-region-active-p)
20284 (save-excursion
20285 (goto-char (region-beginning))
20286 (org-at-item-p))))
20287 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20288 (call-interactively 'org-outdent-item))
20289 (t (call-interactively 'backward-word))))
20291 (defun org-metaright (&optional _arg)
20292 "Demote heading, list item at point or move table column right.
20294 In front of a drawer or a block keyword, indent it correctly.
20296 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20297 `org-indent-drawer' or `org-indent-block' depending on context.
20298 With no specific context, calls the Emacs default `forward-word'.
20299 See the individual commands for more information.
20301 This function runs the hook `org-metaright-hook' as a first step,
20302 and returns at first non-nil value."
20303 (interactive "P")
20304 (cond
20305 ((run-hook-with-args-until-success 'org-metaright-hook))
20306 ((org-at-table-p) (call-interactively 'org-table-move-column))
20307 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20308 ((org-at-block-p) (call-interactively 'org-indent-block))
20309 ((org-with-limited-levels
20310 (or (org-at-heading-p)
20311 (and (org-region-active-p)
20312 (save-excursion
20313 (goto-char (region-beginning))
20314 (org-at-heading-p)))))
20315 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20316 (call-interactively 'org-do-demote))
20317 ;; At an inline task.
20318 ((org-at-heading-p)
20319 (call-interactively 'org-inlinetask-demote))
20320 ((or (org-at-item-p)
20321 (and (org-region-active-p)
20322 (save-excursion
20323 (goto-char (region-beginning))
20324 (org-at-item-p))))
20325 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20326 (call-interactively 'org-indent-item))
20327 (t (call-interactively 'forward-word))))
20329 (defun org-check-for-hidden (what)
20330 "Check if there are hidden headlines/items in the current visual line.
20331 WHAT can be either `headlines' or `items'. If the current line is
20332 an outline or item heading and it has a folded subtree below it,
20333 this function returns t, nil otherwise."
20334 (let ((re (cond
20335 ((eq what 'headlines) org-outline-regexp-bol)
20336 ((eq what 'items) (org-item-beginning-re))
20337 (t (error "This should not happen"))))
20338 beg end)
20339 (save-excursion
20340 (catch 'exit
20341 (unless (org-region-active-p)
20342 (setq beg (point-at-bol))
20343 (beginning-of-line 2)
20344 (while (and (not (eobp)) ;; this is like `next-line'
20345 (get-char-property (1- (point)) 'invisible))
20346 (beginning-of-line 2))
20347 (setq end (point))
20348 (goto-char beg)
20349 (goto-char (point-at-eol))
20350 (setq end (max end (point)))
20351 (while (re-search-forward re end t)
20352 (when (get-char-property (match-beginning 0) 'invisible)
20353 (throw 'exit t))))
20354 nil))))
20356 (defun org-metaup (&optional _arg)
20357 "Move subtree up or move table row up.
20358 Calls `org-move-subtree-up' or `org-table-move-row' or
20359 `org-move-item-up', depending on context. See the individual commands
20360 for more information."
20361 (interactive "P")
20362 (cond
20363 ((run-hook-with-args-until-success 'org-metaup-hook))
20364 ((org-region-active-p)
20365 (let* ((a (min (region-beginning) (region-end)))
20366 (b (1- (max (region-beginning) (region-end))))
20367 (c (save-excursion (goto-char a)
20368 (move-beginning-of-line 0)))
20369 (d (save-excursion (goto-char a)
20370 (move-end-of-line 0) (point))))
20371 (transpose-regions a b c d)
20372 (goto-char c)))
20373 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20374 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20375 ((org-at-item-p) (call-interactively 'org-move-item-up))
20376 (t (org-drag-element-backward))))
20378 (defun org-metadown (&optional _arg)
20379 "Move subtree down or move table row down.
20380 Calls `org-move-subtree-down' or `org-table-move-row' or
20381 `org-move-item-down', depending on context. See the individual
20382 commands for more information."
20383 (interactive "P")
20384 (cond
20385 ((run-hook-with-args-until-success 'org-metadown-hook))
20386 ((org-region-active-p)
20387 (let* ((a (min (region-beginning) (region-end)))
20388 (b (max (region-beginning) (region-end)))
20389 (c (save-excursion (goto-char b)
20390 (move-beginning-of-line 1)))
20391 (d (save-excursion (goto-char b)
20392 (move-end-of-line 1) (1+ (point)))))
20393 (transpose-regions a b c d)
20394 (goto-char d)))
20395 ((org-at-table-p) (call-interactively 'org-table-move-row))
20396 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20397 ((org-at-item-p) (call-interactively 'org-move-item-down))
20398 (t (org-drag-element-forward))))
20400 (defun org-shiftup (&optional arg)
20401 "Increase item in timestamp or increase priority of current headline.
20402 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20403 depending on context. See the individual commands for more information."
20404 (interactive "P")
20405 (cond
20406 ((run-hook-with-args-until-success 'org-shiftup-hook))
20407 ((and org-support-shift-select (org-region-active-p))
20408 (org-call-for-shift-select 'previous-line))
20409 ((org-at-timestamp-p 'lax)
20410 (call-interactively (if org-edit-timestamp-down-means-later
20411 'org-timestamp-down 'org-timestamp-up)))
20412 ((and (not (eq org-support-shift-select 'always))
20413 org-enable-priority-commands
20414 (org-at-heading-p))
20415 (call-interactively 'org-priority-up))
20416 ((and (not org-support-shift-select) (org-at-item-p))
20417 (call-interactively 'org-previous-item))
20418 ((org-clocktable-try-shift 'up arg))
20419 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20420 (org-support-shift-select
20421 (org-call-for-shift-select 'previous-line))
20422 (t (org-shiftselect-error))))
20424 (defun org-shiftdown (&optional arg)
20425 "Decrease item in timestamp or decrease priority of current headline.
20426 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20427 depending on context. See the individual commands for more information."
20428 (interactive "P")
20429 (cond
20430 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20431 ((and org-support-shift-select (org-region-active-p))
20432 (org-call-for-shift-select 'next-line))
20433 ((org-at-timestamp-p 'lax)
20434 (call-interactively (if org-edit-timestamp-down-means-later
20435 'org-timestamp-up 'org-timestamp-down)))
20436 ((and (not (eq org-support-shift-select 'always))
20437 org-enable-priority-commands
20438 (org-at-heading-p))
20439 (call-interactively 'org-priority-down))
20440 ((and (not org-support-shift-select) (org-at-item-p))
20441 (call-interactively 'org-next-item))
20442 ((org-clocktable-try-shift 'down arg))
20443 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20444 (org-support-shift-select
20445 (org-call-for-shift-select 'next-line))
20446 (t (org-shiftselect-error))))
20448 (defun org-shiftright (&optional arg)
20449 "Cycle the thing at point or in the current line, depending on context.
20450 Depending on context, this does one of the following:
20452 - switch a timestamp at point one day into the future
20453 - on a headline, switch to the next TODO keyword.
20454 - on an item, switch entire list to the next bullet type
20455 - on a property line, switch to the next allowed value
20456 - on a clocktable definition line, move time block into the future"
20457 (interactive "P")
20458 (cond
20459 ((run-hook-with-args-until-success 'org-shiftright-hook))
20460 ((and org-support-shift-select (org-region-active-p))
20461 (org-call-for-shift-select 'forward-char))
20462 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20463 ((and (not (eq org-support-shift-select 'always))
20464 (org-at-heading-p))
20465 (let ((org-inhibit-logging
20466 (not org-treat-S-cursor-todo-selection-as-state-change))
20467 (org-inhibit-blocking
20468 (not org-treat-S-cursor-todo-selection-as-state-change)))
20469 (org-call-with-arg 'org-todo 'right)))
20470 ((or (and org-support-shift-select
20471 (not (eq org-support-shift-select 'always))
20472 (org-at-item-bullet-p))
20473 (and (not org-support-shift-select) (org-at-item-p)))
20474 (org-call-with-arg 'org-cycle-list-bullet nil))
20475 ((and (not (eq org-support-shift-select 'always))
20476 (org-at-property-p))
20477 (call-interactively 'org-property-next-allowed-value))
20478 ((org-clocktable-try-shift 'right arg))
20479 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20480 (org-support-shift-select
20481 (org-call-for-shift-select 'forward-char))
20482 (t (org-shiftselect-error))))
20484 (defun org-shiftleft (&optional arg)
20485 "Cycle the thing at point or in the current line, depending on context.
20486 Depending on context, this does one of the following:
20488 - switch a timestamp at point one day into the past
20489 - on a headline, switch to the previous TODO keyword.
20490 - on an item, switch entire list to the previous bullet type
20491 - on a property line, switch to the previous allowed value
20492 - on a clocktable definition line, move time block into the past"
20493 (interactive "P")
20494 (cond
20495 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20496 ((and org-support-shift-select (org-region-active-p))
20497 (org-call-for-shift-select 'backward-char))
20498 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20499 ((and (not (eq org-support-shift-select 'always))
20500 (org-at-heading-p))
20501 (let ((org-inhibit-logging
20502 (not org-treat-S-cursor-todo-selection-as-state-change))
20503 (org-inhibit-blocking
20504 (not org-treat-S-cursor-todo-selection-as-state-change)))
20505 (org-call-with-arg 'org-todo 'left)))
20506 ((or (and org-support-shift-select
20507 (not (eq org-support-shift-select 'always))
20508 (org-at-item-bullet-p))
20509 (and (not org-support-shift-select) (org-at-item-p)))
20510 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20511 ((and (not (eq org-support-shift-select 'always))
20512 (org-at-property-p))
20513 (call-interactively 'org-property-previous-allowed-value))
20514 ((org-clocktable-try-shift 'left arg))
20515 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20516 (org-support-shift-select
20517 (org-call-for-shift-select 'backward-char))
20518 (t (org-shiftselect-error))))
20520 (defun org-shiftcontrolright ()
20521 "Switch to next TODO set."
20522 (interactive)
20523 (cond
20524 ((and org-support-shift-select (org-region-active-p))
20525 (org-call-for-shift-select 'forward-word))
20526 ((and (not (eq org-support-shift-select 'always))
20527 (org-at-heading-p))
20528 (org-call-with-arg 'org-todo 'nextset))
20529 (org-support-shift-select
20530 (org-call-for-shift-select 'forward-word))
20531 (t (org-shiftselect-error))))
20533 (defun org-shiftcontrolleft ()
20534 "Switch to previous TODO set."
20535 (interactive)
20536 (cond
20537 ((and org-support-shift-select (org-region-active-p))
20538 (org-call-for-shift-select 'backward-word))
20539 ((and (not (eq org-support-shift-select 'always))
20540 (org-at-heading-p))
20541 (org-call-with-arg 'org-todo 'previousset))
20542 (org-support-shift-select
20543 (org-call-for-shift-select 'backward-word))
20544 (t (org-shiftselect-error))))
20546 (defun org-shiftcontrolup (&optional n)
20547 "Change timestamps synchronously up in CLOCK log lines.
20548 Optional argument N tells to change by that many units."
20549 (interactive "P")
20550 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20551 (let (org-support-shift-select)
20552 (org-clock-timestamps-up n))
20553 (user-error "Not at a clock log")))
20555 (defun org-shiftcontroldown (&optional n)
20556 "Change timestamps synchronously down in CLOCK log lines.
20557 Optional argument N tells to change by that many units."
20558 (interactive "P")
20559 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20560 (let (org-support-shift-select)
20561 (org-clock-timestamps-down n))
20562 (user-error "Not at a clock log")))
20564 (defun org-increase-number-at-point (&optional inc)
20565 "Increment the number at point.
20566 With an optional prefix numeric argument INC, increment using
20567 this numeric value."
20568 (interactive "p")
20569 (if (not (number-at-point))
20570 (user-error "Not on a number")
20571 (unless inc (setq inc 1))
20572 (let ((pos (point))
20573 (beg (skip-chars-backward "-+^/*0-9eE."))
20574 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20575 (setq nap (buffer-substring-no-properties
20576 (+ pos beg) (+ pos beg end)))
20577 (delete-region (+ pos beg) (+ pos beg end))
20578 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20579 (when (org-at-table-p)
20580 (org-table-align)
20581 (org-table-end-of-field 1))))
20583 (defun org-decrease-number-at-point (&optional inc)
20584 "Decrement the number at point.
20585 With an optional prefix numeric argument INC, decrement using
20586 this numeric value."
20587 (interactive "p")
20588 (org-increase-number-at-point (- (or inc 1))))
20590 (defun org-ctrl-c-ret ()
20591 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20592 (interactive)
20593 (cond
20594 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20595 (t (call-interactively 'org-insert-heading))))
20597 (defun org-find-visible ()
20598 (let ((s (point)))
20599 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20600 (get-char-property s 'invisible)))
20602 (defun org-find-invisible ()
20603 (let ((s (point)))
20604 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20605 (not (get-char-property s 'invisible))))
20608 (defun org-copy-visible (beg end)
20609 "Copy the visible parts of the region."
20610 (interactive "r")
20611 (let ((result ""))
20612 (while (/= beg end)
20613 (when (get-char-property beg 'invisible)
20614 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20615 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20616 (setq result (concat result (buffer-substring beg next)))
20617 (setq beg next)))
20618 (kill-new result)))
20620 (defun org-copy-special ()
20621 "Copy region in table or copy current subtree.
20622 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20623 context. See the individual commands for more information."
20624 (interactive)
20625 (call-interactively
20626 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20628 (defun org-cut-special ()
20629 "Cut region in table or cut current subtree.
20630 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20631 context. See the individual commands for more information."
20632 (interactive)
20633 (call-interactively
20634 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20636 (defun org-paste-special (arg)
20637 "Paste rectangular region into table, or past subtree relative to level.
20638 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20639 See the individual commands for more information."
20640 (interactive "P")
20641 (if (org-at-table-p)
20642 (org-table-paste-rectangle)
20643 (org-paste-subtree arg)))
20645 (defun org-edit-special (&optional arg)
20646 "Call a special editor for the element at point.
20647 When at a table, call the formula editor with `org-table-edit-formulas'.
20648 When in a source code block, call `org-edit-src-code'.
20649 When in a fixed-width region, call `org-edit-fixed-width-region'.
20650 When in an export block, call `org-edit-export-block'.
20651 When in a LaTeX environment, call `org-edit-latex-environment'.
20652 When at an #+INCLUDE keyword, visit the included file.
20653 When at a footnote reference, call `org-edit-footnote-reference'
20654 On a link, call `ffap' to visit the link at point.
20655 Otherwise, return a user error."
20656 (interactive "P")
20657 (let ((element (org-element-at-point)))
20658 (barf-if-buffer-read-only)
20659 (pcase (org-element-type element)
20660 (`src-block
20661 (if (not arg) (org-edit-src-code)
20662 (let* ((info (org-babel-get-src-block-info))
20663 (lang (nth 0 info))
20664 (params (nth 2 info))
20665 (session (cdr (assq :session params))))
20666 (if (not session) (org-edit-src-code)
20667 ;; At a src-block with a session and function called with
20668 ;; an ARG: switch to the buffer related to the inferior
20669 ;; process.
20670 (switch-to-buffer
20671 (funcall (intern (concat "org-babel-prep-session:" lang))
20672 session params))))))
20673 (`keyword
20674 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20675 (org-open-link-from-string
20676 (format "[[%s]]"
20677 (expand-file-name
20678 (let ((value (org-element-property :value element)))
20679 (cond ((org-file-url-p value)
20680 (user-error "The file is specified as a URL, cannot be edited"))
20681 ((not (org-string-nw-p value))
20682 (user-error "No file to edit"))
20683 ((string-match "\\`\"\\(.*?\\)\"" value)
20684 (match-string 1 value))
20685 ((string-match "\\`[^ \t\"]\\S-*" value)
20686 (match-string 0 value))
20687 (t (user-error "No valid file specified")))))))
20688 (user-error "No special environment to edit here")))
20689 (`table
20690 (if (eq (org-element-property :type element) 'table.el)
20691 (org-edit-table.el)
20692 (call-interactively 'org-table-edit-formulas)))
20693 ;; Only Org tables contain `table-row' type elements.
20694 (`table-row (call-interactively 'org-table-edit-formulas))
20695 (`example-block (org-edit-src-code))
20696 (`export-block (org-edit-export-block))
20697 (`fixed-width (org-edit-fixed-width-region))
20698 (`latex-environment (org-edit-latex-environment))
20700 ;; No notable element at point. Though, we may be at a link or
20701 ;; a footnote reference, which are objects. Thus, scan deeper.
20702 (let ((context (org-element-context element)))
20703 (pcase (org-element-type context)
20704 (`footnote-reference (org-edit-footnote-reference))
20705 (`inline-src-block (org-edit-inline-src-code))
20706 (`link (call-interactively #'ffap))
20707 (_ (user-error "No special environment to edit here"))))))))
20709 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20710 (defun org-ctrl-c-ctrl-c (&optional arg)
20711 "Set tags in headline, or update according to changed information at point.
20713 This command does many different things, depending on context:
20715 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20716 this is what we do.
20718 - If the cursor is on a statistics cookie, update it.
20720 - If the cursor is in a headline, prompt for tags and insert them
20721 into the current line, aligned to `org-tags-column'. When called
20722 with prefix arg, realign all tags in the current buffer.
20724 - If the cursor is in one of the special #+KEYWORD lines, this
20725 triggers scanning the buffer for these lines and updating the
20726 information.
20728 - If the cursor is inside a table, realign the table. This command
20729 works even if the automatic table editor has been turned off.
20731 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20732 the entire table.
20734 - If the cursor is at a footnote reference or definition, jump to
20735 the corresponding definition or references, respectively.
20737 - If the cursor is a the beginning of a dynamic block, update it.
20739 - If the current buffer is a capture buffer, close note and file it.
20741 - If the cursor is on a <<<target>>>, update radio targets and
20742 corresponding links in this buffer.
20744 - If the cursor is on a numbered item in a plain list, renumber the
20745 ordered list.
20747 - If the cursor is on a checkbox, toggle it.
20749 - If the cursor is on a code block, evaluate it. The variable
20750 `org-confirm-babel-evaluate' can be used to control prompting
20751 before code block evaluation, by default every code block
20752 evaluation requires confirmation. Code block evaluation can be
20753 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20754 (interactive "P")
20755 (cond
20756 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20757 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20758 (org-remove-occur-highlights)
20759 (message "Temporary highlights/overlays removed from current buffer"))
20760 ((and (local-variable-p 'org-finish-function)
20761 (fboundp org-finish-function))
20762 (funcall org-finish-function))
20763 ((org-babel-hash-at-point))
20764 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20766 (let* ((context
20767 (org-element-lineage
20768 (org-element-context)
20769 ;; Limit to supported contexts.
20770 '(babel-call clock dynamic-block footnote-definition
20771 footnote-reference inline-babel-call inline-src-block
20772 inlinetask item keyword node-property paragraph
20773 plain-list property-drawer radio-target src-block
20774 statistics-cookie table table-cell table-row
20775 timestamp)
20777 (type (org-element-type context)))
20778 ;; For convenience: at the first line of a paragraph on the same
20779 ;; line as an item, apply function on that item instead.
20780 (when (eq type 'paragraph)
20781 (let ((parent (org-element-property :parent context)))
20782 (when (and (eq (org-element-type parent) 'item)
20783 (= (line-beginning-position)
20784 (org-element-property :begin parent)))
20785 (setq context parent)
20786 (setq type 'item))))
20787 ;; Act according to type of element or object at point.
20789 ;; Do nothing on a blank line, except if it is contained in
20790 ;; a src block. Hence, we first check if point is in such
20791 ;; a block and then if it is at a blank line.
20792 (pcase type
20793 ((or `inline-src-block `src-block)
20794 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20795 (org-babel-eval-wipe-error-buffer)
20796 (org-babel-execute-src-block
20797 current-prefix-arg (org-babel-get-src-block-info nil context))))
20798 ((guard (org-match-line "[ \t]*$"))
20799 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20800 (user-error
20801 (substitute-command-keys
20802 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20803 ((or `babel-call `inline-babel-call)
20804 (let ((info (org-babel-lob-get-info context)))
20805 (when info (org-babel-execute-src-block nil info))))
20806 (`clock (org-clock-update-time-maybe))
20807 (`dynamic-block
20808 (save-excursion
20809 (goto-char (org-element-property :post-affiliated context))
20810 (org-update-dblock)))
20811 (`footnote-definition
20812 (goto-char (org-element-property :post-affiliated context))
20813 (call-interactively 'org-footnote-action))
20814 (`footnote-reference (call-interactively #'org-footnote-action))
20815 ((or `headline `inlinetask)
20816 (save-excursion (goto-char (org-element-property :begin context))
20817 (call-interactively #'org-set-tags)))
20818 (`item
20819 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20820 ;; unconditionally, whereas `C-u' will toggle its presence.
20821 ;; Without a universal argument, if the item has a checkbox,
20822 ;; toggle it. Otherwise repair the list.
20823 (let* ((box (org-element-property :checkbox context))
20824 (struct (org-element-property :structure context))
20825 (old-struct (copy-tree struct))
20826 (parents (org-list-parents-alist struct))
20827 (prevs (org-list-prevs-alist struct))
20828 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20829 (org-list-set-checkbox
20830 (org-element-property :begin context) struct
20831 (cond ((equal arg '(16)) "[-]")
20832 ((and (not box) (equal arg '(4))) "[ ]")
20833 ((or (not box) (equal arg '(4))) nil)
20834 ((eq box 'on) "[ ]")
20835 (t "[X]")))
20836 ;; Mimic `org-list-write-struct' but with grabbing a return
20837 ;; value from `org-list-struct-fix-box'.
20838 (org-list-struct-fix-ind struct parents 2)
20839 (org-list-struct-fix-item-end struct)
20840 (org-list-struct-fix-bul struct prevs)
20841 (org-list-struct-fix-ind struct parents)
20842 (let ((block-item
20843 (org-list-struct-fix-box struct parents prevs orderedp)))
20844 (if (and box (equal struct old-struct))
20845 (if (equal arg '(16))
20846 (message "Checkboxes already reset")
20847 (user-error "Cannot toggle this checkbox: %s"
20848 (if (eq box 'on)
20849 "all subitems checked"
20850 "unchecked subitems")))
20851 (org-list-struct-apply-struct struct old-struct)
20852 (org-update-checkbox-count-maybe))
20853 (when block-item
20854 (message "Checkboxes were removed due to empty box at line %d"
20855 (org-current-line block-item))))))
20856 (`keyword
20857 (let ((org-inhibit-startup-visibility-stuff t)
20858 (org-startup-align-all-tables nil))
20859 (when (boundp 'org-table-coordinate-overlays)
20860 (mapc #'delete-overlay org-table-coordinate-overlays)
20861 (setq org-table-coordinate-overlays nil))
20862 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20863 (message "Local setup has been refreshed"))
20864 (`plain-list
20865 ;; At a plain list, with a double C-u argument, set
20866 ;; checkboxes of each item to "[-]", whereas a single one
20867 ;; will toggle their presence according to the state of the
20868 ;; first item in the list. Without an argument, repair the
20869 ;; list.
20870 (let* ((begin (org-element-property :contents-begin context))
20871 (beginm (move-marker (make-marker) begin))
20872 (struct (org-element-property :structure context))
20873 (old-struct (copy-tree struct))
20874 (first-box (save-excursion
20875 (goto-char begin)
20876 (looking-at org-list-full-item-re)
20877 (match-string-no-properties 3)))
20878 (new-box (cond ((equal arg '(16)) "[-]")
20879 ((equal arg '(4)) (unless first-box "[ ]"))
20880 ((equal first-box "[X]") "[ ]")
20881 (t "[X]"))))
20882 (cond
20883 (arg
20884 (dolist (pos
20885 (org-list-get-all-items
20886 begin struct (org-list-prevs-alist struct)))
20887 (org-list-set-checkbox pos struct new-box)))
20888 ((and first-box (eq (point) begin))
20889 ;; For convenience, when point is at bol on the first
20890 ;; item of the list and no argument is provided, simply
20891 ;; toggle checkbox of that item, if any.
20892 (org-list-set-checkbox begin struct new-box)))
20893 (org-list-write-struct
20894 struct (org-list-parents-alist struct) old-struct)
20895 (org-update-checkbox-count-maybe)
20896 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20897 ((or `property-drawer `node-property)
20898 (call-interactively #'org-property-action))
20899 (`radio-target
20900 (call-interactively #'org-update-radio-target-regexp))
20901 (`statistics-cookie
20902 (call-interactively #'org-update-statistics-cookies))
20903 ((or `table `table-cell `table-row)
20904 ;; At a table, recalculate every field and align it. Also
20905 ;; send the table if necessary. If the table has
20906 ;; a `table.el' type, just give up. At a table row or cell,
20907 ;; maybe recalculate line but always align table.
20908 (if (eq (org-element-property :type context) 'table.el)
20909 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20910 Use `\\[org-edit-special]' to edit table.el tables"))
20911 (if (or (eq type 'table)
20912 ;; Check if point is at a TBLFM line.
20913 (and (eq type 'table-row)
20914 (= (point) (org-element-property :end context))))
20915 (save-excursion
20916 (if (org-at-TBLFM-p)
20917 (progn (require 'org-table)
20918 (org-table-calc-current-TBLFM))
20919 (goto-char (org-element-property :contents-begin context))
20920 (org-call-with-arg 'org-table-recalculate (or arg t))
20921 (orgtbl-send-table 'maybe)))
20922 (org-table-maybe-eval-formula)
20923 (cond (arg (call-interactively #'org-table-recalculate))
20924 ((org-table-maybe-recalculate-line))
20925 (t (org-table-align))))))
20926 (`timestamp (org-timestamp-change 0 'day))
20927 ((and `nil (guard (org-at-heading-p)))
20928 ;; When point is on an unsupported object type, we can miss
20929 ;; the fact that it also is at a heading. Handle it here.
20930 (call-interactively #'org-set-tags))
20931 ((guard
20932 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20934 (user-error
20935 (substitute-command-keys
20936 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20938 (defun org-mode-restart ()
20939 (interactive)
20940 (let ((indent-status (bound-and-true-p org-indent-mode)))
20941 (funcall major-mode)
20942 (hack-local-variables)
20943 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20944 (org-indent-mode -1))
20945 (org-reset-file-cache))
20946 (message "%s restarted" major-mode))
20948 (defun org-kill-note-or-show-branches ()
20949 "Abort storing current note, or call `outline-show-branches'."
20950 (interactive)
20951 (if (not org-finish-function)
20952 (progn
20953 (outline-hide-subtree)
20954 (call-interactively 'outline-show-branches))
20955 (let ((org-note-abort t))
20956 (funcall org-finish-function))))
20958 (defun org-delete-indentation (&optional arg)
20959 "Join current line to previous and fix whitespace at join.
20961 If previous line is a headline add to headline title. Otherwise
20962 the function calls `delete-indentation'.
20964 With a non-nil optional argument, join it to the following one."
20965 (interactive "*P")
20966 (if (save-excursion
20967 (beginning-of-line (if arg 1 0))
20968 (let ((case-fold-search nil))
20969 (looking-at org-complex-heading-regexp)))
20970 ;; At headline.
20971 (let ((tags-column (when (match-beginning 5)
20972 (save-excursion (goto-char (match-beginning 5))
20973 (current-column))))
20974 (string (concat " " (progn (when arg (forward-line 1))
20975 (org-trim (delete-and-extract-region
20976 (line-beginning-position)
20977 (line-end-position)))))))
20978 (unless (bobp) (delete-region (point) (1- (point))))
20979 (goto-char (or (match-end 4)
20980 (match-beginning 5)
20981 (match-end 0)))
20982 (skip-chars-backward " \t")
20983 (save-excursion (insert string))
20984 ;; Adjust alignment of tags.
20985 (cond
20986 ((not tags-column)) ;no tags
20987 (org-auto-align-tags (org-set-tags nil t))
20988 (t (org--align-tags-here tags-column)))) ;preserve tags column
20989 (delete-indentation arg)))
20991 (defun org-open-line (n)
20992 "Insert a new row in tables, call `open-line' elsewhere.
20993 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20994 As a special case, when a document starts with a table, allow to
20995 call `open-line' on the very first character."
20996 (interactive "*p")
20997 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20998 (org-table-insert-row)
20999 (open-line n)))
21001 (defun org-return (&optional indent)
21002 "Goto next table row or insert a newline.
21004 Calls `org-table-next-row' or `newline', depending on context.
21006 When optional INDENT argument is non-nil, call
21007 `newline-and-indent' instead of `newline'.
21009 When `org-return-follows-link' is non-nil and point is on
21010 a timestamp or a link, call `org-open-at-point'. However, it
21011 will not happen if point is in a table or on a \"dead\"
21012 object (e.g., within a comment). In these case, you need to use
21013 `org-open-at-point' directly."
21014 (interactive)
21015 (let ((context (if org-return-follows-link (org-element-context)
21016 (org-element-at-point))))
21017 (cond
21018 ;; In a table, call `org-table-next-row'.
21019 ((or (and (eq (org-element-type context) 'table)
21020 (>= (point) (org-element-property :contents-begin context))
21021 (< (point) (org-element-property :contents-end context)))
21022 (org-element-lineage context '(table-row table-cell) t))
21023 (org-table-justify-field-maybe)
21024 (call-interactively #'org-table-next-row))
21025 ;; On a link or a timestamp, call `org-open-at-point' if
21026 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21027 ;; locations, e.g., in a comment, as `org-open-at-point'.
21028 ((and org-return-follows-link
21029 (or (org-in-regexp org-ts-regexp-both nil t)
21030 (org-in-regexp org-tsr-regexp-both nil t)
21031 (org-in-regexp org-any-link-re nil t)))
21032 (call-interactively #'org-open-at-point))
21033 ;; Insert newline in heading, but preserve tags.
21034 ((and (not (bolp))
21035 (save-excursion (beginning-of-line)
21036 (let ((case-fold-search nil))
21037 (looking-at org-complex-heading-regexp))))
21038 ;; At headline. Split line. However, if point is on keyword,
21039 ;; priority cookie or tags, do not break any of them: add
21040 ;; a newline after the headline instead.
21041 (let ((tags-column (and (match-beginning 5)
21042 (save-excursion (goto-char (match-beginning 5))
21043 (current-column))))
21044 (string
21045 (when (and (match-end 4) (org-point-in-group (point) 4))
21046 (delete-and-extract-region (point) (match-end 4)))))
21047 ;; Adjust tag alignment.
21048 (cond
21049 ((not (and tags-column string)))
21050 (org-auto-align-tags (org-set-tags nil t))
21051 (t (org--align-tags-here tags-column))) ;preserve tags column
21052 (end-of-line)
21053 (org-show-entry)
21054 (if indent (newline-and-indent) (newline))
21055 (when string (save-excursion (insert (org-trim string))))))
21056 ;; In a list, make sure indenting keeps trailing text within.
21057 ((and indent
21058 (not (eolp))
21059 (org-element-lineage context '(item)))
21060 (let ((trailing-data
21061 (delete-and-extract-region (point) (line-end-position))))
21062 (newline-and-indent)
21063 (save-excursion (insert trailing-data))))
21064 (t (if indent (newline-and-indent) (newline))))))
21066 (defun org-return-indent ()
21067 "Goto next table row or insert a newline and indent.
21068 Calls `org-table-next-row' or `newline-and-indent', depending on
21069 context. See the individual commands for more information."
21070 (interactive)
21071 (org-return t))
21073 (defun org-ctrl-c-tab (&optional arg)
21074 "Toggle columns width in a table, or show children.
21075 Call `org-table-toggle-column-width' if point is in a table.
21076 Otherwise, call `org-show-children'."
21077 (interactive "p")
21078 (call-interactively
21079 (if (org-at-table-p) #'org-table-toggle-column-width
21080 #'org-show-children)))
21082 (defun org-ctrl-c-star ()
21083 "Compute table, or change heading status of lines.
21084 Calls `org-table-recalculate' or `org-toggle-heading',
21085 depending on context."
21086 (interactive)
21087 (cond
21088 ((org-at-table-p)
21089 (call-interactively 'org-table-recalculate))
21091 ;; Convert all lines in region to list items
21092 (call-interactively 'org-toggle-heading))))
21094 (defun org-ctrl-c-minus ()
21095 "Insert separator line in table or modify bullet status of line.
21096 Also turns a plain line or a region of lines into list items.
21097 Calls `org-table-insert-hline', `org-toggle-item', or
21098 `org-cycle-list-bullet', depending on context."
21099 (interactive)
21100 (cond
21101 ((org-at-table-p)
21102 (call-interactively 'org-table-insert-hline))
21103 ((org-region-active-p)
21104 (call-interactively 'org-toggle-item))
21105 ((org-in-item-p)
21106 (call-interactively 'org-cycle-list-bullet))
21108 (call-interactively 'org-toggle-item))))
21110 (defun org-toggle-heading (&optional nstars)
21111 "Convert headings to normal text, or items or text to headings.
21112 If there is no active region, only convert the current line.
21114 With a `\\[universal-argument]' prefix, convert the whole list at
21115 point into heading.
21117 In a region:
21119 - If the first non blank line is a headline, remove the stars
21120 from all headlines in the region.
21122 - If it is a normal line, turn each and every normal line (i.e.,
21123 not an heading or an item) in the region into headings. If you
21124 want to convert only the first line of this region, use one
21125 universal prefix argument.
21127 - If it is a plain list item, turn all plain list items into headings.
21129 When converting a line into a heading, the number of stars is chosen
21130 such that the lines become children of the current entry. However,
21131 when a numeric prefix argument is given, its value determines the
21132 number of stars to add."
21133 (interactive "P")
21134 (let ((skip-blanks
21135 (function
21136 ;; Return beginning of first non-blank line, starting from
21137 ;; line at POS.
21138 (lambda (pos)
21139 (save-excursion
21140 (goto-char pos)
21141 (while (org-at-comment-p) (forward-line))
21142 (skip-chars-forward " \r\t\n")
21143 (point-at-bol)))))
21144 beg end toggled)
21145 ;; Determine boundaries of changes. If a universal prefix has
21146 ;; been given, put the list in a region. If region ends at a bol,
21147 ;; do not consider the last line to be in the region.
21149 (when (and current-prefix-arg (org-at-item-p))
21150 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21151 (org-mark-element))
21153 (if (org-region-active-p)
21154 (setq beg (funcall skip-blanks (region-beginning))
21155 end (copy-marker (save-excursion
21156 (goto-char (region-end))
21157 (if (bolp) (point) (point-at-eol)))))
21158 (setq beg (funcall skip-blanks (point-at-bol))
21159 end (copy-marker (point-at-eol))))
21160 ;; Ensure inline tasks don't count as headings.
21161 (org-with-limited-levels
21162 (save-excursion
21163 (goto-char beg)
21164 (cond
21165 ;; Case 1. Started at an heading: de-star headings.
21166 ((org-at-heading-p)
21167 (while (< (point) end)
21168 (when (org-at-heading-p t)
21169 (looking-at org-outline-regexp) (replace-match "")
21170 (setq toggled t))
21171 (forward-line)))
21172 ;; Case 2. Started at an item: change items into headlines.
21173 ;; One star will be added by `org-list-to-subtree'.
21174 ((org-at-item-p)
21175 (while (< (point) end)
21176 (when (org-at-item-p)
21177 ;; Pay attention to cases when region ends before list.
21178 (let* ((struct (org-list-struct))
21179 (list-end
21180 (min (org-list-get-bottom-point struct) (1+ end))))
21181 (save-restriction
21182 (narrow-to-region (point) list-end)
21183 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21184 (setq toggled t))
21185 (forward-line)))
21186 ;; Case 3. Started at normal text: make every line an heading,
21187 ;; skipping headlines and items.
21188 (t (let* ((stars
21189 (make-string
21190 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21191 (add-stars
21192 (cond (nstars "") ; stars from prefix only
21193 ((equal stars "") "*") ; before first heading
21194 (org-odd-levels-only "**") ; inside heading, odd
21195 (t "*"))) ; inside heading, oddeven
21196 (rpl (concat stars add-stars " "))
21197 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21198 (while (< (point) (if (equal nstars '(4)) lend end))
21199 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21200 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21201 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21202 (forward-line)))))))
21203 (unless toggled (message "Cannot toggle heading from here"))))
21205 (defun org-meta-return (&optional arg)
21206 "Insert a new heading or wrap a region in a table.
21207 Calls `org-insert-heading', `org-insert-item' or
21208 `org-table-wrap-region', depending on context. When called with
21209 an argument, unconditionally call `org-insert-heading'."
21210 (interactive "P")
21211 (org-check-before-invisible-edit 'insert)
21212 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21213 (call-interactively (cond (arg #'org-insert-heading)
21214 ((org-at-table-p) #'org-table-wrap-region)
21215 ((org-in-item-p) #'org-insert-item)
21216 (t #'org-insert-heading)))))
21218 ;;; Menu entries
21220 (defsubst org-in-subtree-not-table-p ()
21221 "Are we in a subtree and not in a table?"
21222 (and (not (org-before-first-heading-p))
21223 (not (org-at-table-p))))
21225 ;; Define the Org mode menus
21226 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21227 '("Tbl"
21228 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21229 ["Next Field" org-cycle (org-at-table-p)]
21230 ["Previous Field" org-shifttab (org-at-table-p)]
21231 ["Next Row" org-return (org-at-table-p)]
21232 "--"
21233 ["Blank Field" org-table-blank-field (org-at-table-p)]
21234 ["Edit Field" org-table-edit-field (org-at-table-p)]
21235 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21236 "--"
21237 ("Column"
21238 ["Move Column Left" org-metaleft (org-at-table-p)]
21239 ["Move Column Right" org-metaright (org-at-table-p)]
21240 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21241 ["Insert Column" org-shiftmetaright (org-at-table-p)]
21242 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
21243 ("Row"
21244 ["Move Row Up" org-metaup (org-at-table-p)]
21245 ["Move Row Down" org-metadown (org-at-table-p)]
21246 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21247 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21248 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21249 "--"
21250 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21251 ("Rectangle"
21252 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21253 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21254 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21255 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21256 "--"
21257 ("Calculate"
21258 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21259 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21260 ["Edit Formulas" org-edit-special (org-at-table-p)]
21261 "--"
21262 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21263 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21264 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21265 "--"
21266 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21267 "--"
21268 ["Sum Column/Rectangle" org-table-sum
21269 (or (org-at-table-p) (org-region-active-p))]
21270 ["Which Column?" org-table-current-column (org-at-table-p)])
21271 ["Debug Formulas"
21272 org-table-toggle-formula-debugger
21273 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21274 ["Show Col/Row Numbers"
21275 org-table-toggle-coordinate-overlays
21276 :style toggle
21277 :selected (bound-and-true-p org-table-overlay-coordinates)]
21278 "--"
21279 ["Create" org-table-create (not (org-at-table-p))]
21280 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21281 ["Import from File" org-table-import (not (org-at-table-p))]
21282 ["Export to File" org-table-export (org-at-table-p)]
21283 "--"
21284 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21285 "--"
21286 ("Plot"
21287 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21288 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21290 (easy-menu-define org-org-menu org-mode-map "Org menu"
21291 '("Org"
21292 ("Show/Hide"
21293 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21294 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21295 ["Sparse Tree..." org-sparse-tree t]
21296 ["Reveal Context" org-reveal t]
21297 ["Show All" outline-show-all t]
21298 "--"
21299 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21300 "--"
21301 ["New Heading" org-insert-heading t]
21302 ("Navigate Headings"
21303 ["Up" outline-up-heading t]
21304 ["Next" outline-next-visible-heading t]
21305 ["Previous" outline-previous-visible-heading t]
21306 ["Next Same Level" outline-forward-same-level t]
21307 ["Previous Same Level" outline-backward-same-level t]
21308 "--"
21309 ["Jump" org-goto t])
21310 ("Edit Structure"
21311 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21312 "--"
21313 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21314 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21315 "--"
21316 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21317 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21318 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21319 "--"
21320 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21321 "--"
21322 ["Copy visible text" org-copy-visible t]
21323 "--"
21324 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21325 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21326 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21327 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21328 "--"
21329 ["Sort Region/Children" org-sort t]
21330 "--"
21331 ["Convert to odd levels" org-convert-to-odd-levels t]
21332 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21333 ("Editing"
21334 ["Emphasis..." org-emphasize t]
21335 ["Edit Source Example" org-edit-special t]
21336 "--"
21337 ["Footnote new/jump" org-footnote-action t]
21338 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21339 ("Archive"
21340 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21341 "--"
21342 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21343 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21344 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21346 "--"
21347 ("Hyperlinks"
21348 ["Store Link (Global)" org-store-link t]
21349 ["Find existing link to here" org-occur-link-in-agenda-files t]
21350 ["Insert Link" org-insert-link t]
21351 ["Follow Link" org-open-at-point t]
21352 "--"
21353 ["Next link" org-next-link t]
21354 ["Previous link" org-previous-link t]
21355 "--"
21356 ["Descriptive Links"
21357 org-toggle-link-display
21358 :style radio
21359 :selected org-descriptive-links
21361 ["Literal Links"
21362 org-toggle-link-display
21363 :style radio
21364 :selected (not org-descriptive-links)])
21365 "--"
21366 ("TODO Lists"
21367 ["TODO/DONE/-" org-todo t]
21368 ("Select keyword"
21369 ["Next keyword" org-shiftright (org-at-heading-p)]
21370 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21371 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21372 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21373 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21374 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21375 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21376 "--"
21377 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21378 :selected org-enforce-todo-dependencies :style toggle :active t]
21379 "Settings for tree at point"
21380 ["Do Children sequentially" org-toggle-ordered-property :style radio
21381 :selected (org-entry-get nil "ORDERED")
21382 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21383 ["Do Children parallel" org-toggle-ordered-property :style radio
21384 :selected (not (org-entry-get nil "ORDERED"))
21385 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21386 "--"
21387 ["Set Priority" org-priority t]
21388 ["Priority Up" org-shiftup t]
21389 ["Priority Down" org-shiftdown t]
21390 "--"
21391 ["Get news from all feeds" org-feed-update-all t]
21392 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21393 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21394 ("TAGS and Properties"
21395 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21396 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21397 "--"
21398 ["Set property" org-set-property (not (org-before-first-heading-p))]
21399 ["Column view of properties" org-columns t]
21400 ["Insert Column View DBlock" org-columns-insert-dblock t])
21401 ("Dates and Scheduling"
21402 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21403 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21404 ("Change Date"
21405 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21406 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21407 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21408 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21409 ["Compute Time Range" org-evaluate-time-range t]
21410 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21411 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21412 "--"
21413 ["Custom time format" org-toggle-time-stamp-overlays
21414 :style radio :selected org-display-custom-times]
21415 "--"
21416 ["Goto Calendar" org-goto-calendar t]
21417 ["Date from Calendar" org-date-from-calendar t]
21418 "--"
21419 ["Start/Restart Timer" org-timer-start t]
21420 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21421 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21422 ["Insert Timer String" org-timer t]
21423 ["Insert Timer Item" org-timer-item t])
21424 ("Logging work"
21425 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21426 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21427 ["Clock out" org-clock-out t]
21428 ["Clock cancel" org-clock-cancel t]
21429 "--"
21430 ["Mark as default task" org-clock-mark-default-task t]
21431 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21432 ["Goto running clock" org-clock-goto t]
21433 "--"
21434 ["Display times" org-clock-display t]
21435 ["Create clock table" org-clock-report t]
21436 "--"
21437 ["Record DONE time"
21438 (progn (setq org-log-done (not org-log-done))
21439 (message "Switching to %s will %s record a timestamp"
21440 (car org-done-keywords)
21441 (if org-log-done "automatically" "not")))
21442 :style toggle :selected org-log-done])
21443 "--"
21444 ["Agenda Command..." org-agenda t]
21445 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21446 ("File List for Agenda")
21447 ("Special views current file"
21448 ["TODO Tree" org-show-todo-tree t]
21449 ["Check Deadlines" org-check-deadlines t]
21450 ["Tags/Property tree" org-match-sparse-tree t])
21451 "--"
21452 ["Export/Publish..." org-export-dispatch t]
21453 ("LaTeX"
21454 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21455 :selected org-cdlatex-mode]
21456 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21457 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21458 ["Modify math symbol" org-cdlatex-math-modify
21459 (org-inside-LaTeX-fragment-p)]
21460 ["Insert citation" org-reftex-citation t])
21461 "--"
21462 ("MobileOrg"
21463 ["Push Files and Views" org-mobile-push t]
21464 ["Get Captured and Flagged" org-mobile-pull t]
21465 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21466 "--"
21467 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21468 "--"
21469 ("Documentation"
21470 ["Show Version" org-version t]
21471 ["Info Documentation" org-info t])
21472 ("Customize"
21473 ["Browse Org Group" org-customize t]
21474 "--"
21475 ["Expand This Menu" org-create-customize-menu
21476 (fboundp 'customize-menu-create)])
21477 ["Send bug report" org-submit-bug-report t]
21478 "--"
21479 ("Refresh/Reload"
21480 ["Refresh setup current buffer" org-mode-restart t]
21481 ["Reload Org (after update)" org-reload t]
21482 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21485 (defun org-info (&optional node)
21486 "Read documentation for Org in the info system.
21487 With optional NODE, go directly to that node."
21488 (interactive)
21489 (info (format "(org)%s" (or node ""))))
21491 ;;;###autoload
21492 (defun org-submit-bug-report ()
21493 "Submit a bug report on Org via mail.
21495 Don't hesitate to report any problems or inaccurate documentation.
21497 If you don't have setup sending mail from (X)Emacs, please copy the
21498 output buffer into your mail program, as it gives us important
21499 information about your Org version and configuration."
21500 (interactive)
21501 (require 'reporter)
21502 (defvar reporter-prompt-for-summary-p)
21503 (org-load-modules-maybe)
21504 (org-require-autoloaded-modules)
21505 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21506 (reporter-submit-bug-report
21507 "emacs-orgmode@gnu.org"
21508 (org-version nil 'full)
21509 (let (list)
21510 (save-window-excursion
21511 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21512 (delete-other-windows)
21513 (erase-buffer)
21514 (insert "You are about to submit a bug report to the Org mailing list.
21516 We would like to add your full Org and Outline configuration to the
21517 bug report. This greatly simplifies the work of the maintainer and
21518 other experts on the mailing list.
21520 HOWEVER, some variables you have customized may contain private
21521 information. The names of customers, colleagues, or friends, might
21522 appear in the form of file names, tags, todo states, or search strings.
21523 If you answer yes to the prompt, you might want to check and remove
21524 such private information before sending the email.")
21525 (add-text-properties (point-min) (point-max) '(face org-warning))
21526 (when (yes-or-no-p "Include your Org configuration ")
21527 (mapatoms
21528 (lambda (v)
21529 (and (boundp v)
21530 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21531 (or (and (symbol-value v)
21532 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21533 (and
21534 (get v 'custom-type) (get v 'standard-value)
21535 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21536 (push v list)))))
21537 (kill-buffer (get-buffer "*Warn about privacy*"))
21538 list))
21539 nil nil
21540 "Remember to cover the basics, that is, what you expected to happen and
21541 what in fact did happen. You don't know how to make a good report? See
21543 http://orgmode.org/manual/Feedback.html#Feedback
21545 Your bug report will be posted to the Org mailing list.
21546 ------------------------------------------------------------------------")
21547 (save-excursion
21548 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21549 (replace-match "\\1Bug: \\3 [\\2]")))))
21552 (defun org-install-agenda-files-menu ()
21553 (let ((bl (buffer-list)))
21554 (save-excursion
21555 (while bl
21556 (set-buffer (pop bl))
21557 (when (derived-mode-p 'org-mode) (setq bl nil)))
21558 (when (derived-mode-p 'org-mode)
21559 (easy-menu-change
21560 '("Org") "File List for Agenda"
21561 (append
21562 (list
21563 ["Edit File List" (org-edit-agenda-file-list) t]
21564 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21565 ["Remove Current File from List" org-remove-file t]
21566 ["Cycle through agenda files" org-cycle-agenda-files t]
21567 ["Occur in all agenda files" org-occur-in-agenda-files t]
21568 "--")
21569 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21571 ;;;; Documentation
21573 (defun org-require-autoloaded-modules ()
21574 (interactive)
21575 (mapc #'require
21576 '(org-agenda org-archive org-attach org-clock org-colview org-id
21577 org-table org-timer)))
21579 ;;;###autoload
21580 (defun org-reload (&optional uncompiled)
21581 "Reload all org lisp files.
21582 With prefix arg UNCOMPILED, load the uncompiled versions."
21583 (interactive "P")
21584 (require 'loadhist)
21585 (let* ((org-dir (org-find-library-dir "org"))
21586 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21587 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21588 (remove-re (format "\\`%s\\'"
21589 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21590 (feats (delete-dups
21591 (mapcar 'file-name-sans-extension
21592 (mapcar 'file-name-nondirectory
21593 (delq nil
21594 (mapcar 'feature-file
21595 features))))))
21596 (lfeat (append
21597 (sort
21598 (setq feats
21599 (delq nil (mapcar
21600 (lambda (f)
21601 (if (and (string-match feature-re f)
21602 (not (string-match remove-re f)))
21603 f nil))
21604 feats)))
21605 'string-lessp)
21606 (list "org-version" "org")))
21607 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21608 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21609 load-uncore load-misses)
21610 (setq load-misses
21611 (delq 't
21612 (mapcar (lambda (f)
21613 (or (org-load-noerror-mustsuffix (concat org-dir f))
21614 (and (string= org-dir contrib-dir)
21615 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21616 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21617 (add-to-list 'load-uncore f 'append)
21620 lfeat)))
21621 (when load-uncore
21622 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21623 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21624 (if load-misses
21625 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21626 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21627 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21629 ;;;###autoload
21630 (defun org-customize ()
21631 "Call the customize function with org as argument."
21632 (interactive)
21633 (org-load-modules-maybe)
21634 (org-require-autoloaded-modules)
21635 (customize-browse 'org))
21637 (defun org-create-customize-menu ()
21638 "Create a full customization menu for Org mode, insert it into the menu."
21639 (interactive)
21640 (org-load-modules-maybe)
21641 (org-require-autoloaded-modules)
21642 (if (fboundp 'customize-menu-create)
21643 (progn
21644 (easy-menu-change
21645 '("Org") "Customize"
21646 `(["Browse Org group" org-customize t]
21647 "--"
21648 ,(customize-menu-create 'org)
21649 ["Set" Custom-set t]
21650 ["Save" Custom-save t]
21651 ["Reset to Current" Custom-reset-current t]
21652 ["Reset to Saved" Custom-reset-saved t]
21653 ["Reset to Standard Settings" Custom-reset-standard t]))
21654 (message "\"Org\"-menu now contains full customization menu"))
21655 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21657 ;;;; Miscellaneous stuff
21659 ;;; Generally useful functions
21661 (defun org-get-at-eol (property n)
21662 "Get text property PROPERTY at the end of line less N characters."
21663 (get-text-property (- (point-at-eol) n) property))
21665 (defun org-find-text-property-in-string (prop s)
21666 "Return the first non-nil value of property PROP in string S."
21667 (or (get-text-property 0 prop s)
21668 (get-text-property (or (next-single-property-change 0 prop s) 0)
21669 prop s)))
21671 (defun org-display-warning (message)
21672 "Display the given MESSAGE as a warning."
21673 (display-warning 'org message :warning))
21675 (defun org-eval (form)
21676 "Eval FORM and return result."
21677 (condition-case error
21678 (eval form)
21679 (error (format "%%![Error: %s]" error))))
21681 (defun org-in-clocktable-p ()
21682 "Check if the cursor is in a clocktable."
21683 (let ((pos (point)) start)
21684 (save-excursion
21685 (end-of-line 1)
21686 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21687 (setq start (match-beginning 0))
21688 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21689 (>= (match-end 0) pos)
21690 start))))
21692 (defun org-in-verbatim-emphasis ()
21693 (save-match-data
21694 (and (org-in-regexp org-verbatim-re 2)
21695 (>= (point) (match-beginning 3))
21696 (<= (point) (match-end 4)))))
21698 (defun org-overlay-display (ovl text &optional face evap)
21699 "Make overlay OVL display TEXT with face FACE."
21700 (overlay-put ovl 'display text)
21701 (if face (overlay-put ovl 'face face))
21702 (if evap (overlay-put ovl 'evaporate t)))
21704 (defun org-overlay-before-string (ovl text &optional face evap)
21705 "Make overlay OVL display TEXT with face FACE."
21706 (if face (org-add-props text nil 'face face))
21707 (overlay-put ovl 'before-string text)
21708 (if evap (overlay-put ovl 'evaporate t)))
21710 (defun org-find-overlays (prop &optional pos delete)
21711 "Find all overlays specifying PROP at POS or point.
21712 If DELETE is non-nil, delete all those overlays."
21713 (let (found)
21714 (dolist (ov (overlays-at (or pos (point))) found)
21715 (cond ((not (overlay-get ov prop)))
21716 (delete (delete-overlay ov))
21717 (t (push ov found))))))
21719 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21720 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21721 (if (and marker (marker-buffer marker)
21722 (buffer-live-p (marker-buffer marker)))
21723 (progn
21724 (pop-to-buffer-same-window (marker-buffer marker))
21725 (when (or (> marker (point-max)) (< marker (point-min)))
21726 (widen))
21727 (goto-char marker)
21728 (org-show-context 'org-goto))
21729 (if bookmark
21730 (bookmark-jump bookmark)
21731 (error "Cannot find location"))))
21733 (defun org-quote-csv-field (s)
21734 "Quote field for inclusion in CSV material."
21735 (if (string-match "[\",]" s)
21736 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21739 (defun org-force-self-insert (N)
21740 "Needed to enforce self-insert under remapping."
21741 (interactive "p")
21742 (self-insert-command N))
21744 (defun org-shorten-string (s maxlength)
21745 "Shorten string S so that it is no longer than MAXLENGTH characters.
21746 If the string is shorter or has length MAXLENGTH, just return the
21747 original string. If it is longer, the functions finds a space in the
21748 string, breaks this string off at that locations and adds three dots
21749 as ellipsis. Including the ellipsis, the string will not be longer
21750 than MAXLENGTH. If finding a good breaking point in the string does
21751 not work, the string is just chopped off in the middle of a word
21752 if necessary."
21753 (if (<= (length s) maxlength)
21755 (let* ((n (max (- maxlength 4) 1))
21756 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21757 (if (string-match re s)
21758 (concat (match-string 1 s) "...")
21759 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21761 (defun org-get-indentation (&optional line)
21762 "Get the indentation of the current line, interpreting tabs.
21763 When LINE is given, assume it represents a line and compute its indentation."
21764 (if line
21765 (when (string-match "^ *" (org-remove-tabs line))
21766 (match-end 0))
21767 (save-excursion
21768 (beginning-of-line 1)
21769 (skip-chars-forward " \t")
21770 (current-column))))
21772 (defun org-get-string-indentation (s)
21773 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21774 (let ((n -1) (i 0) (w tab-width) c)
21775 (catch 'exit
21776 (while (< (setq n (1+ n)) (length s))
21777 (setq c (aref s n))
21778 (cond ((= c ?\ ) (setq i (1+ i)))
21779 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21780 (t (throw 'exit t)))))
21783 (defun org-remove-tabs (s &optional width)
21784 "Replace tabulators in S with spaces.
21785 Assumes that s is a single line, starting in column 0."
21786 (setq width (or width tab-width))
21787 (while (string-match "\t" s)
21788 (setq s (replace-match
21789 (make-string
21790 (- (* width (/ (+ (match-beginning 0) width) width))
21791 (match-beginning 0)) ?\ )
21792 t t s)))
21795 (defun org-fix-indentation (line ind)
21796 "Fix indentation in LINE.
21797 IND is a cons cell with target and minimum indentation.
21798 If the current indentation in LINE is smaller than the minimum,
21799 leave it alone. If it is larger than ind, set it to the target."
21800 (let* ((l (org-remove-tabs line))
21801 (i (org-get-indentation l))
21802 (i1 (car ind)) (i2 (cdr ind)))
21803 (when (>= i i2) (setq l (substring line i2)))
21804 (if (> i1 0)
21805 (concat (make-string i1 ?\ ) l)
21806 l)))
21808 (defun org-remove-indentation (code &optional n)
21809 "Remove maximum common indentation in string CODE and return it.
21810 N may optionally be the number of columns to remove. Return CODE
21811 as-is if removal failed."
21812 (with-temp-buffer
21813 (insert code)
21814 (if (org-do-remove-indentation n) (buffer-string) code)))
21816 (defun org-do-remove-indentation (&optional n)
21817 "Remove the maximum common indentation from the buffer.
21818 When optional argument N is a positive integer, remove exactly
21819 that much characters from indentation, if possible. Return nil
21820 if it fails."
21821 (catch :exit
21822 (goto-char (point-min))
21823 ;; Find maximum common indentation, if not specified.
21824 (let ((n (or n
21825 (let ((min-ind (point-max)))
21826 (save-excursion
21827 (while (re-search-forward "^[ \t]*\\S-" nil t)
21828 (let ((ind (1- (current-column))))
21829 (if (zerop ind) (throw :exit nil)
21830 (setq min-ind (min min-ind ind))))))
21831 min-ind))))
21832 (if (zerop n) (throw :exit nil)
21833 ;; Remove exactly N indentation, but give up if not possible.
21834 (while (not (eobp))
21835 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21836 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21837 ((< ind n) (throw :exit nil))
21838 (t (indent-line-to (- ind n))))
21839 (forward-line)))
21840 ;; Signal success.
21841 t))))
21843 (defun org-fill-template (template alist)
21844 "Find each %key of ALIST in TEMPLATE and replace it."
21845 (let ((case-fold-search nil))
21846 (dolist (entry (sort (copy-sequence alist)
21847 (lambda (a b) (< (length (car a)) (length (car b))))))
21848 (setq template
21849 (replace-regexp-in-string
21850 (concat "%" (regexp-quote (car entry)))
21851 (or (cdr entry) "") template t t)))
21852 template))
21854 (defun org-base-buffer (buffer)
21855 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21856 (if (not buffer)
21857 buffer
21858 (or (buffer-base-buffer buffer)
21859 buffer)))
21861 (defun org-wrap (string &optional width lines)
21862 "Wrap string to either a number of lines, or a width in characters.
21863 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21864 that costs. If there is a word longer than WIDTH, the text is actually
21865 wrapped to the length of that word.
21866 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21867 many lines, whatever width that takes.
21868 The return value is a list of lines, without newlines at the end."
21869 (let* ((words (split-string string))
21870 (maxword (apply 'max (mapcar 'org-string-width words)))
21871 w ll)
21872 (cond (width
21873 (org-do-wrap words (max maxword width)))
21874 (lines
21875 (setq w maxword)
21876 (setq ll (org-do-wrap words maxword))
21877 (if (<= (length ll) lines)
21879 (setq ll words)
21880 (while (> (length ll) lines)
21881 (setq w (1+ w))
21882 (setq ll (org-do-wrap words w)))
21883 ll))
21884 (t (error "Cannot wrap this")))))
21886 (defun org-do-wrap (words width)
21887 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21888 (let (lines line)
21889 (while words
21890 (setq line (pop words))
21891 (while (and words (< (+ (length line) (length (car words))) width))
21892 (setq line (concat line " " (pop words))))
21893 (setq lines (push line lines)))
21894 (nreverse lines)))
21896 (defun org-quote-vert (s)
21897 "Replace \"|\" with \"\\vert\"."
21898 (while (string-match "|" s)
21899 (setq s (replace-match "\\vert" t t s)))
21902 (defun org-uuidgen-p (s)
21903 "Is S an ID created by UUIDGEN?"
21904 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21906 (defun org-in-src-block-p (&optional inside)
21907 "Whether point is in a code source block.
21908 When INSIDE is non-nil, don't consider we are within a src block
21909 when point is at #+BEGIN_SRC or #+END_SRC."
21910 (let ((case-fold-search t))
21911 (or (and (eq (get-char-property (point) 'src-block) t))
21912 (and (not inside)
21913 (save-match-data
21914 (save-excursion
21915 (beginning-of-line)
21916 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21918 (defun org-context ()
21919 "Return a list of contexts of the current cursor position.
21920 If several contexts apply, all are returned.
21921 Each context entry is a list with a symbol naming the context, and
21922 two positions indicating start and end of the context. Possible
21923 contexts are:
21925 :headline anywhere in a headline
21926 :headline-stars on the leading stars in a headline
21927 :todo-keyword on a TODO keyword (including DONE) in a headline
21928 :tags on the TAGS in a headline
21929 :priority on the priority cookie in a headline
21930 :item on the first line of a plain list item
21931 :item-bullet on the bullet/number of a plain list item
21932 :checkbox on the checkbox in a plain list item
21933 :table in an Org table
21934 :table-special on a special filed in a table
21935 :table-table in a table.el table
21936 :clocktable in a clocktable
21937 :src-block in a source block
21938 :link on a hyperlink
21939 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21940 :target on a <<target>>
21941 :radio-target on a <<<radio-target>>>
21942 :latex-fragment on a LaTeX fragment
21943 :latex-preview on a LaTeX fragment with overlaid preview image
21945 This function expects the position to be visible because it uses font-lock
21946 faces as a help to recognize the following contexts: :table-special, :link,
21947 and :keyword."
21948 (let* ((f (get-text-property (point) 'face))
21949 (faces (if (listp f) f (list f)))
21950 (case-fold-search t)
21951 (p (point)) clist o)
21952 ;; First the large context
21953 (cond
21954 ((org-at-heading-p t)
21955 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21956 (when (progn
21957 (beginning-of-line 1)
21958 (looking-at org-todo-line-tags-regexp))
21959 (push (org-point-in-group p 1 :headline-stars) clist)
21960 (push (org-point-in-group p 2 :todo-keyword) clist)
21961 (push (org-point-in-group p 4 :tags) clist))
21962 (goto-char p)
21963 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21964 (when (looking-at "\\[#[A-Z0-9]\\]")
21965 (push (org-point-in-group p 0 :priority) clist)))
21967 ((org-at-item-p)
21968 (push (org-point-in-group p 2 :item-bullet) clist)
21969 (push (list :item (point-at-bol)
21970 (save-excursion (org-end-of-item) (point)))
21971 clist)
21972 (and (org-at-item-checkbox-p)
21973 (push (org-point-in-group p 0 :checkbox) clist)))
21975 ((org-at-table-p)
21976 (push (list :table (org-table-begin) (org-table-end)) clist)
21977 (when (memq 'org-formula faces)
21978 (push (list :table-special
21979 (previous-single-property-change p 'face)
21980 (next-single-property-change p 'face)) clist)))
21981 ((org-at-table-p 'any)
21982 (push (list :table-table) clist)))
21983 (goto-char p)
21985 (let ((case-fold-search t))
21986 ;; New the "medium" contexts: clocktables, source blocks
21987 (cond ((org-in-clocktable-p)
21988 (push (list :clocktable
21989 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21990 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21991 (match-beginning 1))
21992 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21993 (match-end 0))) clist))
21994 ((org-in-src-block-p)
21995 (push (list :src-block
21996 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21997 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21998 (match-beginning 1))
21999 (and (search-forward "#+END_SRC" nil t)
22000 (match-beginning 0))) clist))))
22001 (goto-char p)
22003 ;; Now the small context
22004 (cond
22005 ((org-at-timestamp-p)
22006 (push (org-point-in-group p 0 :timestamp) clist))
22007 ((memq 'org-link faces)
22008 (push (list :link
22009 (previous-single-property-change p 'face)
22010 (next-single-property-change p 'face)) clist))
22011 ((memq 'org-special-keyword faces)
22012 (push (list :keyword
22013 (previous-single-property-change p 'face)
22014 (next-single-property-change p 'face)) clist))
22015 ((org-at-target-p)
22016 (push (org-point-in-group p 0 :target) clist)
22017 (goto-char (1- (match-beginning 0)))
22018 (when (looking-at org-radio-target-regexp)
22019 (push (org-point-in-group p 0 :radio-target) clist))
22020 (goto-char p))
22021 ((setq o (cl-some
22022 (lambda (o)
22023 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22025 (overlays-at (point))))
22026 (push (list :latex-fragment
22027 (overlay-start o) (overlay-end o)) clist)
22028 (push (list :latex-preview
22029 (overlay-start o) (overlay-end o)) clist))
22030 ((org-inside-LaTeX-fragment-p)
22031 ;; FIXME: positions wrong.
22032 (push (list :latex-fragment (point) (point)) clist)))
22034 (setq clist (nreverse (delq nil clist)))
22035 clist))
22037 (defun org-in-regexp (regexp &optional nlines visually)
22038 "Check if point is inside a match of REGEXP.
22040 Normally only the current line is checked, but you can include
22041 NLINES extra lines around point into the search. If VISUALLY is
22042 set, require that the cursor is not after the match but really
22043 on, so that the block visually is on the match.
22045 Return nil or a cons cell (BEG . END) where BEG and END are,
22046 respectively, the positions at the beginning and the end of the
22047 match."
22048 (catch :exit
22049 (let ((pos (point))
22050 (eol (line-end-position (if nlines (1+ nlines) 1))))
22051 (save-excursion
22052 (beginning-of-line (- 1 (or nlines 0)))
22053 (while (and (re-search-forward regexp eol t)
22054 (<= (match-beginning 0) pos))
22055 (let ((end (match-end 0)))
22056 (when (or (> end pos) (and (= end pos) (not visually)))
22057 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22059 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22060 "Non-nil when point is between matches of START-RE and END-RE.
22062 Also return a non-nil value when point is on one of the matches.
22064 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22065 buffer positions. Default values are the positions of headlines
22066 surrounding the point.
22068 The functions returns a cons cell whose car (resp. cdr) is the
22069 position before START-RE (resp. after END-RE)."
22070 (save-match-data
22071 (let ((pos (point))
22072 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22073 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22074 beg end)
22075 (save-excursion
22076 ;; Point is on a block when on START-RE or if START-RE can be
22077 ;; found before it...
22078 (and (or (org-in-regexp start-re)
22079 (re-search-backward start-re limit-up t))
22080 (setq beg (match-beginning 0))
22081 ;; ... and END-RE after it...
22082 (goto-char (match-end 0))
22083 (re-search-forward end-re limit-down t)
22084 (> (setq end (match-end 0)) pos)
22085 ;; ... without another START-RE in-between.
22086 (goto-char (match-beginning 0))
22087 (not (re-search-backward start-re (1+ beg) t))
22088 ;; Return value.
22089 (cons beg end))))))
22091 (defun org-in-block-p (names)
22092 "Non-nil when point belongs to a block whose name belongs to NAMES.
22094 NAMES is a list of strings containing names of blocks.
22096 Return first block name matched, or nil. Beware that in case of
22097 nested blocks, the returned name may not belong to the closest
22098 block from point."
22099 (save-match-data
22100 (catch 'exit
22101 (let ((case-fold-search t)
22102 (lim-up (save-excursion (outline-previous-heading)))
22103 (lim-down (save-excursion (outline-next-heading))))
22104 (dolist (name names)
22105 (let ((n (regexp-quote name)))
22106 (when (org-between-regexps-p
22107 (concat "^[ \t]*#\\+begin_" n)
22108 (concat "^[ \t]*#\\+end_" n)
22109 lim-up lim-down)
22110 (throw 'exit n)))))
22111 nil)))
22113 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22114 "Call `multi-occur' with buffers for all agenda files."
22115 (interactive "sOrg-files matching: ")
22116 (let* ((files (org-agenda-files))
22117 (tnames (mapcar #'file-truename files))
22118 (extra org-agenda-text-search-extra-files))
22119 (when (eq (car extra) 'agenda-archives)
22120 (setq extra (cdr extra))
22121 (setq files (org-add-archive-files files)))
22122 (dolist (f extra)
22123 (unless (member (file-truename f) tnames)
22124 (unless (member f files) (setq files (append files (list f))))
22125 (setq tnames (append tnames (list (file-truename f))))))
22126 (multi-occur
22127 (mapcar (lambda (x)
22128 (with-current-buffer
22129 ;; FIXME: Why not just (find-file-noselect x)?
22130 ;; Is it to avoid the "revert buffer" prompt?
22131 (or (get-file-buffer x) (find-file-noselect x))
22132 (widen)
22133 (current-buffer)))
22134 files)
22135 regexp)))
22137 (add-hook 'occur-mode-find-occurrence-hook
22138 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22140 (defun org-occur-link-in-agenda-files ()
22141 "Create a link and search for it in the agendas.
22142 The link is not stored in `org-stored-links', it is just created
22143 for the search purpose."
22144 (interactive)
22145 (let ((link (condition-case nil
22146 (org-store-link nil)
22147 (error "Unable to create a link to here"))))
22148 (org-occur-in-agenda-files (regexp-quote link))))
22150 (defun org-reverse-string (string)
22151 "Return the reverse of STRING."
22152 (apply 'string (reverse (string-to-list string))))
22154 ;; defsubst org-uniquify must be defined before first use
22156 (defun org-uniquify-alist (alist)
22157 "Merge elements of ALIST with the same key.
22159 For example, in this alist:
22161 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22162 => \\='((a 1 3) (b 2))
22164 merge (a 1) and (a 3) into (a 1 3).
22166 The function returns the new ALIST."
22167 (let (rtn)
22168 (dolist (e alist rtn)
22169 (let (n)
22170 (if (not (assoc (car e) rtn))
22171 (push e rtn)
22172 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22173 (setq rtn (assq-delete-all (car e) rtn))
22174 (push n rtn))))))
22176 (defun org-delete-all (elts list)
22177 "Remove all elements in ELTS from LIST.
22178 Comparison is done with `equal'. It is a destructive operation
22179 that may remove elements by altering the list structure."
22180 (while elts
22181 (setq list (delete (pop elts) list)))
22182 list)
22184 (defun org-back-over-empty-lines ()
22185 "Move backwards over whitespace, to the beginning of the first empty line.
22186 Returns the number of empty lines passed."
22187 (let ((pos (point)))
22188 (if (cdr (assq 'heading org-blank-before-new-entry))
22189 (skip-chars-backward " \t\n\r")
22190 (unless (eobp)
22191 (forward-line -1)))
22192 (beginning-of-line 2)
22193 (goto-char (min (point) pos))
22194 (count-lines (point) pos)))
22196 (defun org-skip-whitespace ()
22197 (skip-chars-forward " \t\n\r"))
22199 (defun org-point-in-group (point group &optional context)
22200 "Check if POINT is in match-group GROUP.
22201 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22202 match. If the match group does not exist or point is not inside it,
22203 return nil."
22204 (and (match-beginning group)
22205 (>= point (match-beginning group))
22206 (<= point (match-end group))
22207 (if context
22208 (list context (match-beginning group) (match-end group))
22209 t)))
22211 (defun org-switch-to-buffer-other-window (&rest args)
22212 "Switch to buffer in a second window on the current frame.
22213 In particular, do not allow pop-up frames.
22214 Returns the newly created buffer."
22215 (org-no-popups
22216 (apply 'switch-to-buffer-other-window args)))
22218 (defun org-combine-plists (&rest plists)
22219 "Create a single property list from all plists in PLISTS.
22220 The process starts by copying the first list, and then setting properties
22221 from the other lists. Settings in the last list are the most significant
22222 ones and overrule settings in the other lists."
22223 (let ((rtn (copy-sequence (pop plists)))
22224 p v ls)
22225 (while plists
22226 (setq ls (pop plists))
22227 (while ls
22228 (setq p (pop ls) v (pop ls))
22229 (setq rtn (plist-put rtn p v))))
22230 rtn))
22232 (defun org-replace-escapes (string table)
22233 "Replace %-escapes in STRING with values in TABLE.
22234 TABLE is an association list with keys like \"%a\" and string values.
22235 The sequences in STRING may contain normal field width and padding information,
22236 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22237 so values can contain further %-escapes if they are define later in TABLE."
22238 (let ((tbl (copy-alist table))
22239 (case-fold-search nil)
22240 (pchg 0)
22241 re rpl)
22242 (dolist (e tbl)
22243 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22244 (when (and (cdr e) (string-match re (cdr e)))
22245 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22246 (safe "SREF"))
22247 (add-text-properties 0 3 (list 'sref sref) safe)
22248 (setcdr e (replace-match safe t t (cdr e)))))
22249 (while (string-match re string)
22250 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22251 (cdr e)))
22252 (setq string (replace-match rpl t t string))))
22253 (while (setq pchg (next-property-change pchg string))
22254 (let ((sref (get-text-property pchg 'sref string)))
22255 (when (and sref (string-match "SREF" string pchg))
22256 (setq string (replace-match sref t t string)))))
22257 string))
22259 (defun org-find-base-buffer-visiting (file)
22260 "Like `find-buffer-visiting' but always return the base buffer and
22261 not an indirect buffer."
22262 (let ((buf (or (get-file-buffer file)
22263 (find-buffer-visiting file))))
22264 (if buf
22265 (or (buffer-base-buffer buf) buf)
22266 nil)))
22268 ;;; TODO: Only called once, from ox-odt which should probably use
22269 ;;; org-export-inline-image-p or something.
22270 (defun org-file-image-p (file)
22271 "Return non-nil if FILE is an image."
22272 (save-match-data
22273 (string-match (image-file-name-regexp) file)))
22275 (defun org-get-cursor-date (&optional with-time)
22276 "Return the date at cursor in as a time.
22277 This works in the calendar and in the agenda, anywhere else it just
22278 returns the current time.
22279 If WITH-TIME is non-nil, returns the time of the event at point (in
22280 the agenda) or the current time of the day."
22281 (let (date day defd tp hod mod)
22282 (when with-time
22283 (setq tp (get-text-property (point) 'time))
22284 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22285 (setq hod (string-to-number (match-string 1 tp))
22286 mod (string-to-number (match-string 2 tp))))
22287 (or tp (let ((now (decode-time)))
22288 (setq hod (nth 2 now)
22289 mod (nth 1 now)))))
22290 (cond
22291 ((eq major-mode 'calendar-mode)
22292 (setq date (calendar-cursor-to-date)
22293 defd (encode-time 0 (or mod 0) (or hod 0)
22294 (nth 1 date) (nth 0 date) (nth 2 date))))
22295 ((eq major-mode 'org-agenda-mode)
22296 (setq day (get-text-property (point) 'day))
22297 (when day
22298 (setq date (calendar-gregorian-from-absolute day)
22299 defd (encode-time 0 (or mod 0) (or hod 0)
22300 (nth 1 date) (nth 0 date) (nth 2 date))))))
22301 (or defd (current-time))))
22303 (defun org-mark-subtree (&optional up)
22304 "Mark the current subtree.
22305 This puts point at the start of the current subtree, and mark at
22306 the end. If a numeric prefix UP is given, move up into the
22307 hierarchy of headlines by UP levels before marking the subtree."
22308 (interactive "P")
22309 (org-with-limited-levels
22310 (cond ((org-at-heading-p) (beginning-of-line))
22311 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22312 (t (outline-previous-visible-heading 1))))
22313 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22314 (if (called-interactively-p 'any)
22315 (call-interactively 'org-mark-element)
22316 (org-mark-element)))
22318 (defun org-file-newer-than-p (file time)
22319 "Non-nil if FILE is newer than TIME.
22320 FILE is a filename, as a string, TIME is a list of integers, as
22321 returned by, e.g., `current-time'."
22322 (and (file-exists-p file)
22323 ;; Only compare times up to whole seconds as some file-systems
22324 ;; (e.g. HFS+) do not retain any finer granularity. As
22325 ;; a consequence, make sure we return non-nil when the two
22326 ;; times are equal.
22327 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22328 (cl-subseq time 0 2)))))
22330 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22331 "Compile a SOURCE file using PROCESS.
22333 PROCESS is either a function or a list of shell commands, as
22334 strings. EXT is a file extension, without the leading dot, as
22335 a string. It is used to check if the process actually succeeded.
22337 PROCESS must create a file with the same base name and directory
22338 as SOURCE, but ending with EXT. The function then returns its
22339 filename. Otherwise, it raises an error. The error message can
22340 then be refined by providing string ERR-MSG, which is appended to
22341 the standard message.
22343 If PROCESS is a function, it is called with a single argument:
22344 the SOURCE file.
22346 If it is a list of commands, each of them is called using
22347 `shell-command'. By default, in each command, %b, %f, %F, %o and
22348 %O are replaced with, respectively, SOURCE base name, name, full
22349 name, directory and absolute output file name. It is possible,
22350 however, to use more place-holders by specifying them in optional
22351 argument SPEC, as an alist following the pattern
22353 (CHARACTER . REPLACEMENT-STRING).
22355 When PROCESS is a list of commands, optional argument LOG-BUF can
22356 be set to a buffer or a buffer name. `shell-command' then uses
22357 it for output."
22358 (let* ((base-name (file-name-base source))
22359 (full-name (file-truename source))
22360 (out-dir (or (file-name-directory source) "./"))
22361 (output (expand-file-name (concat base-name "." ext) out-dir))
22362 (time (current-time))
22363 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22364 (save-window-excursion
22365 (pcase process
22366 ((pred functionp) (funcall process (shell-quote-argument source)))
22367 ((pred consp)
22368 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22369 (spec (append spec
22370 `((?b . ,(shell-quote-argument base-name))
22371 (?f . ,(shell-quote-argument source))
22372 (?F . ,(shell-quote-argument full-name))
22373 (?o . ,(shell-quote-argument out-dir))
22374 (?O . ,(shell-quote-argument output))))))
22375 (dolist (command process)
22376 (shell-command (format-spec command spec) log-buf))
22377 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22378 (_ (error "No valid command to process %S%s" source err-msg))))
22379 ;; Check for process failure. Output file is expected to be
22380 ;; located in the same directory as SOURCE.
22381 (unless (org-file-newer-than-p output time)
22382 (error (format "File %S wasn't produced%s" output err-msg)))
22383 output))
22385 ;;; Indentation
22387 (defvar org-element-greater-elements)
22388 (defun org--get-expected-indentation (element contentsp)
22389 "Expected indentation column for current line, according to ELEMENT.
22390 ELEMENT is an element containing point. CONTENTSP is non-nil
22391 when indentation is to be computed according to contents of
22392 ELEMENT."
22393 (let ((type (org-element-type element))
22394 (start (org-element-property :begin element))
22395 (post-affiliated (org-element-property :post-affiliated element)))
22396 (org-with-wide-buffer
22397 (cond
22398 (contentsp
22399 (cl-case type
22400 ((diary-sexp footnote-definition) 0)
22401 ((headline inlinetask nil)
22402 (if (not org-adapt-indentation) 0
22403 (let ((level (org-current-level)))
22404 (if level (1+ level) 0))))
22405 ((item plain-list) (org-list-item-body-column post-affiliated))
22407 (goto-char start)
22408 (org-get-indentation))))
22409 ((memq type '(headline inlinetask nil))
22410 (if (org-match-line "[ \t]*$")
22411 (org--get-expected-indentation element t)
22413 ((memq type '(diary-sexp footnote-definition)) 0)
22414 ;; First paragraph of a footnote definition or an item.
22415 ;; Indent like parent.
22416 ((< (line-beginning-position) start)
22417 (org--get-expected-indentation
22418 (org-element-property :parent element) t))
22419 ;; At first line: indent according to previous sibling, if any,
22420 ;; ignoring footnote definitions and inline tasks, or parent's
22421 ;; contents.
22422 ((= (line-beginning-position) start)
22423 (catch 'exit
22424 (while t
22425 (if (= (point-min) start) (throw 'exit 0)
22426 (goto-char (1- start))
22427 (let* ((previous (org-element-at-point))
22428 (parent previous))
22429 (while (and parent (<= (org-element-property :end parent) start))
22430 (setq previous parent
22431 parent (org-element-property :parent parent)))
22432 (cond
22433 ((not previous) (throw 'exit 0))
22434 ((> (org-element-property :end previous) start)
22435 (throw 'exit (org--get-expected-indentation previous t)))
22436 ((memq (org-element-type previous)
22437 '(footnote-definition inlinetask))
22438 (setq start (org-element-property :begin previous)))
22439 (t (goto-char (org-element-property :begin previous))
22440 (throw 'exit
22441 (if (bolp) (org-get-indentation)
22442 ;; At first paragraph in an item or
22443 ;; a footnote definition.
22444 (org--get-expected-indentation
22445 (org-element-property :parent previous) t))))))))))
22446 ;; Otherwise, move to the first non-blank line above.
22448 (beginning-of-line)
22449 (let ((pos (point)))
22450 (skip-chars-backward " \r\t\n")
22451 (cond
22452 ;; Two blank lines end a footnote definition or a plain
22453 ;; list. When we indent an empty line after them, the
22454 ;; containing list or footnote definition is over, so it
22455 ;; qualifies as a previous sibling. Therefore, we indent
22456 ;; like its first line.
22457 ((and (memq type '(footnote-definition plain-list))
22458 (> (count-lines (point) pos) 2))
22459 (goto-char start)
22460 (org-get-indentation))
22461 ;; Line above is the first one of a paragraph at the
22462 ;; beginning of an item or a footnote definition. Indent
22463 ;; like parent.
22464 ((< (line-beginning-position) start)
22465 (org--get-expected-indentation
22466 (org-element-property :parent element) t))
22467 ;; Line above is the beginning of an element, i.e., point
22468 ;; was originally on the blank lines between element's start
22469 ;; and contents.
22470 ((= (line-beginning-position) post-affiliated)
22471 (org--get-expected-indentation element t))
22472 ;; POS is after contents in a greater element. Indent like
22473 ;; the beginning of the element.
22474 ((and (memq type org-element-greater-elements)
22475 (let ((cend (org-element-property :contents-end element)))
22476 (and cend (<= cend pos))))
22477 ;; As a special case, if point is at the end of a footnote
22478 ;; definition or an item, indent like the very last element
22479 ;; within. If that last element is an item, indent like
22480 ;; its contents.
22481 (if (memq type '(footnote-definition item plain-list))
22482 (let ((last (org-element-at-point)))
22483 (goto-char pos)
22484 (org--get-expected-indentation
22485 last (eq (org-element-type last) 'item)))
22486 (goto-char start)
22487 (org-get-indentation)))
22488 ;; In any other case, indent like the current line.
22489 (t (org-get-indentation)))))))))
22491 (defun org--align-node-property ()
22492 "Align node property at point.
22493 Alignment is done according to `org-property-format', which see."
22494 (when (save-excursion
22495 (beginning-of-line)
22496 (looking-at org-property-re))
22497 (replace-match
22498 (concat (match-string 4)
22499 (org-trim
22500 (format org-property-format (match-string 1) (match-string 3))))
22501 t t)))
22503 (defun org-indent-line ()
22504 "Indent line depending on context.
22506 Indentation is done according to the following rules:
22508 - Footnote definitions, diary sexps, headlines and inline tasks
22509 have to start at column 0.
22511 - On the very first line of an element, consider, in order, the
22512 next rules until one matches:
22514 1. If there's a sibling element before, ignoring footnote
22515 definitions and inline tasks, indent like its first line.
22517 2. If element has a parent, indent like its contents. More
22518 precisely, if parent is an item, indent after the
22519 description part, if any, or the bullet (see
22520 `org-list-description-max-indent'). Else, indent like
22521 parent's first line.
22523 3. Otherwise, indent relatively to current level, if
22524 `org-adapt-indentation' is non-nil, or to left margin.
22526 - On a blank line at the end of an element, indent according to
22527 the type of the element. More precisely
22529 1. If element is a plain list, an item, or a footnote
22530 definition, indent like the very last element within.
22532 2. If element is a paragraph, indent like its last non blank
22533 line.
22535 3. Otherwise, indent like its very first line.
22537 - In the code part of a source block, use language major mode
22538 to indent current line if `org-src-tab-acts-natively' is
22539 non-nil. If it is nil, do nothing.
22541 - Otherwise, indent like the first non-blank line above.
22543 The function doesn't indent an item as it could break the whole
22544 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22545 `\\[org-shiftmetaright]'.
22547 Also align node properties according to `org-property-format'."
22548 (interactive)
22549 (cond
22550 (orgstruct-is-++
22551 (let ((indent-line-function
22552 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22553 (indent-according-to-mode)))
22554 ((org-at-heading-p) 'noindent)
22556 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22557 (type (org-element-type element)))
22558 (cond ((and (memq type '(plain-list item))
22559 (= (line-beginning-position)
22560 (org-element-property :post-affiliated element)))
22561 'noindent)
22562 ((and (eq type 'latex-environment)
22563 (>= (point) (org-element-property :post-affiliated element))
22564 (< (point) (org-with-wide-buffer
22565 (goto-char (org-element-property :end element))
22566 (skip-chars-backward " \r\t\n")
22567 (line-beginning-position 2))))
22568 'noindent)
22569 ((and (eq type 'src-block)
22570 org-src-tab-acts-natively
22571 (> (line-beginning-position)
22572 (org-element-property :post-affiliated element))
22573 (< (line-beginning-position)
22574 (org-with-wide-buffer
22575 (goto-char (org-element-property :end element))
22576 (skip-chars-backward " \r\t\n")
22577 (line-beginning-position))))
22578 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22580 (let ((column (org--get-expected-indentation element nil)))
22581 ;; Preserve current column.
22582 (if (<= (current-column) (current-indentation))
22583 (indent-line-to column)
22584 (save-excursion (indent-line-to column))))
22585 ;; Align node property. Also preserve current column.
22586 (when (eq type 'node-property)
22587 (let ((column (current-column)))
22588 (org--align-node-property)
22589 (org-move-to-column column)))))))))
22591 (defun org-indent-region (start end)
22592 "Indent each non-blank line in the region.
22593 Called from a program, START and END specify the region to
22594 indent. The function will not indent contents of example blocks,
22595 verse blocks and export blocks as leading white spaces are
22596 assumed to be significant there."
22597 (interactive "r")
22598 (save-excursion
22599 (goto-char start)
22600 (skip-chars-forward " \r\t\n")
22601 (unless (eobp) (beginning-of-line))
22602 (let ((indent-to
22603 (lambda (ind pos)
22604 ;; Set IND as indentation for all lines between point and
22605 ;; POS. Blank lines are ignored. Leave point after POS
22606 ;; once done.
22607 (let ((limit (copy-marker pos)))
22608 (while (< (point) limit)
22609 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22610 (forward-line))
22611 (set-marker limit nil))))
22612 (end (copy-marker end)))
22613 (while (< (point) end)
22614 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22615 (let* ((element (org-element-at-point))
22616 (type (org-element-type element))
22617 (element-end (copy-marker (org-element-property :end element)))
22618 (ind (org--get-expected-indentation element nil)))
22619 (cond
22620 ;; Element indented as a single block. Example blocks
22621 ;; preserving indentation are a special case since the
22622 ;; "contents" must not be indented whereas the block
22623 ;; boundaries can.
22624 ((or (memq type '(export-block latex-environment))
22625 (and (eq type 'example-block)
22626 (not
22627 (or org-src-preserve-indentation
22628 (org-element-property :preserve-indent element)))))
22629 (let ((offset (- ind (org-get-indentation))))
22630 (unless (zerop offset)
22631 (indent-rigidly (org-element-property :begin element)
22632 (org-element-property :end element)
22633 offset)))
22634 (goto-char element-end))
22635 ;; Elements indented line wise. Be sure to exclude
22636 ;; example blocks (preserving indentation) and source
22637 ;; blocks from this category as they are treated
22638 ;; specially later.
22639 ((or (memq type '(paragraph table table-row))
22640 (not (or (org-element-property :contents-begin element)
22641 (memq type '(example-block src-block)))))
22642 (when (eq type 'node-property)
22643 (org--align-node-property)
22644 (beginning-of-line))
22645 (funcall indent-to ind (min element-end end)))
22646 ;; Elements consisting of three parts: before the
22647 ;; contents, the contents, and after the contents. The
22648 ;; contents are treated specially, according to the
22649 ;; element type, or not indented at all. Other parts are
22650 ;; indented as a single block.
22652 (let* ((post (copy-marker
22653 (org-element-property :post-affiliated element)))
22654 (cbeg
22655 (copy-marker
22656 (cond
22657 ((not (org-element-property :contents-begin element))
22658 ;; Fake contents for source blocks.
22659 (org-with-wide-buffer
22660 (goto-char post)
22661 (line-beginning-position 2)))
22662 ((memq type '(footnote-definition item plain-list))
22663 ;; Contents in these elements could start on
22664 ;; the same line as the beginning of the
22665 ;; element. Make sure we start indenting
22666 ;; from the second line.
22667 (org-with-wide-buffer
22668 (goto-char post)
22669 (end-of-line)
22670 (skip-chars-forward " \r\t\n")
22671 (if (eobp) (point) (line-beginning-position))))
22672 (t (org-element-property :contents-begin element)))))
22673 (cend (copy-marker
22674 (or (org-element-property :contents-end element)
22675 ;; Fake contents for source blocks.
22676 (org-with-wide-buffer
22677 (goto-char element-end)
22678 (skip-chars-backward " \r\t\n")
22679 (line-beginning-position)))
22680 t)))
22681 ;; Do not change items indentation individually as it
22682 ;; might break the list as a whole. On the other
22683 ;; hand, when at a plain list, indent it as a whole.
22684 (cond ((eq type 'plain-list)
22685 (let ((offset (- ind (org-get-indentation))))
22686 (unless (zerop offset)
22687 (indent-rigidly (org-element-property :begin element)
22688 (org-element-property :end element)
22689 offset))
22690 (goto-char cbeg)))
22691 ((eq type 'item) (goto-char cbeg))
22692 (t (funcall indent-to ind (min cbeg end))))
22693 (when (< (point) end)
22694 (cl-case type
22695 ((example-block verse-block))
22696 (src-block
22697 ;; In a source block, indent source code
22698 ;; according to language major mode, but only if
22699 ;; `org-src-tab-acts-natively' is non-nil.
22700 (when (and (< (point) end) org-src-tab-acts-natively)
22701 (ignore-errors
22702 (org-babel-do-in-edit-buffer
22703 (indent-region (point-min) (point-max))))))
22704 (t (org-indent-region (point) (min cend end))))
22705 (goto-char (min cend end))
22706 (when (< (point) end)
22707 (funcall indent-to ind (min element-end end))))
22708 (set-marker post nil)
22709 (set-marker cbeg nil)
22710 (set-marker cend nil))))
22711 (set-marker element-end nil))))
22712 (set-marker end nil))))
22714 (defun org-indent-drawer ()
22715 "Indent the drawer at point."
22716 (interactive)
22717 (unless (save-excursion
22718 (beginning-of-line)
22719 (looking-at-p org-drawer-regexp))
22720 (user-error "Not at a drawer"))
22721 (let ((element (org-element-at-point)))
22722 (unless (memq (org-element-type element) '(drawer property-drawer))
22723 (user-error "Not at a drawer"))
22724 (org-with-wide-buffer
22725 (org-indent-region (org-element-property :begin element)
22726 (org-element-property :end element))))
22727 (message "Drawer at point indented"))
22729 (defun org-indent-block ()
22730 "Indent the block at point."
22731 (interactive)
22732 (unless (save-excursion
22733 (beginning-of-line)
22734 (let ((case-fold-search t))
22735 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22736 (user-error "Not at a block"))
22737 (let ((element (org-element-at-point)))
22738 (unless (memq (org-element-type element)
22739 '(comment-block center-block dynamic-block example-block
22740 export-block quote-block special-block
22741 src-block verse-block))
22742 (user-error "Not at a block"))
22743 (org-with-wide-buffer
22744 (org-indent-region (org-element-property :begin element)
22745 (org-element-property :end element))))
22746 (message "Block at point indented"))
22749 ;;; Filling
22751 ;; We use our own fill-paragraph and auto-fill functions.
22753 ;; `org-fill-paragraph' relies on adaptive filling and context
22754 ;; checking. Appropriate `fill-prefix' is computed with
22755 ;; `org-adaptive-fill-function'.
22757 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22758 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22759 ;; `org-adaptive-fill-function' value. Internally,
22760 ;; `org-comment-line-break-function' breaks the line.
22762 ;; `org-setup-filling' installs filling and auto-filling related
22763 ;; variables during `org-mode' initialization.
22765 (defvar org-element-paragraph-separate) ; org-element.el
22766 (defun org-setup-filling ()
22767 (require 'org-element)
22768 ;; Prevent auto-fill from inserting unwanted new items.
22769 (when (boundp 'fill-nobreak-predicate)
22770 (setq-local
22771 fill-nobreak-predicate
22772 (org-uniquify
22773 (append fill-nobreak-predicate
22774 '(org-fill-line-break-nobreak-p
22775 org-fill-n-macro-as-item-nobreak-p
22776 org-fill-paragraph-with-timestamp-nobreak-p)))))
22777 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22778 (setq-local paragraph-start paragraph-ending)
22779 (setq-local paragraph-separate paragraph-ending))
22780 (setq-local fill-paragraph-function 'org-fill-paragraph)
22781 (setq-local auto-fill-inhibit-regexp nil)
22782 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22783 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22784 (setq-local comment-line-break-function 'org-comment-line-break-function))
22786 (defun org-fill-line-break-nobreak-p ()
22787 "Non-nil when a new line at point would create an Org line break."
22788 (save-excursion
22789 (skip-chars-backward "[ \t]")
22790 (skip-chars-backward "\\\\")
22791 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22793 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22794 "Non-nil when a new line at point would split a timestamp."
22795 (and (org-at-timestamp-p 'lax)
22796 (not (looking-at org-ts-regexp-both))))
22798 (defun org-fill-n-macro-as-item-nobreak-p ()
22799 "Non-nil when a new line at point would create a new list."
22800 ;; During export, a "n" macro followed by a dot or a closing
22801 ;; parenthesis can end up being parsed as a new list item.
22802 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22804 (declare-function message-in-body-p "message" ())
22805 (defvar orgtbl-line-start-regexp) ; From org-table.el
22806 (defun org-adaptive-fill-function ()
22807 "Compute a fill prefix for the current line.
22808 Return fill prefix, as a string, or nil if current line isn't
22809 meant to be filled. For convenience, if `adaptive-fill-regexp'
22810 matches in paragraphs or comments, use it."
22811 (catch 'exit
22812 (when (derived-mode-p 'message-mode)
22813 (save-excursion
22814 (beginning-of-line)
22815 (cond ((not (message-in-body-p)) (throw 'exit nil))
22816 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22817 ((looking-at message-cite-prefix-regexp)
22818 (throw 'exit (match-string-no-properties 0)))
22819 ((looking-at org-outline-regexp)
22820 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22821 (org-with-wide-buffer
22822 (unless (org-at-heading-p)
22823 (let* ((p (line-beginning-position))
22824 (element (save-excursion
22825 (beginning-of-line)
22826 (org-element-at-point)))
22827 (type (org-element-type element))
22828 (post-affiliated (org-element-property :post-affiliated element)))
22829 (unless (< p post-affiliated)
22830 (cl-case type
22831 (comment
22832 (save-excursion
22833 (beginning-of-line)
22834 (looking-at "[ \t]*")
22835 (concat (match-string 0) "# ")))
22836 (footnote-definition "")
22837 ((item plain-list)
22838 (make-string (org-list-item-body-column post-affiliated) ?\s))
22839 (paragraph
22840 ;; Fill prefix is usually the same as the current line,
22841 ;; unless the paragraph is at the beginning of an item.
22842 (let ((parent (org-element-property :parent element)))
22843 (save-excursion
22844 (beginning-of-line)
22845 (cond ((eq (org-element-type parent) 'item)
22846 (make-string (org-list-item-body-column
22847 (org-element-property :begin parent))
22848 ?\s))
22849 ((and adaptive-fill-regexp
22850 ;; Locally disable
22851 ;; `adaptive-fill-function' to let
22852 ;; `fill-context-prefix' handle
22853 ;; `adaptive-fill-regexp' variable.
22854 (let (adaptive-fill-function)
22855 (fill-context-prefix
22856 post-affiliated
22857 (org-element-property :end element)))))
22858 ((looking-at "[ \t]+") (match-string 0))
22859 (t "")))))
22860 (comment-block
22861 ;; Only fill contents if P is within block boundaries.
22862 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22863 (forward-line)
22864 (point)))
22865 (cend (save-excursion
22866 (goto-char (org-element-property :end element))
22867 (skip-chars-backward " \r\t\n")
22868 (line-beginning-position))))
22869 (when (and (>= p cbeg) (< p cend))
22870 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22871 (match-string 0)
22872 "")))))))))))
22874 (declare-function message-goto-body "message" ())
22875 (defvar message-cite-prefix-regexp) ; From message.el
22877 (defun org-fill-element (&optional justify)
22878 "Fill element at point, when applicable.
22880 This function only applies to comment blocks, comments, example
22881 blocks and paragraphs. Also, as a special case, re-align table
22882 when point is at one.
22884 If JUSTIFY is non-nil (interactively, with prefix argument),
22885 justify as well. If `sentence-end-double-space' is non-nil, then
22886 period followed by one space does not end a sentence, so don't
22887 break a line there. The variable `fill-column' controls the
22888 width for filling.
22890 For convenience, when point is at a plain list, an item or
22891 a footnote definition, try to fill the first paragraph within."
22892 (with-syntax-table org-mode-transpose-word-syntax-table
22893 ;; Move to end of line in order to get the first paragraph within
22894 ;; a plain list or a footnote definition.
22895 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22896 ;; First check if point is in a blank line at the beginning of
22897 ;; the buffer. In that case, ignore filling.
22898 (cl-case (org-element-type element)
22899 ;; Use major mode filling function is src blocks.
22900 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22901 ;; Align Org tables, leave table.el tables as-is.
22902 (table-row (org-table-align) t)
22903 (table
22904 (when (eq (org-element-property :type element) 'org)
22905 (save-excursion
22906 (goto-char (org-element-property :post-affiliated element))
22907 (org-table-align)))
22909 (paragraph
22910 ;; Paragraphs may contain `line-break' type objects.
22911 (let ((beg (max (point-min)
22912 (org-element-property :contents-begin element)))
22913 (end (min (point-max)
22914 (org-element-property :contents-end element))))
22915 ;; Do nothing if point is at an affiliated keyword.
22916 (if (< (line-end-position) beg) t
22917 (when (derived-mode-p 'message-mode)
22918 ;; In `message-mode', do not fill following citation
22919 ;; in current paragraph nor text before message body.
22920 (let ((body-start (save-excursion (message-goto-body))))
22921 (when body-start (setq beg (max body-start beg))))
22922 (when (save-excursion
22923 (re-search-forward
22924 (concat "^" message-cite-prefix-regexp) end t))
22925 (setq end (match-beginning 0))))
22926 ;; Fill paragraph, taking line breaks into account.
22927 (save-excursion
22928 (goto-char beg)
22929 (let ((cuts (list beg)))
22930 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22931 (when (eq 'line-break
22932 (org-element-type
22933 (save-excursion (backward-char)
22934 (org-element-context))))
22935 (push (point) cuts)))
22936 (dolist (c (delq end cuts))
22937 (fill-region-as-paragraph c end justify)
22938 (setq end c))))
22939 t)))
22940 ;; Contents of `comment-block' type elements should be
22941 ;; filled as plain text, but only if point is within block
22942 ;; markers.
22943 (comment-block
22944 (let* ((case-fold-search t)
22945 (beg (save-excursion
22946 (goto-char (org-element-property :begin element))
22947 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22948 (forward-line)
22949 (point)))
22950 (end (save-excursion
22951 (goto-char (org-element-property :end element))
22952 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22953 (line-beginning-position))))
22954 (if (or (< (point) beg) (> (point) end)) t
22955 (fill-region-as-paragraph
22956 (save-excursion (end-of-line)
22957 (re-search-backward "^[ \t]*$" beg 'move)
22958 (line-beginning-position))
22959 (save-excursion (beginning-of-line)
22960 (re-search-forward "^[ \t]*$" end 'move)
22961 (line-beginning-position))
22962 justify))))
22963 ;; Fill comments.
22964 (comment
22965 (let ((begin (org-element-property :post-affiliated element))
22966 (end (org-element-property :end element)))
22967 (when (and (>= (point) begin) (<= (point) end))
22968 (let ((begin (save-excursion
22969 (end-of-line)
22970 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22971 (progn (forward-line) (point))
22972 begin)))
22973 (end (save-excursion
22974 (end-of-line)
22975 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22976 (1- (line-beginning-position))
22977 (skip-chars-backward " \r\t\n")
22978 (line-end-position)))))
22979 ;; Do not fill comments when at a blank line.
22980 (when (> end begin)
22981 (let ((fill-prefix
22982 (save-excursion
22983 (beginning-of-line)
22984 (looking-at "[ \t]*#")
22985 (let ((comment-prefix (match-string 0)))
22986 (goto-char (match-end 0))
22987 (if (looking-at adaptive-fill-regexp)
22988 (concat comment-prefix (match-string 0))
22989 (concat comment-prefix " "))))))
22990 (save-excursion
22991 (fill-region-as-paragraph begin end justify))))))
22993 ;; Ignore every other element.
22994 (otherwise t)))))
22996 (defun org-fill-paragraph (&optional justify region)
22997 "Fill element at point, when applicable.
22999 This function only applies to comment blocks, comments, example
23000 blocks and paragraphs. Also, as a special case, re-align table
23001 when point is at one.
23003 For convenience, when point is at a plain list, an item or
23004 a footnote definition, try to fill the first paragraph within.
23006 If JUSTIFY is non-nil (interactively, with prefix argument),
23007 justify as well. If `sentence-end-double-space' is non-nil, then
23008 period followed by one space does not end a sentence, so don't
23009 break a line there. The variable `fill-column' controls the
23010 width for filling.
23012 The REGION argument is non-nil if called interactively; in that
23013 case, if Transient Mark mode is enabled and the mark is active,
23014 fill each of the elements in the active region, instead of just
23015 filling the current element."
23016 (interactive (progn
23017 (barf-if-buffer-read-only)
23018 (list (if current-prefix-arg 'full) t)))
23019 (cond
23020 ((and (derived-mode-p 'message-mode)
23021 (or (not (message-in-body-p))
23022 (save-excursion (move-beginning-of-line 1)
23023 (looking-at message-cite-prefix-regexp))))
23024 ;; First ensure filling is correct in message-mode.
23025 (let ((fill-paragraph-function
23026 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23027 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23028 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23029 (paragraph-separate
23030 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23031 (fill-paragraph nil)))
23032 ((and region transient-mark-mode mark-active
23033 (not (eq (region-beginning) (region-end))))
23034 (let ((origin (point-marker))
23035 (start (region-beginning)))
23036 (unwind-protect
23037 (progn
23038 (goto-char (region-end))
23039 (while (> (point) start)
23040 (org-backward-paragraph)
23041 (org-fill-element justify)))
23042 (goto-char origin)
23043 (set-marker origin nil))))
23044 (t (org-fill-element justify))))
23045 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
23047 (defun org-auto-fill-function ()
23048 "Auto-fill function."
23049 ;; Check if auto-filling is meaningful.
23050 (let ((fc (current-fill-column)))
23051 (when (and fc (> (current-column) fc))
23052 (let* ((fill-prefix (org-adaptive-fill-function))
23053 ;; Enforce empty fill prefix, if required. Otherwise, it
23054 ;; will be computed again.
23055 (adaptive-fill-mode (not (equal fill-prefix ""))))
23056 (when fill-prefix (do-auto-fill))))))
23058 (defun org-comment-line-break-function (&optional soft)
23059 "Break line at point and indent, continuing comment if within one.
23060 The inserted newline is marked hard if variable
23061 `use-hard-newlines' is true, unless optional argument SOFT is
23062 non-nil."
23063 (if soft (insert-and-inherit ?\n) (newline 1))
23064 (save-excursion (forward-char -1) (delete-horizontal-space))
23065 (delete-horizontal-space)
23066 (indent-to-left-margin)
23067 (insert-before-markers-and-inherit fill-prefix))
23070 ;;; Fixed Width Areas
23072 (defun org-toggle-fixed-width ()
23073 "Toggle fixed-width markup.
23075 Add or remove fixed-width markup on current line, whenever it
23076 makes sense. Return an error otherwise.
23078 If a region is active and if it contains only fixed-width areas
23079 or blank lines, remove all fixed-width markup in it. If the
23080 region contains anything else, convert all non-fixed-width lines
23081 to fixed-width ones.
23083 Blank lines at the end of the region are ignored unless the
23084 region only contains such lines."
23085 (interactive)
23086 (if (not (org-region-active-p))
23087 ;; No region:
23089 ;; Remove fixed width marker only in a fixed-with element.
23091 ;; Add fixed width maker in paragraphs, in blank lines after
23092 ;; elements or at the beginning of a headline or an inlinetask,
23093 ;; and before any one-line elements (e.g., a clock).
23094 (progn
23095 (beginning-of-line)
23096 (let* ((element (org-element-at-point))
23097 (type (org-element-type element)))
23098 (cond
23099 ((and (eq type 'fixed-width)
23100 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23101 (replace-match
23102 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23103 ((and (memq type '(babel-call clock comment diary-sexp headline
23104 horizontal-rule keyword paragraph
23105 planning))
23106 (<= (org-element-property :post-affiliated element) (point)))
23107 (skip-chars-forward " \t")
23108 (insert ": "))
23109 ((and (looking-at-p "[ \t]*$")
23110 (or (eq type 'inlinetask)
23111 (save-excursion
23112 (skip-chars-forward " \r\t\n")
23113 (<= (org-element-property :end element) (point)))))
23114 (delete-region (point) (line-end-position))
23115 (org-indent-line)
23116 (insert ": "))
23117 (t (user-error "Cannot insert a fixed-width line here")))))
23118 ;; Region active.
23119 (let* ((begin (save-excursion
23120 (goto-char (region-beginning))
23121 (line-beginning-position)))
23122 (end (copy-marker
23123 (save-excursion
23124 (goto-char (region-end))
23125 (unless (eolp) (beginning-of-line))
23126 (if (save-excursion (re-search-backward "\\S-" begin t))
23127 (progn (skip-chars-backward " \r\t\n") (point))
23128 (point)))))
23129 (all-fixed-width-p
23130 (catch 'not-all-p
23131 (save-excursion
23132 (goto-char begin)
23133 (skip-chars-forward " \r\t\n")
23134 (when (eobp) (throw 'not-all-p nil))
23135 (while (< (point) end)
23136 (let ((element (org-element-at-point)))
23137 (if (eq (org-element-type element) 'fixed-width)
23138 (goto-char (org-element-property :end element))
23139 (throw 'not-all-p nil))))
23140 t))))
23141 (if all-fixed-width-p
23142 (save-excursion
23143 (goto-char begin)
23144 (while (< (point) end)
23145 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23146 (replace-match
23147 "" nil nil nil
23148 (if (= (line-end-position) (match-end 0)) 0 1)))
23149 (forward-line)))
23150 (let ((min-ind (point-max)))
23151 ;; Find minimum indentation across all lines.
23152 (save-excursion
23153 (goto-char begin)
23154 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23155 (setq min-ind 0)
23156 (catch 'zerop
23157 (while (< (point) end)
23158 (unless (looking-at-p "[ \t]*$")
23159 (let ((ind (org-get-indentation)))
23160 (setq min-ind (min min-ind ind))
23161 (when (zerop ind) (throw 'zerop t))))
23162 (forward-line)))))
23163 ;; Loop over all lines and add fixed-width markup everywhere
23164 ;; but in fixed-width lines.
23165 (save-excursion
23166 (goto-char begin)
23167 (while (< (point) end)
23168 (cond
23169 ((org-at-heading-p)
23170 (insert ": ")
23171 (forward-line)
23172 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23173 (insert ":")
23174 (forward-line)))
23175 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23176 (let* ((element (org-element-at-point))
23177 (element-end (org-element-property :end element)))
23178 (if (eq (org-element-type element) 'fixed-width)
23179 (progn (goto-char element-end)
23180 (skip-chars-backward " \r\t\n")
23181 (forward-line))
23182 (let ((limit (min end element-end)))
23183 (while (< (point) limit)
23184 (org-move-to-column min-ind t)
23185 (insert ": ")
23186 (forward-line))))))
23188 (org-move-to-column min-ind t)
23189 (insert ": ")
23190 (forward-line)))))))
23191 (set-marker end nil))))
23194 ;;; Comments
23196 ;; Org comments syntax is quite complex. It requires the entire line
23197 ;; to be just a comment. Also, even with the right syntax at the
23198 ;; beginning of line, some elements (e.g., verse-block or
23199 ;; example-block) don't accept comments. Usual Emacs comment commands
23200 ;; cannot cope with those requirements. Therefore, Org replaces them.
23202 ;; Org still relies on `comment-dwim', but cannot trust
23203 ;; `comment-only-p'. So, `comment-region-function' and
23204 ;; `uncomment-region-function' both point
23205 ;; to`org-comment-or-uncomment-region'. Eventually,
23206 ;; `org-insert-comment' takes care of insertion of comments at the
23207 ;; beginning of line.
23209 ;; `org-setup-comments-handling' install comments related variables
23210 ;; during `org-mode' initialization.
23212 (defun org-setup-comments-handling ()
23213 (interactive)
23214 (setq-local comment-use-syntax nil)
23215 (setq-local comment-start "# ")
23216 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23217 (setq-local comment-insert-comment-function 'org-insert-comment)
23218 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23219 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23221 (defun org-insert-comment ()
23222 "Insert an empty comment above current line.
23223 If the line is empty, insert comment at its beginning. When
23224 point is within a source block, comment according to the related
23225 major mode."
23226 (if (let ((element (org-element-at-point)))
23227 (and (eq (org-element-type element) 'src-block)
23228 (< (save-excursion
23229 (goto-char (org-element-property :post-affiliated element))
23230 (line-end-position))
23231 (point))
23232 (> (save-excursion
23233 (goto-char (org-element-property :end element))
23234 (skip-chars-backward " \r\t\n")
23235 (line-beginning-position))
23236 (point))))
23237 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23238 (beginning-of-line)
23239 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23240 (open-line 1))
23241 (org-indent-line)
23242 (insert "# ")))
23244 (defvar comment-empty-lines) ; From newcomment.el.
23245 (defun org-comment-or-uncomment-region (beg end &rest _)
23246 "Comment or uncomment each non-blank line in the region.
23247 Uncomment each non-blank line between BEG and END if it only
23248 contains commented lines. Otherwise, comment them. If region is
23249 strictly within a source block, use appropriate comment syntax."
23250 (if (let ((element (org-element-at-point)))
23251 (and (eq (org-element-type element) 'src-block)
23252 (< (save-excursion
23253 (goto-char (org-element-property :post-affiliated element))
23254 (line-end-position))
23255 beg)
23256 (>= (save-excursion
23257 (goto-char (org-element-property :end element))
23258 (skip-chars-backward " \r\t\n")
23259 (line-beginning-position))
23260 end)))
23261 ;; Translate region boundaries for the Org buffer to the source
23262 ;; buffer.
23263 (let ((offset (- end beg)))
23264 (save-excursion
23265 (goto-char beg)
23266 (org-babel-do-in-edit-buffer
23267 (comment-or-uncomment-region (point) (+ offset (point))))))
23268 (save-restriction
23269 ;; Restrict region
23270 (narrow-to-region (save-excursion (goto-char beg)
23271 (skip-chars-forward " \r\t\n" end)
23272 (line-beginning-position))
23273 (save-excursion (goto-char end)
23274 (skip-chars-backward " \r\t\n" beg)
23275 (line-end-position)))
23276 (let ((uncommentp
23277 ;; UNCOMMENTP is non-nil when every non blank line between
23278 ;; BEG and END is a comment.
23279 (save-excursion
23280 (goto-char (point-min))
23281 (while (and (not (eobp))
23282 (let ((element (org-element-at-point)))
23283 (and (eq (org-element-type element) 'comment)
23284 (goto-char (min (point-max)
23285 (org-element-property
23286 :end element)))))))
23287 (eobp))))
23288 (if uncommentp
23289 ;; Only blank lines and comments in region: uncomment it.
23290 (save-excursion
23291 (goto-char (point-min))
23292 (while (not (eobp))
23293 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23294 (replace-match "" nil nil nil 1))
23295 (forward-line)))
23296 ;; Comment each line in region.
23297 (let ((min-indent (point-max)))
23298 ;; First find the minimum indentation across all lines.
23299 (save-excursion
23300 (goto-char (point-min))
23301 (while (and (not (eobp)) (not (zerop min-indent)))
23302 (unless (looking-at "[ \t]*$")
23303 (setq min-indent (min min-indent (current-indentation))))
23304 (forward-line)))
23305 ;; Then loop over all lines.
23306 (save-excursion
23307 (goto-char (point-min))
23308 (while (not (eobp))
23309 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23310 ;; Don't get fooled by invisible text (e.g. link path)
23311 ;; when moving to column MIN-INDENT.
23312 (let ((buffer-invisibility-spec nil))
23313 (org-move-to-column min-indent t))
23314 (insert comment-start))
23315 (forward-line)))))))))
23317 (defun org-comment-dwim (_arg)
23318 "Call `comment-dwim' within a source edit buffer if needed."
23319 (interactive "*P")
23320 (if (org-in-src-block-p)
23321 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23322 (call-interactively 'comment-dwim)))
23325 ;;; Timestamps API
23327 ;; This section contains tools to operate on timestamp objects, as
23328 ;; returned by, e.g. `org-element-context'.
23330 (defun org-timestamp--to-internal-time (timestamp &optional end)
23331 "Encode TIMESTAMP object into Emacs internal time.
23332 Use end of date range or time range when END is non-nil."
23333 (apply #'encode-time
23334 (cons 0
23335 (mapcar
23336 (lambda (prop) (or (org-element-property prop timestamp) 0))
23337 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23338 '(:minute-start :hour-start :day-start :month-start
23339 :year-start))))))
23341 (defun org-timestamp-has-time-p (timestamp)
23342 "Non-nil when TIMESTAMP has a time specified."
23343 (org-element-property :hour-start timestamp))
23345 (defun org-timestamp-format (timestamp format &optional end utc)
23346 "Format a TIMESTAMP object into a string.
23348 FORMAT is a format specifier to be passed to
23349 `format-time-string'.
23351 When optional argument END is non-nil, use end of date-range or
23352 time-range, if possible.
23354 When optional argument UTC is non-nil, time will be expressed as
23355 Universal Time."
23356 (format-time-string
23357 format (org-timestamp--to-internal-time timestamp end)
23358 (and utc t)))
23360 (defun org-timestamp-split-range (timestamp &optional end)
23361 "Extract a TIMESTAMP object from a date or time range.
23363 END, when non-nil, means extract the end of the range.
23364 Otherwise, extract its start.
23366 Return a new timestamp object."
23367 (let ((type (org-element-property :type timestamp)))
23368 (if (memq type '(active inactive diary)) timestamp
23369 (let ((split-ts (org-element-copy timestamp)))
23370 ;; Set new type.
23371 (org-element-put-property
23372 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23373 ;; Copy start properties over end properties if END is
23374 ;; non-nil. Otherwise, copy end properties over `start' ones.
23375 (let ((p-alist '((:minute-start . :minute-end)
23376 (:hour-start . :hour-end)
23377 (:day-start . :day-end)
23378 (:month-start . :month-end)
23379 (:year-start . :year-end))))
23380 (dolist (p-cell p-alist)
23381 (org-element-put-property
23382 split-ts
23383 (funcall (if end #'car #'cdr) p-cell)
23384 (org-element-property
23385 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23386 ;; Eventually refresh `:raw-value'.
23387 (org-element-put-property split-ts :raw-value nil)
23388 (org-element-put-property
23389 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23391 (defun org-timestamp-translate (timestamp &optional boundary)
23392 "Translate TIMESTAMP object to custom format.
23394 Format string is defined in `org-time-stamp-custom-formats',
23395 which see.
23397 When optional argument BOUNDARY is non-nil, it is either the
23398 symbol `start' or `end'. In this case, only translate the
23399 starting or ending part of TIMESTAMP if it is a date or time
23400 range. Otherwise, translate both parts.
23402 Return timestamp as-is if `org-display-custom-times' is nil or if
23403 it has a `diary' type."
23404 (let ((type (org-element-property :type timestamp)))
23405 (if (or (not org-display-custom-times) (eq type 'diary))
23406 (org-element-interpret-data timestamp)
23407 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23408 org-time-stamp-custom-formats)))
23409 (if (and (not boundary) (memq type '(active-range inactive-range)))
23410 (concat (org-timestamp-format timestamp fmt)
23411 "--"
23412 (org-timestamp-format timestamp fmt t))
23413 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23417 ;;; Other stuff.
23419 (defvar reftex-docstruct-symbol)
23420 (defvar org--rds)
23422 (defun org-reftex-citation ()
23423 "Use reftex-citation to insert a citation into the buffer.
23424 This looks for a line like
23426 #+BIBLIOGRAPHY: foo plain option:-d
23428 and derives from it that foo.bib is the bibliography file relevant
23429 for this document. It then installs the necessary environment for RefTeX
23430 to work in this buffer and calls `reftex-citation' to insert a citation
23431 into the buffer.
23433 Export of such citations to both LaTeX and HTML is handled by the contributed
23434 package ox-bibtex by Taru Karttunen."
23435 (interactive)
23436 (let ((reftex-docstruct-symbol 'org--rds)
23437 org--rds bib)
23438 (org-with-wide-buffer
23439 (let ((case-fold-search t)
23440 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23441 (if (not (save-excursion
23442 (or (re-search-forward re nil t)
23443 (re-search-backward re nil t))))
23444 (user-error "No bibliography defined in file")
23445 (setq bib (concat (match-string 1) ".bib")
23446 org--rds (list (list 'bib bib))))))
23447 (call-interactively 'reftex-citation)))
23449 ;;;; Functions extending outline functionality
23451 (defun org-beginning-of-line (&optional n)
23452 "Go to the beginning of the current visible line.
23454 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23455 tags on the first attempt, and only move to after the tags when
23456 the cursor is already beyond the end of the headline.
23458 With argument N not nil or 1, move forward N - 1 lines first."
23459 (interactive "^p")
23460 (let ((origin (point))
23461 (special (pcase org-special-ctrl-a/e
23462 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23463 deactivate-mark)
23464 ;; First move to a visible line.
23465 (if (bound-and-true-p visual-line-mode)
23466 (beginning-of-visual-line n)
23467 (move-beginning-of-line n)
23468 ;; `move-beginning-of-line' may leave point after invisible
23469 ;; characters if line starts with such of these (e.g., with
23470 ;; a link at column 0). Really move to the beginning of the
23471 ;; current visible line.
23472 (beginning-of-line))
23473 (cond
23474 ;; No special behavior. Point is already at the beginning of
23475 ;; a line, logical or visual.
23476 ((not special))
23477 ;; `beginning-of-visual-line' left point before logical beginning
23478 ;; of line: point is at the beginning of a visual line. Bail
23479 ;; out.
23480 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23481 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23482 ;; At a headline, special position is before the title, but
23483 ;; after any TODO keyword or priority cookie.
23484 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23485 (line-end-position)))
23486 (bol (point)))
23487 (if (eq special 'reversed)
23488 (when (and (= origin bol) (eq last-command this-command))
23489 (goto-char refpos))
23490 (when (or (> origin refpos) (= origin bol))
23491 (goto-char refpos)))))
23492 ((and (looking-at org-list-full-item-re)
23493 (memq (org-element-type (save-match-data (org-element-at-point)))
23494 '(item plain-list)))
23495 ;; Set special position at first white space character after
23496 ;; bullet, and check-box, if any.
23497 (let ((after-bullet
23498 (let ((box (match-end 3)))
23499 (cond ((not box) (match-end 1))
23500 ((eq (char-after box) ?\s) (1+ box))
23501 (t box)))))
23502 (if (eq special 'reversed)
23503 (when (and (= (point) origin) (eq last-command this-command))
23504 (goto-char after-bullet))
23505 (when (or (> origin after-bullet) (= (point) origin))
23506 (goto-char after-bullet)))))
23507 ;; No special context. Point is already at beginning of line.
23508 (t nil))))
23510 (defun org-end-of-line (&optional n)
23511 "Go to the end of the line, but before ellipsis, if any.
23513 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23514 tags on the first attempt, and only move to after the tags when
23515 the cursor is already beyond the end of the headline.
23517 With argument N not nil or 1, move forward N - 1 lines first."
23518 (interactive "^p")
23519 (let ((origin (point))
23520 (special (pcase org-special-ctrl-a/e
23521 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23522 deactivate-mark)
23523 ;; First move to a visible line.
23524 (if (bound-and-true-p visual-line-mode)
23525 (beginning-of-visual-line n)
23526 (move-beginning-of-line n))
23527 (cond
23528 ;; At a headline, with tags.
23529 ((and special
23530 (save-excursion
23531 (beginning-of-line)
23532 (let ((case-fold-search nil))
23533 (looking-at org-complex-heading-regexp)))
23534 (match-end 5))
23535 (let ((tags (save-excursion
23536 (goto-char (match-beginning 5))
23537 (skip-chars-backward " \t")
23538 (point)))
23539 (visual-end (and (bound-and-true-p visual-line-mode)
23540 (save-excursion
23541 (end-of-visual-line)
23542 (point)))))
23543 ;; If `end-of-visual-line' brings us before end of line or
23544 ;; even tags, i.e., the headline spans over multiple visual
23545 ;; lines, move there.
23546 (cond ((and visual-end
23547 (< visual-end tags)
23548 (<= origin visual-end))
23549 (goto-char visual-end))
23550 ((eq special 'reversed)
23551 (if (and (= origin (line-end-position))
23552 (eq this-command last-command))
23553 (goto-char tags)
23554 (end-of-line)))
23556 (if (or (< origin tags) (= origin (line-end-position)))
23557 (goto-char tags)
23558 (end-of-line))))))
23559 ((bound-and-true-p visual-line-mode)
23560 (let ((bol (line-beginning-position)))
23561 (end-of-visual-line)
23562 ;; If `end-of-visual-line' gets us past the ellipsis at the
23563 ;; end of a line, backtrack and use `end-of-line' instead.
23564 (when (/= bol (line-beginning-position))
23565 (goto-char bol)
23566 (end-of-line))))
23567 (t (end-of-line)))))
23569 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23570 (define-key org-mode-map "\C-e" 'org-end-of-line)
23572 (defun org-backward-sentence (&optional _arg)
23573 "Go to beginning of sentence, or beginning of table field.
23574 This will call `backward-sentence' or `org-table-beginning-of-field',
23575 depending on context."
23576 (interactive)
23577 (let* ((element (org-element-at-point))
23578 (contents-begin (org-element-property :contents-begin element))
23579 (table (org-element-lineage element '(table) t)))
23580 (if (and table
23581 (> (point) contents-begin)
23582 (<= (point) (org-element-property :contents-end table)))
23583 (call-interactively #'org-table-beginning-of-field)
23584 (save-restriction
23585 (when (and contents-begin
23586 (< (point-min) contents-begin)
23587 (> (point) contents-begin))
23588 (narrow-to-region contents-begin
23589 (org-element-property :contents-end element)))
23590 (call-interactively #'backward-sentence)))))
23592 (defun org-forward-sentence (&optional _arg)
23593 "Go to end of sentence, or end of table field.
23594 This will call `forward-sentence' or `org-table-end-of-field',
23595 depending on context."
23596 (interactive)
23597 (if (and (org-at-heading-p)
23598 (save-restriction (skip-chars-forward " \t") (not (eolp))))
23599 (save-restriction
23600 (narrow-to-region (line-beginning-position) (line-end-position))
23601 (call-interactively #'forward-sentence))
23602 (let* ((element (org-element-at-point))
23603 (contents-end (org-element-property :contents-end element))
23604 (table (org-element-lineage element '(table) t)))
23605 (if (and table
23606 (>= (point) (org-element-property :contents-begin table))
23607 (< (point) contents-end))
23608 (call-interactively #'org-table-end-of-field)
23609 (save-restriction
23610 (when (and contents-end
23611 (> (point-max) contents-end)
23612 ;; Skip blank lines between elements.
23613 (< (org-element-property :end element)
23614 (save-excursion (goto-char contents-end)
23615 (skip-chars-forward " \r\t\n"))))
23616 (narrow-to-region (org-element-property :contents-begin element)
23617 contents-end))
23618 (call-interactively #'forward-sentence))))))
23620 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23621 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23623 (defun org-kill-line (&optional _arg)
23624 "Kill line, to tags or end of line."
23625 (interactive)
23626 (cond
23627 ((or (not org-special-ctrl-k)
23628 (bolp)
23629 (not (org-at-heading-p)))
23630 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23631 org-ctrl-k-protect-subtree
23632 (or (eq org-ctrl-k-protect-subtree 'error)
23633 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23634 (user-error "C-k aborted as it would kill a hidden subtree"))
23635 (call-interactively
23636 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23637 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23638 (kill-region (point) (match-beginning 1))
23639 (org-set-tags nil t))
23640 (t (kill-region (point) (point-at-eol)))))
23642 (define-key org-mode-map "\C-k" 'org-kill-line)
23644 (defun org-yank (&optional arg)
23645 "Yank. If the kill is a subtree, treat it specially.
23646 This command will look at the current kill and check if is a single
23647 subtree, or a series of subtrees[1]. If it passes the test, and if the
23648 cursor is at the beginning of a line or after the stars of a currently
23649 empty headline, then the yank is handled specially. How exactly depends
23650 on the value of the following variables.
23652 `org-yank-folded-subtrees'
23653 By default, this variable is non-nil, which results in
23654 subtree(s) being folded after insertion, except if doing so
23655 would swallow text after the yanked text.
23657 `org-yank-adjusted-subtrees'
23658 When non-nil (the default value is nil), the subtree will be
23659 promoted or demoted in order to fit into the local outline tree
23660 structure, which means that the level will be adjusted so that it
23661 becomes the smaller one of the two *visible* surrounding headings.
23663 Any prefix to this command will cause `yank' to be called directly with
23664 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23665 will just
23666 plainly yank the text as it is.
23668 \[1] The test checks if the first non-white line is a heading
23669 and if there are no other headings with fewer stars."
23670 (interactive "P")
23671 (org-yank-generic 'yank arg))
23673 (defun org-yank-generic (command arg)
23674 "Perform some yank-like command.
23676 This function implements the behavior described in the `org-yank'
23677 documentation. However, it has been generalized to work for any
23678 interactive command with similar behavior."
23680 ;; pretend to be command COMMAND
23681 (setq this-command command)
23683 (if arg
23684 (call-interactively command)
23686 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23687 (and (org-kill-is-subtree-p)
23688 (or (bolp)
23689 (and (looking-at "[ \t]*$")
23690 (string-match
23691 "\\`\\*+\\'"
23692 (buffer-substring (point-at-bol) (point)))))))
23693 swallowp)
23694 (cond
23695 ((and subtreep org-yank-folded-subtrees)
23696 (let ((beg (point))
23697 end)
23698 (if (and subtreep org-yank-adjusted-subtrees)
23699 (org-paste-subtree nil nil 'for-yank)
23700 (call-interactively command))
23702 (setq end (point))
23703 (goto-char beg)
23704 (when (and (bolp) subtreep
23705 (not (setq swallowp
23706 (org-yank-folding-would-swallow-text beg end))))
23707 (org-with-limited-levels
23708 (or (looking-at org-outline-regexp)
23709 (re-search-forward org-outline-regexp-bol end t))
23710 (while (and (< (point) end) (looking-at org-outline-regexp))
23711 (outline-hide-subtree)
23712 (org-cycle-show-empty-lines 'folded)
23713 (condition-case nil
23714 (outline-forward-same-level 1)
23715 (error (goto-char end))))))
23716 (when swallowp
23717 (message
23718 "Inserted text not folded because that would swallow text"))
23720 (goto-char end)
23721 (skip-chars-forward " \t\n\r")
23722 (beginning-of-line 1)
23723 (push-mark beg 'nomsg)))
23724 ((and subtreep org-yank-adjusted-subtrees)
23725 (let ((beg (point-at-bol)))
23726 (org-paste-subtree nil nil 'for-yank)
23727 (push-mark beg 'nomsg)))
23729 (call-interactively command))))))
23731 (defun org-yank-folding-would-swallow-text (beg end)
23732 "Would hide-subtree at BEG swallow any text after END?"
23733 (let (level)
23734 (org-with-limited-levels
23735 (save-excursion
23736 (goto-char beg)
23737 (when (or (looking-at org-outline-regexp)
23738 (re-search-forward org-outline-regexp-bol end t))
23739 (setq level (org-outline-level)))
23740 (goto-char end)
23741 (skip-chars-forward " \t\r\n\v\f")
23742 (not (or (eobp)
23743 (and (bolp) (looking-at-p org-outline-regexp)
23744 (<= (org-outline-level) level))))))))
23746 (define-key org-mode-map "\C-y" 'org-yank)
23748 (defun org-truely-invisible-p ()
23749 "Check if point is at a character currently not visible.
23750 This version does not only check the character property, but also
23751 `visible-mode'."
23752 (unless (bound-and-true-p visible-mode)
23753 (org-invisible-p)))
23755 (defun org-invisible-p2 ()
23756 "Check if point is at a character currently not visible.
23758 If the point is at EOL (and not at the beginning of a buffer too),
23759 move it back by one char before doing this check."
23760 (save-excursion
23761 (when (and (eolp) (not (bobp)))
23762 (backward-char 1))
23763 (org-invisible-p)))
23765 (defun org-back-to-heading (&optional invisible-ok)
23766 "Call `outline-back-to-heading', but provide a better error message."
23767 (condition-case nil
23768 (outline-back-to-heading invisible-ok)
23769 (error (error "Before first headline at position %d in buffer %s"
23770 (point) (current-buffer)))))
23772 (defun org-before-first-heading-p ()
23773 "Before first heading?"
23774 (save-excursion
23775 (end-of-line)
23776 (null (re-search-backward org-outline-regexp-bol nil t))))
23778 (defun org-at-heading-p (&optional ignored)
23779 (outline-on-heading-p t))
23781 (defun org-in-commented-heading-p (&optional no-inheritance)
23782 "Non-nil if point is under a commented heading.
23783 This function also checks ancestors of the current headline,
23784 unless optional argument NO-INHERITANCE is non-nil."
23785 (cond
23786 ((org-before-first-heading-p) nil)
23787 ((let ((headline (nth 4 (org-heading-components))))
23788 (and headline
23789 (let ((case-fold-search nil))
23790 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23791 headline)))))
23792 (no-inheritance nil)
23794 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23796 (defun org-at-comment-p nil
23797 "Is cursor in a commented line?"
23798 (save-excursion
23799 (save-match-data
23800 (beginning-of-line)
23801 (looking-at "^[ \t]*# "))))
23803 (defun org-at-drawer-p nil
23804 "Is cursor at a drawer keyword?"
23805 (save-excursion
23806 (move-beginning-of-line 1)
23807 (looking-at org-drawer-regexp)))
23809 (defun org-at-block-p nil
23810 "Is cursor at a block keyword?"
23811 (save-excursion
23812 (move-beginning-of-line 1)
23813 (looking-at org-block-regexp)))
23815 (defun org-point-at-end-of-empty-headline ()
23816 "If point is at the end of an empty headline, return t, else nil.
23817 If the heading only contains a TODO keyword, it is still still considered
23818 empty."
23819 (let ((case-fold-search nil))
23820 (and (looking-at "[ \t]*$")
23821 org-todo-line-regexp
23822 (save-excursion
23823 (beginning-of-line)
23824 (looking-at org-todo-line-regexp)
23825 (string= (match-string 3) "")))))
23827 (defun org-at-heading-or-item-p ()
23828 (or (org-at-heading-p) (org-at-item-p)))
23830 (defun org-at-target-p ()
23831 (or (org-in-regexp org-radio-target-regexp)
23832 (org-in-regexp org-target-regexp)))
23833 ;; Compatibility alias with Org versions < 7.8.03
23834 (defalias 'org-on-target-p 'org-at-target-p)
23836 (defun org-up-heading-all (arg)
23837 "Move to the heading line of which the present line is a subheading.
23838 This function considers both visible and invisible heading lines.
23839 With argument, move up ARG levels."
23840 (outline-up-heading arg t))
23842 (defun org-up-heading-safe ()
23843 "Move to the heading line of which the present line is a subheading.
23844 This version will not throw an error. It will return the level of the
23845 headline found, or nil if no higher level is found.
23847 Also, this function will be a lot faster than `outline-up-heading',
23848 because it relies on stars being the outline starters. This can really
23849 make a significant difference in outlines with very many siblings."
23850 (when (ignore-errors (org-back-to-heading t))
23851 (let ((level-up (1- (funcall outline-level))))
23852 (and (> level-up 0)
23853 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23854 (funcall outline-level)))))
23856 (defun org-first-sibling-p ()
23857 "Is this heading the first child of its parents?"
23858 (interactive)
23859 (let ((re org-outline-regexp-bol)
23860 level l)
23861 (unless (org-at-heading-p t)
23862 (user-error "Not at a heading"))
23863 (setq level (funcall outline-level))
23864 (save-excursion
23865 (if (not (re-search-backward re nil t))
23867 (setq l (funcall outline-level))
23868 (< l level)))))
23870 (defun org-goto-sibling (&optional previous)
23871 "Goto the next sibling, even if it is invisible.
23872 When PREVIOUS is set, go to the previous sibling instead. Returns t
23873 when a sibling was found. When none is found, return nil and don't
23874 move point."
23875 (let ((fun (if previous 're-search-backward 're-search-forward))
23876 (pos (point))
23877 (re org-outline-regexp-bol)
23878 level l)
23879 (when (ignore-errors (org-back-to-heading t))
23880 (setq level (funcall outline-level))
23881 (catch 'exit
23882 (or previous (forward-char 1))
23883 (while (funcall fun re nil t)
23884 (setq l (funcall outline-level))
23885 (when (< l level) (goto-char pos) (throw 'exit nil))
23886 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23887 (goto-char pos)
23888 nil))))
23890 (defun org-show-siblings ()
23891 "Show all siblings of the current headline."
23892 (save-excursion
23893 (while (org-goto-sibling) (org-flag-heading nil)))
23894 (save-excursion
23895 (while (org-goto-sibling 'previous)
23896 (org-flag-heading nil))))
23898 (defun org-goto-first-child ()
23899 "Goto the first child, even if it is invisible.
23900 Return t when a child was found. Otherwise don't move point and
23901 return nil."
23902 (let (level (pos (point)) (re org-outline-regexp-bol))
23903 (when (ignore-errors (org-back-to-heading t))
23904 (setq level (outline-level))
23905 (forward-char 1)
23906 (if (and (re-search-forward re nil t) (> (outline-level) level))
23907 (progn (goto-char (match-beginning 0)) t)
23908 (goto-char pos) nil))))
23910 (defun org-show-hidden-entry ()
23911 "Show an entry where even the heading is hidden."
23912 (save-excursion
23913 (org-show-entry)))
23915 (defun org-flag-heading (flag &optional entry)
23916 "Flag the current heading. FLAG non-nil means make invisible.
23917 When ENTRY is non-nil, show the entire entry."
23918 (save-excursion
23919 (org-back-to-heading t)
23920 ;; Check if we should show the entire entry
23921 (if entry
23922 (progn
23923 (org-show-entry)
23924 (save-excursion
23925 (and (outline-next-heading)
23926 (org-flag-heading nil))))
23927 (outline-flag-region (max (point-min) (1- (point)))
23928 (save-excursion (outline-end-of-heading) (point))
23929 flag))))
23931 (defun org-get-next-sibling ()
23932 "Move to next heading of the same level, and return point.
23933 If there is no such heading, return nil.
23934 This is like outline-next-sibling, but invisible headings are ok."
23935 (let ((level (funcall outline-level)))
23936 (outline-next-heading)
23937 (while (and (not (eobp)) (> (funcall outline-level) level))
23938 (outline-next-heading))
23939 (unless (or (eobp) (< (funcall outline-level) level))
23940 (point))))
23942 (defun org-get-last-sibling ()
23943 "Move to previous heading of the same level, and return point.
23944 If there is no such heading, return nil."
23945 (let ((opoint (point))
23946 (level (funcall outline-level)))
23947 (outline-previous-heading)
23948 (when (and (/= (point) opoint) (outline-on-heading-p t))
23949 (while (and (> (funcall outline-level) level)
23950 (not (bobp)))
23951 (outline-previous-heading))
23952 (unless (< (funcall outline-level) level)
23953 (point)))))
23955 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23956 "Goto to the end of a subtree."
23957 ;; This contains an exact copy of the original function, but it uses
23958 ;; `org-back-to-heading', to make it work also in invisible
23959 ;; trees. And is uses an invisible-ok argument.
23960 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23961 ;; Furthermore, when used inside Org, finding the end of a large subtree
23962 ;; with many children and grandchildren etc, this can be much faster
23963 ;; than the outline version.
23964 (org-back-to-heading invisible-ok)
23965 (let ((first t)
23966 (level (funcall outline-level)))
23967 (if (and (derived-mode-p 'org-mode) (< level 1000))
23968 ;; A true heading (not a plain list item), in Org
23969 ;; This means we can easily find the end by looking
23970 ;; only for the right number of stars. Using a regexp to do
23971 ;; this is so much faster than using a Lisp loop.
23972 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23973 (forward-char 1)
23974 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23975 ;; something else, do it the slow way
23976 (while (and (not (eobp))
23977 (or first (> (funcall outline-level) level)))
23978 (setq first nil)
23979 (outline-next-heading)))
23980 (unless to-heading
23981 (when (memq (preceding-char) '(?\n ?\^M))
23982 ;; Go to end of line before heading
23983 (forward-char -1)
23984 (when (memq (preceding-char) '(?\n ?\^M))
23985 ;; leave blank line before heading
23986 (forward-char -1)))))
23987 (point))
23989 (defun org-end-of-meta-data (&optional full)
23990 "Skip planning line and properties drawer in current entry.
23991 When optional argument FULL is non-nil, also skip empty lines,
23992 clocking lines and regular drawers at the beginning of the
23993 entry."
23994 (org-back-to-heading t)
23995 (forward-line)
23996 (when (looking-at-p org-planning-line-re) (forward-line))
23997 (when (looking-at org-property-drawer-re)
23998 (goto-char (match-end 0))
23999 (forward-line))
24000 (when (and full (not (org-at-heading-p)))
24001 (catch 'exit
24002 (let ((end (save-excursion (outline-next-heading) (point)))
24003 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24004 (while (not (eobp))
24005 (cond ((looking-at-p org-drawer-regexp)
24006 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24007 (forward-line)
24008 (throw 'exit t)))
24009 ((looking-at-p re) (forward-line))
24010 (t (throw 'exit t))))))))
24012 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24013 "Move forward to the ARG'th subheading at same level as this one.
24014 Stop at the first and last subheadings of a superior heading.
24015 Normally this only looks at visible headings, but when INVISIBLE-OK is
24016 non-nil it will also look at invisible ones."
24017 (interactive "p")
24018 (let ((backward? (and arg (< arg 0))))
24019 (if (org-before-first-heading-p)
24020 (if backward? (goto-char (point-min)) (outline-next-heading))
24021 (org-back-to-heading invisible-ok)
24022 (unless backward? (end-of-line)) ;do not match current headline
24023 (let ((level (- (match-end 0) (match-beginning 0) 1))
24024 (f (if backward? #'re-search-backward #'re-search-forward))
24025 (count (if arg (abs arg) 1))
24026 (result (point)))
24027 (while (and (> count 0)
24028 (funcall f org-outline-regexp-bol nil 'move))
24029 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24030 (cond ((< l level) (setq count 0))
24031 ((and (= l level)
24032 (or invisible-ok
24033 (not (org-invisible-p
24034 (line-beginning-position)))))
24035 (cl-decf count)
24036 (when (= l level) (setq result (point)))))))
24037 (goto-char result))
24038 (beginning-of-line))))
24040 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24041 "Move backward to the ARG'th subheading at same level as this one.
24042 Stop at the first and last subheadings of a superior heading."
24043 (interactive "p")
24044 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24046 (defun org-next-visible-heading (arg)
24047 "Move to the next visible heading.
24049 This function wraps `outline-next-visible-heading' with
24050 `org-with-limited-levels' in order to skip over inline tasks and
24051 respect customization of `org-odd-levels-only'."
24052 (interactive "p")
24053 (org-with-limited-levels
24054 (outline-next-visible-heading arg)))
24056 (defun org-previous-visible-heading (arg)
24057 "Move to the previous visible heading.
24059 This function wraps `outline-previous-visible-heading' with
24060 `org-with-limited-levels' in order to skip over inline tasks and
24061 respect customization of `org-odd-levels-only'."
24062 (interactive "p")
24063 (org-with-limited-levels
24064 (outline-previous-visible-heading arg)))
24066 (defun org-next-block (arg &optional backward block-regexp)
24067 "Jump to the next block.
24069 With a prefix argument ARG, jump forward ARG many blocks.
24071 When BACKWARD is non-nil, jump to the previous block.
24073 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24074 Match data is set according to this regexp when the function
24075 returns.
24077 Return point at beginning of the opening line of found block.
24078 Throw an error if no block is found."
24079 (interactive "p")
24080 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24081 (case-fold-search t)
24082 (search-fn (if backward #'re-search-backward #'re-search-forward))
24083 (count (or arg 1))
24084 (origin (point))
24085 last-element)
24086 (if backward (beginning-of-line) (end-of-line))
24087 (while (and (> count 0) (funcall search-fn re nil t))
24088 (let ((element (save-excursion
24089 (goto-char (match-beginning 0))
24090 (save-match-data (org-element-at-point)))))
24091 (when (and (memq (org-element-type element)
24092 '(center-block comment-block dynamic-block
24093 example-block export-block quote-block
24094 special-block src-block verse-block))
24095 (<= (match-beginning 0)
24096 (org-element-property :post-affiliated element)))
24097 (setq last-element element)
24098 (cl-decf count))))
24099 (if (= count 0)
24100 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24101 (save-match-data (org-show-context)))
24102 (goto-char origin)
24103 (user-error "No %s code blocks" (if backward "previous" "further")))))
24105 (defun org-previous-block (arg &optional block-regexp)
24106 "Jump to the previous block.
24107 With a prefix argument ARG, jump backward ARG many source blocks.
24108 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24109 (interactive "p")
24110 (org-next-block arg t block-regexp))
24112 (defun org-forward-paragraph ()
24113 "Move forward to beginning of next paragraph or equivalent.
24115 The function moves point to the beginning of the next visible
24116 structural element, which can be a paragraph, a table, a list
24117 item, etc. It also provides some special moves for convenience:
24119 - On an affiliated keyword, jump to the beginning of the
24120 relative element.
24121 - On an item or a footnote definition, move to the second
24122 element inside, if any.
24123 - On a table or a property drawer, jump after it.
24124 - On a verse or source block, stop after blank lines."
24125 (interactive)
24126 (unless (eobp)
24127 (let* ((deactivate-mark nil)
24128 (element (org-element-at-point))
24129 (type (org-element-type element))
24130 (post-affiliated (org-element-property :post-affiliated element))
24131 (contents-begin (org-element-property :contents-begin element))
24132 (contents-end (org-element-property :contents-end element))
24133 (end (let ((end (org-element-property :end element)) (parent element))
24134 (while (and (setq parent (org-element-property :parent parent))
24135 (= (org-element-property :contents-end parent) end))
24136 (setq end (org-element-property :end parent)))
24137 end)))
24138 (cond ((not element)
24139 (skip-chars-forward " \r\t\n")
24140 (or (eobp) (beginning-of-line)))
24141 ;; On affiliated keywords, move to element's beginning.
24142 ((< (point) post-affiliated)
24143 (goto-char post-affiliated))
24144 ;; At a table row, move to the end of the table. Similarly,
24145 ;; at a node property, move to the end of the property
24146 ;; drawer.
24147 ((memq type '(node-property table-row))
24148 (goto-char (org-element-property
24149 :end (org-element-property :parent element))))
24150 ((memq type '(property-drawer table)) (goto-char end))
24151 ;; Consider blank lines as separators in verse and source
24152 ;; blocks to ease editing.
24153 ((memq type '(src-block verse-block))
24154 (when (eq type 'src-block)
24155 (setq contents-end
24156 (save-excursion (goto-char end)
24157 (skip-chars-backward " \r\t\n")
24158 (line-beginning-position))))
24159 (beginning-of-line)
24160 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24161 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24162 (goto-char end)
24163 (skip-chars-forward " \r\t\n")
24164 (if (= (point) contents-end) (goto-char end)
24165 (beginning-of-line))))
24166 ;; With no contents, just skip element.
24167 ((not contents-begin) (goto-char end))
24168 ;; If contents are invisible, skip the element altogether.
24169 ((org-invisible-p (line-end-position))
24170 (cl-case type
24171 (headline
24172 (org-with-limited-levels (outline-next-visible-heading 1)))
24173 ;; At a plain list, make sure we move to the next item
24174 ;; instead of skipping the whole list.
24175 (plain-list (forward-char)
24176 (org-forward-paragraph))
24177 (otherwise (goto-char end))))
24178 ((>= (point) contents-end) (goto-char end))
24179 ((>= (point) contents-begin)
24180 ;; This can only happen on paragraphs and plain lists.
24181 (cl-case type
24182 (paragraph (goto-char end))
24183 ;; At a plain list, try to move to second element in
24184 ;; first item, if possible.
24185 (plain-list (end-of-line)
24186 (org-forward-paragraph))))
24187 ;; When contents start on the middle of a line (e.g. in
24188 ;; items and footnote definitions), try to reach first
24189 ;; element starting after current line.
24190 ((> (line-end-position) contents-begin)
24191 (end-of-line)
24192 (org-forward-paragraph))
24193 (t (goto-char contents-begin))))))
24195 (defun org-backward-paragraph ()
24196 "Move backward to start of previous paragraph or equivalent.
24198 The function moves point to the beginning of the current
24199 structural element, which can be a paragraph, a table, a list
24200 item, etc., or to the beginning of the previous visible one if
24201 point is already there. It also provides some special moves for
24202 convenience:
24204 - On an affiliated keyword, jump to the first one.
24205 - On a table or a property drawer, move to its beginning.
24206 - On a verse or source block, stop before blank lines."
24207 (interactive)
24208 (unless (bobp)
24209 (let* ((deactivate-mark nil)
24210 (element (org-element-at-point))
24211 (type (org-element-type element))
24212 (contents-begin (org-element-property :contents-begin element))
24213 (contents-end (org-element-property :contents-end element))
24214 (post-affiliated (org-element-property :post-affiliated element))
24215 (begin (org-element-property :begin element)))
24216 (cond
24217 ((not element) (goto-char (point-min)))
24218 ((= (point) begin)
24219 (backward-char)
24220 (org-backward-paragraph))
24221 ((<= (point) post-affiliated) (goto-char begin))
24222 ((memq type '(node-property table-row))
24223 (goto-char (org-element-property
24224 :post-affiliated (org-element-property :parent element))))
24225 ((memq type '(property-drawer table)) (goto-char begin))
24226 ((memq type '(src-block verse-block))
24227 (when (eq type 'src-block)
24228 (setq contents-begin
24229 (save-excursion (goto-char begin) (forward-line) (point))))
24230 (if (= (point) contents-begin) (goto-char post-affiliated)
24231 ;; Inside a verse block, see blank lines as paragraph
24232 ;; separators.
24233 (let ((origin (point)))
24234 (skip-chars-backward " \r\t\n" contents-begin)
24235 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24236 (skip-chars-forward " \r\t\n" origin)
24237 (if (= (point) origin) (goto-char contents-begin)
24238 (beginning-of-line))))))
24239 ((not contents-begin) (goto-char (or post-affiliated begin)))
24240 ((eq type 'paragraph)
24241 (goto-char contents-begin)
24242 ;; When at first paragraph in an item or a footnote definition,
24243 ;; move directly to beginning of line.
24244 (let ((parent-contents
24245 (org-element-property
24246 :contents-begin (org-element-property :parent element))))
24247 (when (and parent-contents (= parent-contents contents-begin))
24248 (beginning-of-line))))
24249 ;; At the end of a greater element, move to the beginning of the
24250 ;; last element within.
24251 ((>= (point) contents-end)
24252 (goto-char (1- contents-end))
24253 (org-backward-paragraph))
24254 (t (goto-char (or post-affiliated begin))))
24255 ;; Ensure we never leave point invisible.
24256 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
24258 (defun org-forward-element ()
24259 "Move forward by one element.
24260 Move to the next element at the same level, when possible."
24261 (interactive)
24262 (cond ((eobp) (user-error "Cannot move further down"))
24263 ((org-with-limited-levels (org-at-heading-p))
24264 (let ((origin (point)))
24265 (goto-char (org-end-of-subtree nil t))
24266 (unless (org-with-limited-levels (org-at-heading-p))
24267 (goto-char origin)
24268 (user-error "Cannot move further down"))))
24270 (let* ((elem (org-element-at-point))
24271 (end (org-element-property :end elem))
24272 (parent (org-element-property :parent elem)))
24273 (cond ((and parent (= (org-element-property :contents-end parent) end))
24274 (goto-char (org-element-property :end parent)))
24275 ((integer-or-marker-p end) (goto-char end))
24276 (t (message "No element at point")))))))
24278 (defun org-backward-element ()
24279 "Move backward by one element.
24280 Move to the previous element at the same level, when possible."
24281 (interactive)
24282 (cond ((bobp) (user-error "Cannot move further up"))
24283 ((org-with-limited-levels (org-at-heading-p))
24284 ;; At a headline, move to the previous one, if any, or stay
24285 ;; here.
24286 (let ((origin (point)))
24287 (org-with-limited-levels (org-backward-heading-same-level 1))
24288 ;; When current headline has no sibling above, move to its
24289 ;; parent.
24290 (when (= (point) origin)
24291 (or (org-with-limited-levels (org-up-heading-safe))
24292 (progn (goto-char origin)
24293 (user-error "Cannot move further up"))))))
24295 (let* ((elem (org-element-at-point))
24296 (beg (org-element-property :begin elem)))
24297 (cond
24298 ;; Move to beginning of current element if point isn't
24299 ;; there already.
24300 ((null beg) (message "No element at point"))
24301 ((/= (point) beg) (goto-char beg))
24302 (t (goto-char beg)
24303 (skip-chars-backward " \r\t\n")
24304 (unless (bobp)
24305 (let ((prev (org-element-at-point)))
24306 (goto-char (org-element-property :begin prev))
24307 (while (and (setq prev (org-element-property :parent prev))
24308 (<= (org-element-property :end prev) beg))
24309 (goto-char (org-element-property :begin prev)))))))))))
24311 (defun org-up-element ()
24312 "Move to upper element."
24313 (interactive)
24314 (if (org-with-limited-levels (org-at-heading-p))
24315 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24316 (let* ((elem (org-element-at-point))
24317 (parent (org-element-property :parent elem)))
24318 (if parent (goto-char (org-element-property :begin parent))
24319 (if (org-with-limited-levels (org-before-first-heading-p))
24320 (user-error "No surrounding element")
24321 (org-with-limited-levels (org-back-to-heading)))))))
24323 (defun org-down-element ()
24324 "Move to inner element."
24325 (interactive)
24326 (let ((element (org-element-at-point)))
24327 (cond
24328 ((memq (org-element-type element) '(plain-list table))
24329 (goto-char (org-element-property :contents-begin element))
24330 (forward-char))
24331 ((memq (org-element-type element) org-element-greater-elements)
24332 ;; If contents are hidden, first disclose them.
24333 (when (org-invisible-p (line-end-position)) (org-cycle))
24334 (goto-char (or (org-element-property :contents-begin element)
24335 (user-error "No content for this element"))))
24336 (t (user-error "No inner element")))))
24338 (defun org-drag-element-backward ()
24339 "Move backward element at point."
24340 (interactive)
24341 (let ((elem (or (org-element-at-point)
24342 (user-error "No element at point"))))
24343 (if (eq (org-element-type elem) 'headline)
24344 ;; Preserve point when moving a whole tree, even if point was
24345 ;; on blank lines below the headline.
24346 (let ((offset (skip-chars-backward " \t\n")))
24347 (unwind-protect (org-move-subtree-up)
24348 (forward-char (- offset))))
24349 (let ((prev-elem
24350 (save-excursion
24351 (goto-char (org-element-property :begin elem))
24352 (skip-chars-backward " \r\t\n")
24353 (unless (bobp)
24354 (let* ((beg (org-element-property :begin elem))
24355 (prev (org-element-at-point))
24356 (up prev))
24357 (while (and (setq up (org-element-property :parent up))
24358 (<= (org-element-property :end up) beg))
24359 (setq prev up))
24360 prev)))))
24361 ;; Error out if no previous element or previous element is
24362 ;; a parent of the current one.
24363 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24364 (user-error "Cannot drag element backward")
24365 (let ((pos (point)))
24366 (org-element-swap-A-B prev-elem elem)
24367 (goto-char (+ (org-element-property :begin prev-elem)
24368 (- pos (org-element-property :begin elem))))))))))
24370 (defun org-drag-element-forward ()
24371 "Move forward element at point."
24372 (interactive)
24373 (let* ((pos (point))
24374 (elem (or (org-element-at-point)
24375 (user-error "No element at point"))))
24376 (when (= (point-max) (org-element-property :end elem))
24377 (user-error "Cannot drag element forward"))
24378 (goto-char (org-element-property :end elem))
24379 (let ((next-elem (org-element-at-point)))
24380 (when (or (org-element-nested-p elem next-elem)
24381 (and (eq (org-element-type next-elem) 'headline)
24382 (not (eq (org-element-type elem) 'headline))))
24383 (goto-char pos)
24384 (user-error "Cannot drag element forward"))
24385 ;; Compute new position of point: it's shifted by NEXT-ELEM
24386 ;; body's length (without final blanks) and by the length of
24387 ;; blanks between ELEM and NEXT-ELEM.
24388 (let ((size-next (- (save-excursion
24389 (goto-char (org-element-property :end next-elem))
24390 (skip-chars-backward " \r\t\n")
24391 (forward-line)
24392 ;; Small correction if buffer doesn't end
24393 ;; with a newline character.
24394 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24395 (org-element-property :begin next-elem)))
24396 (size-blank (- (org-element-property :end elem)
24397 (save-excursion
24398 (goto-char (org-element-property :end elem))
24399 (skip-chars-backward " \r\t\n")
24400 (forward-line)
24401 (point)))))
24402 (org-element-swap-A-B elem next-elem)
24403 (goto-char (+ pos size-next size-blank))))))
24405 (defun org-drag-line-forward (arg)
24406 "Drag the line at point ARG lines forward."
24407 (interactive "p")
24408 (dotimes (_ (abs arg))
24409 (let ((c (current-column)))
24410 (if (< 0 arg)
24411 (progn
24412 (beginning-of-line 2)
24413 (transpose-lines 1)
24414 (beginning-of-line 0))
24415 (transpose-lines 1)
24416 (beginning-of-line -1))
24417 (org-move-to-column c))))
24419 (defun org-drag-line-backward (arg)
24420 "Drag the line at point ARG lines backward."
24421 (interactive "p")
24422 (org-drag-line-forward (- arg)))
24424 (defun org-mark-element ()
24425 "Put point at beginning of this element, mark at end.
24427 Interactively, if this command is repeated or (in Transient Mark
24428 mode) if the mark is active, it marks the next element after the
24429 ones already marked."
24430 (interactive)
24431 (let (deactivate-mark)
24432 (if (and (called-interactively-p 'any)
24433 (or (and (eq last-command this-command) (mark t))
24434 (and transient-mark-mode mark-active)))
24435 (set-mark
24436 (save-excursion
24437 (goto-char (mark))
24438 (goto-char (org-element-property :end (org-element-at-point)))))
24439 (let ((element (org-element-at-point)))
24440 (end-of-line)
24441 (push-mark (org-element-property :end element) t t)
24442 (goto-char (org-element-property :begin element))))))
24444 (defun org-narrow-to-element ()
24445 "Narrow buffer to current element."
24446 (interactive)
24447 (let ((elem (org-element-at-point)))
24448 (cond
24449 ((eq (car elem) 'headline)
24450 (narrow-to-region
24451 (org-element-property :begin elem)
24452 (org-element-property :end elem)))
24453 ((memq (car elem) org-element-greater-elements)
24454 (narrow-to-region
24455 (org-element-property :contents-begin elem)
24456 (org-element-property :contents-end elem)))
24458 (narrow-to-region
24459 (org-element-property :begin elem)
24460 (org-element-property :end elem))))))
24462 (defun org-transpose-element ()
24463 "Transpose current and previous elements, keeping blank lines between.
24464 Point is moved after both elements."
24465 (interactive)
24466 (org-skip-whitespace)
24467 (let ((end (org-element-property :end (org-element-at-point))))
24468 (org-drag-element-backward)
24469 (goto-char end)))
24471 (defun org-unindent-buffer ()
24472 "Un-indent the visible part of the buffer.
24473 Relative indentation (between items, inside blocks, etc.) isn't
24474 modified."
24475 (interactive)
24476 (unless (eq major-mode 'org-mode)
24477 (user-error "Cannot un-indent a buffer not in Org mode"))
24478 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24479 (unindent-tree
24480 (lambda (contents)
24481 (dolist (element (reverse contents))
24482 (if (memq (org-element-type element) '(headline section))
24483 (funcall unindent-tree (org-element-contents element))
24484 (save-excursion
24485 (save-restriction
24486 (narrow-to-region
24487 (org-element-property :begin element)
24488 (org-element-property :end element))
24489 (org-do-remove-indentation))))))))
24490 (funcall unindent-tree (org-element-contents parse-tree))))
24492 (defun org-show-children (&optional level)
24493 "Show all direct subheadings of this heading.
24494 Prefix arg LEVEL is how many levels below the current level
24495 should be shown. Default is enough to cause the following
24496 heading to appear."
24497 (interactive "p")
24498 ;; If `orgstruct-mode' is active, use the slower version.
24499 (if orgstruct-mode (call-interactively #'outline-show-children)
24500 (save-excursion
24501 (org-back-to-heading t)
24502 (let* ((current-level (funcall outline-level))
24503 (max-level (org-get-valid-level
24504 current-level
24505 (if level (prefix-numeric-value level) 1)))
24506 (end (save-excursion (org-end-of-subtree t t)))
24507 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24508 (past-first-child nil)
24509 ;; Make sure to skip inlinetasks.
24510 (re (format regexp-fmt
24511 current-level
24512 (cond
24513 ((not (featurep 'org-inlinetask)) "")
24514 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24516 (t (1- org-inlinetask-min-level))))))
24517 ;; Display parent heading.
24518 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24519 (forward-line)
24520 ;; Display children. First child may be deeper than expected
24521 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24522 ;; MAX-LEVEL accordingly.
24523 (while (re-search-forward re end t)
24524 (unless past-first-child
24525 (setq re (format regexp-fmt
24526 current-level
24527 (max (funcall outline-level) max-level)))
24528 (setq past-first-child t))
24529 (outline-flag-region
24530 (line-end-position 0) (line-end-position) nil))))))
24532 (defun org-show-subtree ()
24533 "Show everything after this heading at deeper levels."
24534 (interactive)
24535 (outline-flag-region
24536 (point)
24537 (save-excursion
24538 (org-end-of-subtree t t))
24539 nil))
24541 (defun org-show-entry ()
24542 "Show the body directly following this heading.
24543 Show the heading too, if it is currently invisible."
24544 (interactive)
24545 (save-excursion
24546 (ignore-errors
24547 (org-back-to-heading t)
24548 (outline-flag-region
24549 (max (point-min) (1- (point)))
24550 (save-excursion
24551 (if (re-search-forward
24552 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24553 (match-beginning 1)
24554 (point-max)))
24555 nil)
24556 (org-cycle-hide-drawers 'children))))
24558 (defun org-make-options-regexp (kwds &optional extra)
24559 "Make a regular expression for keyword lines.
24560 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24561 when non-nil, is a regexp matching keywords names."
24562 (concat "^[ \t]*#\\+\\("
24563 (regexp-opt kwds)
24564 (and extra (concat (and kwds "\\|") extra))
24565 "\\):[ \t]*\\(.*\\)"))
24567 ;;;; Integration with and fixes for other packages
24569 ;;; Imenu support
24571 (defvar-local org-imenu-markers nil
24572 "All markers currently used by Imenu.")
24574 (defun org-imenu-new-marker (&optional pos)
24575 "Return a new marker for use by Imenu, and remember the marker."
24576 (let ((m (make-marker)))
24577 (move-marker m (or pos (point)))
24578 (push m org-imenu-markers)
24581 (defun org-imenu-get-tree ()
24582 "Produce the index for Imenu."
24583 (dolist (x org-imenu-markers) (move-marker x nil))
24584 (setq org-imenu-markers nil)
24585 (let* ((case-fold-search nil)
24586 (n org-imenu-depth)
24587 (re (concat "^" (org-get-limited-outline-regexp)))
24588 (subs (make-vector (1+ n) nil))
24589 (last-level 0)
24590 m level head0 head)
24591 (org-with-wide-buffer
24592 (goto-char (point-max))
24593 (while (re-search-backward re nil t)
24594 (setq level (org-reduced-level (funcall outline-level)))
24595 (when (and (<= level n)
24596 (looking-at org-complex-heading-regexp)
24597 (setq head0 (match-string-no-properties 4)))
24598 (setq head (org-link-display-format head0)
24599 m (org-imenu-new-marker))
24600 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24601 (if (>= level last-level)
24602 (push (cons head m) (aref subs level))
24603 (push (cons head (aref subs (1+ level))) (aref subs level))
24604 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24605 (setq last-level level))))
24606 (aref subs 1)))
24608 (eval-after-load "imenu"
24609 '(progn
24610 (add-hook 'imenu-after-jump-hook
24611 (lambda ()
24612 (when (derived-mode-p 'org-mode)
24613 (org-show-context 'org-goto))))))
24615 (defun org-link-display-format (s)
24616 "Replace links in string S with their description.
24617 If there is no description, use the link target."
24618 (save-match-data
24619 (replace-regexp-in-string
24620 org-bracket-link-analytic-regexp
24621 (lambda (m)
24622 (if (match-end 5) (match-string 5 m)
24623 (concat (match-string 1 m) (match-string 3 m))))
24624 s nil t)))
24626 (defun org-toggle-link-display ()
24627 "Toggle the literal or descriptive display of links."
24628 (interactive)
24629 (if org-descriptive-links
24630 (progn (org-remove-from-invisibility-spec '(org-link))
24631 (org-restart-font-lock)
24632 (setq org-descriptive-links nil))
24633 (progn (add-to-invisibility-spec '(org-link))
24634 (org-restart-font-lock)
24635 (setq org-descriptive-links t))))
24637 ;; Speedbar support
24639 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24640 "Overlay marking the agenda restriction line in speedbar.")
24641 (overlay-put org-speedbar-restriction-lock-overlay
24642 'face 'org-agenda-restriction-lock)
24643 (overlay-put org-speedbar-restriction-lock-overlay
24644 'help-echo "Agendas are currently limited to this item.")
24645 (delete-overlay org-speedbar-restriction-lock-overlay)
24647 (defun org-speedbar-set-agenda-restriction ()
24648 "Restrict future agenda commands to the location at point in speedbar.
24649 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24650 (interactive)
24651 (require 'org-agenda)
24652 (let (p m tp np dir txt)
24653 (cond
24654 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24655 'org-imenu t))
24656 (setq m (get-text-property p 'org-imenu-marker))
24657 (with-current-buffer (marker-buffer m)
24658 (goto-char m)
24659 (org-agenda-set-restriction-lock 'subtree)))
24660 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24661 'speedbar-function 'speedbar-find-file))
24662 (setq tp (previous-single-property-change
24663 (1+ p) 'speedbar-function)
24664 np (next-single-property-change
24665 tp 'speedbar-function)
24666 dir (speedbar-line-directory)
24667 txt (buffer-substring-no-properties (or tp (point-min))
24668 (or np (point-max))))
24669 (with-current-buffer (find-file-noselect
24670 (let ((default-directory dir))
24671 (expand-file-name txt)))
24672 (unless (derived-mode-p 'org-mode)
24673 (user-error "Cannot restrict to non-Org mode file"))
24674 (org-agenda-set-restriction-lock 'file)))
24675 (t (user-error "Don't know how to restrict Org mode agenda")))
24676 (move-overlay org-speedbar-restriction-lock-overlay
24677 (point-at-bol) (point-at-eol))
24678 (setq current-prefix-arg nil)
24679 (org-agenda-maybe-redo)))
24681 (defvar speedbar-file-key-map)
24682 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24683 (eval-after-load "speedbar"
24684 '(progn
24685 (speedbar-add-supported-extension ".org")
24686 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24687 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24688 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24689 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24690 (add-hook 'speedbar-visiting-tag-hook
24691 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24693 ;;; Fixes and Hacks for problems with other packages
24695 (defun org--flyspell-object-check-p (element)
24696 "Non-nil when Flyspell can check object at point.
24697 ELEMENT is the element at point."
24698 (let ((object (save-excursion
24699 (when (looking-at-p "\\>") (backward-char))
24700 (org-element-context element))))
24701 (cl-case (org-element-type object)
24702 ;; Prevent checks in links due to keybinding conflict with
24703 ;; Flyspell.
24704 ((code entity export-snippet inline-babel-call
24705 inline-src-block line-break latex-fragment link macro
24706 statistics-cookie target timestamp verbatim)
24707 nil)
24708 (footnote-reference
24709 ;; Only in inline footnotes, within the definition.
24710 (and (eq (org-element-property :type object) 'inline)
24711 (< (save-excursion
24712 (goto-char (org-element-property :begin object))
24713 (search-forward ":" nil t 2))
24714 (point))))
24715 (otherwise t))))
24717 (defun org-mode-flyspell-verify ()
24718 "Function used for `flyspell-generic-check-word-predicate'."
24719 (if (org-at-heading-p)
24720 ;; At a headline or an inlinetask, check title only. This is
24721 ;; faster than relying on `org-element-at-point'.
24722 (and (save-excursion (beginning-of-line)
24723 (and (let ((case-fold-search t))
24724 (not (looking-at-p "\\*+ END[ \t]*$")))
24725 (let ((case-fold-search nil))
24726 (looking-at org-complex-heading-regexp))))
24727 (match-beginning 4)
24728 (>= (point) (match-beginning 4))
24729 (or (not (match-beginning 5))
24730 (< (point) (match-beginning 5))))
24731 (let* ((element (org-element-at-point))
24732 (post-affiliated (org-element-property :post-affiliated element)))
24733 (cond
24734 ;; Ignore checks in all affiliated keywords but captions.
24735 ((< (point) post-affiliated)
24736 (and (save-excursion
24737 (beginning-of-line)
24738 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24739 (> (point) (match-end 0))
24740 (org--flyspell-object-check-p element)))
24741 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24742 ((let ((log (org-log-into-drawer)))
24743 (and log
24744 (let ((drawer (org-element-lineage element '(drawer))))
24745 (and drawer
24746 (eq (compare-strings
24747 log nil nil
24748 (org-element-property :drawer-name drawer) nil nil t)
24749 t)))))
24750 nil)
24752 (cl-case (org-element-type element)
24753 ((comment quote-section) t)
24754 (comment-block
24755 ;; Allow checks between block markers, not on them.
24756 (and (> (line-beginning-position) post-affiliated)
24757 (save-excursion
24758 (end-of-line)
24759 (skip-chars-forward " \r\t\n")
24760 (< (point) (org-element-property :end element)))))
24761 ;; Arbitrary list of keywords where checks are meaningful.
24762 ;; Make sure point is on the value part of the element.
24763 (keyword
24764 (and (member (org-element-property :key element)
24765 '("DESCRIPTION" "TITLE"))
24766 (save-excursion
24767 (search-backward ":" (line-beginning-position) t))))
24768 ;; Check is globally allowed in paragraphs verse blocks and
24769 ;; table rows (after affiliated keywords) but some objects
24770 ;; must not be affected.
24771 ((paragraph table-row verse-block)
24772 (let ((cbeg (org-element-property :contents-begin element))
24773 (cend (org-element-property :contents-end element)))
24774 (and cbeg (>= (point) cbeg) (< (point) cend)
24775 (org--flyspell-object-check-p element))))))))))
24776 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24778 (defun org-remove-flyspell-overlays-in (beg end)
24779 "Remove flyspell overlays in region."
24780 (and (bound-and-true-p flyspell-mode)
24781 (fboundp 'flyspell-delete-region-overlays)
24782 (flyspell-delete-region-overlays beg end)))
24784 (defvar flyspell-delayed-commands)
24785 (eval-after-load "flyspell"
24786 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24788 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24789 (eval-after-load "bookmark"
24790 '(if (boundp 'bookmark-after-jump-hook)
24791 ;; We can use the hook
24792 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24793 ;; Hook not available, use advice
24794 (defadvice bookmark-jump (after org-make-visible activate)
24795 "Make the position visible."
24796 (org-bookmark-jump-unhide))))
24798 ;; Make sure saveplace shows the location if it was hidden
24799 (eval-after-load "saveplace"
24800 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24801 "Make the position visible."
24802 (org-bookmark-jump-unhide)))
24804 ;; Make sure ecb shows the location if it was hidden
24805 (eval-after-load "ecb"
24806 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24807 "Make hierarchy visible when jumping into location from ECB tree buffer."
24808 (when (derived-mode-p 'org-mode)
24809 (org-show-context))))
24811 (defun org-bookmark-jump-unhide ()
24812 "Unhide the current position, to show the bookmark location."
24813 (and (derived-mode-p 'org-mode)
24814 (or (org-invisible-p)
24815 (save-excursion (goto-char (max (point-min) (1- (point))))
24816 (org-invisible-p)))
24817 (org-show-context 'bookmark-jump)))
24819 (defun org-mark-jump-unhide ()
24820 "Make the point visible with `org-show-context' after jumping to the mark."
24821 (when (and (derived-mode-p 'org-mode)
24822 (org-invisible-p))
24823 (org-show-context 'mark-goto)))
24825 (eval-after-load "simple"
24826 '(defadvice pop-to-mark-command (after org-make-visible activate)
24827 "Make the point visible with `org-show-context'."
24828 (org-mark-jump-unhide)))
24830 (eval-after-load "simple"
24831 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24832 "Make the point visible with `org-show-context'."
24833 (org-mark-jump-unhide)))
24835 (eval-after-load "simple"
24836 '(defadvice pop-global-mark (after org-make-visible activate)
24837 "Make the point visible with `org-show-context'."
24838 (org-mark-jump-unhide)))
24840 ;; Make session.el ignore our circular variable
24841 (defvar session-globals-exclude)
24842 (eval-after-load "session"
24843 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24845 ;;;; Finish up
24847 (provide 'org)
24849 (run-hooks 'org-load-hook)
24851 ;;; org.el ends here