Move `org-uniquify' into "org-macs.el"
[org-mode/org-tableheadings.git] / lisp / org.el
blob691be659d4722015d9d39b01574d20b1744cb95e
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-get-at-bol (property)
190 "Get text property PROPERTY at the beginning of line."
191 (get-text-property (point-at-bol) property))
193 ;; load languages based on value of `org-babel-load-languages'
194 (defvar org-babel-load-languages)
196 ;;;###autoload
197 (defun org-babel-do-load-languages (sym value)
198 "Load the languages defined in `org-babel-load-languages'."
199 (set-default sym value)
200 (dolist (pair org-babel-load-languages)
201 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
202 (if active
203 (require (intern (concat "ob-" lang)))
204 (funcall 'fmakunbound
205 (intern (concat "org-babel-execute:" lang)))
206 (funcall 'fmakunbound
207 (intern (concat "org-babel-expand-body:" lang)))))))
209 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
210 ;;;###autoload
211 (defun org-babel-load-file (file &optional compile)
212 "Load Emacs Lisp source code blocks in the Org FILE.
213 This function exports the source code using `org-babel-tangle'
214 and then loads the resulting file using `load-file'. With prefix
215 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
216 file to byte-code before it is loaded."
217 (interactive "fFile to load: \nP")
218 (let* ((age (lambda (file)
219 (float-time
220 (time-subtract (current-time)
221 (nth 5 (or (file-attributes (file-truename file))
222 (file-attributes file)))))))
223 (base-name (file-name-sans-extension file))
224 (exported-file (concat base-name ".el")))
225 ;; tangle if the Org file is newer than the elisp file
226 (unless (and (file-exists-p exported-file)
227 (> (funcall age file) (funcall age exported-file)))
228 ;; Tangle-file traversal returns reversed list of tangled files
229 ;; and we want to evaluate the first target.
230 (setq exported-file
231 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
232 (message "%s %s"
233 (if compile
234 (progn (byte-compile-file exported-file 'load)
235 "Compiled and loaded")
236 (progn (load-file exported-file) "Loaded"))
237 exported-file)))
239 (defcustom org-babel-load-languages '((emacs-lisp . t))
240 "Languages which can be evaluated in Org buffers.
241 This list can be used to load support for any of the languages
242 below, note that each language will depend on a different set of
243 system executables and/or Emacs modes. When a language is
244 \"loaded\", then code blocks in that language can be evaluated
245 with `org-babel-execute-src-block' bound by default to C-c
246 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
247 be set to remove code block evaluation from the C-c C-c
248 keybinding. By default only Emacs Lisp (which has no
249 requirements) is loaded."
250 :group 'org-babel
251 :set 'org-babel-do-load-languages
252 :version "24.1"
253 :type '(alist :tag "Babel Languages"
254 :key-type
255 (choice
256 (const :tag "Awk" awk)
257 (const :tag "C" C)
258 (const :tag "R" R)
259 (const :tag "Asymptote" asymptote)
260 (const :tag "Calc" calc)
261 (const :tag "Clojure" clojure)
262 (const :tag "CSS" css)
263 (const :tag "Ditaa" ditaa)
264 (const :tag "Dot" dot)
265 (const :tag "Ebnf2ps" ebnf2ps)
266 (const :tag "Emacs Lisp" emacs-lisp)
267 (const :tag "Forth" forth)
268 (const :tag "Fortran" fortran)
269 (const :tag "Gnuplot" gnuplot)
270 (const :tag "Haskell" haskell)
271 (const :tag "hledger" hledger)
272 (const :tag "IO" io)
273 (const :tag "J" J)
274 (const :tag "Java" java)
275 (const :tag "Javascript" js)
276 (const :tag "LaTeX" latex)
277 (const :tag "Ledger" ledger)
278 (const :tag "Lilypond" lilypond)
279 (const :tag "Lisp" lisp)
280 (const :tag "Makefile" makefile)
281 (const :tag "Maxima" maxima)
282 (const :tag "Matlab" matlab)
283 (const :tag "Mscgen" mscgen)
284 (const :tag "Ocaml" ocaml)
285 (const :tag "Octave" octave)
286 (const :tag "Org" org)
287 (const :tag "Perl" perl)
288 (const :tag "Pico Lisp" picolisp)
289 (const :tag "PlantUML" plantuml)
290 (const :tag "Python" python)
291 (const :tag "Ruby" ruby)
292 (const :tag "Sass" sass)
293 (const :tag "Scala" scala)
294 (const :tag "Scheme" scheme)
295 (const :tag "Screen" screen)
296 (const :tag "Shell Script" shell)
297 (const :tag "Shen" shen)
298 (const :tag "Sql" sql)
299 (const :tag "Sqlite" sqlite)
300 (const :tag "Stan" stan)
301 (const :tag "Vala" vala))
302 :value-type (boolean :tag "Activate" :value t)))
304 ;;;; Customization variables
305 (defcustom org-clone-delete-id nil
306 "Remove ID property of clones of a subtree.
307 When non-nil, clones of a subtree don't inherit the ID property.
308 Otherwise they inherit the ID property with a new unique
309 identifier."
310 :type 'boolean
311 :version "24.1"
312 :group 'org-id)
314 ;;; Version
315 (org-check-version)
317 ;;;###autoload
318 (defun org-version (&optional here full message)
319 "Show the Org version.
320 Interactively, or when MESSAGE is non-nil, show it in echo area.
321 With prefix argument, or when HERE is non-nil, insert it at point.
322 In non-interactive uses, a reduced version string is output unless
323 FULL is given."
324 (interactive (list current-prefix-arg t (not current-prefix-arg)))
325 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
326 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
327 (load-suffixes (list ".el"))
328 (org-install-dir
329 (ignore-errors (org-find-library-dir "org-loaddefs"))))
330 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
331 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
332 (let* ((load-suffixes save-load-suffixes)
333 (release (org-release))
334 (git-version (org-git-version))
335 (version (format "Org mode version %s (%s @ %s)"
336 release
337 git-version
338 (if org-install-dir
339 (if (string= org-dir org-install-dir)
340 org-install-dir
341 (concat "mixed installation! "
342 org-install-dir
343 " and "
344 org-dir))
345 "org-loaddefs.el can not be found!")))
346 (version1 (if full version release)))
347 (when here (insert version1))
348 (when message (message "%s" version1))
349 version1)))
351 (defconst org-version (org-version))
354 ;;; Syntax Constants
356 ;;;; Block
358 (defconst org-block-regexp
359 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
360 "Regular expression for hiding blocks.")
362 (defconst org-dblock-start-re
363 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
364 "Matches the start line of a dynamic block, with parameters.")
366 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
367 "Matches the end of a dynamic block.")
369 ;;;; Clock and Planning
371 (defconst org-clock-string "CLOCK:"
372 "String used as prefix for timestamps clocking work hours on an item.")
374 (defvar org-closed-string "CLOSED:"
375 "String used as the prefix for timestamps logging closing a TODO entry.")
377 (defvar org-deadline-string "DEADLINE:"
378 "String to mark deadline entries.
379 \\<org-mode-map>
380 A deadline is this string, followed by a time stamp. It must be
381 a word, terminated by a colon. You can insert a schedule keyword
382 and a timestamp with `\\[org-deadline]'.")
384 (defvar org-scheduled-string "SCHEDULED:"
385 "String to mark scheduled TODO entries.
386 \\<org-mode-map>
387 A schedule is this string, followed by a time stamp. It must be
388 a word, terminated by a colon. You can insert a schedule keyword
389 and a timestamp with `\\[org-schedule]'.")
391 (defconst org-ds-keyword-length
392 (+ 2
393 (apply #'max
394 (mapcar #'length
395 (list org-deadline-string org-scheduled-string
396 org-clock-string org-closed-string))))
397 "Maximum length of the DEADLINE and SCHEDULED keywords.")
399 (defconst org-planning-line-re
400 (concat "^[ \t]*"
401 (regexp-opt
402 (list org-closed-string org-deadline-string org-scheduled-string)
404 "Matches a line with planning info.
405 Matched keyword is in group 1.")
407 (defconst org-clock-line-re
408 (concat "^[ \t]*" org-clock-string)
409 "Matches a line with clock info.")
411 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
412 "Matches the DEADLINE keyword.")
414 (defconst org-deadline-time-regexp
415 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
416 "Matches the DEADLINE keyword together with a time stamp.")
418 (defconst org-deadline-time-hour-regexp
419 (concat "\\<" org-deadline-string
420 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
421 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
423 (defconst org-deadline-line-regexp
424 (concat "\\<\\(" org-deadline-string "\\).*")
425 "Matches the DEADLINE keyword and the rest of the line.")
427 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
428 "Matches the SCHEDULED keyword.")
430 (defconst org-scheduled-time-regexp
431 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
432 "Matches the SCHEDULED keyword together with a time stamp.")
434 (defconst org-scheduled-time-hour-regexp
435 (concat "\\<" org-scheduled-string
436 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
437 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
439 (defconst org-closed-time-regexp
440 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
441 "Matches the CLOSED keyword together with a time stamp.")
443 (defconst org-keyword-time-regexp
444 (concat "\\<"
445 (regexp-opt
446 (list org-scheduled-string org-deadline-string org-closed-string
447 org-clock-string)
449 " *[[<]\\([^]>]+\\)[]>]")
450 "Matches any of the 4 keywords, together with the time stamp.")
452 (defconst org-keyword-time-not-clock-regexp
453 (concat
454 "\\<"
455 (regexp-opt
456 (list org-scheduled-string org-deadline-string org-closed-string) t)
457 " *[[<]\\([^]>]+\\)[]>]")
458 "Matches any of the 3 keywords, together with the time stamp.")
460 (defconst org-maybe-keyword-time-regexp
461 (concat "\\(\\<"
462 (regexp-opt
463 (list org-scheduled-string org-deadline-string org-closed-string
464 org-clock-string)
466 "\\)?"
467 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
468 "\\|"
469 "<%%([^\r\n>]*>\\)")
470 "Matches a timestamp, possibly preceded by a keyword.")
472 (defconst org-all-time-keywords
473 (mapcar (lambda (w) (substring w 0 -1))
474 (list org-scheduled-string org-deadline-string
475 org-clock-string org-closed-string))
476 "List of time keywords.")
478 ;;;; Drawer
480 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
481 "Matches first or last line of a hidden block.
482 Group 1 contains drawer's name or \"END\".")
484 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
485 "Regular expression matching the first line of a property drawer.")
487 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
488 "Regular expression matching the last line of a property drawer.")
490 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
491 "Regular expression matching the first line of a clock drawer.")
493 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
494 "Regular expression matching the last line of a clock drawer.")
496 (defconst org-property-drawer-re
497 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
498 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
499 "[ \t]*:END:[ \t]*$")
500 "Matches an entire property drawer.")
502 (defconst org-clock-drawer-re
503 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
504 org-clock-drawer-end-re "\\)\n?")
505 "Matches an entire clock drawer.")
507 ;;;; Headline
509 (defconst org-heading-keyword-regexp-format
510 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
511 "Printf format for a regexp matching a headline with some keyword.
512 This regexp will match the headline of any node which has the
513 exact keyword that is put into the format. The keyword isn't in
514 any group by default, but the stars and the body are.")
516 (defconst org-heading-keyword-maybe-regexp-format
517 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
518 "Printf format for a regexp matching a headline, possibly with some keyword.
519 This regexp can match any headline with the specified keyword, or
520 without a keyword. The keyword isn't in any group by default,
521 but the stars and the body are.")
523 (defconst org-archive-tag "ARCHIVE"
524 "The tag that marks a subtree as archived.
525 An archived subtree does not open during visibility cycling, and does
526 not contribute to the agenda listings.")
528 (eval-and-compile
529 (defconst org-comment-string "COMMENT"
530 "Entries starting with this keyword will never be exported.
531 \\<org-mode-map>
532 An entry can be toggled between COMMENT and normal with
533 `\\[org-toggle-comment]'."))
536 ;;;; LaTeX Environments and Fragments
538 (defconst org-latex-regexps
539 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
540 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
541 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
542 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
543 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
544 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
545 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
546 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
547 "Regular expressions for matching embedded LaTeX.")
549 ;;;; Node Property
551 (defconst org-effort-property "Effort"
552 "The property that is being used to keep track of effort estimates.
553 Effort estimates given in this property need to have the format H:MM.")
555 ;;;; Table
557 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
558 "Detect an org-type or table-type table.")
560 (defconst org-table-line-regexp "^[ \t]*|"
561 "Detect an org-type table line.")
563 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
564 "Detect an org-type table line.")
566 (defconst org-table-hline-regexp "^[ \t]*|-"
567 "Detect an org-type table hline.")
569 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
570 "Detect a table-type table hline.")
572 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
573 "Detect the first line outside a table when searching from within it.
574 This works for both table types.")
576 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
577 "Detect a #+TBLFM line.")
579 ;;;; Timestamp
581 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
582 "Regular expression for fast time stamp matching.")
584 (defconst org-ts-regexp-inactive
585 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
586 "Regular expression for fast inactive time stamp matching.")
588 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
589 "Regular expression for fast time stamp matching.")
591 (defconst org-ts-regexp0
592 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
593 "Regular expression matching time strings for analysis.
594 This one does not require the space after the date, so it can be used
595 on a string that terminates immediately after the date.")
597 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
598 "Regular expression matching time strings for analysis.")
600 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
601 "Regular expression matching time stamps, with groups.")
603 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
604 "Regular expression matching time stamps (also [..]), with groups.")
606 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
607 "Regular expression matching a time stamp range.")
609 (defconst org-tr-regexp-both
610 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
611 "Regular expression matching a time stamp range.")
613 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
614 org-ts-regexp "\\)?")
615 "Regular expression matching a time stamp or time stamp range.")
617 (defconst org-tsr-regexp-both
618 (concat org-ts-regexp-both "\\(--?-?"
619 org-ts-regexp-both "\\)?")
620 "Regular expression matching a time stamp or time stamp range.
621 The time stamps may be either active or inactive.")
623 (defconst org-repeat-re
624 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
625 "Regular expression for specifying repeated events.
626 After a match, group 1 contains the repeat expression.")
628 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
629 "Formats for `format-time-string' which are used for time stamps.")
632 ;;; The custom variables
634 (defgroup org nil
635 "Outline-based notes management and organizer."
636 :tag "Org"
637 :group 'outlines
638 :group 'calendar)
640 (defcustom org-mode-hook nil
641 "Mode hook for Org mode, run after the mode was turned on."
642 :group 'org
643 :type 'hook)
645 (defcustom org-load-hook nil
646 "Hook that is run after org.el has been loaded."
647 :group 'org
648 :type 'hook)
650 (defcustom org-log-buffer-setup-hook nil
651 "Hook that is run after an Org log buffer is created."
652 :group 'org
653 :version "24.1"
654 :type 'hook)
656 (defvar org-modules) ; defined below
657 (defvar org-modules-loaded nil
658 "Have the modules been loaded already?")
660 (defun org-load-modules-maybe (&optional force)
661 "Load all extensions listed in `org-modules'."
662 (when (or force (not org-modules-loaded))
663 (dolist (ext org-modules)
664 (condition-case nil (require ext)
665 (error (message "Problems while trying to load feature `%s'" ext))))
666 (setq org-modules-loaded t)))
668 (defun org-set-modules (var value)
669 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
670 (set var value)
671 (when (featurep 'org)
672 (org-load-modules-maybe 'force)
673 (org-element-cache-reset 'all)))
675 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
676 "Modules that should always be loaded together with org.el.
678 If a description starts with <C>, the file is not part of Emacs
679 and loading it will require that you have downloaded and properly
680 installed the Org mode distribution.
682 You can also use this system to load external packages (i.e. neither Org
683 core modules, nor modules from the CONTRIB directory). Just add symbols
684 to the end of the list. If the package is called org-xyz.el, then you need
685 to add the symbol `xyz', and the package must have a call to:
687 (provide \\='org-xyz)
689 For export specific modules, see also `org-export-backends'."
690 :group 'org
691 :set 'org-set-modules
692 :version "24.4"
693 :package-version '(Org . "8.0")
694 :type
695 '(set :greedy t
696 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
697 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
698 (const :tag " crypt: Encryption of subtrees" org-crypt)
699 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
700 (const :tag " docview: Links to doc-view buffers" org-docview)
701 (const :tag " eww: Store link to url of eww" org-eww)
702 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
703 (const :tag " habit: Track your consistency with habits" org-habit)
704 (const :tag " id: Global IDs for identifying entries" org-id)
705 (const :tag " info: Links to Info nodes" org-info)
706 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
707 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
708 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
709 (const :tag " mouse: Additional mouse support" org-mouse)
710 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
711 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
712 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
714 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
715 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
716 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
717 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
718 (const :tag "C collector: Collect properties into tables" org-collector)
719 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
720 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
721 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
722 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
723 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
724 (const :tag "C eval: Include command output as text" org-eval)
725 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
726 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
727 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
728 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
729 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
730 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
731 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
732 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
733 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
734 (const :tag "C man: Support for links to manpages in Org mode" org-man)
735 (const :tag "C mew: Links to Mew folders/messages" org-mew)
736 (const :tag "C mtags: Support for muse-like tags" org-mtags)
737 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
738 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
739 (const :tag "C registry: A registry for Org links" org-registry)
740 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
741 (const :tag "C secretary: Team management with org-mode" org-secretary)
742 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
743 (const :tag "C toc: Table of contents for Org buffer" org-toc)
744 (const :tag "C track: Keep up with Org mode development" org-track)
745 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
746 (const :tag "C vm: Links to VM folders/messages" org-vm)
747 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
748 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
749 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
751 (defvar org-export-registered-backends) ; From ox.el.
752 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
753 (declare-function org-export-backend-name "ox" (backend) t)
754 (defcustom org-export-backends '(ascii html icalendar latex odt)
755 "List of export back-ends that should be always available.
757 If a description starts with <C>, the file is not part of Emacs
758 and loading it will require that you have downloaded and properly
759 installed the Org mode distribution.
761 Unlike to `org-modules', libraries in this list will not be
762 loaded along with Org, but only once the export framework is
763 needed.
765 This variable needs to be set before org.el is loaded. If you
766 need to make a change while Emacs is running, use the customize
767 interface or run the following code, where VAL stands for the new
768 value of the variable, after updating it:
770 (progn
771 (setq org-export-registered-backends
772 (cl-remove-if-not
773 (lambda (backend)
774 (let ((name (org-export-backend-name backend)))
775 (or (memq name val)
776 (catch \\='parentp
777 (dolist (b val)
778 (and (org-export-derived-backend-p b name)
779 (throw \\='parentp t)))))))
780 org-export-registered-backends))
781 (let ((new-list (mapcar #\\='org-export-backend-name
782 org-export-registered-backends)))
783 (dolist (backend val)
784 (cond
785 ((not (load (format \"ox-%s\" backend) t t))
786 (message \"Problems while trying to load export back-end \\=`%s\\='\"
787 backend))
788 ((not (memq backend new-list)) (push backend new-list))))
789 (set-default \\='org-export-backends new-list)))
791 Adding a back-end to this list will also pull the back-end it
792 depends on, if any."
793 :group 'org
794 :group 'org-export
795 :version "26.1"
796 :package-version '(Org . "9.0")
797 :initialize 'custom-initialize-set
798 :set (lambda (var val)
799 (if (not (featurep 'ox)) (set-default var val)
800 ;; Any back-end not required anymore (not present in VAL and not
801 ;; a parent of any back-end in the new value) is removed from the
802 ;; list of registered back-ends.
803 (setq org-export-registered-backends
804 (cl-remove-if-not
805 (lambda (backend)
806 (let ((name (org-export-backend-name backend)))
807 (or (memq name val)
808 (catch 'parentp
809 (dolist (b val)
810 (and (org-export-derived-backend-p b name)
811 (throw 'parentp t)))))))
812 org-export-registered-backends))
813 ;; Now build NEW-LIST of both new back-ends and required
814 ;; parents.
815 (let ((new-list (mapcar #'org-export-backend-name
816 org-export-registered-backends)))
817 (dolist (backend val)
818 (cond
819 ((not (load (format "ox-%s" backend) t t))
820 (message "Problems while trying to load export back-end `%s'"
821 backend))
822 ((not (memq backend new-list)) (push backend new-list))))
823 ;; Set VAR to that list with fixed dependencies.
824 (set-default var new-list))))
825 :type '(set :greedy t
826 (const :tag " ascii Export buffer to ASCII format" ascii)
827 (const :tag " beamer Export buffer to Beamer presentation" beamer)
828 (const :tag " html Export buffer to HTML format" html)
829 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
830 (const :tag " latex Export buffer to LaTeX format" latex)
831 (const :tag " man Export buffer to MAN format" man)
832 (const :tag " md Export buffer to Markdown format" md)
833 (const :tag " odt Export buffer to ODT format" odt)
834 (const :tag " org Export buffer to Org format" org)
835 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
836 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
837 (const :tag "C deck Export buffer to deck.js presentations" deck)
838 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
839 (const :tag "C groff Export buffer to Groff format" groff)
840 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
841 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
842 (const :tag "C s5 Export buffer to s5 presentations" s5)
843 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
845 (eval-after-load 'ox
846 '(dolist (backend org-export-backends)
847 (condition-case nil (require (intern (format "ox-%s" backend)))
848 (error (message "Problems while trying to load export back-end `%s'"
849 backend)))))
851 (defcustom org-support-shift-select nil
852 "Non-nil means make shift-cursor commands select text when possible.
853 \\<org-mode-map>\
855 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
856 start selecting a region, or enlarge regions started in this way.
857 In Org mode, in special contexts, these same keys are used for
858 other purposes, important enough to compete with shift selection.
859 Org tries to balance these needs by supporting `shift-select-mode'
860 outside these special contexts, under control of this variable.
862 The default of this variable is nil, to avoid confusing behavior. Shifted
863 cursor keys will then execute Org commands in the following contexts:
864 - on a headline, changing TODO state (left/right) and priority (up/down)
865 - on a time stamp, changing the time
866 - in a plain list item, changing the bullet type
867 - in a property definition line, switching between allowed values
868 - in the BEGIN line of a clock table (changing the time block).
869 Outside these contexts, the commands will throw an error.
871 When this variable is t and the cursor is not in a special
872 context, Org mode will support shift-selection for making and
873 enlarging regions. To make this more effective, the bullet
874 cycling will no longer happen anywhere in an item line, but only
875 if the cursor is exactly on the bullet.
877 If you set this variable to the symbol `always', then the keys
878 will not be special in headlines, property lines, and item lines,
879 to make shift selection work there as well. If this is what you
880 want, you can use the following alternative commands:
881 `\\[org-todo]' and `\\[org-priority]' \
882 to change TODO state and priority,
883 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
884 can be used to switch TODO sets,
885 `\\[org-ctrl-c-minus]' to cycle item bullet types,
886 and properties can be edited by hand or in column view.
888 However, when the cursor is on a timestamp, shift-cursor commands
889 will still edit the time stamp - this is just too good to give up."
890 :group 'org
891 :type '(choice
892 (const :tag "Never" nil)
893 (const :tag "When outside special context" t)
894 (const :tag "Everywhere except timestamps" always)))
896 (defcustom org-loop-over-headlines-in-active-region nil
897 "Shall some commands act upon headlines in the active region?
899 When set to t, some commands will be performed in all headlines
900 within the active region.
902 When set to `start-level', some commands will be performed in all
903 headlines within the active region, provided that these headlines
904 are of the same level than the first one.
906 When set to a string, those commands will be performed on the
907 matching headlines within the active region. Such string must be
908 a tags/property/todo match as it is used in the agenda tags view.
910 The list of commands is: `org-schedule', `org-deadline',
911 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
912 `org-archive-to-archive-sibling'. The archiving commands skip
913 already archived entries."
914 :type '(choice (const :tag "Don't loop" nil)
915 (const :tag "All headlines in active region" t)
916 (const :tag "In active region, headlines at the same level than the first one" start-level)
917 (string :tag "Tags/Property/Todo matcher"))
918 :version "24.1"
919 :group 'org-todo
920 :group 'org-archive)
922 (defgroup org-startup nil
923 "Options concerning startup of Org mode."
924 :tag "Org Startup"
925 :group 'org)
927 (defcustom org-startup-folded t
928 "Non-nil means entering Org mode will switch to OVERVIEW.
930 This can also be configured on a per-file basis by adding one of
931 the following lines anywhere in the buffer:
933 #+STARTUP: fold (or `overview', this is equivalent)
934 #+STARTUP: nofold (or `showall', this is equivalent)
935 #+STARTUP: content
936 #+STARTUP: showeverything
938 Set `org-agenda-inhibit-startup' to a non-nil value if you want
939 to ignore this option when Org opens agenda files for the first
940 time."
941 :group 'org-startup
942 :type '(choice
943 (const :tag "nofold: show all" nil)
944 (const :tag "fold: overview" t)
945 (const :tag "content: all headlines" content)
946 (const :tag "show everything, even drawers" showeverything)))
948 (defcustom org-startup-truncated t
949 "Non-nil means entering Org mode will set `truncate-lines'.
950 This is useful since some lines containing links can be very long and
951 uninteresting. Also tables look terrible when wrapped.
953 The variable `org-startup-truncated' allows to configure
954 truncation for Org mode different to the other modes that use the
955 variable `truncate-lines' and as a shortcut instead of putting
956 the variable `truncate-lines' into the `org-mode-hook'. If one
957 wants to configure truncation for Org mode not statically but
958 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
959 the variable `truncate-lines' has to be used because in such a
960 case it is too late to set the variable `org-startup-truncated'."
961 :group 'org-startup
962 :type 'boolean)
964 (defcustom org-startup-indented nil
965 "Non-nil means turn on `org-indent-mode' on startup.
966 This can also be configured on a per-file basis by adding one of
967 the following lines anywhere in the buffer:
969 #+STARTUP: indent
970 #+STARTUP: noindent"
971 :group 'org-structure
972 :type '(choice
973 (const :tag "Not" nil)
974 (const :tag "Globally (slow on startup in large files)" t)))
976 (defcustom org-use-sub-superscripts t
977 "Non-nil means interpret \"_\" and \"^\" for display.
979 If you want to control how Org exports those characters, see
980 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
981 used to be an alias for `org-export-with-sub-superscripts' in
982 Org <8.0, it is not anymore.
984 When this option is turned on, you can use TeX-like syntax for
985 sub- and superscripts within the buffer. Several characters after
986 \"_\" or \"^\" will be considered as a single item - so grouping
987 with {} is normally not needed. For example, the following things
988 will be parsed as single sub- or superscripts:
990 10^24 or 10^tau several digits will be considered 1 item.
991 10^-12 or 10^-tau a leading sign with digits or a word
992 x^2-y^3 will be read as x^2 - y^3, because items are
993 terminated by almost any nonword/nondigit char.
994 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
996 Still, ambiguity is possible. So when in doubt, use {} to enclose
997 the sub/superscript. If you set this variable to the symbol `{}',
998 the braces are *required* in order to trigger interpretations as
999 sub/superscript. This can be helpful in documents that need \"_\"
1000 frequently in plain text."
1001 :group 'org-startup
1002 :version "24.4"
1003 :package-version '(Org . "8.0")
1004 :type '(choice
1005 (const :tag "Always interpret" t)
1006 (const :tag "Only with braces" {})
1007 (const :tag "Never interpret" nil)))
1009 (defcustom org-startup-with-beamer-mode nil
1010 "Non-nil means turn on `org-beamer-mode' on startup.
1011 This can also be configured on a per-file basis by adding one of
1012 the following lines anywhere in the buffer:
1014 #+STARTUP: beamer"
1015 :group 'org-startup
1016 :version "24.1"
1017 :type 'boolean)
1019 (defcustom org-startup-align-all-tables nil
1020 "Non-nil means align all tables when visiting a file.
1021 This can also be configured on a per-file basis by adding one of
1022 the following lines anywhere in the buffer:
1023 #+STARTUP: align
1024 #+STARTUP: noalign"
1025 :group 'org-startup
1026 :type 'boolean)
1028 (defcustom org-startup-shrink-all-tables nil
1029 "Non-nil means shrink all table columns with a width cookie.
1030 This can also be configured on a per-file basis by adding one of
1031 the following lines anywhere in the buffer:
1032 #+STARTUP: shrink"
1033 :group 'org-startup
1034 :type 'boolean
1035 :version "26.1"
1036 :package-version '(Org . "9.1")
1037 :safe #'booleanp)
1039 (defcustom org-startup-with-inline-images nil
1040 "Non-nil means show inline images when loading a new Org file.
1041 This can also be configured on a per-file basis by adding one of
1042 the following lines anywhere in the buffer:
1043 #+STARTUP: inlineimages
1044 #+STARTUP: noinlineimages"
1045 :group 'org-startup
1046 :version "24.1"
1047 :type 'boolean)
1049 (defcustom org-startup-with-latex-preview nil
1050 "Non-nil means preview LaTeX fragments when loading a new Org file.
1052 This can also be configured on a per-file basis by adding one of
1053 the following lines anywhere in the buffer:
1054 #+STARTUP: latexpreview
1055 #+STARTUP: nolatexpreview"
1056 :group 'org-startup
1057 :version "24.4"
1058 :package-version '(Org . "8.0")
1059 :type 'boolean)
1061 (defcustom org-insert-mode-line-in-empty-file nil
1062 "Non-nil means insert the first line setting Org mode in empty files.
1063 When the function `org-mode' is called interactively in an empty file, this
1064 normally means that the file name does not automatically trigger Org mode.
1065 To ensure that the file will always be in Org mode in the future, a
1066 line enforcing Org mode will be inserted into the buffer, if this option
1067 has been set."
1068 :group 'org-startup
1069 :type 'boolean)
1071 (defcustom org-replace-disputed-keys nil
1072 "Non-nil means use alternative key bindings for some keys.
1073 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1074 These keys are also used by other packages like shift-selection-mode'
1075 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1076 If you want to use Org mode together with one of these other modes,
1077 or more generally if you would like to move some Org mode commands to
1078 other keys, set this variable and configure the keys with the variable
1079 `org-disputed-keys'.
1081 This option is only relevant at load-time of Org mode, and must be set
1082 *before* org.el is loaded. Changing it requires a restart of Emacs to
1083 become effective."
1084 :group 'org-startup
1085 :type 'boolean)
1087 (defcustom org-use-extra-keys nil
1088 "Non-nil means use extra key sequence definitions for certain commands.
1089 This happens automatically if `window-system' is nil. This
1090 variable lets you do the same manually. You must set it before
1091 loading Org."
1092 :group 'org-startup
1093 :type 'boolean)
1095 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1097 (defcustom org-disputed-keys
1098 '(([(shift up)] . [(meta p)])
1099 ([(shift down)] . [(meta n)])
1100 ([(shift left)] . [(meta -)])
1101 ([(shift right)] . [(meta +)])
1102 ([(control shift right)] . [(meta shift +)])
1103 ([(control shift left)] . [(meta shift -)]))
1104 "Keys for which Org mode and other modes compete.
1105 This is an alist, cars are the default keys, second element specifies
1106 the alternative to use when `org-replace-disputed-keys' is t.
1108 Keys can be specified in any syntax supported by `define-key'.
1109 The value of this option takes effect only at Org mode startup,
1110 therefore you'll have to restart Emacs to apply it after changing."
1111 :group 'org-startup
1112 :type 'alist)
1114 (defun org-key (key)
1115 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1116 Or return the original if not disputed."
1117 (when org-replace-disputed-keys
1118 (let* ((nkey (key-description key))
1119 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1120 org-disputed-keys)))
1121 (setq key (if x (cdr x) key))))
1122 key)
1124 (defun org-defkey (keymap key def)
1125 "Define a key, possibly translated, as returned by `org-key'."
1126 (define-key keymap (org-key key) def))
1128 (defcustom org-ellipsis nil
1129 "The ellipsis to use in the Org mode outline.
1131 When nil, just use the standard three dots. When a non-empty string,
1132 use that string instead.
1134 The change affects only Org mode (which will then use its own display table).
1135 Changing this requires executing `\\[org-mode]' in a buffer to become
1136 effective."
1137 :group 'org-startup
1138 :type '(choice (const :tag "Default" nil)
1139 (string :tag "String" :value "...#"))
1140 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1142 (defvar org-display-table nil
1143 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1145 (defgroup org-keywords nil
1146 "Keywords in Org mode."
1147 :tag "Org Keywords"
1148 :group 'org)
1150 (defcustom org-closed-keep-when-no-todo nil
1151 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1152 :group 'org-todo
1153 :group 'org-keywords
1154 :version "24.4"
1155 :package-version '(Org . "8.0")
1156 :type 'boolean)
1158 (defgroup org-structure nil
1159 "Options concerning the general structure of Org files."
1160 :tag "Org Structure"
1161 :group 'org)
1163 (defgroup org-reveal-location nil
1164 "Options about how to make context of a location visible."
1165 :tag "Org Reveal Location"
1166 :group 'org-structure)
1168 (defcustom org-show-context-detail '((agenda . local)
1169 (bookmark-jump . lineage)
1170 (isearch . lineage)
1171 (default . ancestors))
1172 "Alist between context and visibility span when revealing a location.
1174 \\<org-mode-map>Some actions may move point into invisible
1175 locations. As a consequence, Org always expose a neighborhood
1176 around point. How much is shown depends on the initial action,
1177 or context. Valid contexts are
1179 agenda when exposing an entry from the agenda
1180 org-goto when using the command `org-goto' (`\\[org-goto]')
1181 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1182 tags-tree when constructing a sparse tree based on tags matches
1183 link-search when exposing search matches associated with a link
1184 mark-goto when exposing the jump goal of a mark
1185 bookmark-jump when exposing a bookmark location
1186 isearch when exiting from an incremental search
1187 default default for all contexts not set explicitly
1189 Allowed visibility spans are
1191 minimal show current headline; if point is not on headline,
1192 also show entry
1194 local show current headline, entry and next headline
1196 ancestors show current headline and its direct ancestors; if
1197 point is not on headline, also show entry
1199 lineage show current headline, its direct ancestors and all
1200 their children; if point is not on headline, also show
1201 entry and first child
1203 tree show current headline, its direct ancestors and all
1204 their children; if point is not on headline, also show
1205 entry and all children
1207 canonical show current headline, its direct ancestors along with
1208 their entries and children; if point is not located on
1209 the headline, also show current entry and all children
1211 As special cases, a nil or t value means show all contexts in
1212 `minimal' or `canonical' view, respectively.
1214 Some views can make displayed information very compact, but also
1215 make it harder to edit the location of the match. In such
1216 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1217 more context."
1218 :group 'org-reveal-location
1219 :version "26.1"
1220 :package-version '(Org . "9.0")
1221 :type '(choice
1222 (const :tag "Canonical" t)
1223 (const :tag "Minimal" nil)
1224 (repeat :greedy t :tag "Individual contexts"
1225 (cons
1226 (choice :tag "Context"
1227 (const agenda)
1228 (const org-goto)
1229 (const occur-tree)
1230 (const tags-tree)
1231 (const link-search)
1232 (const mark-goto)
1233 (const bookmark-jump)
1234 (const isearch)
1235 (const default))
1236 (choice :tag "Detail level"
1237 (const minimal)
1238 (const local)
1239 (const ancestors)
1240 (const lineage)
1241 (const tree)
1242 (const canonical))))))
1244 (defcustom org-indirect-buffer-display 'other-window
1245 "How should indirect tree buffers be displayed?
1247 This applies to indirect buffers created with the commands
1248 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1250 Valid values are:
1251 current-window Display in the current window
1252 other-window Just display in another window.
1253 dedicated-frame Create one new frame, and re-use it each time.
1254 new-frame Make a new frame each time. Note that in this case
1255 previously-made indirect buffers are kept, and you need to
1256 kill these buffers yourself."
1257 :group 'org-structure
1258 :group 'org-agenda-windows
1259 :type '(choice
1260 (const :tag "In current window" current-window)
1261 (const :tag "In current frame, other window" other-window)
1262 (const :tag "Each time a new frame" new-frame)
1263 (const :tag "One dedicated frame" dedicated-frame)))
1265 (defcustom org-use-speed-commands nil
1266 "Non-nil means activate single letter commands at beginning of a headline.
1267 This may also be a function to test for appropriate locations where speed
1268 commands should be active.
1270 For example, to activate speed commands when the point is on any
1271 star at the beginning of the headline, you can do this:
1273 (setq org-use-speed-commands
1274 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1275 :group 'org-structure
1276 :type '(choice
1277 (const :tag "Never" nil)
1278 (const :tag "At beginning of headline stars" t)
1279 (function)))
1281 (defcustom org-speed-commands-user nil
1282 "Alist of additional speed commands.
1283 This list will be checked before `org-speed-commands-default'
1284 when the variable `org-use-speed-commands' is non-nil
1285 and when the cursor is at the beginning of a headline.
1286 The car if each entry is a string with a single letter, which must
1287 be assigned to `self-insert-command' in the global map.
1288 The cdr is either a command to be called interactively, a function
1289 to be called, or a form to be evaluated.
1290 An entry that is just a list with a single string will be interpreted
1291 as a descriptive headline that will be added when listing the speed
1292 commands in the Help buffer using the `?' speed command."
1293 :group 'org-structure
1294 :type '(repeat :value ("k" . ignore)
1295 (choice :value ("k" . ignore)
1296 (list :tag "Descriptive Headline" (string :tag "Headline"))
1297 (cons :tag "Letter and Command"
1298 (string :tag "Command letter")
1299 (choice
1300 (function)
1301 (sexp))))))
1303 (defcustom org-bookmark-names-plist
1304 '(:last-capture "org-capture-last-stored"
1305 :last-refile "org-refile-last-stored"
1306 :last-capture-marker "org-capture-last-stored-marker")
1307 "Names for bookmarks automatically set by some Org commands.
1308 This can provide strings as names for a number of bookmarks Org sets
1309 automatically. The following keys are currently implemented:
1310 :last-capture
1311 :last-capture-marker
1312 :last-refile
1313 When a key does not show up in the property list, the corresponding bookmark
1314 is not set."
1315 :group 'org-structure
1316 :type 'plist)
1318 (defgroup org-cycle nil
1319 "Options concerning visibility cycling in Org mode."
1320 :tag "Org Cycle"
1321 :group 'org-structure)
1323 (defcustom org-cycle-skip-children-state-if-no-children t
1324 "Non-nil means skip CHILDREN state in entries that don't have any."
1325 :group 'org-cycle
1326 :type 'boolean)
1328 (defcustom org-cycle-max-level nil
1329 "Maximum level which should still be subject to visibility cycling.
1330 Levels higher than this will, for cycling, be treated as text, not a headline.
1331 When `org-odd-levels-only' is set, a value of N in this variable actually
1332 means 2N-1 stars as the limiting headline.
1333 When nil, cycle all levels.
1334 Note that the limiting level of cycling is also influenced by
1335 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1336 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1337 than its value."
1338 :group 'org-cycle
1339 :type '(choice
1340 (const :tag "No limit" nil)
1341 (integer :tag "Maximum level")))
1343 (defcustom org-hide-block-startup nil
1344 "Non-nil means entering Org mode will fold all blocks.
1345 This can also be set in on a per-file basis with
1347 #+STARTUP: hideblocks
1348 #+STARTUP: showblocks"
1349 :group 'org-startup
1350 :group 'org-cycle
1351 :type 'boolean)
1353 (defcustom org-cycle-global-at-bob nil
1354 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1356 This makes it possible to do global cycling without having to use `S-TAB'
1357 or `\\[universal-argument] TAB'. For this special case to work, the first \
1358 line of the buffer
1359 must not be a headline -- it may be empty or some other text.
1361 When used in this way, `org-cycle-hook' is disabled temporarily to make
1362 sure the cursor stays at the beginning of the buffer.
1364 When this option is nil, don't do anything special at the beginning of
1365 the buffer."
1366 :group 'org-cycle
1367 :type 'boolean)
1369 (defcustom org-cycle-level-after-item/entry-creation t
1370 "Non-nil means cycle entry level or item indentation in new empty entries.
1372 When the cursor is at the end of an empty headline, i.e., with only stars
1373 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1374 and then all possible ancestor states, before returning to the original state.
1375 This makes data entry extremely fast: M-RET to create a new headline,
1376 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1378 When the cursor is at the end of an empty plain list item, one TAB will
1379 make it a subitem, two or more tabs will back up to make this an item
1380 higher up in the item hierarchy."
1381 :group 'org-cycle
1382 :type 'boolean)
1384 (defcustom org-cycle-emulate-tab t
1385 "Where should `org-cycle' emulate TAB.
1386 nil Never
1387 white Only in completely white lines
1388 whitestart Only at the beginning of lines, before the first non-white char
1389 t Everywhere except in headlines
1390 exc-hl-bol Everywhere except at the start of a headline
1391 If TAB is used in a place where it does not emulate TAB, the current subtree
1392 visibility is cycled."
1393 :group 'org-cycle
1394 :type '(choice (const :tag "Never" nil)
1395 (const :tag "Only in completely white lines" white)
1396 (const :tag "Before first char in a line" whitestart)
1397 (const :tag "Everywhere except in headlines" t)
1398 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1400 (defcustom org-cycle-separator-lines 2
1401 "Number of empty lines needed to keep an empty line between collapsed trees.
1402 If you leave an empty line between the end of a subtree and the following
1403 headline, this empty line is hidden when the subtree is folded.
1404 Org mode will leave (exactly) one empty line visible if the number of
1405 empty lines is equal or larger to the number given in this variable.
1406 So the default 2 means at least 2 empty lines after the end of a subtree
1407 are needed to produce free space between a collapsed subtree and the
1408 following headline.
1410 If the number is negative, and the number of empty lines is at least -N,
1411 all empty lines are shown.
1413 Special case: when 0, never leave empty lines in collapsed view."
1414 :group 'org-cycle
1415 :type 'integer)
1416 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1418 (defcustom org-pre-cycle-hook nil
1419 "Hook that is run before visibility cycling is happening.
1420 The function(s) in this hook must accept a single argument which indicates
1421 the new state that will be set right after running this hook. The
1422 argument is a symbol. Before a global state change, it can have the values
1423 `overview', `content', or `all'. Before a local state change, it can have
1424 the values `folded', `children', or `subtree'."
1425 :group 'org-cycle
1426 :type 'hook)
1428 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1429 org-cycle-hide-drawers
1430 org-cycle-show-empty-lines
1431 org-optimize-window-after-visibility-change)
1432 "Hook that is run after `org-cycle' has changed the buffer visibility.
1433 The function(s) in this hook must accept a single argument which indicates
1434 the new state that was set by the most recent `org-cycle' command. The
1435 argument is a symbol. After a global state change, it can have the values
1436 `overview', `contents', or `all'. After a local state change, it can have
1437 the values `folded', `children', or `subtree'."
1438 :group 'org-cycle
1439 :type 'hook
1440 :version "26.1"
1441 :package-version '(Org . "8.3"))
1443 (defgroup org-edit-structure nil
1444 "Options concerning structure editing in Org mode."
1445 :tag "Org Edit Structure"
1446 :group 'org-structure)
1448 (defcustom org-odd-levels-only nil
1449 "Non-nil means skip even levels and only use odd levels for the outline.
1450 This has the effect that two stars are being added/taken away in
1451 promotion/demotion commands. It also influences how levels are
1452 handled by the exporters.
1453 Changing it requires restart of `font-lock-mode' to become effective
1454 for fontification also in regions already fontified.
1455 You may also set this on a per-file basis by adding one of the following
1456 lines to the buffer:
1458 #+STARTUP: odd
1459 #+STARTUP: oddeven"
1460 :group 'org-edit-structure
1461 :group 'org-appearance
1462 :type 'boolean)
1464 (defcustom org-adapt-indentation t
1465 "Non-nil means adapt indentation to outline node level.
1467 When this variable is set, Org assumes that you write outlines by
1468 indenting text in each node to align with the headline (after the
1469 stars). The following issues are influenced by this variable:
1471 - The indentation is increased by one space in a demotion
1472 command, and decreased by one in a promotion command. However,
1473 in the latter case, if shifting some line in the entry body
1474 would alter document structure (e.g., insert a new headline),
1475 indentation is not changed at all.
1477 - Property drawers and planning information is inserted indented
1478 when this variable is set. When nil, they will not be indented.
1480 - TAB indents a line relative to current level. The lines below
1481 a headline will be indented when this variable is set.
1483 Note that this is all about true indentation, by adding and
1484 removing space characters. See also `org-indent.el' which does
1485 level-dependent indentation in a virtual way, i.e. at display
1486 time in Emacs."
1487 :group 'org-edit-structure
1488 :type 'boolean)
1490 (defcustom org-special-ctrl-a/e nil
1491 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1493 When t, `C-a' will bring back the cursor to the beginning of the
1494 headline text, i.e. after the stars and after a possible TODO
1495 keyword. In an item, this will be the position after bullet and
1496 check-box, if any. When the cursor is already at that position,
1497 another `C-a' will bring it to the beginning of the line.
1499 `C-e' will jump to the end of the headline, ignoring the presence
1500 of tags in the headline. A second `C-e' will then jump to the
1501 true end of the line, after any tags. This also means that, when
1502 this variable is non-nil, `C-e' also will never jump beyond the
1503 end of the heading of a folded section, i.e. not after the
1504 ellipses.
1506 When set to the symbol `reversed', the first `C-a' or `C-e' works
1507 normally, going to the true line boundary first. Only a directly
1508 following, identical keypress will bring the cursor to the
1509 special positions.
1511 This may also be a cons cell where the behavior for `C-a' and
1512 `C-e' is set separately."
1513 :group 'org-edit-structure
1514 :type '(choice
1515 (const :tag "off" nil)
1516 (const :tag "on: after stars/bullet and before tags first" t)
1517 (const :tag "reversed: true line boundary first" reversed)
1518 (cons :tag "Set C-a and C-e separately"
1519 (choice :tag "Special C-a"
1520 (const :tag "off" nil)
1521 (const :tag "on: after stars/bullet first" t)
1522 (const :tag "reversed: before stars/bullet first" reversed))
1523 (choice :tag "Special C-e"
1524 (const :tag "off" nil)
1525 (const :tag "on: before tags first" t)
1526 (const :tag "reversed: after tags first" reversed)))))
1527 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1529 (defcustom org-special-ctrl-k nil
1530 "Non-nil means `C-k' will behave specially in headlines.
1531 When nil, `C-k' will call the default `kill-line' command.
1532 When t, the following will happen while the cursor is in the headline:
1534 - When the cursor is at the beginning of a headline, kill the entire
1535 line and possible the folded subtree below the line.
1536 - When in the middle of the headline text, kill the headline up to the tags.
1537 - When after the headline text, kill the tags."
1538 :group 'org-edit-structure
1539 :type 'boolean)
1541 (defcustom org-ctrl-k-protect-subtree nil
1542 "Non-nil means, do not delete a hidden subtree with C-k.
1543 When set to the symbol `error', simply throw an error when C-k is
1544 used to kill (part-of) a headline that has hidden text behind it.
1545 Any other non-nil value will result in a query to the user, if it is
1546 OK to kill that hidden subtree. When nil, kill without remorse."
1547 :group 'org-edit-structure
1548 :version "24.1"
1549 :type '(choice
1550 (const :tag "Do not protect hidden subtrees" nil)
1551 (const :tag "Protect hidden subtrees with a security query" t)
1552 (const :tag "Never kill a hidden subtree with C-k" error)))
1554 (defcustom org-special-ctrl-o t
1555 "Non-nil means, make `C-o' insert a row in tables."
1556 :group 'org-edit-structure
1557 :type 'boolean)
1559 (defcustom org-catch-invisible-edits nil
1560 "Check if in invisible region before inserting or deleting a character.
1561 Valid values are:
1563 nil Do not check, so just do invisible edits.
1564 error Throw an error and do nothing.
1565 show Make point visible, and do the requested edit.
1566 show-and-error Make point visible, then throw an error and abort the edit.
1567 smart Make point visible, and do insertion/deletion if it is
1568 adjacent to visible text and the change feels predictable.
1569 Never delete a previously invisible character or add in the
1570 middle or right after an invisible region. Basically, this
1571 allows insertion and backward-delete right before ellipses.
1572 FIXME: maybe in this case we should not even show?"
1573 :group 'org-edit-structure
1574 :version "24.1"
1575 :type '(choice
1576 (const :tag "Do not check" nil)
1577 (const :tag "Throw error when trying to edit" error)
1578 (const :tag "Unhide, but do not do the edit" show-and-error)
1579 (const :tag "Show invisible part and do the edit" show)
1580 (const :tag "Be smart and do the right thing" smart)))
1582 (defcustom org-yank-folded-subtrees t
1583 "Non-nil means when yanking subtrees, fold them.
1584 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1585 it starts with a heading and all other headings in it are either children
1586 or siblings, then fold all the subtrees. However, do this only if no
1587 text after the yank would be swallowed into a folded tree by this action."
1588 :group 'org-edit-structure
1589 :type 'boolean)
1591 (defcustom org-yank-adjusted-subtrees nil
1592 "Non-nil means when yanking subtrees, adjust the level.
1593 With this setting, `org-paste-subtree' is used to insert the subtree, see
1594 this function for details."
1595 :group 'org-edit-structure
1596 :type 'boolean)
1598 (defcustom org-M-RET-may-split-line '((default . t))
1599 "Non-nil means M-RET will split the line at the cursor position.
1600 When nil, it will go to the end of the line before making a
1601 new line.
1602 You may also set this option in a different way for different
1603 contexts. Valid contexts are:
1605 headline when creating a new headline
1606 item when creating a new item
1607 table in a table field
1608 default the value to be used for all contexts not explicitly
1609 customized"
1610 :group 'org-structure
1611 :group 'org-table
1612 :type '(choice
1613 (const :tag "Always" t)
1614 (const :tag "Never" nil)
1615 (repeat :greedy t :tag "Individual contexts"
1616 (cons
1617 (choice :tag "Context"
1618 (const headline)
1619 (const item)
1620 (const table)
1621 (const default))
1622 (boolean)))))
1625 (defcustom org-insert-heading-respect-content nil
1626 "Non-nil means insert new headings after the current subtree.
1627 \\<org-mode-map>
1628 When nil, the new heading is created directly after the current line.
1629 The commands `\\[org-insert-heading-respect-content]' and \
1630 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1631 for the duration of the command."
1632 :group 'org-structure
1633 :type 'boolean)
1635 (defcustom org-blank-before-new-entry '((heading . auto)
1636 (plain-list-item . auto))
1637 "Should `org-insert-heading' leave a blank line before new heading/item?
1638 The value is an alist, with `heading' and `plain-list-item' as CAR,
1639 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1640 which case Org will look at the surrounding headings/items and try to
1641 make an intelligent decision whether to insert a blank line or not."
1642 :group 'org-edit-structure
1643 :type '(list
1644 (cons (const heading)
1645 (choice (const :tag "Never" nil)
1646 (const :tag "Always" t)
1647 (const :tag "Auto" auto)))
1648 (cons (const plain-list-item)
1649 (choice (const :tag "Never" nil)
1650 (const :tag "Always" t)
1651 (const :tag "Auto" auto)))))
1653 (defcustom org-insert-heading-hook nil
1654 "Hook being run after inserting a new heading."
1655 :group 'org-edit-structure
1656 :type 'hook)
1658 (defcustom org-enable-fixed-width-editor t
1659 "Non-nil means lines starting with \":\" are treated as fixed-width.
1660 This currently only means they are never auto-wrapped.
1661 When nil, such lines will be treated like ordinary lines."
1662 :group 'org-edit-structure
1663 :type 'boolean)
1665 (defcustom org-goto-auto-isearch t
1666 "Non-nil means typing characters in `org-goto' starts incremental search.
1667 When nil, you can use these keybindings to navigate the buffer:
1669 q Quit the org-goto interface
1670 n Go to the next visible heading
1671 p Go to the previous visible heading
1672 f Go one heading forward on same level
1673 b Go one heading backward on same level
1674 u Go one heading up"
1675 :group 'org-edit-structure
1676 :type 'boolean)
1678 (defgroup org-sparse-trees nil
1679 "Options concerning sparse trees in Org mode."
1680 :tag "Org Sparse Trees"
1681 :group 'org-structure)
1683 (defcustom org-highlight-sparse-tree-matches t
1684 "Non-nil means highlight all matches that define a sparse tree.
1685 The highlights will automatically disappear the next time the buffer is
1686 changed by an edit command."
1687 :group 'org-sparse-trees
1688 :type 'boolean)
1690 (defcustom org-remove-highlights-with-change t
1691 "Non-nil means any change to the buffer will remove temporary highlights.
1692 \\<org-mode-map>\
1693 Such highlights are created by `org-occur' and `org-clock-display'.
1694 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1695 to get rid of the highlights.
1696 The highlights created by `org-toggle-latex-fragment' always need
1697 `\\[org-toggle-latex-fragment]' to be removed."
1698 :group 'org-sparse-trees
1699 :group 'org-time
1700 :type 'boolean)
1702 (defcustom org-occur-case-fold-search t
1703 "Non-nil means `org-occur' should be case-insensitive.
1704 If set to `smart' the search will be case-insensitive only if it
1705 doesn't specify any upper case character."
1706 :group 'org-sparse-trees
1707 :version "26.1"
1708 :type '(choice
1709 (const :tag "Case-sensitive" nil)
1710 (const :tag "Case-insensitive" t)
1711 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1713 (defcustom org-occur-hook '(org-first-headline-recenter)
1714 "Hook that is run after `org-occur' has constructed a sparse tree.
1715 This can be used to recenter the window to show as much of the structure
1716 as possible."
1717 :group 'org-sparse-trees
1718 :type 'hook)
1720 (defgroup org-imenu-and-speedbar nil
1721 "Options concerning imenu and speedbar in Org mode."
1722 :tag "Org Imenu and Speedbar"
1723 :group 'org-structure)
1725 (defcustom org-imenu-depth 2
1726 "The maximum level for Imenu access to Org headlines.
1727 This also applied for speedbar access."
1728 :group 'org-imenu-and-speedbar
1729 :type 'integer)
1731 (defgroup org-table nil
1732 "Options concerning tables in Org mode."
1733 :tag "Org Table"
1734 :group 'org)
1736 (defcustom org-self-insert-cluster-for-undo nil
1737 "Non-nil means cluster self-insert commands for undo when possible.
1738 If this is set, then, like in the Emacs command loop, 20 consecutive
1739 characters will be undone together.
1740 This is configurable, because there is some impact on typing performance."
1741 :group 'org-table
1742 :type 'boolean)
1744 (defcustom org-table-tab-recognizes-table.el t
1745 "Non-nil means TAB will automatically notice a table.el table.
1746 When it sees such a table, it moves point into it and - if necessary -
1747 calls `table-recognize-table'."
1748 :group 'org-table-editing
1749 :type 'boolean)
1751 (defgroup org-link nil
1752 "Options concerning links in Org mode."
1753 :tag "Org Link"
1754 :group 'org)
1756 (defvar-local org-link-abbrev-alist-local nil
1757 "Buffer-local version of `org-link-abbrev-alist', which see.
1758 The value of this is taken from the #+LINK lines.")
1760 (defcustom org-link-parameters
1761 '(("doi" :follow org--open-doi-link)
1762 ("elisp" :follow org--open-elisp-link)
1763 ("file" :complete org-file-complete-link)
1764 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1765 ("help" :follow org--open-help-link)
1766 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1767 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1768 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1769 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1770 ("shell" :follow org--open-shell-link))
1771 "An alist of properties that defines all the links in Org mode.
1772 The key in each association is a string of the link type.
1773 Subsequent optional elements make up a p-list of link properties.
1775 :follow - A function that takes the link path as an argument.
1777 :export - A function that takes the link path, description and
1778 export-backend as arguments.
1780 :store - A function responsible for storing the link. See the
1781 function `org-store-link-functions'.
1783 :complete - A function that inserts a link with completion. The
1784 function takes one optional prefix arg.
1786 :face - A face for the link, or a function that returns a face.
1787 The function takes one argument which is the link path. The
1788 default face is `org-link'.
1790 :mouse-face - The mouse-face. The default is `highlight'.
1792 :display - `full' will not fold the link in descriptive
1793 display. Default is `org-link'.
1795 :help-echo - A string or function that takes (window object position)
1796 as arguments and returns a string.
1798 :keymap - A keymap that is active on the link. The default is
1799 `org-mouse-map'.
1801 :htmlize-link - A function for the htmlize-link. Defaults
1802 to (list :uri \"type:path\")
1804 :activate-func - A function to run at the end of font-lock
1805 activation. The function must accept (link-start link-end path bracketp)
1806 as arguments."
1807 :group 'org-link
1808 :type '(alist :tag "Link display parameters"
1809 :value-type plist)
1810 :version "26.1"
1811 :package-version '(Org . "9.1"))
1813 (defun org-link-get-parameter (type key)
1814 "Get TYPE link property for KEY.
1815 TYPE is a string and KEY is a plist keyword."
1816 (plist-get
1817 (cdr (assoc type org-link-parameters))
1818 key))
1820 (defun org-link-set-parameters (type &rest parameters)
1821 "Set link TYPE properties to PARAMETERS.
1822 PARAMETERS should be :key val pairs."
1823 (let ((data (assoc type org-link-parameters)))
1824 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1825 (push (cons type parameters) org-link-parameters)
1826 (org-make-link-regexps)
1827 (org-element-update-syntax))))
1829 (defun org-link-types ()
1830 "Return a list of known link types."
1831 (mapcar #'car org-link-parameters))
1833 (defcustom org-link-abbrev-alist nil
1834 "Alist of link abbreviations.
1835 The car of each element is a string, to be replaced at the start of a link.
1836 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1837 links in Org buffers can have an optional tag after a double colon, e.g.,
1839 [[linkkey:tag][description]]
1841 The `linkkey' must be a single word, starting with a letter, followed
1842 by letters, numbers, `-' or `_'.
1844 If REPLACE is a string, the tag will simply be appended to create the link.
1845 If the string contains \"%s\", the tag will be inserted there. If the string
1846 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1847 at that point (see the function `url-hexify-string'). If the string contains
1848 the specifier \"%(my-function)\", then the custom function `my-function' will
1849 be invoked: this function takes the tag as its only argument and must return
1850 a string.
1852 REPLACE may also be a function that will be called with the tag as the
1853 only argument to create the link, which should be returned as a string.
1855 See the manual for examples."
1856 :group 'org-link
1857 :type '(repeat
1858 (cons
1859 (string :tag "Protocol")
1860 (choice
1861 (string :tag "Format")
1862 (function)))))
1864 (defcustom org-descriptive-links t
1865 "Non-nil means Org will display descriptive links.
1866 E.g. [[http://orgmode.org][Org website]] will be displayed as
1867 \"Org Website\", hiding the link itself and just displaying its
1868 description. When set to nil, Org will display the full links
1869 literally.
1871 You can interactively set the value of this variable by calling
1872 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1873 :group 'org-link
1874 :type 'boolean)
1876 (defcustom org-link-file-path-type 'adaptive
1877 "How the path name in file links should be stored.
1878 Valid values are:
1880 relative Relative to the current directory, i.e. the directory of the file
1881 into which the link is being inserted.
1882 absolute Absolute path, if possible with ~ for home directory.
1883 noabbrev Absolute path, no abbreviation of home directory.
1884 adaptive Use relative path for files in the current directory and sub-
1885 directories of it. For other files, use an absolute path."
1886 :group 'org-link
1887 :type '(choice
1888 (const relative)
1889 (const absolute)
1890 (const noabbrev)
1891 (const adaptive)))
1893 (defvaralias 'org-activate-links 'org-highlight-links)
1894 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1895 "Types of links that should be highlighted in Org files.
1897 This is a list of symbols, each one of them leading to the
1898 highlighting of a certain link type.
1900 You can still open links that are not highlighted.
1902 In principle, it does not hurt to turn on highlighting for all
1903 link types. There may be a small gain when turning off unused
1904 link types. The types are:
1906 bracket The recommended [[link][description]] or [[link]] links with hiding.
1907 angle Links in angular brackets that may contain whitespace like
1908 <bbdb:Carsten Dominik>.
1909 plain Plain links in normal text, no whitespace, like http://google.com.
1910 radio Text that is matched by a radio target, see manual for details.
1911 tag Tag settings in a headline (link to tag search).
1912 date Time stamps (link to calendar).
1913 footnote Footnote labels.
1915 If you set this variable during an Emacs session, use `org-mode-restart'
1916 in the Org buffer so that the change takes effect."
1917 :group 'org-link
1918 :group 'org-appearance
1919 :type '(set :greedy t
1920 (const :tag "Double bracket links" bracket)
1921 (const :tag "Angular bracket links" angle)
1922 (const :tag "Plain text links" plain)
1923 (const :tag "Radio target matches" radio)
1924 (const :tag "Tags" tag)
1925 (const :tag "Timestamps" date)
1926 (const :tag "Footnotes" footnote)))
1928 (defcustom org-make-link-description-function nil
1929 "Function to use for generating link descriptions from links.
1930 This function must take two parameters: the first one is the
1931 link, the second one is the description generated by
1932 `org-insert-link'. The function should return the description to
1933 use."
1934 :group 'org-link
1935 :type '(choice (const nil) (function)))
1937 (defgroup org-link-store nil
1938 "Options concerning storing links in Org mode."
1939 :tag "Org Store Link"
1940 :group 'org-link)
1942 (defcustom org-url-hexify-p t
1943 "When non-nil, hexify URL when creating a link."
1944 :type 'boolean
1945 :version "24.3"
1946 :group 'org-link-store)
1948 (defcustom org-email-link-description-format "Email %c: %.30s"
1949 "Format of the description part of a link to an email or usenet message.
1950 The following %-escapes will be replaced by corresponding information:
1952 %F full \"From\" field
1953 %f name, taken from \"From\" field, address if no name
1954 %T full \"To\" field
1955 %t first name in \"To\" field, address if no name
1956 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1957 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1958 %s subject
1959 %d date
1960 %m message-id.
1962 You may use normal field width specification between the % and the letter.
1963 This is for example useful to limit the length of the subject.
1965 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1966 :group 'org-link-store
1967 :type 'string)
1969 (defcustom org-from-is-user-regexp
1970 (let (r1 r2)
1971 (when (and user-mail-address (not (string= user-mail-address "")))
1972 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1973 (when (and user-full-name (not (string= user-full-name "")))
1974 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1975 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1976 "Regexp matched against the \"From:\" header of an email or usenet message.
1977 It should match if the message is from the user him/herself."
1978 :group 'org-link-store
1979 :type 'regexp)
1981 (defcustom org-context-in-file-links t
1982 "Non-nil means file links from `org-store-link' contain context.
1983 \\<org-mode-map>
1984 A search string will be added to the file name with :: as separator
1985 and used to find the context when the link is activated by the command
1986 `org-open-at-point'. When this option is t, the entire active region
1987 will be placed in the search string of the file link. If set to a
1988 positive integer, only the first n lines of context will be stored.
1990 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
1991 \\[org-store-link]')
1992 negates this setting for the duration of the command."
1993 :group 'org-link-store
1994 :type '(choice boolean integer))
1996 (defcustom org-keep-stored-link-after-insertion nil
1997 "Non-nil means keep link in list for entire session.
1998 \\<org-mode-map>
1999 The command `org-store-link' adds a link pointing to the current
2000 location to an internal list. These links accumulate during a session.
2001 The command `org-insert-link' can be used to insert links into any
2002 Org file (offering completion for all stored links).
2004 When this option is nil, every link which has been inserted once using
2005 `\\[org-insert-link]' will be removed from the list, to make completing the \
2006 unused
2007 links more efficient."
2008 :group 'org-link-store
2009 :type 'boolean)
2011 (defgroup org-link-follow nil
2012 "Options concerning following links in Org mode."
2013 :tag "Org Follow Link"
2014 :group 'org-link)
2016 (defcustom org-link-translation-function nil
2017 "Function to translate links with different syntax to Org syntax.
2018 This can be used to translate links created for example by the Planner
2019 or emacs-wiki packages to Org syntax.
2020 The function must accept two parameters, a TYPE containing the link
2021 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2022 which is everything after the link protocol. It should return a cons
2023 with possibly modified values of type and path.
2024 Org contains a function for this, so if you set this variable to
2025 `org-translate-link-from-planner', you should be able follow many
2026 links created by planner."
2027 :group 'org-link-follow
2028 :type '(choice (const nil) (function)))
2030 (defcustom org-follow-link-hook nil
2031 "Hook that is run after a link has been followed."
2032 :group 'org-link-follow
2033 :type 'hook)
2035 (defcustom org-tab-follows-link nil
2036 "Non-nil means on links TAB will follow the link.
2037 Needs to be set before org.el is loaded.
2038 This really should not be used, it does not make sense, and the
2039 implementation is bad."
2040 :group 'org-link-follow
2041 :type 'boolean)
2043 (defcustom org-return-follows-link nil
2044 "Non-nil means on links RET will follow the link.
2045 In tables, the special behavior of RET has precedence."
2046 :group 'org-link-follow
2047 :type 'boolean)
2049 (defcustom org-mouse-1-follows-link
2050 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2051 "Non-nil means mouse-1 on a link will follow the link.
2052 A longer mouse click will still set point. Needs to be set
2053 before org.el is loaded."
2054 :group 'org-link-follow
2055 :version "26.1"
2056 :package-version '(Org . "8.3")
2057 :type '(choice
2058 (const :tag "A double click follows the link" double)
2059 (const :tag "Unconditionally follow the link with mouse-1" t)
2060 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2062 (defcustom org-mark-ring-length 4
2063 "Number of different positions to be recorded in the ring.
2064 Changing this requires a restart of Emacs to work correctly."
2065 :group 'org-link-follow
2066 :type 'integer)
2068 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2069 "Non-nil means internal fuzzy links can only match headlines.
2071 When nil, the a fuzzy link may point to a target or a named
2072 construct in the document. When set to the special value
2073 `query-to-create', offer to create a new headline when none
2074 matched.
2076 Spaces and statistics cookies are ignored during heading searches."
2077 :group 'org-link-follow
2078 :version "24.1"
2079 :type '(choice
2080 (const :tag "Use fuzzy text search" nil)
2081 (const :tag "Match only exact headline" t)
2082 (const :tag "Match exact headline or query to create it"
2083 query-to-create))
2084 :safe #'symbolp)
2086 (defcustom org-link-frame-setup
2087 '((vm . vm-visit-folder-other-frame)
2088 (vm-imap . vm-visit-imap-folder-other-frame)
2089 (gnus . org-gnus-no-new-news)
2090 (file . find-file-other-window)
2091 (wl . wl-other-frame))
2092 "Setup the frame configuration for following links.
2093 When following a link with Emacs, it may often be useful to display
2094 this link in another window or frame. This variable can be used to
2095 set this up for the different types of links.
2096 For VM, use any of
2097 `vm-visit-folder'
2098 `vm-visit-folder-other-window'
2099 `vm-visit-folder-other-frame'
2100 For Gnus, use any of
2101 `gnus'
2102 `gnus-other-frame'
2103 `org-gnus-no-new-news'
2104 For FILE, use any of
2105 `find-file'
2106 `find-file-other-window'
2107 `find-file-other-frame'
2108 For Wanderlust use any of
2109 `wl'
2110 `wl-other-frame'
2111 For the calendar, use the variable `calendar-setup'.
2112 For BBDB, it is currently only possible to display the matches in
2113 another window."
2114 :group 'org-link-follow
2115 :type '(list
2116 (cons (const vm)
2117 (choice
2118 (const vm-visit-folder)
2119 (const vm-visit-folder-other-window)
2120 (const vm-visit-folder-other-frame)))
2121 (cons (const vm-imap)
2122 (choice
2123 (const vm-visit-imap-folder)
2124 (const vm-visit-imap-folder-other-window)
2125 (const vm-visit-imap-folder-other-frame)))
2126 (cons (const gnus)
2127 (choice
2128 (const gnus)
2129 (const gnus-other-frame)
2130 (const org-gnus-no-new-news)))
2131 (cons (const file)
2132 (choice
2133 (const find-file)
2134 (const find-file-other-window)
2135 (const find-file-other-frame)))
2136 (cons (const wl)
2137 (choice
2138 (const wl)
2139 (const wl-other-frame)))))
2141 (defcustom org-display-internal-link-with-indirect-buffer nil
2142 "Non-nil means use indirect buffer to display infile links.
2143 Activating internal links (from one location in a file to another location
2144 in the same file) normally just jumps to the location. When the link is
2145 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2146 is displayed in
2147 another window. When this option is set, the other window actually displays
2148 an indirect buffer clone of the current buffer, to avoid any visibility
2149 changes to the current buffer."
2150 :group 'org-link-follow
2151 :type 'boolean)
2153 (defcustom org-open-non-existing-files nil
2154 "Non-nil means `org-open-file' will open non-existing files.
2155 When nil, an error will be generated.
2156 This variable applies only to external applications because they
2157 might choke on non-existing files. If the link is to a file that
2158 will be opened in Emacs, the variable is ignored."
2159 :group 'org-link-follow
2160 :type 'boolean)
2162 (defcustom org-open-directory-means-index-dot-org nil
2163 "Non-nil means a link to a directory really means to index.org.
2164 When nil, following a directory link will run dired or open a finder/explorer
2165 window on that directory."
2166 :group 'org-link-follow
2167 :type 'boolean)
2169 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2170 "Non-nil means ask for confirmation before executing shell links.
2171 Shell links can be dangerous: just think about a link
2173 [[shell:rm -rf ~/*][Google Search]]
2175 This link would show up in your Org document as \"Google Search\",
2176 but really it would remove your entire home directory.
2177 Therefore we advise against setting this variable to nil.
2178 Just change it to `y-or-n-p' if you want to confirm with a
2179 single keystroke rather than having to type \"yes\"."
2180 :group 'org-link-follow
2181 :type '(choice
2182 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2183 (const :tag "with y-or-n (faster)" y-or-n-p)
2184 (const :tag "no confirmation (dangerous)" nil)))
2185 (put 'org-confirm-shell-link-function
2186 'safe-local-variable
2187 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2189 (defcustom org-confirm-shell-link-not-regexp ""
2190 "A regexp to skip confirmation for shell links."
2191 :group 'org-link-follow
2192 :version "24.1"
2193 :type 'regexp)
2195 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2196 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2197 Elisp links can be dangerous: just think about a link
2199 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2201 This link would show up in your Org document as \"Google Search\",
2202 but really it would remove your entire home directory.
2203 Therefore we advise against setting this variable to nil.
2204 Just change it to `y-or-n-p' if you want to confirm with a
2205 single keystroke rather than having to type \"yes\"."
2206 :group 'org-link-follow
2207 :type '(choice
2208 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2209 (const :tag "with y-or-n (faster)" y-or-n-p)
2210 (const :tag "no confirmation (dangerous)" nil)))
2211 (put 'org-confirm-shell-link-function
2212 'safe-local-variable
2213 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2215 (defcustom org-confirm-elisp-link-not-regexp ""
2216 "A regexp to skip confirmation for Elisp links."
2217 :group 'org-link-follow
2218 :version "24.1"
2219 :type 'regexp)
2221 (defconst org-file-apps-defaults-gnu
2222 '((remote . emacs)
2223 (system . mailcap)
2224 (t . mailcap))
2225 "Default file applications on a UNIX or GNU/Linux system.
2226 See `org-file-apps'.")
2228 (defconst org-file-apps-defaults-macosx
2229 '((remote . emacs)
2230 (system . "open %s")
2231 ("ps.gz" . "gv %s")
2232 ("eps.gz" . "gv %s")
2233 ("dvi" . "xdvi %s")
2234 ("fig" . "xfig %s")
2235 (t . "open %s"))
2236 "Default file applications on a macOS system.
2237 The system \"open\" is known as a default, but we use X11 applications
2238 for some files for which the OS does not have a good default.
2239 See `org-file-apps'.")
2241 (defconst org-file-apps-defaults-windowsnt
2242 (list '(remote . emacs)
2243 (cons 'system (lambda (file _path)
2244 (with-no-warnings (w32-shell-execute "open" file))))
2245 (cons t (lambda (file _path)
2246 (with-no-warnings (w32-shell-execute "open" file)))))
2247 "Default file applications on a Windows NT system.
2248 The system \"open\" is used for most files.
2249 See `org-file-apps'.")
2251 (defcustom org-file-apps
2252 '((auto-mode . emacs)
2253 ("\\.mm\\'" . default)
2254 ("\\.x?html?\\'" . default)
2255 ("\\.pdf\\'" . default))
2256 "External applications for opening `file:path' items in a document.
2257 \\<org-mode-map>\
2259 Org mode uses system defaults for different file types, but
2260 you can use this variable to set the application for a given file
2261 extension. The entries in this list are cons cells where the car identifies
2262 files and the cdr the corresponding command.
2264 Possible values for the file identifier are:
2266 \"string\" A string as a file identifier can be interpreted in different
2267 ways, depending on its contents:
2269 - Alphanumeric characters only:
2270 Match links with this file extension.
2271 Example: (\"pdf\" . \"evince %s\")
2272 to open PDFs with evince.
2274 - Regular expression: Match links where the
2275 filename matches the regexp. If you want to
2276 use groups here, use shy groups.
2278 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2279 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2280 to open *.html and *.xhtml with firefox.
2282 - Regular expression which contains (non-shy) groups:
2283 Match links where the whole link, including \"::\", and
2284 anything after that, matches the regexp.
2285 In a custom command string, %1, %2, etc. are replaced with
2286 the parts of the link that were matched by the groups.
2287 For backwards compatibility, if a command string is given
2288 that does not use any of the group matches, this case is
2289 handled identically to the second one (i.e. match against
2290 file name only).
2291 In a custom function, you can access the group matches with
2292 (match-string n link).
2294 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2295 \"evince -p %1 %s\")
2296 to open [[file:document.pdf::5]] with evince at page 5.
2298 `directory' Matches a directory
2299 `remote' Matches a remote file, accessible through tramp or efs.
2300 Remote files most likely should be visited through Emacs
2301 because external applications cannot handle such paths.
2302 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2303 so all files Emacs knows how to handle. Using this with
2304 command `emacs' will open most files in Emacs. Beware that this
2305 will also open html files inside Emacs, unless you add
2306 (\"html\" . default) to the list as well.
2307 `system' The system command to open files, like `open' on Windows
2308 and macOS, and mailcap under GNU/Linux. This is the command
2309 that will be selected if you call `org-open-at-point' with a
2310 double prefix argument (`\\[universal-argument] \
2311 \\[universal-argument] \\[org-open-at-point]').
2312 t Default for files not matched by any of the other options.
2314 Possible values for the command are:
2316 `emacs' The file will be visited by the current Emacs process.
2317 `default' Use the default application for this file type, which is the
2318 association for t in the list, most likely in the system-specific
2319 part. This can be used to overrule an unwanted setting in the
2320 system-specific variable.
2321 `system' Use the system command for opening files, like \"open\".
2322 This command is specified by the entry whose car is `system'.
2323 Most likely, the system-specific version of this variable
2324 does define this command, but you can overrule/replace it
2325 here.
2326 `mailcap' Use command specified in the mailcaps.
2327 string A command to be executed by a shell; %s will be replaced
2328 by the path to the file.
2329 function A Lisp function, which will be called with two arguments:
2330 the file path and the original link string, without the
2331 \"file:\" prefix.
2333 For more examples, see the system specific constants
2334 `org-file-apps-defaults-macosx'
2335 `org-file-apps-defaults-windowsnt'
2336 `org-file-apps-defaults-gnu'."
2337 :group 'org-link-follow
2338 :type '(repeat
2339 (cons (choice :value ""
2340 (string :tag "Extension")
2341 (const :tag "System command to open files" system)
2342 (const :tag "Default for unrecognized files" t)
2343 (const :tag "Remote file" remote)
2344 (const :tag "Links to a directory" directory)
2345 (const :tag "Any files that have Emacs modes"
2346 auto-mode))
2347 (choice :value ""
2348 (const :tag "Visit with Emacs" emacs)
2349 (const :tag "Use default" default)
2350 (const :tag "Use the system command" system)
2351 (string :tag "Command")
2352 (function :tag "Function")))))
2354 (defcustom org-doi-server-url "http://dx.doi.org/"
2355 "The URL of the DOI server."
2356 :type 'string
2357 :version "24.3"
2358 :group 'org-link-follow)
2360 (defgroup org-refile nil
2361 "Options concerning refiling entries in Org mode."
2362 :tag "Org Refile"
2363 :group 'org)
2365 (defcustom org-directory "~/org"
2366 "Directory with Org files.
2367 This is just a default location to look for Org files. There is no need
2368 at all to put your files into this directory. It is used in the
2369 following situations:
2371 1. When a capture template specifies a target file that is not an
2372 absolute path. The path will then be interpreted relative to
2373 `org-directory'
2374 2. When the value of variable `org-agenda-files' is a single file, any
2375 relative paths in this file will be taken as relative to
2376 `org-directory'."
2377 :group 'org-refile
2378 :group 'org-capture
2379 :type 'directory)
2381 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2382 "Default target for storing notes.
2383 Used as a fall back file for org-capture.el, for templates that
2384 do not specify a target file."
2385 :group 'org-refile
2386 :group 'org-capture
2387 :type 'file)
2389 (defcustom org-goto-interface 'outline
2390 "The default interface to be used for `org-goto'.
2391 Allowed values are:
2392 outline The interface shows an outline of the relevant file
2393 and the correct heading is found by moving through
2394 the outline or by searching with incremental search.
2395 outline-path-completion Headlines in the current buffer are offered via
2396 completion. This is the interface also used by
2397 the refile command."
2398 :group 'org-refile
2399 :type '(choice
2400 (const :tag "Outline" outline)
2401 (const :tag "Outline-path-completion" outline-path-completion)))
2403 (defcustom org-goto-max-level 5
2404 "Maximum target level when running `org-goto' with refile interface."
2405 :group 'org-refile
2406 :type 'integer)
2408 (defcustom org-reverse-note-order nil
2409 "Non-nil means store new notes at the beginning of a file or entry.
2410 When nil, new notes will be filed to the end of a file or entry.
2411 This can also be a list with cons cells of regular expressions that
2412 are matched against file names, and values."
2413 :group 'org-capture
2414 :group 'org-refile
2415 :type '(choice
2416 (const :tag "Reverse always" t)
2417 (const :tag "Reverse never" nil)
2418 (repeat :tag "By file name regexp"
2419 (cons regexp boolean))))
2421 (defcustom org-log-refile nil
2422 "Information to record when a task is refiled.
2424 Possible values are:
2426 nil Don't add anything
2427 time Add a time stamp to the task
2428 note Prompt for a note and add it with template `org-log-note-headings'
2430 This option can also be set with on a per-file-basis with
2432 #+STARTUP: nologrefile
2433 #+STARTUP: logrefile
2434 #+STARTUP: lognoterefile
2436 You can have local logging settings for a subtree by setting the LOGGING
2437 property to one or more of these keywords.
2439 When bulk-refiling from the agenda, the value `note' is forbidden and
2440 will temporarily be changed to `time'."
2441 :group 'org-refile
2442 :group 'org-progress
2443 :version "24.1"
2444 :type '(choice
2445 (const :tag "No logging" nil)
2446 (const :tag "Record timestamp" time)
2447 (const :tag "Record timestamp with note." note)))
2449 (defcustom org-refile-targets nil
2450 "Targets for refiling entries with `\\[org-refile]'.
2451 This is a list of cons cells. Each cell contains:
2452 - a specification of the files to be considered, either a list of files,
2453 or a symbol whose function or variable value will be used to retrieve
2454 a file name or a list of file names. If you use `org-agenda-files' for
2455 that, all agenda files will be scanned for targets. Nil means consider
2456 headings in the current buffer.
2457 - A specification of how to find candidate refile targets. This may be
2458 any of:
2459 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2460 This tag has to be present in all target headlines, inheritance will
2461 not be considered.
2462 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2463 todo keyword.
2464 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2465 headlines that are refiling targets.
2466 - a cons cell (:level . N). Any headline of level N is considered a target.
2467 Note that, when `org-odd-levels-only' is set, level corresponds to
2468 order in hierarchy, not to the number of stars.
2469 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2470 Note that, when `org-odd-levels-only' is set, level corresponds to
2471 order in hierarchy, not to the number of stars.
2473 Each element of this list generates a set of possible targets.
2474 The union of these sets is presented (with completion) to
2475 the user by `org-refile'.
2477 You can set the variable `org-refile-target-verify-function' to a function
2478 to verify each headline found by the simple criteria above.
2480 When this variable is nil, all top-level headlines in the current buffer
2481 are used, equivalent to the value `((nil . (:level . 1))'."
2482 :group 'org-refile
2483 :type '(repeat
2484 (cons
2485 (choice :value org-agenda-files
2486 (const :tag "All agenda files" org-agenda-files)
2487 (const :tag "Current buffer" nil)
2488 (function) (variable) (file))
2489 (choice :tag "Identify target headline by"
2490 (cons :tag "Specific tag" (const :value :tag) (string))
2491 (cons :tag "TODO keyword" (const :value :todo) (string))
2492 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2493 (cons :tag "Level number" (const :value :level) (integer))
2494 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2496 (defcustom org-refile-target-verify-function nil
2497 "Function to verify if the headline at point should be a refile target.
2498 The function will be called without arguments, with point at the
2499 beginning of the headline. It should return t and leave point
2500 where it is if the headline is a valid target for refiling.
2502 If the target should not be selected, the function must return nil.
2503 In addition to this, it may move point to a place from where the search
2504 should be continued. For example, the function may decide that the entire
2505 subtree of the current entry should be excluded and move point to the end
2506 of the subtree."
2507 :group 'org-refile
2508 :type '(choice
2509 (const nil)
2510 (function)))
2512 (defcustom org-refile-use-cache nil
2513 "Non-nil means cache refile targets to speed up the process.
2514 \\<org-mode-map>\
2515 The cache for a particular file will be updated automatically when
2516 the buffer has been killed, or when any of the marker used for flagging
2517 refile targets no longer points at a live buffer.
2518 If you have added new entries to a buffer that might themselves be targets,
2519 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2520 if you find that easier, \
2521 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2522 \\[org-refile]'."
2523 :group 'org-refile
2524 :version "24.1"
2525 :type 'boolean)
2527 (defcustom org-refile-use-outline-path nil
2528 "Non-nil means provide refile targets as paths.
2529 So a level 3 headline will be available as level1/level2/level3.
2531 When the value is `file', also include the file name (without directory)
2532 into the path. In this case, you can also stop the completion after
2533 the file name, to get entries inserted as top level in the file.
2535 When `full-file-path', include the full file path.
2537 When `buffer-name', use the buffer name."
2538 :group 'org-refile
2539 :type '(choice
2540 (const :tag "Not" nil)
2541 (const :tag "Yes" t)
2542 (const :tag "Start with file name" file)
2543 (const :tag "Start with full file path" full-file-path)
2544 (const :tag "Start with buffer name" buffer-name)))
2546 (defcustom org-outline-path-complete-in-steps t
2547 "Non-nil means complete the outline path in hierarchical steps.
2548 When Org uses the refile interface to select an outline path (see
2549 `org-refile-use-outline-path'), the completion of the path can be
2550 done in a single go, or it can be done in steps down the headline
2551 hierarchy. Going in steps is probably the best if you do not use
2552 a special completion package like `ido' or `icicles'. However,
2553 when using these packages, going in one step can be very fast,
2554 while still showing the whole path to the entry."
2555 :group 'org-refile
2556 :type 'boolean)
2558 (defcustom org-refile-allow-creating-parent-nodes nil
2559 "Non-nil means allow the creation of new nodes as refile targets.
2560 New nodes are then created by adding \"/new node name\" to the completion
2561 of an existing node. When the value of this variable is `confirm',
2562 new node creation must be confirmed by the user (recommended).
2563 When nil, the completion must match an existing entry.
2565 Note that, if the new heading is not seen by the criteria
2566 listed in `org-refile-targets', multiple instances of the same
2567 heading would be created by trying again to file under the new
2568 heading."
2569 :group 'org-refile
2570 :type '(choice
2571 (const :tag "Never" nil)
2572 (const :tag "Always" t)
2573 (const :tag "Prompt for confirmation" confirm)))
2575 (defcustom org-refile-active-region-within-subtree nil
2576 "Non-nil means also refile active region within a subtree.
2578 By default `org-refile' doesn't allow refiling regions if they
2579 don't contain a set of subtrees, but it might be convenient to
2580 do so sometimes: in that case, the first line of the region is
2581 converted to a headline before refiling."
2582 :group 'org-refile
2583 :version "24.1"
2584 :type 'boolean)
2586 (defgroup org-todo nil
2587 "Options concerning TODO items in Org mode."
2588 :tag "Org TODO"
2589 :group 'org)
2591 (defgroup org-progress nil
2592 "Options concerning Progress logging in Org mode."
2593 :tag "Org Progress"
2594 :group 'org-time)
2596 (defvar org-todo-interpretation-widgets
2597 '((:tag "Sequence (cycling hits every state)" sequence)
2598 (:tag "Type (cycling directly to DONE)" type))
2599 "The available interpretation symbols for customizing `org-todo-keywords'.
2600 Interested libraries should add to this list.")
2602 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2603 "List of TODO entry keyword sequences and their interpretation.
2604 \\<org-mode-map>This is a list of sequences.
2606 Each sequence starts with a symbol, either `sequence' or `type',
2607 indicating if the keywords should be interpreted as a sequence of
2608 action steps, or as different types of TODO items. The first
2609 keywords are states requiring action - these states will select a headline
2610 for inclusion into the global TODO list Org produces. If one of the
2611 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2612 signify that no further action is necessary. If \"|\" is not found,
2613 the last keyword is treated as the only DONE state of the sequence.
2615 The command `\\[org-todo]' cycles an entry through these states, and one
2616 additional state where no keyword is present. For details about this
2617 cycling, see the manual.
2619 TODO keywords and interpretation can also be set on a per-file basis with
2620 the special #+SEQ_TODO and #+TYP_TODO lines.
2622 Each keyword can optionally specify a character for fast state selection
2623 \(in combination with the variable `org-use-fast-todo-selection')
2624 and specifiers for state change logging, using the same syntax that
2625 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2626 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2627 indicates to record a time stamp each time this state is selected.
2629 Each keyword may also specify if a timestamp or a note should be
2630 recorded when entering or leaving the state, by adding additional
2631 characters in the parenthesis after the keyword. This looks like this:
2632 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2633 record only the time of the state change. With X and Y being either
2634 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2635 Y when leaving the state if and only if the *target* state does not
2636 define X. You may omit any of the fast-selection key or X or /Y,
2637 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2639 For backward compatibility, this variable may also be just a list
2640 of keywords. In this case the interpretation (sequence or type) will be
2641 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2642 :group 'org-todo
2643 :group 'org-keywords
2644 :type '(choice
2645 (repeat :tag "Old syntax, just keywords"
2646 (string :tag "Keyword"))
2647 (repeat :tag "New syntax"
2648 (cons
2649 (choice
2650 :tag "Interpretation"
2651 ;;Quick and dirty way to see
2652 ;;`org-todo-interpretations'. This takes the
2653 ;;place of item arguments
2654 :convert-widget
2655 (lambda (widget)
2656 (widget-put widget
2657 :args (mapcar
2658 (lambda (x)
2659 (widget-convert
2660 (cons 'const x)))
2661 org-todo-interpretation-widgets))
2662 widget))
2663 (repeat
2664 (string :tag "Keyword"))))))
2666 (defvar-local org-todo-keywords-1 nil
2667 "All TODO and DONE keywords active in a buffer.")
2668 (defvar org-todo-keywords-for-agenda nil)
2669 (defvar org-done-keywords-for-agenda nil)
2670 (defvar org-todo-keyword-alist-for-agenda nil)
2671 (defvar org-tag-alist-for-agenda nil
2672 "Alist of all tags from all agenda files.")
2673 (defvar org-tag-groups-alist-for-agenda nil
2674 "Alist of all groups tags from all current agenda files.")
2675 (defvar-local org-tag-groups-alist nil)
2676 (defvar org-agenda-contributing-files nil)
2677 (defvar-local org-current-tag-alist nil
2678 "Alist of all tag groups in current buffer.
2679 This variable takes into consideration `org-tag-alist',
2680 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2681 (defvar-local org-not-done-keywords nil)
2682 (defvar-local org-done-keywords nil)
2683 (defvar-local org-todo-heads nil)
2684 (defvar-local org-todo-sets nil)
2685 (defvar-local org-todo-log-states nil)
2686 (defvar-local org-todo-kwd-alist nil)
2687 (defvar-local org-todo-key-alist nil)
2688 (defvar-local org-todo-key-trigger nil)
2690 (defcustom org-todo-interpretation 'sequence
2691 "Controls how TODO keywords are interpreted.
2692 This variable is in principle obsolete and is only used for
2693 backward compatibility, if the interpretation of todo keywords is
2694 not given already in `org-todo-keywords'. See that variable for
2695 more information."
2696 :group 'org-todo
2697 :group 'org-keywords
2698 :type '(choice (const sequence)
2699 (const type)))
2701 (defcustom org-use-fast-todo-selection t
2702 "\\<org-mode-map>\
2703 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2704 This variable describes if and under what circumstances the cycling
2705 mechanism for TODO keywords will be replaced by a single-key, direct
2706 selection scheme.
2708 When nil, fast selection is never used.
2710 When the symbol `prefix', it will be used when `org-todo' is called
2711 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2712 in an Org buffer, and
2713 `\\[universal-argument] t' in an agenda buffer.
2715 When t, fast selection is used by default. In this case, the prefix
2716 argument forces cycling instead.
2718 In all cases, the special interface is only used if access keys have
2719 actually been assigned by the user, i.e. if keywords in the configuration
2720 are followed by a letter in parenthesis, like TODO(t)."
2721 :group 'org-todo
2722 :type '(choice
2723 (const :tag "Never" nil)
2724 (const :tag "By default" t)
2725 (const :tag "Only with C-u C-c C-t" prefix)))
2727 (defcustom org-provide-todo-statistics t
2728 "Non-nil means update todo statistics after insert and toggle.
2729 ALL-HEADLINES means update todo statistics by including headlines
2730 with no TODO keyword as well, counting them as not done.
2731 A list of TODO keywords means the same, but skip keywords that are
2732 not in this list.
2733 When set to a list of two lists, the first list contains keywords
2734 to consider as TODO keywords, the second list contains keywords
2735 to consider as DONE keywords.
2737 When this is set, todo statistics is updated in the parent of the
2738 current entry each time a todo state is changed."
2739 :group 'org-todo
2740 :type '(choice
2741 (const :tag "Yes, only for TODO entries" t)
2742 (const :tag "Yes, including all entries" all-headlines)
2743 (repeat :tag "Yes, for TODOs in this list"
2744 (string :tag "TODO keyword"))
2745 (list :tag "Yes, for TODOs and DONEs in these lists"
2746 (repeat (string :tag "TODO keyword"))
2747 (repeat (string :tag "DONE keyword")))
2748 (other :tag "No TODO statistics" nil)))
2750 (defcustom org-hierarchical-todo-statistics t
2751 "Non-nil means TODO statistics covers just direct children.
2752 When nil, all entries in the subtree are considered.
2753 This has only an effect if `org-provide-todo-statistics' is set.
2754 To set this to nil for only a single subtree, use a COOKIE_DATA
2755 property and include the word \"recursive\" into the value."
2756 :group 'org-todo
2757 :type 'boolean)
2759 (defcustom org-after-todo-state-change-hook nil
2760 "Hook which is run after the state of a TODO item was changed.
2761 The new state (a string with a TODO keyword, or nil) is available in the
2762 Lisp variable `org-state'."
2763 :group 'org-todo
2764 :type 'hook)
2766 (defvar org-blocker-hook nil
2767 "Hook for functions that are allowed to block a state change.
2769 Functions in this hook should not modify the buffer.
2770 Each function gets as its single argument a property list,
2771 see `org-trigger-hook' for more information about this list.
2773 If any of the functions in this hook returns nil, the state change
2774 is blocked.")
2776 (defvar org-trigger-hook nil
2777 "Hook for functions that are triggered by a state change.
2779 Each function gets as its single argument a property list with at
2780 least the following elements:
2782 (:type type-of-change :position pos-at-entry-start
2783 :from old-state :to new-state)
2785 Depending on the type, more properties may be present.
2787 This mechanism is currently implemented for:
2789 TODO state changes
2790 ------------------
2791 :type todo-state-change
2792 :from previous state (keyword as a string), or nil, or a symbol
2793 `todo' or `done', to indicate the general type of state.
2794 :to new state, like in :from")
2796 (defcustom org-enforce-todo-dependencies nil
2797 "Non-nil means undone TODO entries will block switching the parent to DONE.
2798 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2799 be blocked if any prior sibling is not yet done.
2800 Finally, if the parent is blocked because of ordered siblings of its own,
2801 the child will also be blocked."
2802 :set (lambda (var val)
2803 (set var val)
2804 (if val
2805 (add-hook 'org-blocker-hook
2806 'org-block-todo-from-children-or-siblings-or-parent)
2807 (remove-hook 'org-blocker-hook
2808 'org-block-todo-from-children-or-siblings-or-parent)))
2809 :group 'org-todo
2810 :type 'boolean)
2812 (defcustom org-enforce-todo-checkbox-dependencies nil
2813 "Non-nil means unchecked boxes will block switching the parent to DONE.
2814 When this is nil, checkboxes have no influence on switching TODO states.
2815 When non-nil, you first need to check off all check boxes before the TODO
2816 entry can be switched to DONE.
2817 This variable needs to be set before org.el is loaded, and you need to
2818 restart Emacs after a change to make the change effective. The only way
2819 to change is while Emacs is running is through the customize interface."
2820 :set (lambda (var val)
2821 (set var val)
2822 (if val
2823 (add-hook 'org-blocker-hook
2824 'org-block-todo-from-checkboxes)
2825 (remove-hook 'org-blocker-hook
2826 'org-block-todo-from-checkboxes)))
2827 :group 'org-todo
2828 :type 'boolean)
2830 (defcustom org-treat-insert-todo-heading-as-state-change nil
2831 "Non-nil means inserting a TODO heading is treated as state change.
2832 So when the command `\\[org-insert-todo-heading]' is used, state change
2833 logging will apply if appropriate. When nil, the new TODO item will
2834 be inserted directly, and no logging will take place."
2835 :group 'org-todo
2836 :type 'boolean)
2838 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2839 "Non-nil means switching TODO states with S-cursor counts as state change.
2840 This is the default behavior. However, setting this to nil allows a
2841 convenient way to select a TODO state and bypass any logging associated
2842 with that."
2843 :group 'org-todo
2844 :type 'boolean)
2846 (defcustom org-todo-state-tags-triggers nil
2847 "Tag changes that should be triggered by TODO state changes.
2848 This is a list. Each entry is
2850 (state-change (tag . flag) .......)
2852 State-change can be a string with a state, and empty string to indicate the
2853 state that has no TODO keyword, or it can be one of the symbols `todo'
2854 or `done', meaning any not-done or done state, respectively."
2855 :group 'org-todo
2856 :group 'org-tags
2857 :type '(repeat
2858 (cons (choice :tag "When changing to"
2859 (const :tag "Not-done state" todo)
2860 (const :tag "Done state" done)
2861 (string :tag "State"))
2862 (repeat
2863 (cons :tag "Tag action"
2864 (string :tag "Tag")
2865 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2867 (defcustom org-log-done nil
2868 "Information to record when a task moves to the DONE state.
2870 Possible values are:
2872 nil Don't add anything, just change the keyword
2873 time Add a time stamp to the task
2874 note Prompt for a note and add it with template `org-log-note-headings'
2876 This option can also be set with on a per-file-basis with
2878 #+STARTUP: nologdone
2879 #+STARTUP: logdone
2880 #+STARTUP: lognotedone
2882 You can have local logging settings for a subtree by setting the LOGGING
2883 property to one or more of these keywords."
2884 :group 'org-todo
2885 :group 'org-progress
2886 :type '(choice
2887 (const :tag "No logging" nil)
2888 (const :tag "Record CLOSED timestamp" time)
2889 (const :tag "Record CLOSED timestamp with note." note)))
2891 ;; Normalize old uses of org-log-done.
2892 (cond
2893 ((eq org-log-done t) (setq org-log-done 'time))
2894 ((and (listp org-log-done) (memq 'done org-log-done))
2895 (setq org-log-done 'note)))
2897 (defcustom org-log-reschedule nil
2898 "Information to record when the scheduling date of a tasks is modified.
2900 Possible values are:
2902 nil Don't add anything, just change the date
2903 time Add a time stamp to the task
2904 note Prompt for a note and add it with template `org-log-note-headings'
2906 This option can also be set with on a per-file-basis with
2908 #+STARTUP: nologreschedule
2909 #+STARTUP: logreschedule
2910 #+STARTUP: lognotereschedule"
2911 :group 'org-todo
2912 :group 'org-progress
2913 :type '(choice
2914 (const :tag "No logging" nil)
2915 (const :tag "Record timestamp" time)
2916 (const :tag "Record timestamp with note." note)))
2918 (defcustom org-log-redeadline nil
2919 "Information to record when the deadline date of a tasks is modified.
2921 Possible values are:
2923 nil Don't add anything, just change the date
2924 time Add a time stamp to the task
2925 note Prompt for a note and add it with template `org-log-note-headings'
2927 This option can also be set with on a per-file-basis with
2929 #+STARTUP: nologredeadline
2930 #+STARTUP: logredeadline
2931 #+STARTUP: lognoteredeadline
2933 You can have local logging settings for a subtree by setting the LOGGING
2934 property to one or more of these keywords."
2935 :group 'org-todo
2936 :group 'org-progress
2937 :type '(choice
2938 (const :tag "No logging" nil)
2939 (const :tag "Record timestamp" time)
2940 (const :tag "Record timestamp with note." note)))
2942 (defcustom org-log-note-clock-out nil
2943 "Non-nil means record a note when clocking out of an item.
2944 This can also be configured on a per-file basis by adding one of
2945 the following lines anywhere in the buffer:
2947 #+STARTUP: lognoteclock-out
2948 #+STARTUP: nolognoteclock-out"
2949 :group 'org-todo
2950 :group 'org-progress
2951 :type 'boolean)
2953 (defcustom org-log-done-with-time t
2954 "Non-nil means the CLOSED time stamp will contain date and time.
2955 When nil, only the date will be recorded."
2956 :group 'org-progress
2957 :type 'boolean)
2959 (defcustom org-log-note-headings
2960 '((done . "CLOSING NOTE %t")
2961 (state . "State %-12s from %-12S %t")
2962 (note . "Note taken on %t")
2963 (reschedule . "Rescheduled from %S on %t")
2964 (delschedule . "Not scheduled, was %S on %t")
2965 (redeadline . "New deadline from %S on %t")
2966 (deldeadline . "Removed deadline, was %S on %t")
2967 (refile . "Refiled on %t")
2968 (clock-out . ""))
2969 "Headings for notes added to entries.
2971 The value is an alist, with the car being a symbol indicating the
2972 note context, and the cdr is the heading to be used. The heading
2973 may also be the empty string. The following placeholders can be
2974 used:
2976 %t a time stamp.
2977 %T an active time stamp instead the default inactive one
2978 %d a short-format time stamp.
2979 %D an active short-format time stamp.
2980 %s the new TODO state or time stamp (inactive), in double quotes.
2981 %S the old TODO state or time stamp (inactive), in double quotes.
2982 %u the user name.
2983 %U full user name.
2985 In fact, it is not a good idea to change the `state' entry,
2986 because Agenda Log mode depends on the format of these entries."
2987 :group 'org-todo
2988 :group 'org-progress
2989 :type '(list :greedy t
2990 (cons (const :tag "Heading when closing an item" done) string)
2991 (cons (const :tag
2992 "Heading when changing todo state (todo sequence only)"
2993 state) string)
2994 (cons (const :tag "Heading when just taking a note" note) string)
2995 (cons (const :tag "Heading when rescheduling" reschedule) string)
2996 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2997 (cons (const :tag "Heading when changing deadline" redeadline) string)
2998 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2999 (cons (const :tag "Heading when refiling" refile) string)
3000 (cons (const :tag "Heading when clocking out" clock-out) string)))
3002 (unless (assq 'note org-log-note-headings)
3003 (push '(note . "%t") org-log-note-headings))
3005 (defcustom org-log-into-drawer nil
3006 "Non-nil means insert state change notes and time stamps into a drawer.
3007 When nil, state changes notes will be inserted after the headline and
3008 any scheduling and clock lines, but not inside a drawer.
3010 The value of this variable should be the name of the drawer to use.
3011 LOGBOOK is proposed as the default drawer for this purpose, you can
3012 also set this to a string to define the drawer of your choice.
3014 A value of t is also allowed, representing \"LOGBOOK\".
3016 A value of t or nil can also be set with on a per-file-basis with
3018 #+STARTUP: logdrawer
3019 #+STARTUP: nologdrawer
3021 If this variable is set, `org-log-state-notes-insert-after-drawers'
3022 will be ignored.
3024 You can set the property LOG_INTO_DRAWER to overrule this setting for
3025 a subtree.
3027 Do not check directly this variable in a Lisp program. Call
3028 function `org-log-into-drawer' instead."
3029 :group 'org-todo
3030 :group 'org-progress
3031 :type '(choice
3032 (const :tag "Not into a drawer" nil)
3033 (const :tag "LOGBOOK" t)
3034 (string :tag "Other")))
3036 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3038 (defun org-log-into-drawer ()
3039 "Name of the log drawer, as a string, or nil.
3040 This is the value of `org-log-into-drawer'. However, if the
3041 current entry has or inherits a LOG_INTO_DRAWER property, it will
3042 be used instead of the default value."
3043 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3044 (cond ((equal p "nil") nil)
3045 ((equal p "t") "LOGBOOK")
3046 ((stringp p) p)
3047 (p "LOGBOOK")
3048 ((stringp org-log-into-drawer) org-log-into-drawer)
3049 (org-log-into-drawer "LOGBOOK"))))
3051 (defcustom org-log-state-notes-insert-after-drawers nil
3052 "Non-nil means insert state change notes after any drawers in entry.
3053 Only the drawers that *immediately* follow the headline and the
3054 deadline/scheduled line are skipped.
3055 When nil, insert notes right after the heading and perhaps the line
3056 with deadline/scheduling if present.
3058 This variable will have no effect if `org-log-into-drawer' is
3059 set."
3060 :group 'org-todo
3061 :group 'org-progress
3062 :type 'boolean)
3064 (defcustom org-log-states-order-reversed t
3065 "Non-nil means the latest state note will be directly after heading.
3066 When nil, the state change notes will be ordered according to time.
3068 This option can also be set with on a per-file-basis with
3070 #+STARTUP: logstatesreversed
3071 #+STARTUP: nologstatesreversed"
3072 :group 'org-todo
3073 :group 'org-progress
3074 :type 'boolean)
3076 (defcustom org-todo-repeat-to-state nil
3077 "The TODO state to which a repeater should return the repeating task.
3078 By default this is the first task in a TODO sequence, or the previous state
3079 in a TODO_TYP set. But you can specify another task here.
3080 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3081 :group 'org-todo
3082 :version "24.1"
3083 :type '(choice (const :tag "Head of sequence" nil)
3084 (string :tag "Specific state")))
3086 (defcustom org-log-repeat 'time
3087 "Non-nil means record moving through the DONE state when triggering repeat.
3088 An auto-repeating task is immediately switched back to TODO when
3089 marked DONE. If you are not logging state changes (by adding \"@\"
3090 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3091 record a closing note, there will be no record of the task moving
3092 through DONE. This variable forces taking a note anyway.
3094 nil Don't force a record
3095 time Record a time stamp
3096 note Prompt for a note and add it with template `org-log-note-headings'
3098 This option can also be set with on a per-file-basis with
3100 #+STARTUP: nologrepeat
3101 #+STARTUP: logrepeat
3102 #+STARTUP: lognoterepeat
3104 You can have local logging settings for a subtree by setting the LOGGING
3105 property to one or more of these keywords."
3106 :group 'org-todo
3107 :group 'org-progress
3108 :type '(choice
3109 (const :tag "Don't force a record" nil)
3110 (const :tag "Force recording the DONE state" time)
3111 (const :tag "Force recording a note with the DONE state" note)))
3114 (defgroup org-priorities nil
3115 "Priorities in Org mode."
3116 :tag "Org Priorities"
3117 :group 'org-todo)
3119 (defcustom org-enable-priority-commands t
3120 "Non-nil means priority commands are active.
3121 When nil, these commands will be disabled, so that you never accidentally
3122 set a priority."
3123 :group 'org-priorities
3124 :type 'boolean)
3126 (defcustom org-highest-priority ?A
3127 "The highest priority of TODO items. A character like ?A, ?B etc.
3128 Must have a smaller ASCII number than `org-lowest-priority'."
3129 :group 'org-priorities
3130 :type 'character)
3132 (defcustom org-lowest-priority ?C
3133 "The lowest priority of TODO items. A character like ?A, ?B etc.
3134 Must have a larger ASCII number than `org-highest-priority'."
3135 :group 'org-priorities
3136 :type 'character)
3138 (defcustom org-default-priority ?B
3139 "The default priority of TODO items.
3140 This is the priority an item gets if no explicit priority is given.
3141 When starting to cycle on an empty priority the first step in the cycle
3142 depends on `org-priority-start-cycle-with-default'. The resulting first
3143 step priority must not exceed the range from `org-highest-priority' to
3144 `org-lowest-priority' which means that `org-default-priority' has to be
3145 in this range exclusive or inclusive the range boundaries. Else the
3146 first step refuses to set the default and the second will fall back
3147 to (depending on the command used) the highest or lowest priority."
3148 :group 'org-priorities
3149 :type 'character)
3151 (defcustom org-priority-start-cycle-with-default t
3152 "Non-nil means start with default priority when starting to cycle.
3153 When this is nil, the first step in the cycle will be (depending on the
3154 command used) one higher or lower than the default priority.
3155 See also `org-default-priority'."
3156 :group 'org-priorities
3157 :type 'boolean)
3159 (defcustom org-get-priority-function nil
3160 "Function to extract the priority from a string.
3161 The string is normally the headline. If this is nil Org computes the
3162 priority from the priority cookie like [#A] in the headline. It returns
3163 an integer, increasing by 1000 for each priority level.
3164 The user can set a different function here, which should take a string
3165 as an argument and return the numeric priority."
3166 :group 'org-priorities
3167 :version "24.1"
3168 :type '(choice
3169 (const nil)
3170 (function)))
3172 (defgroup org-time nil
3173 "Options concerning time stamps and deadlines in Org mode."
3174 :tag "Org Time"
3175 :group 'org)
3177 (defcustom org-time-stamp-rounding-minutes '(0 5)
3178 "Number of minutes to round time stamps to.
3179 \\<org-mode-map>\
3180 These are two values, the first applies when first creating a time stamp.
3181 The second applies when changing it with the commands `S-up' and `S-down'.
3182 When changing the time stamp, this means that it will change in steps
3183 of N minutes, as given by the second value.
3185 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3186 numbers should be factors of 60, so for example 5, 10, 15.
3188 When this is larger than 1, you can still force an exact time stamp by using
3189 a double prefix argument to a time stamp command like \
3190 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3191 and by using a prefix arg to `S-up/down' to specify the exact number
3192 of minutes to shift."
3193 :group 'org-time
3194 :get (lambda (var) ; Make sure both elements are there
3195 (if (integerp (default-value var))
3196 (list (default-value var) 5)
3197 (default-value var)))
3198 :type '(list
3199 (integer :tag "when inserting times")
3200 (integer :tag "when modifying times")))
3202 ;; Normalize old customizations of this variable.
3203 (when (integerp org-time-stamp-rounding-minutes)
3204 (setq org-time-stamp-rounding-minutes
3205 (list org-time-stamp-rounding-minutes
3206 org-time-stamp-rounding-minutes)))
3208 (defcustom org-display-custom-times nil
3209 "Non-nil means overlay custom formats over all time stamps.
3210 The formats are defined through the variable `org-time-stamp-custom-formats'.
3211 To turn this on on a per-file basis, insert anywhere in the file:
3212 #+STARTUP: customtime"
3213 :group 'org-time
3214 :set 'set-default
3215 :type 'sexp)
3216 (make-variable-buffer-local 'org-display-custom-times)
3218 (defcustom org-time-stamp-custom-formats
3219 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3220 "Custom formats for time stamps. See `format-time-string' for the syntax.
3221 These are overlaid over the default ISO format if the variable
3222 `org-display-custom-times' is set. Time like %H:%M should be at the
3223 end of the second format. The custom formats are also honored by export
3224 commands, if custom time display is turned on at the time of export."
3225 :group 'org-time
3226 :type 'sexp)
3228 (defun org-time-stamp-format (&optional long inactive)
3229 "Get the right format for a time string."
3230 (let ((f (if long (cdr org-time-stamp-formats)
3231 (car org-time-stamp-formats))))
3232 (if inactive
3233 (concat "[" (substring f 1 -1) "]")
3234 f)))
3236 (defcustom org-deadline-warning-days 14
3237 "Number of days before expiration during which a deadline becomes active.
3238 This variable governs the display in sparse trees and in the agenda.
3239 When 0 or negative, it means use this number (the absolute value of it)
3240 even if a deadline has a different individual lead time specified.
3242 Custom commands can set this variable in the options section."
3243 :group 'org-time
3244 :group 'org-agenda-daily/weekly
3245 :type 'integer)
3247 (defcustom org-scheduled-delay-days 0
3248 "Number of days before a scheduled item becomes active.
3249 This variable governs the display in sparse trees and in the agenda.
3250 The default value (i.e. 0) means: don't delay scheduled item.
3251 When negative, it means use this number (the absolute value of it)
3252 even if a scheduled item has a different individual delay time
3253 specified.
3255 Custom commands can set this variable in the options section."
3256 :group 'org-time
3257 :group 'org-agenda-daily/weekly
3258 :version "24.4"
3259 :package-version '(Org . "8.0")
3260 :type 'integer)
3262 (defcustom org-read-date-prefer-future t
3263 "Non-nil means assume future for incomplete date input from user.
3264 This affects the following situations:
3265 1. The user gives a month but not a year.
3266 For example, if it is April and you enter \"feb 2\", this will be read
3267 as Feb 2, *next* year. \"May 5\", however, will be this year.
3268 2. The user gives a day, but no month.
3269 For example, if today is the 15th, and you enter \"3\", Org will read
3270 this as the third of *next* month. However, if you enter \"17\",
3271 it will be considered as *this* month.
3273 If you set this variable to the symbol `time', then also the following
3274 will work:
3276 3. If the user gives a time.
3277 If the time is before now, it will be interpreted as tomorrow.
3279 Currently none of this works for ISO week specifications.
3281 When this option is nil, the current day, month and year will always be
3282 used as defaults.
3284 See also `org-agenda-jump-prefer-future'."
3285 :group 'org-time
3286 :type '(choice
3287 (const :tag "Never" nil)
3288 (const :tag "Check month and day" t)
3289 (const :tag "Check month, day, and time" time)))
3291 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3292 "Should the agenda jump command prefer the future for incomplete dates?
3293 The default is to do the same as configured in `org-read-date-prefer-future'.
3294 But you can also set a deviating value here.
3295 This may t or nil, or the symbol `org-read-date-prefer-future'."
3296 :group 'org-agenda
3297 :group 'org-time
3298 :version "24.1"
3299 :type '(choice
3300 (const :tag "Use org-read-date-prefer-future"
3301 org-read-date-prefer-future)
3302 (const :tag "Never" nil)
3303 (const :tag "Always" t)))
3305 (defcustom org-read-date-force-compatible-dates t
3306 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3308 Depending on the system Emacs is running on, certain dates cannot
3309 be represented with the type used internally to represent time.
3310 Dates between 1970-1-1 and 2038-1-1 can always be represented
3311 correctly. Some systems allow for earlier dates, some for later,
3312 some for both. One way to find out it to insert any date into an
3313 Org buffer, putting the cursor on the year and hitting S-up and
3314 S-down to test the range.
3316 When this variable is set to t, the date/time prompt will not let
3317 you specify dates outside the 1970-2037 range, so it is certain that
3318 these dates will work in whatever version of Emacs you are
3319 running, and also that you can move a file from one Emacs implementation
3320 to another. WHenever Org is forcing the year for you, it will display
3321 a message and beep.
3323 When this variable is nil, Org will check if the date is
3324 representable in the specific Emacs implementation you are using.
3325 If not, it will force a year, usually the current year, and beep
3326 to remind you. Currently this setting is not recommended because
3327 the likelihood that you will open your Org files in an Emacs that
3328 has limited date range is not negligible.
3330 A workaround for this problem is to use diary sexp dates for time
3331 stamps outside of this range."
3332 :group 'org-time
3333 :version "24.1"
3334 :type 'boolean)
3336 (defcustom org-read-date-display-live t
3337 "Non-nil means display current interpretation of date prompt live.
3338 This display will be in an overlay, in the minibuffer."
3339 :group 'org-time
3340 :type 'boolean)
3342 (defcustom org-read-date-popup-calendar t
3343 "Non-nil means pop up a calendar when prompting for a date.
3344 In the calendar, the date can be selected with mouse-1. However, the
3345 minibuffer will also be active, and you can simply enter the date as well.
3346 When nil, only the minibuffer will be available."
3347 :group 'org-time
3348 :type 'boolean)
3349 (defvaralias 'org-popup-calendar-for-date-prompt
3350 'org-read-date-popup-calendar)
3352 (defcustom org-extend-today-until 0
3353 "The hour when your day really ends. Must be an integer.
3354 This has influence for the following applications:
3355 - When switching the agenda to \"today\". It it is still earlier than
3356 the time given here, the day recognized as TODAY is actually yesterday.
3357 - When a date is read from the user and it is still before the time given
3358 here, the current date and time will be assumed to be yesterday, 23:59.
3359 Also, timestamps inserted in capture templates follow this rule.
3361 IMPORTANT: This is a feature whose implementation is and likely will
3362 remain incomplete. Really, it is only here because past midnight seems to
3363 be the favorite working time of John Wiegley :-)"
3364 :group 'org-time
3365 :type 'integer)
3367 (defcustom org-use-effective-time nil
3368 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3369 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3370 \"effective time\" of any timestamps between midnight and 8am will be
3371 23:59 of the previous day."
3372 :group 'org-time
3373 :version "24.1"
3374 :type 'boolean)
3376 (defcustom org-use-last-clock-out-time-as-effective-time nil
3377 "When non-nil, use the last clock out time for `org-todo'.
3378 Note that this option has precedence over the combined use of
3379 `org-use-effective-time' and `org-extend-today-until'."
3380 :group 'org-time
3381 :version "24.4"
3382 :package-version '(Org . "8.0")
3383 :type 'boolean)
3385 (defcustom org-edit-timestamp-down-means-later nil
3386 "Non-nil means S-down will increase the time in a time stamp.
3387 When nil, S-up will increase."
3388 :group 'org-time
3389 :type 'boolean)
3391 (defcustom org-calendar-follow-timestamp-change t
3392 "Non-nil means make the calendar window follow timestamp changes.
3393 When a timestamp is modified and the calendar window is visible, it will be
3394 moved to the new date."
3395 :group 'org-time
3396 :type 'boolean)
3398 (defgroup org-tags nil
3399 "Options concerning tags in Org mode."
3400 :tag "Org Tags"
3401 :group 'org)
3403 (defcustom org-tag-alist nil
3404 "Default tags available in Org files.
3406 The value of this variable is an alist. Associations either:
3408 (TAG)
3409 (TAG . SELECT)
3410 (SPECIAL)
3412 where TAG is a tag as a string, SELECT is character, used to
3413 select that tag through the fast tag selection interface, and
3414 SPECIAL is one of the following keywords: `:startgroup',
3415 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3416 `:newline'. These keywords are used to define a hierarchy of
3417 tags. See manual for details.
3419 When this variable is nil, Org mode bases tag input on what is
3420 already in the buffer. The value can be overridden locally by
3421 using a TAGS keyword, e.g.,
3423 #+TAGS: tag1 tag2
3425 See also `org-tag-persistent-alist' to sidestep this behavior."
3426 :group 'org-tags
3427 :type '(repeat
3428 (choice
3429 (cons :tag "Tag with key"
3430 (string :tag "Tag name")
3431 (character :tag "Access char"))
3432 (list :tag "Tag" (string :tag "Tag name"))
3433 (const :tag "Start radio group" (:startgroup))
3434 (const :tag "Start tag group, non distinct" (:startgrouptag))
3435 (const :tag "Group tags delimiter" (:grouptags))
3436 (const :tag "End radio group" (:endgroup))
3437 (const :tag "End tag group, non distinct" (:endgrouptag))
3438 (const :tag "New line" (:newline)))))
3440 (defcustom org-tag-persistent-alist nil
3441 "Tags always available in Org files.
3443 The value of this variable is an alist. Associations either:
3445 (TAG)
3446 (TAG . SELECT)
3447 (SPECIAL)
3449 where TAG is a tag as a string, SELECT is a character, used to
3450 select that tag through the fast tag selection interface, and
3451 SPECIAL is one of the following keywords: `:startgroup',
3452 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3453 `:newline'. These keywords are used to define a hierarchy of
3454 tags. See manual for details.
3456 Unlike to `org-tag-alist', tags defined in this variable do not
3457 depend on a local TAGS keyword. Instead, to disable these tags
3458 on a per-file basis, insert anywhere in the file:
3460 #+STARTUP: noptag"
3461 :group 'org-tags
3462 :type '(repeat
3463 (choice
3464 (cons :tag "Tag with key"
3465 (string :tag "Tag name")
3466 (character :tag "Access char"))
3467 (list :tag "Tag" (string :tag "Tag name"))
3468 (const :tag "Start radio group" (:startgroup))
3469 (const :tag "Start tag group, non distinct" (:startgrouptag))
3470 (const :tag "Group tags delimiter" (:grouptags))
3471 (const :tag "End radio group" (:endgroup))
3472 (const :tag "End tag group, non distinct" (:endgrouptag))
3473 (const :tag "New line" (:newline)))))
3475 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3476 "If non-nil, always offer completion for all tags of all agenda files.
3477 Instead of customizing this variable directly, you might want to
3478 set it locally for capture buffers, because there no list of
3479 tags in that file can be created dynamically (there are none).
3481 (add-hook \\='org-capture-mode-hook
3482 (lambda ()
3483 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3484 :group 'org-tags
3485 :version "24.1"
3486 :type 'boolean)
3488 (defvar org-file-tags nil
3489 "List of tags that can be inherited by all entries in the file.
3490 The tags will be inherited if the variable `org-use-tag-inheritance'
3491 says they should be.
3492 This variable is populated from #+FILETAGS lines.")
3494 (defcustom org-use-fast-tag-selection 'auto
3495 "Non-nil means use fast tag selection scheme.
3496 This is a special interface to select and deselect tags with single keys.
3497 When nil, fast selection is never used.
3498 When the symbol `auto', fast selection is used if and only if selection
3499 characters for tags have been configured, either through the variable
3500 `org-tag-alist' or through a #+TAGS line in the buffer.
3501 When t, fast selection is always used and selection keys are assigned
3502 automatically if necessary."
3503 :group 'org-tags
3504 :type '(choice
3505 (const :tag "Always" t)
3506 (const :tag "Never" nil)
3507 (const :tag "When selection characters are configured" auto)))
3509 (defcustom org-fast-tag-selection-single-key nil
3510 "Non-nil means fast tag selection exits after first change.
3511 When nil, you have to press RET to exit it.
3512 During fast tag selection, you can toggle this flag with `C-c'.
3513 This variable can also have the value `expert'. In this case, the window
3514 displaying the tags menu is not even shown, until you press C-c again."
3515 :group 'org-tags
3516 :type '(choice
3517 (const :tag "No" nil)
3518 (const :tag "Yes" t)
3519 (const :tag "Expert" expert)))
3521 (defvar org-fast-tag-selection-include-todo nil
3522 "Non-nil means fast tags selection interface will also offer TODO states.
3523 This is an undocumented feature, you should not rely on it.")
3525 (defcustom org-tags-column -77
3526 "The column to which tags should be indented in a headline.
3527 If this number is positive, it specifies the column. If it is negative,
3528 it means that the tags should be flushright to that column. For example,
3529 -80 works well for a normal 80 character screen.
3530 When 0, place tags directly after headline text, with only one space in
3531 between."
3532 :group 'org-tags
3533 :type 'integer)
3535 (defcustom org-auto-align-tags t
3536 "Non-nil keeps tags aligned when modifying headlines.
3537 Some operations (i.e. demoting) change the length of a headline and
3538 therefore shift the tags around. With this option turned on, after
3539 each such operation the tags are again aligned to `org-tags-column'."
3540 :group 'org-tags
3541 :type 'boolean)
3543 (defcustom org-use-tag-inheritance t
3544 "Non-nil means tags in levels apply also for sublevels.
3545 When nil, only the tags directly given in a specific line apply there.
3546 This may also be a list of tags that should be inherited, or a regexp that
3547 matches tags that should be inherited. Additional control is possible
3548 with the variable `org-tags-exclude-from-inheritance' which gives an
3549 explicit list of tags to be excluded from inheritance, even if the value of
3550 `org-use-tag-inheritance' would select it for inheritance.
3552 If this option is t, a match early-on in a tree can lead to a large
3553 number of matches in the subtree when constructing the agenda or creating
3554 a sparse tree. If you only want to see the first match in a tree during
3555 a search, check out the variable `org-tags-match-list-sublevels'."
3556 :group 'org-tags
3557 :type '(choice
3558 (const :tag "Not" nil)
3559 (const :tag "Always" t)
3560 (repeat :tag "Specific tags" (string :tag "Tag"))
3561 (regexp :tag "Tags matched by regexp")))
3563 (defcustom org-tags-exclude-from-inheritance nil
3564 "List of tags that should never be inherited.
3565 This is a way to exclude a few tags from inheritance. For way to do
3566 the opposite, to actively allow inheritance for selected tags,
3567 see the variable `org-use-tag-inheritance'."
3568 :group 'org-tags
3569 :type '(repeat (string :tag "Tag")))
3571 (defun org-tag-inherit-p (tag)
3572 "Check if TAG is one that should be inherited."
3573 (cond
3574 ((member tag org-tags-exclude-from-inheritance) nil)
3575 ((eq org-use-tag-inheritance t) t)
3576 ((not org-use-tag-inheritance) nil)
3577 ((stringp org-use-tag-inheritance)
3578 (string-match org-use-tag-inheritance tag))
3579 ((listp org-use-tag-inheritance)
3580 (member tag org-use-tag-inheritance))
3581 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3583 (defcustom org-tags-match-list-sublevels t
3584 "Non-nil means list also sublevels of headlines matching a search.
3585 This variable applies to tags/property searches, and also to stuck
3586 projects because this search is based on a tags match as well.
3588 When set to the symbol `indented', sublevels are indented with
3589 leading dots.
3591 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3592 the sublevels of a headline matching a tag search often also match
3593 the same search. Listing all of them can create very long lists.
3594 Setting this variable to nil causes subtrees of a match to be skipped.
3596 This variable is semi-obsolete and probably should always be true. It
3597 is better to limit inheritance to certain tags using the variables
3598 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3599 :group 'org-tags
3600 :type '(choice
3601 (const :tag "No, don't list them" nil)
3602 (const :tag "Yes, do list them" t)
3603 (const :tag "List them, indented with leading dots" indented)))
3605 (defcustom org-tags-sort-function nil
3606 "When set, tags are sorted using this function as a comparator."
3607 :group 'org-tags
3608 :type '(choice
3609 (const :tag "No sorting" nil)
3610 (const :tag "Alphabetical" string<)
3611 (const :tag "Reverse alphabetical" string>)
3612 (function :tag "Custom function" nil)))
3614 (defvar org-tags-history nil
3615 "History of minibuffer reads for tags.")
3616 (defvar org-last-tags-completion-table nil
3617 "The last used completion table for tags.")
3618 (defvar org-after-tags-change-hook nil
3619 "Hook that is run after the tags in a line have changed.")
3621 (defgroup org-properties nil
3622 "Options concerning properties in Org mode."
3623 :tag "Org Properties"
3624 :group 'org)
3626 (defcustom org-property-format "%-10s %s"
3627 "How property key/value pairs should be formatted by `indent-line'.
3628 When `indent-line' hits a property definition, it will format the line
3629 according to this format, mainly to make sure that the values are
3630 lined-up with respect to each other."
3631 :group 'org-properties
3632 :type 'string)
3634 (defcustom org-properties-postprocess-alist nil
3635 "Alist of properties and functions to adjust inserted values.
3636 Elements of this alist must be of the form
3638 ([string] [function])
3640 where [string] must be a property name and [function] must be a
3641 lambda expression: this lambda expression must take one argument,
3642 the value to adjust, and return the new value as a string.
3644 For example, this element will allow the property \"Remaining\"
3645 to be updated wrt the relation between the \"Effort\" property
3646 and the clock summary:
3648 ((\"Remaining\" (lambda(value)
3649 (let ((clocksum (org-clock-sum-current-item))
3650 (effort (org-duration-to-minutes
3651 (org-entry-get (point) \"Effort\"))))
3652 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3653 :group 'org-properties
3654 :version "24.1"
3655 :type '(alist :key-type (string :tag "Property")
3656 :value-type (function :tag "Function")))
3658 (defcustom org-use-property-inheritance nil
3659 "Non-nil means properties apply also for sublevels.
3661 This setting is chiefly used during property searches. Turning it on can
3662 cause significant overhead when doing a search, which is why it is not
3663 on by default.
3665 When nil, only the properties directly given in the current entry count.
3666 When t, every property is inherited. The value may also be a list of
3667 properties that should have inheritance, or a regular expression matching
3668 properties that should be inherited.
3670 However, note that some special properties use inheritance under special
3671 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3672 and the properties ending in \"_ALL\" when they are used as descriptor
3673 for valid values of a property.
3675 Note for programmers:
3676 When querying an entry with `org-entry-get', you can control if inheritance
3677 should be used. By default, `org-entry-get' looks only at the local
3678 properties. You can request inheritance by setting the inherit argument
3679 to t (to force inheritance) or to `selective' (to respect the setting
3680 in this variable)."
3681 :group 'org-properties
3682 :type '(choice
3683 (const :tag "Not" nil)
3684 (const :tag "Always" t)
3685 (repeat :tag "Specific properties" (string :tag "Property"))
3686 (regexp :tag "Properties matched by regexp")))
3688 (defun org-property-inherit-p (property)
3689 "Return a non-nil value if PROPERTY should be inherited."
3690 (cond
3691 ((eq org-use-property-inheritance t) t)
3692 ((not org-use-property-inheritance) nil)
3693 ((stringp org-use-property-inheritance)
3694 (string-match org-use-property-inheritance property))
3695 ((listp org-use-property-inheritance)
3696 (member-ignore-case property org-use-property-inheritance))
3697 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3699 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3700 "The default column format, if no other format has been defined.
3701 This variable can be set on the per-file basis by inserting a line
3703 #+COLUMNS: %25ITEM ....."
3704 :group 'org-properties
3705 :type 'string)
3707 (defcustom org-columns-ellipses ".."
3708 "The ellipses to be used when a field in column view is truncated.
3709 When this is the empty string, as many characters as possible are shown,
3710 but then there will be no visual indication that the field has been truncated.
3711 When this is a string of length N, the last N characters of a truncated
3712 field are replaced by this string. If the column is narrower than the
3713 ellipses string, only part of the ellipses string will be shown."
3714 :group 'org-properties
3715 :type 'string)
3717 (defconst org-global-properties-fixed
3718 '(("VISIBILITY_ALL" . "folded children content all")
3719 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3720 "List of property/value pairs that can be inherited by any entry.
3722 These are fixed values, for the preset properties. The user variable
3723 that can be used to add to this list is `org-global-properties'.
3725 The entries in this list are cons cells where the car is a property
3726 name and cdr is a string with the value. If the value represents
3727 multiple items like an \"_ALL\" property, separate the items by
3728 spaces.")
3730 (defcustom org-global-properties nil
3731 "List of property/value pairs that can be inherited by any entry.
3733 This list will be combined with the constant `org-global-properties-fixed'.
3735 The entries in this list are cons cells where the car is a property
3736 name and cdr is a string with the value.
3738 You can set buffer-local values for the same purpose in the variable
3739 `org-file-properties' this by adding lines like
3741 #+PROPERTY: NAME VALUE"
3742 :group 'org-properties
3743 :type '(repeat
3744 (cons (string :tag "Property")
3745 (string :tag "Value"))))
3747 (defvar-local org-file-properties nil
3748 "List of property/value pairs that can be inherited by any entry.
3749 Valid for the current buffer.
3750 This variable is populated from #+PROPERTY lines.")
3752 (defgroup org-agenda nil
3753 "Options concerning agenda views in Org mode."
3754 :tag "Org Agenda"
3755 :group 'org)
3757 (defvar-local org-category nil
3758 "Variable used by org files to set a category for agenda display.
3759 Such files should use a file variable to set it, for example
3761 # -*- mode: org; org-category: \"ELisp\"
3763 or contain a special line
3765 #+CATEGORY: ELisp
3767 If the file does not specify a category, then file's base name
3768 is used instead.")
3769 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3771 (defcustom org-agenda-files nil
3772 "The files to be used for agenda display.
3774 If an entry is a directory, all files in that directory that are matched
3775 by `org-agenda-file-regexp' will be part of the file list.
3777 If the value of the variable is not a list but a single file name, then
3778 the list of agenda files is actually stored and maintained in that file,
3779 one agenda file per line. In this file paths can be given relative to
3780 `org-directory'. Tilde expansion and environment variable substitution
3781 are also made.
3783 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3784 and removed with `\\[org-remove-file]'."
3785 :group 'org-agenda
3786 :type '(choice
3787 (repeat :tag "List of files and directories" file)
3788 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3790 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3791 "Regular expression to match files for `org-agenda-files'.
3792 If any element in the list in that variable contains a directory instead
3793 of a normal file, all files in that directory that are matched by this
3794 regular expression will be included."
3795 :group 'org-agenda
3796 :type 'regexp)
3798 (defcustom org-agenda-text-search-extra-files nil
3799 "List of extra files to be searched by text search commands.
3800 These files will be searched in addition to the agenda files by the
3801 commands `org-search-view' (`\\[org-agenda] s') \
3802 and `org-occur-in-agenda-files'.
3803 Note that these files will only be searched for text search commands,
3804 not for the other agenda views like todo lists, tag searches or the weekly
3805 agenda. This variable is intended to list notes and possibly archive files
3806 that should also be searched by these two commands.
3807 In fact, if the first element in the list is the symbol `agenda-archives',
3808 then all archive files of all agenda files will be added to the search
3809 scope."
3810 :group 'org-agenda
3811 :type '(set :greedy t
3812 (const :tag "Agenda Archives" agenda-archives)
3813 (repeat :inline t (file))))
3815 (defvaralias 'org-agenda-multi-occur-extra-files
3816 'org-agenda-text-search-extra-files)
3818 (defcustom org-agenda-skip-unavailable-files nil
3819 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3820 A nil value means to remove them, after a query, from the list."
3821 :group 'org-agenda
3822 :type 'boolean)
3824 (defcustom org-calendar-to-agenda-key [?c]
3825 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3826 The command `org-calendar-goto-agenda' will be bound to this key. The
3827 default is the character `c' because then `c' can be used to switch back and
3828 forth between agenda and calendar."
3829 :group 'org-agenda
3830 :type 'sexp)
3832 (defcustom org-calendar-insert-diary-entry-key [?i]
3833 "The key to be installed in `calendar-mode-map' for adding diary entries.
3834 This option is irrelevant until `org-agenda-diary-file' has been configured
3835 to point to an Org file. When that is the case, the command
3836 `org-agenda-diary-entry' will be bound to the key given here, by default
3837 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3838 if you want to continue doing this, you need to change this to a different
3839 key."
3840 :group 'org-agenda
3841 :type 'sexp)
3843 (defcustom org-agenda-diary-file 'diary-file
3844 "File to which to add new entries with the `i' key in agenda and calendar.
3845 When this is the symbol `diary-file', the functionality in the Emacs
3846 calendar will be used to add entries to the `diary-file'. But when this
3847 points to a file, `org-agenda-diary-entry' will be used instead."
3848 :group 'org-agenda
3849 :type '(choice
3850 (const :tag "The standard Emacs diary file" diary-file)
3851 (file :tag "Special Org file diary entries")))
3853 (eval-after-load "calendar"
3854 '(progn
3855 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3856 'org-calendar-goto-agenda)
3857 (add-hook 'calendar-mode-hook
3858 (lambda ()
3859 (unless (eq org-agenda-diary-file 'diary-file)
3860 (define-key calendar-mode-map
3861 org-calendar-insert-diary-entry-key
3862 'org-agenda-diary-entry))))))
3864 (defgroup org-latex nil
3865 "Options for embedding LaTeX code into Org mode."
3866 :tag "Org LaTeX"
3867 :group 'org)
3869 (defcustom org-format-latex-options
3870 '(:foreground default :background default :scale 1.0
3871 :html-foreground "Black" :html-background "Transparent"
3872 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3873 "Options for creating images from LaTeX fragments.
3874 This is a property list with the following properties:
3875 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3876 `default' means use the foreground of the default face.
3877 `auto' means use the foreground from the text face.
3878 :background the background color, or \"Transparent\".
3879 `default' means use the background of the default face.
3880 `auto' means use the background from the text face.
3881 :scale a scaling factor for the size of the images, to get more pixels
3882 :html-foreground, :html-background, :html-scale
3883 the same numbers for HTML export.
3884 :matchers a list indicating which matchers should be used to
3885 find LaTeX fragments. Valid members of this list are:
3886 \"begin\" find environments
3887 \"$1\" find single characters surrounded by $.$
3888 \"$\" find math expressions surrounded by $...$
3889 \"$$\" find math expressions surrounded by $$....$$
3890 \"\\(\" find math expressions surrounded by \\(...\\)
3891 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3892 :group 'org-latex
3893 :type 'plist)
3895 (defcustom org-format-latex-signal-error t
3896 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3897 When nil, just push out a message."
3898 :group 'org-latex
3899 :version "24.1"
3900 :type 'boolean)
3902 (defcustom org-latex-to-mathml-jar-file nil
3903 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3904 Use this to specify additional executable file say a jar file.
3906 When using MathToWeb as the converter, specify the full-path to
3907 your mathtoweb.jar file."
3908 :group 'org-latex
3909 :version "24.1"
3910 :type '(choice
3911 (const :tag "None" nil)
3912 (file :tag "JAR file" :must-match t)))
3914 (defcustom org-latex-to-mathml-convert-command nil
3915 "Command to convert LaTeX fragments to MathML.
3916 Replace format-specifiers in the command as noted below and use
3917 `shell-command' to convert LaTeX to MathML.
3918 %j: Executable file in fully expanded form as specified by
3919 `org-latex-to-mathml-jar-file'.
3920 %I: Input LaTeX file in fully expanded form.
3921 %i: The latex fragment to be converted.
3922 %o: Output MathML file.
3924 This command is used by `org-create-math-formula'.
3926 When using MathToWeb as the converter, set this option to
3927 \"java -jar %j -unicode -force -df %o %I\".
3929 When using LaTeXML set this option to
3930 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3931 :group 'org-latex
3932 :version "24.1"
3933 :type '(choice
3934 (const :tag "None" nil)
3935 (string :tag "\nShell command")))
3937 (defcustom org-preview-latex-default-process 'dvipng
3938 "The default process to convert LaTeX fragments to image files.
3939 All available processes and theirs documents can be found in
3940 `org-preview-latex-process-alist', which see."
3941 :group 'org-latex
3942 :version "26.1"
3943 :package-version '(Org . "9.0")
3944 :type 'symbol)
3946 (defcustom org-preview-latex-process-alist
3947 '((dvipng
3948 :programs ("latex" "dvipng")
3949 :description "dvi > png"
3950 :message "you need to install the programs: latex and dvipng."
3951 :image-input-type "dvi"
3952 :image-output-type "png"
3953 :image-size-adjust (1.0 . 1.0)
3954 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3955 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
3956 (dvisvgm
3957 :programs ("latex" "dvisvgm")
3958 :description "dvi > svg"
3959 :message "you need to install the programs: latex and dvisvgm."
3960 :use-xcolor t
3961 :image-input-type "dvi"
3962 :image-output-type "svg"
3963 :image-size-adjust (1.7 . 1.5)
3964 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
3965 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
3966 (imagemagick
3967 :programs ("latex" "convert")
3968 :description "pdf > png"
3969 :message "you need to install the programs: latex and imagemagick."
3970 :use-xcolor t
3971 :image-input-type "pdf"
3972 :image-output-type "png"
3973 :image-size-adjust (1.0 . 1.0)
3974 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
3975 :image-converter
3976 ("convert -density %D -trim -antialias %f -quality 100 %O")))
3977 "Definitions of external processes for LaTeX previewing.
3978 Org mode can use some external commands to generate TeX snippet's images for
3979 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
3980 `org-create-formula-image' how to call them.
3982 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
3983 PROPERTIES accepts the following attributes:
3985 :programs list of strings, required programs.
3986 :description string, describe the process.
3987 :message string, message it when required programs cannot be found.
3988 :image-input-type string, input file type of image converter (e.g., \"dvi\").
3989 :image-output-type string, output file type of image converter (e.g., \"png\").
3990 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
3991 deal with background and foreground color of image.
3992 Otherwise, dvipng style background and foreground color
3993 format are generated. You may then refer to them in
3994 command options with \"%F\" and \"%B\".
3995 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
3996 image size showed in buffer and the cdr element is for
3997 HTML file. This option is only useful for process
3998 developers, users should use variable
3999 `org-format-latex-options' instead.
4000 :post-clean list of strings, files matched are to be cleaned up once
4001 the image is generated. When nil, the files with \".dvi\",
4002 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4003 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4004 be cleaned up.
4005 :latex-header list of strings, the LaTeX header of the snippet file.
4006 When nil, the fallback value is used instead, which is
4007 controlled by `org-format-latex-header',
4008 `org-latex-default-packages-alist' and
4009 `org-latex-packages-alist', which see.
4010 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4011 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4012 replaced with values defined below.
4013 :image-converter list of image converter commands strings. Each of them is
4014 given to the shell and supports any of the following
4015 place-holders defined below.
4017 Place-holders used by `:image-converter' and `:latex-compiler':
4019 %f input file name
4020 %b base name of input file
4021 %o base directory of input file
4022 %O absolute output file name
4024 Place-holders only used by `:image-converter':
4026 %F foreground of image
4027 %B background of image
4028 %D dpi, which is used to adjust image size by some processing commands.
4029 %S the image size scale ratio, which is used to adjust image size by some
4030 processing commands."
4031 :group 'org-latex
4032 :version "26.1"
4033 :package-version '(Org . "9.0")
4034 :type '(alist :tag "LaTeX to image backends"
4035 :value-type (plist)))
4037 (defcustom org-preview-latex-image-directory "ltximg/"
4038 "Path to store latex preview images.
4039 A relative path here creates many directories relative to the
4040 processed org files paths. An absolute path puts all preview
4041 images at the same place."
4042 :group 'org-latex
4043 :version "26.1"
4044 :package-version '(Org . "9.0")
4045 :type 'string)
4047 (defun org-format-latex-mathml-available-p ()
4048 "Return t if `org-latex-to-mathml-convert-command' is usable."
4049 (save-match-data
4050 (when (and (boundp 'org-latex-to-mathml-convert-command)
4051 org-latex-to-mathml-convert-command)
4052 (let ((executable (car (split-string
4053 org-latex-to-mathml-convert-command))))
4054 (when (executable-find executable)
4055 (if (string-match
4056 "%j" org-latex-to-mathml-convert-command)
4057 (file-readable-p org-latex-to-mathml-jar-file)
4058 t))))))
4060 (defcustom org-format-latex-header "\\documentclass{article}
4061 \\usepackage[usenames]{color}
4062 \[PACKAGES]
4063 \[DEFAULT-PACKAGES]
4064 \\pagestyle{empty} % do not remove
4065 % The settings below are copied from fullpage.sty
4066 \\setlength{\\textwidth}{\\paperwidth}
4067 \\addtolength{\\textwidth}{-3cm}
4068 \\setlength{\\oddsidemargin}{1.5cm}
4069 \\addtolength{\\oddsidemargin}{-2.54cm}
4070 \\setlength{\\evensidemargin}{\\oddsidemargin}
4071 \\setlength{\\textheight}{\\paperheight}
4072 \\addtolength{\\textheight}{-\\headheight}
4073 \\addtolength{\\textheight}{-\\headsep}
4074 \\addtolength{\\textheight}{-\\footskip}
4075 \\addtolength{\\textheight}{-3cm}
4076 \\setlength{\\topmargin}{1.5cm}
4077 \\addtolength{\\topmargin}{-2.54cm}"
4078 "The document header used for processing LaTeX fragments.
4079 It is imperative that this header make sure that no page number
4080 appears on the page. The package defined in the variables
4081 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4082 will either replace the placeholder \"[PACKAGES]\" in this
4083 header, or they will be appended."
4084 :group 'org-latex
4085 :type 'string)
4087 (defun org-set-packages-alist (var val)
4088 "Set the packages alist and make sure it has 3 elements per entry."
4089 (set var (mapcar (lambda (x)
4090 (if (and (consp x) (= (length x) 2))
4091 (list (car x) (nth 1 x) t)
4093 val)))
4095 (defun org-get-packages-alist (var)
4096 "Get the packages alist and make sure it has 3 elements per entry."
4097 (mapcar (lambda (x)
4098 (if (and (consp x) (= (length x) 2))
4099 (list (car x) (nth 1 x) t)
4101 (default-value var)))
4103 (defcustom org-latex-default-packages-alist
4104 '(("AUTO" "inputenc" t ("pdflatex"))
4105 ("T1" "fontenc" t ("pdflatex"))
4106 ("" "graphicx" t)
4107 ("" "grffile" t)
4108 ("" "longtable" nil)
4109 ("" "wrapfig" nil)
4110 ("" "rotating" nil)
4111 ("normalem" "ulem" t)
4112 ("" "amsmath" t)
4113 ("" "textcomp" t)
4114 ("" "amssymb" t)
4115 ("" "capt-of" nil)
4116 ("" "hyperref" nil))
4117 "Alist of default packages to be inserted in the header.
4119 Change this only if one of the packages here causes an
4120 incompatibility with another package you are using.
4122 The packages in this list are needed by one part or another of
4123 Org mode to function properly:
4125 - inputenc, fontenc: for basic font and character selection
4126 - graphicx: for including images
4127 - grffile: allow periods and spaces in graphics file names
4128 - longtable: For multipage tables
4129 - wrapfig: for figure placement
4130 - rotating: for sideways figures and tables
4131 - ulem: for underline and strike-through
4132 - amsmath: for subscript and superscript and math environments
4133 - textcomp, amssymb: for various symbols used
4134 for interpreting the entities in `org-entities'. You can skip
4135 some of these packages if you don't use any of their symbols.
4136 - capt-of: for captions outside of floats
4137 - hyperref: for cross references
4139 Therefore you should not modify this variable unless you know
4140 what you are doing. The one reason to change it anyway is that
4141 you might be loading some other package that conflicts with one
4142 of the default packages. Each element is either a cell or
4143 a string.
4145 A cell is of the format
4147 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4149 If SNIPPET-FLAG is non-nil, the package also needs to be included
4150 when compiling LaTeX snippets into images for inclusion into
4151 non-LaTeX output. COMPILERS is a list of compilers that should
4152 include the package, see `org-latex-compiler'. If the document
4153 compiler is not in the list, and the list is non-nil, the package
4154 will not be inserted in the final document.
4156 A string will be inserted as-is in the header of the document."
4157 :group 'org-latex
4158 :group 'org-export-latex
4159 :set 'org-set-packages-alist
4160 :get 'org-get-packages-alist
4161 :version "26.1"
4162 :package-version '(Org . "8.3")
4163 :type '(repeat
4164 (choice
4165 (list :tag "options/package pair"
4166 (string :tag "options")
4167 (string :tag "package")
4168 (boolean :tag "Snippet"))
4169 (string :tag "A line of LaTeX"))))
4171 (defcustom org-latex-packages-alist nil
4172 "Alist of packages to be inserted in every LaTeX header.
4174 These will be inserted after `org-latex-default-packages-alist'.
4175 Each element is either a cell or a string.
4177 A cell is of the format:
4179 (\"options\" \"package\" SNIPPET-FLAG)
4181 SNIPPET-FLAG, when non-nil, indicates that this package is also
4182 needed when turning LaTeX snippets into images for inclusion into
4183 non-LaTeX output.
4185 A string will be inserted as-is in the header of the document.
4187 Make sure that you only list packages here which:
4189 - you want in every file;
4190 - do not conflict with the setup in `org-format-latex-header';
4191 - do not conflict with the default packages in
4192 `org-latex-default-packages-alist'."
4193 :group 'org-latex
4194 :group 'org-export-latex
4195 :set 'org-set-packages-alist
4196 :get 'org-get-packages-alist
4197 :type '(repeat
4198 (choice
4199 (list :tag "options/package pair"
4200 (string :tag "options")
4201 (string :tag "package")
4202 (boolean :tag "Snippet"))
4203 (string :tag "A line of LaTeX"))))
4205 (defgroup org-appearance nil
4206 "Settings for Org mode appearance."
4207 :tag "Org Appearance"
4208 :group 'org)
4210 (defcustom org-level-color-stars-only nil
4211 "Non-nil means fontify only the stars in each headline.
4212 When nil, the entire headline is fontified.
4213 Changing it requires restart of `font-lock-mode' to become effective
4214 also in regions already fontified."
4215 :group 'org-appearance
4216 :type 'boolean)
4218 (defcustom org-hide-leading-stars nil
4219 "Non-nil means hide the first N-1 stars in a headline.
4220 This works by using the face `org-hide' for these stars. This
4221 face is white for a light background, and black for a dark
4222 background. You may have to customize the face `org-hide' to
4223 make this work.
4224 Changing it requires restart of `font-lock-mode' to become effective
4225 also in regions already fontified.
4226 You may also set this on a per-file basis by adding one of the following
4227 lines to the buffer:
4229 #+STARTUP: hidestars
4230 #+STARTUP: showstars"
4231 :group 'org-appearance
4232 :type 'boolean)
4234 (defcustom org-hidden-keywords nil
4235 "List of symbols corresponding to keywords to be hidden the org buffer.
4236 For example, a value \\='(title) for this list will make the document's title
4237 appear in the buffer without the initial #+TITLE: keyword."
4238 :group 'org-appearance
4239 :version "24.1"
4240 :type '(set (const :tag "#+AUTHOR" author)
4241 (const :tag "#+DATE" date)
4242 (const :tag "#+EMAIL" email)
4243 (const :tag "#+TITLE" title)))
4245 (defcustom org-custom-properties nil
4246 "List of properties (as strings) with a special meaning.
4247 The default use of these custom properties is to let the user
4248 hide them with `org-toggle-custom-properties-visibility'."
4249 :group 'org-properties
4250 :group 'org-appearance
4251 :version "24.3"
4252 :type '(repeat (string :tag "Property Name")))
4254 (defcustom org-fontify-done-headline nil
4255 "Non-nil means change the face of a headline if it is marked DONE.
4256 Normally, only the TODO/DONE keyword indicates the state of a headline.
4257 When this is non-nil, the headline after the keyword is set to the
4258 `org-headline-done' as an additional indication."
4259 :group 'org-appearance
4260 :type 'boolean)
4262 (defcustom org-fontify-emphasized-text t
4263 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4264 Changing this variable requires a restart of Emacs to take effect."
4265 :group 'org-appearance
4266 :type 'boolean)
4268 (defcustom org-fontify-whole-heading-line nil
4269 "Non-nil means fontify the whole line for headings.
4270 This is useful when setting a background color for the
4271 org-level-* faces."
4272 :group 'org-appearance
4273 :type 'boolean)
4275 (defcustom org-highlight-latex-and-related nil
4276 "Non-nil means highlight LaTeX related syntax in the buffer.
4277 When non nil, the value should be a list containing any of the
4278 following symbols:
4279 `latex' Highlight LaTeX snippets and environments.
4280 `script' Highlight subscript and superscript.
4281 `entities' Highlight entities."
4282 :group 'org-appearance
4283 :version "24.4"
4284 :package-version '(Org . "8.0")
4285 :type '(choice
4286 (const :tag "No highlighting" nil)
4287 (set :greedy t :tag "Highlight"
4288 (const :tag "LaTeX snippets and environments" latex)
4289 (const :tag "Subscript and superscript" script)
4290 (const :tag "Entities" entities))))
4292 (defcustom org-hide-emphasis-markers nil
4293 "Non-nil mean font-lock should hide the emphasis marker characters."
4294 :group 'org-appearance
4295 :type 'boolean)
4297 (defcustom org-hide-macro-markers nil
4298 "Non-nil mean font-lock should hide the brackets marking macro calls."
4299 :group 'org-appearance
4300 :type 'boolean)
4302 (defcustom org-pretty-entities nil
4303 "Non-nil means show entities as UTF8 characters.
4304 When nil, the \\name form remains in the buffer."
4305 :group 'org-appearance
4306 :version "24.1"
4307 :type 'boolean)
4309 (defcustom org-pretty-entities-include-sub-superscripts t
4310 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4311 :group 'org-appearance
4312 :version "24.1"
4313 :type 'boolean)
4315 (defvar org-emph-re nil
4316 "Regular expression for matching emphasis.
4317 After a match, the match groups contain these elements:
4318 0 The match of the full regular expression, including the characters
4319 before and after the proper match
4320 1 The character before the proper match, or empty at beginning of line
4321 2 The proper match, including the leading and trailing markers
4322 3 The leading marker like * or /, indicating the type of highlighting
4323 4 The text between the emphasis markers, not including the markers
4324 5 The character after the match, empty at the end of a line")
4326 (defvar org-verbatim-re nil
4327 "Regular expression for matching verbatim text.")
4329 (defvar org-emphasis-regexp-components) ; defined just below
4330 (defvar org-emphasis-alist) ; defined just below
4331 (defun org-set-emph-re (var val)
4332 "Set variable and compute the emphasis regular expression."
4333 (set var val)
4334 (when (and (boundp 'org-emphasis-alist)
4335 (boundp 'org-emphasis-regexp-components)
4336 org-emphasis-alist org-emphasis-regexp-components)
4337 (pcase-let*
4338 ((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
4339 (body (if (<= nl 0) body
4340 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
4341 (template
4342 (format (concat "\\([%s]\\|^\\)" ;before markers
4343 "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
4344 "\\([%s]\\|$\\)") ;after markers
4345 pre border border body border post)))
4346 (setq org-emph-re (format template "*/_+"))
4347 (setq org-verbatim-re (format template "=~")))))
4349 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4350 ;; set this option proved cumbersome. See this message/thread:
4351 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4352 (defvar org-emphasis-regexp-components
4353 '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
4354 "Components used to build the regular expression for emphasis.
4355 This is a list with five entries. Terminology: In an emphasis string
4356 like \" *strong word* \", we call the initial space PREMATCH, the final
4357 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4358 and \"trong wor\" is the body. The different components in this variable
4359 specify what is allowed/forbidden in each part:
4361 pre Chars allowed as prematch. Beginning of line will be allowed too.
4362 post Chars allowed as postmatch. End of line will be allowed too.
4363 border The chars *forbidden* as border characters.
4364 body-regexp A regexp like \".\" to match a body character. Don't use
4365 non-shy groups here, and don't allow newline here.
4366 newline The maximum number of newlines allowed in an emphasis exp.
4368 You need to reload Org or to restart Emacs after setting this.")
4370 (defcustom org-emphasis-alist
4371 '(("*" bold)
4372 ("/" italic)
4373 ("_" underline)
4374 ("=" org-verbatim verbatim)
4375 ("~" org-code verbatim)
4376 ("+" (:strike-through t)))
4377 "Alist of characters and faces to emphasize text.
4378 Text starting and ending with a special character will be emphasized,
4379 for example *bold*, _underlined_ and /italic/. This variable sets the
4380 marker characters and the face to be used by font-lock for highlighting
4381 in Org buffers.
4383 You need to reload Org or to restart Emacs after customizing this."
4384 :group 'org-appearance
4385 :set 'org-set-emph-re
4386 :version "24.4"
4387 :package-version '(Org . "8.0")
4388 :type '(repeat
4389 (list
4390 (string :tag "Marker character")
4391 (choice
4392 (face :tag "Font-lock-face")
4393 (plist :tag "Face property list"))
4394 (option (const verbatim)))))
4396 (defvar org-protecting-blocks '("src" "example" "export")
4397 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4398 This is needed for font-lock setup.")
4400 ;;; Functions and variables from their packages
4401 ;; Declared here to avoid compiler warnings
4402 (defvar mark-active)
4404 ;; Various packages
4405 (declare-function calc-eval "calc" (str &optional separator &rest args))
4406 (declare-function calendar-forward-day "cal-move" (arg))
4407 (declare-function calendar-goto-date "cal-move" (date))
4408 (declare-function calendar-goto-today "cal-move" ())
4409 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4410 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4411 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4412 (declare-function cdlatex-tab "ext:cdlatex" ())
4413 (declare-function dired-get-filename
4414 "dired"
4415 (&optional localp no-error-if-not-filep))
4416 (declare-function iswitchb-read-buffer
4417 "iswitchb"
4418 (prompt &optional
4419 default require-match _predicate start matches-set))
4420 (declare-function org-agenda-change-all-lines
4421 "org-agenda"
4422 (newhead hdmarker &optional fixface just-this))
4423 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4424 "org-agenda"
4425 (&optional end))
4426 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4427 (declare-function org-agenda-format-item
4428 "org-agenda"
4429 (extra txt &optional level category tags dotime
4430 remove-re habitp))
4431 (declare-function org-agenda-maybe-redo "org-agenda" ())
4432 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4433 (declare-function org-agenda-save-markers-for-cut-and-paste
4434 "org-agenda"
4435 (beg end))
4436 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4437 (declare-function org-agenda-skip "org-agenda" ())
4438 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4439 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4440 (declare-function org-indent-mode "org-indent" (&optional arg))
4441 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4442 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4443 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4444 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4445 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4446 (declare-function parse-time-string "parse-time" (string))
4447 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4449 (defvar align-mode-rules-list)
4450 (defvar calc-embedded-close-formula)
4451 (defvar calc-embedded-open-formula)
4452 (defvar calc-embedded-open-mode)
4453 (defvar font-lock-unfontify-region-function)
4454 (defvar iswitchb-temp-buflist)
4455 (defvar org-agenda-tags-todo-honor-ignore-options)
4456 (defvar remember-data-file)
4457 (defvar texmathp-why)
4459 ;;;###autoload
4460 (defun turn-on-orgtbl ()
4461 "Unconditionally turn on `orgtbl-mode'."
4462 (require 'org-table)
4463 (orgtbl-mode 1))
4465 (defun org-at-table-p (&optional table-type)
4466 "Non-nil if the cursor is inside an Org table.
4467 If TABLE-TYPE is non-nil, also check for table.el-type tables."
4468 (and (org-match-line (if table-type "[ \t]*[|+]" "[ \t]*|"))
4469 (or (not (derived-mode-p 'org-mode))
4470 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4471 (and e (or table-type
4472 (eq 'org (org-element-property :type e))))))))
4474 (defun org-at-table.el-p ()
4475 "Non-nil when point is at a table.el table."
4476 (and (org-match-line "[ \t]*[|+]")
4477 (let ((element (org-element-at-point)))
4478 (and (eq (org-element-type element) 'table)
4479 (eq (org-element-property :type element) 'table.el)))))
4481 (defun org-at-table-hline-p ()
4482 "Non-nil when point is inside a hline in a table.
4483 Assume point is already in a table."
4484 (org-match-line org-table-hline-regexp))
4486 (defun org-table-map-tables (function &optional quietly)
4487 "Apply FUNCTION to the start of all tables in the buffer."
4488 (org-with-wide-buffer
4489 (goto-char (point-min))
4490 (while (re-search-forward org-table-any-line-regexp nil t)
4491 (unless quietly
4492 (message "Mapping tables: %d%%"
4493 (floor (* 100.0 (point)) (buffer-size))))
4494 (beginning-of-line 1)
4495 (when (and (looking-at org-table-line-regexp)
4496 ;; Exclude tables in src/example/verbatim/clocktable blocks
4497 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4498 (save-excursion (funcall function))
4499 (or (looking-at org-table-line-regexp)
4500 (forward-char 1)))
4501 (re-search-forward org-table-any-border-regexp nil 1)))
4502 (unless quietly (message "Mapping tables: done")))
4504 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4505 (declare-function org-clock-update-mode-line "org-clock" ())
4506 (declare-function org-resolve-clocks "org-clock"
4507 (&optional also-non-dangling-p prompt last-valid))
4509 (defun org-at-TBLFM-p (&optional pos)
4510 "Non-nil when point (or POS) is in #+TBLFM line."
4511 (save-excursion
4512 (goto-char (or pos (point)))
4513 (beginning-of-line)
4514 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4515 (eq (org-element-type (org-element-at-point)) 'table))))
4517 (defvar org-clock-start-time)
4518 (defvar org-clock-marker (make-marker)
4519 "Marker recording the last clock-in.")
4520 (defvar org-clock-hd-marker (make-marker)
4521 "Marker recording the last clock-in, but the headline position.")
4522 (defvar org-clock-heading ""
4523 "The heading of the current clock entry.")
4524 (defun org-clock-is-active ()
4525 "Return the buffer where the clock is currently running.
4526 Return nil if no clock is running."
4527 (marker-buffer org-clock-marker))
4529 (defun org-check-running-clock ()
4530 "Check if the current buffer contains the running clock.
4531 If yes, offer to stop it and to save the buffer with the changes."
4532 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4533 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4534 (buffer-name))))
4535 (org-clock-out)
4536 (when (y-or-n-p "Save changed buffer?")
4537 (save-buffer))))
4539 (defun org-clocktable-try-shift (dir n)
4540 "Check if this line starts a clock table, if yes, shift the time block."
4541 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4542 (org-clocktable-shift dir n)))
4544 ;;;###autoload
4545 (defun org-clock-persistence-insinuate ()
4546 "Set up hooks for clock persistence."
4547 (require 'org-clock)
4548 (add-hook 'org-mode-hook 'org-clock-load)
4549 (add-hook 'kill-emacs-hook 'org-clock-save))
4551 (defgroup org-archive nil
4552 "Options concerning archiving in Org mode."
4553 :tag "Org Archive"
4554 :group 'org-structure)
4556 (defcustom org-archive-location "%s_archive::"
4557 "The location where subtrees should be archived.
4559 The value of this variable is a string, consisting of two parts,
4560 separated by a double-colon. The first part is a filename and
4561 the second part is a headline.
4563 When the filename is omitted, archiving happens in the same file.
4564 %s in the filename will be replaced by the current file
4565 name (without the directory part). Archiving to a different file
4566 is useful to keep archived entries from contributing to the
4567 Org Agenda.
4569 The archived entries will be filed as subtrees of the specified
4570 headline. When the headline is omitted, the subtrees are simply
4571 filed away at the end of the file, as top-level entries. Also in
4572 the heading you can use %s to represent the file name, this can be
4573 useful when using the same archive for a number of different files.
4575 Here are a few examples:
4576 \"%s_archive::\"
4577 If the current file is Projects.org, archive in file
4578 Projects.org_archive, as top-level trees. This is the default.
4580 \"::* Archived Tasks\"
4581 Archive in the current file, under the top-level headline
4582 \"* Archived Tasks\".
4584 \"~/org/archive.org::\"
4585 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4587 \"~/org/archive.org::* From %s\"
4588 Archive in file ~/org/archive.org (absolute path), under headlines
4589 \"From FILENAME\" where file name is the current file name.
4591 \"~/org/datetree.org::datetree/* Finished Tasks\"
4592 The \"datetree/\" string is special, signifying to archive
4593 items to the datetree. Items are placed in either the CLOSED
4594 date of the item, or the current date if there is no CLOSED date.
4595 The heading will be a subentry to the current date. There doesn't
4596 need to be a heading, but there always needs to be a slash after
4597 datetree. For example, to store archived items directly in the
4598 datetree, use \"~/org/datetree.org::datetree/\".
4600 \"basement::** Finished Tasks\"
4601 Archive in file ./basement (relative path), as level 3 trees
4602 below the level 2 heading \"** Finished Tasks\".
4604 You may set this option on a per-file basis by adding to the buffer a
4605 line like
4607 #+ARCHIVE: basement::** Finished Tasks
4609 You may also define it locally for a subtree by setting an ARCHIVE property
4610 in the entry. If such a property is found in an entry, or anywhere up
4611 the hierarchy, it will be used."
4612 :group 'org-archive
4613 :type 'string)
4615 (defcustom org-agenda-skip-archived-trees t
4616 "Non-nil means the agenda will skip any items located in archived trees.
4617 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4618 variable is no longer recommended, you should leave it at the value t.
4619 Instead, use the key `v' to cycle the archives-mode in the agenda."
4620 :group 'org-archive
4621 :group 'org-agenda-skip
4622 :type 'boolean)
4624 (defcustom org-columns-skip-archived-trees t
4625 "Non-nil means ignore archived trees when creating column view."
4626 :group 'org-archive
4627 :group 'org-properties
4628 :type 'boolean)
4630 (defcustom org-cycle-open-archived-trees nil
4631 "Non-nil means `org-cycle' will open archived trees.
4632 An archived tree is a tree marked with the tag ARCHIVE.
4633 When nil, archived trees will stay folded. You can still open them with
4634 normal outline commands like `show-all', but not with the cycling commands."
4635 :group 'org-archive
4636 :group 'org-cycle
4637 :type 'boolean)
4639 (defcustom org-sparse-tree-open-archived-trees nil
4640 "Non-nil means sparse tree construction shows matches in archived trees.
4641 When nil, matches in these trees are highlighted, but the trees are kept in
4642 collapsed state."
4643 :group 'org-archive
4644 :group 'org-sparse-trees
4645 :type 'boolean)
4647 (defcustom org-sparse-tree-default-date-type nil
4648 "The default date type when building a sparse tree.
4649 When this is nil, a date is a scheduled or a deadline timestamp.
4650 Otherwise, these types are allowed:
4652 all: all timestamps
4653 active: only active timestamps (<...>)
4654 inactive: only inactive timestamps ([...])
4655 scheduled: only scheduled timestamps
4656 deadline: only deadline timestamps"
4657 :type '(choice (const :tag "Scheduled or deadline" nil)
4658 (const :tag "All timestamps" all)
4659 (const :tag "Only active timestamps" active)
4660 (const :tag "Only inactive timestamps" inactive)
4661 (const :tag "Only scheduled timestamps" scheduled)
4662 (const :tag "Only deadline timestamps" deadline)
4663 (const :tag "Only closed timestamps" closed))
4664 :version "26.1"
4665 :package-version '(Org . "8.3")
4666 :group 'org-sparse-trees)
4668 (defun org-cycle-hide-archived-subtrees (state)
4669 "Re-hide all archived subtrees after a visibility state change.
4670 STATE should be one of the symbols listed in the docstring of
4671 `org-cycle-hook'."
4672 (when (and (not org-cycle-open-archived-trees)
4673 (not (memq state '(overview folded))))
4674 (save-excursion
4675 (let* ((globalp (memq state '(contents all)))
4676 (beg (if globalp (point-min) (point)))
4677 (end (if globalp (point-max) (org-end-of-subtree t))))
4678 (org-hide-archived-subtrees beg end)
4679 (goto-char beg)
4680 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4681 (message "%s" (substitute-command-keys
4682 "Subtree is archived and stays closed. Use \
4683 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4685 (defun org-force-cycle-archived ()
4686 "Cycle subtree even if it is archived."
4687 (interactive)
4688 (setq this-command 'org-cycle)
4689 (let ((org-cycle-open-archived-trees t))
4690 (call-interactively 'org-cycle)))
4692 (defun org-hide-archived-subtrees (beg end)
4693 "Re-hide all archived subtrees after a visibility state change."
4694 (org-with-wide-buffer
4695 (let ((case-fold-search nil)
4696 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4697 (goto-char beg)
4698 ;; Include headline point is currently on.
4699 (beginning-of-line)
4700 (while (and (< (point) end) (re-search-forward re end t))
4701 (when (member org-archive-tag (org-get-tags))
4702 (org-flag-subtree t)
4703 (org-end-of-subtree t))))))
4705 (declare-function outline-end-of-heading "outline" ())
4706 (declare-function outline-flag-region "outline" (from to flag))
4707 (defun org-flag-subtree (flag)
4708 (save-excursion
4709 (org-back-to-heading t)
4710 (outline-end-of-heading)
4711 (outline-flag-region (point)
4712 (progn (org-end-of-subtree t) (point))
4713 flag)))
4715 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4717 ;; Declare Column View Code
4719 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4720 (declare-function org-columns-compute "org-colview" (property))
4722 ;; Declare ID code
4724 (declare-function org-id-store-link "org-id")
4725 (declare-function org-id-locations-load "org-id")
4726 (declare-function org-id-locations-save "org-id")
4727 (defvar org-id-track-globally)
4729 ;;; Variables for pre-computed regular expressions, all buffer local
4731 (defvar-local org-todo-regexp nil
4732 "Matches any of the TODO state keywords.
4733 Since TODO keywords are case-sensitive, `case-fold-search' is
4734 expected to be bound to nil when matching against this regexp.")
4736 (defvar-local org-not-done-regexp nil
4737 "Matches any of the TODO state keywords except the last one.
4738 Since TODO keywords are case-sensitive, `case-fold-search' is
4739 expected to be bound to nil when matching against this regexp.")
4741 (defvar-local org-not-done-heading-regexp nil
4742 "Matches a TODO headline that is not done.
4743 Since TODO keywords are case-sensitive, `case-fold-search' is
4744 expected to be bound to nil when matching against this regexp.")
4746 (defvar-local org-todo-line-regexp nil
4747 "Matches a headline and puts TODO state into group 2 if present.
4748 Since TODO keywords are case-sensitive, `case-fold-search' is
4749 expected to be bound to nil when matching against this regexp.")
4751 (defvar-local org-complex-heading-regexp nil
4752 "Matches a headline and puts everything into groups:
4754 group 1: Stars
4755 group 2: The TODO keyword, maybe
4756 group 3: Priority cookie
4757 group 4: True headline
4758 group 5: Tags
4760 Since TODO keywords are case-sensitive, `case-fold-search' is
4761 expected to be bound to nil when matching against this regexp.")
4763 (defvar-local org-complex-heading-regexp-format nil
4764 "Printf format to make regexp to match an exact headline.
4765 This regexp will match the headline of any node which has the
4766 exact headline text that is put into the format, but may have any
4767 TODO state, priority and tags.")
4769 (defvar-local org-todo-line-tags-regexp nil
4770 "Matches a headline and puts TODO state into group 2 if present.
4771 Also put tags into group 4 if tags are present.")
4773 (defconst org-plain-time-of-day-regexp
4774 (concat
4775 "\\(\\<[012]?[0-9]"
4776 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4777 "\\(--?"
4778 "\\(\\<[012]?[0-9]"
4779 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4780 "\\)?")
4781 "Regular expression to match a plain time or time range.
4782 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4783 groups carry important information:
4784 0 the full match
4785 1 the first time, range or not
4786 8 the second time, if it is a range.")
4788 (defconst org-plain-time-extension-regexp
4789 (concat
4790 "\\(\\<[012]?[0-9]"
4791 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4792 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4793 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4794 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4795 groups carry important information:
4796 0 the full match
4797 7 hours of duration
4798 9 minutes of duration")
4800 (defconst org-stamp-time-of-day-regexp
4801 (concat
4802 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4803 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4804 "\\(--?"
4805 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4806 "Regular expression to match a timestamp time or time range.
4807 After a match, the following groups carry important information:
4808 0 the full match
4809 1 date plus weekday, for back referencing to make sure both times are on the same day
4810 2 the first time, range or not
4811 4 the second time, if it is a range.")
4813 (defconst org-startup-options
4814 '(("fold" org-startup-folded t)
4815 ("overview" org-startup-folded t)
4816 ("nofold" org-startup-folded nil)
4817 ("showall" org-startup-folded nil)
4818 ("showeverything" org-startup-folded showeverything)
4819 ("content" org-startup-folded content)
4820 ("indent" org-startup-indented t)
4821 ("noindent" org-startup-indented nil)
4822 ("hidestars" org-hide-leading-stars t)
4823 ("showstars" org-hide-leading-stars nil)
4824 ("odd" org-odd-levels-only t)
4825 ("oddeven" org-odd-levels-only nil)
4826 ("align" org-startup-align-all-tables t)
4827 ("noalign" org-startup-align-all-tables nil)
4828 ("shrink" org-startup-shrink-all-tables t)
4829 ("inlineimages" org-startup-with-inline-images t)
4830 ("noinlineimages" org-startup-with-inline-images nil)
4831 ("latexpreview" org-startup-with-latex-preview t)
4832 ("nolatexpreview" org-startup-with-latex-preview nil)
4833 ("customtime" org-display-custom-times t)
4834 ("logdone" org-log-done time)
4835 ("lognotedone" org-log-done note)
4836 ("nologdone" org-log-done nil)
4837 ("lognoteclock-out" org-log-note-clock-out t)
4838 ("nolognoteclock-out" org-log-note-clock-out nil)
4839 ("logrepeat" org-log-repeat state)
4840 ("lognoterepeat" org-log-repeat note)
4841 ("logdrawer" org-log-into-drawer t)
4842 ("nologdrawer" org-log-into-drawer nil)
4843 ("logstatesreversed" org-log-states-order-reversed t)
4844 ("nologstatesreversed" org-log-states-order-reversed nil)
4845 ("nologrepeat" org-log-repeat nil)
4846 ("logreschedule" org-log-reschedule time)
4847 ("lognotereschedule" org-log-reschedule note)
4848 ("nologreschedule" org-log-reschedule nil)
4849 ("logredeadline" org-log-redeadline time)
4850 ("lognoteredeadline" org-log-redeadline note)
4851 ("nologredeadline" org-log-redeadline nil)
4852 ("logrefile" org-log-refile time)
4853 ("lognoterefile" org-log-refile note)
4854 ("nologrefile" org-log-refile nil)
4855 ("fninline" org-footnote-define-inline t)
4856 ("nofninline" org-footnote-define-inline nil)
4857 ("fnlocal" org-footnote-section nil)
4858 ("fnauto" org-footnote-auto-label t)
4859 ("fnprompt" org-footnote-auto-label nil)
4860 ("fnconfirm" org-footnote-auto-label confirm)
4861 ("fnplain" org-footnote-auto-label plain)
4862 ("fnadjust" org-footnote-auto-adjust t)
4863 ("nofnadjust" org-footnote-auto-adjust nil)
4864 ("constcgs" constants-unit-system cgs)
4865 ("constSI" constants-unit-system SI)
4866 ("noptag" org-tag-persistent-alist nil)
4867 ("hideblocks" org-hide-block-startup t)
4868 ("nohideblocks" org-hide-block-startup nil)
4869 ("beamer" org-startup-with-beamer-mode t)
4870 ("entitiespretty" org-pretty-entities t)
4871 ("entitiesplain" org-pretty-entities nil))
4872 "Variable associated with STARTUP options for org-mode.
4873 Each element is a list of three items: the startup options (as written
4874 in the #+STARTUP line), the corresponding variable, and the value to set
4875 this variable to if the option is found. An optional forth element PUSH
4876 means to push this value onto the list in the variable.")
4878 (defcustom org-group-tags t
4879 "When non-nil (the default), use group tags.
4880 This can be turned on/off through `org-toggle-tags-groups'."
4881 :group 'org-tags
4882 :group 'org-startup
4883 :type 'boolean)
4885 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4887 (defun org-toggle-tags-groups ()
4888 "Toggle support for group tags.
4889 Support for group tags is controlled by the option
4890 `org-group-tags', which is non-nil by default."
4891 (interactive)
4892 (setq org-group-tags (not org-group-tags))
4893 (cond ((and (derived-mode-p 'org-agenda-mode)
4894 org-group-tags)
4895 (org-agenda-redo))
4896 ((derived-mode-p 'org-mode)
4897 (let ((org-inhibit-startup t)) (org-mode))))
4898 (message "Groups tags support has been turned %s"
4899 (if org-group-tags "on" "off")))
4901 (defun org-set-regexps-and-options (&optional tags-only)
4902 "Precompute regular expressions used in the current buffer.
4903 When optional argument TAGS-ONLY is non-nil, only compute tags
4904 related expressions."
4905 (when (derived-mode-p 'org-mode)
4906 (let ((alist (org--setup-collect-keywords
4907 (org-make-options-regexp
4908 (append '("FILETAGS" "TAGS" "SETUPFILE")
4909 (and (not tags-only)
4910 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4911 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4912 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4913 ;; Startup options. Get this early since it does change
4914 ;; behavior for other options (e.g., tags).
4915 (let ((startup (cdr (assq 'startup alist))))
4916 (dolist (option startup)
4917 (let ((entry (assoc-string option org-startup-options t)))
4918 (when entry
4919 (let ((var (nth 1 entry))
4920 (val (nth 2 entry)))
4921 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4922 (unless (listp (symbol-value var))
4923 (set (make-local-variable var) nil))
4924 (add-to-list var val)))))))
4925 (setq-local org-file-tags
4926 (mapcar #'org-add-prop-inherited
4927 (cdr (assq 'filetags alist))))
4928 (setq org-current-tag-alist
4929 (append org-tag-persistent-alist
4930 (let ((tags (cdr (assq 'tags alist))))
4931 (if tags (org-tag-string-to-alist tags)
4932 org-tag-alist))))
4933 (setq org-tag-groups-alist
4934 (org-tag-alist-to-groups org-current-tag-alist))
4935 (unless tags-only
4936 ;; File properties.
4937 (setq-local org-file-properties (cdr (assq 'property alist)))
4938 ;; Archive location.
4939 (let ((archive (cdr (assq 'archive alist))))
4940 (when archive (setq-local org-archive-location archive)))
4941 ;; Category.
4942 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4943 (when cat
4944 (setq-local org-category (intern cat))
4945 (setq-local org-file-properties
4946 (org--update-property-plist
4947 "CATEGORY" cat org-file-properties))))
4948 ;; Columns.
4949 (let ((column (cdr (assq 'columns alist))))
4950 (when column (setq-local org-columns-default-format column)))
4951 ;; Constants.
4952 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4953 ;; Link abbreviations.
4954 (let ((links (cdr (assq 'link alist))))
4955 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4956 ;; Priorities.
4957 (let ((priorities (cdr (assq 'priorities alist))))
4958 (when priorities
4959 (setq-local org-highest-priority (nth 0 priorities))
4960 (setq-local org-lowest-priority (nth 1 priorities))
4961 (setq-local org-default-priority (nth 2 priorities))))
4962 ;; Scripts.
4963 (let ((scripts (assq 'scripts alist)))
4964 (when scripts
4965 (setq-local org-use-sub-superscripts (cdr scripts))))
4966 ;; TODO keywords.
4967 (setq-local org-todo-kwd-alist nil)
4968 (setq-local org-todo-key-alist nil)
4969 (setq-local org-todo-key-trigger nil)
4970 (setq-local org-todo-keywords-1 nil)
4971 (setq-local org-done-keywords nil)
4972 (setq-local org-todo-heads nil)
4973 (setq-local org-todo-sets nil)
4974 (setq-local org-todo-log-states nil)
4975 (let ((todo-sequences
4976 (or (nreverse (cdr (assq 'todo alist)))
4977 (let ((d (default-value 'org-todo-keywords)))
4978 (if (not (stringp (car d))) d
4979 ;; XXX: Backward compatibility code.
4980 (list (cons org-todo-interpretation d)))))))
4981 (dolist (sequence todo-sequences)
4982 (let* ((sequence (or (run-hook-with-args-until-success
4983 'org-todo-setup-filter-hook sequence)
4984 sequence))
4985 (sequence-type (car sequence))
4986 (keywords (cdr sequence))
4987 (sep (member "|" keywords))
4988 names alist)
4989 (dolist (k (remove "|" keywords))
4990 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4992 (error "Invalid TODO keyword %s" k))
4993 (let ((name (match-string 1 k))
4994 (key (match-string 2 k))
4995 (log (org-extract-log-state-settings k)))
4996 (push name names)
4997 (push (cons name (and key (string-to-char key))) alist)
4998 (when log (push log org-todo-log-states))))
4999 (let* ((names (nreverse names))
5000 (done (if sep (org-remove-keyword-keys (cdr sep))
5001 (last names)))
5002 (head (car names))
5003 (tail (list sequence-type head (car done) (org-last done))))
5004 (add-to-list 'org-todo-heads head 'append)
5005 (push names org-todo-sets)
5006 (setq org-done-keywords (append org-done-keywords done nil))
5007 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5008 (setq org-todo-key-alist
5009 (append org-todo-key-alist
5010 (and alist
5011 (append '((:startgroup))
5012 (nreverse alist)
5013 '((:endgroup))))))
5014 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5015 (setq org-todo-sets (nreverse org-todo-sets)
5016 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5017 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5018 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5019 ;; Compute the regular expressions and other local variables.
5020 ;; Using `org-outline-regexp-bol' would complicate them much,
5021 ;; because of the fixed white space at the end of that string.
5022 (unless org-done-keywords
5023 (setq org-done-keywords
5024 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5025 (setq org-not-done-keywords
5026 (org-delete-all org-done-keywords
5027 (copy-sequence org-todo-keywords-1))
5028 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5029 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5030 org-not-done-heading-regexp
5031 (format org-heading-keyword-regexp-format org-not-done-regexp)
5032 org-todo-line-regexp
5033 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5034 org-complex-heading-regexp
5035 (concat "^\\(\\*+\\)"
5036 "\\(?: +" org-todo-regexp "\\)?"
5037 "\\(?: +\\(\\[#.\\]\\)\\)?"
5038 "\\(?: +\\(.*?\\)\\)??"
5039 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5040 "[ \t]*$")
5041 org-complex-heading-regexp-format
5042 (concat "^\\(\\*+\\)"
5043 "\\(?: +" org-todo-regexp "\\)?"
5044 "\\(?: +\\(\\[#.\\]\\)\\)?"
5045 "\\(?: +"
5046 ;; Stats cookies can be stuck to body.
5047 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5048 "\\(%s\\)"
5049 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5050 "\\)"
5051 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5052 "[ \t]*$")
5053 org-todo-line-tags-regexp
5054 (concat "^\\(\\*+\\)"
5055 "\\(?: +" org-todo-regexp "\\)?"
5056 "\\(?: +\\(.*?\\)\\)??"
5057 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5058 "[ \t]*$"))
5059 (org-compute-latex-and-related-regexp)))))
5061 (defun org--setup-collect-keywords (regexp &optional files alist)
5062 "Return setup keywords values as an alist.
5064 REGEXP matches a subset of setup keywords. FILES is a list of
5065 file names already visited. It is used to avoid circular setup
5066 files. ALIST, when non-nil, is the alist computed so far.
5068 Return value contains the following keys: `archive', `category',
5069 `columns', `constants', `filetags', `link', `priorities',
5070 `property', `scripts', `startup', `tags' and `todo'."
5071 (org-with-wide-buffer
5072 (goto-char (point-min))
5073 (let ((case-fold-search t))
5074 (while (re-search-forward regexp nil t)
5075 (let ((element (org-element-at-point)))
5076 (when (eq (org-element-type element) 'keyword)
5077 (let ((key (org-element-property :key element))
5078 (value (org-element-property :value element)))
5079 (cond
5080 ((equal key "ARCHIVE")
5081 (when (org-string-nw-p value)
5082 (push (cons 'archive value) alist)))
5083 ((equal key "CATEGORY") (push (cons 'category value) alist))
5084 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5085 ((equal key "CONSTANTS")
5086 (let* ((constants (assq 'constants alist))
5087 (store (cdr constants)))
5088 (dolist (pair (split-string value))
5089 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5090 pair)
5091 (let* ((name (match-string 1 pair))
5092 (value (match-string 2 pair))
5093 (old (assoc name store)))
5094 (if old (setcdr old value)
5095 (push (cons name value) store)))))
5096 (if constants (setcdr constants store)
5097 (push (cons 'constants store) alist))))
5098 ((equal key "FILETAGS")
5099 (when (org-string-nw-p value)
5100 (let ((old (assq 'filetags alist))
5101 (new (apply #'nconc
5102 (mapcar (lambda (x) (org-split-string x ":"))
5103 (split-string value)))))
5104 (if old (setcdr old (append new (cdr old)))
5105 (push (cons 'filetags new) alist)))))
5106 ((equal key "LINK")
5107 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5108 (let ((links (assq 'link alist))
5109 (pair (cons (match-string-no-properties 1 value)
5110 (match-string-no-properties 2 value))))
5111 (if links (push pair (cdr links))
5112 (push (list 'link pair) alist)))))
5113 ((equal key "OPTIONS")
5114 (when (and (org-string-nw-p value)
5115 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5116 (push (cons 'scripts (read (match-string 1 value))) alist)))
5117 ((equal key "PRIORITIES")
5118 (push (cons 'priorities
5119 (let ((prio (split-string value)))
5120 (if (< (length prio) 3) '(?A ?C ?B)
5121 (mapcar #'string-to-char prio))))
5122 alist))
5123 ((equal key "PROPERTY")
5124 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5125 (let* ((property (assq 'property alist))
5126 (value (org--update-property-plist
5127 (match-string-no-properties 1 value)
5128 (match-string-no-properties 2 value)
5129 (cdr property))))
5130 (if property (setcdr property value)
5131 (push (cons 'property value) alist)))))
5132 ((equal key "STARTUP")
5133 (let ((startup (assq 'startup alist)))
5134 (if startup
5135 (setcdr startup
5136 (append (cdr startup) (split-string value)))
5137 (push (cons 'startup (split-string value)) alist))))
5138 ((equal key "TAGS")
5139 (let ((tag-cell (assq 'tags alist)))
5140 (if tag-cell
5141 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5142 (push (cons 'tags value) alist))))
5143 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5144 (let ((todo (assq 'todo alist))
5145 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5146 (split-string value))))
5147 (if todo (push value (cdr todo))
5148 (push (list 'todo value) alist))))
5149 ((equal key "SETUPFILE")
5150 (unless buffer-read-only ; Do not check in Gnus messages.
5151 (let ((f (and (org-string-nw-p value)
5152 (expand-file-name
5153 (org-unbracket-string "\"" "\"" value)))))
5154 (when (and f (file-readable-p f) (not (member f files)))
5155 (with-temp-buffer
5156 (setq default-directory (file-name-directory f))
5157 (insert-file-contents f)
5158 (setq alist
5159 ;; Fake Org mode to benefit from cache
5160 ;; without recurring needlessly.
5161 (let ((major-mode 'org-mode))
5162 (org--setup-collect-keywords
5163 regexp (cons f files) alist)))))))))))))))
5164 alist)
5166 (defun org-tag-string-to-alist (s)
5167 "Return tag alist associated to string S.
5168 S is a value for TAGS keyword or produced with
5169 `org-tag-alist-to-string'. Return value is an alist suitable for
5170 `org-tag-alist' or `org-tag-persistent-alist'."
5171 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5172 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5173 "\\|{.+?}\\)" ; regular expression
5174 "\\(?:(\\(.\\))\\)?\\'"))
5175 alist group-flag)
5176 (dolist (tokens lines (cdr (nreverse alist)))
5177 (push '(:newline) alist)
5178 (while tokens
5179 (let ((token (pop tokens)))
5180 (pcase token
5181 ("{"
5182 (push '(:startgroup) alist)
5183 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5184 ("}"
5185 (push '(:endgroup) alist)
5186 (setq group-flag nil))
5187 ("["
5188 (push '(:startgrouptag) alist)
5189 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5190 ("]"
5191 (push '(:endgrouptag) alist)
5192 (setq group-flag nil))
5193 (":"
5194 (push '(:grouptags) alist))
5195 ((guard (string-match tag-re token))
5196 (let ((tag (match-string 1 token))
5197 (key (and (match-beginning 2)
5198 (string-to-char (match-string 2 token)))))
5199 ;; Push all tags in groups, no matter if they already
5200 ;; appear somewhere else in the list.
5201 (when (or group-flag (not (assoc tag alist)))
5202 (push (cons tag key) alist))))))))))
5204 (defun org-tag-alist-to-string (alist &optional skip-key)
5205 "Return tag string associated to ALIST.
5207 ALIST is an alist, as defined in `org-tag-alist' or
5208 `org-tag-persistent-alist', or produced with
5209 `org-tag-string-to-alist'.
5211 Return value is a string suitable as a value for \"TAGS\"
5212 keyword.
5214 When optional argument SKIP-KEY is non-nil, skip selection keys
5215 next to tags."
5216 (mapconcat (lambda (token)
5217 (pcase token
5218 (`(:startgroup) "{")
5219 (`(:endgroup) "}")
5220 (`(:startgrouptag) "[")
5221 (`(:endgrouptag) "]")
5222 (`(:grouptags) ":")
5223 (`(:newline) "\\n")
5224 ((and
5225 (guard (not skip-key))
5226 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5227 (format "%s(%c)" tag key))
5228 (`(,(and tag (pred stringp)) . ,_) tag)
5229 (_ (user-error "Invalid tag token: %S" token))))
5230 alist
5231 " "))
5233 (defun org-tag-alist-to-groups (alist)
5234 "Return group alist from tag ALIST.
5235 ALIST is an alist, as defined in `org-tag-alist' or
5236 `org-tag-persistent-alist', or produced with
5237 `org-tag-string-to-alist'. Return value is an alist following
5238 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5239 a string, summarizing TAGS, as a list of strings."
5240 (let (groups group-status current-group)
5241 (dolist (token alist (nreverse groups))
5242 (pcase token
5243 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5244 (`(,(or :endgroup :endgrouptag))
5245 (when (eq group-status 'append)
5246 (push (nreverse current-group) groups))
5247 (setq group-status nil))
5248 (`(:grouptags) (setq group-status 'append))
5249 ((and `(,tag . ,_) (guard group-status))
5250 (if (eq group-status 'append) (push tag current-group)
5251 (setq current-group (list tag))))
5252 (_ nil)))))
5254 (defvar org--file-cache (make-hash-table :test #'equal)
5255 "Hash table to store contents of files referenced via a URL.
5256 This is the cache of file URLs read using `org-file-contents'.")
5258 (defun org-reset-file-cache ()
5259 "Reset the cache of files downloaded by `org-file-contents'."
5260 (clrhash org--file-cache))
5262 (defun org-file-url-p (file)
5263 "Non-nil if FILE is a URL."
5264 (require 'ffap)
5265 (string-match-p ffap-url-regexp file))
5267 (defun org-file-contents (file &optional noerror nocache)
5268 "Return the contents of FILE, as a string.
5270 FILE can be a file name or URL.
5272 If FILE is a URL, download the contents. If the URL contents are
5273 already cached in the `org--file-cache' hash table, the download step
5274 is skipped.
5276 If NOERROR is non-nil, ignore the error when unable to read the FILE
5277 from file or URL.
5279 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
5280 is available. This option applies only if FILE is a URL."
5281 (let* ((is-url (org-file-url-p file))
5282 (cache (and is-url
5283 (not nocache)
5284 (gethash file org--file-cache))))
5285 (cond
5286 (cache)
5287 (is-url
5288 (with-current-buffer (url-retrieve-synchronously file)
5289 (goto-char (point-min))
5290 ;; Move point to after the url-retrieve header.
5291 (search-forward "\n\n" nil :move)
5292 ;; Search for the success code only in the url-retrieve header.
5293 (if (save-excursion (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
5294 ;; Update the cache `org--file-cache' and return contents.
5295 (puthash file
5296 (buffer-substring-no-properties (point) (point-max))
5297 org--file-cache)
5298 (funcall (if noerror #'message #'user-error)
5299 "Unable to fetch file from %S"
5300 file))))
5302 (with-temp-buffer
5303 (condition-case err
5304 (progn
5305 (insert-file-contents file)
5306 (buffer-string))
5307 (file-error
5308 (funcall (if noerror #'message #'user-error)
5309 (error-message-string err)))))))))
5311 (defun org-extract-log-state-settings (x)
5312 "Extract the log state setting from a TODO keyword string.
5313 This will extract info from a string like \"WAIT(w@/!)\"."
5314 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5315 (let ((kw (match-string 1 x))
5316 (log1 (and (match-end 3) (match-string 3 x)))
5317 (log2 (and (match-end 4) (match-string 4 x))))
5318 (and (or log1 log2)
5319 (list kw
5320 (and log1 (if (equal log1 "!") 'time 'note))
5321 (and log2 (if (equal log2 "!") 'time 'note)))))))
5323 (defun org-remove-keyword-keys (list)
5324 "Remove a pair of parenthesis at the end of each string in LIST."
5325 (mapcar (lambda (x)
5326 (if (string-match "(.*)$" x)
5327 (substring x 0 (match-beginning 0))
5329 list))
5331 (defun org-assign-fast-keys (alist)
5332 "Assign fast keys to a keyword-key alist.
5333 Respect keys that are already there."
5334 (let (new e (alt ?0))
5335 (while (setq e (pop alist))
5336 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5337 (cdr e)) ;; Key already assigned.
5338 (push e new)
5339 (let ((clist (string-to-list (downcase (car e))))
5340 (used (append new alist)))
5341 (when (= (car clist) ?@)
5342 (pop clist))
5343 (while (and clist (rassoc (car clist) used))
5344 (pop clist))
5345 (unless clist
5346 (while (rassoc alt used)
5347 (cl-incf alt)))
5348 (push (cons (car e) (or (car clist) alt)) new))))
5349 (nreverse new)))
5351 ;;; Some variables used in various places
5353 (defvar org-window-configuration nil
5354 "Used in various places to store a window configuration.")
5355 (defvar org-selected-window nil
5356 "Used in various places to store a window configuration.")
5357 (defvar org-finish-function nil
5358 "Function to be called when `C-c C-c' is used.
5359 This is for getting out of special buffers like capture.")
5360 (defvar org-last-state)
5362 ;; Defined somewhere in this file, but used before definition.
5363 (defvar org-entities) ;; defined in org-entities.el
5364 (defvar org-struct-menu)
5365 (defvar org-org-menu)
5366 (defvar org-tbl-menu)
5368 ;;;; Define the Org mode
5370 ;; We use a before-change function to check if a table might need
5371 ;; an update.
5372 (defvar org-table-may-need-update t
5373 "Indicates that a table might need an update.
5374 This variable is set by `org-before-change-function'.
5375 `org-table-align' sets it back to nil.")
5376 (defun org-before-change-function (_beg _end)
5377 "Every change indicates that a table might need an update."
5378 (setq org-table-may-need-update t))
5379 (defvar org-mode-map)
5380 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5381 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5382 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5383 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5384 (defvar org-table-buffer-is-an nil)
5386 (defvar bidi-paragraph-direction)
5387 (defvar buffer-face-mode-face)
5389 (require 'outline)
5391 ;; Other stuff we need.
5392 (require 'time-date)
5393 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5394 (require 'easymenu)
5395 (autoload 'easy-menu-add "easymenu")
5396 (require 'overlay)
5398 ;; (require 'org-macs) moved higher up in the file before it is first used
5399 (require 'org-entities)
5400 ;; (require 'org-compat) moved higher up in the file before it is first used
5401 (require 'org-faces)
5402 (require 'org-list)
5403 (require 'org-pcomplete)
5404 (require 'org-src)
5405 (require 'org-footnote)
5406 (require 'org-macro)
5408 ;; babel
5409 (require 'ob)
5411 ;;;###autoload
5412 (define-derived-mode org-mode outline-mode "Org"
5413 "Outline-based notes management and organizer, alias
5414 \"Carsten's outline-mode for keeping track of everything.\"
5416 Org mode develops organizational tasks around a NOTES file which
5417 contains information about projects as plain text. Org mode is
5418 implemented on top of Outline mode, which is ideal to keep the content
5419 of large files well structured. It supports ToDo items, deadlines and
5420 time stamps, which magically appear in the diary listing of the Emacs
5421 calendar. Tables are easily created with a built-in table editor.
5422 Plain text URL-like links connect to websites, emails (VM), Usenet
5423 messages (Gnus), BBDB entries, and any files related to the project.
5424 For printing and sharing of notes, an Org file (or a part of it)
5425 can be exported as a structured ASCII or HTML file.
5427 The following commands are available:
5429 \\{org-mode-map}"
5431 ;; Get rid of Outline menus, they are not needed
5432 ;; Need to do this here because define-derived-mode sets up
5433 ;; the keymap so late. Still, it is a waste to call this each time
5434 ;; we switch another buffer into Org mode.
5435 (define-key org-mode-map [menu-bar headings] 'undefined)
5436 (define-key org-mode-map [menu-bar hide] 'undefined)
5437 (define-key org-mode-map [menu-bar show] 'undefined)
5439 (org-load-modules-maybe)
5440 (org-install-agenda-files-menu)
5441 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5442 (add-to-invisibility-spec '(org-hide-block . t))
5443 (setq-local outline-regexp org-outline-regexp)
5444 (setq-local outline-level 'org-outline-level)
5445 (setq bidi-paragraph-direction 'left-to-right)
5446 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5447 (unless org-display-table
5448 (setq org-display-table (make-display-table)))
5449 (set-display-table-slot
5450 org-display-table 4
5451 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5452 org-ellipsis)))
5453 (setq buffer-display-table org-display-table))
5454 (org-set-regexps-and-options)
5455 (org-set-font-lock-defaults)
5456 (when (and org-tag-faces (not org-tags-special-faces-re))
5457 ;; tag faces set outside customize.... force initialization.
5458 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5459 ;; Calc embedded
5460 (setq-local calc-embedded-open-mode "# ")
5461 ;; Modify a few syntax entries
5462 (modify-syntax-entry ?@ "w")
5463 (modify-syntax-entry ?\" "\"")
5464 (modify-syntax-entry ?\\ "_")
5465 (modify-syntax-entry ?~ "_")
5466 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5467 ;; Activate before-change-function
5468 (setq-local org-table-may-need-update t)
5469 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5470 ;; Check for running clock before killing a buffer
5471 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5472 ;; Initialize macros templates.
5473 (org-macro-initialize-templates)
5474 ;; Initialize radio targets.
5475 (org-update-radio-target-regexp)
5476 ;; Indentation.
5477 (setq-local indent-line-function 'org-indent-line)
5478 (setq-local indent-region-function 'org-indent-region)
5479 ;; Filling and auto-filling.
5480 (org-setup-filling)
5481 ;; Comments.
5482 (org-setup-comments-handling)
5483 ;; Initialize cache.
5484 (org-element-cache-reset)
5485 ;; Beginning/end of defun
5486 (setq-local beginning-of-defun-function 'org-backward-element)
5487 (setq-local end-of-defun-function
5488 (lambda ()
5489 (if (not (org-at-heading-p))
5490 (org-forward-element)
5491 (org-forward-element)
5492 (forward-char -1))))
5493 ;; Next error for sparse trees
5494 (setq-local next-error-function 'org-occur-next-match)
5495 ;; Make sure dependence stuff works reliably, even for users who set it
5496 ;; too late :-(
5497 (if org-enforce-todo-dependencies
5498 (add-hook 'org-blocker-hook
5499 'org-block-todo-from-children-or-siblings-or-parent)
5500 (remove-hook 'org-blocker-hook
5501 'org-block-todo-from-children-or-siblings-or-parent))
5502 (if org-enforce-todo-checkbox-dependencies
5503 (add-hook 'org-blocker-hook
5504 'org-block-todo-from-checkboxes)
5505 (remove-hook 'org-blocker-hook
5506 'org-block-todo-from-checkboxes))
5508 ;; Align options lines
5509 (setq-local
5510 align-mode-rules-list
5511 '((org-in-buffer-settings
5512 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5513 (modes . '(org-mode)))))
5515 ;; Imenu
5516 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5518 ;; Make isearch reveal context
5519 (setq-local outline-isearch-open-invisible-function
5520 (lambda (&rest _) (org-show-context 'isearch)))
5522 ;; Setup the pcomplete hooks
5523 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5524 (setq-local pcomplete-command-name-function 'org-command-at-point)
5525 (setq-local pcomplete-default-completion-function 'ignore)
5526 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5527 (setq-local pcomplete-termination-string "")
5528 (setq-local buffer-face-mode-face 'org-default)
5530 ;; If empty file that did not turn on Org mode automatically, make
5531 ;; it to.
5532 (when (and org-insert-mode-line-in-empty-file
5533 (called-interactively-p 'any)
5534 (= (point-min) (point-max)))
5535 (insert "# -*- mode: org -*-\n\n"))
5536 (unless org-inhibit-startup
5537 (org-unmodified
5538 (when org-startup-with-beamer-mode (org-beamer-mode))
5539 (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
5540 (org-table-map-tables
5541 (cond ((and org-startup-align-all-tables
5542 org-startup-shrink-all-tables)
5543 (lambda () (org-table-align) (org-table-shrink)))
5544 (org-startup-align-all-tables #'org-table-align)
5545 (t #'org-table-shrink))
5547 (when org-startup-with-inline-images (org-display-inline-images))
5548 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5549 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5550 (when org-startup-truncated (setq truncate-lines t))
5551 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5552 (org-refresh-effort-properties)))
5553 ;; Try to set `org-hide' face correctly.
5554 (let ((foreground (org-find-invisible-foreground)))
5555 (when foreground
5556 (set-face-foreground 'org-hide foreground))))
5558 ;; Update `customize-package-emacs-version-alist'
5559 (add-to-list 'customize-package-emacs-version-alist
5560 '(Org ("8.0" . "24.4")
5561 ("8.1" . "24.4")
5562 ("8.2" . "24.4")
5563 ("8.2.7" . "24.4")
5564 ("8.3" . "26.1")
5565 ("9.0" . "26.1")
5566 ("9.1" . "26.1")))
5568 (defvar org-mode-transpose-word-syntax-table
5569 (let ((st (make-syntax-table text-mode-syntax-table)))
5570 (dolist (c org-emphasis-alist st)
5571 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5573 (when (fboundp 'abbrev-table-put)
5574 (abbrev-table-put org-mode-abbrev-table
5575 :parents (list text-mode-abbrev-table)))
5577 (defun org-find-invisible-foreground ()
5578 (let ((candidates (remove
5579 "unspecified-bg"
5580 (nconc
5581 (list (face-background 'default)
5582 (face-background 'org-default))
5583 (mapcar
5584 (lambda (alist)
5585 (when (boundp alist)
5586 (cdr (assq 'background-color (symbol-value alist)))))
5587 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5588 (list (face-foreground 'org-hide))))))
5589 (car (remove nil candidates))))
5591 (defun org-current-time (&optional rounding-minutes past)
5592 "Current time, possibly rounded to ROUNDING-MINUTES.
5593 When ROUNDING-MINUTES is not an integer, fall back on the car of
5594 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5595 the rounding returns a past time."
5596 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5597 (car org-time-stamp-rounding-minutes)))
5598 (time (decode-time)) res)
5599 (if (< r 1)
5600 (current-time)
5601 (setq res
5602 (apply 'encode-time
5603 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5604 (nthcdr 2 time))))
5605 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5606 (seconds-to-time (- (float-time res) (* r 60)))
5607 res))))
5609 (defun org-today ()
5610 "Return today date, considering `org-extend-today-until'."
5611 (time-to-days
5612 (time-subtract (current-time)
5613 (list 0 (* 3600 org-extend-today-until) 0))))
5615 ;;;; Font-Lock stuff, including the activators
5617 (defvar org-mouse-map (make-sparse-keymap))
5618 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5619 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5620 (when org-mouse-1-follows-link
5621 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5622 (when org-tab-follows-link
5623 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5624 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5626 (require 'font-lock)
5628 (defconst org-non-link-chars "]\t\n\r<>")
5629 (defvar org-link-types-re nil
5630 "Matches a link that has a url-like prefix like \"http:\"")
5631 (defvar org-link-re-with-space nil
5632 "Matches a link with spaces, optional angular brackets around it.")
5633 (defvar org-link-re-with-space2 nil
5634 "Matches a link with spaces, optional angular brackets around it.")
5635 (defvar org-link-re-with-space3 nil
5636 "Matches a link with spaces, only for internal part in bracket links.")
5637 (defvar org-angle-link-re nil
5638 "Matches link with angular brackets, spaces are allowed.")
5639 (defvar org-plain-link-re nil
5640 "Matches plain link, without spaces.")
5641 (defvar org-bracket-link-regexp nil
5642 "Matches a link in double brackets.")
5643 (defvar org-bracket-link-analytic-regexp nil
5644 "Regular expression used to analyze links.
5645 Here is what the match groups contain after a match:
5646 1: http:
5647 2: http
5648 3: path
5649 4: [desc]
5650 5: desc")
5651 (defvar org-bracket-link-analytic-regexp++ nil
5652 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5653 (defvar org-any-link-re nil
5654 "Regular expression matching any link.")
5656 (defconst org-match-sexp-depth 3
5657 "Number of stacked braces for sub/superscript matching.")
5659 (defun org-create-multibrace-regexp (left right n)
5660 "Create a regular expression which will match a balanced sexp.
5661 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5662 as single character strings.
5663 The regexp returned will match the entire expression including the
5664 delimiters. It will also define a single group which contains the
5665 match except for the outermost delimiters. The maximum depth of
5666 stacked delimiters is N. Escaping delimiters is not possible."
5667 (let* ((nothing (concat "[^" left right "]*?"))
5668 (or "\\|")
5669 (re nothing)
5670 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5671 (while (> n 1)
5672 (setq n (1- n)
5673 re (concat re or next)
5674 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5675 (concat left "\\(" re "\\)" right)))
5677 (defconst org-match-substring-regexp
5678 (concat
5679 "\\(\\S-\\)\\([_^]\\)\\("
5680 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5681 "\\|"
5682 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5683 "\\|"
5684 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5685 "The regular expression matching a sub- or superscript.")
5687 (defconst org-match-substring-with-braces-regexp
5688 (concat
5689 "\\(\\S-\\)\\([_^]\\)"
5690 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5691 "The regular expression matching a sub- or superscript, forcing braces.")
5693 (defun org-make-link-regexps ()
5694 "Update the link regular expressions.
5695 This should be called after the variable `org-link-parameters' has changed."
5696 (let ((types-re (regexp-opt (org-link-types) t)))
5697 (setq org-link-types-re
5698 (concat "\\`" types-re ":")
5699 org-link-re-with-space
5700 (concat "<?" types-re ":"
5701 "\\([^" org-non-link-chars " ]"
5702 "[^" org-non-link-chars "]*"
5703 "[^" org-non-link-chars " ]\\)>?")
5704 org-link-re-with-space2
5705 (concat "<?" types-re ":"
5706 "\\([^" org-non-link-chars " ]"
5707 "[^\t\n\r]*"
5708 "[^" org-non-link-chars " ]\\)>?")
5709 org-link-re-with-space3
5710 (concat "<?" types-re ":"
5711 "\\([^" org-non-link-chars " ]"
5712 "[^\t\n\r]*\\)")
5713 org-angle-link-re
5714 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5715 types-re)
5716 org-plain-link-re
5717 (concat
5718 "\\<" types-re ":"
5719 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5720 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5721 org-bracket-link-regexp
5722 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5723 org-bracket-link-analytic-regexp
5724 (concat
5725 "\\[\\["
5726 "\\(" types-re ":\\)?"
5727 "\\([^]]+\\)"
5728 "\\]"
5729 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5730 "\\]")
5731 org-bracket-link-analytic-regexp++
5732 (concat
5733 "\\[\\["
5734 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5735 "\\([^]]+\\)"
5736 "\\]"
5737 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5738 "\\]")
5739 org-any-link-re
5740 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5741 org-angle-link-re "\\)\\|\\("
5742 org-plain-link-re "\\)"))))
5744 (org-make-link-regexps)
5746 (defvar org-emph-face nil)
5748 (defun org-do-emphasis-faces (limit)
5749 "Run through the buffer and emphasize strings."
5750 (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
5751 (car org-emphasis-regexp-components))))
5752 (catch :exit
5753 (while (re-search-forward quick-re limit t)
5754 (let* ((marker (match-string 2))
5755 (verbatim? (member marker '("~" "="))))
5756 (when (save-excursion
5757 (goto-char (match-beginning 0))
5758 ;; Do not match headline stars. Do not consider
5759 ;; stars of a headline as closing marker for bold
5760 ;; markup either. Do not match table hlines.
5761 (and
5762 (not (looking-at-p org-outline-regexp-bol))
5763 (not (and (equal marker "+")
5764 (org-match-line
5765 "^[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
5766 (looking-at (if verbatim? org-verbatim-re org-emph-re))
5767 (not (string-match-p
5768 (concat org-outline-regexp-bol "\\'")
5769 (match-string 0)))))
5770 (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist)))
5771 (font-lock-prepend-text-property
5772 (match-beginning 2) (match-end 2) 'face face)
5773 (when verbatim?
5774 (org-remove-flyspell-overlays-in
5775 (match-beginning 0) (match-end 0)))
5776 (add-text-properties (match-beginning 2) (match-end 2)
5777 '(font-lock-multiline t org-emphasis t))
5778 (when org-hide-emphasis-markers
5779 (add-text-properties (match-end 4) (match-beginning 5)
5780 '(invisible org-link))
5781 (add-text-properties (match-beginning 3) (match-end 3)
5782 '(invisible org-link)))
5783 (throw :exit t))))))))
5785 (defun org-emphasize (&optional char)
5786 "Insert or change an emphasis, i.e. a font like bold or italic.
5787 If there is an active region, change that region to a new emphasis.
5788 If there is no region, just insert the marker characters and position
5789 the cursor between them.
5790 CHAR should be the marker character. If it is a space, it means to
5791 remove the emphasis of the selected region.
5792 If CHAR is not given (for example in an interactive call) it will be
5793 prompted for."
5794 (interactive)
5795 (let ((erc org-emphasis-regexp-components)
5796 (string "") beg end move s)
5797 (if (org-region-active-p)
5798 (setq beg (region-beginning)
5799 end (region-end)
5800 string (buffer-substring beg end))
5801 (setq move t))
5803 (unless char
5804 (message "Emphasis marker or tag: [%s]"
5805 (mapconcat #'car org-emphasis-alist ""))
5806 (setq char (read-char-exclusive)))
5807 (if (equal char ?\s)
5808 (setq s ""
5809 move nil)
5810 (unless (assoc (char-to-string char) org-emphasis-alist)
5811 (user-error "No such emphasis marker: \"%c\"" char))
5812 (setq s (char-to-string char)))
5813 (while (and (> (length string) 1)
5814 (equal (substring string 0 1) (substring string -1))
5815 (assoc (substring string 0 1) org-emphasis-alist))
5816 (setq string (substring string 1 -1)))
5817 (setq string (concat s string s))
5818 (when beg (delete-region beg end))
5819 (unless (or (bolp)
5820 (string-match (concat "[" (nth 0 erc) "\n]")
5821 (char-to-string (char-before (point)))))
5822 (insert " "))
5823 (unless (or (eobp)
5824 (string-match (concat "[" (nth 1 erc) "\n]")
5825 (char-to-string (char-after (point)))))
5826 (insert " ") (backward-char 1))
5827 (insert string)
5828 (and move (backward-char 1))))
5830 (defconst org-nonsticky-props
5831 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5833 (defsubst org-rear-nonsticky-at (pos)
5834 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5836 (defun org-activate-links (limit)
5837 "Add link properties to links.
5838 This includes angle, plain, and bracket links."
5839 (catch :exit
5840 (while (re-search-forward org-any-link-re limit t)
5841 (let* ((start (match-beginning 0))
5842 (end (match-end 0))
5843 (style (cond ((eq ?< (char-after start)) 'angle)
5844 ((eq ?\[ (char-after (1+ start))) 'bracket)
5845 (t 'plain))))
5846 (when (and (memq style org-highlight-links)
5847 ;; Do not confuse plain links with tags.
5848 (not (and (eq style 'plain)
5849 (let ((face (get-text-property
5850 (max (1- start) (point-min)) 'face)))
5851 (if (consp face) (memq 'org-tag face)
5852 (eq 'org-tag face))))))
5853 (let* ((link-object (save-excursion
5854 (goto-char start)
5855 (save-match-data (org-element-link-parser))))
5856 (link (org-element-property :raw-link link-object))
5857 (type (org-element-property :type link-object))
5858 (path (org-element-property :path link-object))
5859 (properties ;for link's visible part
5860 (list
5861 'face (pcase (org-link-get-parameter type :face)
5862 ((and (pred functionp) face) (funcall face path))
5863 ((and (pred facep) face) face)
5864 ((and (pred consp) face) face) ;anonymous
5865 (_ 'org-link))
5866 'mouse-face (or (org-link-get-parameter type :mouse-face)
5867 'highlight)
5868 'keymap (or (org-link-get-parameter type :keymap)
5869 org-mouse-map)
5870 'help-echo (pcase (org-link-get-parameter type :help-echo)
5871 ((and (pred stringp) echo) echo)
5872 ((and (pred functionp) echo) echo)
5873 (_ (concat "LINK: " link)))
5874 'htmlize-link (pcase (org-link-get-parameter type
5875 :htmlize-link)
5876 ((and (pred functionp) f) (funcall f))
5877 (_ `(:uri ,link)))
5878 'font-lock-multiline t)))
5879 (org-remove-flyspell-overlays-in start end)
5880 (org-rear-nonsticky-at end)
5881 (if (not (eq 'bracket style))
5882 (add-text-properties start end properties)
5883 ;; Handle invisible parts in bracket links.
5884 (remove-text-properties start end '(invisible nil))
5885 (let ((hidden
5886 (append `(invisible
5887 ,(or (org-link-get-parameter type :display)
5888 'org-link))
5889 properties))
5890 (visible-start (or (match-beginning 4) (match-beginning 2)))
5891 (visible-end (or (match-end 4) (match-end 2))))
5892 (add-text-properties start visible-start hidden)
5893 (add-text-properties visible-start visible-end properties)
5894 (add-text-properties visible-end end hidden)
5895 (org-rear-nonsticky-at visible-start)
5896 (org-rear-nonsticky-at visible-end)))
5897 (let ((f (org-link-get-parameter type :activate-func)))
5898 (when (functionp f)
5899 (funcall f start end path (eq style 'bracket))))
5900 (throw :exit t))))) ;signal success
5901 nil))
5903 (defun org-activate-code (limit)
5904 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5905 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5906 (remove-text-properties (match-beginning 0) (match-end 0)
5907 '(display t invisible t intangible t))
5910 (defcustom org-src-fontify-natively t
5911 "When non-nil, fontify code in code blocks.
5912 See also the `org-block' face."
5913 :type 'boolean
5914 :version "26.1"
5915 :package-version '(Org . "8.3")
5916 :group 'org-appearance
5917 :group 'org-babel)
5919 (defcustom org-allow-promoting-top-level-subtree nil
5920 "When non-nil, allow promoting a top level subtree.
5921 The leading star of the top level headline will be replaced
5922 by a #."
5923 :type 'boolean
5924 :version "24.1"
5925 :group 'org-appearance)
5927 (defun org-fontify-meta-lines-and-blocks (limit)
5928 (condition-case nil
5929 (org-fontify-meta-lines-and-blocks-1 limit)
5930 (error (message "org-mode fontification error in %S at %d"
5931 (current-buffer)
5932 (line-number-at-pos)))))
5934 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5935 "Fontify #+ lines and blocks."
5936 (let ((case-fold-search t))
5937 (when (re-search-forward
5938 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5939 limit t)
5940 (let ((beg (match-beginning 0))
5941 (block-start (match-end 0))
5942 (block-end nil)
5943 (lang (match-string 7))
5944 (beg1 (line-beginning-position 2))
5945 (dc1 (downcase (match-string 2)))
5946 (dc3 (downcase (match-string 3)))
5947 end end1 quoting block-type)
5948 (cond
5949 ((and (match-end 4) (equal dc3 "+begin"))
5950 ;; Truly a block
5951 (setq block-type (downcase (match-string 5))
5952 quoting (member block-type org-protecting-blocks))
5953 (when (re-search-forward
5954 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5955 nil t) ;; on purpose, we look further than LIMIT
5956 (setq end (min (point-max) (match-end 0))
5957 end1 (min (point-max) (1- (match-beginning 0))))
5958 (setq block-end (match-beginning 0))
5959 (when quoting
5960 (org-remove-flyspell-overlays-in beg1 end1)
5961 (remove-text-properties beg end
5962 '(display t invisible t intangible t)))
5963 (add-text-properties
5964 beg end '(font-lock-fontified t font-lock-multiline t))
5965 (add-text-properties beg beg1 '(face org-meta-line))
5966 (org-remove-flyspell-overlays-in beg beg1)
5967 (add-text-properties ; For end_src
5968 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5969 (org-remove-flyspell-overlays-in end1 end)
5970 (cond
5971 ((and lang (not (string= lang "")) org-src-fontify-natively)
5972 (org-src-font-lock-fontify-block lang block-start block-end)
5973 (add-text-properties beg1 block-end '(src-block t)))
5974 (quoting
5975 (add-text-properties beg1 (min (point-max) (1+ end1))
5976 (list 'face
5977 (list :inherit
5978 (let ((face-name
5979 (intern (format "org-block-%s" lang))))
5980 (append (and (facep face-name) (list face-name))
5981 '(org-block))))))) ; end of source block
5982 ((not org-fontify-quote-and-verse-blocks))
5983 ((string= block-type "quote")
5984 (add-face-text-property
5985 beg1 (min (point-max) (1+ end1)) 'org-quote t))
5986 ((string= block-type "verse")
5987 (add-face-text-property
5988 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
5989 (add-text-properties beg beg1 '(face org-block-begin-line))
5990 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5991 '(face org-block-end-line))
5993 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5994 (org-remove-flyspell-overlays-in
5995 (match-beginning 0)
5996 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5997 (add-text-properties
5998 beg (match-end 3)
5999 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6000 '(font-lock-fontified t invisible t)
6001 '(font-lock-fontified t face org-document-info-keyword)))
6002 (add-text-properties
6003 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6004 (if (string-equal dc1 "+title:")
6005 '(font-lock-fontified t face org-document-title)
6006 '(font-lock-fontified t face org-document-info))))
6007 ((string-prefix-p "+caption" dc1)
6008 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6009 (remove-text-properties (match-beginning 0) (match-end 0)
6010 '(display t invisible t intangible t))
6011 ;; Handle short captions.
6012 (save-excursion
6013 (beginning-of-line)
6014 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6015 (add-text-properties (line-beginning-position) (match-end 1)
6016 '(font-lock-fontified t face org-meta-line))
6017 (add-text-properties (match-end 0) (line-end-position)
6018 '(font-lock-fontified t face org-block))
6020 ((member dc3 '(" " ""))
6021 (org-remove-flyspell-overlays-in beg (match-end 0))
6022 (add-text-properties
6023 beg (match-end 0)
6024 '(font-lock-fontified t face font-lock-comment-face)))
6025 (t ;; just any other in-buffer setting, but not indented
6026 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6027 (remove-text-properties (match-beginning 0) (match-end 0)
6028 '(display t invisible t intangible t))
6029 (add-text-properties beg (match-end 0)
6030 '(font-lock-fontified t face org-meta-line))
6031 t))))))
6033 (defun org-fontify-drawers (limit)
6034 "Fontify drawers."
6035 (when (re-search-forward org-drawer-regexp limit t)
6036 (add-text-properties
6037 (match-beginning 0) (match-end 0)
6038 '(font-lock-fontified t face org-special-keyword))
6039 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6042 (defun org-fontify-macros (limit)
6043 "Fontify macros."
6044 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6045 (add-text-properties
6046 (match-beginning 0) (match-end 0)
6047 '(font-lock-fontified t face org-macro))
6048 (when org-hide-macro-markers
6049 (add-text-properties (match-end 2) (match-beginning 2)
6050 '(invisible t))
6051 (add-text-properties (match-beginning 1) (match-end 1)
6052 '(invisible t)))
6053 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6056 (defun org-activate-footnote-links (limit)
6057 "Add text properties for footnotes."
6058 (let ((fn (org-footnote-next-reference-or-definition limit)))
6059 (when fn
6060 (let* ((beg (nth 1 fn))
6061 (end (nth 2 fn))
6062 (label (car fn))
6063 (referencep (/= (line-beginning-position) beg)))
6064 (when (and referencep (nth 3 fn))
6065 (save-excursion
6066 (goto-char beg)
6067 (search-forward (or label "fn:"))
6068 (org-remove-flyspell-overlays-in beg (match-end 0))))
6069 (add-text-properties beg end
6070 (list 'mouse-face 'highlight
6071 'keymap org-mouse-map
6072 'help-echo
6073 (if referencep "Footnote reference"
6074 "Footnote definition")
6075 'font-lock-fontified t
6076 'font-lock-multiline t
6077 'face 'org-footnote))))))
6079 (defun org-activate-dates (limit)
6080 "Add text properties for dates."
6081 (when (and (re-search-forward org-tsr-regexp-both limit t)
6082 (not (equal (char-before (match-beginning 0)) 91)))
6083 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6084 (add-text-properties (match-beginning 0) (match-end 0)
6085 (list 'mouse-face 'highlight
6086 'keymap org-mouse-map))
6087 (org-rear-nonsticky-at (match-end 0))
6088 (when org-display-custom-times
6089 ;; If it's a date range, activate custom time for second date.
6090 (when (match-end 3)
6091 (org-display-custom-time (match-beginning 3) (match-end 3)))
6092 (org-display-custom-time (match-beginning 1) (match-end 1)))
6095 (defvar-local org-target-link-regexp nil
6096 "Regular expression matching radio targets in plain text.")
6098 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6099 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6100 border border border))
6101 "Regular expression matching a link target.")
6103 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6104 "Regular expression matching a radio target.")
6106 (defconst org-any-target-regexp
6107 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6108 "Regular expression matching any target.")
6110 (defun org-activate-target-links (limit)
6111 "Add text properties for target matches."
6112 (when org-target-link-regexp
6113 (let ((case-fold-search t))
6114 (when (re-search-forward org-target-link-regexp limit t)
6115 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6116 (add-text-properties (match-beginning 1) (match-end 1)
6117 (list 'mouse-face 'highlight
6118 'keymap org-mouse-map
6119 'help-echo "Radio target link"
6120 'org-linked-text t))
6121 (org-rear-nonsticky-at (match-end 1))
6122 t))))
6124 (defun org-update-radio-target-regexp ()
6125 "Find all radio targets in this file and update the regular expression.
6126 Also refresh fontification if needed."
6127 (interactive)
6128 (let ((old-regexp org-target-link-regexp)
6129 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6130 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6131 (targets
6132 (org-with-wide-buffer
6133 (goto-char (point-min))
6134 (let (rtn)
6135 (while (re-search-forward org-radio-target-regexp nil t)
6136 ;; Make sure point is really within the object.
6137 (backward-char)
6138 (let ((obj (org-element-context)))
6139 (when (eq (org-element-type obj) 'radio-target)
6140 (cl-pushnew (org-element-property :value obj) rtn
6141 :test #'equal))))
6142 rtn))))
6143 (setq org-target-link-regexp
6144 (and targets
6145 (concat before-re
6146 (mapconcat
6147 (lambda (x)
6148 (replace-regexp-in-string
6149 " +" "\\s-+" (regexp-quote x) t t))
6150 targets
6151 "\\|")
6152 after-re)))
6153 (unless (equal old-regexp org-target-link-regexp)
6154 ;; Clean-up cache.
6155 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6156 ((not org-target-link-regexp) old-regexp)
6158 (concat before-re
6159 (mapconcat
6160 (lambda (re)
6161 (substring re (length before-re)
6162 (- (length after-re))))
6163 (list old-regexp org-target-link-regexp)
6164 "\\|")
6165 after-re)))))
6166 (org-with-wide-buffer
6167 (goto-char (point-min))
6168 (while (re-search-forward regexp nil t)
6169 (org-element-cache-refresh (match-beginning 1)))))
6170 ;; Re fontify buffer.
6171 (when (memq 'radio org-highlight-links)
6172 (org-restart-font-lock)))))
6174 (defvar org-latex-and-related-regexp nil
6175 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6177 (defun org-compute-latex-and-related-regexp ()
6178 "Compute regular expression for LaTeX, entities and sub/superscript.
6179 Result depends on variable `org-highlight-latex-and-related'."
6180 (setq-local
6181 org-latex-and-related-regexp
6182 (let* ((re-sub
6183 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6184 ((eq org-use-sub-superscripts '{})
6185 (list org-match-substring-with-braces-regexp))
6186 (org-use-sub-superscripts (list org-match-substring-regexp))))
6187 (re-latex
6188 (when (memq 'latex org-highlight-latex-and-related)
6189 (let ((matchers (plist-get org-format-latex-options :matchers)))
6190 (delq nil
6191 (mapcar (lambda (x)
6192 (and (member (car x) matchers) (nth 1 x)))
6193 org-latex-regexps)))))
6194 (re-entities
6195 (when (memq 'entities org-highlight-latex-and-related)
6196 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6197 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6199 (defun org-do-latex-and-related (limit)
6200 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6201 LIMIT bounds the search for syntax to highlight. Stop at first
6202 highlighted object, if any. Return t if some highlighting was
6203 done, nil otherwise."
6204 (when (org-string-nw-p org-latex-and-related-regexp)
6205 (catch 'found
6206 (while (re-search-forward org-latex-and-related-regexp limit t)
6207 (unless
6208 (cl-some
6209 (lambda (f)
6210 (memq f '(org-code org-verbatim underline org-special-keyword)))
6211 (save-excursion
6212 (goto-char (1+ (match-beginning 0)))
6213 (face-at-point nil t)))
6214 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6215 '(?_ ?^))
6217 0)))
6218 (font-lock-prepend-text-property
6219 (+ offset (match-beginning 0)) (match-end 0)
6220 'face 'org-latex-and-related)
6221 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6222 '(font-lock-multiline t)))
6223 (throw 'found t)))
6224 nil)))
6226 (defun org-restart-font-lock ()
6227 "Restart `font-lock-mode', to force refontification."
6228 (when (and (boundp 'font-lock-mode) font-lock-mode)
6229 (font-lock-mode -1)
6230 (font-lock-mode 1)))
6232 (defun org-activate-tags (limit)
6233 (when (re-search-forward
6234 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6235 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6236 (add-text-properties (match-beginning 1) (match-end 1)
6237 (list 'mouse-face 'highlight
6238 'keymap org-mouse-map))
6239 (org-rear-nonsticky-at (match-end 1))
6242 (defun org-outline-level ()
6243 "Compute the outline level of the heading at point.
6245 If this is called at a normal headline, the level is the number
6246 of stars. Use `org-reduced-level' to remove the effect of
6247 `org-odd-levels'. Unlike to `org-current-level', this function
6248 takes into consideration inlinetasks."
6249 (org-with-wide-buffer
6250 (end-of-line)
6251 (if (re-search-backward org-outline-regexp-bol nil t)
6252 (1- (- (match-end 0) (match-beginning 0)))
6253 0)))
6255 (defvar org-font-lock-keywords nil)
6257 (defsubst org-re-property (property &optional literal allow-null value)
6258 "Return a regexp matching a PROPERTY line.
6260 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6261 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6262 non-nil, match properties even without a value.
6264 Match group 3 is set to the value when it exists. If there is no
6265 value and ALLOW-NULL is non-nil, it is set to the empty string.
6267 With optional argument VALUE, match only property lines with
6268 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6269 unless LITERAL is non-nil."
6270 (concat
6271 "^\\(?4:[ \t]*\\)"
6272 (format "\\(?1::\\(?2:%s\\):\\)"
6273 (if literal property (regexp-quote property)))
6274 (cond (value
6275 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6276 (if literal value (regexp-quote value))))
6277 (allow-null
6278 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6280 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6282 (defconst org-property-re
6283 (org-re-property "\\S-+" 'literal t)
6284 "Regular expression matching a property line.
6285 There are four matching groups:
6286 1: :PROPKEY: including the leading and trailing colon,
6287 2: PROPKEY without the leading and trailing colon,
6288 3: PROPVAL without leading or trailing spaces,
6289 4: the indentation of the current line,
6290 5: trailing whitespace.")
6292 (defvar org-font-lock-hook nil
6293 "Functions to be called for special font lock stuff.")
6295 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6297 (defvar org-font-lock-set-keywords-hook nil
6298 "Functions that can manipulate `org-font-lock-extra-keywords'.
6299 This is called after `org-font-lock-extra-keywords' is defined, but before
6300 it is installed to be used by font lock. This can be useful if something
6301 needs to be inserted at a specific position in the font-lock sequence.")
6303 (defun org-font-lock-hook (limit)
6304 "Run `org-font-lock-hook' within LIMIT."
6305 (run-hook-with-args 'org-font-lock-hook limit))
6307 (defun org-set-font-lock-defaults ()
6308 "Set font lock defaults for the current buffer."
6309 (let* ((em org-fontify-emphasized-text)
6310 (lk org-highlight-links)
6311 (org-font-lock-extra-keywords
6312 (list
6313 ;; Call the hook
6314 '(org-font-lock-hook)
6315 ;; Headlines
6316 `(,(if org-fontify-whole-heading-line
6317 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6318 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6319 (1 (org-get-level-face 1))
6320 (2 (org-get-level-face 2))
6321 (3 (org-get-level-face 3)))
6322 ;; Table lines
6323 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6324 (1 'org-table t))
6325 ;; Table internals
6326 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6327 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6328 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6329 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6330 ;; Drawers
6331 '(org-fontify-drawers)
6332 ;; Properties
6333 (list org-property-re
6334 '(1 'org-special-keyword t)
6335 '(3 'org-property-value t))
6336 ;; Link related fontification.
6337 '(org-activate-links)
6338 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6339 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6340 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6341 (when (memq 'footnote lk) '(org-activate-footnote-links))
6342 ;; Targets.
6343 (list org-any-target-regexp '(0 'org-target t))
6344 ;; Diary sexps.
6345 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6346 ;; Macro
6347 '(org-fontify-macros)
6348 ;; TODO keyword
6349 (list (format org-heading-keyword-regexp-format
6350 org-todo-regexp)
6351 '(2 (org-get-todo-face 2) t))
6352 ;; DONE
6353 (if org-fontify-done-headline
6354 (list (format org-heading-keyword-regexp-format
6355 (concat
6356 "\\(?:"
6357 (mapconcat 'regexp-quote org-done-keywords "\\|")
6358 "\\)"))
6359 '(2 'org-headline-done t))
6360 nil)
6361 ;; Priorities
6362 '(org-font-lock-add-priority-faces)
6363 ;; Tags
6364 '(org-font-lock-add-tag-faces)
6365 ;; Tags groups
6366 (when (and org-group-tags org-tag-groups-alist)
6367 (list (concat org-outline-regexp-bol ".+\\(:"
6368 (regexp-opt (mapcar 'car org-tag-groups-alist))
6369 ":\\).*$")
6370 '(1 'org-tag-group prepend)))
6371 ;; Special keywords
6372 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6373 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6374 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6375 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6376 ;; Emphasis
6377 (when em '(org-do-emphasis-faces))
6378 ;; Checkboxes
6379 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6380 1 'org-checkbox prepend)
6381 (when (cdr (assq 'checkbox org-list-automatic-rules))
6382 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6383 (0 (org-get-checkbox-statistics-face) t)))
6384 ;; Description list items
6385 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6386 1 'org-list-dt prepend)
6387 ;; ARCHIVEd headings
6388 (list (concat
6389 org-outline-regexp-bol
6390 "\\(.*:" org-archive-tag ":.*\\)")
6391 '(1 'org-archived prepend))
6392 ;; Specials
6393 '(org-do-latex-and-related)
6394 '(org-fontify-entities)
6395 '(org-raise-scripts)
6396 ;; Code
6397 '(org-activate-code (1 'org-code t))
6398 ;; COMMENT
6399 (list (format
6400 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6401 org-todo-regexp
6402 org-comment-string)
6403 '(9 'org-special-keyword t))
6404 ;; Blocks and meta lines
6405 '(org-fontify-meta-lines-and-blocks))))
6406 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6407 (run-hooks 'org-font-lock-set-keywords-hook)
6408 ;; Now set the full font-lock-keywords
6409 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6410 (setq-local font-lock-defaults
6411 '(org-font-lock-keywords t nil nil backward-paragraph))
6412 (kill-local-variable 'font-lock-keywords)
6413 nil))
6415 (defun org-toggle-pretty-entities ()
6416 "Toggle the composition display of entities as UTF8 characters."
6417 (interactive)
6418 (setq-local org-pretty-entities (not org-pretty-entities))
6419 (org-restart-font-lock)
6420 (if org-pretty-entities
6421 (message "Entities are now displayed as UTF8 characters")
6422 (save-restriction
6423 (widen)
6424 (decompose-region (point-min) (point-max))
6425 (message "Entities are now displayed as plain text"))))
6427 (defvar-local org-custom-properties-overlays nil
6428 "List of overlays used for custom properties.")
6430 (defun org-toggle-custom-properties-visibility ()
6431 "Display or hide properties in `org-custom-properties'."
6432 (interactive)
6433 (if org-custom-properties-overlays
6434 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6435 (setq org-custom-properties-overlays nil))
6436 (when org-custom-properties
6437 (org-with-wide-buffer
6438 (goto-char (point-min))
6439 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6440 (while (re-search-forward regexp nil t)
6441 (let ((end (cdr (save-match-data (org-get-property-block)))))
6442 (when (and end (< (point) end))
6443 ;; Hide first custom property in current drawer.
6444 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6445 (overlay-put o 'invisible t)
6446 (overlay-put o 'org-custom-property t)
6447 (push o org-custom-properties-overlays))
6448 ;; Hide additional custom properties in the same drawer.
6449 (while (re-search-forward regexp end t)
6450 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6451 (overlay-put o 'invisible t)
6452 (overlay-put o 'org-custom-property t)
6453 (push o org-custom-properties-overlays)))))
6454 ;; Each entry is limited to a single property drawer.
6455 (outline-next-heading)))))))
6457 (defun org-fontify-entities (limit)
6458 "Find an entity to fontify."
6459 (let (ee)
6460 (when org-pretty-entities
6461 (catch 'match
6462 ;; "\_ "-family is left out on purpose. Only the first one,
6463 ;; i.e., "\_ ", could be fontified anyway, and it would be
6464 ;; confusing when adding a second white space character.
6465 (while (re-search-forward
6466 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6467 limit t)
6468 (when (and (not (org-at-comment-p))
6469 (setq ee (org-entity-get (match-string 1)))
6470 (= (length (nth 6 ee)) 1))
6471 (let* ((end (if (equal (match-string 2) "{}")
6472 (match-end 2)
6473 (match-end 1))))
6474 (add-text-properties
6475 (match-beginning 0) end
6476 (list 'font-lock-fontified t))
6477 (compose-region (match-beginning 0) end
6478 (nth 6 ee) nil)
6479 (backward-char 1)
6480 (throw 'match t))))
6481 nil))))
6483 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6484 "Fontify string S like in Org mode."
6485 (with-temp-buffer
6486 (insert s)
6487 (let ((org-odd-levels-only odd-levels))
6488 (org-mode)
6489 (org-font-lock-ensure)
6490 (buffer-string))))
6492 (defvar org-m nil)
6493 (defvar org-l nil)
6494 (defvar org-f nil)
6495 (defun org-get-level-face (n)
6496 "Get the right face for match N in font-lock matching of headlines."
6497 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6498 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6499 (if org-cycle-level-faces
6500 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6501 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6502 (cond
6503 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6504 ((eq n 2) org-f)
6505 (t (unless org-level-color-stars-only org-f))))
6507 (defun org-face-from-face-or-color (context inherit face-or-color)
6508 "Create a face list that inherits INHERIT, but sets the foreground color.
6509 When FACE-OR-COLOR is not a string, just return it."
6510 (if (stringp face-or-color)
6511 (list :inherit inherit
6512 (cdr (assoc context org-faces-easy-properties))
6513 face-or-color)
6514 face-or-color))
6516 (defun org-get-todo-face (kwd)
6517 "Get the right face for a TODO keyword KWD.
6518 If KWD is a number, get the corresponding match group."
6519 (when (numberp kwd) (setq kwd (match-string kwd)))
6520 (or (org-face-from-face-or-color
6521 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6522 (and (member kwd org-done-keywords) 'org-done)
6523 'org-todo))
6525 (defun org-get-priority-face (priority)
6526 "Get the right face for PRIORITY.
6527 PRIORITY is a character."
6528 (or (org-face-from-face-or-color
6529 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6530 'org-priority))
6532 (defun org-get-tag-face (tag)
6533 "Get the right face for TAG.
6534 If TAG is a number, get the corresponding match group."
6535 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6536 (or (org-face-from-face-or-color
6537 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6538 'org-tag)))
6540 (defun org-font-lock-add-priority-faces (limit)
6541 "Add the special priority faces."
6542 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6543 (add-text-properties
6544 (match-beginning 1) (match-end 1)
6545 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6546 'font-lock-fontified t))))
6548 (defun org-font-lock-add-tag-faces (limit)
6549 "Add the special tag faces."
6550 (when (and org-tag-faces org-tags-special-faces-re)
6551 (while (re-search-forward org-tags-special-faces-re limit t)
6552 (add-text-properties (match-beginning 1) (match-end 1)
6553 (list 'face (org-get-tag-face 1)
6554 'font-lock-fontified t))
6555 (backward-char 1))))
6557 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6558 "Remove fontification and activation overlays from links."
6559 (font-lock-default-unfontify-region beg end)
6560 (let* ((buffer-undo-list t)
6561 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6562 (inhibit-modification-hooks t)
6563 deactivate-mark buffer-file-name buffer-file-truename)
6564 (decompose-region beg end)
6565 (remove-text-properties beg end
6566 '(mouse-face t keymap t org-linked-text t
6567 invisible t intangible t
6568 org-emphasis t))
6569 (org-remove-font-lock-display-properties beg end)))
6571 (defconst org-script-display '(((raise -0.3) (height 0.7))
6572 ((raise 0.3) (height 0.7))
6573 ((raise -0.5))
6574 ((raise 0.5)))
6575 "Display properties for showing superscripts and subscripts.")
6577 (defun org-remove-font-lock-display-properties (beg end)
6578 "Remove specific display properties that have been added by font lock.
6579 The will remove the raise properties that are used to show superscripts
6580 and subscripts."
6581 (let (next prop)
6582 (while (< beg end)
6583 (setq next (next-single-property-change beg 'display nil end)
6584 prop (get-text-property beg 'display))
6585 (when (member prop org-script-display)
6586 (put-text-property beg next 'display nil))
6587 (setq beg next))))
6589 (defun org-raise-scripts (limit)
6590 "Add raise properties to sub/superscripts."
6591 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6592 (re-search-forward
6593 (if (eq org-use-sub-superscripts t)
6594 org-match-substring-regexp
6595 org-match-substring-with-braces-regexp)
6596 limit t))
6597 (let* ((pos (point)) table-p comment-p
6598 (mpos (match-beginning 3))
6599 (emph-p (get-text-property mpos 'org-emphasis))
6600 (link-p (get-text-property mpos 'mouse-face))
6601 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6602 (goto-char (point-at-bol))
6603 (setq table-p (looking-at-p org-table-dataline-regexp)
6604 comment-p (looking-at-p "^[ \t]*#[ +]"))
6605 (goto-char pos)
6606 ;; Handle a_b^c
6607 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6608 (unless (or comment-p emph-p link-p keyw-p)
6609 (put-text-property (match-beginning 3) (match-end 0)
6610 'display
6611 (if (equal (char-after (match-beginning 2)) ?^)
6612 (nth (if table-p 3 1) org-script-display)
6613 (nth (if table-p 2 0) org-script-display)))
6614 (add-text-properties (match-beginning 2) (match-end 2)
6615 (list 'invisible t))
6616 (when (and (eq (char-after (match-beginning 3)) ?{)
6617 (eq (char-before (match-end 3)) ?}))
6618 (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
6619 (list 'invisible t))
6620 (add-text-properties (1- (match-end 3)) (match-end 3)
6621 (list 'invisible t))))
6622 t)))
6624 ;;;; Visibility cycling, including org-goto and indirect buffer
6626 ;;; Cycling
6628 (defvar-local org-cycle-global-status nil)
6629 (put 'org-cycle-global-status 'org-state t)
6630 (defvar-local org-cycle-subtree-status nil)
6631 (put 'org-cycle-subtree-status 'org-state t)
6633 (defvar org-inlinetask-min-level)
6635 (defun org-unlogged-message (&rest args)
6636 "Display a message, but avoid logging it in the *Messages* buffer."
6637 (let ((message-log-max nil))
6638 (apply 'message args)))
6640 ;;;###autoload
6641 (defun org-cycle (&optional arg)
6642 "TAB-action and visibility cycling for Org mode.
6644 This is the command invoked in Org mode by the `TAB' key. Its main
6645 purpose is outline visibility cycling, but it also invokes other actions
6646 in special contexts.
6648 When this function is called with a `\\[universal-argument]' prefix, rotate \
6649 the entire
6650 buffer through 3 states (global cycling)
6651 1. OVERVIEW: Show only top-level headlines.
6652 2. CONTENTS: Show all headlines of all levels, but no body text.
6653 3. SHOW ALL: Show everything.
6655 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6656 switch to the startup visibility,
6657 determined by the variable `org-startup-folded', and by any VISIBILITY
6658 properties in the buffer.
6660 With a `\\[universal-argument] \\[universal-argument] \
6661 \\[universal-argument]' prefix argument, show the entire buffer, including
6662 any drawers.
6664 When inside a table, re-align the table and move to the next field.
6666 When point is at the beginning of a headline, rotate the subtree started
6667 by this line through 3 different states (local cycling)
6668 1. FOLDED: Only the main headline is shown.
6669 2. CHILDREN: The main headline and the direct children are shown.
6670 From this state, you can move to one of the children
6671 and zoom in further.
6672 3. SUBTREE: Show the entire subtree, including body text.
6673 If there is no subtree, switch directly from CHILDREN to FOLDED.
6675 When point is at the beginning of an empty headline and the variable
6676 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6677 of the headline by demoting and promoting it to likely levels. This
6678 speeds up creation document structure by pressing `TAB' once or several
6679 times right after creating a new headline.
6681 When there is a numeric prefix, go up to a heading with level ARG, do
6682 a `show-subtree' and return to the previous cursor position. If ARG
6683 is negative, go up that many levels.
6685 When point is not at the beginning of a headline, execute the global
6686 binding for `TAB', which is re-indenting the line. See the option
6687 `org-cycle-emulate-tab' for details.
6689 As a special case, if point is at the beginning of the buffer and there is
6690 no headline in line 1, this function will act as if called with prefix arg
6691 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6692 prefix arg, but only
6693 if the variable `org-cycle-global-at-bob' is t."
6694 (interactive "P")
6695 (org-load-modules-maybe)
6696 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6697 (and org-cycle-level-after-item/entry-creation
6698 (or (org-cycle-level)
6699 (org-cycle-item-indentation))))
6700 (let* ((limit-level
6701 (or org-cycle-max-level
6702 (and (boundp 'org-inlinetask-min-level)
6703 org-inlinetask-min-level
6704 (1- org-inlinetask-min-level))))
6705 (nstars (and limit-level
6706 (if org-odd-levels-only
6707 (and limit-level (1- (* limit-level 2)))
6708 limit-level)))
6709 (org-outline-regexp
6710 (if (not (derived-mode-p 'org-mode))
6711 outline-regexp
6712 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6713 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6714 (not (looking-at org-outline-regexp))))
6715 (org-cycle-hook
6716 (if bob-special
6717 (delq 'org-optimize-window-after-visibility-change
6718 (copy-sequence org-cycle-hook))
6719 org-cycle-hook))
6720 (pos (point)))
6722 (cond
6724 ((equal arg '(16))
6725 (setq last-command 'dummy)
6726 (org-set-startup-visibility)
6727 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6729 ((equal arg '(64))
6730 (outline-show-all)
6731 (org-unlogged-message "Entire buffer visible, including drawers"))
6733 ((equal arg '(4)) (org-cycle-internal-global))
6735 ;; Try hiding block at point.
6736 ((org-hide-block-toggle-maybe))
6738 ;; Try cdlatex TAB completion
6739 ((org-try-cdlatex-tab))
6741 ;; Table: enter it or move to the next field.
6742 ((org-at-table-p 'any)
6743 (if (org-at-table.el-p)
6744 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6745 Use `\\[org-edit-special]' to edit table.el tables"))
6746 (if arg (org-table-edit-field t)
6747 (org-table-justify-field-maybe)
6748 (call-interactively 'org-table-next-field))))
6750 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6752 ;; Global cycling: delegate to `org-cycle-internal-global'.
6753 (bob-special (org-cycle-internal-global))
6755 ;; Drawers: delegate to `org-flag-drawer'.
6756 ((save-excursion
6757 (beginning-of-line 1)
6758 (looking-at org-drawer-regexp))
6759 (org-flag-drawer ; toggle block visibility
6760 (not (get-char-property (match-end 0) 'invisible))))
6762 ;; Show-subtree, ARG levels up from here.
6763 ((integerp arg)
6764 (save-excursion
6765 (org-back-to-heading)
6766 (outline-up-heading (if (< arg 0) (- arg)
6767 (- (funcall outline-level) arg)))
6768 (org-show-subtree)))
6770 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6771 ((and (featurep 'org-inlinetask)
6772 (org-inlinetask-at-task-p)
6773 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6774 (org-inlinetask-toggle-visibility))
6776 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6777 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6778 (save-excursion (move-beginning-of-line 1)
6779 (looking-at org-outline-regexp)))
6780 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6781 (org-cycle-internal-local))
6783 ;; From there: TAB emulation and template completion.
6784 (buffer-read-only (org-back-to-heading))
6786 ((run-hook-with-args-until-success
6787 'org-tab-after-check-for-cycling-hook))
6789 ((org-try-structure-completion))
6791 ((run-hook-with-args-until-success
6792 'org-tab-before-tab-emulation-hook))
6794 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6795 (or (not (bolp))
6796 (not (looking-at org-outline-regexp))))
6797 (call-interactively (global-key-binding "\t")))
6799 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6800 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6801 (or (and (eq org-cycle-emulate-tab 'white)
6802 (= (match-end 0) (point-at-eol)))
6803 (and (eq org-cycle-emulate-tab 'whitestart)
6804 (>= (match-end 0) pos))))
6806 (eq org-cycle-emulate-tab t))
6807 (call-interactively (global-key-binding "\t")))
6809 (t (save-excursion
6810 (org-back-to-heading)
6811 (org-cycle)))))))
6813 (defun org-cycle-internal-global ()
6814 "Do the global cycling action."
6815 ;; Hack to avoid display of messages for .org attachments in Gnus
6816 (let ((ga (string-match "\\*fontification" (buffer-name))))
6817 (cond
6818 ((and (eq last-command this-command)
6819 (eq org-cycle-global-status 'overview))
6820 ;; We just created the overview - now do table of contents
6821 ;; This can be slow in very large buffers, so indicate action
6822 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6823 (unless ga (org-unlogged-message "CONTENTS..."))
6824 (org-content)
6825 (unless ga (org-unlogged-message "CONTENTS...done"))
6826 (setq org-cycle-global-status 'contents)
6827 (run-hook-with-args 'org-cycle-hook 'contents))
6829 ((and (eq last-command this-command)
6830 (eq org-cycle-global-status 'contents))
6831 ;; We just showed the table of contents - now show everything
6832 (run-hook-with-args 'org-pre-cycle-hook 'all)
6833 (outline-show-all)
6834 (unless ga (org-unlogged-message "SHOW ALL"))
6835 (setq org-cycle-global-status 'all)
6836 (run-hook-with-args 'org-cycle-hook 'all))
6839 ;; Default action: go to overview
6840 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6841 (org-overview)
6842 (unless ga (org-unlogged-message "OVERVIEW"))
6843 (setq org-cycle-global-status 'overview)
6844 (run-hook-with-args 'org-cycle-hook 'overview)))))
6846 (defvar org-called-with-limited-levels nil
6847 "Non-nil when `org-with-limited-levels' is currently active.")
6849 (defun org-invisible-p (&optional pos)
6850 "Non-nil if the character after POS is invisible.
6851 If POS is nil, use `point' instead."
6852 (get-char-property (or pos (point)) 'invisible))
6854 (defun org-cycle-internal-local ()
6855 "Do the local cycling action."
6856 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6857 ;; First, determine end of headline (EOH), end of subtree or item
6858 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6859 (save-excursion
6860 (if (org-at-item-p)
6861 (progn
6862 (beginning-of-line)
6863 (setq struct (org-list-struct))
6864 (setq eoh (point-at-eol))
6865 (setq eos (org-list-get-item-end-before-blank (point) struct))
6866 (setq has-children (org-list-has-child-p (point) struct)))
6867 (org-back-to-heading)
6868 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6869 (setq eos (save-excursion (org-end-of-subtree t t)
6870 (when (bolp) (backward-char)) (point)))
6871 (setq has-children
6872 (or (save-excursion
6873 (let ((level (funcall outline-level)))
6874 (outline-next-heading)
6875 (and (org-at-heading-p t)
6876 (> (funcall outline-level) level))))
6877 (save-excursion
6878 (org-list-search-forward (org-item-beginning-re) eos t)))))
6879 ;; Determine end invisible part of buffer (EOL)
6880 (beginning-of-line 2)
6881 (while (and (not (eobp)) ;This is like `next-line'.
6882 (get-char-property (1- (point)) 'invisible))
6883 (goto-char (next-single-char-property-change (point) 'invisible))
6884 (and (eolp) (beginning-of-line 2)))
6885 (setq eol (point)))
6886 ;; Find out what to do next and set `this-command'
6887 (cond
6888 ((= eos eoh)
6889 ;; Nothing is hidden behind this heading
6890 (unless (org-before-first-heading-p)
6891 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6892 (org-unlogged-message "EMPTY ENTRY")
6893 (setq org-cycle-subtree-status nil)
6894 (save-excursion
6895 (goto-char eos)
6896 (outline-next-heading)
6897 (when (org-invisible-p) (org-flag-heading nil))))
6898 ((and (or (>= eol eos)
6899 (not (string-match "\\S-" (buffer-substring eol eos))))
6900 (or has-children
6901 (not (setq children-skipped
6902 org-cycle-skip-children-state-if-no-children))))
6903 ;; Entire subtree is hidden in one line: children view
6904 (unless (org-before-first-heading-p)
6905 (run-hook-with-args 'org-pre-cycle-hook 'children))
6906 (if (org-at-item-p)
6907 (org-list-set-item-visibility (point-at-bol) struct 'children)
6908 (org-show-entry)
6909 (org-with-limited-levels (org-show-children))
6910 ;; FIXME: This slows down the func way too much.
6911 ;; How keep drawers hidden in subtree anyway?
6912 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6913 ;; (org-cycle-hide-drawers 'subtree))
6915 ;; Fold every list in subtree to top-level items.
6916 (when (eq org-cycle-include-plain-lists 'integrate)
6917 (save-excursion
6918 (org-back-to-heading)
6919 (while (org-list-search-forward (org-item-beginning-re) eos t)
6920 (beginning-of-line 1)
6921 (let* ((struct (org-list-struct))
6922 (prevs (org-list-prevs-alist struct))
6923 (end (org-list-get-bottom-point struct)))
6924 (dolist (e (org-list-get-all-items (point) struct prevs))
6925 (org-list-set-item-visibility e struct 'folded))
6926 (goto-char (if (< end eos) end eos)))))))
6927 (org-unlogged-message "CHILDREN")
6928 (save-excursion
6929 (goto-char eos)
6930 (outline-next-heading)
6931 (when (org-invisible-p) (org-flag-heading nil)))
6932 (setq org-cycle-subtree-status 'children)
6933 (unless (org-before-first-heading-p)
6934 (run-hook-with-args 'org-cycle-hook 'children)))
6935 ((or children-skipped
6936 (and (eq last-command this-command)
6937 (eq org-cycle-subtree-status 'children)))
6938 ;; We just showed the children, or no children are there,
6939 ;; now show everything.
6940 (unless (org-before-first-heading-p)
6941 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6942 (outline-flag-region eoh eos nil)
6943 (org-unlogged-message
6944 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6945 (setq org-cycle-subtree-status 'subtree)
6946 (unless (org-before-first-heading-p)
6947 (run-hook-with-args 'org-cycle-hook 'subtree)))
6949 ;; Default action: hide the subtree.
6950 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6951 (outline-flag-region eoh eos t)
6952 (org-unlogged-message "FOLDED")
6953 (setq org-cycle-subtree-status 'folded)
6954 (unless (org-before-first-heading-p)
6955 (run-hook-with-args 'org-cycle-hook 'folded))))))
6957 ;;;###autoload
6958 (defun org-global-cycle (&optional arg)
6959 "Cycle the global visibility. For details see `org-cycle'.
6960 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
6961 With a numeric prefix, show all headlines up to that level."
6962 (interactive "P")
6963 (let ((org-cycle-include-plain-lists
6964 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6965 (cond
6966 ((integerp arg)
6967 (outline-show-all)
6968 (outline-hide-sublevels arg)
6969 (setq org-cycle-global-status 'contents))
6970 ((equal arg '(4))
6971 (org-set-startup-visibility)
6972 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6974 (org-cycle '(4))))))
6976 (defun org-set-startup-visibility ()
6977 "Set the visibility required by startup options and properties."
6978 (cond
6979 ((eq org-startup-folded t)
6980 (org-overview))
6981 ((eq org-startup-folded 'content)
6982 (org-content))
6983 ((or (eq org-startup-folded 'showeverything)
6984 (eq org-startup-folded nil))
6985 (outline-show-all)))
6986 (unless (eq org-startup-folded 'showeverything)
6987 (when org-hide-block-startup (org-hide-block-all))
6988 (org-set-visibility-according-to-property 'no-cleanup)
6989 (org-cycle-hide-archived-subtrees 'all)
6990 (org-cycle-hide-drawers 'all)
6991 (org-cycle-show-empty-lines t)))
6993 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6994 "Switch subtree visibilities according to :VISIBILITY: property."
6995 (interactive)
6996 (org-with-wide-buffer
6997 (goto-char (point-min))
6998 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6999 (if (not (org-at-property-p)) (outline-next-heading)
7000 (let ((state (match-string 3)))
7001 (save-excursion
7002 (org-back-to-heading t)
7003 (outline-hide-subtree)
7004 (org-reveal)
7005 (cond
7006 ((equal state "folded")
7007 (outline-hide-subtree))
7008 ((equal state "children")
7009 (org-show-hidden-entry)
7010 (org-show-children))
7011 ((equal state "content")
7012 (save-excursion
7013 (save-restriction
7014 (org-narrow-to-subtree)
7015 (org-content))))
7016 ((member state '("all" "showall"))
7017 (outline-show-subtree)))))))
7018 (unless no-cleanup
7019 (org-cycle-hide-archived-subtrees 'all)
7020 (org-cycle-hide-drawers 'all)
7021 (org-cycle-show-empty-lines 'all))))
7023 ;; This function uses outline-regexp instead of the more fundamental
7024 ;; org-outline-regexp so that org-cycle-global works outside of Org
7025 ;; buffers, where outline-regexp is needed.
7026 (defun org-overview ()
7027 "Switch to overview mode, showing only top-level headlines.
7028 This shows all headlines with a level equal or greater than the level
7029 of the first headline in the buffer. This is important, because if the
7030 first headline is not level one, then (hide-sublevels 1) gives confusing
7031 results."
7032 (interactive)
7033 (save-excursion
7034 (let ((level
7035 (save-excursion
7036 (goto-char (point-min))
7037 (when (re-search-forward (concat "^" outline-regexp) nil t)
7038 (goto-char (match-beginning 0))
7039 (funcall outline-level)))))
7040 (and level (outline-hide-sublevels level)))))
7042 (defun org-content (&optional arg)
7043 "Show all headlines in the buffer, like a table of contents.
7044 With numerical argument N, show content up to level N."
7045 (interactive "P")
7046 (org-overview)
7047 (save-excursion
7048 ;; Visit all headings and show their offspring
7049 (and (integerp arg) (org-overview))
7050 (goto-char (point-max))
7051 (catch 'exit
7052 (while (and (progn (condition-case nil
7053 (outline-previous-visible-heading 1)
7054 (error (goto-char (point-min))))
7056 (looking-at org-outline-regexp))
7057 (if (integerp arg)
7058 (org-show-children (1- arg))
7059 (outline-show-branches))
7060 (when (bobp) (throw 'exit nil))))))
7062 (defun org-optimize-window-after-visibility-change (state)
7063 "Adjust the window after a change in outline visibility.
7064 This function is the default value of the hook `org-cycle-hook'."
7065 (when (get-buffer-window (current-buffer))
7066 (cond
7067 ((eq state 'content) nil)
7068 ((eq state 'all) nil)
7069 ((eq state 'folded) nil)
7070 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7071 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7073 (defun org-remove-empty-overlays-at (pos)
7074 "Remove outline overlays that do not contain non-white stuff."
7075 (dolist (o (overlays-at pos))
7076 (and (eq 'outline (overlay-get o 'invisible))
7077 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7078 (overlay-end o))))
7079 (delete-overlay o))))
7081 (defun org-clean-visibility-after-subtree-move ()
7082 "Fix visibility issues after moving a subtree."
7083 ;; First, find a reasonable region to look at:
7084 ;; Start two siblings above, end three below
7085 (let* ((beg (save-excursion
7086 (and (org-get-last-sibling)
7087 (org-get-last-sibling))
7088 (point)))
7089 (end (save-excursion
7090 (and (org-get-next-sibling)
7091 (org-get-next-sibling)
7092 (org-get-next-sibling))
7093 (if (org-at-heading-p)
7094 (point-at-eol)
7095 (point))))
7096 (level (looking-at "\\*+"))
7097 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7098 (save-excursion
7099 (save-restriction
7100 (narrow-to-region beg end)
7101 (when re
7102 ;; Properly fold already folded siblings
7103 (goto-char (point-min))
7104 (while (re-search-forward re nil t)
7105 (when (and (not (org-invisible-p))
7106 (save-excursion
7107 (goto-char (point-at-eol)) (org-invisible-p)))
7108 (outline-hide-entry))))
7109 (org-cycle-show-empty-lines 'overview)
7110 (org-cycle-hide-drawers 'overview)))))
7112 (defun org-cycle-show-empty-lines (state)
7113 "Show empty lines above all visible headlines.
7114 The region to be covered depends on STATE when called through
7115 `org-cycle-hook'. Lisp program can use t for STATE to get the
7116 entire buffer covered. Note that an empty line is only shown if there
7117 are at least `org-cycle-separator-lines' empty lines before the headline."
7118 (when (/= org-cycle-separator-lines 0)
7119 (save-excursion
7120 (let* ((n (abs org-cycle-separator-lines))
7121 (re (cond
7122 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7123 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7124 (t (let ((ns (number-to-string (- n 2))))
7125 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7126 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7127 beg end)
7128 (cond
7129 ((memq state '(overview contents t))
7130 (setq beg (point-min) end (point-max)))
7131 ((memq state '(children folded))
7132 (setq beg (point)
7133 end (progn (org-end-of-subtree t t)
7134 (line-beginning-position 2)))))
7135 (when beg
7136 (goto-char beg)
7137 (while (re-search-forward re end t)
7138 (unless (get-char-property (match-end 1) 'invisible)
7139 (let ((e (match-end 1))
7140 (b (if (>= org-cycle-separator-lines 0)
7141 (match-beginning 1)
7142 (save-excursion
7143 (goto-char (match-beginning 0))
7144 (skip-chars-backward " \t\n")
7145 (line-end-position)))))
7146 (outline-flag-region b e nil))))))))
7147 ;; Never hide empty lines at the end of the file.
7148 (save-excursion
7149 (goto-char (point-max))
7150 (outline-previous-heading)
7151 (outline-end-of-heading)
7152 (when (and (looking-at "[ \t\n]+")
7153 (= (match-end 0) (point-max)))
7154 (outline-flag-region (point) (match-end 0) nil))))
7156 (defun org-show-empty-lines-in-parent ()
7157 "Move to the parent and re-show empty lines before visible headlines."
7158 (save-excursion
7159 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7160 (org-cycle-show-empty-lines context))))
7162 (defun org-files-list ()
7163 "Return `org-agenda-files' list, plus all open Org files.
7164 This is useful for operations that need to scan all of a user's
7165 open and agenda-wise Org files."
7166 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7167 (dolist (buf (buffer-list))
7168 (with-current-buffer buf
7169 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7170 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7171 files))
7173 (defsubst org-entry-beginning-position ()
7174 "Return the beginning position of the current entry."
7175 (save-excursion (org-back-to-heading t) (point)))
7177 (defsubst org-entry-end-position ()
7178 "Return the end position of the current entry."
7179 (save-excursion (outline-next-heading) (point)))
7181 (defun org-cycle-hide-drawers (state &optional exceptions)
7182 "Re-hide all drawers after a visibility state change.
7183 STATE should be one of the symbols listed in the docstring of
7184 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7185 a list of strings specifying which drawers should not be hidden."
7186 (when (and (derived-mode-p 'org-mode)
7187 (not (memq state '(overview folded contents))))
7188 (save-excursion
7189 (let* ((globalp (eq state 'all))
7190 (beg (if globalp (point-min) (point)))
7191 (end (if globalp (point-max)
7192 (if (eq state 'children)
7193 (save-excursion (outline-next-heading) (point))
7194 (org-end-of-subtree t)))))
7195 (goto-char beg)
7196 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7197 (unless (member-ignore-case (match-string 1) exceptions)
7198 (let ((drawer (org-element-at-point)))
7199 (when (memq (org-element-type drawer) '(drawer property-drawer))
7200 (org-flag-drawer t drawer)
7201 ;; Make sure to skip drawer entirely or we might flag
7202 ;; it another time when matching its ending line with
7203 ;; `org-drawer-regexp'.
7204 (goto-char (org-element-property :end drawer))))))))))
7206 (defun org-flag-drawer (flag &optional element)
7207 "When FLAG is non-nil, hide the drawer we are at.
7208 Otherwise make it visible. When optional argument ELEMENT is
7209 a parsed drawer, as returned by `org-element-at-point', hide or
7210 show that drawer instead."
7211 (let ((drawer (or element
7212 (and (save-excursion
7213 (beginning-of-line)
7214 (looking-at-p org-drawer-regexp))
7215 (org-element-at-point)))))
7216 (when (memq (org-element-type drawer) '(drawer property-drawer))
7217 (let ((post (org-element-property :post-affiliated drawer)))
7218 (save-excursion
7219 (outline-flag-region
7220 (progn (goto-char post) (line-end-position))
7221 (progn (goto-char (org-element-property :end drawer))
7222 (skip-chars-backward " \r\t\n")
7223 (line-end-position))
7224 flag))
7225 ;; When the drawer is hidden away, make sure point lies in
7226 ;; a visible part of the buffer.
7227 (when (and flag (> (line-beginning-position) post))
7228 (goto-char post))))))
7230 (defun org-subtree-end-visible-p ()
7231 "Is the end of the current subtree visible?"
7232 (pos-visible-in-window-p
7233 (save-excursion (org-end-of-subtree t) (point))))
7235 (defun org-first-headline-recenter ()
7236 "Move cursor to the first headline and recenter the headline."
7237 (let ((window (get-buffer-window)))
7238 (when window
7239 (goto-char (point-min))
7240 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7241 (set-window-start window (line-beginning-position))))))
7243 ;;; Saving and restoring visibility
7245 (defun org-outline-overlay-data (&optional use-markers)
7246 "Return a list of the locations of all outline overlays.
7247 These are overlays with the `invisible' property value `outline'.
7248 The return value is a list of cons cells, with start and stop
7249 positions for each overlay.
7250 If USE-MARKERS is set, return the positions as markers."
7251 (let (beg end)
7252 (org-with-wide-buffer
7253 (delq nil
7254 (mapcar (lambda (o)
7255 (when (eq (overlay-get o 'invisible) 'outline)
7256 (setq beg (overlay-start o)
7257 end (overlay-end o))
7258 (and beg end (> end beg)
7259 (if use-markers
7260 (cons (copy-marker beg)
7261 (copy-marker end t))
7262 (cons beg end)))))
7263 (overlays-in (point-min) (point-max)))))))
7265 (defun org-set-outline-overlay-data (data)
7266 "Create visibility overlays for all positions in DATA.
7267 DATA should have been made by `org-outline-overlay-data'."
7268 (org-with-wide-buffer
7269 (outline-show-all)
7270 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7272 ;;; Folding of blocks
7274 (defvar-local org-hide-block-overlays nil
7275 "Overlays hiding blocks.")
7277 (defun org-block-map (function &optional start end)
7278 "Call FUNCTION at the head of all source blocks in the current buffer.
7279 Optional arguments START and END can be used to limit the range."
7280 (let ((start (or start (point-min)))
7281 (end (or end (point-max))))
7282 (save-excursion
7283 (goto-char start)
7284 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7285 (save-excursion
7286 (save-match-data
7287 (goto-char (match-beginning 0))
7288 (funcall function)))))))
7290 (defun org-hide-block-toggle-all ()
7291 "Toggle the visibility of all blocks in the current buffer."
7292 (org-block-map 'org-hide-block-toggle))
7294 (defun org-hide-block-all ()
7295 "Fold all blocks in the current buffer."
7296 (interactive)
7297 (org-show-block-all)
7298 (org-block-map 'org-hide-block-toggle-maybe))
7300 (defun org-show-block-all ()
7301 "Unfold all blocks in the current buffer."
7302 (interactive)
7303 (mapc #'delete-overlay org-hide-block-overlays)
7304 (setq org-hide-block-overlays nil))
7306 (defun org-hide-block-toggle-maybe ()
7307 "Toggle visibility of block at point.
7308 Unlike to `org-hide-block-toggle', this function does not throw
7309 an error. Return a non-nil value when toggling is successful."
7310 (interactive)
7311 (ignore-errors (org-hide-block-toggle)))
7313 (defun org-hide-block-toggle (&optional force)
7314 "Toggle the visibility of the current block.
7315 When optional argument FORCE is `off', make block visible. If it
7316 is non-nil, hide it unconditionally. Throw an error when not at
7317 a block. Return a non-nil value when toggling is successful."
7318 (interactive)
7319 (let ((element (org-element-at-point)))
7320 (unless (memq (org-element-type element)
7321 '(center-block comment-block dynamic-block example-block
7322 export-block quote-block special-block
7323 src-block verse-block))
7324 (user-error "Not at a block"))
7325 (let* ((start (save-excursion
7326 (goto-char (org-element-property :post-affiliated element))
7327 (line-end-position)))
7328 (end (save-excursion
7329 (goto-char (org-element-property :end element))
7330 (skip-chars-backward " \r\t\n")
7331 (line-end-position)))
7332 (overlays (overlays-at start)))
7333 (cond
7334 ;; Do nothing when not before or at the block opening line or
7335 ;; at the block closing line.
7336 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7337 ((and (not (eq force 'off))
7338 (not (memq t (mapcar
7339 (lambda (o)
7340 (eq (overlay-get o 'invisible) 'org-hide-block))
7341 overlays))))
7342 (let ((ov (make-overlay start end)))
7343 (overlay-put ov 'invisible 'org-hide-block)
7344 ;; Make the block accessible to `isearch'.
7345 (overlay-put
7346 ov 'isearch-open-invisible
7347 (lambda (ov)
7348 (when (memq ov org-hide-block-overlays)
7349 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7350 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7351 (delete-overlay ov))))
7352 (push ov org-hide-block-overlays)
7353 ;; When the block is hidden away, make sure point is left in
7354 ;; a visible part of the buffer.
7355 (when (> (line-beginning-position) start)
7356 (goto-char start)
7357 (beginning-of-line))
7358 ;; Signal successful toggling.
7360 ((or (not force) (eq force 'off))
7361 (dolist (ov overlays t)
7362 (when (memq ov org-hide-block-overlays)
7363 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7364 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7365 (delete-overlay ov))))))))
7367 ;; Remove overlays when changing major mode
7368 (add-hook 'org-mode-hook
7369 (lambda () (add-hook 'change-major-mode-hook
7370 'org-show-block-all 'append 'local)))
7372 ;;; Org-goto
7374 (defvar org-goto-window-configuration nil)
7375 (defvar org-goto-marker nil)
7376 (defvar org-goto-map)
7377 (defun org-goto-map ()
7378 "Set the keymap `org-goto'."
7379 (setq org-goto-map
7380 (let ((map (make-sparse-keymap)))
7381 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7382 mouse-drag-region universal-argument org-occur)))
7383 (dolist (cmd cmds)
7384 (substitute-key-definition cmd cmd map global-map)))
7385 (suppress-keymap map)
7386 (org-defkey map "\C-m" 'org-goto-ret)
7387 (org-defkey map [(return)] 'org-goto-ret)
7388 (org-defkey map [(left)] 'org-goto-left)
7389 (org-defkey map [(right)] 'org-goto-right)
7390 (org-defkey map [(control ?g)] 'org-goto-quit)
7391 (org-defkey map "\C-i" 'org-cycle)
7392 (org-defkey map [(tab)] 'org-cycle)
7393 (org-defkey map [(down)] 'outline-next-visible-heading)
7394 (org-defkey map [(up)] 'outline-previous-visible-heading)
7395 (if org-goto-auto-isearch
7396 (if (fboundp 'define-key-after)
7397 (define-key-after map [t] 'org-goto-local-auto-isearch)
7398 nil)
7399 (org-defkey map "q" 'org-goto-quit)
7400 (org-defkey map "n" 'outline-next-visible-heading)
7401 (org-defkey map "p" 'outline-previous-visible-heading)
7402 (org-defkey map "f" 'outline-forward-same-level)
7403 (org-defkey map "b" 'outline-backward-same-level)
7404 (org-defkey map "u" 'outline-up-heading))
7405 (org-defkey map "/" 'org-occur)
7406 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7407 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7408 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7409 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7410 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7411 map)))
7413 (defconst org-goto-help
7414 "Browse buffer copy, to find location or copy text.%s
7415 RET=jump to location C-g=quit and return to previous location
7416 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7418 (defvar org-goto-start-pos) ; dynamically scoped parameter
7420 (defun org-goto (&optional alternative-interface)
7421 "Look up a different location in the current file, keeping current visibility.
7423 When you want look-up or go to a different location in a
7424 document, the fastest way is often to fold the entire buffer and
7425 then dive into the tree. This method has the disadvantage, that
7426 the previous location will be folded, which may not be what you
7427 want.
7429 This command works around this by showing a copy of the current
7430 buffer in an indirect buffer, in overview mode. You can dive
7431 into the tree in that copy, use org-occur and incremental search
7432 to find a location. When pressing RET or `Q', the command
7433 returns to the original buffer in which the visibility is still
7434 unchanged. After RET it will also jump to the location selected
7435 in the indirect buffer and expose the headline hierarchy above.
7437 With a prefix argument, use the alternative interface: e.g., if
7438 `org-goto-interface' is `outline' use `outline-path-completion'."
7439 (interactive "P")
7440 (org-goto-map)
7441 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7442 (org-refile-use-outline-path t)
7443 (org-refile-target-verify-function nil)
7444 (interface
7445 (if (not alternative-interface)
7446 org-goto-interface
7447 (if (eq org-goto-interface 'outline)
7448 'outline-path-completion
7449 'outline)))
7450 (org-goto-start-pos (point))
7451 (selected-point
7452 (if (eq interface 'outline)
7453 (car (org-get-location (current-buffer) org-goto-help))
7454 (let ((pa (org-refile-get-location "Goto")))
7455 (org-refile-check-position pa)
7456 (nth 3 pa)))))
7457 (if selected-point
7458 (progn
7459 (org-mark-ring-push org-goto-start-pos)
7460 (goto-char selected-point)
7461 (when (or (org-invisible-p) (org-invisible-p2))
7462 (org-show-context 'org-goto)))
7463 (message "Quit"))))
7465 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7466 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7467 (defvar org-goto-local-auto-isearch-map) ; defined below
7469 (defun org-get-location (_buf help)
7470 "Let the user select a location in current buffer.
7471 This function uses a recursive edit. It returns the selected position
7472 or nil."
7473 (org-no-popups
7474 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7475 (isearch-hide-immediately nil)
7476 (isearch-search-fun-function
7477 (lambda () 'org-goto-local-search-headings))
7478 (org-goto-selected-point org-goto-exit-command))
7479 (save-excursion
7480 (save-window-excursion
7481 (delete-other-windows)
7482 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7483 (pop-to-buffer-same-window
7484 (condition-case nil
7485 (make-indirect-buffer (current-buffer) "*org-goto*")
7486 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7487 (with-output-to-temp-buffer "*Org Help*"
7488 (princ (format help (if org-goto-auto-isearch
7489 " Just type for auto-isearch."
7490 " n/p/f/b/u to navigate, q to quit."))))
7491 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7492 (setq buffer-read-only nil)
7493 (let ((org-startup-truncated t)
7494 (org-startup-folded nil)
7495 (org-startup-align-all-tables nil))
7496 (org-mode)
7497 (org-overview))
7498 (setq buffer-read-only t)
7499 (if (and (boundp 'org-goto-start-pos)
7500 (integer-or-marker-p org-goto-start-pos))
7501 (progn (goto-char org-goto-start-pos)
7502 (when (org-invisible-p)
7503 (org-show-set-visibility 'lineage)))
7504 (goto-char (point-min)))
7505 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7506 (message "Select location and press RET")
7507 (use-local-map org-goto-map)
7508 (recursive-edit)))
7509 (kill-buffer "*org-goto*")
7510 (cons org-goto-selected-point org-goto-exit-command))))
7512 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7513 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7514 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7515 (if (fboundp 'isearch-other-control-char)
7516 (progn
7517 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7518 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7519 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7520 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7521 (define-key org-goto-local-auto-isearch-map [return] nil))
7523 (defun org-goto-local-search-headings (string bound noerror)
7524 "Search and make sure that any matches are in headlines."
7525 (catch 'return
7526 (while (if isearch-forward
7527 (search-forward string bound noerror)
7528 (search-backward string bound noerror))
7529 (when (save-match-data
7530 (and (save-excursion
7531 (beginning-of-line)
7532 (looking-at org-complex-heading-regexp))
7533 (or (not (match-beginning 5))
7534 (< (point) (match-beginning 5)))))
7535 (throw 'return (point))))))
7537 (defun org-goto-local-auto-isearch ()
7538 "Start isearch."
7539 (interactive)
7540 (goto-char (point-min))
7541 (let ((keys (this-command-keys)))
7542 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7543 (isearch-mode t)
7544 (isearch-process-search-char (string-to-char keys)))))
7546 (defun org-goto-ret (&optional _arg)
7547 "Finish `org-goto' by going to the new location."
7548 (interactive "P")
7549 (setq org-goto-selected-point (point))
7550 (setq org-goto-exit-command 'return)
7551 (throw 'exit nil))
7553 (defun org-goto-left ()
7554 "Finish `org-goto' by going to the new location."
7555 (interactive)
7556 (if (org-at-heading-p)
7557 (progn
7558 (beginning-of-line 1)
7559 (setq org-goto-selected-point (point)
7560 org-goto-exit-command 'left)
7561 (throw 'exit nil))
7562 (user-error "Not on a heading")))
7564 (defun org-goto-right ()
7565 "Finish `org-goto' by going to the new location."
7566 (interactive)
7567 (if (org-at-heading-p)
7568 (progn
7569 (setq org-goto-selected-point (point)
7570 org-goto-exit-command 'right)
7571 (throw 'exit nil))
7572 (user-error "Not on a heading")))
7574 (defun org-goto-quit ()
7575 "Finish `org-goto' without cursor motion."
7576 (interactive)
7577 (setq org-goto-selected-point nil)
7578 (setq org-goto-exit-command 'quit)
7579 (throw 'exit nil))
7581 ;;; Indirect buffer display of subtrees
7583 (defvar org-indirect-dedicated-frame nil
7584 "This is the frame being used for indirect tree display.")
7585 (defvar org-last-indirect-buffer nil)
7587 (defun org-tree-to-indirect-buffer (&optional arg)
7588 "Create indirect buffer and narrow it to current subtree.
7590 With a numerical prefix ARG, go up to this level and then take that tree.
7591 If ARG is negative, go up that many levels.
7593 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7594 indirect buffer previously made with this command, to avoid proliferation of
7595 indirect buffers. However, when you call the command with a \
7596 `\\[universal-argument]' prefix, or
7597 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7598 so that you can work with several indirect buffers at the same time. If
7599 `org-indirect-buffer-display' is `dedicated-frame', the \
7600 `\\[universal-argument]' prefix also
7601 requests that a new frame be made for the new buffer, so that the dedicated
7602 frame is not changed."
7603 (interactive "P")
7604 (let ((cbuf (current-buffer))
7605 (cwin (selected-window))
7606 (pos (point))
7607 beg end level heading ibuf)
7608 (save-excursion
7609 (org-back-to-heading t)
7610 (when (numberp arg)
7611 (setq level (org-outline-level))
7612 (when (< arg 0) (setq arg (+ level arg)))
7613 (while (> (setq level (org-outline-level)) arg)
7614 (org-up-heading-safe)))
7615 (setq beg (point)
7616 heading (org-get-heading 'no-tags))
7617 (org-end-of-subtree t t)
7618 (when (org-at-heading-p) (backward-char 1))
7619 (setq end (point)))
7620 (when (and (buffer-live-p org-last-indirect-buffer)
7621 (not (eq org-indirect-buffer-display 'new-frame))
7622 (not arg))
7623 (kill-buffer org-last-indirect-buffer))
7624 (setq ibuf (org-get-indirect-buffer cbuf heading)
7625 org-last-indirect-buffer ibuf)
7626 (cond
7627 ((or (eq org-indirect-buffer-display 'new-frame)
7628 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7629 (select-frame (make-frame))
7630 (delete-other-windows)
7631 (pop-to-buffer-same-window ibuf)
7632 (org-set-frame-title heading))
7633 ((eq org-indirect-buffer-display 'dedicated-frame)
7634 (raise-frame
7635 (select-frame (or (and org-indirect-dedicated-frame
7636 (frame-live-p org-indirect-dedicated-frame)
7637 org-indirect-dedicated-frame)
7638 (setq org-indirect-dedicated-frame (make-frame)))))
7639 (delete-other-windows)
7640 (pop-to-buffer-same-window ibuf)
7641 (org-set-frame-title (concat "Indirect: " heading)))
7642 ((eq org-indirect-buffer-display 'current-window)
7643 (pop-to-buffer-same-window ibuf))
7644 ((eq org-indirect-buffer-display 'other-window)
7645 (pop-to-buffer ibuf))
7646 (t (error "Invalid value")))
7647 (narrow-to-region beg end)
7648 (outline-show-all)
7649 (goto-char pos)
7650 (run-hook-with-args 'org-cycle-hook 'all)
7651 (and (window-live-p cwin) (select-window cwin))))
7653 (defun org-get-indirect-buffer (&optional buffer heading)
7654 (setq buffer (or buffer (current-buffer)))
7655 (let ((n 1) (base (buffer-name buffer)) bname)
7656 (while (buffer-live-p
7657 (get-buffer
7658 (setq bname
7659 (concat base "-"
7660 (if heading (concat heading "-" (number-to-string n))
7661 (number-to-string n))))))
7662 (setq n (1+ n)))
7663 (condition-case nil
7664 (make-indirect-buffer buffer bname 'clone)
7665 (error (make-indirect-buffer buffer bname)))))
7667 (defun org-set-frame-title (title)
7668 "Set the title of the current frame to the string TITLE."
7669 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7671 ;;;; Structure editing
7673 ;;; Inserting headlines
7675 (defun org--line-empty-p (n)
7676 "Is the Nth next line empty?
7678 Counts the current line as N = 1 and the previous line as N = 0;
7679 see `beginning-of-line'."
7680 (save-excursion
7681 (and (not (bobp))
7682 (or (beginning-of-line n) t)
7683 (save-match-data
7684 (looking-at "[ \t]*$")))))
7686 (defun org-previous-line-empty-p ()
7687 "Is the previous line a blank line?
7688 When NEXT is non-nil, check the next line instead."
7689 (org--line-empty-p 0))
7691 (defun org-next-line-empty-p ()
7692 "Is the previous line a blank line?
7693 When NEXT is non-nil, check the next line instead."
7694 (org--line-empty-p 2))
7696 (defun org--blank-before-heading-p (&optional parent)
7697 "Non-nil when an empty line should precede a new heading here.
7698 When optional argument PARENT is non-nil, consider parent
7699 headline instead of current one."
7700 (pcase (assq 'heading org-blank-before-new-entry)
7701 (`(heading . auto)
7702 (save-excursion
7703 (org-with-limited-levels
7704 (unless (and (org-before-first-heading-p)
7705 (not (outline-next-heading)))
7706 (org-back-to-heading t)
7707 (when parent (org-up-heading-safe))
7708 (cond ((not (bobp))
7709 (org-previous-line-empty-p))
7710 ((outline-next-heading)
7711 (org-previous-line-empty-p))
7712 ;; Ignore trailing spaces on last buffer line.
7713 ((progn (skip-chars-backward " \t") (bolp))
7714 (org-previous-line-empty-p))
7715 (t nil))))))
7716 (`(heading . ,value) value)
7717 (_ nil)))
7719 (defun org-insert-heading (&optional arg invisible-ok top)
7720 "Insert a new heading or an item with the same depth at point.
7722 If point is at the beginning of a heading, insert a new heading
7723 or a new headline above the current one. When at the beginning
7724 of a regular line of text, turn it into a heading.
7726 If point is in the middle of a line, split it and create a new
7727 headline with the text in the current line after point (see
7728 `org-M-RET-may-split-line' on how to modify this behavior). As
7729 a special case, on a headline, splitting can only happen on the
7730 title itself. E.g., this excludes breaking stars or tags.
7732 With a `\\[universal-argument]' prefix, set \
7733 `org-insert-heading-respect-content' to
7734 a non-nil value for the duration of the command. This forces the
7735 insertion of a heading after the current subtree, independently
7736 on the location of point.
7738 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7739 insert the heading at the end of the tree
7740 above the current heading. For example, if point is within a
7741 2nd-level heading, then it will insert a 2nd-level heading at
7742 the end of the 1st-level parent subtree.
7744 When INVISIBLE-OK is set, stop at invisible headlines when going
7745 back. This is important for non-interactive uses of the
7746 command.
7748 When optional argument TOP is non-nil, insert a level 1 heading,
7749 unconditionally."
7750 (interactive "P")
7751 (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
7752 (level (org-current-level))
7753 (stars (make-string (if (and level (not top)) level 1) ?*)))
7754 (cond
7755 ((or org-insert-heading-respect-content
7756 (member arg '((4) (16)))
7757 (and (not invisible-ok)
7758 (invisible-p (max (1- (point)) (point-min)))))
7759 ;; Position point at the location of insertion.
7760 (if (not level) ;before first headline
7761 (org-with-limited-levels (outline-next-heading))
7762 ;; Make sure we end up on a visible headline if INVISIBLE-OK
7763 ;; is nil.
7764 (org-with-limited-levels (org-back-to-heading invisible-ok))
7765 (cond ((equal arg '(16))
7766 (org-up-heading-safe)
7767 (org-end-of-subtree t t))
7769 (org-end-of-subtree t t))))
7770 (unless (bolp) (insert "\n")) ;ensure final newline
7771 (unless (and blank? (org-previous-line-empty-p))
7772 (org-N-empty-lines-before-current (if blank? 1 0)))
7773 (insert stars " \n")
7774 (forward-char -1))
7775 ;; At a headline...
7776 ((org-at-heading-p)
7777 (cond ((bolp)
7778 (when blank? (save-excursion (insert "\n")))
7779 (save-excursion (insert stars " \n"))
7780 (unless (and blank? (org-previous-line-empty-p))
7781 (org-N-empty-lines-before-current (if blank? 1 0)))
7782 (end-of-line))
7783 ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
7784 (org-match-line org-complex-heading-regexp)
7785 (org-pos-in-match-range (point) 4))
7786 ;; Grab the text that should moved to the new headline.
7787 ;; Preserve tags.
7788 (let ((split (delete-and-extract-region (point) (match-end 4))))
7789 (if (looking-at "[ \t]*$") (replace-match "")
7790 (org-set-tags nil t))
7791 (end-of-line)
7792 (when blank? (insert "\n"))
7793 (insert "\n" stars " ")
7794 (when (org-string-nw-p split) (insert split))
7795 (when (eobp) (save-excursion (insert "\n")))))
7797 (end-of-line)
7798 (when blank? (insert "\n"))
7799 (insert "\n" stars " ")
7800 (when (eobp) (save-excursion (insert "\n"))))))
7801 ;; On regular text, turn line into a headline or split, if
7802 ;; appropriate.
7803 ((bolp)
7804 (insert stars " ")
7805 (unless (and blank? (org-previous-line-empty-p))
7806 (org-N-empty-lines-before-current (if blank? 1 0))))
7808 (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
7809 (end-of-line))
7810 (insert "\n" stars " ")
7811 (unless (and blank? (org-previous-line-empty-p))
7812 (org-N-empty-lines-before-current (if blank? 1 0))))))
7813 (run-hooks 'org-insert-heading-hook))
7815 (defun org-N-empty-lines-before-current (n)
7816 "Make the number of empty lines before current exactly N.
7817 So this will delete or add empty lines."
7818 (let ((column (current-column)))
7819 (beginning-of-line)
7820 (unless (bobp)
7821 (let ((start (save-excursion
7822 (skip-chars-backward " \r\t\n")
7823 (line-end-position))))
7824 (delete-region start (line-end-position 0))))
7825 (insert (make-string n ?\n))
7826 (move-to-column column)))
7828 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
7829 "Return the heading of the current entry, without the stars.
7830 When NO-TAGS is non-nil, don't include tags.
7831 When NO-TODO is non-nil, don't include TODO keywords.
7832 When NO-PRIORITY is non-nil, don't include priority cookie.
7833 When NO-COMMENT is non-nil, don't include COMMENT string."
7834 (save-excursion
7835 (org-back-to-heading t)
7836 (let ((case-fold-search nil))
7837 (looking-at org-complex-heading-regexp)
7838 (let ((todo (and (not no-todo) (match-string 2)))
7839 (priority (and (not no-priority) (match-string 3)))
7840 (headline (pcase (match-string 4)
7841 (`nil "")
7842 ((and (guard no-comment) h)
7843 (replace-regexp-in-string
7844 (eval-when-compile
7845 (format "\\`%s[ \t]+" org-comment-string))
7846 "" h))
7847 (h h)))
7848 (tags (and (not no-tags) (match-string 5))))
7849 (mapconcat #'identity
7850 (delq nil (list todo priority headline tags))
7851 " ")))))
7853 (defvar orgstruct-mode) ; defined below
7855 (defun org-heading-components ()
7856 "Return the components of the current heading.
7857 This is a list with the following elements:
7858 - the level as an integer
7859 - the reduced level, different if `org-odd-levels-only' is set.
7860 - the TODO keyword, or nil
7861 - the priority character, like ?A, or nil if no priority is given
7862 - the headline text itself, or the tags string if no headline text
7863 - the tags string, or nil."
7864 (save-excursion
7865 (org-back-to-heading t)
7866 (when (let (case-fold-search)
7867 (looking-at
7868 (if orgstruct-mode
7869 org-heading-regexp
7870 org-complex-heading-regexp)))
7871 (if orgstruct-mode
7872 (list (length (match-string 1))
7873 (org-reduced-level (length (match-string 1)))
7876 (match-string 2)
7877 nil)
7878 (list (length (match-string 1))
7879 (org-reduced-level (length (match-string 1)))
7880 (match-string-no-properties 2)
7881 (and (match-end 3) (aref (match-string 3) 2))
7882 (match-string-no-properties 4)
7883 (match-string-no-properties 5))))))
7885 (defun org-get-entry ()
7886 "Get the entry text, after heading, entire subtree."
7887 (save-excursion
7888 (org-back-to-heading t)
7889 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7891 (defun org-edit-headline (&optional heading)
7892 "Edit the current headline.
7893 Set it to HEADING when provided."
7894 (interactive)
7895 (org-with-wide-buffer
7896 (org-back-to-heading t)
7897 (let ((case-fold-search nil))
7898 (when (looking-at org-complex-heading-regexp)
7899 (let* ((old (match-string-no-properties 4))
7900 (new (save-match-data
7901 (org-trim (or heading (read-string "Edit: " old))))))
7902 (unless (equal old new)
7903 (if old (replace-match new t t nil 4)
7904 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7905 (insert " " new))
7906 (org-set-tags nil t)
7907 (when (looking-at "[ \t]*$") (replace-match ""))))))))
7909 (defun org-insert-heading-after-current ()
7910 "Insert a new heading with same level as current, after current subtree."
7911 (interactive)
7912 (org-back-to-heading)
7913 (org-insert-heading)
7914 (org-move-subtree-down)
7915 (end-of-line 1))
7917 (defun org-insert-heading-respect-content (&optional invisible-ok)
7918 "Insert heading with `org-insert-heading-respect-content' set to t."
7919 (interactive)
7920 (org-insert-heading '(4) invisible-ok))
7922 (defun org-insert-todo-heading-respect-content (&optional force-state)
7923 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7924 (interactive)
7925 (org-insert-todo-heading force-state '(4)))
7927 (defun org-insert-todo-heading (arg &optional force-heading)
7928 "Insert a new heading with the same level and TODO state as current heading.
7930 If the heading has no TODO state, or if the state is DONE, use
7931 the first state (TODO by default). Also with one prefix arg,
7932 force first state. With two prefix args, force inserting at the
7933 end of the parent subtree.
7935 When called at a plain list item, insert a new item with an
7936 unchecked check box."
7937 (interactive "P")
7938 (when (or force-heading (not (org-insert-item 'checkbox)))
7939 (org-insert-heading (or (and (equal arg '(16)) '(16))
7940 force-heading))
7941 (save-excursion
7942 (org-back-to-heading)
7943 (outline-previous-heading)
7944 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
7945 (let* ((new-mark-x
7946 (if (or (equal arg '(4))
7947 (not (match-beginning 2))
7948 (member (match-string 2) org-done-keywords))
7949 (car org-todo-keywords-1)
7950 (match-string 2)))
7951 (new-mark
7953 (run-hook-with-args-until-success
7954 'org-todo-get-default-hook new-mark-x nil)
7955 new-mark-x)))
7956 (beginning-of-line 1)
7957 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7958 (if org-treat-insert-todo-heading-as-state-change
7959 (org-todo new-mark)
7960 (insert new-mark " "))))
7961 (when org-provide-todo-statistics
7962 (org-update-parent-todo-statistics))))
7964 (defun org-insert-subheading (arg)
7965 "Insert a new subheading and demote it.
7966 Works for outline headings and for plain lists alike."
7967 (interactive "P")
7968 (org-insert-heading arg)
7969 (cond
7970 ((org-at-heading-p) (org-do-demote))
7971 ((org-at-item-p) (org-indent-item))))
7973 (defun org-insert-todo-subheading (arg)
7974 "Insert a new subheading with TODO keyword or checkbox and demote it.
7975 Works for outline headings and for plain lists alike."
7976 (interactive "P")
7977 (org-insert-todo-heading arg)
7978 (cond
7979 ((org-at-heading-p) (org-do-demote))
7980 ((org-at-item-p) (org-indent-item))))
7982 ;;; Promotion and Demotion
7984 (defvar org-after-demote-entry-hook nil
7985 "Hook run after an entry has been demoted.
7986 The cursor will be at the beginning of the entry.
7987 When a subtree is being demoted, the hook will be called for each node.")
7989 (defvar org-after-promote-entry-hook nil
7990 "Hook run after an entry has been promoted.
7991 The cursor will be at the beginning of the entry.
7992 When a subtree is being promoted, the hook will be called for each node.")
7994 (defun org-promote-subtree ()
7995 "Promote the entire subtree.
7996 See also `org-promote'."
7997 (interactive)
7998 (save-excursion
7999 (org-with-limited-levels (org-map-tree 'org-promote)))
8000 (org-fix-position-after-promote))
8002 (defun org-demote-subtree ()
8003 "Demote the entire subtree.
8004 See `org-demote' and `org-promote'."
8005 (interactive)
8006 (save-excursion
8007 (org-with-limited-levels (org-map-tree 'org-demote)))
8008 (org-fix-position-after-promote))
8010 (defun org-do-promote ()
8011 "Promote the current heading higher up the tree.
8012 If the region is active in `transient-mark-mode', promote all
8013 headings in the region."
8014 (interactive)
8015 (save-excursion
8016 (if (org-region-active-p)
8017 (org-map-region 'org-promote (region-beginning) (region-end))
8018 (org-promote)))
8019 (org-fix-position-after-promote))
8021 (defun org-do-demote ()
8022 "Demote the current heading lower down the tree.
8023 If the region is active in `transient-mark-mode', demote all
8024 headings in the region."
8025 (interactive)
8026 (save-excursion
8027 (if (org-region-active-p)
8028 (org-map-region 'org-demote (region-beginning) (region-end))
8029 (org-demote)))
8030 (org-fix-position-after-promote))
8032 (defun org-fix-position-after-promote ()
8033 "Fix cursor position and indentation after demoting/promoting."
8034 (let ((pos (point)))
8035 (when (save-excursion
8036 (beginning-of-line)
8037 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8038 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8039 (cond ((eobp) (insert " "))
8040 ((eolp) (insert " "))
8041 ((equal (char-after) ?\s) (forward-char 1))))))
8043 (defun org-current-level ()
8044 "Return the level of the current entry, or nil if before the first headline.
8045 The level is the number of stars at the beginning of the
8046 headline. Use `org-reduced-level' to remove the effect of
8047 `org-odd-levels'. Unlike to `org-outline-level', this function
8048 ignores inlinetasks."
8049 (let ((level (org-with-limited-levels (org-outline-level))))
8050 (and (> level 0) level)))
8052 (defun org-get-previous-line-level ()
8053 "Return the outline depth of the last headline before the current line.
8054 Returns 0 for the first headline in the buffer, and nil if before the
8055 first headline."
8056 (and (org-current-level)
8057 (or (and (/= (line-beginning-position) (point-min))
8058 (save-excursion (beginning-of-line 0) (org-current-level)))
8059 0)))
8061 (defun org-reduced-level (l)
8062 "Compute the effective level of a heading.
8063 This takes into account the setting of `org-odd-levels-only'."
8064 (cond
8065 ((zerop l) 0)
8066 (org-odd-levels-only (1+ (floor (/ l 2))))
8067 (t l)))
8069 (defun org-level-increment ()
8070 "Return the number of stars that will be added or removed at a
8071 time to headlines when structure editing, based on the value of
8072 `org-odd-levels-only'."
8073 (if org-odd-levels-only 2 1))
8075 (defun org-get-valid-level (level &optional change)
8076 "Rectify a level change under the influence of `org-odd-levels-only'.
8077 LEVEL is a current level, CHANGE is by how much the level should
8078 be modified. Even if CHANGE is nil, LEVEL may be returned
8079 modified because even level numbers will become the next higher
8080 odd number. Returns values greater than 0."
8081 (if org-odd-levels-only
8082 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8083 ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
8084 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8085 (max 1 (+ level (or change 0)))))
8087 (defun org-promote ()
8088 "Promote the current heading higher up the tree."
8089 (org-with-wide-buffer
8090 (org-back-to-heading t)
8091 (let* ((after-change-functions (remq 'flyspell-after-change-function
8092 after-change-functions))
8093 (level (save-match-data (funcall outline-level)))
8094 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8095 (diff (abs (- level (length up-head) -1))))
8096 (cond
8097 ((and (= level 1) org-allow-promoting-top-level-subtree)
8098 (replace-match "# " nil t))
8099 ((= level 1)
8100 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8101 (t (replace-match up-head nil t)))
8102 (unless (= level 1)
8103 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8104 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8105 (run-hooks 'org-after-promote-entry-hook))))
8107 (defun org-demote ()
8108 "Demote the current heading lower down the tree."
8109 (org-with-wide-buffer
8110 (org-back-to-heading t)
8111 (let* ((after-change-functions (remq 'flyspell-after-change-function
8112 after-change-functions))
8113 (level (save-match-data (funcall outline-level)))
8114 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8115 (diff (abs (- level (length down-head) -1))))
8116 (replace-match down-head nil t)
8117 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8118 (when org-adapt-indentation (org-fixup-indentation diff))
8119 (run-hooks 'org-after-demote-entry-hook))))
8121 (defun org-cycle-level ()
8122 "Cycle the level of an empty headline through possible states.
8123 This goes first to child, then to parent, level, then up the hierarchy.
8124 After top level, it switches back to sibling level."
8125 (interactive)
8126 (let ((org-adapt-indentation nil))
8127 (when (org-point-at-end-of-empty-headline)
8128 (setq this-command 'org-cycle-level) ; Only needed for caching
8129 (let ((cur-level (org-current-level))
8130 (prev-level (org-get-previous-line-level)))
8131 (cond
8132 ;; If first headline in file, promote to top-level.
8133 ((= prev-level 0)
8134 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8135 do (org-do-promote)))
8136 ;; If same level as prev, demote one.
8137 ((= prev-level cur-level)
8138 (org-do-demote))
8139 ;; If parent is top-level, promote to top level if not already.
8140 ((= prev-level 1)
8141 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8142 do (org-do-promote)))
8143 ;; If top-level, return to prev-level.
8144 ((= cur-level 1)
8145 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8146 do (org-do-demote)))
8147 ;; If less than prev-level, promote one.
8148 ((< cur-level prev-level)
8149 (org-do-promote))
8150 ;; If deeper than prev-level, promote until higher than
8151 ;; prev-level.
8152 ((> cur-level prev-level)
8153 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8154 do (org-do-promote))))
8155 t))))
8157 (defun org-map-tree (fun)
8158 "Call FUN for every heading underneath the current one."
8159 (org-back-to-heading t)
8160 (let ((level (funcall outline-level)))
8161 (save-excursion
8162 (funcall fun)
8163 (while (and (progn
8164 (outline-next-heading)
8165 (> (funcall outline-level) level))
8166 (not (eobp)))
8167 (funcall fun)))))
8169 (defun org-map-region (fun beg end)
8170 "Call FUN for every heading between BEG and END."
8171 (let ((org-ignore-region t))
8172 (save-excursion
8173 (setq end (copy-marker end))
8174 (goto-char beg)
8175 (when (and (re-search-forward org-outline-regexp-bol nil t)
8176 (< (point) end))
8177 (funcall fun))
8178 (while (and (progn
8179 (outline-next-heading)
8180 (< (point) end))
8181 (not (eobp)))
8182 (funcall fun)))))
8184 (defun org-fixup-indentation (diff)
8185 "Change the indentation in the current entry by DIFF.
8187 DIFF is an integer. Indentation is done according to the
8188 following rules:
8190 - Planning information and property drawers are always indented
8191 according to the new level of the headline;
8193 - Footnote definitions and their contents are ignored;
8195 - Inlinetasks' boundaries are not shifted;
8197 - Empty lines are ignored;
8199 - Other lines' indentation are shifted by DIFF columns, unless
8200 it would introduce a structural change in the document, in
8201 which case no shifting is done at all.
8203 Assume point is at a heading or an inlinetask beginning."
8204 (org-with-wide-buffer
8205 (narrow-to-region (line-beginning-position)
8206 (save-excursion
8207 (if (org-with-limited-levels (org-at-heading-p))
8208 (org-with-limited-levels (outline-next-heading))
8209 (org-inlinetask-goto-end))
8210 (point)))
8211 (forward-line)
8212 ;; Indent properly planning info and property drawer.
8213 (when (looking-at-p org-planning-line-re)
8214 (org-indent-line)
8215 (forward-line))
8216 (when (looking-at org-property-drawer-re)
8217 (goto-char (match-end 0))
8218 (forward-line)
8219 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8220 (catch 'no-shift
8221 (when (zerop diff) (throw 'no-shift nil))
8222 ;; If DIFF is negative, first check if a shift is possible at all
8223 ;; (e.g., it doesn't break structure). This can only happen if
8224 ;; some contents are not properly indented.
8225 (let ((case-fold-search t))
8226 (when (< diff 0)
8227 (let ((diff (- diff))
8228 (forbidden-re (concat org-outline-regexp
8229 "\\|"
8230 (substring org-footnote-definition-re 1))))
8231 (save-excursion
8232 (while (not (eobp))
8233 (cond
8234 ((looking-at-p "[ \t]*$") (forward-line))
8235 ((and (looking-at-p org-footnote-definition-re)
8236 (let ((e (org-element-at-point)))
8237 (and (eq (org-element-type e) 'footnote-definition)
8238 (goto-char (org-element-property :end e))))))
8239 ((looking-at-p org-outline-regexp) (forward-line))
8240 ;; Give up if shifting would move before column 0 or
8241 ;; if it would introduce a headline or a footnote
8242 ;; definition.
8244 (skip-chars-forward " \t")
8245 (let ((ind (current-column)))
8246 (when (or (< ind diff)
8247 (and (= ind diff) (looking-at-p forbidden-re)))
8248 (throw 'no-shift nil)))
8249 ;; Ignore contents of example blocks and source
8250 ;; blocks if their indentation is meant to be
8251 ;; preserved. Jump to block's closing line.
8252 (beginning-of-line)
8253 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8254 (let ((e (org-element-at-point)))
8255 (and (memq (org-element-type e)
8256 '(example-block src-block))
8257 (or org-src-preserve-indentation
8258 (org-element-property :preserve-indent e))
8259 (goto-char (org-element-property :end e))
8260 (progn (skip-chars-backward " \r\t\n")
8261 (beginning-of-line)
8262 t))))
8263 (forward-line))))))))
8264 ;; Shift lines but footnote definitions, inlinetasks boundaries
8265 ;; by DIFF. Also skip contents of source or example blocks
8266 ;; when indentation is meant to be preserved.
8267 (while (not (eobp))
8268 (cond
8269 ((and (looking-at-p org-footnote-definition-re)
8270 (let ((e (org-element-at-point)))
8271 (and (eq (org-element-type e) 'footnote-definition)
8272 (goto-char (org-element-property :end e))))))
8273 ((looking-at-p org-outline-regexp) (forward-line))
8274 ((looking-at-p "[ \t]*$") (forward-line))
8276 (indent-line-to (+ (org-get-indentation) diff))
8277 (beginning-of-line)
8278 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8279 (let ((e (org-element-at-point)))
8280 (and (memq (org-element-type e)
8281 '(example-block src-block))
8282 (or org-src-preserve-indentation
8283 (org-element-property :preserve-indent e))
8284 (goto-char (org-element-property :end e))
8285 (progn (skip-chars-backward " \r\t\n")
8286 (beginning-of-line)
8287 t))))
8288 (forward-line)))))))))
8290 (defun org-convert-to-odd-levels ()
8291 "Convert an Org file with all levels allowed to one with odd levels.
8292 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8293 level 5 etc."
8294 (interactive)
8295 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8296 (let ((outline-level 'org-outline-level)
8297 (org-odd-levels-only nil) n)
8298 (save-excursion
8299 (goto-char (point-min))
8300 (while (re-search-forward "^\\*\\*+ " nil t)
8301 (setq n (- (length (match-string 0)) 2))
8302 (while (>= (setq n (1- n)) 0)
8303 (org-demote))
8304 (end-of-line 1))))))
8306 (defun org-convert-to-oddeven-levels ()
8307 "Convert an Org file with only odd levels to one with odd/even levels.
8308 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8309 file contains a section with an even level, conversion would
8310 destroy the structure of the file. An error is signaled in this
8311 case."
8312 (interactive)
8313 (goto-char (point-min))
8314 ;; First check if there are no even levels
8315 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8316 (org-show-set-visibility 'canonical)
8317 (error "Not all levels are odd in this file. Conversion not possible"))
8318 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8319 (let ((outline-regexp org-outline-regexp)
8320 (outline-level 'org-outline-level)
8321 (org-odd-levels-only nil) n)
8322 (save-excursion
8323 (goto-char (point-min))
8324 (while (re-search-forward "^\\*\\*+ " nil t)
8325 (setq n (/ (1- (length (match-string 0))) 2))
8326 (while (>= (setq n (1- n)) 0)
8327 (org-promote))
8328 (end-of-line 1))))))
8330 (defun org-tr-level (n)
8331 "Make N odd if required."
8332 (if org-odd-levels-only (1+ (/ n 2)) n))
8334 ;;; Vertical tree motion, cutting and pasting of subtrees
8336 (defun org-move-subtree-up (&optional arg)
8337 "Move the current subtree up past ARG headlines of the same level."
8338 (interactive "p")
8339 (org-move-subtree-down (- (prefix-numeric-value arg))))
8341 (defun org-move-subtree-down (&optional arg)
8342 "Move the current subtree down past ARG headlines of the same level."
8343 (interactive "p")
8344 (setq arg (prefix-numeric-value arg))
8345 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8346 'org-get-last-sibling))
8347 (ins-point (make-marker))
8348 (cnt (abs arg))
8349 (col (current-column))
8350 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8351 ;; Select the tree
8352 (org-back-to-heading)
8353 (setq beg0 (point))
8354 (save-excursion
8355 (setq ne-beg (org-back-over-empty-lines))
8356 (setq beg (point)))
8357 (save-match-data
8358 (save-excursion (outline-end-of-heading)
8359 (setq folded (org-invisible-p)))
8360 (progn (org-end-of-subtree nil t)
8361 (unless (eobp) (backward-char))))
8362 (outline-next-heading)
8363 (setq ne-end (org-back-over-empty-lines))
8364 (setq end (point))
8365 (goto-char beg0)
8366 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8367 ;; include less whitespace
8368 (save-excursion
8369 (goto-char beg)
8370 (forward-line (- ne-beg ne-end))
8371 (setq beg (point))))
8372 ;; Find insertion point, with error handling
8373 (while (> cnt 0)
8374 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8375 (progn (goto-char beg0)
8376 (user-error "Cannot move past superior level or buffer limit")))
8377 (setq cnt (1- cnt)))
8378 (when (> arg 0)
8379 ;; Moving forward - still need to move over subtree
8380 (org-end-of-subtree t t)
8381 (save-excursion
8382 (org-back-over-empty-lines)
8383 (or (bolp) (newline))))
8384 (setq ne-ins (org-back-over-empty-lines))
8385 (move-marker ins-point (point))
8386 (setq txt (buffer-substring beg end))
8387 (org-save-markers-in-region beg end)
8388 (delete-region beg end)
8389 (org-remove-empty-overlays-at beg)
8390 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8391 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8392 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8393 (let ((bbb (point)))
8394 (insert-before-markers txt)
8395 (org-reinstall-markers-in-region bbb)
8396 (move-marker ins-point bbb))
8397 (or (bolp) (insert "\n"))
8398 (setq ins-end (point))
8399 (goto-char ins-point)
8400 (org-skip-whitespace)
8401 (when (and (< arg 0)
8402 (org-first-sibling-p)
8403 (> ne-ins ne-beg))
8404 ;; Move whitespace back to beginning
8405 (save-excursion
8406 (goto-char ins-end)
8407 (let ((kill-whole-line t))
8408 (kill-line (- ne-ins ne-beg)) (point)))
8409 (insert (make-string (- ne-ins ne-beg) ?\n)))
8410 (move-marker ins-point nil)
8411 (if folded
8412 (outline-hide-subtree)
8413 (org-show-entry)
8414 (org-show-children)
8415 (org-cycle-hide-drawers 'children))
8416 (org-clean-visibility-after-subtree-move)
8417 ;; move back to the initial column we were at
8418 (move-to-column col)))
8420 (defvar org-subtree-clip ""
8421 "Clipboard for cut and paste of subtrees.
8422 This is actually only a copy of the kill, because we use the normal kill
8423 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8425 (defvar org-subtree-clip-folded nil
8426 "Was the last copied subtree folded?
8427 This is used to fold the tree back after pasting.")
8429 (defun org-cut-subtree (&optional n)
8430 "Cut the current subtree into the clipboard.
8431 With prefix arg N, cut this many sequential subtrees.
8432 This is a short-hand for marking the subtree and then cutting it."
8433 (interactive "p")
8434 (org-copy-subtree n 'cut))
8436 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8437 "Copy the current subtree it in the clipboard.
8438 With prefix arg N, copy this many sequential subtrees.
8439 This is a short-hand for marking the subtree and then copying it.
8440 If CUT is non-nil, actually cut the subtree.
8441 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8442 of some markers in the region, even if CUT is non-nil. This is
8443 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8444 (interactive "p")
8445 (let (beg end folded (beg0 (point)))
8446 (if (called-interactively-p 'any)
8447 (org-back-to-heading nil) ; take what looks like a subtree
8448 (org-back-to-heading t)) ; take what is really there
8449 (setq beg (point))
8450 (skip-chars-forward " \t\r\n")
8451 (save-match-data
8452 (if nosubtrees
8453 (outline-next-heading)
8454 (save-excursion (outline-end-of-heading)
8455 (setq folded (org-invisible-p)))
8456 (ignore-errors (org-forward-heading-same-level (1- n) t))
8457 (org-end-of-subtree t t)))
8458 ;; Include the end of an inlinetask
8459 (when (and (featurep 'org-inlinetask)
8460 (looking-at-p (concat (org-inlinetask-outline-regexp)
8461 "END[ \t]*$")))
8462 (end-of-line))
8463 (setq end (point))
8464 (goto-char beg0)
8465 (when (> end beg)
8466 (setq org-subtree-clip-folded folded)
8467 (when (or cut force-store-markers)
8468 (org-save-markers-in-region beg end))
8469 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8470 (setq org-subtree-clip (current-kill 0))
8471 (message "%s: Subtree(s) with %d characters"
8472 (if cut "Cut" "Copied")
8473 (length org-subtree-clip)))))
8475 (defun org-paste-subtree (&optional level tree for-yank remove)
8476 "Paste the clipboard as a subtree, with modification of headline level.
8477 The entire subtree is promoted or demoted in order to match a new headline
8478 level.
8480 If the cursor is at the beginning of a headline, the same level as
8481 that headline is used to paste the tree.
8483 If not, the new level is derived from the *visible* headings
8484 before and after the insertion point, and taken to be the inferior headline
8485 level of the two. So if the previous visible heading is level 3 and the
8486 next is level 4 (or vice versa), level 4 will be used for insertion.
8487 This makes sure that the subtree remains an independent subtree and does
8488 not swallow low level entries.
8490 You can also force a different level, either by using a numeric prefix
8491 argument, or by inserting the heading marker by hand. For example, if the
8492 cursor is after \"*****\", then the tree will be shifted to level 5.
8494 If optional TREE is given, use this text instead of the kill ring.
8496 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8497 move back over whitespace before inserting, and move point to the end of
8498 the inserted text when done.
8500 When REMOVE is non-nil, remove the subtree from the clipboard."
8501 (interactive "P")
8502 (setq tree (or tree (and kill-ring (current-kill 0))))
8503 (unless (org-kill-is-subtree-p tree)
8504 (user-error "%s"
8505 (substitute-command-keys
8506 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8507 (org-with-limited-levels
8508 (let* ((visp (not (org-invisible-p)))
8509 (txt tree)
8510 (^re_ "\\(\\*+\\)[ \t]*")
8511 (old-level (if (string-match org-outline-regexp-bol txt)
8512 (- (match-end 0) (match-beginning 0) 1)
8513 -1))
8514 (force-level (cond (level (prefix-numeric-value level))
8515 ((and (looking-at "[ \t]*$")
8516 (string-match
8517 "^\\*+$" (buffer-substring
8518 (point-at-bol) (point))))
8519 (- (match-end 0) (match-beginning 0)))
8520 ((and (bolp)
8521 (looking-at org-outline-regexp))
8522 (- (match-end 0) (point) 1))))
8523 (previous-level (save-excursion
8524 (condition-case nil
8525 (progn
8526 (outline-previous-visible-heading 1)
8527 (if (looking-at ^re_)
8528 (- (match-end 0) (match-beginning 0) 1)
8530 (error 1))))
8531 (next-level (save-excursion
8532 (condition-case nil
8533 (progn
8534 (or (looking-at org-outline-regexp)
8535 (outline-next-visible-heading 1))
8536 (if (looking-at ^re_)
8537 (- (match-end 0) (match-beginning 0) 1)
8539 (error 1))))
8540 (new-level (or force-level (max previous-level next-level)))
8541 (shift (if (or (= old-level -1)
8542 (= new-level -1)
8543 (= old-level new-level))
8545 (- new-level old-level)))
8546 (delta (if (> shift 0) -1 1))
8547 (func (if (> shift 0) 'org-demote 'org-promote))
8548 (org-odd-levels-only nil)
8549 beg end newend)
8550 ;; Remove the forced level indicator
8551 (when force-level
8552 (delete-region (point-at-bol) (point)))
8553 ;; Paste
8554 (beginning-of-line (if (bolp) 1 2))
8555 (setq beg (point))
8556 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8557 (insert-before-markers txt)
8558 (unless (string-suffix-p "\n" txt) (insert "\n"))
8559 (setq newend (point))
8560 (org-reinstall-markers-in-region beg)
8561 (setq end (point))
8562 (goto-char beg)
8563 (skip-chars-forward " \t\n\r")
8564 (setq beg (point))
8565 (when (and (org-invisible-p) visp)
8566 (save-excursion (outline-show-heading)))
8567 ;; Shift if necessary
8568 (unless (= shift 0)
8569 (save-restriction
8570 (narrow-to-region beg end)
8571 (while (not (= shift 0))
8572 (org-map-region func (point-min) (point-max))
8573 (setq shift (+ delta shift)))
8574 (goto-char (point-min))
8575 (setq newend (point-max))))
8576 (when (or (called-interactively-p 'interactive) for-yank)
8577 (message "Clipboard pasted as level %d subtree" new-level))
8578 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8579 kill-ring
8580 (eq org-subtree-clip (current-kill 0))
8581 org-subtree-clip-folded)
8582 ;; The tree was folded before it was killed/copied
8583 (outline-hide-subtree))
8584 (and for-yank (goto-char newend))
8585 (and remove (setq kill-ring (cdr kill-ring))))))
8587 (defun org-kill-is-subtree-p (&optional txt)
8588 "Check if the current kill is an outline subtree, or a set of trees.
8589 Returns nil if kill does not start with a headline, or if the first
8590 headline level is not the largest headline level in the tree.
8591 So this will actually accept several entries of equal levels as well,
8592 which is OK for `org-paste-subtree'.
8593 If optional TXT is given, check this string instead of the current kill."
8594 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8595 (re (org-get-limited-outline-regexp))
8596 (^re (concat "^" re))
8597 (start-level (and kill
8598 (string-match
8599 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8600 kill)
8601 (- (match-end 2) (match-beginning 2) 1)))
8602 (start (1+ (or (match-beginning 2) -1))))
8603 (if (not start-level)
8604 (progn
8605 nil) ;; does not even start with a heading
8606 (catch 'exit
8607 (while (setq start (string-match ^re kill (1+ start)))
8608 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8609 (throw 'exit nil)))
8610 t))))
8612 (defvar org-markers-to-move nil
8613 "Markers that should be moved with a cut-and-paste operation.
8614 Those markers are stored together with their positions relative to
8615 the start of the region.")
8617 (defun org-save-markers-in-region (beg end)
8618 "Check markers in region.
8619 If these markers are between BEG and END, record their position relative
8620 to BEG, so that after moving the block of text, we can put the markers back
8621 into place.
8622 This function gets called just before an entry or tree gets cut from the
8623 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8624 called immediately, to move the markers with the entries."
8625 (setq org-markers-to-move nil)
8626 (when (featurep 'org-clock)
8627 (org-clock-save-markers-for-cut-and-paste beg end))
8628 (when (featurep 'org-agenda)
8629 (org-agenda-save-markers-for-cut-and-paste beg end)))
8631 (defun org-check-and-save-marker (marker beg end)
8632 "Check if MARKER is between BEG and END.
8633 If yes, remember the marker and the distance to BEG."
8634 (when (and (marker-buffer marker)
8635 (equal (marker-buffer marker) (current-buffer))
8636 (>= marker beg) (< marker end))
8637 (push (cons marker (- marker beg)) org-markers-to-move)))
8639 (defun org-reinstall-markers-in-region (beg)
8640 "Move all remembered markers to their position relative to BEG."
8641 (dolist (x org-markers-to-move)
8642 (move-marker (car x) (+ beg (cdr x))))
8643 (setq org-markers-to-move nil))
8645 (defun org-narrow-to-subtree ()
8646 "Narrow buffer to the current subtree."
8647 (interactive)
8648 (save-excursion
8649 (save-match-data
8650 (org-with-limited-levels
8651 (narrow-to-region
8652 (progn (org-back-to-heading t) (point))
8653 (progn (org-end-of-subtree t t)
8654 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8655 (point)))))))
8657 (defun org-narrow-to-block ()
8658 "Narrow buffer to the current block."
8659 (interactive)
8660 (let* ((case-fold-search t)
8661 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8662 "^[ \t]*#\\+end_.*")))
8663 (if blockp
8664 (narrow-to-region (car blockp) (cdr blockp))
8665 (user-error "Not in a block"))))
8667 (defun org-clone-subtree-with-time-shift (n &optional shift)
8668 "Clone the task (subtree) at point N times.
8669 The clones will be inserted as siblings.
8671 In interactive use, the user will be prompted for the number of
8672 clones to be produced. If the entry has a timestamp, the user
8673 will also be prompted for a time shift, which may be a repeater
8674 as used in time stamps, for example `+3d'. To disable this,
8675 you can call the function with a universal prefix argument.
8677 When a valid repeater is given and the entry contains any time
8678 stamps, the clones will become a sequence in time, with time
8679 stamps in the subtree shifted for each clone produced. If SHIFT
8680 is nil or the empty string, time stamps will be left alone. The
8681 ID property of the original subtree is removed.
8683 In each clone, all the CLOCK entries will be removed. This
8684 prevents Org from considering that the clocked times overlap.
8686 If the original subtree did contain time stamps with a repeater,
8687 the following will happen:
8688 - the repeater will be removed in each clone
8689 - an additional clone will be produced, with the current, unshifted
8690 date(s) in the entry.
8691 - the original entry will be placed *after* all the clones, with
8692 repeater intact.
8693 - the start days in the repeater in the original entry will be shifted
8694 to past the last clone.
8695 In this way you can spell out a number of instances of a repeating task,
8696 and still retain the repeater to cover future instances of the task.
8698 As described above, N+1 clones are produced when the original
8699 subtree has a repeater. Setting N to 0, then, can be used to
8700 remove the repeater from a subtree and create a shifted clone
8701 with the original repeater."
8702 (interactive "nNumber of clones to produce: ")
8703 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8704 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8705 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8706 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8707 (shift
8708 (or shift
8709 (if (and (not (equal current-prefix-arg '(4)))
8710 (save-excursion
8711 (goto-char beg)
8712 (re-search-forward org-ts-regexp-both end-of-tree t)))
8713 (read-from-minibuffer
8714 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8715 ""))) ;No time shift
8716 (doshift
8717 (and (org-string-nw-p shift)
8718 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8719 shift)
8720 (user-error "Invalid shift specification %s" shift)))))
8721 (goto-char end-of-tree)
8722 (unless (bolp) (insert "\n"))
8723 (let* ((end (point))
8724 (template (buffer-substring beg end))
8725 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8726 (shift-what (pcase (and doshift (match-string 2 shift))
8727 (`nil nil)
8728 ("d" 'day)
8729 ("w" (setq shift-n (* 7 shift-n)) 'day)
8730 ("m" 'month)
8731 ("y" 'year)
8732 (_ (error "Unsupported time unit"))))
8733 (nmin 1)
8734 (nmax n)
8735 (n-no-remove -1)
8736 (idprop (org-entry-get nil "ID")))
8737 (when (and doshift
8738 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8739 template))
8740 (delete-region beg end)
8741 (setq end beg)
8742 (setq nmin 0)
8743 (setq nmax (1+ nmax))
8744 (setq n-no-remove nmax))
8745 (goto-char end)
8746 (cl-loop for n from nmin to nmax do
8747 (insert
8748 ;; Prepare clone.
8749 (with-temp-buffer
8750 (insert template)
8751 (org-mode)
8752 (goto-char (point-min))
8753 (org-show-subtree)
8754 (and idprop (if org-clone-delete-id
8755 (org-entry-delete nil "ID")
8756 (org-id-get-create t)))
8757 (unless (= n 0)
8758 (while (re-search-forward org-clock-line-re nil t)
8759 (delete-region (line-beginning-position)
8760 (line-beginning-position 2)))
8761 (goto-char (point-min))
8762 (while (re-search-forward org-drawer-regexp nil t)
8763 (org-remove-empty-drawer-at (point))))
8764 (goto-char (point-min))
8765 (when doshift
8766 (while (re-search-forward org-ts-regexp-both nil t)
8767 (org-timestamp-change (* n shift-n) shift-what))
8768 (unless (= n n-no-remove)
8769 (goto-char (point-min))
8770 (while (re-search-forward org-ts-regexp nil t)
8771 (save-excursion
8772 (goto-char (match-beginning 0))
8773 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8774 (delete-region (match-beginning 1) (match-end 1)))))))
8775 (buffer-string)))))
8776 (goto-char beg)))
8778 ;;; Outline Sorting
8780 (defun org-sort (&optional with-case)
8781 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8782 Optional argument WITH-CASE means sort case-sensitively."
8783 (interactive "P")
8784 (org-call-with-arg
8785 (cond ((org-at-table-p) #'org-table-sort-lines)
8786 ((org-at-item-p) #'org-sort-list)
8787 (t #'org-sort-entries))
8788 with-case))
8790 (defun org-sort-remove-invisible (s)
8791 "Remove invisible part of links and emphasis markers from string S."
8792 (remove-text-properties 0 (length s) org-rm-props s)
8793 (replace-regexp-in-string
8794 org-verbatim-re (lambda (m) (format "%s " (match-string 4 m)))
8795 (replace-regexp-in-string
8796 org-emph-re (lambda (m) (format " %s " (match-string 4 m)))
8797 (org-link-display-format s)
8798 t t) t t))
8800 (defvar org-priority-regexp) ; defined later in the file
8802 (defvar org-after-sorting-entries-or-items-hook nil
8803 "Hook that is run after a bunch of entries or items have been sorted.
8804 When children are sorted, the cursor is in the parent line when this
8805 hook gets called. When a region or a plain list is sorted, the cursor
8806 will be in the first entry of the sorted region/list.")
8808 (defun org-sort-entries
8809 (&optional with-case sorting-type getkey-func compare-func property
8810 interactive?)
8811 "Sort entries on a certain level of an outline tree.
8812 If there is an active region, the entries in the region are sorted.
8813 Else, if the cursor is before the first entry, sort the top-level items.
8814 Else, the children of the entry at point are sorted.
8816 Sorting can be alphabetically, numerically, by date/time as given by
8817 a time stamp, by a property, by priority order, or by a custom function.
8819 The command prompts for the sorting type unless it has been given to the
8820 function through the SORTING-TYPE argument, which needs to be a character,
8821 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8822 the precise meaning of each character:
8824 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8825 c By creation time, which is assumed to be the first inactive time stamp
8826 at the beginning of a line.
8827 d By deadline date/time.
8828 k By clocking time.
8829 n Numerically, by converting the beginning of the entry/item to a number.
8830 o By order of TODO keywords.
8831 p By priority according to the cookie.
8832 r By the value of a property.
8833 s By scheduled date/time.
8834 t By date/time, either the first active time stamp in the entry, or, if
8835 none exist, by the first inactive one.
8837 Capital letters will reverse the sort order.
8839 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8840 called with point at the beginning of the record. It must return a
8841 value that is compatible with COMPARE-FUNC, the function used to
8842 compare entries.
8844 Comparing entries ignores case by default. However, with an optional argument
8845 WITH-CASE, the sorting considers case as well.
8847 Sorting is done against the visible part of the headlines, it ignores hidden
8848 links.
8850 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
8852 A non-nil value for INTERACTIVE? is used to signal that this
8853 function is being called interactively."
8854 (interactive (list current-prefix-arg nil nil nil nil t))
8855 (let ((case-func (if with-case 'identity 'downcase))
8856 start beg end stars re re2
8857 txt what tmp)
8858 ;; Find beginning and end of region to sort
8859 (cond
8860 ((org-region-active-p)
8861 ;; we will sort the region
8862 (setq end (region-end)
8863 what "region")
8864 (goto-char (region-beginning))
8865 (unless (org-at-heading-p) (outline-next-heading))
8866 (setq start (point)))
8867 ((or (org-at-heading-p)
8868 (ignore-errors (progn (org-back-to-heading) t)))
8869 ;; we will sort the children of the current headline
8870 (org-back-to-heading)
8871 (setq start (point)
8872 end (progn (org-end-of-subtree t t)
8873 (or (bolp) (insert "\n"))
8874 (when (>= (org-back-over-empty-lines) 1)
8875 (forward-line 1))
8876 (point))
8877 what "children")
8878 (goto-char start)
8879 (outline-show-subtree)
8880 (outline-next-heading))
8882 ;; we will sort the top-level entries in this file
8883 (goto-char (point-min))
8884 (or (org-at-heading-p) (outline-next-heading))
8885 (setq start (point))
8886 (goto-char (point-max))
8887 (beginning-of-line 1)
8888 (when (looking-at ".*?\\S-")
8889 ;; File ends in a non-white line
8890 (end-of-line 1)
8891 (insert "\n"))
8892 (setq end (point-max))
8893 (setq what "top-level")
8894 (goto-char start)
8895 (outline-show-all)))
8897 (setq beg (point))
8898 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8900 (looking-at "\\(\\*+\\)")
8901 (setq stars (match-string 1)
8902 re (concat "^" (regexp-quote stars) " +")
8903 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8904 txt (buffer-substring beg end))
8905 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8906 (when (and (not (equal stars "*")) (string-match re2 txt))
8907 (user-error "Region to sort contains a level above the first entry"))
8909 (unless sorting-type
8910 (message
8911 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8912 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8913 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8914 what)
8915 (setq sorting-type (read-char-exclusive)))
8917 (unless getkey-func
8918 (and (= (downcase sorting-type) ?f)
8919 (setq getkey-func
8920 (or (and interactive?
8921 (org-read-function
8922 "Function for extracting keys: "))
8923 (error "Missing key extractor")))))
8925 (and (= (downcase sorting-type) ?r)
8926 (not property)
8927 (setq property
8928 (completing-read "Property: "
8929 (mapcar #'list (org-buffer-property-keys t))
8930 nil t)))
8932 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8933 (message "Sorting entries...")
8935 (save-restriction
8936 (narrow-to-region start end)
8937 (let ((restore-clock?
8938 ;; The clock marker is lost when using `sort-subr'; mark
8939 ;; the clock with temporary `:org-clock-marker-backup'
8940 ;; text property.
8941 (when (and (eq (org-clock-is-active) (current-buffer))
8942 (<= start (marker-position org-clock-marker))
8943 (>= end (marker-position org-clock-marker)))
8944 (org-with-silent-modifications
8945 (put-text-property (1- org-clock-marker) org-clock-marker
8946 :org-clock-marker-backup t))
8948 (dcst (downcase sorting-type))
8949 (case-fold-search nil)
8950 (now (current-time)))
8951 (sort-subr
8952 (/= dcst sorting-type)
8953 ;; This function moves to the beginning character of the "record" to
8954 ;; be sorted.
8955 (lambda nil
8956 (if (re-search-forward re nil t)
8957 (goto-char (match-beginning 0))
8958 (goto-char (point-max))))
8959 ;; This function moves to the last character of the "record" being
8960 ;; sorted.
8961 (lambda nil
8962 (save-match-data
8963 (condition-case nil
8964 (outline-forward-same-level 1)
8965 (error
8966 (goto-char (point-max))))))
8967 ;; This function returns the value that gets sorted against.
8968 (lambda nil
8969 (cond
8970 ((= dcst ?n)
8971 (if (looking-at org-complex-heading-regexp)
8972 (string-to-number (org-sort-remove-invisible (match-string 4)))
8973 nil))
8974 ((= dcst ?a)
8975 (if (looking-at org-complex-heading-regexp)
8976 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8977 nil))
8978 ((= dcst ?k)
8979 (or (get-text-property (point) :org-clock-minutes) 0))
8980 ((= dcst ?t)
8981 (let ((end (save-excursion (outline-next-heading) (point))))
8982 (if (or (re-search-forward org-ts-regexp end t)
8983 (re-search-forward org-ts-regexp-both end t))
8984 (org-time-string-to-seconds (match-string 0))
8985 (float-time now))))
8986 ((= dcst ?c)
8987 (let ((end (save-excursion (outline-next-heading) (point))))
8988 (if (re-search-forward
8989 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8990 end t)
8991 (org-time-string-to-seconds (match-string 0))
8992 (float-time now))))
8993 ((= dcst ?s)
8994 (let ((end (save-excursion (outline-next-heading) (point))))
8995 (if (re-search-forward org-scheduled-time-regexp end t)
8996 (org-time-string-to-seconds (match-string 1))
8997 (float-time now))))
8998 ((= dcst ?d)
8999 (let ((end (save-excursion (outline-next-heading) (point))))
9000 (if (re-search-forward org-deadline-time-regexp end t)
9001 (org-time-string-to-seconds (match-string 1))
9002 (float-time now))))
9003 ((= dcst ?p)
9004 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9005 (string-to-char (match-string 2))
9006 org-default-priority))
9007 ((= dcst ?r)
9008 (or (org-entry-get nil property) ""))
9009 ((= dcst ?o)
9010 (when (looking-at org-complex-heading-regexp)
9011 (let* ((m (match-string 2))
9012 (s (if (member m org-done-keywords) '- '+)))
9013 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9014 ((= dcst ?f)
9015 (if getkey-func
9016 (progn
9017 (setq tmp (funcall getkey-func))
9018 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9019 tmp)
9020 (error "Invalid key function `%s'" getkey-func)))
9021 (t (error "Invalid sorting type `%c'" sorting-type))))
9023 (cond
9024 ((= dcst ?a) 'string<)
9025 ((= dcst ?f)
9026 (or compare-func
9027 (and interactive?
9028 (org-read-function
9029 (concat "Function for comparing keys "
9030 "(empty for default `sort-subr' predicate): ")
9031 'allow-empty))))
9032 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
9033 (when restore-clock?
9034 (move-marker org-clock-marker
9035 (1+ (next-single-property-change
9036 start :org-clock-marker-backup)))
9037 (remove-text-properties (1- org-clock-marker) org-clock-marker
9038 '(:org-clock-marker-backup t)))))
9039 (run-hooks 'org-after-sorting-entries-or-items-hook)
9040 (message "Sorting entries...done")))
9042 ;;; The orgstruct minor mode
9044 ;; Define a minor mode which can be used in other modes in order to
9045 ;; integrate the Org mode structure editing commands.
9047 ;; This is really a hack, because the Org mode structure commands use
9048 ;; keys which normally belong to the major mode. Here is how it
9049 ;; works: The minor mode defines all the keys necessary to operate the
9050 ;; structure commands, but wraps the commands into a function which
9051 ;; tests if the cursor is currently at a headline or a plain list
9052 ;; item. If that is the case, the structure command is used,
9053 ;; temporarily setting many Org mode variables like regular
9054 ;; expressions for filling etc. However, when any of those keys is
9055 ;; used at a different location, function uses `key-binding' to look
9056 ;; up if the key has an associated command in another currently active
9057 ;; keymap (minor modes, major mode, global), and executes that
9058 ;; command. There might be problems if any of the keys is otherwise
9059 ;; used as a prefix key.
9061 (defcustom orgstruct-heading-prefix-regexp ""
9062 "Regexp that matches the custom prefix of Org headlines in
9063 orgstruct(++)-mode."
9064 :group 'org
9065 :version "26.1"
9066 :package-version '(Org . "8.3")
9067 :type 'regexp)
9068 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9070 (defcustom orgstruct-setup-hook nil
9071 "Hook run after orgstruct-mode-map is filled."
9072 :group 'org
9073 :version "24.4"
9074 :package-version '(Org . "8.0")
9075 :type 'hook)
9077 (defvar orgstruct-initialized nil)
9079 (defvar org-local-vars nil
9080 "List of local variables, for use by `orgstruct-mode'.")
9082 ;;;###autoload
9083 (define-minor-mode orgstruct-mode
9084 "Toggle the minor mode `orgstruct-mode'.
9085 This mode is for using Org mode structure commands in other
9086 modes. The following keys behave as if Org mode were active, if
9087 the cursor is on a headline, or on a plain list item (both as
9088 defined by Org mode)."
9089 nil " OrgStruct" (make-sparse-keymap)
9090 (funcall (if orgstruct-mode
9091 'add-to-invisibility-spec
9092 'remove-from-invisibility-spec)
9093 '(outline . t))
9094 (when orgstruct-mode
9095 (org-load-modules-maybe)
9096 (unless orgstruct-initialized
9097 (orgstruct-setup)
9098 (setq orgstruct-initialized t))))
9100 ;;;###autoload
9101 (defun turn-on-orgstruct ()
9102 "Unconditionally turn on `orgstruct-mode'."
9103 (orgstruct-mode 1))
9105 (defvar-local orgstruct-is-++ nil
9106 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9107 (defvar-local org-fb-vars nil)
9108 (defun orgstruct++-mode (&optional arg)
9109 "Toggle `orgstruct-mode', the enhanced version of it.
9110 In addition to setting orgstruct-mode, this also exports all
9111 indentation and autofilling variables from Org mode into the
9112 buffer. It will also recognize item context in multiline items."
9113 (interactive "P")
9114 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9115 (if (< arg 1)
9116 (progn (orgstruct-mode -1)
9117 (dolist (v org-fb-vars)
9118 (set (make-local-variable (car v))
9119 (if (eq (car-safe (cadr v)) 'quote)
9120 (cl-cadadr v)
9121 (nth 1 v)))))
9122 (orgstruct-mode 1)
9123 (setq org-fb-vars nil)
9124 (unless org-local-vars
9125 (setq org-local-vars (org-get-local-variables)))
9126 (let (var val)
9127 (dolist (x org-local-vars)
9128 (when (string-match
9129 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9130 \\|fill-prefix\\|indent-\\)"
9131 (symbol-name (car x)))
9132 (setq var (car x) val (nth 1 x))
9133 (push (list var `(quote ,(eval var))) org-fb-vars)
9134 (set (make-local-variable var)
9135 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9136 (setq-local orgstruct-is-++ t))))
9138 ;;;###autoload
9139 (defun turn-on-orgstruct++ ()
9140 "Unconditionally turn on `orgstruct++-mode'."
9141 (orgstruct++-mode 1))
9143 (defun orgstruct-error ()
9144 "Error when there is no default binding for a structure key."
9145 (interactive)
9146 (funcall (if (fboundp 'user-error)
9147 'user-error
9148 'error)
9149 "This key has no function outside structure elements"))
9151 (defun orgstruct-setup ()
9152 "Setup orgstruct keymap."
9153 (dolist (cell '((org-demote . t)
9154 (org-metaleft . t)
9155 (org-metaright . t)
9156 (org-promote . t)
9157 (org-shiftmetaleft . t)
9158 (org-shiftmetaright . t)
9159 org-backward-element
9160 org-backward-heading-same-level
9161 org-ctrl-c-ret
9162 org-ctrl-c-minus
9163 org-ctrl-c-star
9164 org-cycle
9165 org-force-cycle-archived
9166 org-forward-heading-same-level
9167 org-insert-heading
9168 org-insert-heading-respect-content
9169 org-kill-note-or-show-branches
9170 org-mark-subtree
9171 org-meta-return
9172 org-metadown
9173 org-metaup
9174 org-narrow-to-subtree
9175 org-promote-subtree
9176 org-reveal
9177 org-shiftdown
9178 org-shiftleft
9179 org-shiftmetadown
9180 org-shiftmetaup
9181 org-shiftright
9182 org-shifttab
9183 org-shifttab
9184 org-shiftup
9185 org-show-children
9186 org-show-subtree
9187 org-sort
9188 org-up-element
9189 outline-demote
9190 outline-next-visible-heading
9191 outline-previous-visible-heading
9192 outline-promote
9193 outline-up-heading))
9194 (let ((f (or (car-safe cell) cell))
9195 (disable-when-heading-prefix (cdr-safe cell)))
9196 (when (fboundp f)
9197 (let ((new-bindings))
9198 (dolist (binding (nconc (where-is-internal f org-mode-map)
9199 (where-is-internal f outline-mode-map)))
9200 (push binding new-bindings)
9201 ;; TODO use local-function-key-map
9202 (dolist (rep '(("<tab>" . "TAB")
9203 ("<return>" . "RET")
9204 ("<escape>" . "ESC")
9205 ("<delete>" . "DEL")))
9206 (setq binding (read-kbd-macro
9207 (let ((case-fold-search))
9208 (replace-regexp-in-string
9209 (regexp-quote (cdr rep))
9210 (car rep)
9211 (key-description binding)))))
9212 (cl-pushnew binding new-bindings :test 'equal)))
9213 (dolist (binding new-bindings)
9214 (let ((key (lookup-key orgstruct-mode-map binding)))
9215 (when (or (not key) (numberp key))
9216 (ignore-errors
9217 (org-defkey orgstruct-mode-map
9218 binding
9219 (orgstruct-make-binding
9220 f binding disable-when-heading-prefix))))))))))
9221 (run-hooks 'orgstruct-setup-hook))
9223 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9224 "Create a function for binding in the structure minor mode.
9225 FUN is the command to call inside a table. KEY is the key that
9226 should be checked in for a command to execute outside of tables.
9227 Non-nil `disable-when-heading-prefix' means to disable the command
9228 if `orgstruct-heading-prefix-regexp' is not empty."
9229 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9230 (let ((nname name)
9231 (i 0))
9232 (while (fboundp (intern nname))
9233 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9234 (setq name (intern nname)))
9235 (eval
9236 (let ((bindings '((org-heading-regexp
9237 (concat "^"
9238 orgstruct-heading-prefix-regexp
9239 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9240 (org-outline-regexp
9241 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9242 (org-outline-regexp-bol
9243 (concat "^" org-outline-regexp))
9244 (outline-regexp org-outline-regexp)
9245 (outline-heading-end-regexp "\n")
9246 (outline-level 'org-outline-level)
9247 (outline-heading-alist))))
9248 `(defun ,name (arg)
9249 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9250 "Outside of structure, run the binding of `"
9251 (key-description key) "'."
9252 (when disable-when-heading-prefix
9253 (concat
9254 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9255 "back to the default binding due to limitations of Org's implementation of\n"
9256 "`" (symbol-name fun) "'.")))
9257 (interactive "p")
9258 (let* ((disable
9259 ,(and disable-when-heading-prefix
9260 '(not (string= orgstruct-heading-prefix-regexp ""))))
9261 (fallback
9262 (or disable
9263 (not
9264 (let* ,bindings
9265 (org-context-p 'headline 'item
9266 ,(when (memq fun
9267 '(org-insert-heading
9268 org-insert-heading-respect-content
9269 org-meta-return))
9270 '(when orgstruct-is-++
9271 'item-body))))))))
9272 (if fallback
9273 (let* ((orgstruct-mode)
9274 (binding
9275 (let ((key ,key))
9276 (catch 'exit
9277 (dolist
9278 (rep
9279 '(nil
9280 ("<\\([^>]*\\)tab>" . "\\1TAB")
9281 ("<\\([^>]*\\)return>" . "\\1RET")
9282 ("<\\([^>]*\\)escape>" . "\\1ESC")
9283 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9284 nil)
9285 (when rep
9286 (setq key (read-kbd-macro
9287 (let ((case-fold-search))
9288 (replace-regexp-in-string
9289 (car rep)
9290 (cdr rep)
9291 (key-description key))))))
9292 (when (key-binding key)
9293 (throw 'exit (key-binding key))))))))
9294 (if (keymapp binding)
9295 (org-set-transient-map binding)
9296 (let ((func (or binding
9297 (unless disable
9298 'orgstruct-error))))
9299 (when func
9300 (call-interactively func)))))
9301 (org-run-like-in-org-mode
9302 (lambda ()
9303 (interactive)
9304 (let* ,bindings
9305 (call-interactively ',fun)))))))))
9306 name))
9308 (defun org-contextualize-keys (alist contexts)
9309 "Return valid elements in ALIST depending on CONTEXTS.
9311 `org-agenda-custom-commands' or `org-capture-templates' are the
9312 values used for ALIST, and `org-agenda-custom-commands-contexts'
9313 or `org-capture-templates-contexts' are the associated contexts
9314 definitions."
9315 (let ((contexts
9316 ;; normalize contexts
9317 (mapcar
9318 (lambda(c) (cond ((listp (cadr c))
9319 (list (car c) (car c) (nth 1 c)))
9320 ((string= "" (cadr c))
9321 (list (car c) (car c) (nth 2 c)))
9322 (t c)))
9323 contexts))
9324 (a alist) r s)
9325 ;; loop over all commands or templates
9326 (dolist (c a)
9327 (let (vrules repl)
9328 (cond
9329 ((not (assoc (car c) contexts))
9330 (push c r))
9331 ((and (assoc (car c) contexts)
9332 (setq vrules (org-contextualize-validate-key
9333 (car c) contexts)))
9334 (mapc (lambda (vr)
9335 (unless (equal (car vr) (cadr vr))
9336 (setq repl vr)))
9337 vrules)
9338 (if (not repl) (push c r)
9339 (push (cadr repl) s)
9340 (push
9341 (cons (car c)
9342 (cdr (or (assoc (cadr repl) alist)
9343 (error "Undefined key `%s' as contextual replacement for `%s'"
9344 (cadr repl) (car c)))))
9345 r))))))
9346 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9347 (delq
9349 (delete-dups
9350 (mapcar (lambda (x)
9351 (let ((tpl (car x)))
9352 (unless (delq
9354 (mapcar (lambda (y)
9355 (equal y tpl))
9357 x)))
9358 (reverse r))))))
9360 (defun org-contextualize-validate-key (key contexts)
9361 "Check CONTEXTS for agenda or capture KEY."
9362 (let (res)
9363 (dolist (r contexts)
9364 (dolist (rr (car (last r)))
9365 (when
9366 (and (equal key (car r))
9367 (if (functionp rr) (funcall rr)
9368 (or (and (eq (car rr) 'in-file)
9369 (buffer-file-name)
9370 (string-match (cdr rr) (buffer-file-name)))
9371 (and (eq (car rr) 'in-mode)
9372 (string-match (cdr rr) (symbol-name major-mode)))
9373 (and (eq (car rr) 'in-buffer)
9374 (string-match (cdr rr) (buffer-name)))
9375 (when (and (eq (car rr) 'not-in-file)
9376 (buffer-file-name))
9377 (not (string-match (cdr rr) (buffer-file-name))))
9378 (when (eq (car rr) 'not-in-mode)
9379 (not (string-match (cdr rr) (symbol-name major-mode))))
9380 (when (eq (car rr) 'not-in-buffer)
9381 (not (string-match (cdr rr) (buffer-name)))))))
9382 (push r res))))
9383 (delete-dups (delq nil res))))
9385 (defun org-context-p (&rest contexts)
9386 "Check if local context is any of CONTEXTS.
9387 Possible values in the list of contexts are `table', `headline', and `item'."
9388 (let ((pos (point)))
9389 (goto-char (point-at-bol))
9390 (prog1 (or (and (memq 'table contexts)
9391 (looking-at "[ \t]*|"))
9392 (and (memq 'headline contexts)
9393 (looking-at org-outline-regexp))
9394 (and (memq 'item contexts)
9395 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9396 (and (memq 'item-body contexts)
9397 (org-in-item-p)))
9398 (goto-char pos))))
9400 ;;;###autoload
9401 (defun org-run-like-in-org-mode (cmd)
9402 "Run a command, pretending that the current buffer is in Org mode.
9403 This will temporarily bind local variables that are typically bound in
9404 Org mode to the values they have in Org mode, and then interactively
9405 call CMD."
9406 (org-load-modules-maybe)
9407 (unless org-local-vars
9408 (setq org-local-vars (org-get-local-variables)))
9409 (let (binds)
9410 (dolist (var org-local-vars)
9411 (when (or (not (boundp (car var)))
9412 (eq (symbol-value (car var))
9413 (default-value (car var))))
9414 (push (list (car var) `(quote ,(cadr var))) binds)))
9415 (eval `(let ,binds
9416 (call-interactively (quote ,cmd))))))
9418 (defun org-get-category (&optional pos force-refresh)
9419 "Get the category applying to position POS."
9420 (save-match-data
9421 (when force-refresh (org-refresh-category-properties))
9422 (let ((pos (or pos (point))))
9423 (or (get-text-property pos 'org-category)
9424 (progn (org-refresh-category-properties)
9425 (get-text-property pos 'org-category))))))
9427 ;;; Refresh properties
9429 (defun org-refresh-properties (dprop tprop)
9430 "Refresh buffer text properties.
9431 DPROP is the drawer property and TPROP is either the
9432 corresponding text property to set, or an alist with each element
9433 being a text property (as a symbol) and a function to apply to
9434 the value of the drawer property."
9435 (let* ((case-fold-search t)
9436 (inhibit-read-only t)
9437 (inherit? (org-property-inherit-p dprop))
9438 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9439 (global (and inherit? (org--property-global-value dprop nil))))
9440 (org-with-silent-modifications
9441 (org-with-point-at 1
9442 ;; Set global values (e.g., values defined through
9443 ;; "#+PROPERTY:" keywords) to the whole buffer.
9444 (when global (put-text-property (point-min) (point-max) tprop global))
9445 ;; Set local values.
9446 (while (re-search-forward property-re nil t)
9447 (when (org-at-property-p)
9448 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9449 (outline-next-heading))))))
9451 (defun org-refresh-property (tprop p &optional inherit)
9452 "Refresh the buffer text property TPROP from the drawer property P.
9453 The refresh happens only for the current headline, or the whole
9454 sub-tree if optional argument INHERIT is non-nil."
9455 (unless (org-before-first-heading-p)
9456 (save-excursion
9457 (org-back-to-heading t)
9458 (let ((start (point))
9459 (end (save-excursion
9460 (if inherit (org-end-of-subtree t t)
9461 (or (outline-next-heading) (point-max))))))
9462 (if (symbolp tprop)
9463 ;; TPROP is a text property symbol.
9464 (put-text-property start end tprop p)
9465 ;; TPROP is an alist with (property . function) elements.
9466 (pcase-dolist (`(,prop . ,f) tprop)
9467 (put-text-property start end prop (funcall f p))))))))
9469 (defun org-refresh-category-properties ()
9470 "Refresh category text properties in the buffer."
9471 (let ((case-fold-search t)
9472 (inhibit-read-only t)
9473 (default-category
9474 (cond ((null org-category)
9475 (if buffer-file-name
9476 (file-name-sans-extension
9477 (file-name-nondirectory buffer-file-name))
9478 "???"))
9479 ((symbolp org-category) (symbol-name org-category))
9480 (t org-category))))
9481 (org-with-silent-modifications
9482 (org-with-wide-buffer
9483 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9484 ;; This is the default category for the buffer. If none is
9485 ;; found, fall-back to `org-category' or buffer file name.
9486 (put-text-property
9487 (point-min) (point-max)
9488 'org-category
9489 (catch 'buffer-category
9490 (goto-char (point-max))
9491 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9492 (let ((element (org-element-at-point)))
9493 (when (eq (org-element-type element) 'keyword)
9494 (throw 'buffer-category
9495 (org-element-property :value element)))))
9496 default-category))
9497 ;; Set sub-tree specific categories.
9498 (goto-char (point-min))
9499 (let ((regexp (org-re-property "CATEGORY")))
9500 (while (re-search-forward regexp nil t)
9501 (let ((value (match-string-no-properties 3)))
9502 (when (org-at-property-p)
9503 (put-text-property
9504 (save-excursion (org-back-to-heading t) (point))
9505 (save-excursion (org-end-of-subtree t t) (point))
9506 'org-category
9507 value)))))))))
9509 (defun org-refresh-stats-properties ()
9510 "Refresh stats text properties in the buffer."
9511 (org-with-silent-modifications
9512 (org-with-point-at 1
9513 (let ((regexp (concat org-outline-regexp-bol
9514 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9515 (while (re-search-forward regexp nil t)
9516 (let* ((numerator (string-to-number (match-string 1)))
9517 (denominator (and (match-end 2)
9518 (string-to-number (match-string 2))))
9519 (stats (cond ((not denominator) numerator) ;percent
9520 ((= denominator 0) 0)
9521 (t (/ (* numerator 100) denominator)))))
9522 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9523 'org-stats stats)))))))
9525 (defun org-refresh-effort-properties ()
9526 "Refresh effort properties"
9527 (org-refresh-properties
9528 org-effort-property
9529 '((effort . identity)
9530 (effort-minutes . org-duration-to-minutes))))
9532 ;;;; Link Stuff
9534 ;;; Link abbreviations
9536 (defun org-link-expand-abbrev (link)
9537 "Apply replacements as defined in `org-link-abbrev-alist'."
9538 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9539 (let* ((key (match-string 1 link))
9540 (as (or (assoc key org-link-abbrev-alist-local)
9541 (assoc key org-link-abbrev-alist)))
9542 (tag (and (match-end 2) (match-string 3 link)))
9543 rpl)
9544 (if (not as)
9545 link
9546 (setq rpl (cdr as))
9547 (cond
9548 ((symbolp rpl) (funcall rpl tag))
9549 ((string-match "%(\\([^)]+\\))" rpl)
9550 (replace-match
9551 (save-match-data
9552 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9553 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9554 ((string-match "%h" rpl)
9555 (replace-match (url-hexify-string (or tag "")) t t rpl))
9556 (t (concat rpl tag)))))
9557 link))
9559 ;;; Storing and inserting links
9561 (defvar org-insert-link-history nil
9562 "Minibuffer history for links inserted with `org-insert-link'.")
9564 (defvar org-stored-links nil
9565 "Contains the links stored with `org-store-link'.")
9567 (defvar org-store-link-plist nil
9568 "Plist with info about the most recently link created with `org-store-link'.")
9570 (defun org-store-link-functions ()
9571 "Return a list of functions that are called to create and store a link.
9572 The functions defined in the :store property of
9573 `org-link-parameters'.
9575 Each function will be called in turn until one returns a non-nil
9576 value. Each function should check if it is responsible for
9577 creating this link (for example by looking at the major mode).
9578 If not, it must exit and return nil. If yes, it should return
9579 a non-nil value after calling `org-store-link-props' with a list
9580 of properties and values. Special properties are:
9582 :type The link prefix, like \"http\". This must be given.
9583 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9584 This is obligatory as well.
9585 :description Optional default description for the second pair
9586 of brackets in an Org mode link. The user can still change
9587 this when inserting this link into an Org mode buffer.
9589 In addition to these, any additional properties can be specified
9590 and then used in capture templates."
9591 (cl-loop for link in org-link-parameters
9592 with store-func
9593 do (setq store-func (org-link-get-parameter (car link) :store))
9594 if store-func
9595 collect store-func))
9597 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9598 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9600 ;;;###autoload
9601 (defun org-store-link (arg)
9602 "Store an org-link to the current location.
9603 \\<org-mode-map>
9604 This link is added to `org-stored-links' and can later be inserted
9605 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9607 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9608 A single
9609 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9610 `org-gnus-prefer-web-links' for links to Usenet articles.
9612 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9613 skipping storing functions that are not
9614 part of Org core.
9616 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9617 prefix ARG forces storing a link for each line in the
9618 active region."
9619 (interactive "P")
9620 (org-load-modules-maybe)
9621 (if (and (equal arg '(64)) (org-region-active-p))
9622 (save-excursion
9623 (let ((end (region-end)))
9624 (goto-char (region-beginning))
9625 (set-mark (point))
9626 (while (< (point-at-eol) end)
9627 (move-end-of-line 1) (activate-mark)
9628 (let (current-prefix-arg)
9629 (call-interactively 'org-store-link))
9630 (move-beginning-of-line 2)
9631 (set-mark (point)))))
9632 (setq org-store-link-plist nil)
9633 (let (link cpltxt desc description search
9634 txt custom-id agenda-link sfuns sfunsn)
9635 (cond
9637 ;; Store a link using an external link type
9638 ((and (not (equal arg '(16)))
9639 (setq sfuns
9640 (delq
9641 nil (mapcar (lambda (f)
9642 (let (fs) (if (funcall f) (push f fs))))
9643 (org-store-link-functions)))
9644 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9645 (or (and (cdr sfuns)
9646 (funcall (intern
9647 (completing-read
9648 "Which function for creating the link? "
9649 sfunsn nil t (car sfunsn)))))
9650 (funcall (caar sfuns)))
9651 (setq link (plist-get org-store-link-plist :link)
9652 desc (or (plist-get org-store-link-plist
9653 :description)
9654 link))))
9656 ;; Store a link from a source code buffer.
9657 ((org-src-edit-buffer-p)
9658 (let ((coderef-format (org-src-coderef-format)))
9659 (cond ((save-excursion
9660 (beginning-of-line)
9661 (looking-at (org-src-coderef-regexp coderef-format)))
9662 (setq link (format "(%s)" (match-string-no-properties 3))))
9663 ((called-interactively-p 'any)
9664 (let ((label (read-string "Code line label: ")))
9665 (end-of-line)
9666 (setq link (format coderef-format label))
9667 (let ((gc (- 79 (length link))))
9668 (if (< (current-column) gc)
9669 (org-move-to-column gc t)
9670 (insert " ")))
9671 (insert link)
9672 (setq link (concat "(" label ")"))
9673 (setq desc nil)))
9674 (t (setq link nil)))))
9676 ;; We are in the agenda, link to referenced location
9677 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9678 (let ((m (or (get-text-property (point) 'org-hd-marker)
9679 (get-text-property (point) 'org-marker))))
9680 (when m
9681 (org-with-point-at m
9682 (setq agenda-link
9683 (if (called-interactively-p 'any)
9684 (call-interactively 'org-store-link)
9685 (org-store-link nil)))))))
9687 ((eq major-mode 'calendar-mode)
9688 (let ((cd (calendar-cursor-to-date)))
9689 (setq link
9690 (format-time-string
9691 (car org-time-stamp-formats)
9692 (apply 'encode-time
9693 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9694 nil nil nil))))
9695 (org-store-link-props :type "calendar" :date cd)))
9697 ((eq major-mode 'help-mode)
9698 (setq link (concat "help:" (save-excursion
9699 (goto-char (point-min))
9700 (looking-at "^[^ ]+")
9701 (match-string 0))))
9702 (org-store-link-props :type "help"))
9704 ((eq major-mode 'w3-mode)
9705 (setq cpltxt (if (and (buffer-name)
9706 (not (string-match "Untitled" (buffer-name))))
9707 (buffer-name)
9708 (url-view-url t))
9709 link (url-view-url t))
9710 (org-store-link-props :type "w3" :url (url-view-url t)))
9712 ((eq major-mode 'image-mode)
9713 (setq cpltxt (concat "file:"
9714 (abbreviate-file-name buffer-file-name))
9715 link cpltxt)
9716 (org-store-link-props :type "image" :file buffer-file-name))
9718 ;; In dired, store a link to the file of the current line
9719 ((derived-mode-p 'dired-mode)
9720 (let ((file (dired-get-filename nil t)))
9721 (setq file (if file
9722 (abbreviate-file-name
9723 (expand-file-name (dired-get-filename nil t)))
9724 ;; otherwise, no file so use current directory.
9725 default-directory))
9726 (setq cpltxt (concat "file:" file)
9727 link cpltxt)))
9729 ((setq search (run-hook-with-args-until-success
9730 'org-create-file-search-functions))
9731 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9732 "::" search))
9733 (setq cpltxt (or description link)))
9735 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9736 (org-with-limited-levels
9737 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9738 (cond
9739 ;; Store a link using the target at point
9740 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9741 (setq cpltxt
9742 (concat "file:"
9743 (abbreviate-file-name
9744 (buffer-file-name (buffer-base-buffer)))
9745 "::" (match-string 1))
9746 link cpltxt))
9747 ((and (featurep 'org-id)
9748 (or (eq org-id-link-to-org-use-id t)
9749 (and (called-interactively-p 'any)
9750 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9751 (and (eq org-id-link-to-org-use-id
9752 'create-if-interactive-and-no-custom-id)
9753 (not custom-id))))
9754 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9755 ;; Store a link using the ID at point
9756 (setq link (condition-case nil
9757 (prog1 (org-id-store-link)
9758 (setq desc (or (plist-get org-store-link-plist
9759 :description)
9760 "")))
9761 (error
9762 ;; Probably before first headline, link only to file
9763 (concat "file:"
9764 (abbreviate-file-name
9765 (buffer-file-name (buffer-base-buffer))))))))
9767 ;; Just link to current headline
9768 (setq cpltxt (concat "file:"
9769 (abbreviate-file-name
9770 (buffer-file-name (buffer-base-buffer)))))
9771 ;; Add a context search string
9772 (when (org-xor org-context-in-file-links
9773 (equal arg '(4)))
9774 (let* ((element (org-element-at-point))
9775 (name (org-element-property :name element)))
9776 (setq txt (cond
9777 ((org-at-heading-p) nil)
9778 (name)
9779 ((org-region-active-p)
9780 (buffer-substring (region-beginning) (region-end)))))
9781 (when (or (null txt) (string-match "\\S-" txt))
9782 (setq cpltxt
9783 (concat cpltxt "::"
9784 (condition-case nil
9785 (org-make-org-heading-search-string txt)
9786 (error "")))
9787 desc (or name
9788 (nth 4 (ignore-errors (org-heading-components)))
9789 "NONE")))))
9790 (when (string-match "::\\'" cpltxt)
9791 (setq cpltxt (substring cpltxt 0 -2)))
9792 (setq link cpltxt)))))
9794 ((buffer-file-name (buffer-base-buffer))
9795 ;; Just link to this file here.
9796 (setq cpltxt (concat "file:"
9797 (abbreviate-file-name
9798 (buffer-file-name (buffer-base-buffer)))))
9799 ;; Add a context string.
9800 (when (org-xor org-context-in-file-links
9801 (equal arg '(4)))
9802 (setq txt (if (org-region-active-p)
9803 (buffer-substring (region-beginning) (region-end))
9804 (buffer-substring (point-at-bol) (point-at-eol))))
9805 ;; Only use search option if there is some text.
9806 (when (string-match "\\S-" txt)
9807 (setq cpltxt
9808 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9809 desc "NONE")))
9810 (setq link cpltxt))
9812 ((called-interactively-p 'interactive)
9813 (user-error "No method for storing a link from this buffer"))
9815 (t (setq link nil)))
9817 ;; We're done setting link and desc, clean up
9818 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9819 (setq link (or link cpltxt)
9820 desc (or desc cpltxt))
9821 (cond ((not desc))
9822 ((equal desc "NONE") (setq desc nil))
9823 (t (setq desc
9824 (replace-regexp-in-string
9825 org-bracket-link-analytic-regexp
9826 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9827 desc))))
9828 ;; Return the link
9829 (if (not (and (or (called-interactively-p 'any)
9830 executing-kbd-macro)
9831 link))
9832 (or agenda-link (and link (org-make-link-string link desc)))
9833 (push (list link desc) org-stored-links)
9834 (message "Stored: %s" (or desc link))
9835 (when custom-id
9836 (setq link (concat "file:" (abbreviate-file-name
9837 (buffer-file-name)) "::#" custom-id))
9838 (push (list link desc) org-stored-links))
9839 (car org-stored-links)))))
9841 (defun org-store-link-props (&rest plist)
9842 "Store link properties, extract names, addresses and dates."
9843 (let ((x (plist-get plist :from)))
9844 (when x
9845 (let ((adr (mail-extract-address-components x)))
9846 (setq plist (plist-put plist :fromname (car adr)))
9847 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9848 (let ((x (plist-get plist :to)))
9849 (when x
9850 (let ((adr (mail-extract-address-components x)))
9851 (setq plist (plist-put plist :toname (car adr)))
9852 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9853 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9854 (when x
9855 (setq plist (plist-put plist :date-timestamp
9856 (format-time-string
9857 (org-time-stamp-format t) x)))
9858 (setq plist (plist-put plist :date-timestamp-inactive
9859 (format-time-string
9860 (org-time-stamp-format t t) x)))))
9861 (let ((from (plist-get plist :from))
9862 (to (plist-get plist :to)))
9863 (when (and from to org-from-is-user-regexp)
9864 (setq plist
9865 (plist-put plist :fromto
9866 (if (string-match org-from-is-user-regexp from)
9867 (concat "to %t")
9868 (concat "from %f"))))))
9869 (setq org-store-link-plist plist))
9871 (defun org-add-link-props (&rest plist)
9872 "Add these properties to the link property list."
9873 (let (key value)
9874 (while plist
9875 (setq key (pop plist) value (pop plist))
9876 (setq org-store-link-plist
9877 (plist-put org-store-link-plist key value)))))
9879 (defun org-email-link-description (&optional fmt)
9880 "Return the description part of an email link.
9881 This takes information from `org-store-link-plist' and formats it
9882 according to FMT (default from `org-email-link-description-format')."
9883 (setq fmt (or fmt org-email-link-description-format))
9884 (let* ((p org-store-link-plist)
9885 (to (plist-get p :toaddress))
9886 (from (plist-get p :fromaddress))
9887 (table
9888 (list
9889 (cons "%c" (plist-get p :fromto))
9890 (cons "%F" (plist-get p :from))
9891 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9892 (cons "%T" (plist-get p :to))
9893 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9894 (cons "%s" (plist-get p :subject))
9895 (cons "%d" (plist-get p :date))
9896 (cons "%m" (plist-get p :message-id)))))
9897 (when (string-match "%c" fmt)
9898 ;; Check if the user wrote this message
9899 (if (and org-from-is-user-regexp from to
9900 (save-match-data (string-match org-from-is-user-regexp from)))
9901 (setq fmt (replace-match "to %t" t t fmt))
9902 (setq fmt (replace-match "from %f" t t fmt))))
9903 (org-replace-escapes fmt table)))
9905 (defun org-make-org-heading-search-string (&optional string)
9906 "Make search string for the current headline or STRING."
9907 (let ((s (or string
9908 (and (derived-mode-p 'org-mode)
9909 (save-excursion
9910 (org-back-to-heading t)
9911 (org-element-property :raw-value (org-element-at-point))))))
9912 (lines org-context-in-file-links))
9913 (unless string (setq s (concat "*" s))) ;Add * for headlines
9914 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9915 (when (and string (integerp lines) (> lines 0))
9916 (let ((slines (org-split-string s "\n")))
9917 (when (< lines (length slines))
9918 (setq s (mapconcat
9919 'identity
9920 (reverse (nthcdr (- (length slines) lines)
9921 (reverse slines))) "\n")))))
9922 (mapconcat #'identity (split-string s) " ")))
9924 (defun org-make-link-string (link &optional description)
9925 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9926 (unless (org-string-nw-p link) (error "Empty link"))
9927 (let ((uri (cond ((string-match org-link-types-re link)
9928 (concat (match-string 1 link)
9929 (org-link-escape (substring link (match-end 1)))))
9930 ;; For readability, url-encode internal links only
9931 ;; when absolutely needed (i.e, when they contain
9932 ;; square brackets). File links however, are
9933 ;; encoded since, e.g., spaces are significant.
9934 ((or (file-name-absolute-p link)
9935 (string-match-p "\\`\\.\\.?/\\|[][]" link))
9936 (org-link-escape link))
9937 (t link)))
9938 (description
9939 (and (org-string-nw-p description)
9940 ;; Remove brackets from description, as they are fatal.
9941 (replace-regexp-in-string
9942 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9943 (org-trim description)))))
9944 (format "[[%s]%s]"
9946 (if description (format "[%s]" description) ""))))
9948 (defconst org-link-escape-chars
9949 ;;%20 %5B %5D %25
9950 '(?\s ?\[ ?\] ?%)
9951 "List of characters that should be escaped in a link when stored to Org.
9952 This is the list that is used for internal purposes.")
9954 (defun org-link-escape (text &optional table merge)
9955 "Return percent escaped representation of TEXT.
9956 TEXT is a string with the text to escape.
9957 Optional argument TABLE is a list with characters that should be
9958 escaped. When nil, `org-link-escape-chars' is used.
9959 If optional argument MERGE is set, merge TABLE into
9960 `org-link-escape-chars'."
9961 (let ((characters-to-encode
9962 (cond ((null table) org-link-escape-chars)
9963 (merge (append org-link-escape-chars table))
9964 (t table))))
9965 (mapconcat
9966 (lambda (c)
9967 (if (or (memq c characters-to-encode)
9968 (and org-url-hexify-p (or (< c 32) (> c 126))))
9969 (mapconcat (lambda (e) (format "%%%.2X" e))
9970 (or (encode-coding-char c 'utf-8)
9971 (error "Unable to percent escape character: %c" c))
9973 (char-to-string c)))
9974 text "")))
9976 (defun org-link-unescape (str)
9977 "Unhex hexified Unicode parts in string STR.
9978 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
9979 reciprocal of `org-link-escape', which see."
9980 (if (org-string-nw-p str)
9981 (replace-regexp-in-string
9982 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
9983 str))
9985 (defun org-link-unescape-compound (hex)
9986 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
9987 Note: this function also decodes single byte encodings like
9988 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
9989 (save-match-data
9990 (let* ((bytes (cdr (split-string hex "%")))
9991 (ret "")
9992 (eat 0)
9993 (sum 0))
9994 (while bytes
9995 (let* ((val (string-to-number (pop bytes) 16))
9996 (shift-xor
9997 (if (= 0 eat)
9998 (cond
9999 ((>= val 252) (cons 6 252))
10000 ((>= val 248) (cons 5 248))
10001 ((>= val 240) (cons 4 240))
10002 ((>= val 224) (cons 3 224))
10003 ((>= val 192) (cons 2 192))
10004 (t (cons 0 0)))
10005 (cons 6 128))))
10006 (when (>= val 192) (setq eat (car shift-xor)))
10007 (setq val (logxor val (cdr shift-xor)))
10008 (setq sum (+ (lsh sum (car shift-xor)) val))
10009 (when (> eat 0) (setq eat (- eat 1)))
10010 (cond
10011 ((= 0 eat) ;multi byte
10012 (setq ret (concat ret (char-to-string sum)))
10013 (setq sum 0))
10014 ((not bytes) ; single byte(s)
10015 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10016 ret)))
10018 (defun org-link-unescape-single-byte-sequence (hex)
10019 "Unhexify hex-encoded single byte character sequences."
10020 (mapconcat (lambda (byte)
10021 (char-to-string (string-to-number byte 16)))
10022 (cdr (split-string hex "%")) ""))
10024 (defun org-xor (a b)
10025 "Exclusive or."
10026 (if a (not b) b))
10028 (defun org-fixup-message-id-for-http (s)
10029 "Replace special characters in a message id, so it can be used in an http query."
10030 (when (string-match "%" s)
10031 (setq s (mapconcat (lambda (c)
10032 (if (eq c ?%)
10033 "%25"
10034 (char-to-string c)))
10035 s "")))
10036 (while (string-match "<" s)
10037 (setq s (replace-match "%3C" t t s)))
10038 (while (string-match ">" s)
10039 (setq s (replace-match "%3E" t t s)))
10040 (while (string-match "@" s)
10041 (setq s (replace-match "%40" t t s)))
10044 (defun org-link-prettify (link)
10045 "Return a human-readable representation of LINK.
10046 The car of LINK must be a raw link.
10047 The cdr of LINK must be either a link description or nil."
10048 (let ((desc (or (cadr link) "<no description>")))
10049 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10050 "<" (car link) ">")))
10052 ;;;###autoload
10053 (defun org-insert-link-global ()
10054 "Insert a link like Org mode does.
10055 This command can be called in any mode to insert a link in Org syntax."
10056 (interactive)
10057 (org-load-modules-maybe)
10058 (org-run-like-in-org-mode 'org-insert-link))
10060 (defun org-insert-all-links (arg &optional pre post)
10061 "Insert all links in `org-stored-links'.
10062 When a universal prefix, do not delete the links from `org-stored-links'.
10063 When `ARG' is a number, insert the last N link(s).
10064 `PRE' and `POST' are optional arguments to define a string to
10065 prepend or to append."
10066 (interactive "P")
10067 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10068 (links (copy-sequence org-stored-links))
10069 (pr (or pre "- "))
10070 (po (or post "\n"))
10071 (cnt 1) l)
10072 (if (null org-stored-links)
10073 (message "No link to insert")
10074 (while (and (or (listp arg) (>= arg cnt))
10075 (setq l (if (listp arg)
10076 (pop links)
10077 (pop org-stored-links))))
10078 (setq cnt (1+ cnt))
10079 (insert pr)
10080 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10081 (insert po)))))
10083 (defun org-insert-last-stored-link (arg)
10084 "Insert the last link stored in `org-stored-links'."
10085 (interactive "p")
10086 (org-insert-all-links arg "" "\n"))
10088 (defun org-link-fontify-links-to-this-file ()
10089 "Fontify links to the current file in `org-stored-links'."
10090 (let ((f (buffer-file-name)) a b)
10091 (setq a (mapcar (lambda(l)
10092 (let ((ll (car l)))
10093 (when (and (string-match "^file:\\(.+\\)::" ll)
10094 (equal f (expand-file-name (match-string 1 ll))))
10095 ll)))
10096 org-stored-links))
10097 (when (featurep 'org-id)
10098 (setq b (mapcar (lambda(l)
10099 (let ((ll (car l)))
10100 (when (and (string-match "^id:\\(.+\\)$" ll)
10101 (equal f (expand-file-name
10102 (or (org-id-find-id-file
10103 (match-string 1 ll)) ""))))
10104 ll)))
10105 org-stored-links)))
10106 (mapcar (lambda(l)
10107 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10108 (delq nil (append a b)))))
10110 (defvar org--links-history nil)
10111 (defun org-insert-link (&optional complete-file link-location default-description)
10112 "Insert a link. At the prompt, enter the link.
10114 Completion can be used to insert any of the link protocol prefixes in use.
10116 The history can be used to select a link previously stored with
10117 `org-store-link'. When the empty string is entered (i.e. if you just
10118 press `RET' at the prompt), the link defaults to the most recently
10119 stored link. As `SPC' triggers completion in the minibuffer, you need to
10120 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10122 You will also be prompted for a description, and if one is given, it will
10123 be displayed in the buffer instead of the link.
10125 If there is already a link at point, this command will allow you to edit
10126 link and description parts.
10128 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10129 file name can be
10130 selected using completion. The path to the file will be relative to the
10131 current directory if the file is in the current directory or a subdirectory.
10132 Otherwise, the link will be the absolute path as completed in the minibuffer
10133 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10134 option `org-link-file-path-type'.
10136 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10137 absolute path even if the file is in
10138 the current directory or below.
10140 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10141 prefix negates `org-keep-stored-link-after-insertion'.
10143 If the LINK-LOCATION parameter is non-nil, this value will be used as
10144 the link location instead of reading one interactively.
10146 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10147 be used as the default description. Otherwise, if
10148 `org-make-link-description-function' is non-nil, this function
10149 will be called with the link target, and the result will be the
10150 default link description."
10151 (interactive "P")
10152 (let* ((wcf (current-window-configuration))
10153 (origbuf (current-buffer))
10154 (region (when (org-region-active-p)
10155 (buffer-substring (region-beginning) (region-end))))
10156 (remove (and region (list (region-beginning) (region-end))))
10157 (desc region)
10158 (link link-location)
10159 (abbrevs org-link-abbrev-alist-local)
10160 entry all-prefixes auto-desc)
10161 (cond
10162 (link-location) ; specified by arg, just use it.
10163 ((org-in-regexp org-bracket-link-regexp 1)
10164 ;; We do have a link at point, and we are going to edit it.
10165 (setq remove (list (match-beginning 0) (match-end 0)))
10166 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10167 (setq link (read-string "Link: "
10168 (org-link-unescape
10169 (match-string-no-properties 1)))))
10170 ((or (org-in-regexp org-angle-link-re)
10171 (org-in-regexp org-plain-link-re))
10172 ;; Convert to bracket link
10173 (setq remove (list (match-beginning 0) (match-end 0))
10174 link (read-string "Link: "
10175 (org-unbracket-string "<" ">" (match-string 0)))))
10176 ((member complete-file '((4) (16)))
10177 ;; Completing read for file names.
10178 (setq link (org-file-complete-link complete-file)))
10180 ;; Read link, with completion for stored links.
10181 (org-link-fontify-links-to-this-file)
10182 (org-switch-to-buffer-other-window "*Org Links*")
10183 (with-current-buffer "*Org Links*"
10184 (erase-buffer)
10185 (insert "Insert a link.
10186 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10187 (when org-stored-links
10188 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10189 (insert (mapconcat 'org-link-prettify
10190 (reverse org-stored-links) "\n")))
10191 (goto-char (point-min)))
10192 (let ((cw (selected-window)))
10193 (select-window (get-buffer-window "*Org Links*" 'visible))
10194 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10195 (unless (pos-visible-in-window-p (point-max))
10196 (org-fit-window-to-buffer))
10197 (and (window-live-p cw) (select-window cw)))
10198 (setq all-prefixes (append (mapcar 'car abbrevs)
10199 (mapcar 'car org-link-abbrev-alist)
10200 (org-link-types)))
10201 (unwind-protect
10202 ;; Fake a link history, containing the stored links.
10203 (let ((org--links-history
10204 (append (mapcar #'car org-stored-links)
10205 org-insert-link-history)))
10206 (setq link
10207 (org-completing-read
10208 "Link: "
10209 (append
10210 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10211 (mapcar #'car org-stored-links))
10212 nil nil nil
10213 'org--links-history
10214 (caar org-stored-links)))
10215 (unless (org-string-nw-p link) (user-error "No link selected"))
10216 (dolist (l org-stored-links)
10217 (when (equal link (cadr l))
10218 (setq link (car l))
10219 (setq auto-desc t)))
10220 (when (or (member link all-prefixes)
10221 (and (equal ":" (substring link -1))
10222 (member (substring link 0 -1) all-prefixes)
10223 (setq link (substring link 0 -1))))
10224 (setq link (with-current-buffer origbuf
10225 (org-link-try-special-completion link)))))
10226 (set-window-configuration wcf)
10227 (kill-buffer "*Org Links*"))
10228 (setq entry (assoc link org-stored-links))
10229 (or entry (push link org-insert-link-history))
10230 (setq desc (or desc (nth 1 entry)))))
10232 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10233 (not org-keep-stored-link-after-insertion))
10234 (setq org-stored-links (delq (assoc link org-stored-links)
10235 org-stored-links)))
10237 (when (and (string-match org-plain-link-re link)
10238 (not (string-match org-ts-regexp link)))
10239 ;; URL-like link, normalize the use of angular brackets.
10240 (setq link (org-unbracket-string "<" ">" link)))
10242 ;; Check if we are linking to the current file with a search
10243 ;; option If yes, simplify the link by using only the search
10244 ;; option.
10245 (when (and buffer-file-name
10246 (let ((case-fold-search nil))
10247 (string-match "\\`file:\\(.+?\\)::" link)))
10248 (let ((path (match-string-no-properties 1 link))
10249 (search (substring-no-properties link (match-end 0))))
10250 (save-match-data
10251 (when (equal (file-truename buffer-file-name) (file-truename path))
10252 ;; We are linking to this same file, with a search option
10253 (setq link search)))))
10255 ;; Check if we can/should use a relative path. If yes, simplify the link
10256 (let ((case-fold-search nil))
10257 (when (string-match "\\`\\(file\\|docview\\):" link)
10258 (let* ((type (match-string-no-properties 0 link))
10259 (path (substring-no-properties link (match-end 0)))
10260 (origpath path))
10261 (cond
10262 ((or (eq org-link-file-path-type 'absolute)
10263 (equal complete-file '(16)))
10264 (setq path (abbreviate-file-name (expand-file-name path))))
10265 ((eq org-link-file-path-type 'noabbrev)
10266 (setq path (expand-file-name path)))
10267 ((eq org-link-file-path-type 'relative)
10268 (setq path (file-relative-name path)))
10270 (save-match-data
10271 (if (string-match (concat "^" (regexp-quote
10272 (expand-file-name
10273 (file-name-as-directory
10274 default-directory))))
10275 (expand-file-name path))
10276 ;; We are linking a file with relative path name.
10277 (setq path (substring (expand-file-name path)
10278 (match-end 0)))
10279 (setq path (abbreviate-file-name (expand-file-name path)))))))
10280 (setq link (concat type path))
10281 (when (equal desc origpath)
10282 (setq desc path)))))
10284 (unless auto-desc
10285 (let ((initial-input
10286 (cond
10287 (default-description)
10288 ((not org-make-link-description-function) desc)
10289 (t (condition-case nil
10290 (funcall org-make-link-description-function link desc)
10291 (error
10292 (message "Can't get link description from `%s'"
10293 (symbol-name org-make-link-description-function))
10294 (sit-for 2)
10295 nil))))))
10296 (setq desc (read-string "Description: " initial-input))))
10298 (unless (string-match "\\S-" desc) (setq desc nil))
10299 (when remove (apply 'delete-region remove))
10300 (insert (org-make-link-string link desc))
10301 ;; Redisplay so as the new link has proper invisible characters.
10302 (sit-for 0)))
10304 (defun org-link-try-special-completion (type)
10305 "If there is completion support for link type TYPE, offer it."
10306 (let ((fun (org-link-get-parameter type :complete)))
10307 (if (functionp fun)
10308 (funcall fun)
10309 (read-string "Link (no completion support): " (concat type ":")))))
10311 (defun org-file-complete-link (&optional arg)
10312 "Create a file link using completion."
10313 (let ((file (read-file-name "File: "))
10314 (pwd (file-name-as-directory (expand-file-name ".")))
10315 (pwd1 (file-name-as-directory (abbreviate-file-name
10316 (expand-file-name ".")))))
10317 (cond ((equal arg '(16))
10318 (concat "file:"
10319 (abbreviate-file-name (expand-file-name file))))
10320 ((string-match
10321 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10322 (concat "file:" (match-string 1 file)))
10323 ((string-match
10324 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10325 (expand-file-name file))
10326 (concat "file:"
10327 (match-string 1 (expand-file-name file))))
10328 (t (concat "file:" file)))))
10330 (defun org-completing-read (&rest args)
10331 "Completing-read with SPACE being a normal character."
10332 (let ((enable-recursive-minibuffers t)
10333 (minibuffer-local-completion-map
10334 (copy-keymap minibuffer-local-completion-map)))
10335 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10336 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10337 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10338 'org-time-stamp-inactive)
10339 (apply #'completing-read args)))
10341 ;;; Opening/following a link
10343 (defvar org-link-search-failed nil)
10345 (defvar org-open-link-functions nil
10346 "Hook for functions finding a plain text link.
10347 These functions must take a single argument, the link content.
10348 They will be called for links that look like [[link text][description]]
10349 when LINK TEXT does not have a protocol like \"http:\" and does not look
10350 like a filename (e.g. \"./blue.png\").
10352 These functions will be called *before* Org attempts to resolve the
10353 link by doing text searches in the current buffer - so if you want a
10354 link \"[[target]]\" to still find \"<<target>>\", your function should
10355 handle this as a special case.
10357 When the function does handle the link, it must return a non-nil value.
10358 If it decides that it is not responsible for this link, it must return
10359 nil to indicate that that Org can continue with other options like
10360 exact and fuzzy text search.")
10362 (defun org-next-link (&optional search-backward)
10363 "Move forward to the next link.
10364 If the link is in hidden text, expose it."
10365 (interactive "P")
10366 (when (and org-link-search-failed (eq this-command last-command))
10367 (goto-char (point-min))
10368 (message "Link search wrapped back to beginning of buffer"))
10369 (setq org-link-search-failed nil)
10370 (let* ((pos (point))
10371 (ct (org-context))
10372 (a (assq :link ct))
10373 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10374 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10375 ((looking-at org-any-link-re)
10376 ;; Don't stay stuck at link without an org-link face
10377 (forward-char (if search-backward -1 1))))
10378 (if (funcall srch-fun org-any-link-re nil t)
10379 (progn
10380 (goto-char (match-beginning 0))
10381 (when (org-invisible-p) (org-show-context)))
10382 (goto-char pos)
10383 (setq org-link-search-failed t)
10384 (message "No further link found"))))
10386 (defun org-previous-link ()
10387 "Move backward to the previous link.
10388 If the link is in hidden text, expose it."
10389 (interactive)
10390 (funcall 'org-next-link t))
10392 (defun org-translate-link (s)
10393 "Translate a link string if a translation function has been defined."
10394 (with-temp-buffer
10395 (insert (org-trim s))
10396 (org-trim (org-element-interpret-data (org-element-context)))))
10398 (defun org-translate-link-from-planner (type path)
10399 "Translate a link from Emacs Planner syntax so that Org can follow it.
10400 This is still an experimental function, your mileage may vary."
10401 (cond
10402 ((member type '("http" "https" "news" "ftp"))
10403 ;; standard Internet links are the same.
10404 nil)
10405 ((and (equal type "irc") (string-match "^//" path))
10406 ;; Planner has two / at the beginning of an irc link, we have 1.
10407 ;; We should have zero, actually....
10408 (setq path (substring path 1)))
10409 ((and (equal type "lisp") (string-match "^/" path))
10410 ;; Planner has a slash, we do not.
10411 (setq type "elisp" path (substring path 1)))
10412 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10413 ;; A typical message link. Planner has the id after the final slash,
10414 ;; we separate it with a hash mark
10415 (setq path (concat (match-string 1 path) "#"
10416 (org-unbracket-string "<" ">" (match-string 2 path))))))
10417 (cons type path))
10419 (defun org-find-file-at-mouse (ev)
10420 "Open file link or URL at mouse."
10421 (interactive "e")
10422 (mouse-set-point ev)
10423 (org-open-at-point 'in-emacs))
10425 (defun org-open-at-mouse (ev)
10426 "Open file link or URL at mouse.
10427 See the docstring of `org-open-file' for details."
10428 (interactive "e")
10429 (mouse-set-point ev)
10430 (when (eq major-mode 'org-agenda-mode)
10431 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10432 (org-open-at-point))
10434 (defvar org-window-config-before-follow-link nil
10435 "The window configuration before following a link.
10436 This is saved in case the need arises to restore it.")
10438 ;;;###autoload
10439 (defun org-open-at-point-global ()
10440 "Follow a link or time-stamp like Org mode does.
10441 This command can be called in any mode to follow an external link
10442 or a time-stamp that has Org mode syntax. Its behavior is
10443 undefined when called on internal links (e.g., fuzzy links).
10444 Raise an error when there is nothing to follow. "
10445 (interactive)
10446 (cond ((org-in-regexp org-any-link-re)
10447 (org-open-link-from-string (match-string-no-properties 0)))
10448 ((or (org-in-regexp org-ts-regexp-both nil t)
10449 (org-in-regexp org-tsr-regexp-both nil t))
10450 (org-follow-timestamp-link))
10451 (t (user-error "No link found"))))
10453 ;;;###autoload
10454 (defun org-open-link-from-string (s &optional arg reference-buffer)
10455 "Open a link in the string S, as if it was in Org mode."
10456 (interactive "sLink: \nP")
10457 (let ((reference-buffer (or reference-buffer (current-buffer))))
10458 (with-temp-buffer
10459 (let ((org-inhibit-startup (not reference-buffer)))
10460 (org-mode)
10461 (insert s)
10462 (goto-char (point-min))
10463 (when reference-buffer
10464 (setq org-link-abbrev-alist-local
10465 (with-current-buffer reference-buffer
10466 org-link-abbrev-alist-local)))
10467 (org-open-at-point arg reference-buffer)))))
10469 (defvar org-open-at-point-functions nil
10470 "Hook that is run when following a link at point.
10472 Functions in this hook must return t if they identify and follow
10473 a link at point. If they don't find anything interesting at point,
10474 they must return nil.")
10476 (defvar org-link-search-inhibit-query nil)
10477 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10478 (defun org--open-doi-link (path)
10479 "Open a \"doi\" type link.
10480 PATH is a the path to search for, as a string."
10481 (browse-url (url-encode-url (concat org-doi-server-url path))))
10483 (defun org--open-elisp-link (path)
10484 "Open a \"elisp\" type link.
10485 PATH is the sexp to evaluate, as a string."
10486 (let ((cmd path))
10487 (if (or (and (org-string-nw-p
10488 org-confirm-elisp-link-not-regexp)
10489 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10490 (not org-confirm-elisp-link-function)
10491 (funcall org-confirm-elisp-link-function
10492 (format "Execute \"%s\" as elisp? "
10493 (org-add-props cmd nil 'face 'org-warning))))
10494 (message "%s => %s" cmd
10495 (if (eq (string-to-char cmd) ?\()
10496 (eval (read cmd))
10497 (call-interactively (read cmd))))
10498 (user-error "Abort"))))
10500 (defun org--open-help-link (path)
10501 "Open a \"help\" type link.
10502 PATH is a symbol name, as a string."
10503 (pcase (intern path)
10504 ((and (pred fboundp) variable) (describe-function variable))
10505 ((and (pred boundp) function) (describe-variable function))
10506 (name (user-error "Unknown function or variable: %s" name))))
10508 (defun org--open-shell-link (path)
10509 "Open a \"shell\" type link.
10510 PATH is the command to execute, as a string."
10511 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10512 (cmd path))
10513 (if (or (and (org-string-nw-p
10514 org-confirm-shell-link-not-regexp)
10515 (string-match
10516 org-confirm-shell-link-not-regexp cmd))
10517 (not org-confirm-shell-link-function)
10518 (funcall org-confirm-shell-link-function
10519 (format "Execute \"%s\" in shell? "
10520 (org-add-props cmd nil
10521 'face 'org-warning))))
10522 (progn
10523 (message "Executing %s" cmd)
10524 (shell-command cmd buf)
10525 (when (featurep 'midnight)
10526 (setq clean-buffer-list-kill-buffer-names
10527 (cons (buffer-name buf)
10528 clean-buffer-list-kill-buffer-names))))
10529 (user-error "Abort"))))
10531 (defun org-open-at-point (&optional arg reference-buffer)
10532 "Open link, timestamp, footnote or tags at point.
10534 When point is on a link, follow it. Normally, files will be
10535 opened by an appropriate application. If the optional prefix
10536 argument ARG is non-nil, Emacs will visit the file. With
10537 a double prefix argument, try to open outside of Emacs, in the
10538 application the system uses for this file type.
10540 When point is on a timestamp, open the agenda at the day
10541 specified.
10543 When point is a footnote definition, move to the first reference
10544 found. If it is on a reference, move to the associated
10545 definition.
10547 When point is on a headline, display a list of every link in the
10548 entry, so it is possible to pick one, or all, of them. If point
10549 is on a tag, call `org-tags-view' instead.
10551 When optional argument REFERENCE-BUFFER is non-nil, it should
10552 specify a buffer from where the link search should happen. This
10553 is used internally by `org-open-link-from-string'.
10555 On top of syntactically correct links, this function will also
10556 try to open links and time-stamps in comments, example
10557 blocks... i.e., whenever point is on something looking like
10558 a timestamp or a link."
10559 (interactive "P")
10560 ;; On a code block, open block's results.
10561 (unless (call-interactively 'org-babel-open-src-block-result)
10562 (org-load-modules-maybe)
10563 (setq org-window-config-before-follow-link (current-window-configuration))
10564 (org-remove-occur-highlights nil nil t)
10565 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10566 (let* ((context
10567 ;; Only consider supported types, even if they are not
10568 ;; the closest one.
10569 (org-element-lineage
10570 (org-element-context)
10571 '(clock footnote-definition footnote-reference headline
10572 inlinetask link timestamp)
10574 (type (org-element-type context))
10575 (value (org-element-property :value context)))
10576 (cond
10577 ;; On a headline or an inlinetask, but not on a timestamp,
10578 ;; a link, a footnote reference.
10579 ((memq type '(headline inlinetask))
10580 (org-match-line org-complex-heading-regexp)
10581 (if (and (match-beginning 5)
10582 (>= (point) (match-beginning 5))
10583 (< (point) (match-end 5)))
10584 ;; On tags.
10585 (org-tags-view arg (substring (match-string 5) 0 -1))
10586 ;; Not on tags.
10587 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10588 (`(nil . ,_)
10589 (require 'org-attach)
10590 (org-attach-reveal 'if-exists))
10591 (`(,links . ,links-end)
10592 (dolist (link (if (stringp links) (list links) links))
10593 (search-forward link nil links-end)
10594 (goto-char (match-beginning 0))
10595 (org-open-at-point))))))
10596 ;; On a footnote reference or at definition's label.
10597 ((or (eq type 'footnote-reference)
10598 (and (eq type 'footnote-definition)
10599 (save-excursion
10600 ;; Do not validate action when point is on the
10601 ;; spaces right after the footnote label, in
10602 ;; order to be on par with behaviour on links.
10603 (skip-chars-forward " \t")
10604 (let ((begin
10605 (org-element-property :contents-begin context)))
10606 (if begin (< (point) begin)
10607 (= (org-element-property :post-affiliated context)
10608 (line-beginning-position)))))))
10609 (org-footnote-action))
10610 ;; No valid context. Ignore catch-all types like `headline'.
10611 ;; If point is on something looking like a link or
10612 ;; a time-stamp, try opening it. It may be useful in
10613 ;; comments, example blocks...
10614 ((memq type '(footnote-definition headline inlinetask nil))
10615 (call-interactively #'org-open-at-point-global))
10616 ;; On a clock line, make sure point is on the timestamp
10617 ;; before opening it.
10618 ((and (eq type 'clock)
10619 value
10620 (>= (point) (org-element-property :begin value))
10621 (<= (point) (org-element-property :end value)))
10622 (org-follow-timestamp-link))
10623 ;; Do nothing on white spaces after an object.
10624 ((>= (point)
10625 (save-excursion
10626 (goto-char (org-element-property :end context))
10627 (skip-chars-backward " \t")
10628 (point)))
10629 (user-error "No link found"))
10630 ((eq type 'timestamp) (org-follow-timestamp-link))
10631 ((eq type 'link)
10632 (let ((type (org-element-property :type context))
10633 (path (org-link-unescape (org-element-property :path context))))
10634 ;; Switch back to REFERENCE-BUFFER needed when called in
10635 ;; a temporary buffer through `org-open-link-from-string'.
10636 (with-current-buffer (or reference-buffer (current-buffer))
10637 (cond
10638 ((equal type "file")
10639 (if (string-match "[*?{]" (file-name-nondirectory path))
10640 (dired path)
10641 ;; Look into `org-link-parameters' in order to find
10642 ;; a DEDICATED-FUNCTION to open file. The function
10643 ;; will be applied on raw link instead of parsed
10644 ;; link due to the limitation in `org-add-link-type'
10645 ;; ("open" function called with a single argument).
10646 ;; If no such function is found, fallback to
10647 ;; `org-open-file'.
10648 (let* ((option (org-element-property :search-option context))
10649 (app (org-element-property :application context))
10650 (dedicated-function
10651 (org-link-get-parameter
10652 (if app (concat type "+" app) type)
10653 :follow)))
10654 (if dedicated-function
10655 (funcall dedicated-function
10656 (concat path
10657 (and option (concat "::" option))))
10658 (apply #'org-open-file
10659 path
10660 (cond (arg)
10661 ((equal app "emacs") 'emacs)
10662 ((equal app "sys") 'system))
10663 (cond ((not option) nil)
10664 ((string-match-p "\\`[0-9]+\\'" option)
10665 (list (string-to-number option)))
10666 (t (list nil
10667 (org-link-unescape option)))))))))
10668 ((functionp (org-link-get-parameter type :follow))
10669 (funcall (org-link-get-parameter type :follow) path))
10670 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10671 (unless (run-hook-with-args-until-success
10672 'org-open-link-functions path)
10673 (if (not arg) (org-mark-ring-push)
10674 (switch-to-buffer-other-window
10675 (org-get-buffer-for-internal-link (current-buffer))))
10676 (let ((destination
10677 (org-with-wide-buffer
10678 (if (equal type "radio")
10679 (org-search-radio-target
10680 (org-element-property :path context))
10681 (org-link-search
10682 (if (member type '("custom-id" "coderef"))
10683 (org-element-property :raw-link context)
10684 path)
10685 ;; Prevent fuzzy links from matching
10686 ;; themselves.
10687 (and (equal type "fuzzy")
10688 (+ 2 (org-element-property :begin context)))))
10689 (point))))
10690 (unless (and (<= (point-min) destination)
10691 (>= (point-max) destination))
10692 (widen))
10693 (goto-char destination))))
10694 (t (browse-url-at-point))))))
10695 (t (user-error "No link found")))))
10696 (run-hook-with-args 'org-follow-link-hook)))
10698 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10699 "Offer links in the current entry and return the selected link.
10700 If there is only one link, return it.
10701 If NTH is an integer, return the NTH link found.
10702 If ZERO is a string, check also this string for a link, and if
10703 there is one, return it."
10704 (with-current-buffer buffer
10705 (org-with-wide-buffer
10706 (goto-char marker)
10707 (let ((cnt ?0)
10708 have-zero end links link c)
10709 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10710 (push (match-string 0 zero) links)
10711 (setq cnt (1- cnt) have-zero t))
10712 (save-excursion
10713 (org-back-to-heading t)
10714 (setq end (save-excursion (outline-next-heading) (point)))
10715 (while (re-search-forward org-any-link-re end t)
10716 (push (match-string 0) links))
10717 (setq links (org-uniquify (reverse links))))
10718 (cond
10719 ((null links)
10720 (message "No links"))
10721 ((equal (length links) 1)
10722 (setq link (car links)))
10723 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10724 (setq link (nth (if have-zero nth (1- nth)) links)))
10725 (t ; we have to select a link
10726 (save-excursion
10727 (save-window-excursion
10728 (delete-other-windows)
10729 (with-output-to-temp-buffer "*Select Link*"
10730 (dolist (l links)
10731 (cond
10732 ((not (string-match org-bracket-link-regexp l))
10733 (princ (format "[%c] %s\n" (cl-incf cnt)
10734 (org-unbracket-string "<" ">" l))))
10735 ((match-end 3)
10736 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10737 (match-string 3 l) (match-string 1 l))))
10738 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10739 (match-string 1 l)))))))
10740 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10741 (message "Select link to open, RET to open all:")
10742 (setq c (read-char-exclusive))
10743 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10744 (when (equal c ?q) (user-error "Abort"))
10745 (if (equal c ?\C-m)
10746 (setq link links)
10747 (setq nth (- c ?0))
10748 (when have-zero (setq nth (1+ nth)))
10749 (unless (and (integerp nth) (>= (length links) nth))
10750 (user-error "Invalid link selection"))
10751 (setq link (nth (1- nth) links)))))
10752 (cons link end)))))
10754 ;; TODO: These functions are deprecated since `org-open-at-point'
10755 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10756 (defun org-open-file-with-system (path)
10757 "Open file at PATH using the system way of opening it."
10758 (org-open-file path 'system))
10759 (defun org-open-file-with-emacs (path)
10760 "Open file at PATH in Emacs."
10761 (org-open-file path 'emacs))
10764 ;;; File search
10766 (defvar org-create-file-search-functions nil
10767 "List of functions to construct the right search string for a file link.
10768 These functions are called in turn with point at the location to
10769 which the link should point.
10771 A function in the hook should first test if it would like to
10772 handle this file type, for example by checking the `major-mode'
10773 or the file extension. If it decides not to handle this file, it
10774 should just return nil to give other functions a chance. If it
10775 does handle the file, it must return the search string to be used
10776 when following the link. The search string will be part of the
10777 file link, given after a double colon, and `org-open-at-point'
10778 will automatically search for it. If special measures must be
10779 taken to make the search successful, another function should be
10780 added to the companion hook `org-execute-file-search-functions',
10781 which see.
10783 A function in this hook may also use `setq' to set the variable
10784 `description' to provide a suggestion for the descriptive text to
10785 be used for this link when it gets inserted into an Org buffer
10786 with \\[org-insert-link].")
10788 (defvar org-execute-file-search-functions nil
10789 "List of functions to execute a file search triggered by a link.
10791 Functions added to this hook must accept a single argument, the
10792 search string that was part of the file link, the part after the
10793 double colon. The function must first check if it would like to
10794 handle this search, for example by checking the `major-mode' or
10795 the file extension. If it decides not to handle this search, it
10796 should just return nil to give other functions a chance. If it
10797 does handle the search, it must return a non-nil value to keep
10798 other functions from trying.
10800 Each function can access the current prefix argument through the
10801 variable `current-prefix-arg'. Note that a single prefix is used
10802 to force opening a link in Emacs, so it may be good to only use a
10803 numeric or double prefix to guide the search function.
10805 In case this is needed, a function in this hook can also restore
10806 the window configuration before `org-open-at-point' was called using:
10808 (set-window-configuration org-window-config-before-follow-link)")
10810 (defun org-search-radio-target (target)
10811 "Search a radio target matching TARGET in current buffer.
10812 White spaces are not significant."
10813 (let ((re (format "<<<%s>>>"
10814 (mapconcat #'regexp-quote
10815 (split-string target)
10816 "[ \t]+\\(?:\n[ \t]*\\)?")))
10817 (origin (point)))
10818 (goto-char (point-min))
10819 (catch :radio-match
10820 (while (re-search-forward re nil t)
10821 (backward-char)
10822 (let ((object (org-element-context)))
10823 (when (eq (org-element-type object) 'radio-target)
10824 (goto-char (org-element-property :begin object))
10825 (org-show-context 'link-search)
10826 (throw :radio-match nil))))
10827 (goto-char origin)
10828 (user-error "No match for radio target: %s" target))))
10830 (defun org-link-search (s &optional avoid-pos stealth)
10831 "Search for a search string S.
10833 If S starts with \"#\", it triggers a custom ID search.
10835 If S is enclosed within parenthesis, it initiates a coderef
10836 search.
10838 If S is surrounded by forward slashes, it is interpreted as
10839 a regular expression. In Org mode files, this will create an
10840 `org-occur' sparse tree. In ordinary files, `occur' will be used
10841 to list matches. If the current buffer is in `dired-mode', grep
10842 will be used to search in all files.
10844 When AVOID-POS is given, ignore matches near that position.
10846 When optional argument STEALTH is non-nil, do not modify
10847 visibility around point, thus ignoring `org-show-context-detail'
10848 variable.
10850 Search is case-insensitive and ignores white spaces. Return type
10851 of matched result, which is either `dedicated' or `fuzzy'."
10852 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10853 (let* ((case-fold-search t)
10854 (origin (point))
10855 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10856 (starred (eq (string-to-char normalized) ?*))
10857 (words (split-string (if starred (substring s 1) s)))
10858 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
10859 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10860 type)
10861 (cond
10862 ;; Check if there are any special search functions.
10863 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10864 ((eq (string-to-char s) ?#)
10865 ;; Look for a custom ID S if S starts with "#".
10866 (let* ((id (substring normalized 1))
10867 (match (org-find-property "CUSTOM_ID" id)))
10868 (if match (progn (goto-char match) (setf type 'dedicated))
10869 (error "No match for custom ID: %s" id))))
10870 ((string-match "\\`(\\(.*\\))\\'" normalized)
10871 ;; Look for coderef targets if S is enclosed within parenthesis.
10872 (let ((coderef (match-string-no-properties 1 normalized))
10873 (re (substring s-single-re 1 -1)))
10874 (goto-char (point-min))
10875 (catch :coderef-match
10876 (while (re-search-forward re nil t)
10877 (let ((element (org-element-at-point)))
10878 (when (and (memq (org-element-type element)
10879 '(example-block src-block))
10880 ;; Build proper regexp according to current
10881 ;; block's label format.
10882 (let ((label-fmt
10883 (regexp-quote
10884 (or (org-element-property :label-fmt element)
10885 org-coderef-label-format))))
10886 (save-excursion
10887 (beginning-of-line)
10888 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10889 (format label-fmt coderef))))))
10890 (setq type 'dedicated)
10891 (goto-char (match-beginning 1))
10892 (throw :coderef-match nil))))
10893 (goto-char origin)
10894 (error "No match for coderef: %s" coderef))))
10895 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10896 ;; Look for a regular expression.
10897 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10898 (match-string 1 s)))
10899 ;; From here, we handle fuzzy links.
10901 ;; Look for targets, only if not in a headline search.
10902 ((and (not starred)
10903 (let ((target (format "<<%s>>" s-multi-re)))
10904 (catch :target-match
10905 (goto-char (point-min))
10906 (while (re-search-forward target nil t)
10907 (backward-char)
10908 (let ((context (org-element-context)))
10909 (when (eq (org-element-type context) 'target)
10910 (setq type 'dedicated)
10911 (goto-char (org-element-property :begin context))
10912 (throw :target-match t))))
10913 nil))))
10914 ;; Look for elements named after S, only if not in a headline
10915 ;; search.
10916 ((and (not starred)
10917 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10918 (catch :name-match
10919 (goto-char (point-min))
10920 (while (re-search-forward name nil t)
10921 (let ((element (org-element-at-point)))
10922 (when (equal words
10923 (split-string
10924 (org-element-property :name element)))
10925 (setq type 'dedicated)
10926 (beginning-of-line)
10927 (throw :name-match t))))
10928 nil))))
10929 ;; Regular text search. Prefer headlines in Org mode buffers.
10930 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
10931 ;; statistics cookies and tags.
10932 ((and (derived-mode-p 'org-mode)
10933 (let ((title-re
10934 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
10935 org-outline-regexp-bol
10936 org-comment-string
10937 (mapconcat #'regexp-quote words ".+")))
10938 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
10939 (comment-re (eval-when-compile
10940 (format "\\`%s[ \t]+" org-comment-string))))
10941 (goto-char (point-min))
10942 (catch :found
10943 (while (re-search-forward title-re nil t)
10944 (when (equal words
10945 (split-string
10946 (replace-regexp-in-string
10947 cookie-re ""
10948 (replace-regexp-in-string
10949 comment-re "" (org-get-heading t t t)))))
10950 (throw :found t)))
10951 nil)))
10952 (beginning-of-line)
10953 (setq type 'dedicated))
10954 ;; Offer to create non-existent headline depending on
10955 ;; `org-link-search-must-match-exact-headline'.
10956 ((and (derived-mode-p 'org-mode)
10957 (not org-link-search-inhibit-query)
10958 (eq org-link-search-must-match-exact-headline 'query-to-create)
10959 (yes-or-no-p "No match - create this as a new heading? "))
10960 (goto-char (point-max))
10961 (unless (bolp) (newline))
10962 (org-insert-heading nil t t)
10963 (insert s "\n")
10964 (beginning-of-line 0))
10965 ;; Only headlines are looked after. No need to process
10966 ;; further: throw an error.
10967 ((and (derived-mode-p 'org-mode)
10968 (or starred org-link-search-must-match-exact-headline))
10969 (goto-char origin)
10970 (error "No match for fuzzy expression: %s" normalized))
10971 ;; Regular text search.
10972 ((catch :fuzzy-match
10973 (goto-char (point-min))
10974 (while (re-search-forward s-multi-re nil t)
10975 ;; Skip match if it contains AVOID-POS or it is included in
10976 ;; a link with a description but outside the description.
10977 (unless (or (and avoid-pos
10978 (<= (match-beginning 0) avoid-pos)
10979 (> (match-end 0) avoid-pos))
10980 (and (save-match-data
10981 (org-in-regexp org-bracket-link-regexp))
10982 (match-beginning 3)
10983 (or (> (match-beginning 3) (point))
10984 (<= (match-end 3) (point)))
10985 (org-element-lineage
10986 (save-match-data (org-element-context))
10987 '(link) t)))
10988 (goto-char (match-beginning 0))
10989 (setq type 'fuzzy)
10990 (throw :fuzzy-match t)))
10991 nil))
10992 ;; All failed. Throw an error.
10993 (t (goto-char origin)
10994 (error "No match for fuzzy expression: %s" normalized)))
10995 ;; Disclose surroundings of match, if appropriate.
10996 (when (and (derived-mode-p 'org-mode) (not stealth))
10997 (org-show-context 'link-search))
10998 type))
11000 (defun org-get-buffer-for-internal-link (buffer)
11001 "Return a buffer to be used for displaying the link target of internal links."
11002 (cond
11003 ((not org-display-internal-link-with-indirect-buffer)
11004 buffer)
11005 ((string-suffix-p "(Clone)" (buffer-name buffer))
11006 (message "Buffer is already a clone, not making another one")
11007 ;; we also do not modify visibility in this case
11008 buffer)
11009 (t ; make a new indirect buffer for displaying the link
11010 (let* ((bn (buffer-name buffer))
11011 (ibn (concat bn "(Clone)"))
11012 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11013 (with-current-buffer ib (org-overview))
11014 ib))))
11016 (defun org-do-occur (regexp &optional cleanup)
11017 "Call the Emacs command `occur'.
11018 If CLEANUP is non-nil, remove the printout of the regular expression
11019 in the *Occur* buffer. This is useful if the regex is long and not useful
11020 to read."
11021 (occur regexp)
11022 (when cleanup
11023 (let ((cwin (selected-window)) win beg end)
11024 (when (setq win (get-buffer-window "*Occur*"))
11025 (select-window win))
11026 (goto-char (point-min))
11027 (when (re-search-forward "match[a-z]+" nil t)
11028 (setq beg (match-end 0))
11029 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11030 (setq end (1- (match-beginning 0)))))
11031 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11032 (goto-char (point-min))
11033 (select-window cwin))))
11035 ;;; The mark ring for links jumps
11037 (defvar org-mark-ring nil
11038 "Mark ring for positions before jumps in Org mode.")
11039 (defvar org-mark-ring-last-goto nil
11040 "Last position in the mark ring used to go back.")
11041 ;; Fill and close the ring
11042 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11043 (dotimes (_ org-mark-ring-length)
11044 (push (make-marker) org-mark-ring))
11045 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11046 org-mark-ring)
11048 (defun org-mark-ring-push (&optional pos buffer)
11049 "Put the current position or POS into the mark ring and rotate it."
11050 (interactive)
11051 (setq pos (or pos (point)))
11052 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11053 (move-marker (car org-mark-ring)
11054 (or pos (point))
11055 (or buffer (current-buffer)))
11056 (message "%s"
11057 (substitute-command-keys
11058 "Position saved to mark ring, go back with \
11059 `\\[org-mark-ring-goto]'.")))
11061 (defun org-mark-ring-goto (&optional n)
11062 "Jump to the previous position in the mark ring.
11063 With prefix arg N, jump back that many stored positions. When
11064 called several times in succession, walk through the entire ring.
11065 Org mode commands jumping to a different position in the current file,
11066 or to another Org file, automatically push the old position onto the ring."
11067 (interactive "p")
11068 (let (p m)
11069 (if (eq last-command this-command)
11070 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11071 (setq p org-mark-ring))
11072 (setq org-mark-ring-last-goto p)
11073 (setq m (car p))
11074 (pop-to-buffer-same-window (marker-buffer m))
11075 (goto-char m)
11076 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11078 (defun org-add-angle-brackets (s)
11079 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11080 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11083 ;;; Following specific links
11085 (defvar org-agenda-buffer-tmp-name)
11086 (defvar org-agenda-start-on-weekday)
11087 (defun org-follow-timestamp-link ()
11088 "Open an agenda view for the time-stamp date/range at point."
11089 (cond
11090 ((org-at-date-range-p t)
11091 (let ((org-agenda-start-on-weekday)
11092 (t1 (match-string 1))
11093 (t2 (match-string 2)) tt1 tt2)
11094 (setq tt1 (time-to-days (org-time-string-to-time t1))
11095 tt2 (time-to-days (org-time-string-to-time t2)))
11096 (let ((org-agenda-buffer-tmp-name
11097 (format "*Org Agenda(a:%s)"
11098 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11099 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11100 ((org-at-timestamp-p 'lax)
11101 (let ((org-agenda-buffer-tmp-name
11102 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11103 (org-agenda-list nil (time-to-days (org-time-string-to-time
11104 (substring (match-string 1) 0 10)))
11105 1)))
11106 (t (error "This should not happen"))))
11109 ;;; Following file links
11110 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11111 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11112 (declare-function mailcap-mime-info
11113 "mailcap" (string &optional request no-decode))
11114 (defvar org-wait nil)
11115 (defun org-open-file (path &optional in-emacs line search)
11116 "Open the file at PATH.
11117 First, this expands any special file name abbreviations. Then the
11118 configuration variable `org-file-apps' is checked if it contains an
11119 entry for this file type, and if yes, the corresponding command is launched.
11121 If no application is found, Emacs simply visits the file.
11123 With optional prefix argument IN-EMACS, Emacs will visit the file.
11124 With a double \\[universal-argument] \\[universal-argument] \
11125 prefix arg, Org tries to avoid opening in Emacs
11126 and to use an external application to visit the file.
11128 Optional LINE specifies a line to go to, optional SEARCH a string
11129 to search for. If LINE or SEARCH is given, the file will be
11130 opened in Emacs, unless an entry from org-file-apps that makes
11131 use of groups in a regexp matches.
11133 If you want to change the way frames are used when following a
11134 link, please customize `org-link-frame-setup'.
11136 If the file does not exist, an error is thrown."
11137 (let* ((file (if (equal path "")
11138 buffer-file-name
11139 (substitute-in-file-name (expand-file-name path))))
11140 (file-apps (append org-file-apps (org-default-apps)))
11141 (apps (cl-remove-if
11142 'org-file-apps-entry-match-against-dlink-p file-apps))
11143 (apps-dlink (cl-remove-if-not
11144 'org-file-apps-entry-match-against-dlink-p file-apps))
11145 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11146 (dirp (unless remp (file-directory-p file)))
11147 (file (if (and dirp org-open-directory-means-index-dot-org)
11148 (concat (file-name-as-directory file) "index.org")
11149 file))
11150 (a-m-a-p (assq 'auto-mode apps))
11151 (dfile (downcase file))
11152 ;; Reconstruct the original link from the PATH, LINE and
11153 ;; SEARCH args.
11154 (link (cond (line (concat file "::" (number-to-string line)))
11155 (search (concat file "::" search))
11156 (t file)))
11157 (dlink (downcase link))
11158 (ext
11159 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11160 (match-string 1 dfile)))
11161 (save-position-maybe
11162 (let ((old-buffer (current-buffer))
11163 (old-pos (point))
11164 (old-mode major-mode))
11165 (lambda ()
11166 (and (derived-mode-p 'org-mode)
11167 (eq old-mode 'org-mode)
11168 (or (not (eq old-buffer (current-buffer)))
11169 (not (eq old-pos (point))))
11170 (org-mark-ring-push old-pos old-buffer)))))
11171 cmd link-match-data)
11172 (cond
11173 ((member in-emacs '((16) system))
11174 (setq cmd (cdr (assq 'system apps))))
11175 (in-emacs (setq cmd 'emacs))
11177 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11178 (and dirp (cdr (assq 'directory apps)))
11179 ;; First, try matching against apps-dlink if we
11180 ;; get a match here, store the match data for
11181 ;; later.
11182 (let ((match (assoc-default dlink apps-dlink
11183 'string-match)))
11184 (if match
11185 (progn (setq link-match-data (match-data))
11186 match)
11187 (progn (setq in-emacs (or in-emacs line search))
11188 nil))) ; if we have no match in apps-dlink,
11189 ; always open the file in emacs if line or search
11190 ; is given (for backwards compatibility)
11191 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11192 'string-match)
11193 (cdr (assoc ext apps))
11194 (cdr (assq t apps))))))
11195 (when (eq cmd 'system)
11196 (setq cmd (cdr (assq 'system apps))))
11197 (when (eq cmd 'default)
11198 (setq cmd (cdr (assoc t apps))))
11199 (when (eq cmd 'mailcap)
11200 (require 'mailcap)
11201 (mailcap-parse-mailcaps)
11202 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11203 (command (mailcap-mime-info mime-type)))
11204 (if (stringp command)
11205 (setq cmd command)
11206 (setq cmd 'emacs))))
11207 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11208 (not (file-exists-p file))
11209 (not org-open-non-existing-files))
11210 (user-error "No such file: %s" file))
11211 (cond
11212 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11213 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11214 (while (string-match "['\"]%s['\"]" cmd)
11215 (setq cmd (replace-match "%s" t t cmd)))
11216 (setq cmd (replace-regexp-in-string
11217 "%s"
11218 (shell-quote-argument (convert-standard-filename file))
11220 nil t))
11222 ;; Replace "%1", "%2" etc. in command with group matches from regex
11223 (save-match-data
11224 (let ((match-index 1)
11225 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11226 (set-match-data link-match-data)
11227 (while (<= match-index number-of-groups)
11228 (let ((regex (concat "%" (number-to-string match-index)))
11229 (replace-with (match-string match-index dlink)))
11230 (while (string-match regex cmd)
11231 (setq cmd (replace-match replace-with t t cmd))))
11232 (setq match-index (+ match-index 1)))))
11234 (save-window-excursion
11235 (message "Running %s...done" cmd)
11236 (start-process-shell-command cmd nil cmd)
11237 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11238 ((or (stringp cmd)
11239 (eq cmd 'emacs))
11240 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11241 (widen)
11242 (cond (line (org-goto-line line)
11243 (when (derived-mode-p 'org-mode) (org-reveal)))
11244 (search (condition-case err
11245 (org-link-search search)
11246 ;; Save position before error-ing out so user
11247 ;; can easily move back to the original buffer.
11248 (error (funcall save-position-maybe)
11249 (error (nth 1 err)))))))
11250 ((functionp cmd)
11251 (save-match-data
11252 (set-match-data link-match-data)
11253 (condition-case nil
11254 (funcall cmd file link)
11255 ;; FIXME: Remove this check when most default installations
11256 ;; of Emacs have at least Org 9.0.
11257 ((debug wrong-number-of-arguments wrong-type-argument
11258 invalid-function)
11259 (user-error "Please see Org News for version 9.0 about \
11260 `org-file-apps'--Lisp error: %S" cmd)))))
11261 ((consp cmd)
11262 ;; FIXME: Remove this check when most default installations of
11263 ;; Emacs have at least Org 9.0. Heads-up instead of silently
11264 ;; fall back to `org-link-frame-setup' for an old usage of
11265 ;; `org-file-apps' with sexp instead of a function for `cmd'.
11266 (user-error "Please see Org News for version 9.0 about \
11267 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11268 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11269 (funcall save-position-maybe)))
11271 (defun org-file-apps-entry-match-against-dlink-p (entry)
11272 "This function returns non-nil if `entry' uses a regular
11273 expression which should be matched against the whole link by
11274 org-open-file.
11276 It assumes that is the case when the entry uses a regular
11277 expression which has at least one grouping construct and the
11278 action is either a lisp form or a command string containing
11279 `%1', i.e. using at least one subexpression match as a
11280 parameter."
11281 (let ((selector (car entry))
11282 (action (cdr entry)))
11283 (if (stringp selector)
11284 (and (> (regexp-opt-depth selector) 0)
11285 (or (and (stringp action)
11286 (string-match "%[0-9]" action))
11287 (consp action)))
11288 nil)))
11290 (defun org-default-apps ()
11291 "Return the default applications for this operating system."
11292 (cond
11293 ((eq system-type 'darwin)
11294 org-file-apps-defaults-macosx)
11295 ((eq system-type 'windows-nt)
11296 org-file-apps-defaults-windowsnt)
11297 (t org-file-apps-defaults-gnu)))
11299 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11300 "Convert extensions to regular expressions in the cars of LIST.
11301 Also, weed out any non-string entries, because the return value is used
11302 only for regexp matching.
11303 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11304 point to the symbol `emacs', indicating that the file should
11305 be opened in Emacs."
11306 (append
11307 (delq nil
11308 (mapcar (lambda (x)
11309 (unless (not (stringp (car x)))
11310 (if (string-match "\\W" (car x))
11312 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11313 list))
11314 (when add-auto-mode
11315 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11317 (defvar ange-ftp-name-format)
11318 (defun org-file-remote-p (file)
11319 "Test whether FILE specifies a location on a remote system.
11320 Return non-nil if the location is indeed remote.
11322 For example, the filename \"/user@host:/foo\" specifies a location
11323 on the system \"/user@host:\"."
11324 (cond ((fboundp 'file-remote-p)
11325 (file-remote-p file))
11326 ((fboundp 'tramp-handle-file-remote-p)
11327 (tramp-handle-file-remote-p file))
11328 ((and (boundp 'ange-ftp-name-format)
11329 (string-match (car ange-ftp-name-format) file))
11330 t)))
11333 ;;;; Refiling
11335 (defun org-get-org-file ()
11336 "Read a filename, with default directory `org-directory'."
11337 (let ((default (or org-default-notes-file remember-data-file)))
11338 (read-file-name (format "File name [%s]: " default)
11339 (file-name-as-directory org-directory)
11340 default)))
11342 (defun org-notes-order-reversed-p ()
11343 "Check if the current file should receive notes in reversed order."
11344 (cond
11345 ((not org-reverse-note-order) nil)
11346 ((eq t org-reverse-note-order) t)
11347 ((not (listp org-reverse-note-order)) nil)
11348 (t (catch 'exit
11349 (dolist (entry org-reverse-note-order)
11350 (when (string-match (car entry) buffer-file-name)
11351 (throw 'exit (cdr entry))))))))
11353 (defvar org-refile-target-table nil
11354 "The list of refile targets, created by `org-refile'.")
11356 (defvar org-agenda-new-buffers nil
11357 "Buffers created to visit agenda files.")
11359 (defvar org-refile-cache nil
11360 "Cache for refile targets.")
11362 (defvar org-refile-markers nil
11363 "All the markers used for caching refile locations.")
11365 (defun org-refile-marker (pos)
11366 "Get a new refile marker, but only if caching is in use."
11367 (if (not org-refile-use-cache)
11369 (let ((m (make-marker)))
11370 (move-marker m pos)
11371 (push m org-refile-markers)
11372 m)))
11374 (defun org-refile-cache-clear ()
11375 "Clear the refile cache and disable all the markers."
11376 (dolist (m org-refile-markers) (move-marker m nil))
11377 (setq org-refile-markers nil)
11378 (setq org-refile-cache nil)
11379 (message "Refile cache has been cleared"))
11381 (defun org-refile-cache-check-set (set)
11382 "Check if all the markers in the cache still have live buffers."
11383 (let (marker)
11384 (catch 'exit
11385 (while (and set (setq marker (nth 3 (pop set))))
11386 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11387 (when (and marker (null (marker-buffer marker)))
11388 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11389 (sit-for 3)
11390 (throw 'exit nil)))
11391 t)))
11393 (defun org-refile-cache-put (set &rest identifiers)
11394 "Push the refile targets SET into the cache, under IDENTIFIERS."
11395 (let* ((key (sha1 (prin1-to-string identifiers)))
11396 (entry (assoc key org-refile-cache)))
11397 (if entry
11398 (setcdr entry set)
11399 (push (cons key set) org-refile-cache))))
11401 (defun org-refile-cache-get (&rest identifiers)
11402 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11403 (cond
11404 ((not org-refile-cache) nil)
11405 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11407 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11408 org-refile-cache))))
11409 (and set (org-refile-cache-check-set set) set)))))
11411 (defvar org-outline-path-cache nil
11412 "Alist between buffer positions and outline paths.
11413 It value is an alist (POSITION . PATH) where POSITION is the
11414 buffer position at the beginning of an entry and PATH is a list
11415 of strings describing the outline path for that entry, in reverse
11416 order.")
11418 (defun org-refile-get-targets (&optional default-buffer)
11419 "Produce a table with refile targets."
11420 (let ((case-fold-search nil)
11421 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11422 (entries (or org-refile-targets '((nil . (:level . 1)))))
11423 targets tgs files desc descre)
11424 (message "Getting targets...")
11425 (with-current-buffer (or default-buffer (current-buffer))
11426 (dolist (entry entries)
11427 (setq files (car entry) desc (cdr entry))
11428 (cond
11429 ((null files) (setq files (list (current-buffer))))
11430 ((eq files 'org-agenda-files)
11431 (setq files (org-agenda-files 'unrestricted)))
11432 ((and (symbolp files) (fboundp files))
11433 (setq files (funcall files)))
11434 ((and (symbolp files) (boundp files))
11435 (setq files (symbol-value files))))
11436 (when (stringp files) (setq files (list files)))
11437 (cond
11438 ((eq (car desc) :tag)
11439 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11440 ((eq (car desc) :todo)
11441 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11442 ((eq (car desc) :regexp)
11443 (setq descre (cdr desc)))
11444 ((eq (car desc) :level)
11445 (setq descre (concat "^\\*\\{" (number-to-string
11446 (if org-odd-levels-only
11447 (1- (* 2 (cdr desc)))
11448 (cdr desc)))
11449 "\\}[ \t]")))
11450 ((eq (car desc) :maxlevel)
11451 (setq descre (concat "^\\*\\{1," (number-to-string
11452 (if org-odd-levels-only
11453 (1- (* 2 (cdr desc)))
11454 (cdr desc)))
11455 "\\}[ \t]")))
11456 (t (error "Bad refiling target description %s" desc)))
11457 (dolist (f files)
11458 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11460 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11461 (progn
11462 (when (bufferp f)
11463 (setq f (buffer-file-name (buffer-base-buffer f))))
11464 (setq f (and f (expand-file-name f)))
11465 (when (eq org-refile-use-outline-path 'file)
11466 (push (list (file-name-nondirectory f) f nil nil) tgs))
11467 (when (eq org-refile-use-outline-path 'buffer-name)
11468 (push (list (buffer-name (buffer-base-buffer)) f nil nil) tgs))
11469 (when (eq org-refile-use-outline-path 'full-file-path)
11470 (push (list (file-truename (buffer-file-name (buffer-base-buffer))) f nil nil) tgs))
11471 (org-with-wide-buffer
11472 (goto-char (point-min))
11473 (setq org-outline-path-cache nil)
11474 (while (re-search-forward descre nil t)
11475 (beginning-of-line)
11476 (let ((case-fold-search nil))
11477 (looking-at org-complex-heading-regexp))
11478 (let ((begin (point))
11479 (heading (match-string-no-properties 4)))
11480 (unless (or (and
11481 org-refile-target-verify-function
11482 (not
11483 (funcall org-refile-target-verify-function)))
11484 (not heading))
11485 (let ((re (format org-complex-heading-regexp-format
11486 (regexp-quote heading)))
11487 (target
11488 (if (not org-refile-use-outline-path) heading
11489 (mapconcat
11490 #'identity
11491 (append
11492 (pcase org-refile-use-outline-path
11493 (`file (list (file-name-nondirectory
11494 (buffer-file-name
11495 (buffer-base-buffer)))))
11496 (`full-file-path
11497 (list (buffer-file-name
11498 (buffer-base-buffer))))
11499 (`buffer-name
11500 (list (buffer-name
11501 (buffer-base-buffer))))
11502 (_ nil))
11503 (mapcar (lambda (s) (replace-regexp-in-string
11504 "/" "\\/" s nil t))
11505 (org-get-outline-path t t)))
11506 "/"))))
11507 (push (list target f re (org-refile-marker (point)))
11508 tgs)))
11509 (when (= (point) begin)
11510 ;; Verification function has not moved point.
11511 (end-of-line)))))))
11512 (when org-refile-use-cache
11513 (org-refile-cache-put tgs (buffer-file-name) descre))
11514 (setq targets (append tgs targets))))))
11515 (message "Getting targets...done")
11516 (delete-dups (nreverse targets))))
11518 (defun org--get-outline-path-1 (&optional use-cache)
11519 "Return outline path to current headline.
11521 Outline path is a list of strings, in reverse order. When
11522 optional argument USE-CACHE is non-nil, make use of a cache. See
11523 `org-get-outline-path' for details.
11525 Assume buffer is widened and point is on a headline."
11526 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11527 (let ((p (point))
11528 (heading (let ((case-fold-search nil))
11529 (looking-at org-complex-heading-regexp)
11530 (if (not (match-end 4)) ""
11531 ;; Remove statistics cookies.
11532 (org-trim
11533 (org-link-display-format
11534 (replace-regexp-in-string
11535 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11536 (match-string-no-properties 4))))))))
11537 (if (org-up-heading-safe)
11538 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11539 (when use-cache
11540 (push (cons p path) org-outline-path-cache))
11541 path)
11542 ;; This is a new root node. Since we assume we are moving
11543 ;; forward, we can drop previous cache so as to limit number
11544 ;; of associations there.
11545 (let ((path (list heading)))
11546 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11547 path)))))
11549 (defun org-get-outline-path (&optional with-self use-cache)
11550 "Return the outline path to the current entry.
11552 An outline path is a list of ancestors for current headline, as
11553 a list of strings. Statistics cookies are removed and links are
11554 replaced with their description, if any, or their path otherwise.
11556 When optional argument WITH-SELF is non-nil, the path also
11557 includes the current headline.
11559 When optional argument USE-CACHE is non-nil, cache outline paths
11560 between calls to this function so as to avoid backtracking. This
11561 argument is useful when planning to find more than one outline
11562 path in the same document. In that case, there are two
11563 conditions to satisfy:
11564 - `org-outline-path-cache' is set to nil before starting the
11565 process;
11566 - outline paths are computed by increasing buffer positions."
11567 (org-with-wide-buffer
11568 (and (or (and with-self (org-back-to-heading t))
11569 (org-up-heading-safe))
11570 (reverse (org--get-outline-path-1 use-cache)))))
11572 (defun org-format-outline-path (path &optional width prefix separator)
11573 "Format the outline path PATH for display.
11574 WIDTH is the maximum number of characters that is available.
11575 PREFIX is a prefix to be included in the returned string,
11576 such as the file name.
11577 SEPARATOR is inserted between the different parts of the path,
11578 the default is \"/\"."
11579 (setq width (or width 79))
11580 (setq path (delq nil path))
11581 (unless (> width 0)
11582 (user-error "Argument `width' must be positive"))
11583 (setq separator (or separator "/"))
11584 (let* ((org-odd-levels-only nil)
11585 (fpath (concat
11586 prefix (and prefix path separator)
11587 (mapconcat
11588 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11589 (cl-loop for head in path
11590 for n from 0
11591 collect (org-add-props
11592 head nil 'face
11593 (nth (% n org-n-level-faces) org-level-faces)))
11594 separator))))
11595 (when (> (length fpath) width)
11596 (if (< width 7)
11597 ;; It's unlikely that `width' will be this small, but don't
11598 ;; waste characters by adding ".." if it is.
11599 (setq fpath (substring fpath 0 width))
11600 (setf (substring fpath (- width 2)) "..")))
11601 fpath))
11603 (defun org-display-outline-path (&optional file current separator just-return-string)
11604 "Display the current outline path in the echo area.
11606 If FILE is non-nil, prepend the output with the file name.
11607 If CURRENT is non-nil, append the current heading to the output.
11608 SEPARATOR is passed through to `org-format-outline-path'. It separates
11609 the different parts of the path and defaults to \"/\".
11610 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11611 (interactive "P")
11612 (let* (case-fold-search
11613 (bfn (buffer-file-name (buffer-base-buffer)))
11614 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11615 res)
11616 (when current (setq path (append path
11617 (save-excursion
11618 (org-back-to-heading t)
11619 (when (looking-at org-complex-heading-regexp)
11620 (list (match-string 4)))))))
11621 (setq res
11622 (org-format-outline-path
11623 path
11624 (1- (frame-width))
11625 (and file bfn (concat (file-name-nondirectory bfn) separator))
11626 separator))
11627 (if just-return-string
11628 (org-no-properties res)
11629 (org-unlogged-message "%s" res))))
11631 (defvar org-refile-history nil
11632 "History for refiling operations.")
11634 (defvar org-after-refile-insert-hook nil
11635 "Hook run after `org-refile' has inserted its stuff at the new location.
11636 Note that this is still *before* the stuff will be removed from
11637 the *old* location.")
11639 (defvar org-capture-last-stored-marker)
11640 (defvar org-refile-keep nil
11641 "Non-nil means `org-refile' will copy instead of refile.")
11643 (defun org-copy ()
11644 "Like `org-refile', but copy."
11645 (interactive)
11646 (let ((org-refile-keep t))
11647 (funcall 'org-refile nil nil nil "Copy")))
11649 (defun org-refile (&optional arg default-buffer rfloc msg)
11650 "Move the entry or entries at point to another heading.
11652 The list of target headings is compiled using the information in
11653 `org-refile-targets', which see.
11655 At the target location, the entry is filed as a subitem of the
11656 target heading. Depending on `org-reverse-note-order', the new
11657 subitem will either be the first or the last subitem.
11659 If there is an active region, all entries in that region will be
11660 refiled. However, the region must fulfill the requirement that
11661 the first heading sets the top-level of the moved text.
11663 With a `\\[universal-argument]' ARG, the command will only visit the target \
11664 location
11665 and not actually move anything.
11667 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11668 location where the last
11669 refiling operation has put the subtree.
11671 With a numeric prefix argument of `2', refile to the running clock.
11673 With a numeric prefix argument of `3', emulate `org-refile-keep'
11674 being set to t and copy to the target location, don't move it.
11675 Beware that keeping refiled entries may result in duplicated ID
11676 properties.
11678 RFLOC can be a refile location obtained in a different way.
11680 MSG is a string to replace \"Refile\" in the default prompt with
11681 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11683 See also `org-refile-use-outline-path'.
11685 If you are using target caching (see `org-refile-use-cache'), you
11686 have to clear the target cache in order to find new targets.
11687 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11688 prefix argument (`C-u C-u C-u C-c C-w')."
11689 (interactive "P")
11690 (if (member arg '(0 (64)))
11691 (org-refile-cache-clear)
11692 (let* ((actionmsg (cond (msg msg)
11693 ((equal arg 3) "Refile (and keep)")
11694 (t "Refile")))
11695 (regionp (org-region-active-p))
11696 (region-start (and regionp (region-beginning)))
11697 (region-end (and regionp (region-end)))
11698 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11699 pos it nbuf file level reversed)
11700 (setq last-command nil)
11701 (when regionp
11702 (goto-char region-start)
11703 (or (bolp) (goto-char (point-at-bol)))
11704 (setq region-start (point))
11705 (unless (or (org-kill-is-subtree-p
11706 (buffer-substring region-start region-end))
11707 (prog1 org-refile-active-region-within-subtree
11708 (let ((s (point-at-eol)))
11709 (org-toggle-heading)
11710 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11711 (user-error "The region is not a (sequence of) subtree(s)")))
11712 (if (equal arg '(16))
11713 (org-refile-goto-last-stored)
11714 (when (or
11715 (and (equal arg 2)
11716 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11717 (prog1
11718 (setq it (list (or org-clock-heading "running clock")
11719 (buffer-file-name
11720 (marker-buffer org-clock-hd-marker))
11722 (marker-position org-clock-hd-marker)))
11723 (setq arg nil)))
11724 (setq it
11725 (or rfloc
11726 (let (heading-text)
11727 (save-excursion
11728 (unless (and arg (listp arg))
11729 (org-back-to-heading t)
11730 (setq heading-text
11731 (replace-regexp-in-string
11732 org-bracket-link-regexp
11733 "\\3"
11734 (or (nth 4 (org-heading-components))
11735 ""))))
11736 (org-refile-get-location
11737 (cond ((and arg (listp arg)) "Goto")
11738 (regionp (concat actionmsg " region to"))
11739 (t (concat actionmsg " subtree \""
11740 heading-text "\" to")))
11741 default-buffer
11742 (and (not (equal '(4) arg))
11743 org-refile-allow-creating-parent-nodes)))))))
11744 (setq file (nth 1 it)
11745 pos (nth 3 it))
11746 (when (and (not arg)
11748 (equal (buffer-file-name) file)
11749 (if regionp
11750 (and (>= pos region-start)
11751 (<= pos region-end))
11752 (and (>= pos (point))
11753 (< pos (save-excursion
11754 (org-end-of-subtree t t))))))
11755 (error "Cannot refile to position inside the tree or region"))
11756 (setq nbuf (or (find-buffer-visiting file)
11757 (find-file-noselect file)))
11758 (if (and arg (not (equal arg 3)))
11759 (progn
11760 (pop-to-buffer-same-window nbuf)
11761 (goto-char (cond (pos)
11762 ((org-notes-order-reversed-p) (point-min))
11763 (t (point-max))))
11764 (org-show-context 'org-goto))
11765 (if regionp
11766 (progn
11767 (org-kill-new (buffer-substring region-start region-end))
11768 (org-save-markers-in-region region-start region-end))
11769 (org-copy-subtree 1 nil t))
11770 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11771 (find-file-noselect file)))
11772 (setq reversed (org-notes-order-reversed-p))
11773 (org-with-wide-buffer
11774 (if pos
11775 (progn
11776 (goto-char pos)
11777 (setq level (org-get-valid-level (funcall outline-level) 1))
11778 (goto-char
11779 (if reversed
11780 (or (outline-next-heading) (point-max))
11781 (or (save-excursion (org-get-next-sibling))
11782 (org-end-of-subtree t t)
11783 (point-max)))))
11784 (setq level 1)
11785 (if (not reversed)
11786 (goto-char (point-max))
11787 (goto-char (point-min))
11788 (or (outline-next-heading) (goto-char (point-max)))))
11789 (unless (bolp) (newline))
11790 (org-paste-subtree level nil nil t)
11791 (when org-log-refile
11792 (org-add-log-setup 'refile nil nil org-log-refile)
11793 (unless (eq org-log-refile 'note)
11794 (save-excursion (org-add-log-note))))
11795 (and org-auto-align-tags
11796 (let ((org-loop-over-headlines-in-active-region nil))
11797 (org-set-tags nil t)))
11798 (let ((bookmark-name (plist-get org-bookmark-names-plist
11799 :last-refile)))
11800 (when bookmark-name
11801 (with-demoted-errors
11802 (bookmark-set bookmark-name))))
11803 ;; If we are refiling for capture, make sure that the
11804 ;; last-capture pointers point here
11805 (when (bound-and-true-p org-capture-is-refiling)
11806 (let ((bookmark-name (plist-get org-bookmark-names-plist
11807 :last-capture-marker)))
11808 (when bookmark-name
11809 (with-demoted-errors
11810 (bookmark-set bookmark-name))))
11811 (move-marker org-capture-last-stored-marker (point)))
11812 (when (fboundp 'deactivate-mark) (deactivate-mark))
11813 (run-hooks 'org-after-refile-insert-hook)))
11814 (unless org-refile-keep
11815 (if regionp
11816 (delete-region (point) (+ (point) (- region-end region-start)))
11817 (delete-region
11818 (and (org-back-to-heading t) (point))
11819 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11820 (when (featurep 'org-inlinetask)
11821 (org-inlinetask-remove-END-maybe))
11822 (setq org-markers-to-move nil)
11823 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11825 (defun org-refile-goto-last-stored ()
11826 "Go to the location where the last refile was stored."
11827 (interactive)
11828 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11829 (message "This is the location of the last refile"))
11831 (defun org-refile--get-location (refloc tbl)
11832 "When user refile to REFLOC, find the associated target in TBL.
11833 Also check `org-refile-target-table'."
11834 (car (delq
11836 (mapcar
11837 (lambda (r) (or (assoc r tbl)
11838 (assoc r org-refile-target-table)))
11839 (list (replace-regexp-in-string "/$" "" refloc)
11840 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11842 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11843 "Prompt the user for a refile location, using PROMPT.
11844 PROMPT should not be suffixed with a colon and a space, because
11845 this function appends the default value from
11846 `org-refile-history' automatically, if that is not empty."
11847 (let ((org-refile-targets org-refile-targets)
11848 (org-refile-use-outline-path org-refile-use-outline-path))
11849 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11850 (unless org-refile-target-table
11851 (user-error "No refile targets"))
11852 (let* ((cbuf (current-buffer))
11853 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11854 (cfunc (if (and org-refile-use-outline-path
11855 org-outline-path-complete-in-steps)
11856 #'org-olpath-completing-read
11857 #'completing-read))
11858 (extra (if org-refile-use-outline-path "/" ""))
11859 (cbnex (concat (buffer-name) extra))
11860 (filename (and cfn (expand-file-name cfn)))
11861 (tbl (mapcar
11862 (lambda (x)
11863 (if (and (not (member org-refile-use-outline-path
11864 '(file full-file-path)))
11865 (not (equal filename (nth 1 x))))
11866 (cons (concat (car x) extra " ("
11867 (file-name-nondirectory (nth 1 x)) ")")
11868 (cdr x))
11869 (cons (concat (car x) extra) (cdr x))))
11870 org-refile-target-table))
11871 (completion-ignore-case t)
11872 cdef
11873 (prompt (concat prompt
11874 (or (and (car org-refile-history)
11875 (concat " (default " (car org-refile-history) ")"))
11876 (and (assoc cbnex tbl) (setq cdef cbnex)
11877 (concat " (default " cbnex ")"))) ": "))
11878 pa answ parent-target child parent old-hist)
11879 (setq old-hist org-refile-history)
11880 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11881 nil 'org-refile-history (or cdef (car org-refile-history))))
11882 (if (setq pa (org-refile--get-location answ tbl))
11883 (progn
11884 (org-refile-check-position pa)
11885 (when (or (not org-refile-history)
11886 (not (eq old-hist org-refile-history))
11887 (not (equal (car pa) (car org-refile-history))))
11888 (setq org-refile-history
11889 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11890 org-refile-history
11891 (cdr org-refile-history))))
11892 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11893 (pop org-refile-history)))
11895 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11896 (progn
11897 (setq parent (match-string 1 answ)
11898 child (match-string 2 answ))
11899 (setq parent-target (org-refile--get-location parent tbl))
11900 (when (and parent-target
11901 (or (eq new-nodes t)
11902 (and (eq new-nodes 'confirm)
11903 (y-or-n-p (format "Create new node \"%s\"? "
11904 child)))))
11905 (org-refile-new-child parent-target child)))
11906 (user-error "Invalid target location")))))
11908 (declare-function org-string-nw-p "org-macs" (s))
11909 (defun org-refile-check-position (refile-pointer)
11910 "Check if the refile pointer matches the headline to which it points."
11911 (let* ((file (nth 1 refile-pointer))
11912 (re (nth 2 refile-pointer))
11913 (pos (nth 3 refile-pointer))
11914 buffer)
11915 (if (and (not (markerp pos)) (not file))
11916 (user-error "Please indicate a target file in the refile path")
11917 (when (org-string-nw-p re)
11918 (setq buffer (if (markerp pos)
11919 (marker-buffer pos)
11920 (or (find-buffer-visiting file)
11921 (find-file-noselect file))))
11922 (with-current-buffer buffer
11923 (org-with-wide-buffer
11924 (goto-char pos)
11925 (beginning-of-line 1)
11926 (unless (looking-at-p re)
11927 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
11929 (defun org-refile-new-child (parent-target child)
11930 "Use refile target PARENT-TARGET to add new CHILD below it."
11931 (unless parent-target
11932 (error "Cannot find parent for new node"))
11933 (let ((file (nth 1 parent-target))
11934 (pos (nth 3 parent-target))
11935 level)
11936 (with-current-buffer (or (find-buffer-visiting file)
11937 (find-file-noselect file))
11938 (org-with-wide-buffer
11939 (if pos
11940 (goto-char pos)
11941 (goto-char (point-max))
11942 (unless (bolp) (newline)))
11943 (when (looking-at org-outline-regexp)
11944 (setq level (funcall outline-level))
11945 (org-end-of-subtree t t))
11946 (org-back-over-empty-lines)
11947 (insert "\n" (make-string
11948 (if pos (org-get-valid-level level 1) 1) ?*)
11949 " " child "\n")
11950 (beginning-of-line 0)
11951 (list (concat (car parent-target) "/" child) file "" (point))))))
11953 (defun org-olpath-completing-read (prompt collection &rest args)
11954 "Read an outline path like a file name."
11955 (let ((thetable collection))
11956 (apply #'completing-read
11957 prompt
11958 (lambda (string predicate &optional flag)
11959 (cond
11960 ((eq flag nil) (try-completion string thetable))
11961 ((eq flag t)
11962 (let ((l (length string)))
11963 (mapcar (lambda (x)
11964 (let ((r (substring x l))
11965 (f (if (string-match " ([^)]*)$" x)
11966 (match-string 0 x)
11967 "")))
11968 (if (string-match "/" r)
11969 (concat string (substring r 0 (match-end 0)) f)
11970 x)))
11971 (all-completions string thetable predicate))))
11972 ;; Exact match?
11973 ((eq flag 'lambda) (assoc string thetable))))
11974 args)))
11976 ;;;; Dynamic blocks
11978 (defun org-find-dblock (name)
11979 "Find the first dynamic block with name NAME in the buffer.
11980 If not found, stay at current position and return nil."
11981 (let ((case-fold-search t) pos)
11982 (save-excursion
11983 (goto-char (point-min))
11984 (setq pos (and (re-search-forward
11985 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
11986 (match-beginning 0))))
11987 (when pos (goto-char pos))
11988 pos))
11990 (defun org-create-dblock (plist)
11991 "Create a dynamic block section, with parameters taken from PLIST.
11992 PLIST must contain a :name entry which is used as the name of the block."
11993 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
11994 (end-of-line 1)
11995 (newline))
11996 (let ((col (current-column))
11997 (name (plist-get plist :name)))
11998 (insert "#+BEGIN: " name)
11999 (while plist
12000 (if (eq (car plist) :name)
12001 (setq plist (cddr plist))
12002 (insert " " (prin1-to-string (pop plist)))))
12003 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12004 (beginning-of-line -2)))
12006 (defun org-prepare-dblock ()
12007 "Prepare dynamic block for refresh.
12008 This empties the block, puts the cursor at the insert position and returns
12009 the property list including an extra property :name with the block name."
12010 (unless (looking-at org-dblock-start-re)
12011 (user-error "Not at a dynamic block"))
12012 (let* ((begdel (1+ (match-end 0)))
12013 (name (org-no-properties (match-string 1)))
12014 (params (append (list :name name)
12015 (read (concat "(" (match-string 3) ")")))))
12016 (save-excursion
12017 (beginning-of-line 1)
12018 (skip-chars-forward " \t")
12019 (setq params (plist-put params :indentation-column (current-column))))
12020 (unless (re-search-forward org-dblock-end-re nil t)
12021 (error "Dynamic block not terminated"))
12022 (setq params
12023 (append params
12024 (list :content (buffer-substring
12025 begdel (match-beginning 0)))))
12026 (delete-region begdel (match-beginning 0))
12027 (goto-char begdel)
12028 (open-line 1)
12029 params))
12031 (defun org-map-dblocks (&optional command)
12032 "Apply COMMAND to all dynamic blocks in the current buffer.
12033 If COMMAND is not given, use `org-update-dblock'."
12034 (let ((cmd (or command 'org-update-dblock)))
12035 (save-excursion
12036 (goto-char (point-min))
12037 (while (re-search-forward org-dblock-start-re nil t)
12038 (goto-char (match-beginning 0))
12039 (save-excursion
12040 (condition-case nil
12041 (funcall cmd)
12042 (error (message "Error during update of dynamic block"))))
12043 (unless (re-search-forward org-dblock-end-re nil t)
12044 (error "Dynamic block not terminated"))))))
12046 (defun org-dblock-update (&optional arg)
12047 "User command for updating dynamic blocks.
12048 Update the dynamic block at point. With prefix ARG, update all dynamic
12049 blocks in the buffer."
12050 (interactive "P")
12051 (if arg
12052 (org-update-all-dblocks)
12053 (or (looking-at org-dblock-start-re)
12054 (org-beginning-of-dblock))
12055 (org-update-dblock)))
12057 (defun org-update-dblock ()
12058 "Update the dynamic block at point.
12059 This means to empty the block, parse for parameters and then call
12060 the correct writing function."
12061 (interactive)
12062 (save-excursion
12063 (let* ((win (selected-window))
12064 (pos (point))
12065 (line (org-current-line))
12066 (params (org-prepare-dblock))
12067 (name (plist-get params :name))
12068 (indent (plist-get params :indentation-column))
12069 (cmd (intern (concat "org-dblock-write:" name))))
12070 (message "Updating dynamic block `%s' at line %d..." name line)
12071 (funcall cmd params)
12072 (message "Updating dynamic block `%s' at line %d...done" name line)
12073 (goto-char pos)
12074 (when (and indent (> indent 0))
12075 (setq indent (make-string indent ?\ ))
12076 (save-excursion
12077 (select-window win)
12078 (org-beginning-of-dblock)
12079 (forward-line 1)
12080 (while (not (looking-at org-dblock-end-re))
12081 (insert indent)
12082 (beginning-of-line 2))
12083 (when (looking-at org-dblock-end-re)
12084 (and (looking-at "[ \t]+")
12085 (replace-match ""))
12086 (insert indent)))))))
12088 (defun org-beginning-of-dblock ()
12089 "Find the beginning of the dynamic block at point.
12090 Error if there is no such block at point."
12091 (let ((pos (point))
12092 beg)
12093 (end-of-line 1)
12094 (if (and (re-search-backward org-dblock-start-re nil t)
12095 (setq beg (match-beginning 0))
12096 (re-search-forward org-dblock-end-re nil t)
12097 (> (match-end 0) pos))
12098 (goto-char beg)
12099 (goto-char pos)
12100 (error "Not in a dynamic block"))))
12102 (defun org-update-all-dblocks ()
12103 "Update all dynamic blocks in the buffer.
12104 This function can be used in a hook."
12105 (interactive)
12106 (when (derived-mode-p 'org-mode)
12107 (org-map-dblocks 'org-update-dblock)))
12110 ;;;; Completion
12112 (declare-function org-export-backend-options "ox" (cl-x) t)
12113 (defun org-get-export-keywords ()
12114 "Return a list of all currently understood export keywords.
12115 Export keywords include options, block names, attributes and
12116 keywords relative to each registered export back-end."
12117 (let (keywords)
12118 (dolist (backend
12119 (bound-and-true-p org-export-registered-backends)
12120 (delq nil keywords))
12121 ;; Back-end name (for keywords, like #+LATEX:)
12122 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12123 (dolist (option-entry (org-export-backend-options backend))
12124 ;; Back-end options.
12125 (push (nth 1 option-entry) keywords)))))
12127 (defconst org-options-keywords
12128 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12129 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12130 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12131 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12132 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12134 (defcustom org-structure-template-alist
12135 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12136 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12137 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12138 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12139 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12140 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12141 ("C" "#+BEGIN_COMMENT\n?\n#+END_COMMENT")
12142 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12143 ("L" "#+LaTeX: ")
12144 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12145 ("H" "#+HTML: ")
12146 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12147 ("A" "#+ASCII: ")
12148 ("i" "#+INDEX: ?")
12149 ("I" "#+INCLUDE: %file ?"))
12150 "Structure completion elements.
12151 This is a list of abbreviation keys and values. The value gets inserted
12152 if you type `<' followed by the key and then press the completion key,
12153 usually `TAB'. %file will be replaced by a file name after prompting
12154 for the file using completion. The cursor will be placed at the position
12155 of the `?' in the template.
12156 There are two templates for each key, the first uses the original Org syntax,
12157 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12158 the default when the /org-mtags.el/ module has been loaded. See also the
12159 variable `org-mtags-prefer-muse-templates'."
12160 :group 'org-completion
12161 :type '(repeat
12162 (list
12163 (string :tag "Key")
12164 (string :tag "Template")))
12165 :version "26.1"
12166 :package-version '(Org . "8.3"))
12168 (defun org-try-structure-completion ()
12169 "Try to complete a structure template before point.
12170 This looks for strings like \"<e\" on an otherwise empty line and
12171 expands them."
12172 (let ((l (buffer-substring (point-at-bol) (point)))
12174 (when (and (looking-at "[ \t]*$")
12175 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12176 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12177 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12178 (match-beginning 1)) a)
12179 t)))
12181 (defun org-complete-expand-structure-template (start cell)
12182 "Expand a structure template."
12183 (let ((rpl (nth 1 cell))
12184 (ind ""))
12185 (delete-region start (point))
12186 (when (string-match "\\`[ \t]*#\\+" rpl)
12187 (cond
12188 ((bolp))
12189 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12190 (setq ind (buffer-substring (point-at-bol) (point))))
12191 (t (newline))))
12192 (setq start (point))
12193 (when (string-match "%file" rpl)
12194 (setq rpl (replace-match
12195 (concat
12196 "\""
12197 (save-match-data
12198 (abbreviate-file-name (read-file-name "Include file: ")))
12199 "\"")
12200 t t rpl)))
12201 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12202 (concat "\n" ind)))
12203 (insert rpl)
12204 (when (re-search-backward "\\?" start t) (delete-char 1))))
12206 ;;;; TODO, DEADLINE, Comments
12208 (defun org-toggle-comment ()
12209 "Change the COMMENT state of an entry."
12210 (interactive)
12211 (save-excursion
12212 (org-back-to-heading)
12213 (let ((case-fold-search nil))
12214 (looking-at org-complex-heading-regexp))
12215 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12216 (skip-chars-forward " \t")
12217 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12218 (if (org-in-commented-heading-p t)
12219 (delete-region (point)
12220 (progn (search-forward " " (line-end-position) 'move)
12221 (skip-chars-forward " \t")
12222 (point)))
12223 (insert org-comment-string)
12224 (unless (eolp) (insert " ")))))
12226 (defvar org-last-todo-state-is-todo nil
12227 "This is non-nil when the last TODO state change led to a TODO state.
12228 If the last change removed the TODO tag or switched to DONE, then
12229 this is nil.")
12231 (defvar org-setting-tags nil) ; dynamically skipped
12233 (defvar org-todo-setup-filter-hook nil
12234 "Hook for functions that pre-filter todo specs.
12235 Each function takes a todo spec and returns either nil or the spec
12236 transformed into canonical form." )
12238 (defvar org-todo-get-default-hook nil
12239 "Hook for functions that get a default item for todo.
12240 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12241 nil or a string to be used for the todo mark." )
12243 (defvar org-agenda-headline-snapshot-before-repeat)
12245 (defun org-current-effective-time ()
12246 "Return current time adjusted for `org-extend-today-until' variable."
12247 (let* ((ct (org-current-time))
12248 (dct (decode-time ct))
12249 (ct1
12250 (cond
12251 (org-use-last-clock-out-time-as-effective-time
12252 (or (org-clock-get-last-clock-out-time) ct))
12253 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12254 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12255 (t ct))))
12256 ct1))
12258 (defun org-todo-yesterday (&optional arg)
12259 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12260 (interactive "P")
12261 (if (eq major-mode 'org-agenda-mode)
12262 (apply 'org-agenda-todo-yesterday arg)
12263 (let* ((org-use-effective-time t)
12264 (hour (nth 2 (decode-time (org-current-time))))
12265 (org-extend-today-until (1+ hour)))
12266 (org-todo arg))))
12268 (defvar org-block-entry-blocking ""
12269 "First entry preventing the TODO state change.")
12271 (defun org-cancel-repeater ()
12272 "Cancel a repeater by setting its numeric value to zero."
12273 (interactive)
12274 (save-excursion
12275 (org-back-to-heading t)
12276 (let ((bound1 (point))
12277 (bound0 (save-excursion (outline-next-heading) (point))))
12278 (when (and (re-search-forward
12279 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12280 org-deadline-time-regexp "\\)\\|\\("
12281 org-ts-regexp "\\)")
12282 bound0 t)
12283 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12284 bound1 t))
12285 (replace-match "0" t nil nil 1)))))
12287 (defvar org-state)
12288 (defvar org-blocked-by-checkboxes)
12289 (defun org-todo (&optional arg)
12290 "Change the TODO state of an item.
12292 The state of an item is given by a keyword at the start of the heading,
12293 like
12294 *** TODO Write paper
12295 *** DONE Call mom
12297 The different keywords are specified in the variable `org-todo-keywords'.
12298 By default the available states are \"TODO\" and \"DONE\". So, for this
12299 example: when the item starts with TODO, it is changed to DONE.
12300 When it starts with DONE, the DONE is removed. And when neither TODO nor
12301 DONE are present, add TODO at the beginning of the heading.
12303 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12304 state.
12305 With numeric prefix ARG, switch to that state.
12306 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12307 next set of TODO \
12308 keywords (nextset).
12309 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12310 prefix, circumvent any state blocking.
12311 With a numeric prefix arg of 0, inhibit note taking for the change.
12312 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12314 When called through ELisp, arg is also interpreted in the following way:
12315 `none' -> empty state
12316 \"\" -> switch to empty state
12317 `done' -> switch to DONE
12318 `nextset' -> switch to the next set of keywords
12319 `previousset' -> switch to the previous set of keywords
12320 \"WAITING\" -> switch to the specified keyword, but only if it
12321 really is a member of `org-todo-keywords'."
12322 (interactive "P")
12323 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12324 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12325 'region-start-level 'region))
12326 org-loop-over-headlines-in-active-region)
12327 (org-map-entries
12328 `(org-todo ,arg)
12329 org-loop-over-headlines-in-active-region
12330 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12331 (when (equal arg '(16)) (setq arg 'nextset))
12332 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12333 (let ((org-blocker-hook org-blocker-hook)
12334 commentp
12335 case-fold-search)
12336 (when (equal arg '(64))
12337 (setq arg nil org-blocker-hook nil))
12338 (when (and org-blocker-hook
12339 (or org-inhibit-blocking
12340 (org-entry-get nil "NOBLOCKING")))
12341 (setq org-blocker-hook nil))
12342 (save-excursion
12343 (catch 'exit
12344 (org-back-to-heading t)
12345 (when (org-in-commented-heading-p t)
12346 (org-toggle-comment)
12347 (setq commentp t))
12348 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12349 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12350 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12351 (let* ((match-data (match-data))
12352 (startpos (point-at-bol))
12353 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12354 (org-log-done org-log-done)
12355 (org-log-repeat org-log-repeat)
12356 (org-todo-log-states org-todo-log-states)
12357 (org-inhibit-logging
12358 (if (equal arg 0)
12359 (progn (setq arg nil) 'note) org-inhibit-logging))
12360 (this (match-string 1))
12361 (hl-pos (match-beginning 0))
12362 (head (org-get-todo-sequence-head this))
12363 (ass (assoc head org-todo-kwd-alist))
12364 (interpret (nth 1 ass))
12365 (done-word (nth 3 ass))
12366 (final-done-word (nth 4 ass))
12367 (org-last-state (or this ""))
12368 (completion-ignore-case t)
12369 (member (member this org-todo-keywords-1))
12370 (tail (cdr member))
12371 (org-state (cond
12372 ((and org-todo-key-trigger
12373 (or (and (equal arg '(4))
12374 (eq org-use-fast-todo-selection 'prefix))
12375 (and (not arg) org-use-fast-todo-selection
12376 (not (eq org-use-fast-todo-selection
12377 'prefix)))))
12378 ;; Use fast selection.
12379 (org-fast-todo-selection))
12380 ((and (equal arg '(4))
12381 (or (not org-use-fast-todo-selection)
12382 (not org-todo-key-trigger)))
12383 ;; Read a state with completion.
12384 (completing-read
12385 "State: " (mapcar #'list org-todo-keywords-1)
12386 nil t))
12387 ((eq arg 'right)
12388 (if this
12389 (if tail (car tail) nil)
12390 (car org-todo-keywords-1)))
12391 ((eq arg 'left)
12392 (unless (equal member org-todo-keywords-1)
12393 (if this
12394 (nth (- (length org-todo-keywords-1)
12395 (length tail) 2)
12396 org-todo-keywords-1)
12397 (org-last org-todo-keywords-1))))
12398 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12399 (setq arg nil))) ;hack to fall back to cycling
12400 (arg
12401 ;; User or caller requests a specific state.
12402 (cond
12403 ((equal arg "") nil)
12404 ((eq arg 'none) nil)
12405 ((eq arg 'done) (or done-word (car org-done-keywords)))
12406 ((eq arg 'nextset)
12407 (or (car (cdr (member head org-todo-heads)))
12408 (car org-todo-heads)))
12409 ((eq arg 'previousset)
12410 (let ((org-todo-heads (reverse org-todo-heads)))
12411 (or (car (cdr (member head org-todo-heads)))
12412 (car org-todo-heads))))
12413 ((car (member arg org-todo-keywords-1)))
12414 ((stringp arg)
12415 (user-error "State `%s' not valid in this file" arg))
12416 ((nth (1- (prefix-numeric-value arg))
12417 org-todo-keywords-1))))
12418 ((null member) (or head (car org-todo-keywords-1)))
12419 ((equal this final-done-word) nil) ;-> make empty
12420 ((null tail) nil) ;-> first entry
12421 ((memq interpret '(type priority))
12422 (if (eq this-command last-command)
12423 (car tail)
12424 (if (> (length tail) 0)
12425 (or done-word (car org-done-keywords))
12426 nil)))
12428 (car tail))))
12429 (org-state (or
12430 (run-hook-with-args-until-success
12431 'org-todo-get-default-hook org-state org-last-state)
12432 org-state))
12433 (next (if org-state (concat " " org-state " ") " "))
12434 (change-plist (list :type 'todo-state-change :from this :to org-state
12435 :position startpos))
12436 dolog now-done-p)
12437 (when org-blocker-hook
12438 (let (org-blocked-by-checkboxes block-reason)
12439 (setq org-last-todo-state-is-todo
12440 (not (member this org-done-keywords)))
12441 (unless (save-excursion
12442 (save-match-data
12443 (org-with-wide-buffer
12444 (run-hook-with-args-until-failure
12445 'org-blocker-hook change-plist))))
12446 (setq block-reason (if org-blocked-by-checkboxes
12447 "contained checkboxes"
12448 (format "\"%s\"" org-block-entry-blocking)))
12449 (if (called-interactively-p 'interactive)
12450 (user-error "TODO state change from %s to %s blocked (by %s)"
12451 this org-state block-reason)
12452 ;; Fail silently.
12453 (message "TODO state change from %s to %s blocked (by %s)"
12454 this org-state block-reason)
12455 (throw 'exit nil)))))
12456 (store-match-data match-data)
12457 (replace-match next t t)
12458 (cond ((equal this org-state)
12459 (message "TODO state was already %s" (org-trim next)))
12460 ((not (pos-visible-in-window-p hl-pos))
12461 (message "TODO state changed to %s" (org-trim next))))
12462 (unless head
12463 (setq head (org-get-todo-sequence-head org-state)
12464 ass (assoc head org-todo-kwd-alist)
12465 interpret (nth 1 ass)
12466 done-word (nth 3 ass)
12467 final-done-word (nth 4 ass)))
12468 (when (memq arg '(nextset previousset))
12469 (message "Keyword-Set %d/%d: %s"
12470 (- (length org-todo-sets) -1
12471 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12472 (length org-todo-sets)
12473 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12474 (setq org-last-todo-state-is-todo
12475 (not (member org-state org-done-keywords)))
12476 (setq now-done-p (and (member org-state org-done-keywords)
12477 (not (member this org-done-keywords))))
12478 (and logging (org-local-logging logging))
12479 (when (and (or org-todo-log-states org-log-done)
12480 (not (eq org-inhibit-logging t))
12481 (not (memq arg '(nextset previousset))))
12482 ;; We need to look at recording a time and note.
12483 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12484 (nth 2 (assoc this org-todo-log-states))))
12485 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12486 (setq dolog 'time))
12487 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12488 (and org-state
12489 (member org-state org-not-done-keywords)
12490 (not (member this org-not-done-keywords))))
12491 ;; This is now a todo state and was not one before
12492 ;; If there was a CLOSED time stamp, get rid of it.
12493 (org-add-planning-info nil nil 'closed))
12494 (when (and now-done-p org-log-done)
12495 ;; It is now done, and it was not done before.
12496 (org-add-planning-info 'closed (org-current-effective-time))
12497 (when (and (not dolog) (eq 'note org-log-done))
12498 (org-add-log-setup 'done org-state this 'note)))
12499 (when (and org-state dolog)
12500 ;; This is a non-nil state, and we need to log it.
12501 (org-add-log-setup 'state org-state this dolog)))
12502 ;; Fixup tag positioning.
12503 (org-todo-trigger-tag-changes org-state)
12504 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12505 (when org-provide-todo-statistics
12506 (org-update-parent-todo-statistics))
12507 (run-hooks 'org-after-todo-state-change-hook)
12508 (when (and arg (not (member org-state org-done-keywords)))
12509 (setq head (org-get-todo-sequence-head org-state)))
12510 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12511 ;; Do we need to trigger a repeat?
12512 (when now-done-p
12513 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12514 ;; This is for the agenda, take a snapshot of the headline.
12515 (save-match-data
12516 (setq org-agenda-headline-snapshot-before-repeat
12517 (org-get-heading))))
12518 (org-auto-repeat-maybe org-state))
12519 ;; Fixup cursor location if close to the keyword.
12520 (when (and (outline-on-heading-p)
12521 (not (bolp))
12522 (save-excursion (beginning-of-line 1)
12523 (looking-at org-todo-line-regexp))
12524 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12525 (goto-char (or (match-end 2) (match-end 1)))
12526 (and (looking-at " ") (just-one-space)))
12527 (when org-trigger-hook
12528 (save-excursion
12529 (run-hook-with-args 'org-trigger-hook change-plist)))
12530 (when commentp (org-toggle-comment))))))))
12532 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12533 "Block turning an entry into a TODO, using the hierarchy.
12534 This checks whether the current task should be blocked from state
12535 changes. Such blocking occurs when:
12537 1. The task has children which are not all in a completed state.
12539 2. A task has a parent with the property :ORDERED:, and there
12540 are siblings prior to the current task with incomplete
12541 status.
12543 3. The parent of the task is blocked because it has siblings that should
12544 be done first, or is child of a block grandparent TODO entry."
12546 (if (not org-enforce-todo-dependencies)
12547 t ; if locally turned off don't block
12548 (catch 'dont-block
12549 ;; If this is not a todo state change, or if this entry is already DONE,
12550 ;; do not block
12551 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12552 (member (plist-get change-plist :from)
12553 (cons 'done org-done-keywords))
12554 (member (plist-get change-plist :to)
12555 (cons 'todo org-not-done-keywords))
12556 (not (plist-get change-plist :to)))
12557 (throw 'dont-block t))
12558 ;; If this task has children, and any are undone, it's blocked
12559 (save-excursion
12560 (org-back-to-heading t)
12561 (let ((this-level (funcall outline-level)))
12562 (outline-next-heading)
12563 (let ((child-level (funcall outline-level)))
12564 (while (and (not (eobp))
12565 (> child-level this-level))
12566 ;; this todo has children, check whether they are all
12567 ;; completed
12568 (when (and (not (org-entry-is-done-p))
12569 (org-entry-is-todo-p))
12570 (setq org-block-entry-blocking (org-get-heading))
12571 (throw 'dont-block nil))
12572 (outline-next-heading)
12573 (setq child-level (funcall outline-level))))))
12574 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12575 ;; any previous siblings are undone, it's blocked
12576 (save-excursion
12577 (org-back-to-heading t)
12578 (let* ((pos (point))
12579 (parent-pos (and (org-up-heading-safe) (point)))
12580 (case-fold-search nil))
12581 (unless parent-pos (throw 'dont-block t)) ; no parent
12582 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12583 (forward-line 1)
12584 (re-search-forward org-not-done-heading-regexp pos t))
12585 (setq org-block-entry-blocking (match-string 0))
12586 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12587 ;; Search further up the hierarchy, to see if an ancestor is blocked
12588 (while t
12589 (goto-char parent-pos)
12590 (unless (looking-at org-not-done-heading-regexp)
12591 (throw 'dont-block t)) ; do not block, parent is not a TODO
12592 (setq pos (point))
12593 (setq parent-pos (and (org-up-heading-safe) (point)))
12594 (unless parent-pos (throw 'dont-block t)) ; no parent
12595 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12596 (forward-line 1)
12597 (re-search-forward org-not-done-heading-regexp pos t)
12598 (setq org-block-entry-blocking (org-get-heading)))
12599 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12601 (defcustom org-track-ordered-property-with-tag nil
12602 "Should the ORDERED property also be shown as a tag?
12603 The ORDERED property decides if an entry should require subtasks to be
12604 completed in sequence. Since a property is not very visible, setting
12605 this option means that toggling the ORDERED property with the command
12606 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12607 not relevant for the behavior, but it makes things more visible.
12609 Note that toggling the tag with tags commands will not change the property
12610 and therefore not influence behavior!
12612 This can be t, meaning the tag ORDERED should be used, It can also be a
12613 string to select a different tag for this task."
12614 :group 'org-todo
12615 :type '(choice
12616 (const :tag "No tracking" nil)
12617 (const :tag "Track with ORDERED tag" t)
12618 (string :tag "Use other tag")))
12620 (defun org-toggle-ordered-property ()
12621 "Toggle the ORDERED property of the current entry.
12622 For better visibility, you can track the value of this property with a tag.
12623 See variable `org-track-ordered-property-with-tag'."
12624 (interactive)
12625 (let* ((t1 org-track-ordered-property-with-tag)
12626 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12627 (save-excursion
12628 (org-back-to-heading)
12629 (if (org-entry-get nil "ORDERED")
12630 (progn
12631 (org-delete-property "ORDERED")
12632 (and tag (org-toggle-tag tag 'off))
12633 (message "Subtasks can be completed in arbitrary order"))
12634 (org-entry-put nil "ORDERED" "t")
12635 (and tag (org-toggle-tag tag 'on))
12636 (message "Subtasks must be completed in sequence")))))
12638 (defun org-block-todo-from-checkboxes (change-plist)
12639 "Block turning an entry into a TODO, using checkboxes.
12640 This checks whether the current task should be blocked from state
12641 changes because there are unchecked boxes in this entry."
12642 (if (not org-enforce-todo-checkbox-dependencies)
12643 t ; if locally turned off don't block
12644 (catch 'dont-block
12645 ;; If this is not a todo state change, or if this entry is already DONE,
12646 ;; do not block
12647 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12648 (member (plist-get change-plist :from)
12649 (cons 'done org-done-keywords))
12650 (member (plist-get change-plist :to)
12651 (cons 'todo org-not-done-keywords))
12652 (not (plist-get change-plist :to)))
12653 (throw 'dont-block t))
12654 ;; If this task has checkboxes that are not checked, it's blocked
12655 (save-excursion
12656 (org-back-to-heading t)
12657 (let ((beg (point)) end)
12658 (outline-next-heading)
12659 (setq end (point))
12660 (goto-char beg)
12661 (when (org-list-search-forward
12662 (concat (org-item-beginning-re)
12663 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12664 "\\[[- ]\\]")
12665 end t)
12666 (when (boundp 'org-blocked-by-checkboxes)
12667 (setq org-blocked-by-checkboxes t))
12668 (throw 'dont-block nil))))
12669 t))) ; do not block
12671 (defun org-entry-blocked-p ()
12672 "Non-nil if entry at point is blocked."
12673 (and (not (org-entry-get nil "NOBLOCKING"))
12674 (member (org-entry-get nil "TODO") org-not-done-keywords)
12675 (not (run-hook-with-args-until-failure
12676 'org-blocker-hook
12677 (list :type 'todo-state-change
12678 :position (point)
12679 :from 'todo
12680 :to 'done)))))
12682 (defun org-update-statistics-cookies (all)
12683 "Update the statistics cookie, either from TODO or from checkboxes.
12684 This should be called with the cursor in a line with a statistics
12685 cookie. When called with a \\[universal-argument] prefix, update
12686 all statistics cookies in the buffer."
12687 (interactive "P")
12688 (if all
12689 (progn
12690 (org-update-checkbox-count 'all)
12691 (org-map-entries 'org-update-parent-todo-statistics))
12692 (if (not (org-at-heading-p))
12693 (org-update-checkbox-count)
12694 (let ((pos (point-marker))
12695 end l1 l2)
12696 (ignore-errors (org-back-to-heading t))
12697 (if (not (org-at-heading-p))
12698 (org-update-checkbox-count)
12699 (setq l1 (org-outline-level))
12700 (setq end (save-excursion
12701 (outline-next-heading)
12702 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12703 (point)))
12704 (if (and (save-excursion
12705 (re-search-forward
12706 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12707 (not (save-excursion (re-search-forward
12708 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12709 (org-update-checkbox-count)
12710 (if (and l2 (> l2 l1))
12711 (progn
12712 (goto-char end)
12713 (org-update-parent-todo-statistics))
12714 (goto-char pos)
12715 (beginning-of-line 1)
12716 (while (re-search-forward
12717 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12718 (point-at-eol) t)
12719 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12720 (goto-char pos)
12721 (move-marker pos nil)))))
12723 (defvar org-entry-property-inherited-from) ;; defined below
12724 (defun org-update-parent-todo-statistics ()
12725 "Update any statistics cookie in the parent of the current headline.
12726 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12727 the entire subtree and this will travel up the hierarchy and update
12728 statistics everywhere."
12729 (let* ((prop (save-excursion (org-up-heading-safe)
12730 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12731 (recursive (or (not org-hierarchical-todo-statistics)
12732 (and prop (string-match "\\<recursive\\>" prop))))
12733 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12735 (first t)
12736 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12737 level ltoggle l1 new ndel
12738 (cnt-all 0) (cnt-done 0) is-percent kwd
12739 checkbox-beg cookie-present)
12740 (catch 'exit
12741 (save-excursion
12742 (beginning-of-line 1)
12743 (setq ltoggle (funcall outline-level))
12744 ;; Three situations are to consider:
12746 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12747 ;; to the top-level ancestor on the headline;
12749 ;; 2. If parent has "recursive" property, repeat up to the
12750 ;; headline setting that property, taking inheritance into
12751 ;; account;
12753 ;; 3. Else, move up to direct parent and proceed only once.
12754 (while (and (setq level (org-up-heading-safe))
12755 (or recursive first)
12756 (>= (point) lim))
12757 (setq first nil cookie-present nil)
12758 (unless (and level
12759 (not (string-match
12760 "\\<checkbox\\>"
12761 (downcase (or (org-entry-get nil "COOKIE_DATA")
12762 "")))))
12763 (throw 'exit nil))
12764 (while (re-search-forward box-re (point-at-eol) t)
12765 (setq cnt-all 0 cnt-done 0 cookie-present t)
12766 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12767 (save-match-data
12768 (unless (outline-next-heading) (throw 'exit nil))
12769 (while (and (looking-at org-complex-heading-regexp)
12770 (> (setq l1 (length (match-string 1))) level))
12771 (setq kwd (and (or recursive (= l1 ltoggle))
12772 (match-string 2)))
12773 (if (or (eq org-provide-todo-statistics 'all-headlines)
12774 (and (eq org-provide-todo-statistics t)
12775 (or (member kwd org-done-keywords)))
12776 (and (listp org-provide-todo-statistics)
12777 (stringp (car org-provide-todo-statistics))
12778 (or (member kwd org-provide-todo-statistics)
12779 (member kwd org-done-keywords)))
12780 (and (listp org-provide-todo-statistics)
12781 (listp (car org-provide-todo-statistics))
12782 (or (member kwd (car org-provide-todo-statistics))
12783 (and (member kwd org-done-keywords)
12784 (member kwd (cadr org-provide-todo-statistics))))))
12785 (setq cnt-all (1+ cnt-all))
12786 (and (eq org-provide-todo-statistics t)
12788 (setq cnt-all (1+ cnt-all))))
12789 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12790 (member kwd org-done-keywords))
12791 (and (listp org-provide-todo-statistics)
12792 (listp (car org-provide-todo-statistics))
12793 (member kwd org-done-keywords)
12794 (member kwd (cadr org-provide-todo-statistics)))
12795 (and (listp org-provide-todo-statistics)
12796 (stringp (car org-provide-todo-statistics))
12797 (member kwd org-done-keywords)))
12798 (setq cnt-done (1+ cnt-done)))
12799 (outline-next-heading)))
12800 (setq new
12801 (if is-percent
12802 (format "[%d%%]" (floor (* 100.0 cnt-done)
12803 (max 1 cnt-all)))
12804 (format "[%d/%d]" cnt-done cnt-all))
12805 ndel (- (match-end 0) checkbox-beg))
12806 (goto-char checkbox-beg)
12807 (insert new)
12808 (delete-region (point) (+ (point) ndel))
12809 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
12810 (when cookie-present
12811 (run-hook-with-args 'org-after-todo-statistics-hook
12812 cnt-done (- cnt-all cnt-done))))))
12813 (run-hooks 'org-todo-statistics-hook)))
12815 (defvar org-after-todo-statistics-hook nil
12816 "Hook that is called after a TODO statistics cookie has been updated.
12817 Each function is called with two arguments: the number of not-done entries
12818 and the number of done entries.
12820 For example, the following function, when added to this hook, will switch
12821 an entry to DONE when all children are done, and back to TODO when new
12822 entries are set to a TODO status. Note that this hook is only called
12823 when there is a statistics cookie in the headline!
12825 (defun org-summary-todo (n-done n-not-done)
12826 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12827 (let (org-log-done org-log-states) ; turn off logging
12828 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12831 (defvar org-todo-statistics-hook nil
12832 "Hook that is run whenever Org thinks TODO statistics should be updated.
12833 This hook runs even if there is no statistics cookie present, in which case
12834 `org-after-todo-statistics-hook' would not run.")
12836 (defun org-todo-trigger-tag-changes (state)
12837 "Apply the changes defined in `org-todo-state-tags-triggers'."
12838 (let ((l org-todo-state-tags-triggers)
12839 changes)
12840 (when (or (not state) (equal state ""))
12841 (setq changes (append changes (cdr (assoc "" l)))))
12842 (when (and (stringp state) (> (length state) 0))
12843 (setq changes (append changes (cdr (assoc state l)))))
12844 (when (member state org-not-done-keywords)
12845 (setq changes (append changes (cdr (assq 'todo l)))))
12846 (when (member state org-done-keywords)
12847 (setq changes (append changes (cdr (assq 'done l)))))
12848 (dolist (c changes)
12849 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12851 (defun org-local-logging (value)
12852 "Get logging settings from a property VALUE."
12853 ;; Directly set the variables, they are already local.
12854 (setq org-log-done nil
12855 org-log-repeat nil
12856 org-todo-log-states nil)
12857 (dolist (w (split-string value))
12858 (let (a)
12859 (cond
12860 ((setq a (assoc w org-startup-options))
12861 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12862 (set (nth 1 a) (nth 2 a))))
12863 ((setq a (org-extract-log-state-settings w))
12864 (and (member (car a) org-todo-keywords-1)
12865 (push a org-todo-log-states)))))))
12867 (defun org-get-todo-sequence-head (kwd)
12868 "Return the head of the TODO sequence to which KWD belongs.
12869 If KWD is not set, check if there is a text property remembering the
12870 right sequence."
12871 (let (p)
12872 (cond
12873 ((not kwd)
12874 (or (get-text-property (point-at-bol) 'org-todo-head)
12875 (progn
12876 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12877 nil (point-at-eol)))
12878 (get-text-property p 'org-todo-head))))
12879 ((not (member kwd org-todo-keywords-1))
12880 (car org-todo-keywords-1))
12881 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12883 (defun org-fast-todo-selection ()
12884 "Fast TODO keyword selection with single keys.
12885 Returns the new TODO keyword, or nil if no state change should occur."
12886 (let* ((fulltable org-todo-key-alist)
12887 (done-keywords org-done-keywords) ;; needed for the faces.
12888 (maxlen (apply 'max (mapcar
12889 (lambda (x)
12890 (if (stringp (car x)) (string-width (car x)) 0))
12891 fulltable)))
12892 (expert nil)
12893 (fwidth (+ maxlen 3 1 3))
12894 (ncol (/ (- (window-width) 4) fwidth))
12895 tg cnt e c tbl
12896 groups ingroup)
12897 (save-excursion
12898 (save-window-excursion
12899 (if expert
12900 (set-buffer (get-buffer-create " *Org todo*"))
12901 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12902 (erase-buffer)
12903 (setq-local org-done-keywords done-keywords)
12904 (setq tbl fulltable cnt 0)
12905 (while (setq e (pop tbl))
12906 (cond
12907 ((equal e '(:startgroup))
12908 (push '() groups) (setq ingroup t)
12909 (unless (= cnt 0)
12910 (setq cnt 0)
12911 (insert "\n"))
12912 (insert "{ "))
12913 ((equal e '(:endgroup))
12914 (setq ingroup nil cnt 0)
12915 (insert "}\n"))
12916 ((equal e '(:newline))
12917 (unless (= cnt 0)
12918 (setq cnt 0)
12919 (insert "\n")
12920 (setq e (car tbl))
12921 (while (equal (car tbl) '(:newline))
12922 (insert "\n")
12923 (setq tbl (cdr tbl)))))
12925 (setq tg (car e) c (cdr e))
12926 (when ingroup (push tg (car groups)))
12927 (setq tg (org-add-props tg nil 'face
12928 (org-get-todo-face tg)))
12929 (when (and (= cnt 0) (not ingroup)) (insert " "))
12930 (insert "[" c "] " tg (make-string
12931 (- fwidth 4 (length tg)) ?\ ))
12932 (when (= (setq cnt (1+ cnt)) ncol)
12933 (insert "\n")
12934 (when ingroup (insert " "))
12935 (setq cnt 0)))))
12936 (insert "\n")
12937 (goto-char (point-min))
12938 (unless expert (org-fit-window-to-buffer))
12939 (message "[a-z..]:Set [SPC]:clear")
12940 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12941 (cond
12942 ((or (= c ?\C-g)
12943 (and (= c ?q) (not (rassoc c fulltable))))
12944 (setq quit-flag t))
12945 ((= c ?\ ) nil)
12946 ((setq e (rassoc c fulltable) tg (car e))
12948 (t (setq quit-flag t)))))))
12950 (defun org-entry-is-todo-p ()
12951 (member (org-get-todo-state) org-not-done-keywords))
12953 (defun org-entry-is-done-p ()
12954 (member (org-get-todo-state) org-done-keywords))
12956 (defun org-get-todo-state ()
12957 "Return the TODO keyword of the current subtree."
12958 (save-excursion
12959 (org-back-to-heading t)
12960 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
12961 (match-end 2)
12962 (match-string 2))))
12964 (defun org-at-date-range-p (&optional inactive-ok)
12965 "Non-nil if point is inside a date range.
12967 When optional argument INACTIVE-OK is non-nil, also consider
12968 inactive time ranges.
12970 When this function returns a non-nil value, match data is set
12971 according to `org-tr-regexp-both' or `org-tr-regexp', depending
12972 on INACTIVE-OK."
12973 (interactive)
12974 (save-excursion
12975 (catch 'exit
12976 (let ((pos (point)))
12977 (skip-chars-backward "^[<\r\n")
12978 (skip-chars-backward "<[")
12979 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12980 (>= (match-end 0) pos)
12981 (throw 'exit t))
12982 (skip-chars-backward "^<[\r\n")
12983 (skip-chars-backward "<[")
12984 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
12985 (>= (match-end 0) pos)
12986 (throw 'exit t)))
12987 nil)))
12989 (defun org-get-repeat (&optional timestamp)
12990 "Check if there is a time-stamp with repeater in this entry.
12992 Return the repeater, as a string, or nil. Also return nil when
12993 this function is called before first heading.
12995 When optional argument TIMESTAMP is a string, extract the
12996 repeater from there instead."
12997 (save-match-data
12998 (cond (timestamp
12999 (and (string-match org-repeat-re timestamp)
13000 (match-string-no-properties 1 timestamp)))
13001 ((org-before-first-heading-p) nil)
13003 (save-excursion
13004 (org-back-to-heading t)
13005 (let ((end (org-entry-end-position)))
13006 (catch :repeat
13007 (while (re-search-forward org-repeat-re end t)
13008 (when (save-match-data (org-at-timestamp-p 'agenda))
13009 (throw :repeat (match-string-no-properties 1)))))))))))
13011 (defvar org-last-changed-timestamp)
13012 (defvar org-last-inserted-timestamp)
13013 (defvar org-log-post-message)
13014 (defvar org-log-note-purpose)
13015 (defvar org-log-note-how nil)
13016 (defvar org-log-note-extra)
13017 (defun org-auto-repeat-maybe (done-word)
13018 "Check if the current headline contains a repeated time-stamp.
13020 If yes, set TODO state back to what it was and change the base date
13021 of repeating deadline/scheduled time stamps to new date.
13023 This function is run automatically after each state change to a DONE state."
13024 (let* ((repeat (org-get-repeat))
13025 (aa (assoc org-last-state org-todo-kwd-alist))
13026 (interpret (nth 1 aa))
13027 (head (nth 2 aa))
13028 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13029 (msg "Entry repeats: ")
13030 (org-log-done nil)
13031 (org-todo-log-states nil)
13032 (end (copy-marker (org-entry-end-position))))
13033 (unwind-protect
13034 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13035 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13036 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13037 org-todo-repeat-to-state)))
13038 (org-todo (cond
13039 ((and to-state (member to-state org-todo-keywords-1))
13040 to-state)
13041 ((eq interpret 'type) org-last-state)
13042 (head)
13043 (t 'none))))
13044 (org-back-to-heading t)
13045 (org-add-planning-info nil nil 'closed)
13046 ;; When `org-log-repeat' is non-nil or entry contains
13047 ;; a clock, set LAST_REPEAT property.
13048 (when (or org-log-repeat
13049 (catch :clock
13050 (save-excursion
13051 (while (re-search-forward org-clock-line-re end t)
13052 (when (org-at-clock-log-p) (throw :clock t))))))
13053 (org-entry-put nil "LAST_REPEAT" (format-time-string
13054 (org-time-stamp-format t t)
13055 (current-time))))
13056 (when org-log-repeat
13057 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13058 (memq 'org-add-log-note post-command-hook))
13059 ;; We are already setup for some record.
13060 (when (eq org-log-repeat 'note)
13061 ;; Make sure we take a note, not only a time stamp.
13062 (setq org-log-note-how 'note))
13063 ;; Set up for taking a record.
13064 (org-add-log-setup 'state
13065 (or done-word (car org-done-keywords))
13066 org-last-state
13067 org-log-repeat)))
13068 (let ((planning-re (regexp-opt
13069 (list org-scheduled-string org-deadline-string))))
13070 (while (re-search-forward org-ts-regexp end t)
13071 (let* ((ts (match-string 0))
13072 (planning? (org-at-planning-p))
13073 (type (if (not planning?) "Plain:"
13074 (save-excursion
13075 (re-search-backward
13076 planning-re (line-beginning-position) t)
13077 (match-string 0)))))
13078 (cond
13079 ;; Ignore fake time-stamps (e.g., within comments).
13080 ((not (org-at-timestamp-p 'agenda)))
13081 ;; Time-stamps without a repeater are usually
13082 ;; skipped. However, a SCHEDULED time-stamp without
13083 ;; one is removed, as they are no longer relevant.
13084 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13085 ts))
13086 (when (equal type org-scheduled-string)
13087 (org-remove-timestamp-with-keyword type)))
13089 (let ((n (string-to-number (match-string 2 ts)))
13090 (what (match-string 3 ts)))
13091 (when (equal what "w") (setq n (* n 7) what "d"))
13092 (when (and (equal what "h")
13093 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13094 ts)))
13095 (user-error
13096 "Cannot repeat in Repeat in %d hour(s) because no hour \
13097 has been set"
13099 ;; Preparation, see if we need to modify the start
13100 ;; date for the change.
13101 (when (match-end 1)
13102 (let ((time (save-match-data
13103 (org-time-string-to-time ts))))
13104 (cond
13105 ((equal (match-string 1 ts) ".")
13106 ;; Shift starting date to today
13107 (org-timestamp-change
13108 (- (org-today) (time-to-days time))
13109 'day))
13110 ((equal (match-string 1 ts) "+")
13111 (let ((nshiftmax 10)
13112 (nshift 0))
13113 (while (or (= nshift 0)
13114 (not (time-less-p (current-time) time)))
13115 (when (= (cl-incf nshift) nshiftmax)
13116 (or (y-or-n-p
13117 (format "%d repeater intervals were not \
13118 enough to shift date past today. Continue? "
13119 nshift))
13120 (user-error "Abort")))
13121 (org-timestamp-change n (cdr (assoc what whata)))
13122 (org-in-regexp org-ts-regexp3)
13123 (setq ts (match-string 1))
13124 (setq time
13125 (save-match-data
13126 (org-time-string-to-time ts)))))
13127 (org-timestamp-change (- n) (cdr (assoc what whata)))
13128 ;; Rematch, so that we have everything in place
13129 ;; for the real shift.
13130 (org-in-regexp org-ts-regexp3)
13131 (setq ts (match-string 1))
13132 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13133 ts)))))
13134 (save-excursion
13135 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13136 (setq msg
13137 (concat
13138 msg type " " org-last-changed-timestamp " "))))))))
13139 (setq org-log-post-message msg)
13140 (message "%s" msg))
13141 (set-marker end nil))))
13143 (defun org-show-todo-tree (arg)
13144 "Make a compact tree which shows all headlines marked with TODO.
13145 The tree will show the lines where the regexp matches, and all higher
13146 headlines above the match.
13147 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13148 With a numeric prefix N, construct a sparse tree for the Nth element
13149 of `org-todo-keywords-1'."
13150 (interactive "P")
13151 (let ((case-fold-search nil)
13152 (kwd-re
13153 (cond ((null arg) org-not-done-regexp)
13154 ((equal arg '(4))
13155 (let ((kwd
13156 (completing-read "Keyword (or KWD1|KWD2|...): "
13157 (mapcar #'list org-todo-keywords-1))))
13158 (concat "\\("
13159 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13160 "\\)\\>")))
13161 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13162 (regexp-quote (nth (1- (prefix-numeric-value arg))
13163 org-todo-keywords-1)))
13164 (t (user-error "Invalid prefix argument: %s" arg)))))
13165 (message "%d TODO entries found"
13166 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13168 (defun org--deadline-or-schedule (arg type time)
13169 "Insert DEADLINE or SCHEDULE information in current entry.
13170 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13171 `org-schedule' for information about ARG and TIME arguments."
13172 (let* ((deadline? (eq type 'deadline))
13173 (keyword (if deadline? org-deadline-string org-scheduled-string))
13174 (log (if deadline? org-log-redeadline org-log-reschedule))
13175 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13176 (old-date-time (and old-date (org-time-string-to-time old-date)))
13177 ;; Save repeater cookie from either TIME or current scheduled
13178 ;; time stamp. We are going to insert it back at the end of
13179 ;; the process.
13180 (repeater (or (and (org-string-nw-p time)
13181 ;; We use `org-repeat-re' because we need
13182 ;; to tell the difference between a real
13183 ;; repeater and a time delta, e.g. "+2d".
13184 (string-match org-repeat-re time)
13185 (match-string 1 time))
13186 (and (org-string-nw-p old-date)
13187 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13188 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13189 old-date)
13190 (match-string 1 old-date)))))
13191 (pcase arg
13192 (`(4)
13193 (when (and old-date log)
13194 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13195 nil old-date log))
13196 (org-remove-timestamp-with-keyword keyword)
13197 (message (if deadline? "Item no longer has a deadline."
13198 "Item is no longer scheduled.")))
13199 (`(16)
13200 (save-excursion
13201 (org-back-to-heading t)
13202 (let ((regexp (if deadline? org-deadline-time-regexp
13203 org-scheduled-time-regexp)))
13204 (if (not (re-search-forward regexp (line-end-position 2) t))
13205 (user-error (if deadline? "No deadline information to update"
13206 "No scheduled information to update"))
13207 (let* ((rpl0 (match-string 1))
13208 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13209 (msg (if deadline? "Warn starting from" "Delay until")))
13210 (replace-match
13211 (concat keyword
13212 " <" rpl
13213 (format " -%dd"
13214 (abs (- (time-to-days
13215 (save-match-data
13216 (org-read-date
13217 nil t nil msg old-date-time)))
13218 (time-to-days old-date-time))))
13219 ">") t t))))))
13221 (org-add-planning-info type time 'closed)
13222 (when (and old-date
13224 (not (equal old-date org-last-inserted-timestamp)))
13225 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13226 org-last-inserted-timestamp
13227 old-date
13228 log))
13229 (when repeater
13230 (save-excursion
13231 (org-back-to-heading t)
13232 (when (re-search-forward
13233 (concat keyword " " org-last-inserted-timestamp)
13234 (line-end-position 2)
13236 (goto-char (1- (match-end 0)))
13237 (insert " " repeater)
13238 (setq org-last-inserted-timestamp
13239 (concat (substring org-last-inserted-timestamp 0 -1)
13240 " " repeater
13241 (substring org-last-inserted-timestamp -1))))))
13242 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13243 org-last-inserted-timestamp)))))
13245 (defun org-deadline (arg &optional time)
13246 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13247 With one universal prefix argument, remove any deadline from the item.
13248 With two universal prefix arguments, prompt for a warning delay.
13249 With argument TIME, set the deadline at the corresponding date. TIME
13250 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13251 (interactive "P")
13252 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13253 (org-map-entries
13254 (lambda () (org--deadline-or-schedule arg 'deadline time))
13256 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13257 'region-start-level
13258 'region)
13259 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13260 (org--deadline-or-schedule arg 'deadline time)))
13262 (defun org-schedule (arg &optional time)
13263 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13264 With one universal prefix argument, remove any scheduling date from the item.
13265 With two universal prefix arguments, prompt for a delay cookie.
13266 With argument TIME, scheduled at the corresponding date. TIME can
13267 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13268 (interactive "P")
13269 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13270 (org-map-entries
13271 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13273 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13274 'region-start-level
13275 'region)
13276 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13277 (org--deadline-or-schedule arg 'scheduled time)))
13279 (defun org-get-scheduled-time (pom &optional inherit)
13280 "Get the scheduled time as a time tuple, of a format suitable
13281 for calling org-schedule with, or if there is no scheduling,
13282 returns nil."
13283 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13284 (when time
13285 (apply 'encode-time (org-parse-time-string time)))))
13287 (defun org-get-deadline-time (pom &optional inherit)
13288 "Get the deadline as a time tuple, of a format suitable for
13289 calling org-deadline with, or if there is no scheduling, returns
13290 nil."
13291 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13292 (when time
13293 (apply 'encode-time (org-parse-time-string time)))))
13295 (defun org-remove-timestamp-with-keyword (keyword)
13296 "Remove all time stamps with KEYWORD in the current entry."
13297 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13298 beg)
13299 (save-excursion
13300 (org-back-to-heading t)
13301 (setq beg (point))
13302 (outline-next-heading)
13303 (while (re-search-backward re beg t)
13304 (replace-match "")
13305 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13306 (equal (char-before) ?\ ))
13307 (backward-delete-char 1)
13308 (when (string-match "^[ \t]*$" (buffer-substring
13309 (point-at-bol) (point-at-eol)))
13310 (delete-region (point-at-bol)
13311 (min (point-max) (1+ (point-at-eol))))))))))
13313 (defvar org-time-was-given) ; dynamically scoped parameter
13314 (defvar org-end-time-was-given) ; dynamically scoped parameter
13316 (defun org-at-planning-p ()
13317 "Non-nil when point is on a planning info line."
13318 ;; This is as accurate and faster than `org-element-at-point' since
13319 ;; planning info location is fixed in the section.
13320 (org-with-wide-buffer
13321 (beginning-of-line)
13322 (and (looking-at-p org-planning-line-re)
13323 (eq (point)
13324 (ignore-errors
13325 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13326 (org-back-to-heading t)
13327 (org-with-limited-levels (org-back-to-heading t)))
13328 (line-beginning-position 2))))))
13330 (defun org-add-planning-info (what &optional time &rest remove)
13331 "Insert new timestamp with keyword in the planning line.
13332 WHAT indicates what kind of time stamp to add. It is a symbol
13333 among `closed', `deadline', `scheduled' and nil. TIME indicates
13334 the time to use. If none is given, the user is prompted for
13335 a date. REMOVE indicates what kind of entries to remove. An old
13336 WHAT entry will also be removed."
13337 (let (org-time-was-given org-end-time-was-given default-time default-input)
13338 (catch 'exit
13339 (when (and (memq what '(scheduled deadline))
13340 (or (not time)
13341 (and (stringp time)
13342 (string-match "^[-+]+[0-9]" time))))
13343 ;; Try to get a default date/time from existing timestamp
13344 (save-excursion
13345 (org-back-to-heading t)
13346 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13347 (when (re-search-forward (if (eq what 'scheduled)
13348 org-scheduled-time-regexp
13349 org-deadline-time-regexp)
13350 end t)
13351 (setq ts (match-string 1)
13352 default-time (apply 'encode-time (org-parse-time-string ts))
13353 default-input (and ts (org-get-compact-tod ts)))))))
13354 (when what
13355 (setq time
13356 (if (stringp time)
13357 ;; This is a string (relative or absolute), set
13358 ;; proper date.
13359 (apply #'encode-time
13360 (org-read-date-analyze
13361 time default-time (decode-time default-time)))
13362 ;; If necessary, get the time from the user
13363 (or time (org-read-date nil 'to-time nil nil
13364 default-time default-input)))))
13366 (org-with-wide-buffer
13367 (org-back-to-heading t)
13368 (forward-line)
13369 (unless (bolp) (insert "\n"))
13370 (cond ((looking-at-p org-planning-line-re)
13371 ;; Move to current indentation.
13372 (skip-chars-forward " \t")
13373 ;; Check if we have to remove something.
13374 (dolist (type (if what (cons what remove) remove))
13375 (save-excursion
13376 (when (re-search-forward
13377 (cl-case type
13378 (closed org-closed-time-regexp)
13379 (deadline org-deadline-time-regexp)
13380 (scheduled org-scheduled-time-regexp)
13381 (otherwise
13382 (error "Invalid planning type: %s" type)))
13383 (line-end-position) t)
13384 ;; Delete until next keyword or end of line.
13385 (delete-region
13386 (match-beginning 0)
13387 (if (re-search-forward org-keyword-time-not-clock-regexp
13388 (line-end-position)
13390 (match-beginning 0)
13391 (line-end-position))))))
13392 ;; If there is nothing more to add and no more keyword
13393 ;; is left, remove the line completely.
13394 (if (and (looking-at-p "[ \t]*$") (not what))
13395 (delete-region (line-beginning-position)
13396 (line-beginning-position 2))
13397 ;; If we removed last keyword, do not leave trailing
13398 ;; white space at the end of line.
13399 (let ((p (point)))
13400 (save-excursion
13401 (end-of-line)
13402 (unless (= (skip-chars-backward " \t" p) 0)
13403 (delete-region (point) (line-end-position)))))))
13404 ((not what) (throw 'exit nil)) ; Nothing to do.
13405 (t (insert-before-markers "\n")
13406 (backward-char 1)
13407 (when org-adapt-indentation
13408 (indent-to-column (1+ (org-outline-level))))))
13409 (when what
13410 ;; Insert planning keyword.
13411 (insert (cl-case what
13412 (closed org-closed-string)
13413 (deadline org-deadline-string)
13414 (scheduled org-scheduled-string)
13415 (otherwise (error "Invalid planning type: %s" what)))
13416 " ")
13417 ;; Insert associated timestamp.
13418 (let ((ts (org-insert-time-stamp
13419 time
13420 (or org-time-was-given
13421 (and (eq what 'closed) org-log-done-with-time))
13422 (eq what 'closed)
13423 nil nil (list org-end-time-was-given))))
13424 (unless (eolp) (insert " "))
13425 ts))))))
13427 (defvar org-log-note-marker (make-marker)
13428 "Marker pointing at the entry where the note is to be inserted.")
13429 (defvar org-log-note-purpose nil)
13430 (defvar org-log-note-state nil)
13431 (defvar org-log-note-previous-state nil)
13432 (defvar org-log-note-extra nil)
13433 (defvar org-log-note-window-configuration nil)
13434 (defvar org-log-note-return-to (make-marker))
13435 (defvar org-log-note-effective-time nil
13436 "Remembered current time so that dynamically scoped
13437 `org-extend-today-until' affects timestamps in state change log")
13439 (defvar org-log-post-message nil
13440 "Message to be displayed after a log note has been stored.
13441 The auto-repeater uses this.")
13443 (defun org-add-note ()
13444 "Add a note to the current entry.
13445 This is done in the same way as adding a state change note."
13446 (interactive)
13447 (org-add-log-setup 'note))
13449 (defun org-log-beginning (&optional create)
13450 "Return expected start of log notes in current entry.
13451 When optional argument CREATE is non-nil, the function creates
13452 a drawer to store notes, if necessary. Returned position ignores
13453 narrowing."
13454 (org-with-wide-buffer
13455 (let ((drawer (org-log-into-drawer)))
13456 (cond
13457 (drawer
13458 (org-end-of-meta-data)
13459 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13460 (end (if (org-at-heading-p) (point)
13461 (save-excursion (outline-next-heading) (point))))
13462 (case-fold-search t))
13463 (catch 'exit
13464 ;; Try to find existing drawer.
13465 (while (re-search-forward regexp end t)
13466 (let ((element (org-element-at-point)))
13467 (when (eq (org-element-type element) 'drawer)
13468 (let ((cend (org-element-property :contents-end element)))
13469 (when (and (not org-log-states-order-reversed) cend)
13470 (goto-char cend)))
13471 (throw 'exit nil))))
13472 ;; No drawer found. Create one, if permitted.
13473 (when create
13474 (unless (bolp) (insert "\n"))
13475 (let ((beg (point)))
13476 (insert ":" drawer ":\n:END:\n")
13477 (org-indent-region beg (point)))
13478 (end-of-line -1)))))
13480 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13481 (skip-chars-forward " \t\n")
13482 (beginning-of-line)
13483 (unless org-log-states-order-reversed
13484 (org-skip-over-state-notes)
13485 (skip-chars-backward " \t\n")
13486 (forward-line)))))
13487 (if (bolp) (point) (line-beginning-position 2))))
13489 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13490 "Set up the post command hook to take a note.
13491 If this is about to TODO state change, the new state is expected in STATE.
13492 HOW is an indicator what kind of note should be created.
13493 EXTRA is additional text that will be inserted into the notes buffer."
13494 (move-marker org-log-note-marker (point))
13495 (setq org-log-note-purpose purpose
13496 org-log-note-state state
13497 org-log-note-previous-state prev-state
13498 org-log-note-how how
13499 org-log-note-extra extra
13500 org-log-note-effective-time (org-current-effective-time))
13501 (add-hook 'post-command-hook 'org-add-log-note 'append))
13503 (defun org-skip-over-state-notes ()
13504 "Skip past the list of State notes in an entry."
13505 (when (ignore-errors (goto-char (org-in-item-p)))
13506 (let* ((struct (org-list-struct))
13507 (prevs (org-list-prevs-alist struct))
13508 (regexp
13509 (concat "[ \t]*- +"
13510 (replace-regexp-in-string
13511 " +" " +"
13512 (org-replace-escapes
13513 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13514 `(("%d" . ,org-ts-regexp-inactive)
13515 ("%D" . ,org-ts-regexp)
13516 ("%s" . "\"\\S-+\"")
13517 ("%S" . "\"\\S-+\"")
13518 ("%t" . ,org-ts-regexp-inactive)
13519 ("%T" . ,org-ts-regexp)
13520 ("%u" . ".*?")
13521 ("%U" . ".*?")))))))
13522 (while (looking-at-p regexp)
13523 (goto-char (or (org-list-get-next-item (point) struct prevs)
13524 (org-list-get-item-end (point) struct)))))))
13526 (defun org-add-log-note (&optional _purpose)
13527 "Pop up a window for taking a note, and add this note later."
13528 (remove-hook 'post-command-hook 'org-add-log-note)
13529 (setq org-log-note-window-configuration (current-window-configuration))
13530 (delete-other-windows)
13531 (move-marker org-log-note-return-to (point))
13532 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13533 (goto-char org-log-note-marker)
13534 (org-switch-to-buffer-other-window "*Org Note*")
13535 (erase-buffer)
13536 (if (memq org-log-note-how '(time state))
13537 (org-store-log-note)
13538 (let ((org-inhibit-startup t)) (org-mode))
13539 (insert (format "# Insert note for %s.
13540 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13541 (cond
13542 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13543 ((eq org-log-note-purpose 'done) "closed todo item")
13544 ((eq org-log-note-purpose 'state)
13545 (format "state change from \"%s\" to \"%s\""
13546 (or org-log-note-previous-state "")
13547 (or org-log-note-state "")))
13548 ((eq org-log-note-purpose 'reschedule)
13549 "rescheduling")
13550 ((eq org-log-note-purpose 'delschedule)
13551 "no longer scheduled")
13552 ((eq org-log-note-purpose 'redeadline)
13553 "changing deadline")
13554 ((eq org-log-note-purpose 'deldeadline)
13555 "removing deadline")
13556 ((eq org-log-note-purpose 'refile)
13557 "refiling")
13558 ((eq org-log-note-purpose 'note)
13559 "this entry")
13560 (t (error "This should not happen")))))
13561 (when org-log-note-extra (insert org-log-note-extra))
13562 (setq-local org-finish-function 'org-store-log-note)
13563 (run-hooks 'org-log-buffer-setup-hook)))
13565 (defvar org-note-abort nil) ; dynamically scoped
13566 (defun org-store-log-note ()
13567 "Finish taking a log note, and insert it to where it belongs."
13568 (let ((txt (prog1 (buffer-string)
13569 (kill-buffer)))
13570 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13571 lines)
13572 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13573 (setq txt (replace-match "" t t txt)))
13574 (when (string-match "\\s-+\\'" txt)
13575 (setq txt (replace-match "" t t txt)))
13576 (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
13577 (when (org-string-nw-p note)
13578 (setq note
13579 (org-replace-escapes
13580 note
13581 (list (cons "%u" (user-login-name))
13582 (cons "%U" user-full-name)
13583 (cons "%t" (format-time-string
13584 (org-time-stamp-format 'long 'inactive)
13585 org-log-note-effective-time))
13586 (cons "%T" (format-time-string
13587 (org-time-stamp-format 'long nil)
13588 org-log-note-effective-time))
13589 (cons "%d" (format-time-string
13590 (org-time-stamp-format nil 'inactive)
13591 org-log-note-effective-time))
13592 (cons "%D" (format-time-string
13593 (org-time-stamp-format nil nil)
13594 org-log-note-effective-time))
13595 (cons "%s" (cond
13596 ((not org-log-note-state) "")
13597 ((string-match-p org-ts-regexp
13598 org-log-note-state)
13599 (format "\"[%s]\""
13600 (substring org-log-note-state 1 -1)))
13601 (t (format "\"%s\"" org-log-note-state))))
13602 (cons "%S"
13603 (cond
13604 ((not org-log-note-previous-state) "")
13605 ((string-match-p org-ts-regexp
13606 org-log-note-previous-state)
13607 (format "\"[%s]\""
13608 (substring
13609 org-log-note-previous-state 1 -1)))
13610 (t (format "\"%s\""
13611 org-log-note-previous-state)))))))
13612 (when lines (setq note (concat note " \\\\")))
13613 (push note lines))
13614 (when (and lines (not org-note-abort))
13615 (with-current-buffer (marker-buffer org-log-note-marker)
13616 (org-with-wide-buffer
13617 ;; Find location for the new note.
13618 (goto-char org-log-note-marker)
13619 (set-marker org-log-note-marker nil)
13620 ;; Note associated to a clock is to be located right after
13621 ;; the clock. Do not move point.
13622 (unless (eq org-log-note-purpose 'clock-out)
13623 (goto-char (org-log-beginning t)))
13624 ;; Make sure point is at the beginning of an empty line.
13625 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13626 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13627 ;; In an existing list, add a new item at the top level.
13628 ;; Otherwise, indent line like a regular one.
13629 (let ((itemp (org-in-item-p)))
13630 (if itemp
13631 (indent-line-to
13632 (let ((struct (save-excursion
13633 (goto-char itemp) (org-list-struct))))
13634 (org-list-get-ind (org-list-get-top-point struct) struct)))
13635 (org-indent-line)))
13636 (insert (org-list-bullet-string "-") (pop lines))
13637 (let ((ind (org-list-item-body-column (line-beginning-position))))
13638 (dolist (line lines)
13639 (insert "\n")
13640 (indent-line-to ind)
13641 (insert line)))
13642 (message "Note stored")
13643 (org-back-to-heading t)
13644 (org-cycle-hide-drawers 'children))
13645 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13646 ;; from within `org-add-log-note' because `buffer-undo-list'
13647 ;; is then modified outside of `org-with-remote-undo'.
13648 (when (eq this-command 'org-agenda-todo)
13649 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13650 ;; Don't add undo information when called from `org-agenda-todo'.
13651 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13652 (set-window-configuration org-log-note-window-configuration)
13653 (with-current-buffer (marker-buffer org-log-note-return-to)
13654 (goto-char org-log-note-return-to))
13655 (move-marker org-log-note-return-to nil)
13656 (when org-log-post-message (message "%s" org-log-post-message))))
13658 (defun org-remove-empty-drawer-at (pos)
13659 "Remove an empty drawer at position POS.
13660 POS may also be a marker."
13661 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13662 (org-with-wide-buffer
13663 (goto-char pos)
13664 (let ((drawer (org-element-at-point)))
13665 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13666 (not (org-element-property :contents-begin drawer)))
13667 (delete-region (org-element-property :begin drawer)
13668 (progn (goto-char (org-element-property :end drawer))
13669 (skip-chars-backward " \r\t\n")
13670 (forward-line)
13671 (point))))))))
13673 (defvar org-ts-type nil)
13674 (defun org-sparse-tree (&optional arg type)
13675 "Create a sparse tree, prompt for the details.
13676 This command can create sparse trees. You first need to select the type
13677 of match used to create the tree:
13679 t Show all TODO entries.
13680 T Show entries with a specific TODO keyword.
13681 m Show entries selected by a tags/property match.
13682 p Enter a property name and its value (both with completion on existing
13683 names/values) and show entries with that property.
13684 r Show entries matching a regular expression (`/' can be used as well).
13685 b Show deadlines and scheduled items before a date.
13686 a Show deadlines and scheduled items after a date.
13687 d Show deadlines due within `org-deadline-warning-days'.
13688 D Show deadlines and scheduled items between a date range."
13689 (interactive "P")
13690 (setq type (or type org-sparse-tree-default-date-type))
13691 (setq org-ts-type type)
13692 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13693 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13694 \[c]ycle through date types: %s"
13695 (cl-case type
13696 (all "all timestamps")
13697 (scheduled "only scheduled")
13698 (deadline "only deadline")
13699 (active "only active timestamps")
13700 (inactive "only inactive timestamps")
13701 (closed "with a closed time-stamp")
13702 (otherwise "scheduled/deadline")))
13703 (let ((answer (read-char-exclusive)))
13704 (cl-case answer
13706 (org-sparse-tree
13708 (cadr
13709 (memq type '(nil all scheduled deadline active inactive closed)))))
13710 (?d (call-interactively 'org-check-deadlines))
13711 (?b (call-interactively 'org-check-before-date))
13712 (?a (call-interactively 'org-check-after-date))
13713 (?D (call-interactively 'org-check-dates-range))
13714 (?t (call-interactively 'org-show-todo-tree))
13715 (?T (org-show-todo-tree '(4)))
13716 (?m (call-interactively 'org-match-sparse-tree))
13717 ((?p ?P)
13718 (let* ((kwd (completing-read
13719 "Property: " (mapcar #'list (org-buffer-property-keys))))
13720 (value (completing-read
13721 "Value: " (mapcar #'list (org-property-values kwd)))))
13722 (unless (string-match "\\`{.*}\\'" value)
13723 (setq value (concat "\"" value "\"")))
13724 (org-match-sparse-tree arg (concat kwd "=" value))))
13725 ((?r ?R ?/) (call-interactively 'org-occur))
13726 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13728 (defvar-local org-occur-highlights nil
13729 "List of overlays used for occur matches.")
13730 (defvar-local org-occur-parameters nil
13731 "Parameters of the active org-occur calls.
13732 This is a list, each call to org-occur pushes as cons cell,
13733 containing the regular expression and the callback, onto the list.
13734 The list can contain several entries if `org-occur' has been called
13735 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13736 will only contain one set of parameters. When the highlights are
13737 removed (for example with `C-c C-c', or with the next edit (depending
13738 on `org-remove-highlights-with-change'), this variable is emptied
13739 as well.")
13741 (defun org-occur (regexp &optional keep-previous callback)
13742 "Make a compact tree which shows all matches of REGEXP.
13744 The tree will show the lines where the regexp matches, and any other context
13745 defined in `org-show-context-detail', which see.
13747 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13748 done by a previous call to `org-occur' will be kept, to allow stacking of
13749 calls to this command.
13751 Optional argument CALLBACK can be a function of no argument. In this case,
13752 it is called with point at the end of the match, match data being set
13753 accordingly. Current match is shown only if the return value is non-nil.
13754 The function must neither move point nor alter narrowing."
13755 (interactive "sRegexp: \nP")
13756 (when (equal regexp "")
13757 (user-error "Regexp cannot be empty"))
13758 (unless keep-previous
13759 (org-remove-occur-highlights nil nil t))
13760 (push (cons regexp callback) org-occur-parameters)
13761 (let ((cnt 0))
13762 (save-excursion
13763 (goto-char (point-min))
13764 (when (or (not keep-previous) ; do not want to keep
13765 (not org-occur-highlights)) ; no previous matches
13766 ;; hide everything
13767 (org-overview))
13768 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13769 (isearch-no-upper-case-p regexp t)
13770 org-occur-case-fold-search)))
13771 (while (re-search-forward regexp nil t)
13772 (when (or (not callback)
13773 (save-match-data (funcall callback)))
13774 (setq cnt (1+ cnt))
13775 (when org-highlight-sparse-tree-matches
13776 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13777 (org-show-context 'occur-tree)))))
13778 (when org-remove-highlights-with-change
13779 (add-hook 'before-change-functions 'org-remove-occur-highlights
13780 nil 'local))
13781 (unless org-sparse-tree-open-archived-trees
13782 (org-hide-archived-subtrees (point-min) (point-max)))
13783 (run-hooks 'org-occur-hook)
13784 (when (called-interactively-p 'interactive)
13785 (message "%d match(es) for regexp %s" cnt regexp))
13786 cnt))
13788 (defun org-occur-next-match (&optional n _reset)
13789 "Function for `next-error-function' to find sparse tree matches.
13790 N is the number of matches to move, when negative move backwards.
13791 This function always goes back to the starting point when no
13792 match is found."
13793 (let* ((limit (if (< n 0) (point-min) (point-max)))
13794 (search-func (if (< n 0)
13795 'previous-single-char-property-change
13796 'next-single-char-property-change))
13797 (n (abs n))
13798 (pos (point))
13800 (catch 'exit
13801 (while (setq p1 (funcall search-func (point) 'org-type))
13802 (when (equal p1 limit)
13803 (goto-char pos)
13804 (user-error "No more matches"))
13805 (when (equal (get-char-property p1 'org-type) 'org-occur)
13806 (setq n (1- n))
13807 (when (= n 0)
13808 (goto-char p1)
13809 (throw 'exit (point))))
13810 (goto-char p1))
13811 (goto-char p1)
13812 (user-error "No more matches"))))
13814 (defun org-show-context (&optional key)
13815 "Make sure point and context are visible.
13816 Optional argument KEY, when non-nil, is a symbol. See
13817 `org-show-context-detail' for allowed values and how much is to
13818 be shown."
13819 (org-show-set-visibility
13820 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13821 ((cdr (assq key org-show-context-detail)))
13822 (t (cdr (assq 'default org-show-context-detail))))))
13824 (defun org-show-set-visibility (detail)
13825 "Set visibility around point according to DETAIL.
13826 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13827 `tree', `canonical' or t. See `org-show-context-detail' for more
13828 information."
13829 ;; Show current heading and possibly its entry, following headline
13830 ;; or all children.
13831 (if (and (org-at-heading-p) (not (eq detail 'local)))
13832 (org-flag-heading nil)
13833 (org-show-entry)
13834 ;; If point is hidden within a drawer or a block, make sure to
13835 ;; expose it.
13836 (dolist (o (overlays-at (point)))
13837 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13838 (delete-overlay o)))
13839 (unless (org-before-first-heading-p)
13840 (org-with-limited-levels
13841 (cl-case detail
13842 ((tree canonical t) (org-show-children))
13843 ((nil minimal ancestors))
13844 (t (save-excursion
13845 (outline-next-heading)
13846 (org-flag-heading nil)))))))
13847 ;; Show all siblings.
13848 (when (eq detail 'lineage) (org-show-siblings))
13849 ;; Show ancestors, possibly with their children.
13850 (when (memq detail '(ancestors lineage tree canonical t))
13851 (save-excursion
13852 (while (org-up-heading-safe)
13853 (org-flag-heading nil)
13854 (when (memq detail '(canonical t)) (org-show-entry))
13855 (when (memq detail '(tree canonical t)) (org-show-children))))))
13857 (defvar org-reveal-start-hook nil
13858 "Hook run before revealing a location.")
13860 (defun org-reveal (&optional siblings)
13861 "Show current entry, hierarchy above it, and the following headline.
13863 This can be used to show a consistent set of context around
13864 locations exposed with `org-show-context'.
13866 With optional argument SIBLINGS, on each level of the hierarchy all
13867 siblings are shown. This repairs the tree structure to what it would
13868 look like when opened with hierarchical calls to `org-cycle'.
13870 With a \\[universal-argument] \\[universal-argument] prefix, \
13871 go to the parent and show the entire tree."
13872 (interactive "P")
13873 (run-hooks 'org-reveal-start-hook)
13874 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13875 ((equal siblings '(16))
13876 (save-excursion
13877 (when (org-up-heading-safe)
13878 (org-show-subtree)
13879 (run-hook-with-args 'org-cycle-hook 'subtree))))
13880 (t (org-show-set-visibility 'lineage))))
13882 (defun org-highlight-new-match (beg end)
13883 "Highlight from BEG to END and mark the highlight is an occur headline."
13884 (let ((ov (make-overlay beg end)))
13885 (overlay-put ov 'face 'secondary-selection)
13886 (overlay-put ov 'org-type 'org-occur)
13887 (push ov org-occur-highlights)))
13889 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13890 "Remove the occur highlights from the buffer.
13891 BEG and END are ignored. If NOREMOVE is nil, remove this function
13892 from the `before-change-functions' in the current buffer."
13893 (interactive)
13894 (unless org-inhibit-highlight-removal
13895 (mapc #'delete-overlay org-occur-highlights)
13896 (setq org-occur-highlights nil)
13897 (setq org-occur-parameters nil)
13898 (unless noremove
13899 (remove-hook 'before-change-functions
13900 'org-remove-occur-highlights 'local))))
13902 ;;;; Priorities
13904 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13905 "Regular expression matching the priority indicator.")
13907 (defvar org-remove-priority-next-time nil)
13909 (defun org-priority-up ()
13910 "Increase the priority of the current item."
13911 (interactive)
13912 (org-priority 'up))
13914 (defun org-priority-down ()
13915 "Decrease the priority of the current item."
13916 (interactive)
13917 (org-priority 'down))
13919 (defun org-priority (&optional action _show)
13920 "Change the priority of an item.
13921 ACTION can be `set', `up', `down', or a character."
13922 (interactive "P")
13923 (if (equal action '(4))
13924 (org-show-priority)
13925 (unless org-enable-priority-commands
13926 (user-error "Priority commands are disabled"))
13927 (setq action (or action 'set))
13928 (let (current new news have remove)
13929 (save-excursion
13930 (org-back-to-heading t)
13931 (when (looking-at org-priority-regexp)
13932 (setq current (string-to-char (match-string 2))
13933 have t))
13934 (cond
13935 ((eq action 'remove)
13936 (setq remove t new ?\ ))
13937 ((or (eq action 'set)
13938 (integerp action))
13939 (if (not (eq action 'set))
13940 (setq new action)
13941 (message "Priority %c-%c, SPC to remove: "
13942 org-highest-priority org-lowest-priority)
13943 (save-match-data
13944 (setq new (read-char-exclusive))))
13945 (when (and (= (upcase org-highest-priority) org-highest-priority)
13946 (= (upcase org-lowest-priority) org-lowest-priority))
13947 (setq new (upcase new)))
13948 (cond ((equal new ?\ ) (setq remove t))
13949 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
13950 (user-error "Priority must be between `%c' and `%c'"
13951 org-highest-priority org-lowest-priority))))
13952 ((eq action 'up)
13953 (setq new (if have
13954 (1- current) ; normal cycling
13955 ;; last priority was empty
13956 (if (eq last-command this-command)
13957 org-lowest-priority ; wrap around empty to lowest
13958 ;; default
13959 (if org-priority-start-cycle-with-default
13960 org-default-priority
13961 (1- org-default-priority))))))
13962 ((eq action 'down)
13963 (setq new (if have
13964 (1+ current) ; normal cycling
13965 ;; last priority was empty
13966 (if (eq last-command this-command)
13967 org-highest-priority ; wrap around empty to highest
13968 ;; default
13969 (if org-priority-start-cycle-with-default
13970 org-default-priority
13971 (1+ org-default-priority))))))
13972 (t (user-error "Invalid action")))
13973 (when (or (< (upcase new) org-highest-priority)
13974 (> (upcase new) org-lowest-priority))
13975 (if (and (memq action '(up down))
13976 (not have) (not (eq last-command this-command)))
13977 ;; `new' is from default priority
13978 (error
13979 "The default can not be set, see `org-default-priority' why")
13980 ;; normal cycling: `new' is beyond highest/lowest priority
13981 ;; and is wrapped around to the empty priority
13982 (setq remove t)))
13983 (setq news (format "%c" new))
13984 (if have
13985 (if remove
13986 (replace-match "" t t nil 1)
13987 (replace-match news t t nil 2))
13988 (if remove
13989 (user-error "No priority cookie found in line")
13990 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13991 (if (match-end 2)
13992 (progn
13993 (goto-char (match-end 2))
13994 (insert " [#" news "]"))
13995 (goto-char (match-beginning 3))
13996 (insert "[#" news "] "))))
13997 (org-set-tags nil 'align))
13998 (if remove
13999 (message "Priority removed")
14000 (message "Priority of current item set to %s" news)))))
14002 (defun org-show-priority ()
14003 "Show the priority of the current item.
14004 This priority is composed of the main priority given with the [#A] cookies,
14005 and by additional input from the age of a schedules or deadline entry."
14006 (interactive)
14007 (let ((pri (if (eq major-mode 'org-agenda-mode)
14008 (org-get-at-bol 'priority)
14009 (save-excursion
14010 (save-match-data
14011 (beginning-of-line)
14012 (and (looking-at org-heading-regexp)
14013 (org-get-priority (match-string 0))))))))
14014 (message "Priority is %d" (if pri pri -1000))))
14016 (defun org-get-priority (s)
14017 "Find priority cookie and return priority."
14018 (save-match-data
14019 (if (functionp org-get-priority-function)
14020 (funcall org-get-priority-function)
14021 (if (not (string-match org-priority-regexp s))
14022 (* 1000 (- org-lowest-priority org-default-priority))
14023 (* 1000 (- org-lowest-priority
14024 (string-to-char (match-string 2 s))))))))
14026 ;;;; Tags
14028 (defvar org-agenda-archives-mode)
14029 (defvar org-map-continue-from nil
14030 "Position from where mapping should continue.
14031 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14033 (defvar org-scanner-tags nil
14034 "The current tag list while the tags scanner is running.")
14036 (defvar org-trust-scanner-tags nil
14037 "Should `org-get-tags-at' use the tags for the scanner.
14038 This is for internal dynamical scoping only.
14039 When this is non-nil, the function `org-get-tags-at' will return the value
14040 of `org-scanner-tags' instead of building the list by itself. This
14041 can lead to large speed-ups when the tags scanner is used in a file with
14042 many entries, and when the list of tags is retrieved, for example to
14043 obtain a list of properties. Building the tags list for each entry in such
14044 a file becomes an N^2 operation - but with this variable set, it scales
14045 as N.")
14047 (defvar org--matcher-tags-todo-only nil)
14049 (defun org-scan-tags (action matcher todo-only &optional start-level)
14050 "Scan headline tags with inheritance and produce output ACTION.
14052 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14053 or `agenda' to produce an entry list for an agenda view. It can also be
14054 a Lisp form or a function that should be called at each matched headline, in
14055 this case the return value is a list of all return values from these calls.
14057 MATCHER is a function accepting three arguments, returning
14058 a non-nil value whenever a given set of tags qualifies a headline
14059 for inclusion. See `org-make-tags-matcher' for more information.
14060 As a special case, it can also be set to t (respectively nil) in
14061 order to match all (respectively none) headline.
14063 When TODO-ONLY is non-nil, only lines with a TODO keyword are
14064 included in the output.
14066 START-LEVEL can be a string with asterisks, reducing the scope to
14067 headlines matching this string."
14068 (require 'org-agenda)
14069 (let* ((re (concat "^"
14070 (if start-level
14071 ;; Get the correct level to match
14072 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14073 org-outline-regexp)
14074 " *\\(\\<\\("
14075 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14076 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14077 (props (list 'face 'default
14078 'done-face 'org-agenda-done
14079 'undone-face 'default
14080 'mouse-face 'highlight
14081 'org-not-done-regexp org-not-done-regexp
14082 'org-todo-regexp org-todo-regexp
14083 'org-complex-heading-regexp org-complex-heading-regexp
14084 'help-echo
14085 (format "mouse-2 or RET jump to org file %s"
14086 (abbreviate-file-name
14087 (or (buffer-file-name (buffer-base-buffer))
14088 (buffer-name (buffer-base-buffer)))))))
14089 (org-map-continue-from nil)
14090 lspos tags tags-list
14091 (tags-alist (list (cons 0 org-file-tags)))
14092 (llast 0) rtn rtn1 level category i txt
14093 todo marker entry priority
14094 ts-date ts-date-type ts-date-pair)
14095 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14096 (setq action (list 'lambda nil action)))
14097 (save-excursion
14098 (goto-char (point-min))
14099 (when (eq action 'sparse-tree)
14100 (org-overview)
14101 (org-remove-occur-highlights))
14102 (while (let (case-fold-search)
14103 (re-search-forward re nil t))
14104 (setq org-map-continue-from nil)
14105 (catch :skip
14106 (setq todo
14107 ;; TODO: is the 1-2 difference a bug?
14108 (when (match-end 1) (match-string-no-properties 2))
14109 tags (when (match-end 4) (match-string-no-properties 4)))
14110 (goto-char (setq lspos (match-beginning 0)))
14111 (setq level (org-reduced-level (org-outline-level))
14112 category (org-get-category))
14113 (when (eq action 'agenda)
14114 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14115 ts-date (car ts-date-pair)
14116 ts-date-type (cdr ts-date-pair)))
14117 (setq i llast llast level)
14118 ;; remove tag lists from same and sublevels
14119 (while (>= i level)
14120 (when (setq entry (assoc i tags-alist))
14121 (setq tags-alist (delete entry tags-alist)))
14122 (setq i (1- i)))
14123 ;; add the next tags
14124 (when tags
14125 (setq tags (org-split-string tags ":")
14126 tags-alist
14127 (cons (cons level tags) tags-alist)))
14128 ;; compile tags for current headline
14129 (setq tags-list
14130 (if org-use-tag-inheritance
14131 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14132 tags)
14133 org-scanner-tags tags-list)
14134 (when org-use-tag-inheritance
14135 (setcdr (car tags-alist)
14136 (mapcar (lambda (x)
14137 (setq x (copy-sequence x))
14138 (org-add-prop-inherited x))
14139 (cdar tags-alist))))
14140 (when (and tags org-use-tag-inheritance
14141 (or (not (eq t org-use-tag-inheritance))
14142 org-tags-exclude-from-inheritance))
14143 ;; Selective inheritance, remove uninherited ones.
14144 (setcdr (car tags-alist)
14145 (org-remove-uninherited-tags (cdar tags-alist))))
14146 (when (and
14148 ;; eval matcher only when the todo condition is OK
14149 (and (or (not todo-only) (member todo org-todo-keywords-1))
14150 (if (functionp matcher)
14151 (let ((case-fold-search t) (org-trust-scanner-tags t))
14152 (funcall matcher todo tags-list level))
14153 matcher))
14155 ;; Call the skipper, but return t if it does not
14156 ;; skip, so that the `and' form continues evaluating.
14157 (progn
14158 (unless (eq action 'sparse-tree) (org-agenda-skip))
14161 ;; Check if timestamps are deselecting this entry
14162 (or (not todo-only)
14163 (and (member todo org-todo-keywords-1)
14164 (or (not org-agenda-tags-todo-honor-ignore-options)
14165 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14167 ;; select this headline
14168 (cond
14169 ((eq action 'sparse-tree)
14170 (and org-highlight-sparse-tree-matches
14171 (org-get-heading) (match-end 0)
14172 (org-highlight-new-match
14173 (match-beginning 1) (match-end 1)))
14174 (org-show-context 'tags-tree))
14175 ((eq action 'agenda)
14176 (setq txt (org-agenda-format-item
14178 (concat
14179 (if (eq org-tags-match-list-sublevels 'indented)
14180 (make-string (1- level) ?.) "")
14181 (org-get-heading))
14182 (make-string level ?\s)
14183 category
14184 tags-list)
14185 priority (org-get-priority txt))
14186 (goto-char lspos)
14187 (setq marker (org-agenda-new-marker))
14188 (org-add-props txt props
14189 'org-marker marker 'org-hd-marker marker 'org-category category
14190 'todo-state todo
14191 'ts-date ts-date
14192 'priority priority
14193 'type (concat "tagsmatch" ts-date-type))
14194 (push txt rtn))
14195 ((functionp action)
14196 (setq org-map-continue-from nil)
14197 (save-excursion
14198 (setq rtn1 (funcall action))
14199 (push rtn1 rtn)))
14200 (t (user-error "Invalid action")))
14202 ;; if we are to skip sublevels, jump to end of subtree
14203 (unless org-tags-match-list-sublevels
14204 (org-end-of-subtree t)
14205 (backward-char 1))))
14206 ;; Get the correct position from where to continue
14207 (if org-map-continue-from
14208 (goto-char org-map-continue-from)
14209 (and (= (point) lspos) (end-of-line 1)))))
14210 (when (and (eq action 'sparse-tree)
14211 (not org-sparse-tree-open-archived-trees))
14212 (org-hide-archived-subtrees (point-min) (point-max)))
14213 (nreverse rtn)))
14215 (defun org-remove-uninherited-tags (tags)
14216 "Remove all tags that are not inherited from the list TAGS."
14217 (cond
14218 ((eq org-use-tag-inheritance t)
14219 (if org-tags-exclude-from-inheritance
14220 (org-delete-all org-tags-exclude-from-inheritance tags)
14221 tags))
14222 ((not org-use-tag-inheritance) nil)
14223 ((stringp org-use-tag-inheritance)
14224 (delq nil (mapcar
14225 (lambda (x)
14226 (if (and (string-match org-use-tag-inheritance x)
14227 (not (member x org-tags-exclude-from-inheritance)))
14228 x nil))
14229 tags)))
14230 ((listp org-use-tag-inheritance)
14231 (delq nil (mapcar
14232 (lambda (x)
14233 (if (member x org-use-tag-inheritance) x nil))
14234 tags)))))
14236 (defun org-match-sparse-tree (&optional todo-only match)
14237 "Create a sparse tree according to tags string MATCH.
14239 MATCH is a string with match syntax. It can contain a selection
14240 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14241 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14242 those. See the manual for details.
14244 If optional argument TODO-ONLY is non-nil, only select lines that
14245 are also TODO tasks."
14246 (interactive "P")
14247 (org-agenda-prepare-buffers (list (current-buffer)))
14248 (let ((org--matcher-tags-todo-only todo-only))
14249 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14250 org--matcher-tags-todo-only)))
14252 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14254 (defvar org-cached-props nil)
14255 (defun org-cached-entry-get (pom property)
14256 (if (or (eq t org-use-property-inheritance)
14257 (and (stringp org-use-property-inheritance)
14258 (let ((case-fold-search t))
14259 (string-match-p org-use-property-inheritance property)))
14260 (and (listp org-use-property-inheritance)
14261 (member-ignore-case property org-use-property-inheritance)))
14262 ;; Caching is not possible, check it directly.
14263 (org-entry-get pom property 'inherit)
14264 ;; Get all properties, so we can do complicated checks easily.
14265 (cdr (assoc-string property
14266 (or org-cached-props
14267 (setq org-cached-props (org-entry-properties pom)))
14268 t))))
14270 (defun org-global-tags-completion-table (&optional files)
14271 "Return the list of all tags in all agenda buffer/files.
14272 Optional FILES argument is a list of files which can be used
14273 instead of the agenda files."
14274 (save-excursion
14275 (org-uniquify
14276 (delq nil
14277 (apply #'append
14278 (mapcar
14279 (lambda (file)
14280 (set-buffer (find-file-noselect file))
14281 (mapcar (lambda (x)
14282 (and (stringp (car-safe x))
14283 (list (car-safe x))))
14284 (or org-current-tag-alist (org-get-buffer-tags))))
14285 (if (car-safe files) files
14286 (org-agenda-files))))))))
14288 (defun org-make-tags-matcher (match)
14289 "Create the TAGS/TODO matcher form for the selection string MATCH.
14291 Returns a cons of the selection string MATCH and a function
14292 implementing the matcher.
14294 The matcher is to be called at an Org entry, with point on the
14295 headline, and returns non-nil if the entry matches the selection
14296 string MATCH. It must be called with three arguments: the TODO
14297 keyword at the entry (or nil if none), the list of all tags at
14298 the entry including inherited ones and the reduced level of the
14299 headline. Additionally, the category of the entry, if any, must
14300 be specified as the text property `org-category' on the headline.
14302 This function sets the variable `org--matcher-tags-todo-only' to
14303 a non-nil value if the matcher restricts matching to TODO
14304 entries, otherwise it is not touched.
14306 See also `org-scan-tags'."
14307 (unless match
14308 ;; Get a new match request, with completion against the global
14309 ;; tags table and the local tags in current buffer.
14310 (let ((org-last-tags-completion-table
14311 (org-uniquify
14312 (delq nil (append (org-get-buffer-tags)
14313 (org-global-tags-completion-table))))))
14314 (setq match
14315 (completing-read
14316 "Match: "
14317 'org-tags-completion-function nil nil nil 'org-tags-history))))
14319 (let ((match0 match)
14320 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14321 (start 0)
14322 tagsmatch todomatch tagsmatcher todomatcher)
14324 ;; Expand group tags.
14325 (setq match (org-tags-expand match))
14327 ;; Check if there is a TODO part of this match, which would be the
14328 ;; part after a "/". To make sure that this slash is not part of
14329 ;; a property value to be matched against, we also check that
14330 ;; there is no / after that slash. First, find the last slash.
14331 (let ((s 0))
14332 (while (string-match "/+" match s)
14333 (setq start (match-beginning 0))
14334 (setq s (match-end 0))))
14335 (if (and (string-match "/+" match start)
14336 (not (string-match-p "\"" match start)))
14337 ;; Match contains also a TODO-matching request.
14338 (progn
14339 (setq tagsmatch (substring match 0 (match-beginning 0)))
14340 (setq todomatch (substring match (match-end 0)))
14341 (when (string-prefix-p "!" todomatch)
14342 (setq org--matcher-tags-todo-only t)
14343 (setq todomatch (substring todomatch 1)))
14344 (when (string-match "\\`\\s-*\\'" todomatch)
14345 (setq todomatch nil)))
14346 ;; Only matching tags.
14347 (setq tagsmatch match)
14348 (setq todomatch nil))
14350 ;; Make the tags matcher.
14351 (when (org-string-nw-p tagsmatch)
14352 (let ((orlist nil)
14353 (orterms (org-split-string tagsmatch "|"))
14354 term)
14355 (while (setq term (pop orterms))
14356 (while (and (equal (substring term -1) "\\") orterms)
14357 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14358 (while (string-match re term)
14359 (let* ((rest (substring term (match-end 0)))
14360 (minus (and (match-end 1)
14361 (equal (match-string 1 term) "-")))
14362 (tag (save-match-data
14363 (replace-regexp-in-string
14364 "\\\\-" "-" (match-string 2 term))))
14365 (regexp (eq (string-to-char tag) ?{))
14366 (levelp (match-end 4))
14367 (propp (match-end 5))
14369 (cond
14370 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14371 (levelp
14372 `(,(org-op-to-function (match-string 3 term))
14373 level
14374 ,(string-to-number (match-string 4 term))))
14375 (propp
14376 (let* ((gv (pcase (upcase (match-string 5 term))
14377 ("CATEGORY"
14378 '(get-text-property (point) 'org-category))
14379 ("TODO" 'todo)
14380 (p `(org-cached-entry-get nil ,p))))
14381 (pv (match-string 7 term))
14382 (regexp (eq (string-to-char pv) ?{))
14383 (strp (eq (string-to-char pv) ?\"))
14384 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14385 (po (org-op-to-function (match-string 6 term)
14386 (if timep 'time strp))))
14387 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14388 (when timep (setq pv (org-matcher-time pv)))
14389 (cond ((and regexp (eq po 'org<>))
14390 `(not (string-match ,pv (or ,gv ""))))
14391 (regexp `(string-match ,pv (or ,gv "")))
14392 (strp `(,po (or ,gv "") ,pv))
14394 `(,po
14395 (string-to-number (or ,gv ""))
14396 ,(string-to-number pv))))))
14397 (t `(member ,tag tags-list)))))
14398 (push (if minus `(not ,mm) mm) tagsmatcher)
14399 (setq term rest)))
14400 (push `(and ,@tagsmatcher) orlist)
14401 (setq tagsmatcher nil))
14402 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14404 ;; Make the TODO matcher.
14405 (when (org-string-nw-p todomatch)
14406 (let ((orlist nil))
14407 (dolist (term (org-split-string todomatch "|"))
14408 (while (string-match re term)
14409 (let* ((minus (and (match-end 1)
14410 (equal (match-string 1 term) "-")))
14411 (kwd (match-string 2 term))
14412 (regexp (eq (string-to-char kwd) ?{))
14413 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14414 `(equal todo ,kwd))))
14415 (push (if minus `(not ,mm) mm) todomatcher))
14416 (setq term (substring term (match-end 0))))
14417 (push (if (> (length todomatcher) 1)
14418 (cons 'and todomatcher)
14419 (car todomatcher))
14420 orlist)
14421 (setq todomatcher nil))
14422 (setq todomatcher (cons 'or orlist))))
14424 ;; Return the string and function of the matcher. If no
14425 ;; tags-specific or todo-specific matcher exists, match
14426 ;; everything.
14427 (let ((matcher (if (and tagsmatcher todomatcher)
14428 `(and ,tagsmatcher ,todomatcher)
14429 (or tagsmatcher todomatcher t))))
14430 (when org--matcher-tags-todo-only
14431 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14432 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14434 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14435 "Expand group tags in MATCH.
14437 This replaces every group tag in MATCH with a regexp tag search.
14438 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14439 will be replaced like this:
14441 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14442 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14443 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14445 Replacing by a regexp preserves the structure of the match.
14446 E.g., this expansion
14448 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14450 will match anything tagged with \"Lab\" and \"Home\", or tagged
14451 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14453 A group tag in MATCH can contain regular expressions of its own.
14454 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14455 will be replaced like this:
14457 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14459 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14460 assumed to be a single group tag, and the function will return
14461 the list of tags in this group.
14463 When DOWNCASE is non-nil, expand downcased TAGS."
14464 (if org-group-tags
14465 (let* ((case-fold-search t)
14466 (stable org-mode-syntax-table)
14467 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14468 (taggroups (if downcased
14469 (mapcar (lambda (tg) (mapcar #'downcase tg))
14470 taggroups)
14471 taggroups))
14472 (taggroups-keys (mapcar #'car taggroups))
14473 (return-match (if downcased (downcase match) match))
14474 (count 0)
14475 (work-already-expanded tags-already-expanded)
14476 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14477 ;; @ and _ are allowed as word-components in tags.
14478 (modify-syntax-entry ?@ "w" stable)
14479 (modify-syntax-entry ?_ "w" stable)
14480 ;; Temporarily replace regexp-expressions in the match-expression.
14481 (while (string-match "{.+?}" return-match)
14482 (cl-incf count)
14483 (push (match-string 0 return-match) regexps-in-match)
14484 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14485 (while (and taggroups-keys
14486 (with-syntax-table stable
14487 (string-match
14488 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14489 (regexp-opt taggroups-keys) "\\>\\)")
14490 return-match)))
14491 (let* ((dir (match-string 1 return-match))
14492 (tag (match-string 2 return-match))
14493 (tag (if downcased (downcase tag) tag)))
14494 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14495 (member tag work-already-expanded))
14496 (setq tags-in-group (assoc tag taggroups))
14497 (push tag work-already-expanded)
14498 ;; Recursively expand each tag in the group, if the tag hasn't
14499 ;; already been expanded. Restore the match-data after all recursive calls.
14500 (save-match-data
14501 (let (tags-expanded)
14502 (dolist (x (cdr tags-in-group))
14503 (if (and (member x taggroups-keys)
14504 (not (member x work-already-expanded)))
14505 (setq tags-expanded
14506 (delete-dups
14507 (append
14508 (org-tags-expand x t downcased
14509 work-already-expanded)
14510 tags-expanded)))
14511 (setq tags-expanded
14512 (append (list x) tags-expanded)))
14513 (setq work-already-expanded
14514 (delete-dups
14515 (append tags-expanded
14516 work-already-expanded))))
14517 (setq tags-in-group
14518 (delete-dups (cons (car tags-in-group)
14519 tags-expanded)))))
14520 ;; Filter tag-regexps from tags.
14521 (setq regexp-in-group-escaped
14522 (delq nil (mapcar (lambda (x)
14523 (if (stringp x)
14524 (and (equal "{" (substring x 0 1))
14525 (equal "}" (substring x -1))
14528 tags-in-group))
14529 regexp-in-group
14530 (mapcar (lambda (x)
14531 (substring x 1 -1))
14532 regexp-in-group-escaped)
14533 tags-in-group
14534 (delq nil (mapcar (lambda (x)
14535 (if (stringp x)
14536 (and (not (equal "{" (substring x 0 1)))
14537 (not (equal "}" (substring x -1)))
14540 tags-in-group)))
14541 ;; If single-as-list, do no more in the while-loop.
14542 (if (not single-as-list)
14543 (progn
14544 (when regexp-in-group
14545 (setq regexp-in-group
14546 (concat "\\|"
14547 (mapconcat 'identity regexp-in-group
14548 "\\|"))))
14549 (setq tags-in-group
14550 (concat dir
14551 "{\\<"
14552 (regexp-opt tags-in-group)
14553 "\\>"
14554 regexp-in-group
14555 "}"))
14556 (when (stringp tags-in-group)
14557 (org-add-props tags-in-group '(grouptag t)))
14558 (setq return-match
14559 (replace-match tags-in-group t t return-match)))
14560 (setq tags-in-group
14561 (append regexp-in-group-escaped tags-in-group))))
14562 (setq taggroups-keys (delete tag taggroups-keys))))
14563 ;; Add the regular expressions back into the match-expression again.
14564 (while regexps-in-match
14565 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14566 (pop regexps-in-match)
14567 return-match t t))
14568 (cl-decf count))
14569 (if single-as-list
14570 (if tags-in-group tags-in-group (list return-match))
14571 return-match))
14572 (if single-as-list
14573 (list (if downcased (downcase match) match))
14574 match)))
14576 (defun org-op-to-function (op &optional stringp)
14577 "Turn an operator into the appropriate function."
14578 (setq op
14579 (cond
14580 ((equal op "<" ) '(< string< org-time<))
14581 ((equal op ">" ) '(> org-string> org-time>))
14582 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14583 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14584 ((member op '("=" "==")) '(= string= org-time=))
14585 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14586 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14588 (defun org<> (a b) (not (= a b)))
14589 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14590 (defun org-string>= (a b) (not (string< a b)))
14591 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14592 (defun org-string<> (a b) (not (string= a b)))
14593 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14594 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14595 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14596 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> 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) (org<> a b)))
14599 (defun org-2ft (s)
14600 "Convert S to a floating point time.
14601 If S is already a number, just return it. If it is a string, parse
14602 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14603 (cond
14604 ((numberp s) s)
14605 ((stringp s)
14606 (condition-case nil
14607 (float-time (apply #'encode-time (org-parse-time-string s nil t)))
14608 (error 0.)))
14609 (t 0.)))
14611 (defun org-time-today ()
14612 "Time in seconds today at 0:00.
14613 Returns the float number of seconds since the beginning of the
14614 epoch to the beginning of today (00:00)."
14615 (float-time (apply 'encode-time
14616 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14618 (defun org-matcher-time (s)
14619 "Interpret a time comparison value."
14620 (save-match-data
14621 (cond
14622 ((string= s "<now>") (float-time))
14623 ((string= s "<today>") (org-time-today))
14624 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14625 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14626 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14627 (+ (org-time-today)
14628 (* (string-to-number (match-string 1 s))
14629 (cdr (assoc (match-string 2 s)
14630 '(("d" . 86400.0) ("w" . 604800.0)
14631 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14632 (t (org-2ft s)))))
14634 (defun org-match-any-p (re list)
14635 "Does re match any element of list?"
14636 (setq list (mapcar (lambda (x) (string-match re x)) list))
14637 (delq nil list))
14639 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14640 (defvar org-tags-overlay (make-overlay 1 1))
14641 (delete-overlay org-tags-overlay)
14643 (defun org-get-local-tags-at (&optional pos)
14644 "Get a list of tags defined in the current headline."
14645 (org-get-tags-at pos 'local))
14647 (defun org-get-local-tags ()
14648 "Get a list of tags defined in the current headline."
14649 (org-get-tags-at nil 'local))
14651 (defun org-get-tags-at (&optional pos local)
14652 "Get a list of all headline tags applicable at POS.
14653 POS defaults to point. If tags are inherited, the list contains
14654 the targets in the same sequence as the headlines appear, i.e.
14655 the tags of the current headline come last.
14656 When LOCAL is non-nil, only return tags from the current headline,
14657 ignore inherited ones."
14658 (interactive)
14659 (if (and org-trust-scanner-tags
14660 (or (not pos) (equal pos (point)))
14661 (not local))
14662 org-scanner-tags
14663 (let (tags ltags lastpos parent)
14664 (save-excursion
14665 (save-restriction
14666 (widen)
14667 (goto-char (or pos (point)))
14668 (save-match-data
14669 (catch 'done
14670 (condition-case nil
14671 (progn
14672 (org-back-to-heading t)
14673 (while (not (equal lastpos (point)))
14674 (setq lastpos (point))
14675 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14676 (setq ltags (org-split-string
14677 (match-string-no-properties 1) ":"))
14678 (when parent
14679 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14680 (setq tags (append
14681 (if parent
14682 (org-remove-uninherited-tags ltags)
14683 ltags)
14684 tags)))
14685 (or org-use-tag-inheritance (throw 'done t))
14686 (when local (throw 'done t))
14687 (or (org-up-heading-safe) (error nil))
14688 (setq parent t)))
14689 (error nil)))))
14690 (if local
14691 tags
14692 (reverse (delete-dups
14693 (reverse (append
14694 (org-remove-uninherited-tags
14695 org-file-tags)
14696 tags)))))))))
14698 (defun org-add-prop-inherited (s)
14699 (add-text-properties 0 (length s) '(inherited t) s)
14702 (defun org-toggle-tag (tag &optional onoff)
14703 "Toggle the tag TAG for the current line.
14704 If ONOFF is `on' or `off', don't toggle but set to this state."
14705 (save-excursion
14706 (org-back-to-heading t)
14707 (let ((current
14708 (when (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14709 (line-end-position) t)
14710 (let ((tags (match-string 1)))
14711 ;; Clear current tags.
14712 (replace-match "")
14713 ;; Reverse the tags list so any new tag is appended to
14714 ;; the current list of tags.
14715 (nreverse (org-split-string tags ":")))))
14716 res)
14717 (pcase onoff
14718 (`off (setq current (delete tag current)))
14719 ((or `on (guard (not (member tag current))))
14720 (setq res t)
14721 (cl-pushnew tag current :test #'equal))
14722 (_ (setq current (delete tag current))))
14723 (end-of-line)
14724 (if current
14725 (progn
14726 (insert " :" (mapconcat #'identity (nreverse current) ":") ":")
14727 (org-set-tags nil t))
14728 (delete-horizontal-space))
14729 (run-hooks 'org-after-tags-change-hook)
14730 res)))
14732 (defun org--align-tags-here (to-col)
14733 "Align tags on the current headline to TO-COL.
14734 Assume point is on a headline."
14735 (let ((pos (point)))
14736 (beginning-of-line)
14737 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14738 (>= pos (match-beginning 2)))
14739 ;; No tags or point within tags: do not align.
14740 (goto-char pos)
14741 (goto-char (match-beginning 1))
14742 (let ((shift (max (- (if (>= to-col 0) to-col
14743 (- (abs to-col) (string-width (match-string 2))))
14744 (current-column))
14745 1)))
14746 (replace-match (make-string shift ?\s) nil nil nil 1)
14747 ;; Preserve initial position, if possible. In any case, stop
14748 ;; before tags.
14749 (when (< pos (point)) (goto-char pos))))))
14751 (defun org-set-tags-command (&optional arg just-align)
14752 "Call the set-tags command for the current entry."
14753 (interactive "P")
14754 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14755 (org-set-tags arg just-align)
14756 (save-excursion
14757 (unless (and (org-region-active-p)
14758 org-loop-over-headlines-in-active-region)
14759 (org-back-to-heading t))
14760 (org-set-tags arg just-align))))
14762 (defun org-set-tags-to (data)
14763 "Set the tags of the current entry to DATA, replacing the current tags.
14764 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14765 If DATA is nil or the empty string, any tags will be removed."
14766 (interactive "sTags: ")
14767 (setq data
14768 (cond
14769 ((eq data nil) "")
14770 ((equal data "") "")
14771 ((stringp data)
14772 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14773 ":"))
14774 ((listp data)
14775 (concat ":" (mapconcat 'identity data ":") ":"))))
14776 (when data
14777 (save-excursion
14778 (org-back-to-heading t)
14779 (when (let ((case-fold-search nil))
14780 (looking-at org-complex-heading-regexp))
14781 (if (match-end 5)
14782 (progn
14783 (goto-char (match-beginning 5))
14784 (insert data)
14785 (delete-region (point) (point-at-eol))
14786 (org-set-tags nil 'align))
14787 (goto-char (point-at-eol))
14788 (insert " " data)
14789 (org-set-tags nil 'align)))
14790 (beginning-of-line 1)
14791 (when (looking-at ".*?\\([ \t]+\\)$")
14792 (delete-region (match-beginning 1) (match-end 1))))))
14794 (defun org-align-all-tags ()
14795 "Align the tags in all headings."
14796 (interactive)
14797 (save-excursion
14798 (or (ignore-errors (org-back-to-heading t))
14799 (outline-next-heading))
14800 (if (org-at-heading-p)
14801 (org-set-tags t)
14802 (message "No headings"))))
14804 (defvar org-indent-indentation-per-level)
14805 (defun org-set-tags (&optional arg just-align)
14806 "Set the tags for the current headline.
14807 With prefix ARG, realign all tags in headings in the current buffer.
14808 When JUST-ALIGN is non-nil, only align tags."
14809 (interactive "P")
14810 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14811 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14812 'region-start-level
14813 'region))
14814 org-loop-over-headlines-in-active-region)
14815 (org-map-entries
14816 ;; We don't use ARG and JUST-ALIGN here because these args
14817 ;; are not useful when looping over headlines.
14818 #'org-set-tags
14819 org-loop-over-headlines-in-active-region
14821 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14822 (let ((org-setting-tags t))
14823 (if arg
14824 (save-excursion
14825 (goto-char (point-min))
14826 (while (re-search-forward org-outline-regexp-bol nil t)
14827 (org-set-tags nil t)
14828 (end-of-line))
14829 (message "All tags realigned to column %d" org-tags-column))
14830 (let* ((current (org-get-tags-string))
14831 (tags
14832 (if just-align current
14833 ;; Get a new set of tags from the user.
14834 (save-excursion
14835 (let* ((seen)
14836 (table
14837 (setq
14838 org-last-tags-completion-table
14839 ;; Uniquify tags in alists, yet preserve
14840 ;; structure (i.e., keywords).
14841 (delq nil
14842 (mapcar
14843 (lambda (pair)
14844 (let ((head (car pair)))
14845 (cond ((symbolp head) pair)
14846 ((member head seen) nil)
14847 (t (push head seen)
14848 pair))))
14849 (append
14850 (or org-current-tag-alist
14851 (org-get-buffer-tags))
14852 (and
14853 org-complete-tags-always-offer-all-agenda-tags
14854 (org-global-tags-completion-table
14855 (org-agenda-files))))))))
14856 (current-tags (org-split-string current ":"))
14857 (inherited-tags
14858 (nreverse (nthcdr (length current-tags)
14859 (nreverse (org-get-tags-at))))))
14860 (replace-regexp-in-string
14861 "\\([-+&]+\\|,\\)"
14863 (if (or (eq t org-use-fast-tag-selection)
14864 (and org-use-fast-tag-selection
14865 (delq nil (mapcar #'cdr table))))
14866 (org-fast-tag-selection
14867 current-tags inherited-tags table
14868 (and org-fast-tag-selection-include-todo
14869 org-todo-key-alist))
14870 (let ((org-add-colon-after-tag-completion
14871 (< 1 (length table))))
14872 (org-trim
14873 (completing-read
14874 "Tags: "
14875 #'org-tags-completion-function
14876 nil nil current 'org-tags-history))))))))))
14878 (when org-tags-sort-function
14879 (setq tags
14880 (mapconcat
14881 #'identity
14882 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
14883 org-tags-sort-function)
14884 ":")))
14886 (if (or (string= ":" tags)
14887 (string= "::" tags))
14888 (setq tags ""))
14889 (if (not (org-string-nw-p tags)) (setq tags "")
14890 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
14891 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
14893 ;; Insert new tags at the correct column.
14894 (unless (equal current tags)
14895 (save-excursion
14896 (beginning-of-line)
14897 (let ((case-fold-search nil))
14898 (looking-at org-complex-heading-regexp))
14899 ;; Remove current tags, if any.
14900 (when (match-end 5) (replace-match "" nil nil nil 5))
14901 ;; Insert new tags, if any. Otherwise, remove trailing
14902 ;; white spaces.
14903 (end-of-line)
14904 (if (not (equal tags ""))
14905 ;; When text is being inserted on an invisible
14906 ;; region boundary, it can be inadvertently sucked
14907 ;; into invisibility.
14908 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
14909 (skip-chars-backward " \t")
14910 (delete-region (point) (line-end-position)))))
14911 ;; Align tags, if any. Fix tags column if `org-indent-mode'
14912 ;; is on.
14913 (unless (equal tags "")
14914 (let* ((level (save-excursion
14915 (beginning-of-line)
14916 (skip-chars-forward "\\*")))
14917 (offset (if (bound-and-true-p org-indent-mode)
14918 (* (1- org-indent-indentation-per-level)
14919 (1- level))
14921 (tags-column
14922 (+ org-tags-column
14923 (if (> org-tags-column 0) (- offset) offset))))
14924 (org--align-tags-here tags-column))))
14925 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14927 (defun org-change-tag-in-region (beg end tag off)
14928 "Add or remove TAG for each entry in the region.
14929 This works in the agenda, and also in an Org buffer."
14930 (interactive
14931 (list (region-beginning) (region-end)
14932 (let ((org-last-tags-completion-table
14933 (if (derived-mode-p 'org-mode)
14934 (org-uniquify
14935 (delq nil (append (org-get-buffer-tags)
14936 (org-global-tags-completion-table))))
14937 (org-global-tags-completion-table))))
14938 (completing-read
14939 "Tag: " 'org-tags-completion-function nil nil nil
14940 'org-tags-history))
14941 (progn
14942 (message "[s]et or [r]emove? ")
14943 (equal (read-char-exclusive) ?r))))
14944 (when (fboundp 'deactivate-mark) (deactivate-mark))
14945 (let ((agendap (equal major-mode 'org-agenda-mode))
14946 l1 l2 m buf pos newhead (cnt 0))
14947 (goto-char end)
14948 (setq l2 (1- (org-current-line)))
14949 (goto-char beg)
14950 (setq l1 (org-current-line))
14951 (cl-loop for l from l1 to l2 do
14952 (org-goto-line l)
14953 (setq m (get-text-property (point) 'org-hd-marker))
14954 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
14955 (and agendap m))
14956 (setq buf (if agendap (marker-buffer m) (current-buffer))
14957 pos (if agendap m (point)))
14958 (with-current-buffer buf
14959 (save-excursion
14960 (save-restriction
14961 (goto-char pos)
14962 (setq cnt (1+ cnt))
14963 (org-toggle-tag tag (if off 'off 'on))
14964 (setq newhead (org-get-heading)))))
14965 (and agendap (org-agenda-change-all-lines newhead m))))
14966 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14968 (defun org-tags-completion-function (string _predicate &optional flag)
14969 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14970 (confirm (lambda (x) (stringp (car x)))))
14971 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
14972 (setq s1 (match-string 1 string)
14973 s2 (match-string 2 string))
14974 (setq s1 "" s2 string))
14975 (cond
14976 ((eq flag nil)
14977 ;; try completion
14978 (setq rtn (try-completion s2 ctable confirm))
14979 (when (stringp rtn)
14980 (setq rtn
14981 (concat s1 s2 (substring rtn (length s2))
14982 (if (and org-add-colon-after-tag-completion
14983 (assoc rtn ctable))
14984 ":" ""))))
14985 rtn)
14986 ((eq flag t)
14987 ;; all-completions
14988 (all-completions s2 ctable confirm))
14989 ((eq flag 'lambda)
14990 ;; exact match?
14991 (assoc s2 ctable)))))
14993 (defun org-fast-tag-insert (kwd tags face &optional end)
14994 "Insert KDW, and the TAGS, the latter with face FACE.
14995 Also insert END."
14996 (insert (format "%-12s" (concat kwd ":"))
14997 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14998 (or end "")))
15000 (defun org-fast-tag-show-exit (flag)
15001 (save-excursion
15002 (org-goto-line 3)
15003 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15004 (replace-match ""))
15005 (when flag
15006 (end-of-line 1)
15007 (org-move-to-column (- (window-width) 19) t)
15008 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15010 (defun org-set-current-tags-overlay (current prefix)
15011 "Add an overlay to CURRENT tag with PREFIX."
15012 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15013 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15014 (org-overlay-display org-tags-overlay (concat prefix s))))
15016 (defvar org-last-tag-selection-key nil)
15017 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15018 "Fast tag selection with single keys.
15019 CURRENT is the current list of tags in the headline, INHERITED is the
15020 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15021 possibly with grouping information. TODO-TABLE is a similar table with
15022 TODO keywords, should these have keys assigned to them.
15023 If the keys are nil, a-z are automatically assigned.
15024 Returns the new tags string, or nil to not change the current settings."
15025 (let* ((fulltable (append table todo-table))
15026 (maxlen (apply 'max (mapcar
15027 (lambda (x)
15028 (if (stringp (car x)) (string-width (car x)) 0))
15029 fulltable)))
15030 (buf (current-buffer))
15031 (expert (eq org-fast-tag-selection-single-key 'expert))
15032 (buffer-tags nil)
15033 (fwidth (+ maxlen 3 1 3))
15034 (ncol (/ (- (window-width) 4) fwidth))
15035 (i-face 'org-done)
15036 (c-face 'org-todo)
15037 tg cnt e c char c1 c2 ntable tbl rtn
15038 ov-start ov-end ov-prefix
15039 (exit-after-next org-fast-tag-selection-single-key)
15040 (done-keywords org-done-keywords)
15041 groups ingroup intaggroup)
15042 (save-excursion
15043 (beginning-of-line 1)
15044 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15045 (setq ov-start (match-beginning 1)
15046 ov-end (match-end 1)
15047 ov-prefix "")
15048 (setq ov-start (1- (point-at-eol))
15049 ov-end (1+ ov-start))
15050 (skip-chars-forward "^\n\r")
15051 (setq ov-prefix
15052 (concat
15053 (buffer-substring (1- (point)) (point))
15054 (if (> (current-column) org-tags-column)
15056 (make-string (- org-tags-column (current-column)) ?\ ))))))
15057 (move-overlay org-tags-overlay ov-start ov-end)
15058 (save-window-excursion
15059 (if expert
15060 (set-buffer (get-buffer-create " *Org tags*"))
15061 (delete-other-windows)
15062 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15063 (org-switch-to-buffer-other-window " *Org tags*"))
15064 (erase-buffer)
15065 (setq-local org-done-keywords done-keywords)
15066 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15067 (org-fast-tag-insert "Current" current c-face "\n\n")
15068 (org-fast-tag-show-exit exit-after-next)
15069 (org-set-current-tags-overlay current ov-prefix)
15070 (setq tbl fulltable char ?a cnt 0)
15071 (while (setq e (pop tbl))
15072 (cond
15073 ((eq (car e) :startgroup)
15074 (push '() groups) (setq ingroup t)
15075 (unless (zerop cnt)
15076 (setq cnt 0)
15077 (insert "\n"))
15078 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15079 ((eq (car e) :endgroup)
15080 (setq ingroup nil cnt 0)
15081 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15082 ((eq (car e) :startgrouptag)
15083 (setq intaggroup t)
15084 (unless (zerop cnt)
15085 (setq cnt 0)
15086 (insert "\n"))
15087 (insert "[ "))
15088 ((eq (car e) :endgrouptag)
15089 (setq intaggroup nil cnt 0)
15090 (insert "]\n"))
15091 ((equal e '(:newline))
15092 (unless (zerop cnt)
15093 (setq cnt 0)
15094 (insert "\n")
15095 (setq e (car tbl))
15096 (while (equal (car tbl) '(:newline))
15097 (insert "\n")
15098 (setq tbl (cdr tbl)))))
15099 ((equal e '(:grouptags)) (insert " : "))
15101 (setq tg (copy-sequence (car e)) c2 nil)
15102 (if (cdr e)
15103 (setq c (cdr e))
15104 ;; automatically assign a character.
15105 (setq c1 (string-to-char
15106 (downcase (substring
15107 tg (if (= (string-to-char tg) ?@) 1 0)))))
15108 (if (or (rassoc c1 ntable) (rassoc c1 table))
15109 (while (or (rassoc char ntable) (rassoc char table))
15110 (setq char (1+ char)))
15111 (setq c2 c1))
15112 (setq c (or c2 char)))
15113 (when ingroup (push tg (car groups)))
15114 (setq tg (org-add-props tg nil 'face
15115 (cond
15116 ((not (assoc tg table))
15117 (org-get-todo-face tg))
15118 ((member tg current) c-face)
15119 ((member tg inherited) i-face))))
15120 (when (equal (caar tbl) :grouptags)
15121 (org-add-props tg nil 'face 'org-tag-group))
15122 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15123 (insert "[" c "] " tg (make-string
15124 (- fwidth 4 (length tg)) ?\ ))
15125 (push (cons tg c) ntable)
15126 (when (= (cl-incf cnt) ncol)
15127 (insert "\n")
15128 (when (or ingroup intaggroup) (insert " "))
15129 (setq cnt 0)))))
15130 (setq ntable (nreverse ntable))
15131 (insert "\n")
15132 (goto-char (point-min))
15133 (unless expert (org-fit-window-to-buffer))
15134 (setq rtn
15135 (catch 'exit
15136 (while t
15137 (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
15138 (if (not groups) "no " "")
15139 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15140 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15141 (setq org-last-tag-selection-key c)
15142 (cond
15143 ((= c ?\r) (throw 'exit t))
15144 ((= c ?!)
15145 (setq groups (not groups))
15146 (goto-char (point-min))
15147 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15148 ((= c ?\C-c)
15149 (if (not expert)
15150 (org-fast-tag-show-exit
15151 (setq exit-after-next (not exit-after-next)))
15152 (setq expert nil)
15153 (delete-other-windows)
15154 (set-window-buffer (split-window-vertically) " *Org tags*")
15155 (org-switch-to-buffer-other-window " *Org tags*")
15156 (org-fit-window-to-buffer)))
15157 ((or (= c ?\C-g)
15158 (and (= c ?q) (not (rassoc c ntable))))
15159 (delete-overlay org-tags-overlay)
15160 (setq quit-flag t))
15161 ((= c ?\ )
15162 (setq current nil)
15163 (when exit-after-next (setq exit-after-next 'now)))
15164 ((= c ?\t)
15165 (condition-case nil
15166 (setq tg (completing-read
15167 "Tag: "
15168 (or buffer-tags
15169 (with-current-buffer buf
15170 (setq buffer-tags
15171 (org-get-buffer-tags))))))
15172 (quit (setq tg "")))
15173 (when (string-match "\\S-" tg)
15174 (cl-pushnew (list tg) buffer-tags :test #'equal)
15175 (if (member tg current)
15176 (setq current (delete tg current))
15177 (push tg current)))
15178 (when exit-after-next (setq exit-after-next 'now)))
15179 ((setq e (rassoc c todo-table) tg (car e))
15180 (with-current-buffer buf
15181 (save-excursion (org-todo tg)))
15182 (when exit-after-next (setq exit-after-next 'now)))
15183 ((setq e (rassoc c ntable) tg (car e))
15184 (if (member tg current)
15185 (setq current (delete tg current))
15186 (cl-loop for g in groups do
15187 (when (member tg g)
15188 (dolist (x g) (setq current (delete x current)))))
15189 (push tg current))
15190 (when exit-after-next (setq exit-after-next 'now))))
15192 ;; Create a sorted list
15193 (setq current
15194 (sort current
15195 (lambda (a b)
15196 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15197 (when (eq exit-after-next 'now) (throw 'exit t))
15198 (goto-char (point-min))
15199 (beginning-of-line 2)
15200 (delete-region (point) (point-at-eol))
15201 (org-fast-tag-insert "Current" current c-face)
15202 (org-set-current-tags-overlay current ov-prefix)
15203 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15204 (setq tg (match-string 1))
15205 (add-text-properties
15206 (match-beginning 1) (match-end 1)
15207 (list 'face
15208 (cond
15209 ((member tg current) c-face)
15210 ((member tg inherited) i-face)
15211 (t (get-text-property (match-beginning 1) 'face))))))
15212 (goto-char (point-min)))))
15213 (delete-overlay org-tags-overlay)
15214 (if rtn
15215 (mapconcat 'identity current ":")
15216 nil))))
15218 (defun org-get-tags-string ()
15219 "Get the TAGS string in the current headline."
15220 (unless (org-at-heading-p t)
15221 (user-error "Not on a heading"))
15222 (save-excursion
15223 (beginning-of-line 1)
15224 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15225 (match-string-no-properties 1)
15226 "")))
15228 (defun org-get-tags ()
15229 "Get the list of tags specified in the current headline."
15230 (org-split-string (org-get-tags-string) ":"))
15232 (defun org-get-buffer-tags ()
15233 "Get a table of all tags used in the buffer, for completion."
15234 (org-with-wide-buffer
15235 (goto-char (point-min))
15236 (let ((tag-re (concat org-outline-regexp-bol
15237 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15238 tags)
15239 (while (re-search-forward tag-re nil t)
15240 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15241 (push tag tags)))
15242 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15244 ;;;; The mapping API
15246 (defvar org-agenda-skip-comment-trees)
15247 (defvar org-agenda-skip-function)
15248 (defun org-map-entries (func &optional match scope &rest skip)
15249 "Call FUNC at each headline selected by MATCH in SCOPE.
15251 FUNC is a function or a lisp form. The function will be called without
15252 arguments, with the cursor positioned at the beginning of the headline.
15253 The return values of all calls to the function will be collected and
15254 returned as a list.
15256 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15257 does not need to preserve point. After evaluation, the cursor will be
15258 moved to the end of the line (presumably of the headline of the
15259 processed entry) and search continues from there. Under some
15260 circumstances, this may not produce the wanted results. For example,
15261 if you have removed (e.g. archived) the current (sub)tree it could
15262 mean that the next entry will be skipped entirely. In such cases, you
15263 can specify the position from where search should continue by making
15264 FUNC set the variable `org-map-continue-from' to the desired buffer
15265 position.
15267 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15268 Only headlines that are matched by this query will be considered during
15269 the iteration. When MATCH is nil or t, all headlines will be
15270 visited by the iteration.
15272 SCOPE determines the scope of this command. It can be any of:
15274 nil The current buffer, respecting the restriction if any
15275 tree The subtree started with the entry at point
15276 region The entries within the active region, if any
15277 region-start-level
15278 The entries within the active region, but only those at
15279 the same level than the first one.
15280 file The current buffer, without restriction
15281 file-with-archives
15282 The current buffer, and any archives associated with it
15283 agenda All agenda files
15284 agenda-with-archives
15285 All agenda files with any archive files associated with them
15286 \(file1 file2 ...)
15287 If this is a list, all files in the list will be scanned
15289 The remaining args are treated as settings for the skipping facilities of
15290 the scanner. The following items can be given here:
15292 archive skip trees with the archive tag
15293 comment skip trees with the COMMENT keyword
15294 function or Emacs Lisp form:
15295 will be used as value for `org-agenda-skip-function', so
15296 whenever the function returns a position, FUNC will not be
15297 called for that entry and search will continue from the
15298 position returned
15300 If your function needs to retrieve the tags including inherited tags
15301 at the *current* entry, you can use the value of the variable
15302 `org-scanner-tags' which will be much faster than getting the value
15303 with `org-get-tags-at'. If your function gets properties with
15304 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15305 to t around the call to `org-entry-properties' to get the same speedup.
15306 Note that if your function moves around to retrieve tags and properties at
15307 a *different* entry, you cannot use these techniques."
15308 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15309 (not (org-region-active-p)))
15310 (let* ((org-agenda-archives-mode nil) ; just to make sure
15311 (org-agenda-skip-archived-trees (memq 'archive skip))
15312 (org-agenda-skip-comment-trees (memq 'comment skip))
15313 (org-agenda-skip-function
15314 (car (org-delete-all '(comment archive) skip)))
15315 (org-tags-match-list-sublevels t)
15316 (start-level (eq scope 'region-start-level))
15317 matcher res
15318 org-todo-keywords-for-agenda
15319 org-done-keywords-for-agenda
15320 org-todo-keyword-alist-for-agenda
15321 org-tag-alist-for-agenda
15322 org--matcher-tags-todo-only)
15324 (cond
15325 ((eq match t) (setq matcher t))
15326 ((eq match nil) (setq matcher t))
15327 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15329 (save-excursion
15330 (save-restriction
15331 (cond ((eq scope 'tree)
15332 (org-back-to-heading t)
15333 (org-narrow-to-subtree)
15334 (setq scope nil))
15335 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15336 (org-region-active-p))
15337 ;; If needed, set start-level to a string like "2"
15338 (when start-level
15339 (save-excursion
15340 (goto-char (region-beginning))
15341 (unless (org-at-heading-p) (outline-next-heading))
15342 (setq start-level (org-current-level))))
15343 (narrow-to-region (region-beginning)
15344 (save-excursion
15345 (goto-char (region-end))
15346 (unless (and (bolp) (org-at-heading-p))
15347 (outline-next-heading))
15348 (point)))
15349 (setq scope nil)))
15351 (if (not scope)
15352 (progn
15353 (org-agenda-prepare-buffers
15354 (and buffer-file-name (list buffer-file-name)))
15355 (setq res
15356 (org-scan-tags
15357 func matcher org--matcher-tags-todo-only start-level)))
15358 ;; Get the right scope
15359 (cond
15360 ((and scope (listp scope) (symbolp (car scope)))
15361 (setq scope (eval scope)))
15362 ((eq scope 'agenda)
15363 (setq scope (org-agenda-files t)))
15364 ((eq scope 'agenda-with-archives)
15365 (setq scope (org-agenda-files t))
15366 (setq scope (org-add-archive-files scope)))
15367 ((eq scope 'file)
15368 (setq scope (and buffer-file-name (list buffer-file-name))))
15369 ((eq scope 'file-with-archives)
15370 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15371 (org-agenda-prepare-buffers scope)
15372 (dolist (file scope)
15373 (with-current-buffer (org-find-base-buffer-visiting file)
15374 (org-with-wide-buffer
15375 (goto-char (point-min))
15376 (setq res
15377 (append
15379 (org-scan-tags
15380 func matcher org--matcher-tags-todo-only)))))))))
15381 res)))
15383 ;;; Properties API
15385 (defconst org-special-properties
15386 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15387 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15388 "The special properties valid in Org mode.
15389 These are properties that are not defined in the property drawer,
15390 but in some other way.")
15392 (defconst org-default-properties
15393 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15394 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15395 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15396 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15397 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15398 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15399 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15400 "Some properties that are used by Org mode for various purposes.
15401 Being in this list makes sure that they are offered for completion.")
15403 (defun org--valid-property-p (property)
15404 "Non nil when string PROPERTY is a valid property name."
15405 (not
15406 (or (equal property "")
15407 (string-match-p "\\s-" property))))
15409 (defun org--update-property-plist (key val props)
15410 "Associate KEY to VAL in alist PROPS.
15411 Modifications are made by side-effect. Return new alist."
15412 (let* ((appending (string= (substring key -1) "+"))
15413 (key (if appending (substring key 0 -1) key))
15414 (old (assoc-string key props t)))
15415 (if (not old) (cons (cons key val) props)
15416 (setcdr old (if appending (concat (cdr old) " " val) val))
15417 props)))
15419 (defun org-get-property-block (&optional beg force)
15420 "Return the (beg . end) range of the body of the property drawer.
15421 BEG is the beginning of the current subtree, or of the part
15422 before the first headline. If it is not given, it will be found.
15423 If the drawer does not exist, create it if FORCE is non-nil, or
15424 return nil."
15425 (org-with-wide-buffer
15426 (when beg (goto-char beg))
15427 (unless (org-before-first-heading-p)
15428 (let ((beg (cond (beg)
15429 ((or (not (featurep 'org-inlinetask))
15430 (org-inlinetask-in-task-p))
15431 (org-back-to-heading t))
15432 (t (org-with-limited-levels (org-back-to-heading t))))))
15433 (forward-line)
15434 (when (looking-at-p org-planning-line-re) (forward-line))
15435 (cond ((looking-at org-property-drawer-re)
15436 (forward-line)
15437 (cons (point) (progn (goto-char (match-end 0))
15438 (line-beginning-position))))
15439 (force
15440 (goto-char beg)
15441 (org-insert-property-drawer)
15442 (let ((pos (save-excursion (search-forward ":END:")
15443 (line-beginning-position))))
15444 (cons pos pos))))))))
15446 (defun org-at-property-p ()
15447 "Non-nil when point is inside a property drawer.
15448 See `org-property-re' for match data, if applicable."
15449 (save-excursion
15450 (beginning-of-line)
15451 (and (looking-at org-property-re)
15452 (let ((property-drawer (save-match-data (org-get-property-block))))
15453 (and property-drawer
15454 (>= (point) (car property-drawer))
15455 (< (point) (cdr property-drawer)))))))
15457 (defun org-property-action ()
15458 "Do an action on properties."
15459 (interactive)
15460 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15461 (let ((c (read-char-exclusive)))
15462 (cl-case c
15463 (?s (call-interactively #'org-set-property))
15464 (?d (call-interactively #'org-delete-property))
15465 (?D (call-interactively #'org-delete-property-globally))
15466 (?c (call-interactively #'org-compute-property-at-point))
15467 (otherwise (user-error "No such property action %c" c)))))
15469 (defun org-inc-effort ()
15470 "Increment the value of the effort property in the current entry."
15471 (interactive)
15472 (org-set-effort nil t))
15474 (defvar org-clock-effort) ; Defined in org-clock.el.
15475 (defvar org-clock-current-task) ; Defined in org-clock.el.
15476 (defun org-set-effort (&optional value increment)
15477 "Set the effort property of the current entry.
15478 With numerical prefix arg, use the nth allowed value, 0 stands for the
15479 10th allowed value.
15481 When INCREMENT is non-nil, set the property to the next allowed value."
15482 (interactive "P")
15483 (when (equal value 0) (setq value 10))
15484 (let* ((completion-ignore-case t)
15485 (prop org-effort-property)
15486 (cur (org-entry-get nil prop))
15487 (allowed (org-property-get-allowed-values nil prop 'table))
15488 (existing (mapcar 'list (org-property-values prop)))
15489 (heading (nth 4 (org-heading-components)))
15491 (val (cond
15492 ((stringp value) value)
15493 ((and allowed (integerp value))
15494 (or (car (nth (1- value) allowed))
15495 (car (org-last allowed))))
15496 ((and allowed increment)
15497 (or (cl-caadr (member (list cur) allowed))
15498 (user-error "Allowed effort values are not set")))
15499 (allowed
15500 (message "Select 1-9,0, [RET%s]: %s"
15501 (if cur (concat "=" cur) "")
15502 (mapconcat 'car allowed " "))
15503 (setq rpl (read-char-exclusive))
15504 (if (equal rpl ?\r)
15506 (setq rpl (- rpl ?0))
15507 (when (equal rpl 0) (setq rpl 10))
15508 (if (and (> rpl 0) (<= rpl (length allowed)))
15509 (car (nth (1- rpl) allowed))
15510 (org-completing-read "Effort: " allowed nil))))
15512 (org-completing-read
15513 (concat "Effort" (and cur (string-match "\\S-" cur)
15514 (concat " [" cur "]"))
15515 ": ")
15516 existing nil nil "" nil cur)))))
15517 (unless (equal (org-entry-get nil prop) val)
15518 (org-entry-put nil prop val))
15519 (org-refresh-property
15520 '((effort . identity)
15521 (effort-minutes . org-duration-to-minutes))
15522 val)
15523 (when (equal heading (bound-and-true-p org-clock-current-task))
15524 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15525 (org-clock-update-mode-line))
15526 (message "%s is now %s" prop val)))
15528 (defun org-entry-properties (&optional pom which)
15529 "Get all properties of the current entry.
15531 When POM is a buffer position, get all properties from the entry
15532 there instead.
15534 This includes the TODO keyword, the tags, time strings for
15535 deadline, scheduled, and clocking, and any additional properties
15536 defined in the entry.
15538 If WHICH is nil or `all', get all properties. If WHICH is
15539 `special' or `standard', only get that subclass. If WHICH is
15540 a string, only get that property.
15542 Return value is an alist. Keys are properties, as upcased
15543 strings."
15544 (org-with-point-at pom
15545 (when (and (derived-mode-p 'org-mode)
15546 (ignore-errors (org-back-to-heading t)))
15547 (catch 'exit
15548 (let* ((beg (point))
15549 (specific (and (stringp which) (upcase which)))
15550 (which (cond ((not specific) which)
15551 ((member specific org-special-properties) 'special)
15552 (t 'standard)))
15553 props)
15554 ;; Get the special properties, like TODO and TAGS.
15555 (when (memq which '(nil all special))
15556 (when (or (not specific) (string= specific "CLOCKSUM"))
15557 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15558 (when clocksum
15559 (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
15560 props)))
15561 (when specific (throw 'exit props)))
15562 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15563 (let ((clocksumt (get-text-property (point)
15564 :org-clock-minutes-today)))
15565 (when clocksumt
15566 (push (cons "CLOCKSUM_T"
15567 (org-duration-from-minutes clocksumt))
15568 props)))
15569 (when specific (throw 'exit props)))
15570 (when (or (not specific) (string= specific "ITEM"))
15571 (let ((case-fold-search nil))
15572 (when (looking-at org-complex-heading-regexp)
15573 (push (cons "ITEM"
15574 (let ((title (match-string-no-properties 4)))
15575 (if (org-string-nw-p title)
15576 (org-remove-tabs title)
15577 "")))
15578 props)))
15579 (when specific (throw 'exit props)))
15580 (when (or (not specific) (string= specific "TODO"))
15581 (let ((case-fold-search nil))
15582 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15583 (push (cons "TODO" (match-string-no-properties 2)) props)))
15584 (when specific (throw 'exit props)))
15585 (when (or (not specific) (string= specific "PRIORITY"))
15586 (push (cons "PRIORITY"
15587 (if (looking-at org-priority-regexp)
15588 (match-string-no-properties 2)
15589 (char-to-string org-default-priority)))
15590 props)
15591 (when specific (throw 'exit props)))
15592 (when (or (not specific) (string= specific "FILE"))
15593 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15594 props)
15595 (when specific (throw 'exit props)))
15596 (when (or (not specific) (string= specific "TAGS"))
15597 (let ((value (org-string-nw-p (org-get-tags-string))))
15598 (when value (push (cons "TAGS" value) props)))
15599 (when specific (throw 'exit props)))
15600 (when (or (not specific) (string= specific "ALLTAGS"))
15601 (let ((value (org-get-tags-at)))
15602 (when value
15603 (push (cons "ALLTAGS"
15604 (format ":%s:" (mapconcat #'identity value ":")))
15605 props)))
15606 (when specific (throw 'exit props)))
15607 (when (or (not specific) (string= specific "BLOCKED"))
15608 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15609 (when specific (throw 'exit props)))
15610 (when (or (not specific)
15611 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15612 (forward-line)
15613 (when (looking-at-p org-planning-line-re)
15614 (end-of-line)
15615 (let ((bol (line-beginning-position))
15616 ;; Backward compatibility: time keywords used to
15617 ;; be configurable (before 8.3). Make sure we
15618 ;; get the correct keyword.
15619 (key-assoc `(("CLOSED" . ,org-closed-string)
15620 ("DEADLINE" . ,org-deadline-string)
15621 ("SCHEDULED" . ,org-scheduled-string))))
15622 (dolist (pair (if specific (list (assoc specific key-assoc))
15623 key-assoc))
15624 (save-excursion
15625 (when (search-backward (cdr pair) bol t)
15626 (goto-char (match-end 0))
15627 (skip-chars-forward " \t")
15628 (and (looking-at org-ts-regexp-both)
15629 (push (cons (car pair)
15630 (match-string-no-properties 0))
15631 props)))))))
15632 (when specific (throw 'exit props)))
15633 (when (or (not specific)
15634 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15635 (let ((find-ts
15636 (lambda (end ts)
15637 ;; Fix next time-stamp before END. TS is the
15638 ;; list of time-stamps found so far.
15639 (let ((ts ts)
15640 (regexp (cond
15641 ((string= specific "TIMESTAMP")
15642 org-ts-regexp)
15643 ((string= specific "TIMESTAMP_IA")
15644 org-ts-regexp-inactive)
15645 ((assoc "TIMESTAMP_IA" ts)
15646 org-ts-regexp)
15647 ((assoc "TIMESTAMP" ts)
15648 org-ts-regexp-inactive)
15649 (t org-ts-regexp-both))))
15650 (catch 'next
15651 (while (re-search-forward regexp end t)
15652 (backward-char)
15653 (let ((object (org-element-context)))
15654 ;; Accept to match timestamps in node
15655 ;; properties, too.
15656 (when (memq (org-element-type object)
15657 '(node-property timestamp))
15658 (let ((type
15659 (org-element-property :type object)))
15660 (cond
15661 ((and (memq type '(active active-range))
15662 (not (equal specific "TIMESTAMP_IA")))
15663 (unless (assoc "TIMESTAMP" ts)
15664 (push (cons "TIMESTAMP"
15665 (org-element-property
15666 :raw-value object))
15668 (when specific (throw 'exit ts))))
15669 ((and (memq type '(inactive inactive-range))
15670 (not (string= specific "TIMESTAMP")))
15671 (unless (assoc "TIMESTAMP_IA" ts)
15672 (push (cons "TIMESTAMP_IA"
15673 (org-element-property
15674 :raw-value object))
15676 (when specific (throw 'exit ts))))))
15677 ;; Both timestamp types are found,
15678 ;; move to next part.
15679 (when (= (length ts) 2) (throw 'next ts)))))
15680 ts)))))
15681 (goto-char beg)
15682 ;; First look for timestamps within headline.
15683 (let ((ts (funcall find-ts (line-end-position) nil)))
15684 (if (= (length ts) 2) (setq props (nconc ts props))
15685 ;; Then find timestamps in the section, skipping
15686 ;; planning line.
15687 (let ((end (save-excursion (outline-next-heading))))
15688 (forward-line)
15689 (when (looking-at-p org-planning-line-re) (forward-line))
15690 (setq props (nconc (funcall find-ts end ts) props))))))))
15691 ;; Get the standard properties, like :PROP:.
15692 (when (memq which '(nil all standard))
15693 ;; If we are looking after a specific property, delegate
15694 ;; to `org-entry-get', which is faster. However, make an
15695 ;; exception for "CATEGORY", since it can be also set
15696 ;; through keywords (i.e. #+CATEGORY).
15697 (if (and specific (not (equal specific "CATEGORY")))
15698 (let ((value (org-entry-get beg specific nil t)))
15699 (throw 'exit (and value (list (cons specific value)))))
15700 (let ((range (org-get-property-block beg)))
15701 (when range
15702 (let ((end (cdr range)) seen-base)
15703 (goto-char (car range))
15704 ;; Unlike to `org--update-property-plist', we
15705 ;; handle the case where base values is found
15706 ;; after its extension. We also forbid standard
15707 ;; properties to be named as special properties.
15708 (while (re-search-forward org-property-re end t)
15709 (let* ((key (upcase (match-string-no-properties 2)))
15710 (extendp (string-match-p "\\+\\'" key))
15711 (key-base (if extendp (substring key 0 -1) key))
15712 (value (match-string-no-properties 3)))
15713 (cond
15714 ((member-ignore-case key-base org-special-properties))
15715 (extendp
15716 (setq props
15717 (org--update-property-plist key value props)))
15718 ((member key seen-base))
15719 (t (push key seen-base)
15720 (let ((p (assoc-string key props t)))
15721 (if p (setcdr p (concat value " " (cdr p)))
15722 (push (cons key value) props))))))))))))
15723 (unless (assoc "CATEGORY" props)
15724 (push (cons "CATEGORY" (org-get-category beg)) props)
15725 (when (string= specific "CATEGORY") (throw 'exit props)))
15726 ;; Return value.
15727 props)))))
15729 (defun org--property-local-values (property literal-nil)
15730 "Return value for PROPERTY in current entry.
15731 Value is a list whose car is the base value for PROPERTY and cdr
15732 a list of accumulated values. Return nil if neither is found in
15733 the entry. Also return nil when PROPERTY is set to \"nil\",
15734 unless LITERAL-NIL is non-nil."
15735 (let ((range (org-get-property-block)))
15736 (when range
15737 (goto-char (car range))
15738 (let* ((case-fold-search t)
15739 (end (cdr range))
15740 (value
15741 ;; Base value.
15742 (save-excursion
15743 (let ((v (and (re-search-forward
15744 (org-re-property property nil t) end t)
15745 (match-string-no-properties 3))))
15746 (list (if literal-nil v (org-not-nil v)))))))
15747 ;; Find additional values.
15748 (let* ((property+ (org-re-property (concat property "+") nil t)))
15749 (while (re-search-forward property+ end t)
15750 (push (match-string-no-properties 3) value)))
15751 ;; Return final values.
15752 (and (not (equal value '(nil))) (nreverse value))))))
15754 (defun org--property-global-value (property literal-nil)
15755 "Return value for PROPERTY in current buffer.
15756 Return value is a string. Return nil if property is not set
15757 globally. Also return nil when PROPERTY is set to \"nil\",
15758 unless LITERAL-NIL is non-nil."
15759 (let ((global
15760 (cdr (or (assoc-string property org-file-properties t)
15761 (assoc-string property org-global-properties t)
15762 (assoc-string property org-global-properties-fixed t)))))
15763 (if literal-nil global (org-not-nil global))))
15765 (defun org-entry-get (pom property &optional inherit literal-nil)
15766 "Get value of PROPERTY for entry or content at point-or-marker POM.
15768 If INHERIT is non-nil and the entry does not have the property,
15769 then also check higher levels of the hierarchy. If INHERIT is
15770 the symbol `selective', use inheritance only if the setting in
15771 `org-use-property-inheritance' selects PROPERTY for inheritance.
15773 If the property is present but empty, the return value is the
15774 empty string. If the property is not present at all, nil is
15775 returned. In any other case, return the value as a string.
15776 Search is case-insensitive.
15778 If LITERAL-NIL is set, return the string value \"nil\" as
15779 a string, do not interpret it as the list atom nil. This is used
15780 for inheritance when a \"nil\" value can supersede a non-nil
15781 value higher up the hierarchy."
15782 (org-with-point-at pom
15783 (cond
15784 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15785 ;; We need a special property. Use `org-entry-properties' to
15786 ;; retrieve it, but specify the wanted property.
15787 (cdr (assoc-string property (org-entry-properties nil property))))
15788 ((and inherit
15789 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15790 (org-entry-get-with-inheritance property literal-nil))
15792 (let* ((local (org--property-local-values property literal-nil))
15793 (value (and local (mapconcat #'identity (delq nil local) " "))))
15794 (if literal-nil value (org-not-nil value)))))))
15796 (defun org-property-or-variable-value (var &optional inherit)
15797 "Check if there is a property fixing the value of VAR.
15798 If yes, return this value. If not, return the current value of the variable."
15799 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15800 (if (and prop (stringp prop) (string-match "\\S-" prop))
15801 (read prop)
15802 (symbol-value var))))
15804 (defun org-entry-delete (pom property)
15805 "Delete PROPERTY from entry at point-or-marker POM.
15806 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15807 non-nil when a property was removed."
15808 (org-with-point-at pom
15809 (pcase (org-get-property-block)
15810 (`(,begin . ,origin)
15811 (let* ((end (copy-marker origin))
15812 (re (org-re-property
15813 (concat (regexp-quote property) "\\+?") t t)))
15814 (goto-char begin)
15815 (while (re-search-forward re end t)
15816 (delete-region (match-beginning 0) (line-beginning-position 2)))
15817 ;; If drawer is empty, remove it altogether.
15818 (when (= begin end)
15819 (delete-region (line-beginning-position 0)
15820 (line-beginning-position 2)))
15821 ;; Return non-nil if some property was removed.
15822 (prog1 (/= end origin) (set-marker end nil))))
15823 (_ nil))))
15825 ;; Multi-values properties are properties that contain multiple values
15826 ;; These values are assumed to be single words, separated by whitespace.
15827 (defun org-entry-add-to-multivalued-property (pom property value)
15828 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15829 (let* ((old (org-entry-get pom property))
15830 (values (and old (split-string old))))
15831 (setq value (org-entry-protect-space value))
15832 (unless (member value values)
15833 (setq values (append values (list value)))
15834 (org-entry-put pom property (mapconcat #'identity values " ")))))
15836 (defun org-entry-remove-from-multivalued-property (pom property value)
15837 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15838 (let* ((old (org-entry-get pom property))
15839 (values (and old (split-string old))))
15840 (setq value (org-entry-protect-space value))
15841 (when (member value values)
15842 (setq values (delete value values))
15843 (org-entry-put pom property (mapconcat #'identity values " ")))))
15845 (defun org-entry-member-in-multivalued-property (pom property value)
15846 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15847 (let* ((old (org-entry-get pom property))
15848 (values (and old (split-string old))))
15849 (setq value (org-entry-protect-space value))
15850 (member value values)))
15852 (defun org-entry-get-multivalued-property (pom property)
15853 "Return a list of values in a multivalued property."
15854 (let* ((value (org-entry-get pom property))
15855 (values (and value (split-string value))))
15856 (mapcar #'org-entry-restore-space values)))
15858 (defun org-entry-put-multivalued-property (pom property &rest values)
15859 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15860 VALUES should be a list of strings. Spaces will be protected."
15861 (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
15862 (let* ((value (org-entry-get pom property))
15863 (values (and value (split-string value))))
15864 (mapcar #'org-entry-restore-space values)))
15866 (defun org-entry-protect-space (s)
15867 "Protect spaces and newline in string S."
15868 (while (string-match " " s)
15869 (setq s (replace-match "%20" t t s)))
15870 (while (string-match "\n" s)
15871 (setq s (replace-match "%0A" t t s)))
15874 (defun org-entry-restore-space (s)
15875 "Restore spaces and newline in string S."
15876 (while (string-match "%20" s)
15877 (setq s (replace-match " " t t s)))
15878 (while (string-match "%0A" s)
15879 (setq s (replace-match "\n" t t s)))
15882 (defvar org-entry-property-inherited-from (make-marker)
15883 "Marker pointing to the entry from where a property was inherited.
15884 Each call to `org-entry-get-with-inheritance' will set this marker to the
15885 location of the entry where the inheritance search matched. If there was
15886 no match, the marker will point nowhere.
15887 Note that also `org-entry-get' calls this function, if the INHERIT flag
15888 is set.")
15890 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15891 "Get PROPERTY of entry or content at point, search higher levels if needed.
15892 The search will stop at the first ancestor which has the property defined.
15893 If the value found is \"nil\", return nil to show that the property
15894 should be considered as undefined (this is the meaning of nil here).
15895 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15896 (move-marker org-entry-property-inherited-from nil)
15897 (org-with-wide-buffer
15898 (let (value)
15899 (catch 'exit
15900 (while t
15901 (let ((v (org--property-local-values property literal-nil)))
15902 (when v
15903 (setq value
15904 (concat (mapconcat #'identity (delq nil v) " ")
15905 (and value " ")
15906 value)))
15907 (cond
15908 ((car v)
15909 (org-back-to-heading t)
15910 (move-marker org-entry-property-inherited-from (point))
15911 (throw 'exit nil))
15912 ((org-up-heading-safe))
15914 (let ((global (org--property-global-value property literal-nil)))
15915 (cond ((not global))
15916 (value (setq value (concat global " " value)))
15917 (t (setq value global))))
15918 (throw 'exit nil))))))
15919 (if literal-nil value (org-not-nil value)))))
15921 (defvar org-property-changed-functions nil
15922 "Hook called when the value of a property has changed.
15923 Each hook function should accept two arguments, the name of the property
15924 and the new value.")
15926 (defun org-entry-put (pom property value)
15927 "Set PROPERTY to VALUE for entry at point-or-marker POM.
15929 If the value is nil, it is converted to the empty string. If it
15930 is not a string, an error is raised. Also raise an error on
15931 invalid property names.
15933 PROPERTY can be any regular property (see
15934 `org-special-properties'). It can also be \"TODO\",
15935 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
15937 For the last two properties, VALUE may have any of the special
15938 values \"earlier\" and \"later\". The function then increases or
15939 decreases scheduled or deadline date by one day."
15940 (cond ((null value) (setq value ""))
15941 ((not (stringp value)) (error "Properties values should be strings"))
15942 ((not (org--valid-property-p property))
15943 (user-error "Invalid property name: \"%s\"" property)))
15944 (org-with-point-at pom
15945 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
15946 (org-back-to-heading t)
15947 (org-with-limited-levels (org-back-to-heading t)))
15948 (let ((beg (point)))
15949 (cond
15950 ((equal property "TODO")
15951 (cond ((not (org-string-nw-p value)) (setq value 'none))
15952 ((not (member value org-todo-keywords-1))
15953 (user-error "\"%s\" is not a valid TODO state" value)))
15954 (org-todo value)
15955 (org-set-tags nil 'align))
15956 ((equal property "PRIORITY")
15957 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
15958 (org-set-tags nil 'align))
15959 ((equal property "SCHEDULED")
15960 (forward-line)
15961 (if (and (looking-at-p org-planning-line-re)
15962 (re-search-forward
15963 org-scheduled-time-regexp (line-end-position) t))
15964 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15965 ((string= value "later") (org-timestamp-change 1 'day))
15966 ((string= value "") (org-schedule '(4)))
15967 (t (org-schedule nil value)))
15968 (if (member value '("earlier" "later" ""))
15969 (call-interactively #'org-schedule)
15970 (org-schedule nil value))))
15971 ((equal property "DEADLINE")
15972 (forward-line)
15973 (if (and (looking-at-p org-planning-line-re)
15974 (re-search-forward
15975 org-deadline-time-regexp (line-end-position) t))
15976 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
15977 ((string= value "later") (org-timestamp-change 1 'day))
15978 ((string= value "") (org-deadline '(4)))
15979 (t (org-deadline nil value)))
15980 (if (member value '("earlier" "later" ""))
15981 (call-interactively #'org-deadline)
15982 (org-deadline nil value))))
15983 ((member property org-special-properties)
15984 (error "The %s property cannot be set with `org-entry-put'" property))
15986 (let* ((range (org-get-property-block beg 'force))
15987 (end (cdr range))
15988 (case-fold-search t))
15989 (goto-char (car range))
15990 (if (re-search-forward (org-re-property property nil t) end t)
15991 (progn (delete-region (match-beginning 0) (match-end 0))
15992 (goto-char (match-beginning 0)))
15993 (goto-char end)
15994 (insert "\n")
15995 (backward-char))
15996 (insert ":" property ":")
15997 (when value (insert " " value))
15998 (org-indent-line)))))
15999 (run-hook-with-args 'org-property-changed-functions property value)))
16001 (defun org-buffer-property-keys (&optional specials defaults columns)
16002 "Get all property keys in the current buffer.
16004 When SPECIALS is non-nil, also list the special properties that
16005 reflect things like tags and TODO state.
16007 When DEFAULTS is non-nil, also include properties that has
16008 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16009 DESCRIPTION, LOCATION, and LOGGING and others.
16011 When COLUMNS in non-nil, also include property names given in
16012 COLUMN formats in the current buffer."
16013 (let ((case-fold-search t)
16014 (props (append
16015 (and specials org-special-properties)
16016 (and defaults (cons org-effort-property org-default-properties))
16017 nil)))
16018 (org-with-wide-buffer
16019 (goto-char (point-min))
16020 (while (re-search-forward org-property-start-re nil t)
16021 (catch :skip
16022 (let ((range (org-get-property-block)))
16023 (unless range (throw :skip nil))
16024 (goto-char (car range))
16025 (let ((begin (car range))
16026 (end (cdr range)))
16027 ;; Make sure that found property block is not located
16028 ;; before current point, as it would generate an infloop.
16029 ;; It can happen, for example, in the following
16030 ;; situation:
16032 ;; * Headline
16033 ;; :PROPERTIES:
16034 ;; ...
16035 ;; :END:
16036 ;; *************** Inlinetask
16037 ;; #+BEGIN_EXAMPLE
16038 ;; :PROPERTIES:
16039 ;; #+END_EXAMPLE
16041 (if (< begin (point)) (throw :skip nil) (goto-char begin))
16042 (while (< (point) end)
16043 (let ((p (progn (looking-at org-property-re)
16044 (match-string-no-properties 2))))
16045 ;; Only add true property name, not extension symbol.
16046 (push (if (not (string-match-p "\\+\\'" p)) p
16047 (substring p 0 -1))
16048 props))
16049 (forward-line))))
16050 (outline-next-heading)))
16051 (when columns
16052 (goto-char (point-min))
16053 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16054 (let ((element (org-element-at-point)))
16055 (when (memq (org-element-type element) '(keyword node-property))
16056 (let ((value (org-element-property :value element))
16057 (start 0))
16058 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16059 (setq start (match-end 0))
16060 (let ((p (match-string-no-properties 1 value)))
16061 (unless (member-ignore-case p org-special-properties)
16062 (push p props))))))))))
16063 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16065 (defun org-property-values (key)
16066 "List all non-nil values of property KEY in current buffer."
16067 (org-with-wide-buffer
16068 (goto-char (point-min))
16069 (let ((case-fold-search t)
16070 (re (org-re-property key))
16071 values)
16072 (while (re-search-forward re nil t)
16073 (push (org-entry-get (point) key) values))
16074 (delete-dups values))))
16076 (defun org-insert-property-drawer ()
16077 "Insert a property drawer into the current entry."
16078 (org-with-wide-buffer
16079 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16080 (org-back-to-heading t)
16081 (org-with-limited-levels (org-back-to-heading t)))
16082 (forward-line)
16083 (when (looking-at-p org-planning-line-re) (forward-line))
16084 (unless (looking-at-p org-property-drawer-re)
16085 ;; Make sure we start editing a line from current entry, not from
16086 ;; next one. It prevents extending text properties or overlays
16087 ;; belonging to the latter.
16088 (when (bolp) (backward-char))
16089 (let ((begin (1+ (point)))
16090 (inhibit-read-only t))
16091 (insert "\n:PROPERTIES:\n:END:")
16092 (when (eobp) (insert "\n"))
16093 (org-indent-region begin (point))))))
16095 (defun org-insert-drawer (&optional arg drawer)
16096 "Insert a drawer at point.
16098 When optional argument ARG is non-nil, insert a property drawer.
16100 Optional argument DRAWER, when non-nil, is a string representing
16101 drawer's name. Otherwise, the user is prompted for a name.
16103 If a region is active, insert the drawer around that region
16104 instead.
16106 Point is left between drawer's boundaries."
16107 (interactive "P")
16108 (let* ((drawer (if arg "PROPERTIES"
16109 (or drawer (read-from-minibuffer "Drawer: ")))))
16110 (cond
16111 ;; With C-u, fall back on `org-insert-property-drawer'
16112 (arg (org-insert-property-drawer))
16113 ;; Check validity of suggested drawer's name.
16114 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16115 (user-error "Invalid drawer name"))
16116 ;; With an active region, insert a drawer at point.
16117 ((not (org-region-active-p))
16118 (progn
16119 (unless (bolp) (insert "\n"))
16120 (insert (format ":%s:\n\n:END:\n" drawer))
16121 (forward-line -2)))
16122 ;; Otherwise, insert the drawer at point
16124 (let ((rbeg (region-beginning))
16125 (rend (copy-marker (region-end))))
16126 (unwind-protect
16127 (progn
16128 (goto-char rbeg)
16129 (beginning-of-line)
16130 (when (save-excursion
16131 (re-search-forward org-outline-regexp-bol rend t))
16132 (user-error "Drawers cannot contain headlines"))
16133 ;; Position point at the beginning of the first
16134 ;; non-blank line in region. Insert drawer's opening
16135 ;; there, then indent it.
16136 (org-skip-whitespace)
16137 (beginning-of-line)
16138 (insert ":" drawer ":\n")
16139 (forward-line -1)
16140 (indent-for-tab-command)
16141 ;; Move point to the beginning of the first blank line
16142 ;; after the last non-blank line in region. Insert
16143 ;; drawer's closing, then indent it.
16144 (goto-char rend)
16145 (skip-chars-backward " \r\t\n")
16146 (insert "\n:END:")
16147 (deactivate-mark t)
16148 (indent-for-tab-command)
16149 (unless (eolp) (insert "\n")))
16150 ;; Clear marker, whatever the outcome of insertion is.
16151 (set-marker rend nil)))))))
16153 (defvar org-property-set-functions-alist nil
16154 "Property set function alist.
16155 Each entry should have the following format:
16157 (PROPERTY . READ-FUNCTION)
16159 The read function will be called with the same argument as
16160 `org-completing-read'.")
16162 (defun org-set-property-function (property)
16163 "Get the function that should be used to set PROPERTY.
16164 This is computed according to `org-property-set-functions-alist'."
16165 (or (cdr (assoc property org-property-set-functions-alist))
16166 'org-completing-read))
16168 (defun org-read-property-value (property)
16169 "Read PROPERTY value from user."
16170 (let* ((completion-ignore-case t)
16171 (allowed (org-property-get-allowed-values nil property 'table))
16172 (cur (org-entry-get nil property))
16173 (prompt (concat property " value"
16174 (if (and cur (string-match "\\S-" cur))
16175 (concat " [" cur "]") "") ": "))
16176 (set-function (org-set-property-function property))
16177 (val (if allowed
16178 (funcall set-function prompt allowed nil
16179 (not (get-text-property 0 'org-unrestricted
16180 (caar allowed))))
16181 (funcall set-function prompt
16182 (mapcar 'list (org-property-values property))
16183 nil nil "" nil cur))))
16184 (org-trim val)))
16186 (defvar org-last-set-property nil)
16187 (defvar org-last-set-property-value nil)
16188 (defun org-read-property-name ()
16189 "Read a property name."
16190 (let ((completion-ignore-case t)
16191 (default-prop (or (and (org-at-property-p)
16192 (match-string-no-properties 2))
16193 org-last-set-property)))
16194 (org-completing-read
16195 (concat "Property"
16196 (if default-prop (concat " [" default-prop "]") "")
16197 ": ")
16198 (mapcar #'list (org-buffer-property-keys nil t t))
16199 nil nil nil nil default-prop)))
16201 (defun org-set-property-and-value (use-last)
16202 "Allow to set [PROPERTY]: [value] direction from prompt.
16203 When use-default, don't even ask, just use the last
16204 \"[PROPERTY]: [value]\" string from the history."
16205 (interactive "P")
16206 (let* ((completion-ignore-case t)
16207 (pv (or (and use-last org-last-set-property-value)
16208 (org-completing-read
16209 "Enter a \"[Property]: [value]\" pair: "
16210 nil nil nil nil nil
16211 org-last-set-property-value)))
16212 prop val)
16213 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16214 (setq prop (match-string 1 pv)
16215 val (match-string 2 pv))
16216 (org-set-property prop val))))
16218 (defun org-set-property (property value)
16219 "In the current entry, set PROPERTY to VALUE.
16221 When called interactively, this will prompt for a property name, offering
16222 completion on existing and default properties. And then it will prompt
16223 for a value, offering completion either on allowed values (via an inherited
16224 xxx_ALL property) or on existing values in other instances of this property
16225 in the current file.
16227 Throw an error when trying to set a property with an invalid name."
16228 (interactive (list nil nil))
16229 (let ((property (or property (org-read-property-name))))
16230 ;; `org-entry-put' also makes the following check, but this one
16231 ;; avoids polluting `org-last-set-property' and
16232 ;; `org-last-set-property-value' needlessly.
16233 (unless (org--valid-property-p property)
16234 (user-error "Invalid property name: \"%s\"" property))
16235 (let ((value (or value (org-read-property-value property)))
16236 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16237 (setq org-last-set-property property)
16238 (setq org-last-set-property-value (concat property ": " value))
16239 ;; Possibly postprocess the inserted value:
16240 (when fn (setq value (funcall fn value)))
16241 (unless (equal (org-entry-get nil property) value)
16242 (org-entry-put nil property value)))))
16244 (defun org-find-property (property &optional value)
16245 "Find first entry in buffer that sets PROPERTY.
16247 When optional argument VALUE is non-nil, only consider an entry
16248 if it contains PROPERTY set to this value. If PROPERTY should be
16249 explicitly set to nil, use string \"nil\" for VALUE.
16251 Return position where the entry begins, or nil if there is no
16252 such entry. If narrowing is in effect, only search the visible
16253 part of the buffer."
16254 (save-excursion
16255 (goto-char (point-min))
16256 (let ((case-fold-search t)
16257 (re (org-re-property property nil (not value) value)))
16258 (catch 'exit
16259 (while (re-search-forward re nil t)
16260 (when (if value (org-at-property-p)
16261 (org-entry-get (point) property nil t))
16262 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16264 (defun org-delete-property (property)
16265 "In the current entry, delete PROPERTY."
16266 (interactive
16267 (let* ((completion-ignore-case t)
16268 (cat (org-entry-get (point) "CATEGORY"))
16269 (props0 (org-entry-properties nil 'standard))
16270 (props (if cat props0
16271 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16272 (prop (if (< 1 (length props))
16273 (completing-read "Property: " props nil t)
16274 (caar props))))
16275 (list prop)))
16276 (if (not property)
16277 (message "No property to delete in this entry")
16278 (org-entry-delete nil property)
16279 (message "Property \"%s\" deleted" property)))
16281 (defun org-delete-property-globally (property)
16282 "Remove PROPERTY globally, from all entries.
16283 This function ignores narrowing, if any."
16284 (interactive
16285 (let* ((completion-ignore-case t)
16286 (prop (completing-read
16287 "Globally remove property: "
16288 (mapcar #'list (org-buffer-property-keys)))))
16289 (list prop)))
16290 (org-with-wide-buffer
16291 (goto-char (point-min))
16292 (let ((count 0)
16293 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16294 (while (re-search-forward re nil t)
16295 (when (org-entry-delete (point) property) (cl-incf count)))
16296 (message "Property \"%s\" removed from %d entries" property count))))
16298 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16300 (defun org-compute-property-at-point ()
16301 "Compute the property at point.
16302 This looks for an enclosing column format, extracts the operator and
16303 then applies it to the property in the column format's scope."
16304 (interactive)
16305 (unless (org-at-property-p)
16306 (user-error "Not at a property"))
16307 (let ((prop (match-string-no-properties 2)))
16308 (org-columns-get-format-and-top-level)
16309 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16310 (user-error "No operator defined for property %s" prop))
16311 (org-columns-compute prop)))
16313 (defvar org-property-allowed-value-functions nil
16314 "Hook for functions supplying allowed values for a specific property.
16315 The functions must take a single argument, the name of the property, and
16316 return a flat list of allowed values. If \":ETC\" is one of
16317 the values, this means that these values are intended as defaults for
16318 completion, but that other values should be allowed too.
16319 The functions must return nil if they are not responsible for this
16320 property.")
16322 (defun org-property-get-allowed-values (pom property &optional table)
16323 "Get allowed values for the property PROPERTY.
16324 When TABLE is non-nil, return an alist that can directly be used for
16325 completion."
16326 (let (vals)
16327 (cond
16328 ((equal property "TODO")
16329 (setq vals (org-with-point-at pom
16330 (append org-todo-keywords-1 '("")))))
16331 ((equal property "PRIORITY")
16332 (let ((n org-lowest-priority))
16333 (while (>= n org-highest-priority)
16334 (push (char-to-string n) vals)
16335 (setq n (1- n)))))
16336 ((equal property "CATEGORY"))
16337 ((member property org-special-properties))
16338 ((setq vals (run-hook-with-args-until-success
16339 'org-property-allowed-value-functions property)))
16341 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16342 (when (and vals (string-match "\\S-" vals))
16343 (setq vals (car (read-from-string (concat "(" vals ")"))))
16344 (setq vals (mapcar (lambda (x)
16345 (cond ((stringp x) x)
16346 ((numberp x) (number-to-string x))
16347 ((symbolp x) (symbol-name x))
16348 (t "???")))
16349 vals)))))
16350 (when (member ":ETC" vals)
16351 (setq vals (remove ":ETC" vals))
16352 (org-add-props (car vals) '(org-unrestricted t)))
16353 (if table (mapcar 'list vals) vals)))
16355 (defun org-property-previous-allowed-value (&optional _previous)
16356 "Switch to the next allowed value for this property."
16357 (interactive)
16358 (org-property-next-allowed-value t))
16360 (defun org-property-next-allowed-value (&optional previous)
16361 "Switch to the next allowed value for this property."
16362 (interactive)
16363 (unless (org-at-property-p)
16364 (user-error "Not at a property"))
16365 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16366 (key (match-string 2))
16367 (value (match-string 3))
16368 (allowed (or (org-property-get-allowed-values (point) key)
16369 (and (member value '("[ ]" "[-]" "[X]"))
16370 '("[ ]" "[X]"))))
16371 (heading (save-match-data (nth 4 (org-heading-components))))
16372 nval)
16373 (unless allowed
16374 (user-error "Allowed values for this property have not been defined"))
16375 (when previous (setq allowed (reverse allowed)))
16376 (when (member value allowed)
16377 (setq nval (car (cdr (member value allowed)))))
16378 (setq nval (or nval (car allowed)))
16379 (when (equal nval value)
16380 (user-error "Only one allowed value for this property"))
16381 (org-at-property-p)
16382 (replace-match (concat " :" key ": " nval) t t)
16383 (org-indent-line)
16384 (beginning-of-line 1)
16385 (skip-chars-forward " \t")
16386 (when (equal prop org-effort-property)
16387 (org-refresh-property
16388 '((effort . identity)
16389 (effort-minutes . org-duration-to-minutes))
16390 nval)
16391 (when (string= org-clock-current-task heading)
16392 (setq org-clock-effort nval)
16393 (org-clock-update-mode-line)))
16394 (run-hook-with-args 'org-property-changed-functions key nval)))
16396 (defun org-find-olp (path &optional this-buffer)
16397 "Return a marker pointing to the entry at outline path OLP.
16398 If anything goes wrong, throw an error.
16399 You can wrap this call to catch the error like this:
16401 (condition-case msg
16402 (org-mobile-locate-entry (match-string 4))
16403 (error (nth 1 msg)))
16405 The return value will then be either a string with the error message,
16406 or a marker if everything is OK.
16408 If THIS-BUFFER is set, the outline path does not contain a file,
16409 only headings."
16410 (let* ((file (if this-buffer buffer-file-name (pop path)))
16411 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16412 (level 1)
16413 (lmin 1)
16414 (lmax 1)
16415 end found flevel)
16416 (unless buffer (error "File not found :%s" file))
16417 (with-current-buffer buffer
16418 (unless (derived-mode-p 'org-mode)
16419 (error "Buffer %s needs to be in Org mode" buffer))
16420 (org-with-wide-buffer
16421 (goto-char (point-min))
16422 (dolist (heading path)
16423 (let ((re (format org-complex-heading-regexp-format
16424 (regexp-quote heading)))
16425 (cnt 0))
16426 (while (re-search-forward re end t)
16427 (setq level (- (match-end 1) (match-beginning 1)))
16428 (when (and (>= level lmin) (<= level lmax))
16429 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16430 (when (= cnt 0)
16431 (error "Heading not found on level %d: %s" lmax heading))
16432 (when (> cnt 1)
16433 (error "Heading not unique on level %d: %s" lmax heading))
16434 (goto-char found)
16435 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16436 (setq end (save-excursion (org-end-of-subtree t t)))))
16437 (when (org-at-heading-p)
16438 (point-marker))))))
16440 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16441 "Find node HEADING in BUFFER.
16442 Return a marker to the heading if it was found, or nil if not.
16443 If POS-ONLY is set, return just the position instead of a marker.
16445 The heading text must match exact, but it may have a TODO keyword,
16446 a priority cookie and tags in the standard locations."
16447 (with-current-buffer (or buffer (current-buffer))
16448 (org-with-wide-buffer
16449 (goto-char (point-min))
16450 (let (case-fold-search)
16451 (when (re-search-forward
16452 (format org-complex-heading-regexp-format
16453 (regexp-quote heading)) nil t)
16454 (if pos-only
16455 (match-beginning 0)
16456 (move-marker (make-marker) (match-beginning 0))))))))
16458 (defun org-find-exact-heading-in-directory (heading &optional dir)
16459 "Find Org node headline HEADING in all .org files in directory DIR.
16460 When the target headline is found, return a marker to this location."
16461 (let ((files (directory-files (or dir default-directory)
16462 t "\\`[^.#].*\\.org\\'"))
16463 visiting m buffer)
16464 (catch 'found
16465 (dolist (file files)
16466 (message "trying %s" file)
16467 (setq visiting (org-find-base-buffer-visiting file))
16468 (setq buffer (or visiting (find-file-noselect file)))
16469 (setq m (org-find-exact-headline-in-buffer
16470 heading buffer))
16471 (when (and (not m) (not visiting)) (kill-buffer buffer))
16472 (and m (throw 'found m))))))
16474 (defun org-find-entry-with-id (ident)
16475 "Locate the entry that contains the ID property with exact value IDENT.
16476 IDENT can be a string, a symbol or a number, this function will search for
16477 the string representation of it.
16478 Return the position where this entry starts, or nil if there is no such entry."
16479 (interactive "sID: ")
16480 (let ((id (cond
16481 ((stringp ident) ident)
16482 ((symbolp ident) (symbol-name ident))
16483 ((numberp ident) (number-to-string ident))
16484 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16485 (org-with-wide-buffer (org-find-property "ID" id))))
16487 ;;;; Timestamps
16489 (defvar org-last-changed-timestamp nil)
16490 (defvar org-last-inserted-timestamp nil
16491 "The last time stamp inserted with `org-insert-time-stamp'.")
16493 (defun org-time-stamp (arg &optional inactive)
16494 "Prompt for a date/time and insert a time stamp.
16496 If the user specifies a time like HH:MM or if this command is
16497 called with at least one prefix argument, the time stamp contains
16498 the date and the time. Otherwise, only the date is included.
16500 All parts of a date not specified by the user are filled in from
16501 the timestamp at point, if any, or the current date/time
16502 otherwise.
16504 If there is already a timestamp at the cursor, it is replaced.
16506 With two universal prefix arguments, insert an active timestamp
16507 with the current time without prompting the user.
16509 When called from lisp, the timestamp is inactive if INACTIVE is
16510 non-nil."
16511 (interactive "P")
16512 (let* ((ts (cond
16513 ((org-at-date-range-p t)
16514 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16515 ((org-at-timestamp-p 'lax) (match-string 0))))
16516 ;; Default time is either the timestamp at point or today.
16517 ;; When entering a range, only the range start is considered.
16518 (default-time (if (not ts) (current-time)
16519 (apply #'encode-time (org-parse-time-string ts))))
16520 (default-input (and ts (org-get-compact-tod ts)))
16521 (repeater (and ts
16522 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16523 (match-string 0 ts)))
16524 org-time-was-given
16525 org-end-time-was-given
16526 (time
16527 (and (if (equal arg '(16)) (current-time)
16528 ;; Preserve `this-command' and `last-command'.
16529 (let ((this-command this-command)
16530 (last-command last-command))
16531 (org-read-date
16532 arg 'totime nil nil default-time default-input
16533 inactive))))))
16534 (cond
16535 ((and ts
16536 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16537 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16538 (insert "--")
16539 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16541 ;; Make sure we're on a timestamp. When in the middle of a date
16542 ;; range, move arbitrarily to range end.
16543 (unless (org-at-timestamp-p 'lax)
16544 (skip-chars-forward "-")
16545 (org-at-timestamp-p 'lax))
16546 (replace-match "")
16547 (setq org-last-changed-timestamp
16548 (org-insert-time-stamp
16549 time (or org-time-was-given arg)
16550 inactive nil nil (list org-end-time-was-given)))
16551 (when repeater
16552 (backward-char)
16553 (insert " " repeater)
16554 (setq org-last-changed-timestamp
16555 (concat (substring org-last-inserted-timestamp 0 -1)
16556 " " repeater ">")))
16557 (message "Timestamp updated"))
16558 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16559 (t (org-insert-time-stamp
16560 time (or org-time-was-given arg) inactive nil nil
16561 (list org-end-time-was-given))))))
16563 ;; FIXME: can we use this for something else, like computing time differences?
16564 (defun org-get-compact-tod (s)
16565 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16566 (let* ((t1 (match-string 1 s))
16567 (h1 (string-to-number (match-string 2 s)))
16568 (m1 (string-to-number (match-string 3 s)))
16569 (t2 (and (match-end 4) (match-string 5 s)))
16570 (h2 (and t2 (string-to-number (match-string 6 s))))
16571 (m2 (and t2 (string-to-number (match-string 7 s))))
16572 dh dm)
16573 (if (not t2)
16575 (setq dh (- h2 h1) dm (- m2 m1))
16576 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16577 (concat t1 "+" (number-to-string dh)
16578 (and (/= 0 dm) (format ":%02d" dm)))))))
16580 (defun org-time-stamp-inactive (&optional arg)
16581 "Insert an inactive time stamp.
16582 An inactive time stamp is enclosed in square brackets instead of angle
16583 brackets. It is inactive in the sense that it does not trigger agenda entries,
16584 does not link to the calendar and cannot be changed with the S-cursor keys.
16585 So these are more for recording a certain time/date."
16586 (interactive "P")
16587 (org-time-stamp arg 'inactive))
16589 (defvar org-date-ovl (make-overlay 1 1))
16590 (overlay-put org-date-ovl 'face 'org-date-selected)
16591 (delete-overlay org-date-ovl)
16593 (defvar org-ans1) ; dynamically scoped parameter
16594 (defvar org-ans2) ; dynamically scoped parameter
16596 (defvar org-plain-time-of-day-regexp) ; defined below
16598 (defvar org-overriding-default-time nil) ; dynamically scoped
16599 (defvar org-read-date-overlay nil)
16600 (defvar org-dcst nil) ; dynamically scoped
16601 (defvar org-read-date-history nil)
16602 (defvar org-read-date-final-answer nil)
16603 (defvar org-read-date-analyze-futurep nil)
16604 (defvar org-read-date-analyze-forced-year nil)
16605 (defvar org-read-date-inactive)
16607 (defvar org-read-date-minibuffer-local-map
16608 (let* ((map (make-sparse-keymap)))
16609 (set-keymap-parent map minibuffer-local-map)
16610 (org-defkey map (kbd ".")
16611 (lambda () (interactive)
16612 ;; Are we at the beginning of the prompt?
16613 (if (looking-back "^[^:]+: "
16614 (let ((inhibit-field-text-motion t))
16615 (line-beginning-position)))
16616 (org-eval-in-calendar '(calendar-goto-today))
16617 (insert "."))))
16618 (org-defkey map (kbd "C-.")
16619 (lambda () (interactive)
16620 (org-eval-in-calendar '(calendar-goto-today))))
16621 (org-defkey map [(meta shift left)]
16622 (lambda () (interactive)
16623 (org-eval-in-calendar '(calendar-backward-month 1))))
16624 (org-defkey map [(meta shift right)]
16625 (lambda () (interactive)
16626 (org-eval-in-calendar '(calendar-forward-month 1))))
16627 (org-defkey map [(meta shift up)]
16628 (lambda () (interactive)
16629 (org-eval-in-calendar '(calendar-backward-year 1))))
16630 (org-defkey map [(meta shift down)]
16631 (lambda () (interactive)
16632 (org-eval-in-calendar '(calendar-forward-year 1))))
16633 (org-defkey map [?\e (shift left)]
16634 (lambda () (interactive)
16635 (org-eval-in-calendar '(calendar-backward-month 1))))
16636 (org-defkey map [?\e (shift right)]
16637 (lambda () (interactive)
16638 (org-eval-in-calendar '(calendar-forward-month 1))))
16639 (org-defkey map [?\e (shift up)]
16640 (lambda () (interactive)
16641 (org-eval-in-calendar '(calendar-backward-year 1))))
16642 (org-defkey map [?\e (shift down)]
16643 (lambda () (interactive)
16644 (org-eval-in-calendar '(calendar-forward-year 1))))
16645 (org-defkey map [(shift up)]
16646 (lambda () (interactive)
16647 (org-eval-in-calendar '(calendar-backward-week 1))))
16648 (org-defkey map [(shift down)]
16649 (lambda () (interactive)
16650 (org-eval-in-calendar '(calendar-forward-week 1))))
16651 (org-defkey map [(shift left)]
16652 (lambda () (interactive)
16653 (org-eval-in-calendar '(calendar-backward-day 1))))
16654 (org-defkey map [(shift right)]
16655 (lambda () (interactive)
16656 (org-eval-in-calendar '(calendar-forward-day 1))))
16657 (org-defkey map "!"
16658 (lambda () (interactive)
16659 (org-eval-in-calendar '(diary-view-entries))
16660 (message "")))
16661 (org-defkey map ">"
16662 (lambda () (interactive)
16663 (org-eval-in-calendar '(calendar-scroll-left 1))))
16664 (org-defkey map "<"
16665 (lambda () (interactive)
16666 (org-eval-in-calendar '(calendar-scroll-right 1))))
16667 (org-defkey map "\C-v"
16668 (lambda () (interactive)
16669 (org-eval-in-calendar
16670 '(calendar-scroll-left-three-months 1))))
16671 (org-defkey map "\M-v"
16672 (lambda () (interactive)
16673 (org-eval-in-calendar
16674 '(calendar-scroll-right-three-months 1))))
16675 map)
16676 "Keymap for minibuffer commands when using `org-read-date'.")
16678 (defvar org-def)
16679 (defvar org-defdecode)
16680 (defvar org-with-time)
16682 (defvar calendar-setup) ; Dynamically scoped.
16683 (defun org-read-date (&optional with-time to-time from-string prompt
16684 default-time default-input inactive)
16685 "Read a date, possibly a time, and make things smooth for the user.
16686 The prompt will suggest to enter an ISO date, but you can also enter anything
16687 which will at least partially be understood by `parse-time-string'.
16688 Unrecognized parts of the date will default to the current day, month, year,
16689 hour and minute. If this command is called to replace a timestamp at point,
16690 or to enter the second timestamp of a range, the default time is taken
16691 from the existing stamp. Furthermore, the command prefers the future,
16692 so if you are giving a date where the year is not given, and the day-month
16693 combination is already past in the current year, it will assume you
16694 mean next year. For details, see the manual. A few examples:
16696 3-2-5 --> 2003-02-05
16697 feb 15 --> currentyear-02-15
16698 2/15 --> currentyear-02-15
16699 sep 12 9 --> 2009-09-12
16700 12:45 --> today 12:45
16701 22 sept 0:34 --> currentyear-09-22 0:34
16702 12 --> currentyear-currentmonth-12
16703 Fri --> nearest Friday after today
16704 -Tue --> last Tuesday
16705 etc.
16707 Furthermore you can specify a relative date by giving, as the *first* thing
16708 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16709 change in days weeks, months, years.
16710 With a single plus or minus, the date is relative to today. With a double
16711 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16712 +4d --> four days from today
16713 +4 --> same as above
16714 +2w --> two weeks from today
16715 ++5 --> five days from default date
16717 The function understands only English month and weekday abbreviations.
16719 While prompting, a calendar is popped up - you can also select the
16720 date with the mouse (button 1). The calendar shows a period of three
16721 months. To scroll it to other months, use the keys `>' and `<'.
16722 If you don't like the calendar, turn it off with
16723 (setq org-read-date-popup-calendar nil)
16725 With optional argument TO-TIME, the date will immediately be converted
16726 to an internal time.
16727 With an optional argument WITH-TIME, the prompt will suggest to
16728 also insert a time. Note that when WITH-TIME is not set, you can
16729 still enter a time, and this function will inform the calling routine
16730 about this change. The calling routine may then choose to change the
16731 format used to insert the time stamp into the buffer to include the time.
16732 With optional argument FROM-STRING, read from this string instead from
16733 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16734 the time/date that is used for everything that is not specified by the
16735 user."
16736 (require 'parse-time)
16737 (let* ((org-with-time with-time)
16738 (org-time-stamp-rounding-minutes
16739 (if (equal org-with-time '(16))
16740 '(0 0)
16741 org-time-stamp-rounding-minutes))
16742 (org-dcst org-display-custom-times)
16743 (ct (org-current-time))
16744 (org-def (or org-overriding-default-time default-time ct))
16745 (org-defdecode (decode-time org-def))
16746 (cur-frame (selected-frame))
16747 (mouse-autoselect-window nil) ; Don't let the mouse jump
16748 (calendar-setup
16749 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16750 (calendar-move-hook nil)
16751 (calendar-view-diary-initially-flag nil)
16752 (calendar-view-holidays-initially-flag nil)
16753 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16754 ;; Rationalize `org-def' and `org-defdecode', if required.
16755 (when (< (nth 2 org-defdecode) org-extend-today-until)
16756 (setf (nth 2 org-defdecode) -1)
16757 (setf (nth 1 org-defdecode) 59)
16758 (setq org-def (apply #'encode-time org-defdecode))
16759 (setq org-defdecode (decode-time org-def)))
16760 (let* ((timestr (format-time-string
16761 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16762 org-def))
16763 (prompt (concat (if prompt (concat prompt " ") "")
16764 (format "Date+time [%s]: " timestr))))
16765 (cond
16766 (from-string (setq ans from-string))
16767 (org-read-date-popup-calendar
16768 (save-excursion
16769 (save-window-excursion
16770 (calendar)
16771 (when (eq calendar-setup 'calendar-only)
16772 (setq cal-frame
16773 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16774 (select-frame cal-frame))
16775 (org-eval-in-calendar '(setq cursor-type nil) t)
16776 (unwind-protect
16777 (progn
16778 (calendar-forward-day (- (time-to-days org-def)
16779 (calendar-absolute-from-gregorian
16780 (calendar-current-date))))
16781 (org-eval-in-calendar nil t)
16782 (let* ((old-map (current-local-map))
16783 (map (copy-keymap calendar-mode-map))
16784 (minibuffer-local-map
16785 (copy-keymap org-read-date-minibuffer-local-map)))
16786 (org-defkey map (kbd "RET") 'org-calendar-select)
16787 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16788 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16789 (unwind-protect
16790 (progn
16791 (use-local-map map)
16792 (setq org-read-date-inactive inactive)
16793 (add-hook 'post-command-hook 'org-read-date-display)
16794 (setq org-ans0
16795 (read-string prompt
16796 default-input
16797 'org-read-date-history
16798 nil))
16799 ;; org-ans0: from prompt
16800 ;; org-ans1: from mouse click
16801 ;; org-ans2: from calendar motion
16802 (setq ans
16803 (concat org-ans0 " " (or org-ans1 org-ans2))))
16804 (remove-hook 'post-command-hook 'org-read-date-display)
16805 (use-local-map old-map)
16806 (when org-read-date-overlay
16807 (delete-overlay org-read-date-overlay)
16808 (setq org-read-date-overlay nil)))))
16809 (bury-buffer "*Calendar*")
16810 (when cal-frame
16811 (delete-frame cal-frame)
16812 (select-frame-set-input-focus cur-frame))))))
16814 (t ; Naked prompt only
16815 (unwind-protect
16816 (setq ans (read-string prompt default-input
16817 'org-read-date-history timestr))
16818 (when org-read-date-overlay
16819 (delete-overlay org-read-date-overlay)
16820 (setq org-read-date-overlay nil))))))
16822 (setq final (org-read-date-analyze ans org-def org-defdecode))
16824 (when org-read-date-analyze-forced-year
16825 (message "Year was forced into %s"
16826 (if org-read-date-force-compatible-dates
16827 "compatible range (1970-2037)"
16828 "range representable on this machine"))
16829 (ding))
16831 ;; One round trip to get rid of 34th of August and stuff like that....
16832 (setq final (decode-time (apply 'encode-time final)))
16834 (setq org-read-date-final-answer ans)
16836 (if to-time
16837 (apply 'encode-time final)
16838 (if (and (boundp 'org-time-was-given) org-time-was-given)
16839 (format "%04d-%02d-%02d %02d:%02d"
16840 (nth 5 final) (nth 4 final) (nth 3 final)
16841 (nth 2 final) (nth 1 final))
16842 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16844 (defun org-read-date-display ()
16845 "Display the current date prompt interpretation in the minibuffer."
16846 (when org-read-date-display-live
16847 (when org-read-date-overlay
16848 (delete-overlay org-read-date-overlay))
16849 (when (minibufferp (current-buffer))
16850 (save-excursion
16851 (end-of-line 1)
16852 (while (not (equal (buffer-substring
16853 (max (point-min) (- (point) 4)) (point))
16854 " "))
16855 (insert " ")))
16856 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16857 " " (or org-ans1 org-ans2)))
16858 (org-end-time-was-given nil)
16859 (f (org-read-date-analyze ans org-def org-defdecode))
16860 (fmts (if org-dcst
16861 org-time-stamp-custom-formats
16862 org-time-stamp-formats))
16863 (fmt (if (or org-with-time
16864 (and (boundp 'org-time-was-given) org-time-was-given))
16865 (cdr fmts)
16866 (car fmts)))
16867 (txt (format-time-string fmt (apply 'encode-time f)))
16868 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16869 (txt (concat "=> " txt)))
16870 (when (and org-end-time-was-given
16871 (string-match org-plain-time-of-day-regexp txt))
16872 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16873 org-end-time-was-given
16874 (substring txt (match-end 0)))))
16875 (when org-read-date-analyze-futurep
16876 (setq txt (concat txt " (=>F)")))
16877 (setq org-read-date-overlay
16878 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16879 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16881 (defun org-read-date-analyze (ans def defdecode)
16882 "Analyze the combined answer of the date prompt."
16883 ;; FIXME: cleanup and comment
16884 ;; Pass `current-time' result to `decode-time' (instead of calling
16885 ;; without arguments) so that only `current-time' has to be
16886 ;; overridden in tests.
16887 (let ((org-def def)
16888 (org-defdecode defdecode)
16889 (nowdecode (decode-time (current-time)))
16890 delta deltan deltaw deltadef year month day
16891 hour minute second wday pm h2 m2 tl wday1
16892 iso-year iso-weekday iso-week iso-date futurep kill-year)
16893 (setq org-read-date-analyze-futurep nil
16894 org-read-date-analyze-forced-year nil)
16895 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16896 (setq ans "+0"))
16898 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16899 (setq ans (replace-match "" t t ans)
16900 deltan (car delta)
16901 deltaw (nth 1 delta)
16902 deltadef (nth 2 delta)))
16904 ;; Check if there is an iso week date in there. If yes, store the
16905 ;; info and postpone interpreting it until the rest of the parsing
16906 ;; is done.
16907 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16908 (setq iso-year (when (match-end 1)
16909 (org-small-year-to-year
16910 (string-to-number (match-string 1 ans))))
16911 iso-weekday (when (match-end 3)
16912 (string-to-number (match-string 3 ans)))
16913 iso-week (string-to-number (match-string 2 ans)))
16914 (setq ans (replace-match "" t t ans)))
16916 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
16917 (when (string-match
16918 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16919 (setq year (if (match-end 2)
16920 (string-to-number (match-string 2 ans))
16921 (progn (setq kill-year t)
16922 (string-to-number (format-time-string "%Y"))))
16923 month (string-to-number (match-string 3 ans))
16924 day (string-to-number (match-string 4 ans)))
16925 (setq year (org-small-year-to-year year))
16926 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16927 t nil ans)))
16929 ;; Help matching dotted european dates
16930 (when (string-match
16931 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
16932 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
16933 (setq kill-year t)
16934 (string-to-number (format-time-string "%Y")))
16935 day (string-to-number (match-string 1 ans))
16936 month (string-to-number (match-string 2 ans))
16937 ans (replace-match (format "%04d-%02d-%02d" year month day)
16938 t nil ans)))
16940 ;; Help matching american dates, like 5/30 or 5/30/7
16941 (when (string-match
16942 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
16943 (setq year (if (match-end 4)
16944 (string-to-number (match-string 4 ans))
16945 (progn (setq kill-year t)
16946 (string-to-number (format-time-string "%Y"))))
16947 month (string-to-number (match-string 1 ans))
16948 day (string-to-number (match-string 2 ans)))
16949 (setq year (org-small-year-to-year year))
16950 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16951 t nil ans)))
16952 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16953 ;; If there is a time with am/pm, and *no* time without it, we convert
16954 ;; so that matching will be successful.
16955 (cl-loop for i from 1 to 2 do ; twice, for end time as well
16956 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16957 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16958 (setq hour (string-to-number (match-string 1 ans))
16959 minute (if (match-end 3)
16960 (string-to-number (match-string 3 ans))
16962 pm (equal ?p
16963 (string-to-char (downcase (match-string 4 ans)))))
16964 (if (and (= hour 12) (not pm))
16965 (setq hour 0)
16966 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
16967 (setq ans (replace-match (format "%02d:%02d" hour minute)
16968 t t ans))))
16970 ;; Check if a time range is given as a duration
16971 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16972 (setq hour (string-to-number (match-string 1 ans))
16973 h2 (+ hour (string-to-number (match-string 3 ans)))
16974 minute (string-to-number (match-string 2 ans))
16975 m2 (+ minute (if (match-end 5) (string-to-number
16976 (match-string 5 ans))0)))
16977 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16978 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
16979 t t ans)))
16981 ;; Check if there is a time range
16982 (when (boundp 'org-end-time-was-given)
16983 (setq org-time-was-given nil)
16984 (when (and (string-match org-plain-time-of-day-regexp ans)
16985 (match-end 8))
16986 (setq org-end-time-was-given (match-string 8 ans))
16987 (setq ans (concat (substring ans 0 (match-beginning 7))
16988 (substring ans (match-end 7))))))
16990 (setq tl (parse-time-string ans)
16991 day (or (nth 3 tl) (nth 3 org-defdecode))
16992 month
16993 (cond ((nth 4 tl))
16994 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
16995 ;; Day was specified. Make sure DAY+MONTH
16996 ;; combination happens in the future.
16997 ((nth 3 tl)
16998 (setq futurep t)
16999 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17000 (nth 4 nowdecode)))
17001 (t (nth 4 org-defdecode)))
17002 year
17003 (cond ((and (not kill-year) (nth 5 tl)))
17004 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17005 ;; Month was guessed in the future and is at least
17006 ;; equal to NOWDECODE's. Fix year accordingly.
17007 (futurep
17008 (if (or (> month (nth 4 nowdecode))
17009 (>= day (nth 3 nowdecode)))
17010 (nth 5 nowdecode)
17011 (1+ (nth 5 nowdecode))))
17012 ;; Month was specified. Make sure MONTH+YEAR
17013 ;; combination happens in the future.
17014 ((nth 4 tl)
17015 (setq futurep t)
17016 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17017 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17018 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17019 (t (nth 5 nowdecode))))
17020 (t (nth 5 org-defdecode)))
17021 hour (or (nth 2 tl) (nth 2 org-defdecode))
17022 minute (or (nth 1 tl) (nth 1 org-defdecode))
17023 second (or (nth 0 tl) 0)
17024 wday (nth 6 tl))
17026 (when (and (eq org-read-date-prefer-future 'time)
17027 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17028 (equal day (nth 3 nowdecode))
17029 (equal month (nth 4 nowdecode))
17030 (equal year (nth 5 nowdecode))
17031 (nth 2 tl)
17032 (or (< (nth 2 tl) (nth 2 nowdecode))
17033 (and (= (nth 2 tl) (nth 2 nowdecode))
17034 (nth 1 tl)
17035 (< (nth 1 tl) (nth 1 nowdecode)))))
17036 (setq day (1+ day)
17037 futurep t))
17039 ;; Special date definitions below
17040 (cond
17041 (iso-week
17042 ;; There was an iso week
17043 (require 'cal-iso)
17044 (setq futurep nil)
17045 (setq year (or iso-year year)
17046 day (or iso-weekday wday 1)
17047 wday nil ; to make sure that the trigger below does not match
17048 iso-date (calendar-gregorian-from-absolute
17049 (calendar-iso-to-absolute
17050 (list iso-week day year))))
17051 ; FIXME: Should we also push ISO weeks into the future?
17052 ; (when (and org-read-date-prefer-future
17053 ; (not iso-year)
17054 ; (< (calendar-absolute-from-gregorian iso-date)
17055 ; (time-to-days (current-time))))
17056 ; (setq year (1+ year)
17057 ; iso-date (calendar-gregorian-from-absolute
17058 ; (calendar-iso-to-absolute
17059 ; (list iso-week day year)))))
17060 (setq month (car iso-date)
17061 year (nth 2 iso-date)
17062 day (nth 1 iso-date)))
17063 (deltan
17064 (setq futurep nil)
17065 (unless deltadef
17066 ;; Pass `current-time' result to `decode-time' (instead of
17067 ;; calling without arguments) so that only `current-time' has
17068 ;; to be overridden in tests.
17069 (let ((now (decode-time (current-time))))
17070 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17071 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17072 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17073 ((equal deltaw "m") (setq month (+ month deltan)))
17074 ((equal deltaw "y") (setq year (+ year deltan)))))
17075 ((and wday (not (nth 3 tl)))
17076 ;; Weekday was given, but no day, so pick that day in the week
17077 ;; on or after the derived date.
17078 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17079 (unless (equal wday wday1)
17080 (setq day (+ day (% (- wday wday1 -7) 7))))))
17081 (when (and (boundp 'org-time-was-given)
17082 (nth 2 tl))
17083 (setq org-time-was-given t))
17084 (when (< year 100) (setq year (+ 2000 year)))
17085 ;; Check of the date is representable
17086 (if org-read-date-force-compatible-dates
17087 (progn
17088 (when (< year 1970)
17089 (setq year 1970 org-read-date-analyze-forced-year t))
17090 (when (> year 2037)
17091 (setq year 2037 org-read-date-analyze-forced-year t)))
17092 (condition-case nil
17093 (ignore (encode-time second minute hour day month year))
17094 (error
17095 (setq year (nth 5 org-defdecode))
17096 (setq org-read-date-analyze-forced-year t))))
17097 (setq org-read-date-analyze-futurep futurep)
17098 (list second minute hour day month year)))
17100 (defvar parse-time-weekdays)
17101 (defun org-read-date-get-relative (s today default)
17102 "Check string S for special relative date string.
17103 TODAY and DEFAULT are internal times, for today and for a default.
17104 Return shift list (N what def-flag)
17105 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17106 N is the number of WHATs to shift.
17107 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17108 the DEFAULT date rather than TODAY."
17109 (require 'parse-time)
17110 (when (and
17111 (string-match
17112 (concat
17113 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17114 "\\([0-9]+\\)?"
17115 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17116 "\\([ \t]\\|$\\)") s)
17117 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17118 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17119 (string-to-char (substring (match-string 1 s) -1))
17120 ?+))
17121 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17122 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17123 (what (if (match-end 3) (match-string 3 s) "d"))
17124 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17125 (date (if rel default today))
17126 (wday (nth 6 (decode-time date)))
17127 delta)
17128 (if wday1
17129 (progn
17130 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17131 (when (= delta 0) (setq delta 7))
17132 (when (= dir ?-)
17133 (setq delta (- delta 7))
17134 (when (= delta 0) (setq delta -7)))
17135 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17136 (list delta "d" rel))
17137 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17139 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17140 "Turn a user-specified date into the internal representation.
17141 The internal representation needed by the calendar is (month day year).
17142 This is a wrapper to handle the brain-dead convention in calendar that
17143 user function argument order change dependent on argument order."
17144 (pcase calendar-date-style
17145 (`american (list arg1 arg2 arg3))
17146 (`european (list arg2 arg1 arg3))
17147 (`iso (list arg2 arg3 arg1))))
17149 (defun org-eval-in-calendar (form &optional keepdate)
17150 "Eval FORM in the calendar window and return to current window.
17151 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17152 (let ((sf (selected-frame))
17153 (sw (selected-window)))
17154 (select-window (get-buffer-window "*Calendar*" t))
17155 (eval form)
17156 (when (and (not keepdate) (calendar-cursor-to-date))
17157 (let* ((date (calendar-cursor-to-date))
17158 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17159 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17160 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17161 (select-window sw)
17162 (select-frame-set-input-focus sf)))
17164 (defun org-calendar-select ()
17165 "Return to `org-read-date' with the date currently selected.
17166 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17167 (interactive)
17168 (when (calendar-cursor-to-date)
17169 (let* ((date (calendar-cursor-to-date))
17170 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17171 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17172 (when (active-minibuffer-window) (exit-minibuffer))))
17174 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17175 "Insert a date stamp for the date given by the internal TIME.
17176 See `format-time-string' for the format of TIME.
17177 WITH-HM means use the stamp format that includes the time of the day.
17178 INACTIVE means use square brackets instead of angular ones, so that the
17179 stamp will not contribute to the agenda.
17180 PRE and POST are optional strings to be inserted before and after the
17181 stamp.
17182 The command returns the inserted time stamp."
17183 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17184 stamp)
17185 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17186 (insert-before-markers (or pre ""))
17187 (when (listp extra)
17188 (setq extra (car extra))
17189 (if (and (stringp extra)
17190 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17191 (setq extra (format "-%02d:%02d"
17192 (string-to-number (match-string 1 extra))
17193 (string-to-number (match-string 2 extra))))
17194 (setq extra nil)))
17195 (when extra
17196 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17197 (insert-before-markers (setq stamp (format-time-string fmt time)))
17198 (insert-before-markers (or post ""))
17199 (setq org-last-inserted-timestamp stamp)))
17201 (defun org-toggle-time-stamp-overlays ()
17202 "Toggle the use of custom time stamp formats."
17203 (interactive)
17204 (setq org-display-custom-times (not org-display-custom-times))
17205 (unless org-display-custom-times
17206 (let ((p (point-min)) (bmp (buffer-modified-p)))
17207 (while (setq p (next-single-property-change p 'display))
17208 (when (and (get-text-property p 'display)
17209 (eq (get-text-property p 'face) 'org-date))
17210 (remove-text-properties
17211 p (setq p (next-single-property-change p 'display))
17212 '(display t))))
17213 (set-buffer-modified-p bmp)))
17214 (org-restart-font-lock)
17215 (setq org-table-may-need-update t)
17216 (if org-display-custom-times
17217 (message "Time stamps are overlaid with custom format")
17218 (message "Time stamp overlays removed")))
17220 (defun org-display-custom-time (beg end)
17221 "Overlay modified time stamp format over timestamp between BEG and END."
17222 (let* ((ts (buffer-substring beg end))
17223 t1 with-hm tf time str (off 0))
17224 (save-match-data
17225 (setq t1 (org-parse-time-string ts t))
17226 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17227 (setq off (- (match-end 0) (match-beginning 0)))))
17228 (setq end (- end off))
17229 (setq with-hm (and (nth 1 t1) (nth 2 t1))
17230 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17231 time (org-fix-decoded-time t1)
17232 str (org-add-props
17233 (format-time-string
17234 (substring tf 1 -1) (apply 'encode-time time))
17235 nil 'mouse-face 'highlight))
17236 (put-text-property beg end 'display str)))
17238 (defun org-fix-decoded-time (time)
17239 "Set 0 instead of nil for the first 6 elements of time.
17240 Don't touch the rest."
17241 (let ((n 0))
17242 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17244 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17245 "Difference between TIMESTAMP-STRING and now in days.
17246 If SECONDS is non-nil, return the difference in seconds."
17247 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17248 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17249 (funcall fdiff (current-time)))))
17251 (defun org-deadline-close-p (timestamp-string &optional ndays)
17252 "Is the time in TIMESTAMP-STRING close to the current date?"
17253 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17254 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17255 (not (org-entry-is-done-p))))
17257 (defun org-get-wdays (ts &optional delay zero-delay)
17258 "Get the deadline lead time appropriate for timestring TS.
17259 When DELAY is non-nil, get the delay time for scheduled items
17260 instead of the deadline lead time. When ZERO-DELAY is non-nil
17261 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17262 don't try to find the delay cookie in the scheduled timestamp."
17263 (let ((tv (if delay org-scheduled-delay-days
17264 org-deadline-warning-days)))
17265 (cond
17266 ((or (and delay (< tv 0))
17267 (and delay zero-delay (<= tv 0))
17268 (and (not delay) (<= tv 0)))
17269 ;; Enforce this value no matter what
17270 (- tv))
17271 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17272 ;; lead time is specified.
17273 (floor (* (string-to-number (match-string 1 ts))
17274 (cdr (assoc (match-string 2 ts)
17275 '(("d" . 1) ("w" . 7)
17276 ("m" . 30.4) ("y" . 365.25)
17277 ("h" . 0.041667)))))))
17278 ;; go for the default.
17279 (t tv))))
17281 (defun org-calendar-select-mouse (ev)
17282 "Return to `org-read-date' with the date currently selected.
17283 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17284 (interactive "e")
17285 (mouse-set-point ev)
17286 (when (calendar-cursor-to-date)
17287 (let* ((date (calendar-cursor-to-date))
17288 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17289 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17290 (when (active-minibuffer-window) (exit-minibuffer))))
17292 (defun org-check-deadlines (ndays)
17293 "Check if there are any deadlines due or past due.
17294 A deadline is considered due if it happens within `org-deadline-warning-days'
17295 days from today's date. If the deadline appears in an entry marked DONE,
17296 it is not shown. A numeric prefix argument NDAYS can be used to test that
17297 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17298 are shown."
17299 (interactive "P")
17300 (let* ((org-warn-days
17301 (cond
17302 ((equal ndays '(4)) 100000)
17303 (ndays (prefix-numeric-value ndays))
17304 (t (abs org-deadline-warning-days))))
17305 (case-fold-search nil)
17306 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17307 (callback
17308 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17309 (message "%d deadlines past-due or due within %d days"
17310 (org-occur regexp nil callback)
17311 org-warn-days)))
17313 (defsubst org-re-timestamp (type)
17314 "Return a regexp for timestamp TYPE.
17315 Allowed values for TYPE are:
17317 all: all timestamps
17318 active: only active timestamps (<...>)
17319 inactive: only inactive timestamps ([...])
17320 scheduled: only scheduled timestamps
17321 deadline: only deadline timestamps
17322 closed: only closed time-stamps
17324 When TYPE is nil, fall back on returning a regexp that matches
17325 both scheduled and deadline timestamps."
17326 (cl-case type
17327 (all org-ts-regexp-both)
17328 (active org-ts-regexp)
17329 (inactive org-ts-regexp-inactive)
17330 (scheduled org-scheduled-time-regexp)
17331 (deadline org-deadline-time-regexp)
17332 (closed org-closed-time-regexp)
17333 (otherwise
17334 (concat "\\<"
17335 (regexp-opt (list org-deadline-string org-scheduled-string))
17336 " *<\\([^>]+\\)>"))))
17338 (defun org-check-before-date (d)
17339 "Check if there are deadlines or scheduled entries before date D."
17340 (interactive (list (org-read-date)))
17341 (let* ((case-fold-search nil)
17342 (regexp (org-re-timestamp org-ts-type))
17343 (ts-type org-ts-type)
17344 (callback
17345 (lambda ()
17346 (let ((match (match-string 1)))
17347 (and (if (memq ts-type '(active inactive all))
17348 (eq (org-element-type (save-excursion
17349 (backward-char)
17350 (org-element-context)))
17351 'timestamp)
17352 (org-at-planning-p))
17353 (time-less-p
17354 (org-time-string-to-time match t)
17355 (org-time-string-to-time d t)))))))
17356 (message "%d entries before %s"
17357 (org-occur regexp nil callback)
17358 d)))
17360 (defun org-check-after-date (d)
17361 "Check if there are deadlines or scheduled entries after date D."
17362 (interactive (list (org-read-date)))
17363 (let* ((case-fold-search nil)
17364 (regexp (org-re-timestamp org-ts-type))
17365 (ts-type org-ts-type)
17366 (callback
17367 (lambda ()
17368 (let ((match (match-string 1)))
17369 (and (if (memq ts-type '(active inactive all))
17370 (eq (org-element-type (save-excursion
17371 (backward-char)
17372 (org-element-context)))
17373 'timestamp)
17374 (org-at-planning-p))
17375 (not (time-less-p
17376 (org-time-string-to-time match t)
17377 (org-time-string-to-time d t))))))))
17378 (message "%d entries after %s"
17379 (org-occur regexp nil callback)
17380 d)))
17382 (defun org-check-dates-range (start-date end-date)
17383 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17384 (interactive (list (org-read-date nil nil nil "Range starts")
17385 (org-read-date nil nil nil "Range end")))
17386 (let ((case-fold-search nil)
17387 (regexp (org-re-timestamp org-ts-type))
17388 (callback
17389 (let ((type org-ts-type))
17390 (lambda ()
17391 (let ((match (match-string 1)))
17392 (and
17393 (if (memq type '(active inactive all))
17394 (eq (org-element-type (save-excursion
17395 (backward-char)
17396 (org-element-context)))
17397 'timestamp)
17398 (org-at-planning-p))
17399 (not (time-less-p
17400 (org-time-string-to-time match t)
17401 (org-time-string-to-time start-date t)))
17402 (time-less-p
17403 (org-time-string-to-time match t)
17404 (org-time-string-to-time end-date t))))))))
17405 (message "%d entries between %s and %s"
17406 (org-occur regexp nil callback) start-date end-date)))
17408 (defun org-evaluate-time-range (&optional to-buffer)
17409 "Evaluate a time range by computing the difference between start and end.
17410 Normally the result is just printed in the echo area, but with prefix arg
17411 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17412 If the time range is actually in a table, the result is inserted into the
17413 next column.
17414 For time difference computation, a year is assumed to be exactly 365
17415 days in order to avoid rounding problems."
17416 (interactive "P")
17418 (org-clock-update-time-maybe)
17419 (save-excursion
17420 (unless (org-at-date-range-p t)
17421 (goto-char (point-at-bol))
17422 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17423 (unless (org-at-date-range-p t)
17424 (user-error "Not at a time-stamp range, and none found in current line")))
17425 (let* ((ts1 (match-string 1))
17426 (ts2 (match-string 2))
17427 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17428 (match-end (match-end 0))
17429 (time1 (org-time-string-to-time ts1))
17430 (time2 (org-time-string-to-time ts2))
17431 (t1 (float-time time1))
17432 (t2 (float-time time2))
17433 (diff (abs (- t2 t1)))
17434 (negative (< (- t2 t1) 0))
17435 ;; (ys (floor (* 365 24 60 60)))
17436 (ds (* 24 60 60))
17437 (hs (* 60 60))
17438 (fy "%dy %dd %02d:%02d")
17439 (fy1 "%dy %dd")
17440 (fd "%dd %02d:%02d")
17441 (fd1 "%dd")
17442 (fh "%02d:%02d")
17443 y d h m align)
17444 (if havetime
17445 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17447 d (floor (/ diff ds)) diff (mod diff ds)
17448 h (floor (/ diff hs)) diff (mod diff hs)
17449 m (floor (/ diff 60)))
17450 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17452 d (floor (+ (/ diff ds) 0.5))
17453 h 0 m 0))
17454 (if (not to-buffer)
17455 (message "%s" (org-make-tdiff-string y d h m))
17456 (if (org-at-table-p)
17457 (progn
17458 (goto-char match-end)
17459 (setq align t)
17460 (and (looking-at " *|") (goto-char (match-end 0))))
17461 (goto-char match-end))
17462 (when (looking-at
17463 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17464 (replace-match ""))
17465 (when negative (insert " -"))
17466 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17467 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17468 (insert " " (format fh h m))))
17469 (when align (org-table-align))
17470 (message "Time difference inserted")))))
17472 (defun org-make-tdiff-string (y d h m)
17473 (let ((fmt "")
17474 (l nil))
17475 (when (> y 0)
17476 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17477 (push y l))
17478 (when (> d 0)
17479 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17480 (push d l))
17481 (when (> h 0)
17482 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17483 (push h l))
17484 (when (> m 0)
17485 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17486 (push m l))
17487 (apply 'format fmt (nreverse l))))
17489 (defun org-time-string-to-time (s &optional zone)
17490 "Convert timestamp string S into internal time.
17491 The optional ZONE is omitted or nil for Emacs local time, t for
17492 Universal Time, ‘wall’ for system wall clock time, or a string as
17493 in the TZ environment variable."
17494 (apply #'encode-time (org-parse-time-string s nil zone)))
17496 (defun org-time-string-to-seconds (s &optional zone)
17497 "Convert a timestamp string S into a number of seconds.
17498 The optional ZONE is omitted or nil for Emacs local time, t for
17499 Universal Time, ‘wall’ for system wall clock time, or a string as
17500 in the TZ environment variable."
17501 (float-time (org-time-string-to-time s zone)))
17503 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17505 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17506 "Convert time stamp S to an absolute day number.
17508 If DAYNR in non-nil, and there is a specifier for a cyclic time
17509 stamp, get the closest date to DAYNR. If PREFER is
17510 `past' (respectively `future') return a date past (respectively
17511 after) or equal to DAYNR.
17513 POS is the location of time stamp S, as a buffer position in
17514 BUFFER.
17516 Diary sexp timestamps are matched against DAYNR, when non-nil.
17517 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17518 signaled."
17519 (cond
17520 ((string-match "\\`%%\\((.*)\\)" s)
17521 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17522 ;; only able to match individual dates. If it fails, raise an
17523 ;; error.
17524 (if (and daynr
17525 (org-diary-sexp-entry
17526 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17527 daynr
17528 (signal 'org-diary-sexp-no-match (list s))))
17529 (daynr (org-closest-date s daynr prefer))
17530 (t (time-to-days
17531 (condition-case errdata
17532 (apply #'encode-time (org-parse-time-string s))
17533 (error (error "Bad timestamp `%s'%s\nError was: %s"
17535 (if (not (and buffer pos)) ""
17536 (format-message " at %d in buffer `%s'" pos buffer))
17537 (cdr errdata))))))))
17539 (defun org-days-to-iso-week (days)
17540 "Return the iso week number."
17541 (require 'cal-iso)
17542 (car (calendar-iso-from-absolute days)))
17544 (defun org-small-year-to-year (year)
17545 "Convert 2-digit years into 4-digit years.
17546 YEAR is expanded into one of the 30 next years, if possible, or
17547 into a past one. Any year larger than 99 is returned unchanged."
17548 (if (>= year 100) year
17549 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17550 (century (/ current 100))
17551 (offset (- year (% current 100))))
17552 (cond ((> offset 30) (+ (* (1- century) 100) year))
17553 ((> offset -70) (+ (* century 100) year))
17554 (t (+ (* (1+ century) 100) year))))))
17556 (defun org-time-from-absolute (d)
17557 "Return the time corresponding to date D.
17558 D may be an absolute day number, or a calendar-type list (month day year)."
17559 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17560 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17562 (defvar org-agenda-current-date)
17563 (defun org-calendar-holiday ()
17564 "List of holidays, for Diary display in Org mode."
17565 (require 'holidays)
17566 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17567 (and hl (mapconcat #'identity hl "; "))))
17569 (defun org-diary-sexp-entry (sexp entry d)
17570 "Process a SEXP diary ENTRY for date D."
17571 (require 'diary-lib)
17572 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17573 ;; dynamically.
17574 (let* ((sexp `(let ((entry ,entry)
17575 (date ',d))
17576 ,(car (read-from-string sexp))))
17577 (result (if calendar-debug-sexp (eval sexp)
17578 (condition-case nil
17579 (eval sexp)
17580 (error
17581 (beep)
17582 (message "Bad sexp at line %d in %s: %s"
17583 (org-current-line)
17584 (buffer-file-name) sexp)
17585 (sleep-for 2))))))
17586 (cond ((stringp result) (split-string result "; "))
17587 ((and (consp result)
17588 (not (consp (cdr result)))
17589 (stringp (cdr result))) (cdr result))
17590 ((and (consp result)
17591 (stringp (car result))) result)
17592 (result entry))))
17594 (defun org-diary-to-ical-string (frombuf)
17595 "Get iCalendar entries from diary entries in buffer FROMBUF.
17596 This uses the icalendar.el library."
17597 (let* ((tmpdir temporary-file-directory)
17598 (tmpfile (make-temp-name
17599 (expand-file-name "orgics" tmpdir)))
17600 buf rtn b e)
17601 (with-current-buffer frombuf
17602 (icalendar-export-region (point-min) (point-max) tmpfile)
17603 (setq buf (find-buffer-visiting tmpfile))
17604 (set-buffer buf)
17605 (goto-char (point-min))
17606 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17607 (setq b (match-beginning 0)))
17608 (goto-char (point-max))
17609 (when (re-search-backward "^END:VEVENT" nil t)
17610 (setq e (match-end 0)))
17611 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17612 (kill-buffer buf)
17613 (delete-file tmpfile)
17614 rtn))
17616 (defun org-closest-date (start current prefer)
17617 "Return closest date to CURRENT starting from START.
17619 CURRENT and START are both time stamps.
17621 When PREFER is `past', return a date that is either CURRENT or
17622 past. When PREFER is `future', return a date that is either
17623 CURRENT or future.
17625 Only time stamps with a repeater are modified. Any other time
17626 stamp stay unchanged. In any case, return value is an absolute
17627 day number."
17628 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17629 ;; No repeater. Do not shift time stamp.
17630 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17631 (let ((value (string-to-number (match-string 1 start)))
17632 (type (match-string 2 start)))
17633 (if (= 0 value)
17634 ;; Repeater with a 0-value is considered as void.
17635 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17636 (let* ((base (org-date-to-gregorian start))
17637 (target (org-date-to-gregorian current))
17638 (sday (calendar-absolute-from-gregorian base))
17639 (cday (calendar-absolute-from-gregorian target))
17640 n1 n2)
17641 ;; If START is already past CURRENT, just return START.
17642 (if (<= cday sday) sday
17643 ;; Compute closest date before (N1) and closest date past
17644 ;; (N2) CURRENT.
17645 (pcase type
17646 ("h"
17647 (let ((missing-hours
17648 (mod (+ (- (* 24 (- cday sday))
17649 (nth 2 (org-parse-time-string start)))
17650 org-extend-today-until)
17651 value)))
17652 (setf n1 (if (= missing-hours 0) cday
17653 (- cday (1+ (/ missing-hours 24)))))
17654 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17655 ((or "d" "w")
17656 (let ((value (if (equal type "w") (* 7 value) value)))
17657 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17658 (setf n2 (+ n1 value))))
17659 ("m"
17660 (let* ((add-months
17661 (lambda (d n)
17662 ;; Add N months to gregorian date D, i.e.,
17663 ;; a list (MONTH DAY YEAR). Return a valid
17664 ;; gregorian date.
17665 (let ((m (+ (nth 0 d) n)))
17666 (list (mod m 12)
17667 (nth 1 d)
17668 (+ (/ m 12) (nth 2 d))))))
17669 (months ; Complete months to TARGET.
17670 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17671 (- (nth 0 target) (nth 0 base))
17672 ;; If START's day is greater than
17673 ;; TARGET's, remove incomplete month.
17674 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17675 value)
17676 value))
17677 (before (funcall add-months base months)))
17678 (setf n1 (calendar-absolute-from-gregorian before))
17679 (setf n2
17680 (calendar-absolute-from-gregorian
17681 (funcall add-months before value)))))
17683 (let* ((d (nth 1 base))
17684 (m (nth 0 base))
17685 (y (nth 2 base))
17686 (years ; Complete years to TARGET.
17687 (* (/ (- (nth 2 target)
17689 ;; If START's month and day are
17690 ;; greater than TARGET's, remove
17691 ;; incomplete year.
17692 (if (or (> (nth 0 target) m)
17693 (and (= (nth 0 target) m)
17694 (> (nth 1 target) d)))
17697 value)
17698 value))
17699 (before (list m d (+ y years))))
17700 (setf n1 (calendar-absolute-from-gregorian before))
17701 (setf n2 (calendar-absolute-from-gregorian
17702 (list m d (+ (nth 2 before) value)))))))
17703 ;; Handle PREFER parameter, if any.
17704 (cond
17705 ((eq prefer 'past) (if (= cday n2) n2 n1))
17706 ((eq prefer 'future) (if (= cday n1) n1 n2))
17707 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17709 (defun org-date-to-gregorian (d)
17710 "Turn any specification of date D into a Gregorian date for the calendar."
17711 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17712 ((and (listp d) (= (length d) 3)) d)
17713 ((stringp d)
17714 (let ((d (org-parse-time-string d)))
17715 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17716 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17718 (defun org-parse-time-string (s &optional nodefault zone)
17719 "Parse the standard Org time string.
17721 This should be a lot faster than the normal `parse-time-string'.
17723 If time is not given, defaults to 0:00. However, with optional
17724 NODEFAULT, hour and minute fields will be nil if not given.
17726 The optional ZONE is omitted or nil for Emacs local time, t for
17727 Universal Time, ‘wall’ for system wall clock time, or a string as
17728 in the TZ environment variable."
17729 (cond ((string-match org-ts-regexp0 s)
17730 (list 0
17731 (when (or (match-beginning 8) (not nodefault))
17732 (string-to-number (or (match-string 8 s) "0")))
17733 (when (or (match-beginning 7) (not nodefault))
17734 (string-to-number (or (match-string 7 s) "0")))
17735 (string-to-number (match-string 4 s))
17736 (string-to-number (match-string 3 s))
17737 (string-to-number (match-string 2 s))
17738 nil nil zone))
17739 ((string-match "^<[^>]+>$" s)
17740 ;; FIXME: `decode-time' needs to be called with ZONE as its
17741 ;; second argument. However, this requires at least Emacs
17742 ;; 25.1. We can do it when we switch to this version as our
17743 ;; minimal requirement.
17744 (decode-time (seconds-to-time (org-matcher-time s))))
17745 (t (error "Not a standard Org time string: %s" s))))
17747 (defun org-timestamp-up (&optional arg)
17748 "Increase the date item at the cursor by one.
17749 If the cursor is on the year, change the year. If it is on the month,
17750 the day or the time, change that.
17751 With prefix ARG, change by that many units."
17752 (interactive "p")
17753 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17755 (defun org-timestamp-down (&optional arg)
17756 "Decrease the date item at the cursor by one.
17757 If the cursor is on the year, change the year. If it is on the month,
17758 the day or the time, change that.
17759 With prefix ARG, change by that many units."
17760 (interactive "p")
17761 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17763 (defun org-timestamp-up-day (&optional arg)
17764 "Increase the date in the time stamp by one day.
17765 With prefix ARG, change that many days."
17766 (interactive "p")
17767 (if (and (not (org-at-timestamp-p 'lax))
17768 (org-at-heading-p))
17769 (org-todo 'up)
17770 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17772 (defun org-timestamp-down-day (&optional arg)
17773 "Decrease the date in the time stamp by one day.
17774 With prefix ARG, change that many days."
17775 (interactive "p")
17776 (if (and (not (org-at-timestamp-p 'lax))
17777 (org-at-heading-p))
17778 (org-todo 'down)
17779 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17781 (defun org-at-timestamp-p (&optional extended)
17782 "Non-nil if point is inside a timestamp.
17784 By default, the function only consider syntactically valid active
17785 timestamps. However, the caller may have a broader definition
17786 for timestamps. As a consequence, optional argument EXTENDED can
17787 be set to the following values
17789 `inactive'
17791 Include also syntactically valid inactive timestamps.
17793 `agenda'
17795 Include timestamps allowed in Agenda, i.e., those in
17796 properties drawers, planning lines and clock lines.
17798 `lax'
17800 Ignore context. The function matches any part of the
17801 document looking like a timestamp. This includes comments,
17802 example blocks...
17804 For backward-compatibility with Org 9.0, every other non-nil
17805 value is equivalent to `inactive'.
17807 When at a timestamp, return the position of the point as a symbol
17808 among `bracket', `after', `year', `month', `hour', `minute',
17809 `day' or a number of character from the last know part of the
17810 time stamp.
17812 When matching, the match groups are the following:
17813 group 1: year
17814 group 2: month
17815 group 3: day number
17816 group 4: day name
17817 group 5: hours, if any
17818 group 6: minutes, if any"
17819 (let* ((regexp (if extended org-ts-regexp3 org-ts-regexp2))
17820 (pos (point))
17821 (match?
17822 (let ((boundaries (org-in-regexp regexp)))
17823 (save-match-data
17824 (cond ((null boundaries) nil)
17825 ((eq extended 'lax) t)
17827 (or (and (eq extended 'agenda)
17828 (or (org-at-planning-p)
17829 (org-at-property-p)
17830 (and (bound-and-true-p
17831 org-agenda-include-inactive-timestamps)
17832 (org-at-clock-log-p))))
17833 (eq 'timestamp
17834 (save-excursion
17835 (when (= pos (cdr boundaries)) (forward-char -1))
17836 (org-element-type (org-element-context)))))))))))
17837 (cond
17838 ((not match?) nil)
17839 ((= pos (match-beginning 0)) 'bracket)
17840 ;; Distinguish location right before the closing bracket from
17841 ;; right after it.
17842 ((= pos (1- (match-end 0))) 'bracket)
17843 ((= pos (match-end 0)) 'after)
17844 ((org-pos-in-match-range pos 2) 'year)
17845 ((org-pos-in-match-range pos 3) 'month)
17846 ((org-pos-in-match-range pos 7) 'hour)
17847 ((org-pos-in-match-range pos 8) 'minute)
17848 ((or (org-pos-in-match-range pos 4)
17849 (org-pos-in-match-range pos 5)) 'day)
17850 ((and (> pos (or (match-end 8) (match-end 5)))
17851 (< pos (match-end 0)))
17852 (- pos (or (match-end 8) (match-end 5))))
17853 (t 'day))))
17855 (defun org-toggle-timestamp-type ()
17856 "Toggle the type (<active> or [inactive]) of a time stamp."
17857 (interactive)
17858 (when (org-at-timestamp-p 'lax)
17859 (let ((beg (match-beginning 0)) (end (match-end 0))
17860 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17861 (save-excursion
17862 (goto-char beg)
17863 (while (re-search-forward "[][<>]" end t)
17864 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17865 t t)))
17866 (message "Timestamp is now %sactive"
17867 (if (equal (char-after beg) ?<) "" "in")))))
17869 (defun org-at-clock-log-p ()
17870 "Non-nil if point is on a clock log line."
17871 (and (org-match-line org-clock-line-re)
17872 (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
17874 (defvar org-clock-history) ; defined in org-clock.el
17875 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17876 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17877 "Change the date in the time stamp at point.
17878 The date will be changed by N times WHAT. WHAT can be `day', `month',
17879 `year', `minute', `second'. If WHAT is not given, the cursor position
17880 in the timestamp determines what will be changed.
17881 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17882 (let ((origin (point))
17883 (timestamp? (org-at-timestamp-p 'lax))
17884 origin-cat
17885 with-hm inactive
17886 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17887 extra rem
17888 ts time time0 fixnext clrgx)
17889 (unless timestamp? (user-error "Not at a timestamp"))
17890 (if (and (not what) (eq timestamp? 'bracket))
17891 (org-toggle-timestamp-type)
17892 ;; Point isn't on brackets. Remember the part of the time-stamp
17893 ;; the point was in. Indeed, size of time-stamps may change,
17894 ;; but point must be kept in the same category nonetheless.
17895 (setq origin-cat timestamp?)
17896 (when (and (not what) (not (eq timestamp? 'day))
17897 org-display-custom-times
17898 (get-text-property (point) 'display)
17899 (not (get-text-property (1- (point)) 'display)))
17900 (setq timestamp? 'day))
17901 (setq timestamp? (or what timestamp?)
17902 inactive (= (char-after (match-beginning 0)) ?\[)
17903 ts (match-string 0))
17904 (replace-match "")
17905 (when (string-match
17906 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17908 (setq extra (match-string 1 ts))
17909 (when suppress-tmp-delay
17910 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17911 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17912 (setq with-hm t))
17913 (setq time0 (org-parse-time-string ts))
17914 (when (and updown
17915 (eq timestamp? 'minute)
17916 (not current-prefix-arg))
17917 ;; This looks like s-up and s-down. Change by one rounding step.
17918 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17919 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17920 (setcar (cdr time0) (+ (nth 1 time0)
17921 (if (> n 0) (- rem) (- dm rem))))))
17922 (setq time
17923 (apply #'encode-time
17924 (or (car time0) 0)
17925 (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
17926 (+ (if (eq timestamp? 'hour) n 0) (nth 2 time0))
17927 (+ (if (eq timestamp? 'day) n 0) (nth 3 time0))
17928 (+ (if (eq timestamp? 'month) n 0) (nth 4 time0))
17929 (+ (if (eq timestamp? 'year) n 0) (nth 5 time0))
17930 (nthcdr 6 time0)))
17931 (when (and (memq timestamp? '(hour minute))
17932 extra
17933 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17934 (setq extra (org-modify-ts-extra
17935 extra
17936 (if (eq timestamp? 'hour) 2 5)
17937 n dm)))
17938 (when (integerp timestamp?)
17939 (setq extra (org-modify-ts-extra extra timestamp? n dm)))
17940 (when (eq what 'calendar)
17941 (let ((cal-date (org-get-date-from-calendar)))
17942 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17943 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17944 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17945 (setcar time0 (or (car time0) 0))
17946 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17947 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17948 (setq time (apply 'encode-time time0))))
17949 ;; Insert the new time-stamp, and ensure point stays in the same
17950 ;; category as before (i.e. not after the last position in that
17951 ;; category).
17952 (let ((pos (point)))
17953 ;; Stay before inserted string. `save-excursion' is of no use.
17954 (setq org-last-changed-timestamp
17955 (org-insert-time-stamp time with-hm inactive nil nil extra))
17956 (goto-char pos))
17957 (save-match-data
17958 (looking-at org-ts-regexp3)
17959 (goto-char
17960 (pcase origin-cat
17961 ;; `day' category ends before `hour' if any, or at the end
17962 ;; of the day name.
17963 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
17964 (`hour (min (match-end 7) origin))
17965 (`minute (min (1- (match-end 8)) origin))
17966 ((pred integerp) (min (1- (match-end 0)) origin))
17967 ;; Point was right after the time-stamp. However, the
17968 ;; time-stamp length might have changed, so refer to
17969 ;; (match-end 0) instead.
17970 (`after (match-end 0))
17971 ;; `year' and `month' have both fixed size: point couldn't
17972 ;; have moved into another part.
17973 (_ origin))))
17974 ;; Update clock if on a CLOCK line.
17975 (org-clock-update-time-maybe)
17976 ;; Maybe adjust the closest clock in `org-clock-history'
17977 (when org-clock-adjust-closest
17978 (if (not (and (org-at-clock-log-p)
17979 (< 1 (length (delq nil (mapcar 'marker-position
17980 org-clock-history))))))
17981 (message "No clock to adjust")
17982 (cond ((save-excursion ; fix previous clock?
17983 (re-search-backward org-ts-regexp0 nil t)
17984 (looking-back (concat org-clock-string " \\[")
17985 (line-beginning-position)))
17986 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
17987 ((save-excursion ; fix next clock?
17988 (re-search-backward org-ts-regexp0 nil t)
17989 (looking-at (concat org-ts-regexp0 "\\] =>")))
17990 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
17991 (save-window-excursion
17992 ;; Find closest clock to point, adjust the previous/next one in history
17993 (let* ((p (save-excursion (org-back-to-heading t)))
17994 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
17995 (clfixnth
17996 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
17997 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
17998 (if (not clfixpos)
17999 (message "No clock to adjust")
18000 (save-excursion
18001 (org-goto-marker-or-bmk clfixpos)
18002 (org-show-subtree)
18003 (when (re-search-forward clrgx nil t)
18004 (goto-char (match-beginning 1))
18005 (let (org-clock-adjust-closest)
18006 (org-timestamp-change n timestamp? updown))
18007 (message "Clock adjusted in %s for heading: %s"
18008 (file-name-nondirectory (buffer-file-name))
18009 (org-get-heading t t)))))))))
18010 ;; Try to recenter the calendar window, if any.
18011 (when (and org-calendar-follow-timestamp-change
18012 (get-buffer-window "*Calendar*" t)
18013 (memq timestamp? '(day month year)))
18014 (org-recenter-calendar (time-to-days time))))))
18016 (defun org-modify-ts-extra (s pos n dm)
18017 "Change the different parts of the lead-time and repeat fields in timestamp."
18018 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18019 ng h m new rem)
18020 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18021 (cond
18022 ((or (org-pos-in-match-range pos 2)
18023 (org-pos-in-match-range pos 3))
18024 (setq m (string-to-number (match-string 3 s))
18025 h (string-to-number (match-string 2 s)))
18026 (if (org-pos-in-match-range pos 2)
18027 (setq h (+ h n))
18028 (setq n (* dm (with-no-warnings (signum n))))
18029 (unless (= 0 (setq rem (% m dm)))
18030 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18031 (setq m (+ m n)))
18032 (when (< m 0) (setq m (+ m 60) h (1- h)))
18033 (when (> m 59) (setq m (- m 60) h (1+ h)))
18034 (setq h (mod h 24))
18035 (setq ng 1 new (format "-%02d:%02d" h m)))
18036 ((org-pos-in-match-range pos 6)
18037 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18038 ((org-pos-in-match-range pos 5)
18039 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18041 ((org-pos-in-match-range pos 9)
18042 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18043 ((org-pos-in-match-range pos 8)
18044 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18046 (when ng
18047 (setq s (concat
18048 (substring s 0 (match-beginning ng))
18050 (substring s (match-end ng))))))
18053 (defun org-recenter-calendar (d)
18054 "If the calendar is visible, recenter it to date D."
18055 (let ((cwin (get-buffer-window "*Calendar*" t)))
18056 (when cwin
18057 (let ((calendar-move-hook nil))
18058 (with-selected-window cwin
18059 (calendar-goto-date
18060 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18062 (defun org-goto-calendar (&optional arg)
18063 "Go to the Emacs calendar at the current date.
18064 If there is a time stamp in the current line, go to that date.
18065 A prefix ARG can be used to force the current date."
18066 (interactive "P")
18067 (let ((calendar-move-hook nil)
18068 (calendar-view-holidays-initially-flag nil)
18069 (calendar-view-diary-initially-flag nil)
18070 diff)
18071 (when (or (org-at-timestamp-p 'lax)
18072 (org-match-line (concat ".*" org-ts-regexp)))
18073 (let ((d1 (time-to-days (current-time)))
18074 (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
18075 (setq diff (- d2 d1))))
18076 (calendar)
18077 (calendar-goto-today)
18078 (when (and diff (not arg)) (calendar-forward-day diff))))
18080 (defun org-get-date-from-calendar ()
18081 "Return a list (month day year) of date at point in calendar."
18082 (with-current-buffer "*Calendar*"
18083 (save-match-data
18084 (calendar-cursor-to-date))))
18086 (defun org-date-from-calendar ()
18087 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18088 If there is already a time stamp at the cursor position, update it."
18089 (interactive)
18090 (if (org-at-timestamp-p 'lax)
18091 (org-timestamp-change 0 'calendar)
18092 (let ((cal-date (org-get-date-from-calendar)))
18093 (org-insert-time-stamp
18094 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18096 (defcustom org-effort-durations
18097 `(("min" . 1)
18098 ("h" . 60)
18099 ("d" . ,(* 60 8))
18100 ("w" . ,(* 60 8 5))
18101 ("m" . ,(* 60 8 5 4))
18102 ("y" . ,(* 60 8 5 40)))
18103 "Conversion factor to minutes for an effort modifier.
18105 Each entry has the form (MODIFIER . MINUTES).
18107 In an effort string, a number followed by MODIFIER is multiplied
18108 by the specified number of MINUTES to obtain an effort in
18109 minutes.
18111 For example, if the value of this variable is ((\"hours\" . 60)), then an
18112 effort string \"2hours\" is equivalent to 120 minutes."
18113 :group 'org-agenda
18114 :version "26.1"
18115 :package-version '(Org . "8.3")
18116 :type '(alist :key-type (string :tag "Modifier")
18117 :value-type (number :tag "Minutes")))
18119 (defcustom org-image-actual-width t
18120 "Should we use the actual width of images when inlining them?
18122 When set to t, always use the image width.
18124 When set to a number, use imagemagick (when available) to set
18125 the image's width to this value.
18127 When set to a number in a list, try to get the width from any
18128 #+ATTR.* keyword if it matches a width specification like
18130 #+ATTR_HTML: :width 300px
18132 and fall back on that number if none is found.
18134 When set to nil, try to get the width from an #+ATTR.* keyword
18135 and fall back on the original width if none is found.
18137 This requires Emacs >= 24.1, build with imagemagick support."
18138 :group 'org-appearance
18139 :version "24.4"
18140 :package-version '(Org . "8.0")
18141 :type '(choice
18142 (const :tag "Use the image width" t)
18143 (integer :tag "Use a number of pixels")
18144 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18145 (const :tag "Use #+ATTR* or don't resize" nil)))
18147 (defcustom org-agenda-inhibit-startup nil
18148 "Inhibit startup when preparing agenda buffers.
18149 When this variable is t, the initialization of the Org agenda
18150 buffers is inhibited: e.g. the visibility state is not set, the
18151 tables are not re-aligned, etc."
18152 :type 'boolean
18153 :version "24.3"
18154 :group 'org-agenda)
18156 (defcustom org-agenda-ignore-properties nil
18157 "Avoid updating text properties when building the agenda.
18158 Properties are used to prepare buffers for effort estimates,
18159 appointments, statistics and subtree-local categories.
18160 If you don't use these in the agenda, you can add them to this
18161 list and agenda building will be a bit faster.
18162 The value is a list, with zero or more of the symbols `effort', `appt',
18163 `stats' or `category'."
18164 :type '(set :greedy t
18165 (const effort)
18166 (const appt)
18167 (const stats)
18168 (const category))
18169 :version "26.1"
18170 :package-version '(Org . "8.3")
18171 :group 'org-agenda)
18173 ;;;; Files
18175 (defun org-save-all-org-buffers ()
18176 "Save all Org buffers without user confirmation."
18177 (interactive)
18178 (message "Saving all Org buffers...")
18179 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18180 (when (featurep 'org-id) (org-id-locations-save))
18181 (message "Saving all Org buffers... done"))
18183 (defun org-revert-all-org-buffers ()
18184 "Revert all Org buffers.
18185 Prompt for confirmation when there are unsaved changes.
18186 Be sure you know what you are doing before letting this function
18187 overwrite your changes.
18189 This function is useful in a setup where one tracks org files
18190 with a version control system, to revert on one machine after pulling
18191 changes from another. I believe the procedure must be like this:
18193 1. M-x org-save-all-org-buffers
18194 2. Pull changes from the other machine, resolve conflicts
18195 3. M-x org-revert-all-org-buffers"
18196 (interactive)
18197 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18198 (user-error "Abort"))
18199 (save-excursion
18200 (save-window-excursion
18201 (dolist (b (buffer-list))
18202 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18203 (with-current-buffer b buffer-file-name))
18204 (pop-to-buffer-same-window b)
18205 (revert-buffer t 'no-confirm)))
18206 (when (and (featurep 'org-id) org-id-track-globally)
18207 (org-id-locations-load)))))
18209 ;;;; Agenda files
18211 ;;;###autoload
18212 (defun org-switchb (&optional arg)
18213 "Switch between Org buffers.
18215 With `\\[universal-argument]' prefix, restrict available buffers to files.
18217 With `\\[universal-argument] \\[universal-argument]' \
18218 prefix, restrict available buffers to agenda files."
18219 (interactive "P")
18220 (let ((blist (org-buffer-list
18221 (cond ((equal arg '(4)) 'files)
18222 ((equal arg '(16)) 'agenda)))))
18223 (pop-to-buffer-same-window
18224 (completing-read "Org buffer: "
18225 (mapcar #'list (mapcar #'buffer-name blist))
18226 nil t))))
18228 (defun org-buffer-list (&optional predicate exclude-tmp)
18229 "Return a list of Org buffers.
18230 PREDICATE can be `export', `files' or `agenda'.
18232 export restrict the list to Export buffers.
18233 files restrict the list to buffers visiting Org files.
18234 agenda restrict the list to buffers visiting agenda files.
18236 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18237 (let* ((bfn nil)
18238 (agenda-files (and (eq predicate 'agenda)
18239 (mapcar 'file-truename (org-agenda-files t))))
18240 (filter
18241 (cond
18242 ((eq predicate 'files)
18243 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18244 ((eq predicate 'export)
18245 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18246 ((eq predicate 'agenda)
18247 (lambda (b)
18248 (with-current-buffer b
18249 (and (derived-mode-p 'org-mode)
18250 (setq bfn (buffer-file-name b))
18251 (member (file-truename bfn) agenda-files)))))
18252 (t (lambda (b) (with-current-buffer b
18253 (or (derived-mode-p 'org-mode)
18254 (string-match "\\*Org .*Export"
18255 (buffer-name b)))))))))
18256 (delq nil
18257 (mapcar
18258 (lambda(b)
18259 (if (and (funcall filter b)
18260 (or (not exclude-tmp)
18261 (not (string-match "tmp" (buffer-name b)))))
18263 nil))
18264 (buffer-list)))))
18266 (defun org-agenda-files (&optional unrestricted archives)
18267 "Get the list of agenda files.
18268 Optional UNRESTRICTED means return the full list even if a restriction
18269 is currently in place.
18270 When ARCHIVES is t, include all archive files that are really being
18271 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18272 `org-agenda-archives-mode' is t."
18273 (let ((files
18274 (cond
18275 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18276 ((stringp org-agenda-files) (org-read-agenda-file-list))
18277 ((listp org-agenda-files) org-agenda-files)
18278 (t (error "Invalid value of `org-agenda-files'")))))
18279 (setq files (apply 'append
18280 (mapcar (lambda (f)
18281 (if (file-directory-p f)
18282 (directory-files
18283 f t org-agenda-file-regexp)
18284 (list f)))
18285 files)))
18286 (when org-agenda-skip-unavailable-files
18287 (setq files (delq nil
18288 (mapcar (function
18289 (lambda (file)
18290 (and (file-readable-p file) file)))
18291 files))))
18292 (when (or (eq archives t)
18293 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18294 (setq files (org-add-archive-files files)))
18295 files))
18297 (defun org-agenda-file-p (&optional file)
18298 "Return non-nil, if FILE is an agenda file.
18299 If FILE is omitted, use the file associated with the current
18300 buffer."
18301 (let ((fname (or file (buffer-file-name))))
18302 (and fname
18303 (member (file-truename fname)
18304 (mapcar #'file-truename (org-agenda-files t))))))
18306 (defun org-edit-agenda-file-list ()
18307 "Edit the list of agenda files.
18308 Depending on setup, this either uses customize to edit the variable
18309 `org-agenda-files', or it visits the file that is holding the list. In the
18310 latter case, the buffer is set up in a way that saving it automatically kills
18311 the buffer and restores the previous window configuration."
18312 (interactive)
18313 (if (stringp org-agenda-files)
18314 (let ((cw (current-window-configuration)))
18315 (find-file org-agenda-files)
18316 (setq-local org-window-configuration cw)
18317 (add-hook 'after-save-hook
18318 (lambda ()
18319 (set-window-configuration
18320 (prog1 org-window-configuration
18321 (kill-buffer (current-buffer))))
18322 (org-install-agenda-files-menu)
18323 (message "New agenda file list installed"))
18324 nil 'local)
18325 (message "%s" (substitute-command-keys
18326 "Edit list and finish with \\[save-buffer]")))
18327 (customize-variable 'org-agenda-files)))
18329 (defun org-store-new-agenda-file-list (list)
18330 "Set new value for the agenda file list and save it correctly."
18331 (if (stringp org-agenda-files)
18332 (let ((fe (org-read-agenda-file-list t)) b u)
18333 (while (setq b (find-buffer-visiting org-agenda-files))
18334 (kill-buffer b))
18335 (with-temp-file org-agenda-files
18336 (insert
18337 (mapconcat
18338 (lambda (f) ;; Keep un-expanded entries.
18339 (if (setq u (assoc f fe))
18340 (cdr u)
18342 list "\n")
18343 "\n")))
18344 (let ((org-mode-hook nil) (org-inhibit-startup t)
18345 (org-insert-mode-line-in-empty-file nil))
18346 (setq org-agenda-files list)
18347 (customize-save-variable 'org-agenda-files org-agenda-files))))
18349 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18350 "Read the list of agenda files from a file.
18351 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18352 filenames, used by `org-store-new-agenda-file-list' to write back
18353 un-expanded file names."
18354 (when (file-directory-p org-agenda-files)
18355 (error "`org-agenda-files' cannot be a single directory"))
18356 (when (stringp org-agenda-files)
18357 (with-temp-buffer
18358 (insert-file-contents org-agenda-files)
18359 (mapcar
18360 (lambda (f)
18361 (let ((e (expand-file-name (substitute-in-file-name f)
18362 org-directory)))
18363 (if pair-with-expansion
18364 (cons e f)
18365 e)))
18366 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18368 ;;;###autoload
18369 (defun org-cycle-agenda-files ()
18370 "Cycle through the files in `org-agenda-files'.
18371 If the current buffer visits an agenda file, find the next one in the list.
18372 If the current buffer does not, find the first agenda file."
18373 (interactive)
18374 (let* ((fs (or (org-agenda-files t)
18375 (user-error "No agenda files")))
18376 (files (copy-sequence fs))
18377 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18378 file)
18379 (when tcf
18380 (while (and (setq file (pop files))
18381 (not (equal (file-truename file) tcf)))))
18382 (find-file (car (or files fs)))
18383 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18385 (defun org-agenda-file-to-front (&optional to-end)
18386 "Move/add the current file to the top of the agenda file list.
18387 If the file is not present in the list, it is added to the front. If it is
18388 present, it is moved there. With optional argument TO-END, add/move to the
18389 end of the list."
18390 (interactive "P")
18391 (let ((org-agenda-skip-unavailable-files nil)
18392 (file-alist (mapcar (lambda (x)
18393 (cons (file-truename x) x))
18394 (org-agenda-files t)))
18395 (ctf (file-truename
18396 (or buffer-file-name
18397 (user-error "Please save the current buffer to a file"))))
18398 x had)
18399 (setq x (assoc ctf file-alist) had x)
18401 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18402 (if to-end
18403 (setq file-alist (append (delq x file-alist) (list x)))
18404 (setq file-alist (cons x (delq x file-alist))))
18405 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18406 (org-install-agenda-files-menu)
18407 (message "File %s to %s of agenda file list"
18408 (if had "moved" "added") (if to-end "end" "front"))))
18410 (defun org-remove-file (&optional file)
18411 "Remove current file from the list of files in variable `org-agenda-files'.
18412 These are the files which are being checked for agenda entries.
18413 Optional argument FILE means use this file instead of the current."
18414 (interactive)
18415 (let* ((org-agenda-skip-unavailable-files nil)
18416 (file (or file buffer-file-name
18417 (user-error "Current buffer does not visit a file")))
18418 (true-file (file-truename file))
18419 (afile (abbreviate-file-name file))
18420 (files (delq nil (mapcar
18421 (lambda (x)
18422 (unless (equal true-file
18423 (file-truename x))
18425 (org-agenda-files t)))))
18426 (if (not (= (length files) (length (org-agenda-files t))))
18427 (progn
18428 (org-store-new-agenda-file-list files)
18429 (org-install-agenda-files-menu)
18430 (message "Removed from Org Agenda list: %s" afile))
18431 (message "File was not in list: %s (not removed)" afile))))
18433 (defun org-file-menu-entry (file)
18434 (vector file (list 'find-file file) t))
18436 (defun org-check-agenda-file (file)
18437 "Make sure FILE exists. If not, ask user what to do."
18438 (unless (file-exists-p file)
18439 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18440 (abbreviate-file-name file))
18441 (let ((r (downcase (read-char-exclusive))))
18442 (cond
18443 ((equal r ?r)
18444 (org-remove-file file)
18445 (throw 'nextfile t))
18446 (t (user-error "Abort"))))))
18448 (defun org-get-agenda-file-buffer (file)
18449 "Get an agenda buffer visiting FILE.
18450 If the buffer needs to be created, add it to the list of buffers
18451 which might be released later."
18452 (let ((buf (org-find-base-buffer-visiting file)))
18453 (if buf
18454 buf ; just return it
18455 ;; Make a new buffer and remember it
18456 (setq buf (find-file-noselect file))
18457 (when buf (push buf org-agenda-new-buffers))
18458 buf)))
18460 (defun org-release-buffers (blist)
18461 "Release all buffers in list, asking the user for confirmation when needed.
18462 When a buffer is unmodified, it is just killed. When modified, it is saved
18463 \(if the user agrees) and then killed."
18464 (let (file)
18465 (dolist (buf blist)
18466 (setq file (buffer-file-name buf))
18467 (when (and (buffer-modified-p buf)
18468 file
18469 (y-or-n-p (format "Save file %s? " file)))
18470 (with-current-buffer buf (save-buffer)))
18471 (kill-buffer buf))))
18473 (defun org-agenda-prepare-buffers (files)
18474 "Create buffers for all agenda files, protect archived trees and comments."
18475 (interactive)
18476 (let ((pa '(:org-archived t))
18477 (pc '(:org-comment t))
18478 (pall '(:org-archived t :org-comment t))
18479 (inhibit-read-only t)
18480 (org-inhibit-startup org-agenda-inhibit-startup)
18481 (rea (concat ":" org-archive-tag ":"))
18482 re pos)
18483 (setq org-tag-alist-for-agenda nil
18484 org-tag-groups-alist-for-agenda nil)
18485 (save-excursion
18486 (save-restriction
18487 (dolist (file files)
18488 (catch 'nextfile
18489 (if (bufferp file)
18490 (set-buffer file)
18491 (org-check-agenda-file file)
18492 (set-buffer (org-get-agenda-file-buffer file)))
18493 (widen)
18494 (org-set-regexps-and-options 'tags-only)
18495 (setq pos (point))
18496 (or (memq 'category org-agenda-ignore-properties)
18497 (org-refresh-category-properties))
18498 (or (memq 'stats org-agenda-ignore-properties)
18499 (org-refresh-stats-properties))
18500 (or (memq 'effort org-agenda-ignore-properties)
18501 (org-refresh-effort-properties))
18502 (or (memq 'appt org-agenda-ignore-properties)
18503 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18504 (setq org-todo-keywords-for-agenda
18505 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18506 (setq org-done-keywords-for-agenda
18507 (append org-done-keywords-for-agenda org-done-keywords))
18508 (setq org-todo-keyword-alist-for-agenda
18509 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18510 (setq org-tag-alist-for-agenda
18511 (org-uniquify
18512 (append org-tag-alist-for-agenda
18513 org-current-tag-alist)))
18514 ;; Merge current file's tag groups into global
18515 ;; `org-tag-groups-alist-for-agenda'.
18516 (when org-group-tags
18517 (dolist (alist org-tag-groups-alist)
18518 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18519 (if old
18520 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18521 (push alist org-tag-groups-alist-for-agenda)))))
18522 (org-with-silent-modifications
18523 (save-excursion
18524 (remove-text-properties (point-min) (point-max) pall)
18525 (when org-agenda-skip-archived-trees
18526 (goto-char (point-min))
18527 (while (re-search-forward rea nil t)
18528 (when (org-at-heading-p t)
18529 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18530 (goto-char (point-min))
18531 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18532 (while (re-search-forward re nil t)
18533 (when (save-match-data (org-in-commented-heading-p t))
18534 (add-text-properties
18535 (match-beginning 0) (org-end-of-subtree t) pc)))))
18536 (goto-char pos)))))
18537 (setq org-todo-keywords-for-agenda
18538 (org-uniquify org-todo-keywords-for-agenda))
18539 (setq org-todo-keyword-alist-for-agenda
18540 (org-uniquify org-todo-keyword-alist-for-agenda))))
18543 ;;;; CDLaTeX minor mode
18545 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18546 "Keymap for the minor `org-cdlatex-mode'.")
18548 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18549 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18550 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18551 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18552 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18554 (defvar org-cdlatex-texmathp-advice-is-done nil
18555 "Flag remembering if we have applied the advice to texmathp already.")
18557 (define-minor-mode org-cdlatex-mode
18558 "Toggle the minor `org-cdlatex-mode'.
18559 This mode supports entering LaTeX environment and math in LaTeX fragments
18560 in Org mode.
18561 \\{org-cdlatex-mode-map}"
18562 nil " OCDL" nil
18563 (when org-cdlatex-mode
18564 (require 'cdlatex)
18565 (run-hooks 'cdlatex-mode-hook)
18566 (cdlatex-compute-tables))
18567 (unless org-cdlatex-texmathp-advice-is-done
18568 (setq org-cdlatex-texmathp-advice-is-done t)
18569 (defadvice texmathp (around org-math-always-on activate)
18570 "Always return t in Org buffers.
18571 This is because we want to insert math symbols without dollars even outside
18572 the LaTeX math segments. If Org mode thinks that point is actually inside
18573 an embedded LaTeX fragment, let `texmathp' do its job.
18574 `\\[org-cdlatex-mode-map]'"
18575 (interactive)
18576 (let (p)
18577 (cond
18578 ((not (derived-mode-p 'org-mode)) ad-do-it)
18579 ((eq this-command 'cdlatex-math-symbol)
18580 (setq ad-return-value t
18581 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18583 (let ((p (org-inside-LaTeX-fragment-p)))
18584 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18585 (setq ad-return-value t
18586 texmathp-why '("Org mode embedded math" . 0))
18587 (when p ad-do-it)))))))))
18589 (defun turn-on-org-cdlatex ()
18590 "Unconditionally turn on `org-cdlatex-mode'."
18591 (org-cdlatex-mode 1))
18593 (defun org-try-cdlatex-tab ()
18594 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18595 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18596 - inside a LaTeX fragment, or
18597 - after the first word in a line, where an abbreviation expansion could
18598 insert a LaTeX environment."
18599 (when org-cdlatex-mode
18600 (cond
18601 ;; Before any word on the line: No expansion possible.
18602 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18603 ;; Just after first word on the line: Expand it. Make sure it
18604 ;; cannot happen on headlines, though.
18605 ((save-excursion
18606 (skip-chars-backward "a-zA-Z0-9*")
18607 (skip-chars-backward " \t")
18608 (and (bolp) (not (org-at-heading-p))))
18609 (cdlatex-tab) t)
18610 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18612 (defun org-cdlatex-underscore-caret (&optional _arg)
18613 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18614 Revert to the normal definition outside of these fragments."
18615 (interactive "P")
18616 (if (org-inside-LaTeX-fragment-p)
18617 (call-interactively 'cdlatex-sub-superscript)
18618 (let (org-cdlatex-mode)
18619 (call-interactively (key-binding (vector last-input-event))))))
18621 (defun org-cdlatex-math-modify (&optional _arg)
18622 "Execute `cdlatex-math-modify' in LaTeX fragments.
18623 Revert to the normal definition outside of these fragments."
18624 (interactive "P")
18625 (if (org-inside-LaTeX-fragment-p)
18626 (call-interactively 'cdlatex-math-modify)
18627 (let (org-cdlatex-mode)
18628 (call-interactively (key-binding (vector last-input-event))))))
18630 (defun org-cdlatex-environment-indent (&optional environment item)
18631 "Execute `cdlatex-environment' and indent the inserted environment.
18633 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18635 The inserted environment is indented to current indentation
18636 unless point is at the beginning of the line, in which the
18637 environment remains unintended."
18638 (interactive)
18639 ;; cdlatex-environment always return nil. Therefore, capture output
18640 ;; first and determine if an environment was selected.
18641 (let* ((beg (point-marker))
18642 (end (copy-marker (point) t))
18643 (inserted (progn
18644 (ignore-errors (cdlatex-environment environment item))
18645 (< beg end)))
18646 ;; Figure out how many lines to move forward after the
18647 ;; environment has been inserted.
18648 (lines (when inserted
18649 (save-excursion
18650 (- (cl-loop while (< beg (point))
18651 with x = 0
18652 do (forward-line -1)
18653 (cl-incf x)
18654 finally return x)
18655 (if (progn (goto-char beg)
18656 (and (progn (skip-chars-forward " \t") (eolp))
18657 (progn (skip-chars-backward " \t") (bolp))))
18658 1 0)))))
18659 (env (org-trim (delete-and-extract-region beg end))))
18660 (when inserted
18661 ;; Get indentation of next line unless at column 0.
18662 (let ((ind (if (bolp) 0
18663 (save-excursion
18664 (org-return-indent)
18665 (prog1 (org-get-indentation)
18666 (when (progn (skip-chars-forward " \t") (eolp))
18667 (delete-region beg (point)))))))
18668 (bol (progn (skip-chars-backward " \t") (bolp))))
18669 ;; Insert a newline before environment unless at column zero
18670 ;; to "escape" the current line. Insert a newline if
18671 ;; something is one the same line as \end{ENVIRONMENT}.
18672 (insert
18673 (concat (unless bol "\n") env
18674 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18675 (unless (zerop ind)
18676 (save-excursion
18677 (goto-char beg)
18678 (while (< (point) end)
18679 (unless (eolp) (indent-line-to ind))
18680 (forward-line))))
18681 (goto-char beg)
18682 (forward-line lines)
18683 (indent-line-to ind)))
18684 (set-marker beg nil)
18685 (set-marker end nil)))
18688 ;;;; LaTeX fragments
18690 (defun org-inside-LaTeX-fragment-p ()
18691 "Test if point is inside a LaTeX fragment.
18692 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18693 sequence appearing also before point.
18694 Even though the matchers for math are configurable, this function assumes
18695 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18696 delimiters are skipped when they have been removed by customization.
18697 The return value is nil, or a cons cell with the delimiter and the
18698 position of this delimiter.
18700 This function does a reasonably good job, but can locally be fooled by
18701 for example currency specifications. For example it will assume being in
18702 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18703 fragments that are properly closed, but during editing, we have to live
18704 with the uncertainty caused by missing closing delimiters. This function
18705 looks only before point, not after."
18706 (catch 'exit
18707 (let ((pos (point))
18708 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18709 (lim (save-excursion (org-backward-paragraph) (point)))
18710 dd-on str (start 0) m re)
18711 (goto-char pos)
18712 (when dodollar
18713 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18714 re (nth 1 (assoc "$" org-latex-regexps)))
18715 (while (string-match re str start)
18716 (cond
18717 ((= (match-end 0) (length str))
18718 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18719 ((= (match-end 0) (- (length str) 5))
18720 (throw 'exit nil))
18721 (t (setq start (match-end 0))))))
18722 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18723 (goto-char pos)
18724 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18725 (and (match-beginning 2) (throw 'exit nil))
18726 ;; count $$
18727 (while (re-search-backward "\\$\\$" lim t)
18728 (setq dd-on (not dd-on)))
18729 (goto-char pos)
18730 (when dd-on (cons "$$" m))))))
18732 (defun org-inside-latex-macro-p ()
18733 "Is point inside a LaTeX macro or its arguments?"
18734 (save-match-data
18735 (org-in-regexp
18736 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18738 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
18739 "Build an overlay between BEG and END using IMAGE file.
18740 Argument IMAGETYPE is the extension of the displayed image,
18741 as a string. It defaults to \"png\"."
18742 (let ((ov (make-overlay beg end))
18743 (imagetype (or (intern imagetype) 'png)))
18744 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18745 (overlay-put ov 'evaporate t)
18746 (overlay-put ov
18747 'modification-hooks
18748 (list (lambda (o _flag _beg _end &optional _l)
18749 (delete-overlay o))))
18750 (overlay-put ov
18751 'display
18752 (list 'image :type imagetype :file image :ascent 'center))))
18754 (defun org--list-latex-overlays (&optional beg end)
18755 "List all Org LaTeX overlays in current buffer.
18756 Limit to overlays between BEG and END when those are provided."
18757 (cl-remove-if-not
18758 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18759 (overlays-in (or beg (point-min)) (or end (point-max)))))
18761 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18762 "Remove all overlays with LaTeX fragment images in current buffer.
18763 When optional arguments BEG and END are non-nil, remove all
18764 overlays between them instead. Return a non-nil value when some
18765 overlays were removed, nil otherwise."
18766 (let ((overlays (org--list-latex-overlays beg end)))
18767 (mapc #'delete-overlay overlays)
18768 overlays))
18770 (defun org-toggle-latex-fragment (&optional arg)
18771 "Preview the LaTeX fragment at point, or all locally or globally.
18773 If the cursor is on a LaTeX fragment, create the image and overlay
18774 it over the source code, if there is none. Remove it otherwise.
18775 If there is no fragment at point, display all fragments in the
18776 current section.
18778 With prefix ARG, preview or clear image for all fragments in the
18779 current subtree or in the whole buffer when used before the first
18780 headline. With a prefix ARG `\\[universal-argument] \
18781 \\[universal-argument]' preview or clear images
18782 for all fragments in the buffer."
18783 (interactive "P")
18784 (when (display-graphic-p)
18785 (catch 'exit
18786 (save-excursion
18787 (let (beg end msg)
18788 (cond
18789 ((or (equal arg '(16))
18790 (and (equal arg '(4))
18791 (org-with-limited-levels (org-before-first-heading-p))))
18792 (if (org-remove-latex-fragment-image-overlays)
18793 (progn (message "LaTeX fragments images removed from buffer")
18794 (throw 'exit nil))
18795 (setq msg "Creating images for buffer...")))
18796 ((equal arg '(4))
18797 (org-with-limited-levels (org-back-to-heading t))
18798 (setq beg (point))
18799 (setq end (progn (org-end-of-subtree t) (point)))
18800 (if (org-remove-latex-fragment-image-overlays beg end)
18801 (progn
18802 (message "LaTeX fragment images removed from subtree")
18803 (throw 'exit nil))
18804 (setq msg "Creating images for subtree...")))
18805 ((let ((datum (org-element-context)))
18806 (when (memq (org-element-type datum)
18807 '(latex-environment latex-fragment))
18808 (setq beg (org-element-property :begin datum))
18809 (setq end (org-element-property :end datum))
18810 (if (org-remove-latex-fragment-image-overlays beg end)
18811 (progn (message "LaTeX fragment image removed")
18812 (throw 'exit nil))
18813 (setq msg "Creating image...")))))
18815 (org-with-limited-levels
18816 (setq beg (if (org-at-heading-p) (line-beginning-position)
18817 (outline-previous-heading)
18818 (point)))
18819 (setq end (progn (outline-next-heading) (point)))
18820 (if (org-remove-latex-fragment-image-overlays beg end)
18821 (progn
18822 (message "LaTeX fragment images removed from section")
18823 (throw 'exit nil))
18824 (setq msg "Creating images for section...")))))
18825 (let ((file (buffer-file-name (buffer-base-buffer))))
18826 (org-format-latex
18827 (concat org-preview-latex-image-directory "org-ltximg")
18828 beg end
18829 ;; Emacs cannot overlay images from remote hosts. Create
18830 ;; it in `temporary-file-directory' instead.
18831 (if (or (not file) (file-remote-p file))
18832 temporary-file-directory
18833 default-directory)
18834 'overlays msg 'forbuffer org-preview-latex-default-process))
18835 (message (concat msg "done")))))))
18837 (defun org-format-latex
18838 (prefix &optional beg end dir overlays msg forbuffer processing-type)
18839 "Replace LaTeX fragments with links to an image.
18841 The function takes care of creating the replacement image.
18843 Only consider fragments between BEG and END when those are
18844 provided.
18846 When optional argument OVERLAYS is non-nil, display the image on
18847 top of the fragment instead of replacing it.
18849 PROCESSING-TYPE is the conversion method to use, as a symbol.
18851 Some of the options can be changed using the variable
18852 `org-format-latex-options', which see."
18853 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
18854 (unless (eq processing-type 'verbatim)
18855 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
18856 (cnt 0)
18857 checkdir-flag)
18858 (goto-char (or beg (point-min)))
18859 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
18860 (when (and overlays (memq processing-type '(dvipng imagemagick)))
18861 (overlay-recenter (or end (point-max))))
18862 (while (re-search-forward math-regexp end t)
18863 (unless (and overlays
18864 (eq (get-char-property (point) 'org-overlay-type)
18865 'org-latex-overlay))
18866 (let* ((context (org-element-context))
18867 (type (org-element-type context)))
18868 (when (memq type '(latex-environment latex-fragment))
18869 (let ((block-type (eq type 'latex-environment))
18870 (value (org-element-property :value context))
18871 (beg (org-element-property :begin context))
18872 (end (save-excursion
18873 (goto-char (org-element-property :end context))
18874 (skip-chars-backward " \r\t\n")
18875 (point))))
18876 (cond
18877 ((eq processing-type 'mathjax)
18878 ;; Prepare for MathJax processing.
18879 (if (not (string-match "\\`\\$\\$?" value))
18880 (goto-char end)
18881 (delete-region beg end)
18882 (if (string= (match-string 0 value) "$$")
18883 (insert "\\[" (substring value 2 -2) "\\]")
18884 (insert "\\(" (substring value 1 -1) "\\)"))))
18885 ((assq processing-type org-preview-latex-process-alist)
18886 ;; Process to an image.
18887 (cl-incf cnt)
18888 (goto-char beg)
18889 (let* ((processing-info
18890 (cdr (assq processing-type org-preview-latex-process-alist)))
18891 (face (face-at-point))
18892 ;; Get the colors from the face at point.
18894 (let ((color (plist-get org-format-latex-options
18895 :foreground)))
18896 (if (and forbuffer (eq color 'auto))
18897 (face-attribute face :foreground nil 'default)
18898 color)))
18900 (let ((color (plist-get org-format-latex-options
18901 :background)))
18902 (if (and forbuffer (eq color 'auto))
18903 (face-attribute face :background nil 'default)
18904 color)))
18905 (hash (sha1 (prin1-to-string
18906 (list org-format-latex-header
18907 org-latex-default-packages-alist
18908 org-latex-packages-alist
18909 org-format-latex-options
18910 forbuffer value fg bg))))
18911 (imagetype (or (plist-get processing-info :image-output-type) "png"))
18912 (absprefix (expand-file-name prefix dir))
18913 (linkfile (format "%s_%s.%s" prefix hash imagetype))
18914 (movefile (format "%s_%s.%s" absprefix hash imagetype))
18915 (sep (and block-type "\n\n"))
18916 (link (concat sep "[[file:" linkfile "]]" sep))
18917 (options
18918 (org-combine-plists
18919 org-format-latex-options
18920 `(:foreground ,fg :background ,bg))))
18921 (when msg (message msg cnt))
18922 (unless checkdir-flag ; Ensure the directory exists.
18923 (setq checkdir-flag t)
18924 (let ((todir (file-name-directory absprefix)))
18925 (unless (file-directory-p todir)
18926 (make-directory todir t))))
18927 (unless (file-exists-p movefile)
18928 (org-create-formula-image
18929 value movefile options forbuffer processing-type))
18930 (if overlays
18931 (progn
18932 (dolist (o (overlays-in beg end))
18933 (when (eq (overlay-get o 'org-overlay-type)
18934 'org-latex-overlay)
18935 (delete-overlay o)))
18936 (org--format-latex-make-overlay beg end movefile imagetype)
18937 (goto-char end))
18938 (delete-region beg end)
18939 (insert
18940 (org-add-props link
18941 (list 'org-latex-src
18942 (replace-regexp-in-string "\"" "" value)
18943 'org-latex-src-embed-type
18944 (if block-type 'paragraph 'character)))))))
18945 ((eq processing-type 'mathml)
18946 ;; Process to MathML.
18947 (unless (org-format-latex-mathml-available-p)
18948 (user-error "LaTeX to MathML converter not configured"))
18949 (cl-incf cnt)
18950 (when msg (message msg cnt))
18951 (goto-char beg)
18952 (delete-region beg end)
18953 (insert (org-format-latex-as-mathml
18954 value block-type prefix dir)))
18956 (error "Unknown conversion process %s for LaTeX fragments"
18957 processing-type)))))))))))
18959 (defun org-create-math-formula (latex-frag &optional mathml-file)
18960 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
18961 Use `org-latex-to-mathml-convert-command'. If the conversion is
18962 sucessful, return the portion between \"<math...> </math>\"
18963 elements otherwise return nil. When MATHML-FILE is specified,
18964 write the results in to that file. When invoked as an
18965 interactive command, prompt for LATEX-FRAG, with initial value
18966 set to the current active region and echo the results for user
18967 inspection."
18968 (interactive (list (let ((frag (when (org-region-active-p)
18969 (buffer-substring-no-properties
18970 (region-beginning) (region-end)))))
18971 (read-string "LaTeX Fragment: " frag nil frag))))
18972 (unless latex-frag (user-error "Invalid LaTeX fragment"))
18973 (let* ((tmp-in-file
18974 (let ((file (file-relative-name
18975 (make-temp-name (expand-file-name "ltxmathml-in")))))
18976 (write-region latex-frag nil file)
18977 file))
18978 (tmp-out-file (file-relative-name
18979 (make-temp-name (expand-file-name "ltxmathml-out"))))
18980 (cmd (format-spec
18981 org-latex-to-mathml-convert-command
18982 `((?j . ,(and org-latex-to-mathml-jar-file
18983 (shell-quote-argument
18984 (expand-file-name
18985 org-latex-to-mathml-jar-file))))
18986 (?I . ,(shell-quote-argument tmp-in-file))
18987 (?i . ,latex-frag)
18988 (?o . ,(shell-quote-argument tmp-out-file)))))
18989 mathml shell-command-output)
18990 (when (called-interactively-p 'any)
18991 (unless (org-format-latex-mathml-available-p)
18992 (user-error "LaTeX to MathML converter not configured")))
18993 (message "Running %s" cmd)
18994 (setq shell-command-output (shell-command-to-string cmd))
18995 (setq mathml
18996 (when (file-readable-p tmp-out-file)
18997 (with-current-buffer (find-file-noselect tmp-out-file t)
18998 (goto-char (point-min))
18999 (when (re-search-forward
19000 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19001 (regexp-quote
19002 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19003 nil t)
19004 (prog1 (match-string 0) (kill-buffer))))))
19005 (cond
19006 (mathml
19007 (setq mathml
19008 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19009 (when mathml-file
19010 (write-region mathml nil mathml-file))
19011 (when (called-interactively-p 'any)
19012 (message mathml)))
19013 ((message "LaTeX to MathML conversion failed")
19014 (message shell-command-output)))
19015 (delete-file tmp-in-file)
19016 (when (file-exists-p tmp-out-file)
19017 (delete-file tmp-out-file))
19018 mathml))
19020 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19021 prefix &optional dir)
19022 "Use `org-create-math-formula' but check local cache first."
19023 (let* ((absprefix (expand-file-name prefix dir))
19024 (print-length nil) (print-level nil)
19025 (formula-id (concat
19026 "formula-"
19027 (sha1
19028 (prin1-to-string
19029 (list latex-frag
19030 org-latex-to-mathml-convert-command)))))
19031 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19032 (formula-cache-dir (file-name-directory formula-cache)))
19034 (unless (file-directory-p formula-cache-dir)
19035 (make-directory formula-cache-dir t))
19037 (unless (file-exists-p formula-cache)
19038 (org-create-math-formula latex-frag formula-cache))
19040 (if (file-exists-p formula-cache)
19041 ;; Successful conversion. Return the link to MathML file.
19042 (org-add-props
19043 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19044 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19045 'org-latex-src-embed-type (if latex-frag-type
19046 'paragraph 'character)))
19047 ;; Failed conversion. Return the LaTeX fragment verbatim
19048 latex-frag)))
19050 (defun org--get-display-dpi ()
19051 "Get the DPI of the display.
19052 The function assumes that the display has the same pixel width in
19053 the horizontal and vertical directions."
19054 (if (display-graphic-p)
19055 (round (/ (display-pixel-height)
19056 (/ (display-mm-height) 25.4)))
19057 (error "Attempt to calculate the dpi of a non-graphic display")))
19059 (defun org-create-formula-image
19060 (string tofile options buffer &optional processing-type)
19061 "Create an image from LaTeX source using external processes.
19063 The LaTeX STRING is saved to a temporary LaTeX file, then
19064 converted to an image file by process PROCESSING-TYPE defined in
19065 `org-preview-latex-process-alist'. A nil value defaults to
19066 `org-preview-latex-default-process'.
19068 The generated image file is eventually moved to TOFILE.
19070 The OPTIONS argument controls the size, foreground color and
19071 background color of the generated image.
19073 When BUFFER non-nil, this function is used for LaTeX previewing.
19074 Otherwise, it is used to deal with LaTeX snippets showed in
19075 a HTML file."
19076 (let* ((processing-type (or processing-type
19077 org-preview-latex-default-process))
19078 (processing-info
19079 (cdr (assq processing-type org-preview-latex-process-alist)))
19080 (programs (plist-get processing-info :programs))
19081 (error-message (or (plist-get processing-info :message) ""))
19082 (use-xcolor (plist-get processing-info :use-xcolor))
19083 (image-input-type (plist-get processing-info :image-input-type))
19084 (image-output-type (plist-get processing-info :image-output-type))
19085 (post-clean (or (plist-get processing-info :post-clean)
19086 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19087 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19088 (latex-header
19089 (or (plist-get processing-info :latex-header)
19090 (org-latex-make-preamble
19091 (org-export-get-environment (org-export-get-backend 'latex))
19092 org-format-latex-header
19093 'snippet)))
19094 (latex-compiler (plist-get processing-info :latex-compiler))
19095 (image-converter (plist-get processing-info :image-converter))
19096 (tmpdir temporary-file-directory)
19097 (texfilebase (make-temp-name
19098 (expand-file-name "orgtex" tmpdir)))
19099 (texfile (concat texfilebase ".tex"))
19100 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19101 '(1.0 . 1.0)))
19102 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19103 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19104 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19105 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19106 "Black"))
19107 (bg (or (plist-get options (if buffer :background :html-background))
19108 "Transparent"))
19109 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19110 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19111 (dolist (program programs)
19112 (org-check-external-command program error-message))
19113 (if use-xcolor
19114 (progn (if (eq fg 'default)
19115 (setq fg (org-latex-color :foreground))
19116 (setq fg (org-latex-color-format fg)))
19117 (if (eq bg 'default)
19118 (setq bg (org-latex-color :background))
19119 (setq bg (org-latex-color-format
19120 (if (string= bg "Transparent") "white" bg))))
19121 (with-temp-file texfile
19122 (insert latex-header)
19123 (insert "\n\\begin{document}\n"
19124 "\\definecolor{fg}{rgb}{" fg "}\n"
19125 "\\definecolor{bg}{rgb}{" bg "}\n"
19126 "\n\\pagecolor{bg}\n"
19127 "\n{\\color{fg}\n"
19128 string
19129 "\n}\n"
19130 "\n\\end{document}\n")))
19131 (if (eq fg 'default)
19132 (setq fg (org-dvipng-color :foreground))
19133 (unless (string= fg "Transparent")
19134 (setq fg (org-dvipng-color-format fg))))
19135 (if (eq bg 'default)
19136 (setq bg (org-dvipng-color :background))
19137 (unless (string= bg "Transparent")
19138 (setq bg (org-dvipng-color-format bg))))
19139 (with-temp-file texfile
19140 (insert latex-header)
19141 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19143 (let* ((err-msg (format "Please adjust `%s' part of \
19144 `org-preview-latex-process-alist'."
19145 processing-type))
19146 (image-input-file
19147 (org-compile-file
19148 texfile latex-compiler image-input-type err-msg log-buf))
19149 (image-output-file
19150 (org-compile-file
19151 image-input-file image-converter image-output-type err-msg log-buf
19152 `((?F . ,(shell-quote-argument fg))
19153 (?B . ,(shell-quote-argument bg))
19154 (?D . ,(shell-quote-argument (format "%s" dpi)))
19155 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19156 (copy-file image-output-file tofile 'replace)
19157 (dolist (e post-clean)
19158 (when (file-exists-p (concat texfilebase e))
19159 (delete-file (concat texfilebase e))))
19160 image-output-file)))
19162 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19163 "Fill a LaTeX header template TPL.
19164 In the template, the following place holders will be recognized:
19166 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19167 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19168 [PACKAGES] \\usepackage statements for PKG
19169 [NO-PACKAGES] do not include PKG
19170 [EXTRA] the string EXTRA
19171 [NO-EXTRA] do not include EXTRA
19173 For backward compatibility, if both the positive and the negative place
19174 holder is missing, the positive one (without the \"NO-\") will be
19175 assumed to be present at the end of the template.
19176 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19177 EXTRA is a string.
19178 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19179 (let (rpl (end ""))
19180 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19181 (setq rpl (if (or (match-end 1) (not def-pkg))
19182 "" (org-latex-packages-to-string def-pkg snippets-p t))
19183 tpl (replace-match rpl t t tpl))
19184 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19186 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19187 (setq rpl (if (or (match-end 1) (not pkg))
19188 "" (org-latex-packages-to-string pkg snippets-p t))
19189 tpl (replace-match rpl t t tpl))
19190 (when pkg (setq end
19191 (concat end "\n"
19192 (org-latex-packages-to-string pkg snippets-p)))))
19194 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19195 (setq rpl (if (or (match-end 1) (not extra))
19196 "" (concat extra "\n"))
19197 tpl (replace-match rpl t t tpl))
19198 (when (and extra (string-match "\\S-" extra))
19199 (setq end (concat end "\n" extra))))
19201 (if (string-match "\\S-" end)
19202 (concat tpl "\n" end)
19203 tpl)))
19205 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19206 "Turn an alist of packages into a string with the \\usepackage macros."
19207 (setq pkg (mapconcat (lambda(p)
19208 (cond
19209 ((stringp p) p)
19210 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19211 (format "%% Package %s omitted" (cadr p)))
19212 ((equal "" (car p))
19213 (format "\\usepackage{%s}" (cadr p)))
19215 (format "\\usepackage[%s]{%s}"
19216 (car p) (cadr p)))))
19218 "\n"))
19219 (if newline (concat pkg "\n") pkg))
19221 (defun org-dvipng-color (attr)
19222 "Return a RGB color specification for dvipng."
19223 (org-dvipng-color-format (face-attribute 'default attr nil)))
19225 (defun org-dvipng-color-format (color-name)
19226 "Convert COLOR-NAME to a RGB color value for dvipng."
19227 (apply #'format "rgb %s %s %s"
19228 (mapcar 'org-normalize-color
19229 (color-values color-name))))
19231 (defun org-latex-color (attr)
19232 "Return a RGB color for the LaTeX color package."
19233 (org-latex-color-format (face-attribute 'default attr nil)))
19235 (defun org-latex-color-format (color-name)
19236 "Convert COLOR-NAME to a RGB color value."
19237 (apply #'format "%s,%s,%s"
19238 (mapcar 'org-normalize-color
19239 (color-values color-name))))
19241 (defun org-normalize-color (value)
19242 "Return string to be used as color value for an RGB component."
19243 (format "%g" (/ value 65535.0)))
19247 ;; Image display
19249 (defvar-local org-inline-image-overlays nil)
19251 (defun org-toggle-inline-images (&optional include-linked)
19252 "Toggle the display of inline images.
19253 INCLUDE-LINKED is passed to `org-display-inline-images'."
19254 (interactive "P")
19255 (if org-inline-image-overlays
19256 (progn
19257 (org-remove-inline-images)
19258 (when (called-interactively-p 'interactive)
19259 (message "Inline image display turned off")))
19260 (org-display-inline-images include-linked)
19261 (when (called-interactively-p 'interactive)
19262 (message (if org-inline-image-overlays
19263 (format "%d images displayed inline"
19264 (length org-inline-image-overlays))
19265 "No images to display inline")))))
19267 (defun org-redisplay-inline-images ()
19268 "Refresh the display of inline images."
19269 (interactive)
19270 (if (not org-inline-image-overlays)
19271 (org-toggle-inline-images)
19272 (org-toggle-inline-images)
19273 (org-toggle-inline-images)))
19275 (defun org-display-inline-images (&optional include-linked refresh beg end)
19276 "Display inline images.
19278 An inline image is a link which follows either of these
19279 conventions:
19281 1. Its path is a file with an extension matching return value
19282 from `image-file-name-regexp' and it has no contents.
19284 2. Its description consists in a single link of the previous
19285 type.
19287 When optional argument INCLUDE-LINKED is non-nil, also links with
19288 a text description part will be inlined. This can be nice for
19289 a quick look at those images, but it does not reflect what
19290 exported files will look like.
19292 When optional argument REFRESH is non-nil, refresh existing
19293 images between BEG and END. This will create new image displays
19294 only if necessary. BEG and END default to the buffer
19295 boundaries."
19296 (interactive "P")
19297 (when (display-graphic-p)
19298 (unless refresh
19299 (org-remove-inline-images)
19300 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19301 (org-with-wide-buffer
19302 (goto-char (or beg (point-min)))
19303 (let* ((case-fold-search t)
19304 (file-extension-re (image-file-name-regexp))
19305 (link-abbrevs (mapcar #'car
19306 (append org-link-abbrev-alist-local
19307 org-link-abbrev-alist)))
19308 ;; Check absolute, relative file names and explicit
19309 ;; "file:" links. Also check link abbreviations since
19310 ;; some might expand to "file" links.
19311 (file-types-re (format "[][]\\[\\(?:file\\|[./~]%s\\)"
19312 (and link-abbrevs
19313 (format "\\|\\(?:%s:\\)"
19314 (regexp-opt link-abbrevs))))))
19315 (while (re-search-forward file-types-re end t)
19316 (let ((link (save-match-data (org-element-context))))
19317 ;; Check if we're at an inline image, i.e., an image file
19318 ;; link without a description (unless INCLUDE-LINKED is
19319 ;; non-nil).
19320 (when (and (equal "file" (org-element-property :type link))
19321 (or include-linked
19322 (null (org-element-contents link)))
19323 (string-match-p file-extension-re
19324 (org-element-property :path link)))
19325 (let ((file (expand-file-name
19326 (org-link-unescape
19327 (org-element-property :path link)))))
19328 (when (file-exists-p file)
19329 (let ((width
19330 ;; Apply `org-image-actual-width' specifications.
19331 (cond
19332 ((not (image-type-available-p 'imagemagick)) nil)
19333 ((eq org-image-actual-width t) nil)
19334 ((listp org-image-actual-width)
19336 ;; First try to find a width among
19337 ;; attributes associated to the paragraph
19338 ;; containing link.
19339 (let ((paragraph
19340 (let ((e link))
19341 (while (and (setq e (org-element-property
19342 :parent e))
19343 (not (eq (org-element-type e)
19344 'paragraph))))
19345 e)))
19346 (when paragraph
19347 (save-excursion
19348 (goto-char (org-element-property :begin paragraph))
19349 (when
19350 (re-search-forward
19351 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19352 (org-element-property
19353 :post-affiliated paragraph)
19355 (string-to-number (match-string 1))))))
19356 ;; Otherwise, fall-back to provided number.
19357 (car org-image-actual-width)))
19358 ((numberp org-image-actual-width)
19359 org-image-actual-width)))
19360 (old (get-char-property-and-overlay
19361 (org-element-property :begin link)
19362 'org-image-overlay)))
19363 (if (and (car-safe old) refresh)
19364 (image-refresh (overlay-get (cdr old) 'display))
19365 (let ((image (create-image file
19366 (and width 'imagemagick)
19368 :width width)))
19369 (when image
19370 (let ((ov (make-overlay
19371 (org-element-property :begin link)
19372 (progn
19373 (goto-char
19374 (org-element-property :end link))
19375 (skip-chars-backward " \t")
19376 (point)))))
19377 (overlay-put ov 'display image)
19378 (overlay-put ov 'face 'default)
19379 (overlay-put ov 'org-image-overlay t)
19380 (overlay-put
19381 ov 'modification-hooks
19382 (list 'org-display-inline-remove-overlay))
19383 (push ov org-inline-image-overlays)))))))))))))))
19385 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19386 "Remove inline-display overlay if a corresponding region is modified."
19387 (let ((inhibit-modification-hooks t))
19388 (when (and ov after)
19389 (delete ov org-inline-image-overlays)
19390 (delete-overlay ov))))
19392 (defun org-remove-inline-images ()
19393 "Remove inline display of images."
19394 (interactive)
19395 (mapc #'delete-overlay org-inline-image-overlays)
19396 (setq org-inline-image-overlays nil))
19398 ;;;; Key bindings
19400 (defun org-remap (map &rest commands)
19401 "In MAP, remap the functions given in COMMANDS.
19402 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
19403 (let (new old)
19404 (while commands
19405 (setq old (pop commands) new (pop commands))
19406 (org-defkey map (vector 'remap old) new))))
19408 ;; Outline functions from `outline-mode-prefix-map'
19409 ;; that can be remapped in Org:
19410 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19411 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19412 (define-key org-mode-map [remap outline-forward-same-level]
19413 'org-forward-heading-same-level)
19414 (define-key org-mode-map [remap outline-backward-same-level]
19415 'org-backward-heading-same-level)
19416 (define-key org-mode-map [remap outline-show-branches]
19417 'org-kill-note-or-show-branches)
19418 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19419 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19420 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19421 (define-key org-mode-map [remap outline-next-visible-heading]
19422 'org-next-visible-heading)
19423 (define-key org-mode-map [remap outline-previous-visible-heading]
19424 'org-previous-visible-heading)
19425 (define-key org-mode-map [remap show-children] 'org-show-children)
19427 ;; Outline functions from `outline-mode-prefix-map' that can not
19428 ;; be remapped in Org:
19430 ;; - the column "key binding" shows whether the Outline function is still
19431 ;; available in Org mode on the same key that it has been bound to in
19432 ;; Outline mode:
19433 ;; - "overridden": key used for a different functionality in Org mode
19434 ;; - else: key still bound to the same Outline function in Org mode
19436 ;; | Outline function | key binding | Org replacement |
19437 ;; |------------------------------------+-------------+--------------------------|
19438 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19439 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19440 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19441 ;; | `show-entry' | overridden | no replacement |
19442 ;; | `show-branches' | `C-c C-k' | still same function |
19443 ;; | `show-subtree' | overridden | visibility cycling |
19444 ;; | `show-all' | overridden | no replacement |
19445 ;; | `hide-subtree' | overridden | visibility cycling |
19446 ;; | `hide-body' | overridden | no replacement |
19447 ;; | `hide-entry' | overridden | visibility cycling |
19448 ;; | `hide-leaves' | overridden | no replacement |
19449 ;; | `hide-sublevels' | overridden | no replacement |
19450 ;; | `hide-other' | overridden | no replacement |
19452 ;; Make `C-c C-x' a prefix key
19453 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19455 ;; TAB key with modifiers
19456 (org-defkey org-mode-map "\C-i" 'org-cycle)
19457 (org-defkey org-mode-map [(tab)] 'org-cycle)
19458 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19459 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19461 ;; The following line is necessary under Suse GNU/Linux
19462 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19463 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19464 (define-key org-mode-map [backtab] 'org-shifttab)
19466 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19467 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19468 (org-defkey org-mode-map (kbd "M-RET") #'org-meta-return)
19470 ;; Cursor keys with modifiers
19471 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19472 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19473 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19474 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19476 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19477 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19478 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19479 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19480 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19481 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19483 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19484 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19485 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19486 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19488 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19489 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19490 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19491 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19493 ;; Babel keys
19494 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19495 (dolist (pair org-babel-key-bindings)
19496 (define-key org-babel-map (car pair) (cdr pair)))
19498 ;;; Extra keys for tty access.
19499 ;; We only set them when really needed because otherwise the
19500 ;; menus don't show the simple keys
19502 (when (or org-use-extra-keys (not window-system))
19503 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19504 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19505 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19506 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19507 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19508 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19509 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19510 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19511 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19512 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19513 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19514 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19515 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19516 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19517 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19518 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19519 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19520 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19521 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19522 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19523 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19524 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19525 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19526 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19527 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19528 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19529 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19530 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19532 ;; All the other keys
19533 (org-remap org-mode-map
19534 'self-insert-command 'org-self-insert-command
19535 'delete-char 'org-delete-char
19536 'delete-backward-char 'org-delete-backward-char)
19537 (org-defkey org-mode-map "|" 'org-force-self-insert)
19539 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19540 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19541 (if (boundp 'narrow-map)
19542 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19543 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19544 (if (boundp 'narrow-map)
19545 (org-defkey narrow-map "b" 'org-narrow-to-block)
19546 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19547 (if (boundp 'narrow-map)
19548 (org-defkey narrow-map "e" 'org-narrow-to-element)
19549 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19550 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19551 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19552 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19553 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19554 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19555 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19556 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19557 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19558 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19559 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19560 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19561 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19562 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19563 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19564 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19565 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19566 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19567 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19568 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19569 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19570 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19571 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19572 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19573 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19574 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19575 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19576 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19577 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19578 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19579 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19580 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19581 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19582 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19583 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19584 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19585 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19586 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19587 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19588 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19589 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19590 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19591 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19592 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19593 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19594 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19595 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19596 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19597 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19598 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19599 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19600 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19601 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19602 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19603 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19604 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19605 (org-defkey org-mode-map (kbd "C-c TAB") #'org-ctrl-c-tab)
19606 (org-defkey org-mode-map "\C-c^" 'org-sort)
19607 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19608 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19609 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19610 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19611 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19612 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19613 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19614 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19615 (org-defkey org-mode-map "\C-m" 'org-return)
19616 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19617 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19618 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19619 (org-defkey org-mode-map (kbd "C-c TAB") #'org-table-toggle-column-width)
19620 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19621 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19622 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19623 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19624 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19625 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19626 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19627 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19628 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19629 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19630 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19631 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19632 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19633 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19634 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19635 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19636 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19637 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19638 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19639 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19640 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19641 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19643 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19644 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19645 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19647 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19648 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19649 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19650 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19651 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19652 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19653 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19654 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19655 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19656 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19657 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19658 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19659 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19660 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19661 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19662 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19663 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19664 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19665 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19666 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19667 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19668 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19670 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19671 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19672 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19673 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19674 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19676 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19678 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19680 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19681 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19683 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19686 (defconst org-speed-commands-default
19688 ("Outline Navigation")
19689 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19690 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19691 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19692 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19693 ("F" . org-next-block)
19694 ("B" . org-previous-block)
19695 ("u" . (org-speed-move-safe 'outline-up-heading))
19696 ("j" . org-goto)
19697 ("g" . (org-refile t))
19698 ("Outline Visibility")
19699 ("c" . org-cycle)
19700 ("C" . org-shifttab)
19701 (" " . org-display-outline-path)
19702 ("s" . org-narrow-to-subtree)
19703 ("=" . org-columns)
19704 ("Outline Structure Editing")
19705 ("U" . org-metaup)
19706 ("D" . org-metadown)
19707 ("r" . org-metaright)
19708 ("l" . org-metaleft)
19709 ("R" . org-shiftmetaright)
19710 ("L" . org-shiftmetaleft)
19711 ("i" . (progn (forward-char 1) (call-interactively
19712 'org-insert-heading-respect-content)))
19713 ("^" . org-sort)
19714 ("w" . org-refile)
19715 ("a" . org-archive-subtree-default-with-confirmation)
19716 ("@" . org-mark-subtree)
19717 ("#" . org-toggle-comment)
19718 ("Clock Commands")
19719 ("I" . org-clock-in)
19720 ("O" . org-clock-out)
19721 ("Meta Data Editing")
19722 ("t" . org-todo)
19723 ("," . (org-priority))
19724 ("0" . (org-priority ?\ ))
19725 ("1" . (org-priority ?A))
19726 ("2" . (org-priority ?B))
19727 ("3" . (org-priority ?C))
19728 (":" . org-set-tags-command)
19729 ("e" . org-set-effort)
19730 ("E" . org-inc-effort)
19731 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
19732 (org-entry-put (point) "APPT_WARNTIME" m)))
19733 ("Agenda Views etc")
19734 ("v" . org-agenda)
19735 ("/" . org-sparse-tree)
19736 ("Misc")
19737 ("o" . org-open-at-point)
19738 ("?" . org-speed-command-help)
19739 ("<" . (org-agenda-set-restriction-lock 'subtree))
19740 (">" . (org-agenda-remove-restriction-lock))
19742 "The default speed commands.")
19744 (defun org-print-speed-command (e)
19745 (if (> (length (car e)) 1)
19746 (progn
19747 (princ "\n")
19748 (princ (car e))
19749 (princ "\n")
19750 (princ (make-string (length (car e)) ?-))
19751 (princ "\n"))
19752 (princ (car e))
19753 (princ " ")
19754 (if (symbolp (cdr e))
19755 (princ (symbol-name (cdr e)))
19756 (prin1 (cdr e)))
19757 (princ "\n")))
19759 (defun org-speed-command-help ()
19760 "Show the available speed commands."
19761 (interactive)
19762 (if (not org-use-speed-commands)
19763 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
19764 (with-output-to-temp-buffer "*Help*"
19765 (princ "User-defined Speed commands\n===========================\n")
19766 (mapc #'org-print-speed-command org-speed-commands-user)
19767 (princ "\n")
19768 (princ "Built-in Speed commands\n=======================\n")
19769 (mapc #'org-print-speed-command org-speed-commands-default))
19770 (with-current-buffer "*Help*"
19771 (setq truncate-lines t))))
19773 (defun org-speed-move-safe (cmd)
19774 "Execute CMD, but make sure that the cursor always ends up in a headline.
19775 If not, return to the original position and throw an error."
19776 (interactive)
19777 (let ((pos (point)))
19778 (call-interactively cmd)
19779 (unless (and (bolp) (org-at-heading-p))
19780 (goto-char pos)
19781 (error "Boundary reached while executing %s" cmd))))
19783 (defvar org-self-insert-command-undo-counter 0)
19785 (defvar org-table-auto-blank-field) ; defined in org-table.el
19786 (defvar org-speed-command nil)
19788 (defun org-speed-command-activate (keys)
19789 "Hook for activating single-letter speed commands.
19790 `org-speed-commands-default' specifies a minimal command set.
19791 Use `org-speed-commands-user' for further customization."
19792 (when (or (and (bolp) (looking-at org-outline-regexp))
19793 (and (functionp org-use-speed-commands)
19794 (funcall org-use-speed-commands)))
19795 (cdr (assoc keys (append org-speed-commands-user
19796 org-speed-commands-default)))))
19798 (defun org-babel-speed-command-activate (keys)
19799 "Hook for activating single-letter code block commands."
19800 (when (and (bolp) (looking-at org-babel-src-block-regexp))
19801 (cdr (assoc keys org-babel-key-bindings))))
19803 (defcustom org-speed-command-hook
19804 '(org-speed-command-activate org-babel-speed-command-activate)
19805 "Hook for activating speed commands at strategic locations.
19806 Hook functions are called in sequence until a valid handler is
19807 found.
19809 Each hook takes a single argument, a user-pressed command key
19810 which is also a `self-insert-command' from the global map.
19812 Within the hook, examine the cursor position and the command key
19813 and return nil or a valid handler as appropriate. Handler could
19814 be one of an interactive command, a function, or a form.
19816 Set `org-use-speed-commands' to non-nil value to enable this
19817 hook. The default setting is `org-speed-command-activate'."
19818 :group 'org-structure
19819 :version "24.1"
19820 :type 'hook)
19822 (defun org-self-insert-command (N)
19823 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
19824 If the cursor is in a table looking at whitespace, the whitespace is
19825 overwritten, and the table is not marked as requiring realignment."
19826 (interactive "p")
19827 (org-check-before-invisible-edit 'insert)
19828 (cond
19829 ((and org-use-speed-commands
19830 (let ((kv (this-command-keys-vector)))
19831 (setq org-speed-command
19832 (run-hook-with-args-until-success
19833 'org-speed-command-hook
19834 (make-string 1 (aref kv (1- (length kv))))))))
19835 (cond
19836 ((commandp org-speed-command)
19837 (setq this-command org-speed-command)
19838 (call-interactively org-speed-command))
19839 ((functionp org-speed-command)
19840 (funcall org-speed-command))
19841 ((and org-speed-command (listp org-speed-command))
19842 (eval org-speed-command))
19843 (t (let (org-use-speed-commands)
19844 (call-interactively 'org-self-insert-command)))))
19845 ((and
19846 (org-at-table-p)
19847 (eq N 1)
19848 (not (org-region-active-p))
19849 (progn
19850 ;; Check if we blank the field, and if that triggers align.
19851 (and (featurep 'org-table) org-table-auto-blank-field
19852 (memq last-command
19853 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
19854 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
19855 ;; Got extra space, this field does not determine
19856 ;; column width.
19857 (let (org-table-may-need-update) (org-table-blank-field))
19858 ;; No extra space, this field may determine column
19859 ;; width.
19860 (org-table-blank-field)))
19862 (looking-at "[^|\n]* \\( \\)|"))
19863 ;; There is room for insertion without re-aligning the table.
19864 (delete-region (match-beginning 1) (match-end 1))
19865 (self-insert-command N))
19867 (setq org-table-may-need-update t)
19868 (self-insert-command N)
19869 (org-fix-tags-on-the-fly)
19870 (when org-self-insert-cluster-for-undo
19871 (if (not (eq last-command 'org-self-insert-command))
19872 (setq org-self-insert-command-undo-counter 1)
19873 (if (>= org-self-insert-command-undo-counter 20)
19874 (setq org-self-insert-command-undo-counter 1)
19875 (and (> org-self-insert-command-undo-counter 0)
19876 buffer-undo-list (listp buffer-undo-list)
19877 (not (cadr buffer-undo-list)) ; remove nil entry
19878 (setcdr buffer-undo-list (cddr buffer-undo-list)))
19879 (setq org-self-insert-command-undo-counter
19880 (1+ org-self-insert-command-undo-counter))))))))
19882 (defun org-check-before-invisible-edit (kind)
19883 "Check is editing if kind KIND would be dangerous with invisible text around.
19884 The detailed reaction depends on the user option `org-catch-invisible-edits'."
19885 ;; First, try to get out of here as quickly as possible, to reduce overhead
19886 (when (and org-catch-invisible-edits
19887 (or (not (boundp 'visible-mode)) (not visible-mode))
19888 (or (get-char-property (point) 'invisible)
19889 (get-char-property (max (point-min) (1- (point))) 'invisible)))
19890 ;; OK, we need to take a closer look. Do not consider
19891 ;; invisibility obtained through text properties (e.g., link
19892 ;; fontification), as it cannot be toggled.
19893 (let* ((invisible-at-point
19894 (pcase (get-char-property-and-overlay (point) 'invisible)
19895 (`(,_ . ,(and (pred overlayp) o)) o)))
19896 ;; Assume that point cannot land in the middle of an
19897 ;; overlay, or between two overlays.
19898 (invisible-before-point
19899 (and (not invisible-at-point)
19900 (not (bobp))
19901 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
19902 (`(,_ . ,(and (pred overlayp) o)) o))))
19903 (border-and-ok-direction
19905 ;; Check if we are acting predictably before invisible
19906 ;; text.
19907 (and invisible-at-point
19908 (memq kind '(insert delete-backward)))
19909 ;; Check if we are acting predictably after invisible text
19910 ;; This works not well, and I have turned it off. It seems
19911 ;; better to always show and stop after invisible text.
19912 ;; (and (not invisible-at-point) invisible-before-point
19913 ;; (memq kind '(insert delete)))
19915 (when (or invisible-at-point invisible-before-point)
19916 (when (eq org-catch-invisible-edits 'error)
19917 (user-error "Editing in invisible areas is prohibited, make them visible first"))
19918 (if (and org-custom-properties-overlays
19919 (y-or-n-p "Display invisible properties in this buffer? "))
19920 (org-toggle-custom-properties-visibility)
19921 ;; Make the area visible
19922 (save-excursion
19923 (when invisible-before-point
19924 (goto-char
19925 (previous-single-char-property-change (point) 'invisible)))
19926 ;; Remove whatever overlay is currently making yet-to-be
19927 ;; edited text invisible. Also remove nested invisibility
19928 ;; related overlays.
19929 (delete-overlay (or invisible-at-point invisible-before-point))
19930 (let ((origin (if invisible-at-point (point) (1- (point)))))
19931 (while (pcase (get-char-property-and-overlay origin 'invisible)
19932 (`(,_ . ,(and (pred overlayp) o))
19933 (delete-overlay o)
19934 t)))))
19935 (cond
19936 ((eq org-catch-invisible-edits 'show)
19937 ;; That's it, we do the edit after showing
19938 (message
19939 "Unfolding invisible region around point before editing")
19940 (sit-for 1))
19941 ((and (eq org-catch-invisible-edits 'smart)
19942 border-and-ok-direction)
19943 (message "Unfolding invisible region around point before editing"))
19945 ;; Don't do the edit, make the user repeat it in full visibility
19946 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
19948 (defun org-fix-tags-on-the-fly ()
19949 "Align tags in headline at point.
19950 Unlike to `org-set-tags', it ignores region and sorting."
19951 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
19952 (org-at-heading-p))
19953 (let ((org-ignore-region t)
19954 (org-tags-sort-function nil))
19955 (org-set-tags nil t))))
19957 (defun org-delete-backward-char (N)
19958 "Like `delete-backward-char', insert whitespace at field end in tables.
19959 When deleting backwards, in tables this function will insert whitespace in
19960 front of the next \"|\" separator, to keep the table aligned. The table will
19961 still be marked for re-alignment if the field did fill the entire column,
19962 because, in this case the deletion might narrow the column."
19963 (interactive "p")
19964 (save-match-data
19965 (org-check-before-invisible-edit 'delete-backward)
19966 (if (and (org-at-table-p)
19967 (eq N 1)
19968 (not (org-region-active-p))
19969 (string-match "|" (buffer-substring (point-at-bol) (point)))
19970 (looking-at ".*?|"))
19971 (let ((pos (point))
19972 (noalign (looking-at "[^|\n\r]* |"))
19973 (c org-table-may-need-update))
19974 (backward-delete-char N)
19975 (unless overwrite-mode
19976 (skip-chars-forward "^|")
19977 (insert " ")
19978 (goto-char (1- pos)))
19979 ;; noalign: if there were two spaces at the end, this field
19980 ;; does not determine the width of the column.
19981 (when noalign (setq org-table-may-need-update c)))
19982 (backward-delete-char N)
19983 (org-fix-tags-on-the-fly))))
19985 (defun org-delete-char (N)
19986 "Like `delete-char', but insert whitespace at field end in tables.
19987 When deleting characters, in tables this function will insert whitespace in
19988 front of the next \"|\" separator, to keep the table aligned. The table will
19989 still be marked for re-alignment if the field did fill the entire column,
19990 because, in this case the deletion might narrow the column."
19991 (interactive "p")
19992 (save-match-data
19993 (org-check-before-invisible-edit 'delete)
19994 (if (and (org-at-table-p)
19995 (not (bolp))
19996 (not (= (char-after) ?|))
19997 (eq N 1))
19998 (if (looking-at ".*?|")
19999 (let ((pos (point))
20000 (noalign (looking-at "[^|\n\r]* |"))
20001 (c org-table-may-need-update))
20002 (replace-match
20003 (concat (substring (match-string 0) 1 -1) " |") nil t)
20004 (goto-char pos)
20005 ;; noalign: if there were two spaces at the end, this field
20006 ;; does not determine the width of the column.
20007 (when noalign (setq org-table-may-need-update c)))
20008 (delete-char N))
20009 (delete-char N)
20010 (org-fix-tags-on-the-fly))))
20012 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20013 (put 'org-self-insert-command 'delete-selection
20014 (lambda ()
20015 (not (run-hook-with-args-until-success
20016 'self-insert-uses-region-functions))))
20017 (put 'orgtbl-self-insert-command 'delete-selection
20018 (lambda ()
20019 (not (run-hook-with-args-until-success
20020 'self-insert-uses-region-functions))))
20021 (put 'org-delete-char 'delete-selection 'supersede)
20022 (put 'org-delete-backward-char 'delete-selection 'supersede)
20023 (put 'org-yank 'delete-selection 'yank)
20025 ;; Make `flyspell-mode' delay after some commands
20026 (put 'org-self-insert-command 'flyspell-delayed t)
20027 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20028 (put 'org-delete-char 'flyspell-delayed t)
20029 (put 'org-delete-backward-char 'flyspell-delayed t)
20031 ;; Make pabbrev-mode expand after Org mode commands
20032 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20033 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20035 (defun org-transpose-words ()
20036 "Transpose words for Org.
20037 This uses the `org-mode-transpose-word-syntax-table' syntax
20038 table, which interprets characters in `org-emphasis-alist' as
20039 word constituents."
20040 (interactive)
20041 (with-syntax-table org-mode-transpose-word-syntax-table
20042 (call-interactively 'transpose-words)))
20043 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20045 (defvar org-ctrl-c-ctrl-c-hook nil
20046 "Hook for functions attaching themselves to `C-c C-c'.
20048 This can be used to add additional functionality to the C-c C-c
20049 key which executes context-dependent commands. This hook is run
20050 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20051 run after the last test.
20053 Each function will be called with no arguments. The function
20054 must check if the context is appropriate for it to act. If yes,
20055 it should do its thing and then return a non-nil value. If the
20056 context is wrong, just do nothing and return nil.")
20058 (defvar org-ctrl-c-ctrl-c-final-hook nil
20059 "Hook for functions attaching themselves to `C-c C-c'.
20061 This can be used to add additional functionality to the C-c C-c
20062 key which executes context-dependent commands. This hook is run
20063 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20064 before the first test.
20066 Each function will be called with no arguments. The function
20067 must check if the context is appropriate for it to act. If yes,
20068 it should do its thing and then return a non-nil value. If the
20069 context is wrong, just do nothing and return nil.")
20071 (defvar org-tab-first-hook nil
20072 "Hook for functions to attach themselves to TAB.
20073 See `org-ctrl-c-ctrl-c-hook' for more information.
20074 This hook runs as the first action when TAB is pressed, even before
20075 `org-cycle' messes around with the `outline-regexp' to cater for
20076 inline tasks and plain list item folding.
20077 If any function in this hook returns t, any other actions that
20078 would have been caused by TAB (such as table field motion or visibility
20079 cycling) will not occur.")
20081 (defvar org-tab-after-check-for-table-hook nil
20082 "Hook for functions to attach themselves to TAB.
20083 See `org-ctrl-c-ctrl-c-hook' for more information.
20084 This hook runs after it has been established that the cursor is not in a
20085 table, but before checking if the cursor is in a headline or if global cycling
20086 should be done.
20087 If any function in this hook returns t, not other actions like visibility
20088 cycling will be done.")
20090 (defvar org-tab-after-check-for-cycling-hook nil
20091 "Hook for functions to attach themselves to TAB.
20092 See `org-ctrl-c-ctrl-c-hook' for more information.
20093 This hook runs after it has been established that not table field motion and
20094 not visibility should be done because of current context. This is probably
20095 the place where a package like yasnippets can hook in.")
20097 (defvar org-tab-before-tab-emulation-hook nil
20098 "Hook for functions to attach themselves to TAB.
20099 See `org-ctrl-c-ctrl-c-hook' for more information.
20100 This hook runs after every other options for TAB have been exhausted, but
20101 before indentation and \t insertion takes place.")
20103 (defvar org-metaleft-hook nil
20104 "Hook for functions attaching themselves to `M-left'.
20105 See `org-ctrl-c-ctrl-c-hook' for more information.")
20106 (defvar org-metaright-hook nil
20107 "Hook for functions attaching themselves to `M-right'.
20108 See `org-ctrl-c-ctrl-c-hook' for more information.")
20109 (defvar org-metaup-hook nil
20110 "Hook for functions attaching themselves to `M-up'.
20111 See `org-ctrl-c-ctrl-c-hook' for more information.")
20112 (defvar org-metadown-hook nil
20113 "Hook for functions attaching themselves to `M-down'.
20114 See `org-ctrl-c-ctrl-c-hook' for more information.")
20115 (defvar org-shiftmetaleft-hook nil
20116 "Hook for functions attaching themselves to `M-S-left'.
20117 See `org-ctrl-c-ctrl-c-hook' for more information.")
20118 (defvar org-shiftmetaright-hook nil
20119 "Hook for functions attaching themselves to `M-S-right'.
20120 See `org-ctrl-c-ctrl-c-hook' for more information.")
20121 (defvar org-shiftmetaup-hook nil
20122 "Hook for functions attaching themselves to `M-S-up'.
20123 See `org-ctrl-c-ctrl-c-hook' for more information.")
20124 (defvar org-shiftmetadown-hook nil
20125 "Hook for functions attaching themselves to `M-S-down'.
20126 See `org-ctrl-c-ctrl-c-hook' for more information.")
20127 (defvar org-metareturn-hook nil
20128 "Hook for functions attaching themselves to `M-RET'.
20129 See `org-ctrl-c-ctrl-c-hook' for more information.")
20130 (defvar org-shiftup-hook nil
20131 "Hook for functions attaching themselves to `S-up'.
20132 See `org-ctrl-c-ctrl-c-hook' for more information.")
20133 (defvar org-shiftup-final-hook nil
20134 "Hook for functions attaching themselves to `S-up'.
20135 This one runs after all other options except shift-select have been excluded.
20136 See `org-ctrl-c-ctrl-c-hook' for more information.")
20137 (defvar org-shiftdown-hook nil
20138 "Hook for functions attaching themselves to `S-down'.
20139 See `org-ctrl-c-ctrl-c-hook' for more information.")
20140 (defvar org-shiftdown-final-hook nil
20141 "Hook for functions attaching themselves to `S-down'.
20142 This one runs after all other options except shift-select have been excluded.
20143 See `org-ctrl-c-ctrl-c-hook' for more information.")
20144 (defvar org-shiftleft-hook nil
20145 "Hook for functions attaching themselves to `S-left'.
20146 See `org-ctrl-c-ctrl-c-hook' for more information.")
20147 (defvar org-shiftleft-final-hook nil
20148 "Hook for functions attaching themselves to `S-left'.
20149 This one runs after all other options except shift-select have been excluded.
20150 See `org-ctrl-c-ctrl-c-hook' for more information.")
20151 (defvar org-shiftright-hook nil
20152 "Hook for functions attaching themselves to `S-right'.
20153 See `org-ctrl-c-ctrl-c-hook' for more information.")
20154 (defvar org-shiftright-final-hook nil
20155 "Hook for functions attaching themselves to `S-right'.
20156 This one runs after all other options except shift-select have been excluded.
20157 See `org-ctrl-c-ctrl-c-hook' for more information.")
20159 (defun org-modifier-cursor-error ()
20160 "Throw an error, a modified cursor command was applied in wrong context."
20161 (user-error "This command is active in special context like tables, headlines or items"))
20163 (defun org-shiftselect-error ()
20164 "Throw an error because Shift-Cursor command was applied in wrong context."
20165 (if (and (boundp 'shift-select-mode) shift-select-mode)
20166 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20167 (user-error "This command works only in special context like headlines or timestamps")))
20169 (defun org-call-for-shift-select (cmd)
20170 (let ((this-command-keys-shift-translated t))
20171 (call-interactively cmd)))
20173 (defun org-shifttab (&optional arg)
20174 "Global visibility cycling or move to previous table field.
20175 Call `org-table-previous-field' within a table.
20176 When ARG is nil, cycle globally through visibility states.
20177 When ARG is a numeric prefix, show contents of this level."
20178 (interactive "P")
20179 (cond
20180 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20181 ((integerp arg)
20182 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20183 (message "Content view to level: %d" arg)
20184 (org-content (prefix-numeric-value arg2))
20185 (org-cycle-show-empty-lines t)
20186 (setq org-cycle-global-status 'overview)))
20187 (t (call-interactively 'org-global-cycle))))
20189 (defun org-shiftmetaleft ()
20190 "Promote subtree or delete table column.
20191 Calls `org-promote-subtree', `org-outdent-item-tree', or
20192 `org-table-delete-column', depending on context. See the
20193 individual commands for more information."
20194 (interactive)
20195 (cond
20196 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20197 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20198 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20199 ((if (not (org-region-active-p)) (org-at-item-p)
20200 (save-excursion (goto-char (region-beginning))
20201 (org-at-item-p)))
20202 (call-interactively 'org-outdent-item-tree))
20203 (t (org-modifier-cursor-error))))
20205 (defun org-shiftmetaright ()
20206 "Demote subtree or insert table column.
20207 Calls `org-demote-subtree', `org-indent-item-tree', or
20208 `org-table-insert-column', depending on context. See the
20209 individual commands for more information."
20210 (interactive)
20211 (cond
20212 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20213 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20214 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20215 ((if (not (org-region-active-p)) (org-at-item-p)
20216 (save-excursion (goto-char (region-beginning))
20217 (org-at-item-p)))
20218 (call-interactively 'org-indent-item-tree))
20219 (t (org-modifier-cursor-error))))
20221 (defun org-shiftmetaup (&optional _arg)
20222 "Drag the line at point up.
20223 In a table, kill the current row.
20224 On a clock timestamp, update the value of the timestamp like `S-<up>'
20225 but also adjust the previous clocked item in the clock history.
20226 Everywhere else, drag the line at point up."
20227 (interactive "P")
20228 (cond
20229 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20230 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20231 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20232 (call-interactively 'org-timestamp-up)))
20233 (t (call-interactively 'org-drag-line-backward))))
20235 (defun org-shiftmetadown (&optional _arg)
20236 "Drag the line at point down.
20237 In a table, insert an empty row at the current line.
20238 On a clock timestamp, update the value of the timestamp like `S-<down>'
20239 but also adjust the previous clocked item in the clock history.
20240 Everywhere else, drag the line at point down."
20241 (interactive "P")
20242 (cond
20243 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20244 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20245 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20246 (call-interactively 'org-timestamp-down)))
20247 (t (call-interactively 'org-drag-line-forward))))
20249 (defsubst org-hidden-tree-error ()
20250 (user-error
20251 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20253 (defun org-metaleft (&optional _arg)
20254 "Promote heading, list item at point or move table column left.
20256 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20257 depending on context. With no specific context, calls the Emacs
20258 default `backward-word'. See the individual commands for more
20259 information.
20261 This function runs the hook `org-metaleft-hook' as a first step,
20262 and returns at first non-nil value."
20263 (interactive "P")
20264 (cond
20265 ((run-hook-with-args-until-success 'org-metaleft-hook))
20266 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20267 ((org-with-limited-levels
20268 (or (org-at-heading-p)
20269 (and (org-region-active-p)
20270 (save-excursion
20271 (goto-char (region-beginning))
20272 (org-at-heading-p)))))
20273 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20274 (call-interactively 'org-do-promote))
20275 ;; At an inline task.
20276 ((org-at-heading-p)
20277 (call-interactively 'org-inlinetask-promote))
20278 ((or (org-at-item-p)
20279 (and (org-region-active-p)
20280 (save-excursion
20281 (goto-char (region-beginning))
20282 (org-at-item-p))))
20283 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20284 (call-interactively 'org-outdent-item))
20285 (t (call-interactively 'backward-word))))
20287 (defun org-metaright (&optional _arg)
20288 "Demote heading, list item at point or move table column right.
20290 In front of a drawer or a block keyword, indent it correctly.
20292 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20293 `org-indent-drawer' or `org-indent-block' depending on context.
20294 With no specific context, calls the Emacs default `forward-word'.
20295 See the individual commands for more information.
20297 This function runs the hook `org-metaright-hook' as a first step,
20298 and returns at first non-nil value."
20299 (interactive "P")
20300 (cond
20301 ((run-hook-with-args-until-success 'org-metaright-hook))
20302 ((org-at-table-p) (call-interactively 'org-table-move-column))
20303 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20304 ((org-at-block-p) (call-interactively 'org-indent-block))
20305 ((org-with-limited-levels
20306 (or (org-at-heading-p)
20307 (and (org-region-active-p)
20308 (save-excursion
20309 (goto-char (region-beginning))
20310 (org-at-heading-p)))))
20311 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20312 (call-interactively 'org-do-demote))
20313 ;; At an inline task.
20314 ((org-at-heading-p)
20315 (call-interactively 'org-inlinetask-demote))
20316 ((or (org-at-item-p)
20317 (and (org-region-active-p)
20318 (save-excursion
20319 (goto-char (region-beginning))
20320 (org-at-item-p))))
20321 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20322 (call-interactively 'org-indent-item))
20323 (t (call-interactively 'forward-word))))
20325 (defun org-check-for-hidden (what)
20326 "Check if there are hidden headlines/items in the current visual line.
20327 WHAT can be either `headlines' or `items'. If the current line is
20328 an outline or item heading and it has a folded subtree below it,
20329 this function returns t, nil otherwise."
20330 (let ((re (cond
20331 ((eq what 'headlines) org-outline-regexp-bol)
20332 ((eq what 'items) (org-item-beginning-re))
20333 (t (error "This should not happen"))))
20334 beg end)
20335 (save-excursion
20336 (catch 'exit
20337 (unless (org-region-active-p)
20338 (setq beg (point-at-bol))
20339 (beginning-of-line 2)
20340 (while (and (not (eobp)) ;; this is like `next-line'
20341 (get-char-property (1- (point)) 'invisible))
20342 (beginning-of-line 2))
20343 (setq end (point))
20344 (goto-char beg)
20345 (goto-char (point-at-eol))
20346 (setq end (max end (point)))
20347 (while (re-search-forward re end t)
20348 (when (get-char-property (match-beginning 0) 'invisible)
20349 (throw 'exit t))))
20350 nil))))
20352 (defun org-metaup (&optional _arg)
20353 "Move subtree up or move table row up.
20354 Calls `org-move-subtree-up' or `org-table-move-row' or
20355 `org-move-item-up', depending on context. See the individual commands
20356 for more information."
20357 (interactive "P")
20358 (cond
20359 ((run-hook-with-args-until-success 'org-metaup-hook))
20360 ((org-region-active-p)
20361 (let* ((a (min (region-beginning) (region-end)))
20362 (b (1- (max (region-beginning) (region-end))))
20363 (c (save-excursion (goto-char a)
20364 (move-beginning-of-line 0)))
20365 (d (save-excursion (goto-char a)
20366 (move-end-of-line 0) (point))))
20367 (transpose-regions a b c d)
20368 (goto-char c)))
20369 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20370 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20371 ((org-at-item-p) (call-interactively 'org-move-item-up))
20372 (t (org-drag-element-backward))))
20374 (defun org-metadown (&optional _arg)
20375 "Move subtree down or move table row down.
20376 Calls `org-move-subtree-down' or `org-table-move-row' or
20377 `org-move-item-down', depending on context. See the individual
20378 commands for more information."
20379 (interactive "P")
20380 (cond
20381 ((run-hook-with-args-until-success 'org-metadown-hook))
20382 ((org-region-active-p)
20383 (let* ((a (min (region-beginning) (region-end)))
20384 (b (max (region-beginning) (region-end)))
20385 (c (save-excursion (goto-char b)
20386 (move-beginning-of-line 1)))
20387 (d (save-excursion (goto-char b)
20388 (move-end-of-line 1) (1+ (point)))))
20389 (transpose-regions a b c d)
20390 (goto-char d)))
20391 ((org-at-table-p) (call-interactively 'org-table-move-row))
20392 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20393 ((org-at-item-p) (call-interactively 'org-move-item-down))
20394 (t (org-drag-element-forward))))
20396 (defun org-shiftup (&optional arg)
20397 "Increase item in timestamp or increase priority of current headline.
20398 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20399 depending on context. See the individual commands for more information."
20400 (interactive "P")
20401 (cond
20402 ((run-hook-with-args-until-success 'org-shiftup-hook))
20403 ((and org-support-shift-select (org-region-active-p))
20404 (org-call-for-shift-select 'previous-line))
20405 ((org-at-timestamp-p 'lax)
20406 (call-interactively (if org-edit-timestamp-down-means-later
20407 'org-timestamp-down 'org-timestamp-up)))
20408 ((and (not (eq org-support-shift-select 'always))
20409 org-enable-priority-commands
20410 (org-at-heading-p))
20411 (call-interactively 'org-priority-up))
20412 ((and (not org-support-shift-select) (org-at-item-p))
20413 (call-interactively 'org-previous-item))
20414 ((org-clocktable-try-shift 'up arg))
20415 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20416 (org-support-shift-select
20417 (org-call-for-shift-select 'previous-line))
20418 (t (org-shiftselect-error))))
20420 (defun org-shiftdown (&optional arg)
20421 "Decrease item in timestamp or decrease priority of current headline.
20422 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20423 depending on context. See the individual commands for more information."
20424 (interactive "P")
20425 (cond
20426 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20427 ((and org-support-shift-select (org-region-active-p))
20428 (org-call-for-shift-select 'next-line))
20429 ((org-at-timestamp-p 'lax)
20430 (call-interactively (if org-edit-timestamp-down-means-later
20431 'org-timestamp-up 'org-timestamp-down)))
20432 ((and (not (eq org-support-shift-select 'always))
20433 org-enable-priority-commands
20434 (org-at-heading-p))
20435 (call-interactively 'org-priority-down))
20436 ((and (not org-support-shift-select) (org-at-item-p))
20437 (call-interactively 'org-next-item))
20438 ((org-clocktable-try-shift 'down arg))
20439 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20440 (org-support-shift-select
20441 (org-call-for-shift-select 'next-line))
20442 (t (org-shiftselect-error))))
20444 (defun org-shiftright (&optional arg)
20445 "Cycle the thing at point or in the current line, depending on context.
20446 Depending on context, this does one of the following:
20448 - switch a timestamp at point one day into the future
20449 - on a headline, switch to the next TODO keyword.
20450 - on an item, switch entire list to the next bullet type
20451 - on a property line, switch to the next allowed value
20452 - on a clocktable definition line, move time block into the future"
20453 (interactive "P")
20454 (cond
20455 ((run-hook-with-args-until-success 'org-shiftright-hook))
20456 ((and org-support-shift-select (org-region-active-p))
20457 (org-call-for-shift-select 'forward-char))
20458 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
20459 ((and (not (eq org-support-shift-select 'always))
20460 (org-at-heading-p))
20461 (let ((org-inhibit-logging
20462 (not org-treat-S-cursor-todo-selection-as-state-change))
20463 (org-inhibit-blocking
20464 (not org-treat-S-cursor-todo-selection-as-state-change)))
20465 (org-call-with-arg 'org-todo 'right)))
20466 ((or (and org-support-shift-select
20467 (not (eq org-support-shift-select 'always))
20468 (org-at-item-bullet-p))
20469 (and (not org-support-shift-select) (org-at-item-p)))
20470 (org-call-with-arg 'org-cycle-list-bullet nil))
20471 ((and (not (eq org-support-shift-select 'always))
20472 (org-at-property-p))
20473 (call-interactively 'org-property-next-allowed-value))
20474 ((org-clocktable-try-shift 'right arg))
20475 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20476 (org-support-shift-select
20477 (org-call-for-shift-select 'forward-char))
20478 (t (org-shiftselect-error))))
20480 (defun org-shiftleft (&optional arg)
20481 "Cycle the thing at point or in the current line, depending on context.
20482 Depending on context, this does one of the following:
20484 - switch a timestamp at point one day into the past
20485 - on a headline, switch to the previous TODO keyword.
20486 - on an item, switch entire list to the previous bullet type
20487 - on a property line, switch to the previous allowed value
20488 - on a clocktable definition line, move time block into the past"
20489 (interactive "P")
20490 (cond
20491 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20492 ((and org-support-shift-select (org-region-active-p))
20493 (org-call-for-shift-select 'backward-char))
20494 ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
20495 ((and (not (eq org-support-shift-select 'always))
20496 (org-at-heading-p))
20497 (let ((org-inhibit-logging
20498 (not org-treat-S-cursor-todo-selection-as-state-change))
20499 (org-inhibit-blocking
20500 (not org-treat-S-cursor-todo-selection-as-state-change)))
20501 (org-call-with-arg 'org-todo 'left)))
20502 ((or (and org-support-shift-select
20503 (not (eq org-support-shift-select 'always))
20504 (org-at-item-bullet-p))
20505 (and (not org-support-shift-select) (org-at-item-p)))
20506 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20507 ((and (not (eq org-support-shift-select 'always))
20508 (org-at-property-p))
20509 (call-interactively 'org-property-previous-allowed-value))
20510 ((org-clocktable-try-shift 'left arg))
20511 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20512 (org-support-shift-select
20513 (org-call-for-shift-select 'backward-char))
20514 (t (org-shiftselect-error))))
20516 (defun org-shiftcontrolright ()
20517 "Switch to next TODO set."
20518 (interactive)
20519 (cond
20520 ((and org-support-shift-select (org-region-active-p))
20521 (org-call-for-shift-select 'forward-word))
20522 ((and (not (eq org-support-shift-select 'always))
20523 (org-at-heading-p))
20524 (org-call-with-arg 'org-todo 'nextset))
20525 (org-support-shift-select
20526 (org-call-for-shift-select 'forward-word))
20527 (t (org-shiftselect-error))))
20529 (defun org-shiftcontrolleft ()
20530 "Switch to previous TODO set."
20531 (interactive)
20532 (cond
20533 ((and org-support-shift-select (org-region-active-p))
20534 (org-call-for-shift-select 'backward-word))
20535 ((and (not (eq org-support-shift-select 'always))
20536 (org-at-heading-p))
20537 (org-call-with-arg 'org-todo 'previousset))
20538 (org-support-shift-select
20539 (org-call-for-shift-select 'backward-word))
20540 (t (org-shiftselect-error))))
20542 (defun org-shiftcontrolup (&optional n)
20543 "Change timestamps synchronously up in CLOCK log lines.
20544 Optional argument N tells to change by that many units."
20545 (interactive "P")
20546 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20547 (let (org-support-shift-select)
20548 (org-clock-timestamps-up n))
20549 (user-error "Not at a clock log")))
20551 (defun org-shiftcontroldown (&optional n)
20552 "Change timestamps synchronously down in CLOCK log lines.
20553 Optional argument N tells to change by that many units."
20554 (interactive "P")
20555 (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
20556 (let (org-support-shift-select)
20557 (org-clock-timestamps-down n))
20558 (user-error "Not at a clock log")))
20560 (defun org-increase-number-at-point (&optional inc)
20561 "Increment the number at point.
20562 With an optional prefix numeric argument INC, increment using
20563 this numeric value."
20564 (interactive "p")
20565 (if (not (number-at-point))
20566 (user-error "Not on a number")
20567 (unless inc (setq inc 1))
20568 (let ((pos (point))
20569 (beg (skip-chars-backward "-+^/*0-9eE."))
20570 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20571 (setq nap (buffer-substring-no-properties
20572 (+ pos beg) (+ pos beg end)))
20573 (delete-region (+ pos beg) (+ pos beg end))
20574 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20575 (when (org-at-table-p)
20576 (org-table-align)
20577 (org-table-end-of-field 1))))
20579 (defun org-decrease-number-at-point (&optional inc)
20580 "Decrement the number at point.
20581 With an optional prefix numeric argument INC, decrement using
20582 this numeric value."
20583 (interactive "p")
20584 (org-increase-number-at-point (- (or inc 1))))
20586 (defun org-ctrl-c-ret ()
20587 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20588 (interactive)
20589 (cond
20590 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20591 (t (call-interactively 'org-insert-heading))))
20593 (defun org-find-visible ()
20594 (let ((s (point)))
20595 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20596 (get-char-property s 'invisible)))
20598 (defun org-find-invisible ()
20599 (let ((s (point)))
20600 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20601 (not (get-char-property s 'invisible))))
20604 (defun org-copy-visible (beg end)
20605 "Copy the visible parts of the region."
20606 (interactive "r")
20607 (let ((result ""))
20608 (while (/= beg end)
20609 (when (get-char-property beg 'invisible)
20610 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20611 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20612 (setq result (concat result (buffer-substring beg next)))
20613 (setq beg next)))
20614 (kill-new result)))
20616 (defun org-copy-special ()
20617 "Copy region in table or copy current subtree.
20618 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20619 context. See the individual commands for more information."
20620 (interactive)
20621 (call-interactively
20622 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20624 (defun org-cut-special ()
20625 "Cut region in table or cut current subtree.
20626 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20627 context. See the individual commands for more information."
20628 (interactive)
20629 (call-interactively
20630 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20632 (defun org-paste-special (arg)
20633 "Paste rectangular region into table, or past subtree relative to level.
20634 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20635 See the individual commands for more information."
20636 (interactive "P")
20637 (if (org-at-table-p)
20638 (org-table-paste-rectangle)
20639 (org-paste-subtree arg)))
20641 (defun org-edit-special (&optional arg)
20642 "Call a special editor for the element at point.
20643 When at a table, call the formula editor with `org-table-edit-formulas'.
20644 When in a source code block, call `org-edit-src-code'.
20645 When in a fixed-width region, call `org-edit-fixed-width-region'.
20646 When in an export block, call `org-edit-export-block'.
20647 When in a LaTeX environment, call `org-edit-latex-environment'.
20648 When at an #+INCLUDE keyword, visit the included file.
20649 When at a footnote reference, call `org-edit-footnote-reference'
20650 On a link, call `ffap' to visit the link at point.
20651 Otherwise, return a user error."
20652 (interactive "P")
20653 (let ((element (org-element-at-point)))
20654 (barf-if-buffer-read-only)
20655 (pcase (org-element-type element)
20656 (`src-block
20657 (if (not arg) (org-edit-src-code)
20658 (let* ((info (org-babel-get-src-block-info))
20659 (lang (nth 0 info))
20660 (params (nth 2 info))
20661 (session (cdr (assq :session params))))
20662 (if (not session) (org-edit-src-code)
20663 ;; At a src-block with a session and function called with
20664 ;; an ARG: switch to the buffer related to the inferior
20665 ;; process.
20666 (switch-to-buffer
20667 (funcall (intern (concat "org-babel-prep-session:" lang))
20668 session params))))))
20669 (`keyword
20670 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20671 (org-open-link-from-string
20672 (format "[[%s]]"
20673 (expand-file-name
20674 (let ((value (org-element-property :value element)))
20675 (cond ((org-file-url-p value)
20676 (user-error "The file is specified as a URL, cannot be edited"))
20677 ((not (org-string-nw-p value))
20678 (user-error "No file to edit"))
20679 ((string-match "\\`\"\\(.*?\\)\"" value)
20680 (match-string 1 value))
20681 ((string-match "\\`[^ \t\"]\\S-*" value)
20682 (match-string 0 value))
20683 (t (user-error "No valid file specified")))))))
20684 (user-error "No special environment to edit here")))
20685 (`table
20686 (if (eq (org-element-property :type element) 'table.el)
20687 (org-edit-table.el)
20688 (call-interactively 'org-table-edit-formulas)))
20689 ;; Only Org tables contain `table-row' type elements.
20690 (`table-row (call-interactively 'org-table-edit-formulas))
20691 (`example-block (org-edit-src-code))
20692 (`export-block (org-edit-export-block))
20693 (`fixed-width (org-edit-fixed-width-region))
20694 (`latex-environment (org-edit-latex-environment))
20696 ;; No notable element at point. Though, we may be at a link or
20697 ;; a footnote reference, which are objects. Thus, scan deeper.
20698 (let ((context (org-element-context element)))
20699 (pcase (org-element-type context)
20700 (`footnote-reference (org-edit-footnote-reference))
20701 (`inline-src-block (org-edit-inline-src-code))
20702 (`link (call-interactively #'ffap))
20703 (_ (user-error "No special environment to edit here"))))))))
20705 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20706 (defun org-ctrl-c-ctrl-c (&optional arg)
20707 "Set tags in headline, or update according to changed information at point.
20709 This command does many different things, depending on context:
20711 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20712 this is what we do.
20714 - If the cursor is on a statistics cookie, update it.
20716 - If the cursor is in a headline, prompt for tags and insert them
20717 into the current line, aligned to `org-tags-column'. When called
20718 with prefix arg, realign all tags in the current buffer.
20720 - If the cursor is in one of the special #+KEYWORD lines, this
20721 triggers scanning the buffer for these lines and updating the
20722 information.
20724 - If the cursor is inside a table, realign the table. This command
20725 works even if the automatic table editor has been turned off.
20727 - If the cursor is on a #+TBLFM line, re-apply the formulas to
20728 the entire table.
20730 - If the cursor is at a footnote reference or definition, jump to
20731 the corresponding definition or references, respectively.
20733 - If the cursor is a the beginning of a dynamic block, update it.
20735 - If the current buffer is a capture buffer, close note and file it.
20737 - If the cursor is on a <<<target>>>, update radio targets and
20738 corresponding links in this buffer.
20740 - If the cursor is on a numbered item in a plain list, renumber the
20741 ordered list.
20743 - If the cursor is on a checkbox, toggle it.
20745 - If the cursor is on a code block, evaluate it. The variable
20746 `org-confirm-babel-evaluate' can be used to control prompting
20747 before code block evaluation, by default every code block
20748 evaluation requires confirmation. Code block evaluation can be
20749 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
20750 (interactive "P")
20751 (cond
20752 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
20753 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
20754 (org-remove-occur-highlights)
20755 (message "Temporary highlights/overlays removed from current buffer"))
20756 ((and (local-variable-p 'org-finish-function)
20757 (fboundp org-finish-function))
20758 (funcall org-finish-function))
20759 ((org-babel-hash-at-point))
20760 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
20762 (let* ((context
20763 (org-element-lineage
20764 (org-element-context)
20765 ;; Limit to supported contexts.
20766 '(babel-call clock dynamic-block footnote-definition
20767 footnote-reference inline-babel-call inline-src-block
20768 inlinetask item keyword node-property paragraph
20769 plain-list property-drawer radio-target src-block
20770 statistics-cookie table table-cell table-row
20771 timestamp)
20773 (type (org-element-type context)))
20774 ;; For convenience: at the first line of a paragraph on the same
20775 ;; line as an item, apply function on that item instead.
20776 (when (eq type 'paragraph)
20777 (let ((parent (org-element-property :parent context)))
20778 (when (and (eq (org-element-type parent) 'item)
20779 (= (line-beginning-position)
20780 (org-element-property :begin parent)))
20781 (setq context parent)
20782 (setq type 'item))))
20783 ;; Act according to type of element or object at point.
20785 ;; Do nothing on a blank line, except if it is contained in
20786 ;; a src block. Hence, we first check if point is in such
20787 ;; a block and then if it is at a blank line.
20788 (pcase type
20789 ((or `inline-src-block `src-block)
20790 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
20791 (org-babel-eval-wipe-error-buffer)
20792 (org-babel-execute-src-block
20793 current-prefix-arg (org-babel-get-src-block-info nil context))))
20794 ((guard (org-match-line "[ \t]*$"))
20795 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
20796 (user-error
20797 (substitute-command-keys
20798 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
20799 ((or `babel-call `inline-babel-call)
20800 (let ((info (org-babel-lob-get-info context)))
20801 (when info (org-babel-execute-src-block nil info))))
20802 (`clock (org-clock-update-time-maybe))
20803 (`dynamic-block
20804 (save-excursion
20805 (goto-char (org-element-property :post-affiliated context))
20806 (org-update-dblock)))
20807 (`footnote-definition
20808 (goto-char (org-element-property :post-affiliated context))
20809 (call-interactively 'org-footnote-action))
20810 (`footnote-reference (call-interactively #'org-footnote-action))
20811 ((or `headline `inlinetask)
20812 (save-excursion (goto-char (org-element-property :begin context))
20813 (call-interactively #'org-set-tags)))
20814 (`item
20815 ;; At an item: `C-u C-u' sets checkbox to "[-]"
20816 ;; unconditionally, whereas `C-u' will toggle its presence.
20817 ;; Without a universal argument, if the item has a checkbox,
20818 ;; toggle it. Otherwise repair the list.
20819 (let* ((box (org-element-property :checkbox context))
20820 (struct (org-element-property :structure context))
20821 (old-struct (copy-tree struct))
20822 (parents (org-list-parents-alist struct))
20823 (prevs (org-list-prevs-alist struct))
20824 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
20825 (org-list-set-checkbox
20826 (org-element-property :begin context) struct
20827 (cond ((equal arg '(16)) "[-]")
20828 ((and (not box) (equal arg '(4))) "[ ]")
20829 ((or (not box) (equal arg '(4))) nil)
20830 ((eq box 'on) "[ ]")
20831 (t "[X]")))
20832 ;; Mimic `org-list-write-struct' but with grabbing a return
20833 ;; value from `org-list-struct-fix-box'.
20834 (org-list-struct-fix-ind struct parents 2)
20835 (org-list-struct-fix-item-end struct)
20836 (org-list-struct-fix-bul struct prevs)
20837 (org-list-struct-fix-ind struct parents)
20838 (let ((block-item
20839 (org-list-struct-fix-box struct parents prevs orderedp)))
20840 (if (and box (equal struct old-struct))
20841 (if (equal arg '(16))
20842 (message "Checkboxes already reset")
20843 (user-error "Cannot toggle this checkbox: %s"
20844 (if (eq box 'on)
20845 "all subitems checked"
20846 "unchecked subitems")))
20847 (org-list-struct-apply-struct struct old-struct)
20848 (org-update-checkbox-count-maybe))
20849 (when block-item
20850 (message "Checkboxes were removed due to empty box at line %d"
20851 (org-current-line block-item))))))
20852 (`keyword
20853 (let ((org-inhibit-startup-visibility-stuff t)
20854 (org-startup-align-all-tables nil))
20855 (when (boundp 'org-table-coordinate-overlays)
20856 (mapc #'delete-overlay org-table-coordinate-overlays)
20857 (setq org-table-coordinate-overlays nil))
20858 (org-save-outline-visibility 'use-markers (org-mode-restart)))
20859 (message "Local setup has been refreshed"))
20860 (`plain-list
20861 ;; At a plain list, with a double C-u argument, set
20862 ;; checkboxes of each item to "[-]", whereas a single one
20863 ;; will toggle their presence according to the state of the
20864 ;; first item in the list. Without an argument, repair the
20865 ;; list.
20866 (let* ((begin (org-element-property :contents-begin context))
20867 (beginm (move-marker (make-marker) begin))
20868 (struct (org-element-property :structure context))
20869 (old-struct (copy-tree struct))
20870 (first-box (save-excursion
20871 (goto-char begin)
20872 (looking-at org-list-full-item-re)
20873 (match-string-no-properties 3)))
20874 (new-box (cond ((equal arg '(16)) "[-]")
20875 ((equal arg '(4)) (unless first-box "[ ]"))
20876 ((equal first-box "[X]") "[ ]")
20877 (t "[X]"))))
20878 (cond
20879 (arg
20880 (dolist (pos
20881 (org-list-get-all-items
20882 begin struct (org-list-prevs-alist struct)))
20883 (org-list-set-checkbox pos struct new-box)))
20884 ((and first-box (eq (point) begin))
20885 ;; For convenience, when point is at bol on the first
20886 ;; item of the list and no argument is provided, simply
20887 ;; toggle checkbox of that item, if any.
20888 (org-list-set-checkbox begin struct new-box)))
20889 (org-list-write-struct
20890 struct (org-list-parents-alist struct) old-struct)
20891 (org-update-checkbox-count-maybe)
20892 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
20893 ((or `property-drawer `node-property)
20894 (call-interactively #'org-property-action))
20895 (`radio-target
20896 (call-interactively #'org-update-radio-target-regexp))
20897 (`statistics-cookie
20898 (call-interactively #'org-update-statistics-cookies))
20899 ((or `table `table-cell `table-row)
20900 ;; At a table, recalculate every field and align it. Also
20901 ;; send the table if necessary. If the table has
20902 ;; a `table.el' type, just give up. At a table row or cell,
20903 ;; maybe recalculate line but always align table.
20904 (if (eq (org-element-property :type context) 'table.el)
20905 (message "%s" (substitute-command-keys "\\<org-mode-map>\
20906 Use `\\[org-edit-special]' to edit table.el tables"))
20907 (if (or (eq type 'table)
20908 ;; Check if point is at a TBLFM line.
20909 (and (eq type 'table-row)
20910 (= (point) (org-element-property :end context))))
20911 (save-excursion
20912 (if (org-at-TBLFM-p)
20913 (progn (require 'org-table)
20914 (org-table-calc-current-TBLFM))
20915 (goto-char (org-element-property :contents-begin context))
20916 (org-call-with-arg 'org-table-recalculate (or arg t))
20917 (orgtbl-send-table 'maybe)))
20918 (org-table-maybe-eval-formula)
20919 (cond (arg (call-interactively #'org-table-recalculate))
20920 ((org-table-maybe-recalculate-line))
20921 (t (org-table-align))))))
20922 (`timestamp (org-timestamp-change 0 'day))
20923 ((and `nil (guard (org-at-heading-p)))
20924 ;; When point is on an unsupported object type, we can miss
20925 ;; the fact that it also is at a heading. Handle it here.
20926 (call-interactively #'org-set-tags))
20927 ((guard
20928 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
20930 (user-error
20931 (substitute-command-keys
20932 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
20934 (defun org-mode-restart ()
20935 (interactive)
20936 (let ((indent-status (bound-and-true-p org-indent-mode)))
20937 (funcall major-mode)
20938 (hack-local-variables)
20939 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
20940 (org-indent-mode -1))
20941 (org-reset-file-cache))
20942 (message "%s restarted" major-mode))
20944 (defun org-kill-note-or-show-branches ()
20945 "Abort storing current note, or call `outline-show-branches'."
20946 (interactive)
20947 (if (not org-finish-function)
20948 (progn
20949 (outline-hide-subtree)
20950 (call-interactively 'outline-show-branches))
20951 (let ((org-note-abort t))
20952 (funcall org-finish-function))))
20954 (defun org-delete-indentation (&optional arg)
20955 "Join current line to previous and fix whitespace at join.
20957 If previous line is a headline add to headline title. Otherwise
20958 the function calls `delete-indentation'.
20960 With a non-nil optional argument, join it to the following one."
20961 (interactive "*P")
20962 (if (save-excursion
20963 (beginning-of-line (if arg 1 0))
20964 (let ((case-fold-search nil))
20965 (looking-at org-complex-heading-regexp)))
20966 ;; At headline.
20967 (let ((tags-column (when (match-beginning 5)
20968 (save-excursion (goto-char (match-beginning 5))
20969 (current-column))))
20970 (string (concat " " (progn (when arg (forward-line 1))
20971 (org-trim (delete-and-extract-region
20972 (line-beginning-position)
20973 (line-end-position)))))))
20974 (unless (bobp) (delete-region (point) (1- (point))))
20975 (goto-char (or (match-end 4)
20976 (match-beginning 5)
20977 (match-end 0)))
20978 (skip-chars-backward " \t")
20979 (save-excursion (insert string))
20980 ;; Adjust alignment of tags.
20981 (cond
20982 ((not tags-column)) ;no tags
20983 (org-auto-align-tags (org-set-tags nil t))
20984 (t (org--align-tags-here tags-column)))) ;preserve tags column
20985 (delete-indentation arg)))
20987 (defun org-open-line (n)
20988 "Insert a new row in tables, call `open-line' elsewhere.
20989 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
20990 As a special case, when a document starts with a table, allow to
20991 call `open-line' on the very first character."
20992 (interactive "*p")
20993 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
20994 (org-table-insert-row)
20995 (open-line n)))
20997 (defun org-return (&optional indent)
20998 "Goto next table row or insert a newline.
21000 Calls `org-table-next-row' or `newline', depending on context.
21002 When optional INDENT argument is non-nil, call
21003 `newline-and-indent' instead of `newline'.
21005 When `org-return-follows-link' is non-nil and point is on
21006 a timestamp or a link, call `org-open-at-point'. However, it
21007 will not happen if point is in a table or on a \"dead\"
21008 object (e.g., within a comment). In these case, you need to use
21009 `org-open-at-point' directly."
21010 (interactive)
21011 (let ((context (if org-return-follows-link (org-element-context)
21012 (org-element-at-point))))
21013 (cond
21014 ;; In a table, call `org-table-next-row'.
21015 ((or (and (eq (org-element-type context) 'table)
21016 (>= (point) (org-element-property :contents-begin context))
21017 (< (point) (org-element-property :contents-end context)))
21018 (org-element-lineage context '(table-row table-cell) t))
21019 (org-table-justify-field-maybe)
21020 (call-interactively #'org-table-next-row))
21021 ;; On a link or a timestamp, call `org-open-at-point' if
21022 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21023 ;; locations, e.g., in a comment, as `org-open-at-point'.
21024 ((and org-return-follows-link
21025 (or (org-in-regexp org-ts-regexp-both nil t)
21026 (org-in-regexp org-tsr-regexp-both nil t)
21027 (org-in-regexp org-any-link-re nil t)))
21028 (call-interactively #'org-open-at-point))
21029 ;; Insert newline in heading, but preserve tags.
21030 ((and (not (bolp))
21031 (save-excursion (beginning-of-line)
21032 (let ((case-fold-search nil))
21033 (looking-at org-complex-heading-regexp))))
21034 ;; At headline. Split line. However, if point is on keyword,
21035 ;; priority cookie or tags, do not break any of them: add
21036 ;; a newline after the headline instead.
21037 (let ((tags-column (and (match-beginning 5)
21038 (save-excursion (goto-char (match-beginning 5))
21039 (current-column))))
21040 (string
21041 (when (and (match-end 4) (org-point-in-group (point) 4))
21042 (delete-and-extract-region (point) (match-end 4)))))
21043 ;; Adjust tag alignment.
21044 (cond
21045 ((not (and tags-column string)))
21046 (org-auto-align-tags (org-set-tags nil t))
21047 (t (org--align-tags-here tags-column))) ;preserve tags column
21048 (end-of-line)
21049 (org-show-entry)
21050 (if indent (newline-and-indent) (newline))
21051 (when string (save-excursion (insert (org-trim string))))))
21052 ;; In a list, make sure indenting keeps trailing text within.
21053 ((and indent
21054 (not (eolp))
21055 (org-element-lineage context '(item)))
21056 (let ((trailing-data
21057 (delete-and-extract-region (point) (line-end-position))))
21058 (newline-and-indent)
21059 (save-excursion (insert trailing-data))))
21060 (t (if indent (newline-and-indent) (newline))))))
21062 (defun org-return-indent ()
21063 "Goto next table row or insert a newline and indent.
21064 Calls `org-table-next-row' or `newline-and-indent', depending on
21065 context. See the individual commands for more information."
21066 (interactive)
21067 (org-return t))
21069 (defun org-ctrl-c-tab (&optional _arg)
21070 "Toggle columns width in a table, or show children.
21071 Call `org-table-toggle-column-width' if point is in a table.
21072 Otherwise, call `org-show-children'."
21073 (interactive "p")
21074 (call-interactively
21075 (if (org-at-table-p) #'org-table-toggle-column-width
21076 #'org-show-children)))
21078 (defun org-ctrl-c-star ()
21079 "Compute table, or change heading status of lines.
21080 Calls `org-table-recalculate' or `org-toggle-heading',
21081 depending on context."
21082 (interactive)
21083 (cond
21084 ((org-at-table-p)
21085 (call-interactively 'org-table-recalculate))
21087 ;; Convert all lines in region to list items
21088 (call-interactively 'org-toggle-heading))))
21090 (defun org-ctrl-c-minus ()
21091 "Insert separator line in table or modify bullet status of line.
21092 Also turns a plain line or a region of lines into list items.
21093 Calls `org-table-insert-hline', `org-toggle-item', or
21094 `org-cycle-list-bullet', depending on context."
21095 (interactive)
21096 (cond
21097 ((org-at-table-p)
21098 (call-interactively 'org-table-insert-hline))
21099 ((org-region-active-p)
21100 (call-interactively 'org-toggle-item))
21101 ((org-in-item-p)
21102 (call-interactively 'org-cycle-list-bullet))
21104 (call-interactively 'org-toggle-item))))
21106 (defun org-toggle-heading (&optional nstars)
21107 "Convert headings to normal text, or items or text to headings.
21108 If there is no active region, only convert the current line.
21110 With a `\\[universal-argument]' prefix, convert the whole list at
21111 point into heading.
21113 In a region:
21115 - If the first non blank line is a headline, remove the stars
21116 from all headlines in the region.
21118 - If it is a normal line, turn each and every normal line (i.e.,
21119 not an heading or an item) in the region into headings. If you
21120 want to convert only the first line of this region, use one
21121 universal prefix argument.
21123 - If it is a plain list item, turn all plain list items into headings.
21125 When converting a line into a heading, the number of stars is chosen
21126 such that the lines become children of the current entry. However,
21127 when a numeric prefix argument is given, its value determines the
21128 number of stars to add."
21129 (interactive "P")
21130 (let ((skip-blanks
21131 (function
21132 ;; Return beginning of first non-blank line, starting from
21133 ;; line at POS.
21134 (lambda (pos)
21135 (save-excursion
21136 (goto-char pos)
21137 (while (org-at-comment-p) (forward-line))
21138 (skip-chars-forward " \r\t\n")
21139 (point-at-bol)))))
21140 beg end toggled)
21141 ;; Determine boundaries of changes. If a universal prefix has
21142 ;; been given, put the list in a region. If region ends at a bol,
21143 ;; do not consider the last line to be in the region.
21145 (when (and current-prefix-arg (org-at-item-p))
21146 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21147 (org-mark-element))
21149 (if (org-region-active-p)
21150 (setq beg (funcall skip-blanks (region-beginning))
21151 end (copy-marker (save-excursion
21152 (goto-char (region-end))
21153 (if (bolp) (point) (point-at-eol)))))
21154 (setq beg (funcall skip-blanks (point-at-bol))
21155 end (copy-marker (point-at-eol))))
21156 ;; Ensure inline tasks don't count as headings.
21157 (org-with-limited-levels
21158 (save-excursion
21159 (goto-char beg)
21160 (cond
21161 ;; Case 1. Started at an heading: de-star headings.
21162 ((org-at-heading-p)
21163 (while (< (point) end)
21164 (when (org-at-heading-p t)
21165 (looking-at org-outline-regexp) (replace-match "")
21166 (setq toggled t))
21167 (forward-line)))
21168 ;; Case 2. Started at an item: change items into headlines.
21169 ;; One star will be added by `org-list-to-subtree'.
21170 ((org-at-item-p)
21171 (while (< (point) end)
21172 (when (org-at-item-p)
21173 ;; Pay attention to cases when region ends before list.
21174 (let* ((struct (org-list-struct))
21175 (list-end
21176 (min (org-list-get-bottom-point struct) (1+ end))))
21177 (save-restriction
21178 (narrow-to-region (point) list-end)
21179 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21180 (setq toggled t))
21181 (forward-line)))
21182 ;; Case 3. Started at normal text: make every line an heading,
21183 ;; skipping headlines and items.
21184 (t (let* ((stars
21185 (make-string
21186 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21187 (add-stars
21188 (cond (nstars "") ; stars from prefix only
21189 ((equal stars "") "*") ; before first heading
21190 (org-odd-levels-only "**") ; inside heading, odd
21191 (t "*"))) ; inside heading, oddeven
21192 (rpl (concat stars add-stars " "))
21193 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21194 (while (< (point) (if (equal nstars '(4)) lend end))
21195 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21196 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21197 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21198 (forward-line)))))))
21199 (unless toggled (message "Cannot toggle heading from here"))))
21201 (defun org-meta-return (&optional arg)
21202 "Insert a new heading or wrap a region in a table.
21203 Calls `org-insert-heading', `org-insert-item' or
21204 `org-table-wrap-region', depending on context. When called with
21205 an argument, unconditionally call `org-insert-heading'."
21206 (interactive "P")
21207 (org-check-before-invisible-edit 'insert)
21208 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21209 (call-interactively (cond (arg #'org-insert-heading)
21210 ((org-at-table-p) #'org-table-wrap-region)
21211 ((org-in-item-p) #'org-insert-item)
21212 (t #'org-insert-heading)))))
21214 ;;; Menu entries
21216 (defsubst org-in-subtree-not-table-p ()
21217 "Are we in a subtree and not in a table?"
21218 (and (not (org-before-first-heading-p))
21219 (not (org-at-table-p))))
21221 ;; Define the Org mode menus
21222 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21223 '("Tbl"
21224 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21225 ["Next Field" org-cycle (org-at-table-p)]
21226 ["Previous Field" org-shifttab (org-at-table-p)]
21227 ["Next Row" org-return (org-at-table-p)]
21228 "--"
21229 ["Blank Field" org-table-blank-field (org-at-table-p)]
21230 ["Edit Field" org-table-edit-field (org-at-table-p)]
21231 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21232 "--"
21233 ("Column"
21234 ["Move Column Left" org-metaleft (org-at-table-p)]
21235 ["Move Column Right" org-metaright (org-at-table-p)]
21236 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21237 ["Insert Column" org-shiftmetaright (org-at-table-p)]
21238 ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
21239 ("Row"
21240 ["Move Row Up" org-metaup (org-at-table-p)]
21241 ["Move Row Down" org-metadown (org-at-table-p)]
21242 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21243 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21244 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21245 "--"
21246 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21247 ("Rectangle"
21248 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21249 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21250 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21251 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21252 "--"
21253 ("Calculate"
21254 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21255 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21256 ["Edit Formulas" org-edit-special (org-at-table-p)]
21257 "--"
21258 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21259 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21260 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21261 "--"
21262 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21263 "--"
21264 ["Sum Column/Rectangle" org-table-sum
21265 (or (org-at-table-p) (org-region-active-p))]
21266 ["Which Column?" org-table-current-column (org-at-table-p)])
21267 ["Debug Formulas"
21268 org-table-toggle-formula-debugger
21269 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21270 ["Show Col/Row Numbers"
21271 org-table-toggle-coordinate-overlays
21272 :style toggle
21273 :selected (bound-and-true-p org-table-overlay-coordinates)]
21274 "--"
21275 ["Create" org-table-create (not (org-at-table-p))]
21276 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21277 ["Import from File" org-table-import (not (org-at-table-p))]
21278 ["Export to File" org-table-export (org-at-table-p)]
21279 "--"
21280 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21281 "--"
21282 ("Plot"
21283 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21284 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21286 (easy-menu-define org-org-menu org-mode-map "Org menu"
21287 '("Org"
21288 ("Show/Hide"
21289 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21290 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21291 ["Sparse Tree..." org-sparse-tree t]
21292 ["Reveal Context" org-reveal t]
21293 ["Show All" outline-show-all t]
21294 "--"
21295 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21296 "--"
21297 ["New Heading" org-insert-heading t]
21298 ("Navigate Headings"
21299 ["Up" outline-up-heading t]
21300 ["Next" outline-next-visible-heading t]
21301 ["Previous" outline-previous-visible-heading t]
21302 ["Next Same Level" outline-forward-same-level t]
21303 ["Previous Same Level" outline-backward-same-level t]
21304 "--"
21305 ["Jump" org-goto t])
21306 ("Edit Structure"
21307 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21308 "--"
21309 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21310 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21311 "--"
21312 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21313 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21314 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21315 "--"
21316 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21317 "--"
21318 ["Copy visible text" org-copy-visible t]
21319 "--"
21320 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21321 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21322 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21323 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21324 "--"
21325 ["Sort Region/Children" org-sort t]
21326 "--"
21327 ["Convert to odd levels" org-convert-to-odd-levels t]
21328 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21329 ("Editing"
21330 ["Emphasis..." org-emphasize t]
21331 ["Edit Source Example" org-edit-special t]
21332 "--"
21333 ["Footnote new/jump" org-footnote-action t]
21334 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21335 ("Archive"
21336 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21337 "--"
21338 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21339 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21340 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21342 "--"
21343 ("Hyperlinks"
21344 ["Store Link (Global)" org-store-link t]
21345 ["Find existing link to here" org-occur-link-in-agenda-files t]
21346 ["Insert Link" org-insert-link t]
21347 ["Follow Link" org-open-at-point t]
21348 "--"
21349 ["Next link" org-next-link t]
21350 ["Previous link" org-previous-link t]
21351 "--"
21352 ["Descriptive Links"
21353 org-toggle-link-display
21354 :style radio
21355 :selected org-descriptive-links
21357 ["Literal Links"
21358 org-toggle-link-display
21359 :style radio
21360 :selected (not org-descriptive-links)])
21361 "--"
21362 ("TODO Lists"
21363 ["TODO/DONE/-" org-todo t]
21364 ("Select keyword"
21365 ["Next keyword" org-shiftright (org-at-heading-p)]
21366 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21367 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21368 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21369 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21370 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21371 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21372 "--"
21373 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21374 :selected org-enforce-todo-dependencies :style toggle :active t]
21375 "Settings for tree at point"
21376 ["Do Children sequentially" org-toggle-ordered-property :style radio
21377 :selected (org-entry-get nil "ORDERED")
21378 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21379 ["Do Children parallel" org-toggle-ordered-property :style radio
21380 :selected (not (org-entry-get nil "ORDERED"))
21381 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21382 "--"
21383 ["Set Priority" org-priority t]
21384 ["Priority Up" org-shiftup t]
21385 ["Priority Down" org-shiftdown t]
21386 "--"
21387 ["Get news from all feeds" org-feed-update-all t]
21388 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21389 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21390 ("TAGS and Properties"
21391 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21392 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21393 "--"
21394 ["Set property" org-set-property (not (org-before-first-heading-p))]
21395 ["Column view of properties" org-columns t]
21396 ["Insert Column View DBlock" org-columns-insert-dblock t])
21397 ("Dates and Scheduling"
21398 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21399 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21400 ("Change Date"
21401 ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
21402 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
21403 ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
21404 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
21405 ["Compute Time Range" org-evaluate-time-range t]
21406 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21407 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21408 "--"
21409 ["Custom time format" org-toggle-time-stamp-overlays
21410 :style radio :selected org-display-custom-times]
21411 "--"
21412 ["Goto Calendar" org-goto-calendar t]
21413 ["Date from Calendar" org-date-from-calendar t]
21414 "--"
21415 ["Start/Restart Timer" org-timer-start t]
21416 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21417 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21418 ["Insert Timer String" org-timer t]
21419 ["Insert Timer Item" org-timer-item t])
21420 ("Logging work"
21421 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21422 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21423 ["Clock out" org-clock-out t]
21424 ["Clock cancel" org-clock-cancel t]
21425 "--"
21426 ["Mark as default task" org-clock-mark-default-task t]
21427 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21428 ["Goto running clock" org-clock-goto t]
21429 "--"
21430 ["Display times" org-clock-display t]
21431 ["Create clock table" org-clock-report t]
21432 "--"
21433 ["Record DONE time"
21434 (progn (setq org-log-done (not org-log-done))
21435 (message "Switching to %s will %s record a timestamp"
21436 (car org-done-keywords)
21437 (if org-log-done "automatically" "not")))
21438 :style toggle :selected org-log-done])
21439 "--"
21440 ["Agenda Command..." org-agenda t]
21441 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21442 ("File List for Agenda")
21443 ("Special views current file"
21444 ["TODO Tree" org-show-todo-tree t]
21445 ["Check Deadlines" org-check-deadlines t]
21446 ["Tags/Property tree" org-match-sparse-tree t])
21447 "--"
21448 ["Export/Publish..." org-export-dispatch t]
21449 ("LaTeX"
21450 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21451 :selected org-cdlatex-mode]
21452 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21453 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21454 ["Modify math symbol" org-cdlatex-math-modify
21455 (org-inside-LaTeX-fragment-p)]
21456 ["Insert citation" org-reftex-citation t])
21457 "--"
21458 ("MobileOrg"
21459 ["Push Files and Views" org-mobile-push t]
21460 ["Get Captured and Flagged" org-mobile-pull t]
21461 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21462 "--"
21463 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21464 "--"
21465 ("Documentation"
21466 ["Show Version" org-version t]
21467 ["Info Documentation" org-info t])
21468 ("Customize"
21469 ["Browse Org Group" org-customize t]
21470 "--"
21471 ["Expand This Menu" org-create-customize-menu
21472 (fboundp 'customize-menu-create)])
21473 ["Send bug report" org-submit-bug-report t]
21474 "--"
21475 ("Refresh/Reload"
21476 ["Refresh setup current buffer" org-mode-restart t]
21477 ["Reload Org (after update)" org-reload t]
21478 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21481 (defun org-info (&optional node)
21482 "Read documentation for Org in the info system.
21483 With optional NODE, go directly to that node."
21484 (interactive)
21485 (info (format "(org)%s" (or node ""))))
21487 ;;;###autoload
21488 (defun org-submit-bug-report ()
21489 "Submit a bug report on Org via mail.
21491 Don't hesitate to report any problems or inaccurate documentation.
21493 If you don't have setup sending mail from (X)Emacs, please copy the
21494 output buffer into your mail program, as it gives us important
21495 information about your Org version and configuration."
21496 (interactive)
21497 (require 'reporter)
21498 (defvar reporter-prompt-for-summary-p)
21499 (org-load-modules-maybe)
21500 (org-require-autoloaded-modules)
21501 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21502 (reporter-submit-bug-report
21503 "emacs-orgmode@gnu.org"
21504 (org-version nil 'full)
21505 (let (list)
21506 (save-window-excursion
21507 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21508 (delete-other-windows)
21509 (erase-buffer)
21510 (insert "You are about to submit a bug report to the Org mailing list.
21512 We would like to add your full Org and Outline configuration to the
21513 bug report. This greatly simplifies the work of the maintainer and
21514 other experts on the mailing list.
21516 HOWEVER, some variables you have customized may contain private
21517 information. The names of customers, colleagues, or friends, might
21518 appear in the form of file names, tags, todo states, or search strings.
21519 If you answer yes to the prompt, you might want to check and remove
21520 such private information before sending the email.")
21521 (add-text-properties (point-min) (point-max) '(face org-warning))
21522 (when (yes-or-no-p "Include your Org configuration ")
21523 (mapatoms
21524 (lambda (v)
21525 (and (boundp v)
21526 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21527 (or (and (symbol-value v)
21528 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21529 (and
21530 (get v 'custom-type) (get v 'standard-value)
21531 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21532 (push v list)))))
21533 (kill-buffer (get-buffer "*Warn about privacy*"))
21534 list))
21535 nil nil
21536 "Remember to cover the basics, that is, what you expected to happen and
21537 what in fact did happen. You don't know how to make a good report? See
21539 http://orgmode.org/manual/Feedback.html#Feedback
21541 Your bug report will be posted to the Org mailing list.
21542 ------------------------------------------------------------------------")
21543 (save-excursion
21544 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21545 (replace-match "\\1Bug: \\3 [\\2]")))))
21548 (defun org-install-agenda-files-menu ()
21549 (let ((bl (buffer-list)))
21550 (save-excursion
21551 (while bl
21552 (set-buffer (pop bl))
21553 (when (derived-mode-p 'org-mode) (setq bl nil)))
21554 (when (derived-mode-p 'org-mode)
21555 (easy-menu-change
21556 '("Org") "File List for Agenda"
21557 (append
21558 (list
21559 ["Edit File List" (org-edit-agenda-file-list) t]
21560 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21561 ["Remove Current File from List" org-remove-file t]
21562 ["Cycle through agenda files" org-cycle-agenda-files t]
21563 ["Occur in all agenda files" org-occur-in-agenda-files t]
21564 "--")
21565 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21567 ;;;; Documentation
21569 (defun org-require-autoloaded-modules ()
21570 (interactive)
21571 (mapc #'require
21572 '(org-agenda org-archive org-attach org-clock org-colview org-id
21573 org-table org-timer)))
21575 ;;;###autoload
21576 (defun org-reload (&optional uncompiled)
21577 "Reload all org lisp files.
21578 With prefix arg UNCOMPILED, load the uncompiled versions."
21579 (interactive "P")
21580 (require 'loadhist)
21581 (let* ((org-dir (org-find-library-dir "org"))
21582 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21583 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21584 (remove-re (format "\\`%s\\'"
21585 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21586 (feats (delete-dups
21587 (mapcar 'file-name-sans-extension
21588 (mapcar 'file-name-nondirectory
21589 (delq nil
21590 (mapcar 'feature-file
21591 features))))))
21592 (lfeat (append
21593 (sort
21594 (setq feats
21595 (delq nil (mapcar
21596 (lambda (f)
21597 (if (and (string-match feature-re f)
21598 (not (string-match remove-re f)))
21599 f nil))
21600 feats)))
21601 'string-lessp)
21602 (list "org-version" "org")))
21603 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21604 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21605 load-uncore load-misses)
21606 (setq load-misses
21607 (delq 't
21608 (mapcar (lambda (f)
21609 (or (org-load-noerror-mustsuffix (concat org-dir f))
21610 (and (string= org-dir contrib-dir)
21611 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21612 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21613 (add-to-list 'load-uncore f 'append)
21616 lfeat)))
21617 (when load-uncore
21618 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21619 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21620 (if load-misses
21621 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21622 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21623 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21625 ;;;###autoload
21626 (defun org-customize ()
21627 "Call the customize function with org as argument."
21628 (interactive)
21629 (org-load-modules-maybe)
21630 (org-require-autoloaded-modules)
21631 (customize-browse 'org))
21633 (defun org-create-customize-menu ()
21634 "Create a full customization menu for Org mode, insert it into the menu."
21635 (interactive)
21636 (org-load-modules-maybe)
21637 (org-require-autoloaded-modules)
21638 (if (fboundp 'customize-menu-create)
21639 (progn
21640 (easy-menu-change
21641 '("Org") "Customize"
21642 `(["Browse Org group" org-customize t]
21643 "--"
21644 ,(customize-menu-create 'org)
21645 ["Set" Custom-set t]
21646 ["Save" Custom-save t]
21647 ["Reset to Current" Custom-reset-current t]
21648 ["Reset to Saved" Custom-reset-saved t]
21649 ["Reset to Standard Settings" Custom-reset-standard t]))
21650 (message "\"Org\"-menu now contains full customization menu"))
21651 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21653 ;;;; Miscellaneous stuff
21655 ;;; Generally useful functions
21657 (defun org-get-at-eol (property n)
21658 "Get text property PROPERTY at the end of line less N characters."
21659 (get-text-property (- (point-at-eol) n) property))
21661 (defun org-find-text-property-in-string (prop s)
21662 "Return the first non-nil value of property PROP in string S."
21663 (or (get-text-property 0 prop s)
21664 (get-text-property (or (next-single-property-change 0 prop s) 0)
21665 prop s)))
21667 (defun org-display-warning (message)
21668 "Display the given MESSAGE as a warning."
21669 (display-warning 'org message :warning))
21671 (defun org-eval (form)
21672 "Eval FORM and return result."
21673 (condition-case error
21674 (eval form)
21675 (error (format "%%![Error: %s]" error))))
21677 (defun org-in-clocktable-p ()
21678 "Check if the cursor is in a clocktable."
21679 (let ((pos (point)) start)
21680 (save-excursion
21681 (end-of-line 1)
21682 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21683 (setq start (match-beginning 0))
21684 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21685 (>= (match-end 0) pos)
21686 start))))
21688 (defun org-in-verbatim-emphasis ()
21689 (save-match-data
21690 (and (org-in-regexp org-verbatim-re 2)
21691 (>= (point) (match-beginning 3))
21692 (<= (point) (match-end 4)))))
21694 (defun org-overlay-display (ovl text &optional face evap)
21695 "Make overlay OVL display TEXT with face FACE."
21696 (overlay-put ovl 'display text)
21697 (if face (overlay-put ovl 'face face))
21698 (if evap (overlay-put ovl 'evaporate t)))
21700 (defun org-overlay-before-string (ovl text &optional face evap)
21701 "Make overlay OVL display TEXT with face FACE."
21702 (if face (org-add-props text nil 'face face))
21703 (overlay-put ovl 'before-string text)
21704 (if evap (overlay-put ovl 'evaporate t)))
21706 (defun org-find-overlays (prop &optional pos delete)
21707 "Find all overlays specifying PROP at POS or point.
21708 If DELETE is non-nil, delete all those overlays."
21709 (let (found)
21710 (dolist (ov (overlays-at (or pos (point))) found)
21711 (cond ((not (overlay-get ov prop)))
21712 (delete (delete-overlay ov))
21713 (t (push ov found))))))
21715 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21716 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21717 (if (and marker (marker-buffer marker)
21718 (buffer-live-p (marker-buffer marker)))
21719 (progn
21720 (pop-to-buffer-same-window (marker-buffer marker))
21721 (when (or (> marker (point-max)) (< marker (point-min)))
21722 (widen))
21723 (goto-char marker)
21724 (org-show-context 'org-goto))
21725 (if bookmark
21726 (bookmark-jump bookmark)
21727 (error "Cannot find location"))))
21729 (defun org-quote-csv-field (s)
21730 "Quote field for inclusion in CSV material."
21731 (if (string-match "[\",]" s)
21732 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
21735 (defun org-force-self-insert (N)
21736 "Needed to enforce self-insert under remapping."
21737 (interactive "p")
21738 (self-insert-command N))
21740 (defun org-shorten-string (s maxlength)
21741 "Shorten string S so that it is no longer than MAXLENGTH characters.
21742 If the string is shorter or has length MAXLENGTH, just return the
21743 original string. If it is longer, the functions finds a space in the
21744 string, breaks this string off at that locations and adds three dots
21745 as ellipsis. Including the ellipsis, the string will not be longer
21746 than MAXLENGTH. If finding a good breaking point in the string does
21747 not work, the string is just chopped off in the middle of a word
21748 if necessary."
21749 (if (<= (length s) maxlength)
21751 (let* ((n (max (- maxlength 4) 1))
21752 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
21753 (if (string-match re s)
21754 (concat (match-string 1 s) "...")
21755 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
21757 (defun org-get-indentation (&optional line)
21758 "Get the indentation of the current line, interpreting tabs.
21759 When LINE is given, assume it represents a line and compute its indentation."
21760 (if line
21761 (when (string-match "^ *" (org-remove-tabs line))
21762 (match-end 0))
21763 (save-excursion
21764 (beginning-of-line 1)
21765 (skip-chars-forward " \t")
21766 (current-column))))
21768 (defun org-get-string-indentation (s)
21769 "What indentation has S due to SPACE and TAB at the beginning of the string?"
21770 (let ((n -1) (i 0) (w tab-width) c)
21771 (catch 'exit
21772 (while (< (setq n (1+ n)) (length s))
21773 (setq c (aref s n))
21774 (cond ((= c ?\ ) (setq i (1+ i)))
21775 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
21776 (t (throw 'exit t)))))
21779 (defun org-remove-tabs (s &optional width)
21780 "Replace tabulators in S with spaces.
21781 Assumes that s is a single line, starting in column 0."
21782 (setq width (or width tab-width))
21783 (while (string-match "\t" s)
21784 (setq s (replace-match
21785 (make-string
21786 (- (* width (/ (+ (match-beginning 0) width) width))
21787 (match-beginning 0)) ?\ )
21788 t t s)))
21791 (defun org-fix-indentation (line ind)
21792 "Fix indentation in LINE.
21793 IND is a cons cell with target and minimum indentation.
21794 If the current indentation in LINE is smaller than the minimum,
21795 leave it alone. If it is larger than ind, set it to the target."
21796 (let* ((l (org-remove-tabs line))
21797 (i (org-get-indentation l))
21798 (i1 (car ind)) (i2 (cdr ind)))
21799 (when (>= i i2) (setq l (substring line i2)))
21800 (if (> i1 0)
21801 (concat (make-string i1 ?\ ) l)
21802 l)))
21804 (defun org-remove-indentation (code &optional n)
21805 "Remove maximum common indentation in string CODE and return it.
21806 N may optionally be the number of columns to remove. Return CODE
21807 as-is if removal failed."
21808 (with-temp-buffer
21809 (insert code)
21810 (if (org-do-remove-indentation n) (buffer-string) code)))
21812 (defun org-do-remove-indentation (&optional n)
21813 "Remove the maximum common indentation from the buffer.
21814 When optional argument N is a positive integer, remove exactly
21815 that much characters from indentation, if possible. Return nil
21816 if it fails."
21817 (catch :exit
21818 (goto-char (point-min))
21819 ;; Find maximum common indentation, if not specified.
21820 (let ((n (or n
21821 (let ((min-ind (point-max)))
21822 (save-excursion
21823 (while (re-search-forward "^[ \t]*\\S-" nil t)
21824 (let ((ind (1- (current-column))))
21825 (if (zerop ind) (throw :exit nil)
21826 (setq min-ind (min min-ind ind))))))
21827 min-ind))))
21828 (if (zerop n) (throw :exit nil)
21829 ;; Remove exactly N indentation, but give up if not possible.
21830 (while (not (eobp))
21831 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
21832 (cond ((eolp) (delete-region (line-beginning-position) (point)))
21833 ((< ind n) (throw :exit nil))
21834 (t (indent-line-to (- ind n))))
21835 (forward-line)))
21836 ;; Signal success.
21837 t))))
21839 (defun org-fill-template (template alist)
21840 "Find each %key of ALIST in TEMPLATE and replace it."
21841 (let ((case-fold-search nil))
21842 (dolist (entry (sort (copy-sequence alist)
21843 (lambda (a b) (< (length (car a)) (length (car b))))))
21844 (setq template
21845 (replace-regexp-in-string
21846 (concat "%" (regexp-quote (car entry)))
21847 (or (cdr entry) "") template t t)))
21848 template))
21850 (defun org-base-buffer (buffer)
21851 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
21852 (if (not buffer)
21853 buffer
21854 (or (buffer-base-buffer buffer)
21855 buffer)))
21857 (defun org-wrap (string &optional width lines)
21858 "Wrap string to either a number of lines, or a width in characters.
21859 If WIDTH is non-nil, the string is wrapped to that width, however many lines
21860 that costs. If there is a word longer than WIDTH, the text is actually
21861 wrapped to the length of that word.
21862 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
21863 many lines, whatever width that takes.
21864 The return value is a list of lines, without newlines at the end."
21865 (let* ((words (split-string string))
21866 (maxword (apply 'max (mapcar 'org-string-width words)))
21867 w ll)
21868 (cond (width
21869 (org-do-wrap words (max maxword width)))
21870 (lines
21871 (setq w maxword)
21872 (setq ll (org-do-wrap words maxword))
21873 (if (<= (length ll) lines)
21875 (setq ll words)
21876 (while (> (length ll) lines)
21877 (setq w (1+ w))
21878 (setq ll (org-do-wrap words w)))
21879 ll))
21880 (t (error "Cannot wrap this")))))
21882 (defun org-do-wrap (words width)
21883 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
21884 (let (lines line)
21885 (while words
21886 (setq line (pop words))
21887 (while (and words (< (+ (length line) (length (car words))) width))
21888 (setq line (concat line " " (pop words))))
21889 (setq lines (push line lines)))
21890 (nreverse lines)))
21892 (defun org-quote-vert (s)
21893 "Replace \"|\" with \"\\vert\"."
21894 (while (string-match "|" s)
21895 (setq s (replace-match "\\vert" t t s)))
21898 (defun org-uuidgen-p (s)
21899 "Is S an ID created by UUIDGEN?"
21900 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
21902 (defun org-in-src-block-p (&optional inside)
21903 "Whether point is in a code source block.
21904 When INSIDE is non-nil, don't consider we are within a src block
21905 when point is at #+BEGIN_SRC or #+END_SRC."
21906 (let ((case-fold-search t))
21907 (or (and (eq (get-char-property (point) 'src-block) t))
21908 (and (not inside)
21909 (save-match-data
21910 (save-excursion
21911 (beginning-of-line)
21912 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
21914 (defun org-context ()
21915 "Return a list of contexts of the current cursor position.
21916 If several contexts apply, all are returned.
21917 Each context entry is a list with a symbol naming the context, and
21918 two positions indicating start and end of the context. Possible
21919 contexts are:
21921 :headline anywhere in a headline
21922 :headline-stars on the leading stars in a headline
21923 :todo-keyword on a TODO keyword (including DONE) in a headline
21924 :tags on the TAGS in a headline
21925 :priority on the priority cookie in a headline
21926 :item on the first line of a plain list item
21927 :item-bullet on the bullet/number of a plain list item
21928 :checkbox on the checkbox in a plain list item
21929 :table in an Org table
21930 :table-special on a special filed in a table
21931 :table-table in a table.el table
21932 :clocktable in a clocktable
21933 :src-block in a source block
21934 :link on a hyperlink
21935 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
21936 :target on a <<target>>
21937 :radio-target on a <<<radio-target>>>
21938 :latex-fragment on a LaTeX fragment
21939 :latex-preview on a LaTeX fragment with overlaid preview image
21941 This function expects the position to be visible because it uses font-lock
21942 faces as a help to recognize the following contexts: :table-special, :link,
21943 and :keyword."
21944 (let* ((f (get-text-property (point) 'face))
21945 (faces (if (listp f) f (list f)))
21946 (case-fold-search t)
21947 (p (point)) clist o)
21948 ;; First the large context
21949 (cond
21950 ((org-at-heading-p t)
21951 (push (list :headline (point-at-bol) (point-at-eol)) clist)
21952 (when (progn
21953 (beginning-of-line 1)
21954 (looking-at org-todo-line-tags-regexp))
21955 (push (org-point-in-group p 1 :headline-stars) clist)
21956 (push (org-point-in-group p 2 :todo-keyword) clist)
21957 (push (org-point-in-group p 4 :tags) clist))
21958 (goto-char p)
21959 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
21960 (when (looking-at "\\[#[A-Z0-9]\\]")
21961 (push (org-point-in-group p 0 :priority) clist)))
21963 ((org-at-item-p)
21964 (push (org-point-in-group p 2 :item-bullet) clist)
21965 (push (list :item (point-at-bol)
21966 (save-excursion (org-end-of-item) (point)))
21967 clist)
21968 (and (org-at-item-checkbox-p)
21969 (push (org-point-in-group p 0 :checkbox) clist)))
21971 ((org-at-table-p)
21972 (push (list :table (org-table-begin) (org-table-end)) clist)
21973 (when (memq 'org-formula faces)
21974 (push (list :table-special
21975 (previous-single-property-change p 'face)
21976 (next-single-property-change p 'face)) clist)))
21977 ((org-at-table-p 'any)
21978 (push (list :table-table) clist)))
21979 (goto-char p)
21981 (let ((case-fold-search t))
21982 ;; New the "medium" contexts: clocktables, source blocks
21983 (cond ((org-in-clocktable-p)
21984 (push (list :clocktable
21985 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
21986 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
21987 (match-beginning 1))
21988 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
21989 (match-end 0))) clist))
21990 ((org-in-src-block-p)
21991 (push (list :src-block
21992 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
21993 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
21994 (match-beginning 1))
21995 (and (search-forward "#+END_SRC" nil t)
21996 (match-beginning 0))) clist))))
21997 (goto-char p)
21999 ;; Now the small context
22000 (cond
22001 ((org-at-timestamp-p)
22002 (push (org-point-in-group p 0 :timestamp) clist))
22003 ((memq 'org-link faces)
22004 (push (list :link
22005 (previous-single-property-change p 'face)
22006 (next-single-property-change p 'face)) clist))
22007 ((memq 'org-special-keyword faces)
22008 (push (list :keyword
22009 (previous-single-property-change p 'face)
22010 (next-single-property-change p 'face)) clist))
22011 ((org-at-target-p)
22012 (push (org-point-in-group p 0 :target) clist)
22013 (goto-char (1- (match-beginning 0)))
22014 (when (looking-at org-radio-target-regexp)
22015 (push (org-point-in-group p 0 :radio-target) clist))
22016 (goto-char p))
22017 ((setq o (cl-some
22018 (lambda (o)
22019 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22021 (overlays-at (point))))
22022 (push (list :latex-fragment
22023 (overlay-start o) (overlay-end o)) clist)
22024 (push (list :latex-preview
22025 (overlay-start o) (overlay-end o)) clist))
22026 ((org-inside-LaTeX-fragment-p)
22027 ;; FIXME: positions wrong.
22028 (push (list :latex-fragment (point) (point)) clist)))
22030 (setq clist (nreverse (delq nil clist)))
22031 clist))
22033 (defun org-in-regexp (regexp &optional nlines visually)
22034 "Check if point is inside a match of REGEXP.
22036 Normally only the current line is checked, but you can include
22037 NLINES extra lines around point into the search. If VISUALLY is
22038 set, require that the cursor is not after the match but really
22039 on, so that the block visually is on the match.
22041 Return nil or a cons cell (BEG . END) where BEG and END are,
22042 respectively, the positions at the beginning and the end of the
22043 match."
22044 (catch :exit
22045 (let ((pos (point))
22046 (eol (line-end-position (if nlines (1+ nlines) 1))))
22047 (save-excursion
22048 (beginning-of-line (- 1 (or nlines 0)))
22049 (while (and (re-search-forward regexp eol t)
22050 (<= (match-beginning 0) pos))
22051 (let ((end (match-end 0)))
22052 (when (or (> end pos) (and (= end pos) (not visually)))
22053 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22055 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22056 "Non-nil when point is between matches of START-RE and END-RE.
22058 Also return a non-nil value when point is on one of the matches.
22060 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22061 buffer positions. Default values are the positions of headlines
22062 surrounding the point.
22064 The functions returns a cons cell whose car (resp. cdr) is the
22065 position before START-RE (resp. after END-RE)."
22066 (save-match-data
22067 (let ((pos (point))
22068 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22069 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22070 beg end)
22071 (save-excursion
22072 ;; Point is on a block when on START-RE or if START-RE can be
22073 ;; found before it...
22074 (and (or (org-in-regexp start-re)
22075 (re-search-backward start-re limit-up t))
22076 (setq beg (match-beginning 0))
22077 ;; ... and END-RE after it...
22078 (goto-char (match-end 0))
22079 (re-search-forward end-re limit-down t)
22080 (> (setq end (match-end 0)) pos)
22081 ;; ... without another START-RE in-between.
22082 (goto-char (match-beginning 0))
22083 (not (re-search-backward start-re (1+ beg) t))
22084 ;; Return value.
22085 (cons beg end))))))
22087 (defun org-in-block-p (names)
22088 "Non-nil when point belongs to a block whose name belongs to NAMES.
22090 NAMES is a list of strings containing names of blocks.
22092 Return first block name matched, or nil. Beware that in case of
22093 nested blocks, the returned name may not belong to the closest
22094 block from point."
22095 (save-match-data
22096 (catch 'exit
22097 (let ((case-fold-search t)
22098 (lim-up (save-excursion (outline-previous-heading)))
22099 (lim-down (save-excursion (outline-next-heading))))
22100 (dolist (name names)
22101 (let ((n (regexp-quote name)))
22102 (when (org-between-regexps-p
22103 (concat "^[ \t]*#\\+begin_" n)
22104 (concat "^[ \t]*#\\+end_" n)
22105 lim-up lim-down)
22106 (throw 'exit n)))))
22107 nil)))
22109 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22110 "Call `multi-occur' with buffers for all agenda files."
22111 (interactive "sOrg-files matching: ")
22112 (let* ((files (org-agenda-files))
22113 (tnames (mapcar #'file-truename files))
22114 (extra org-agenda-text-search-extra-files))
22115 (when (eq (car extra) 'agenda-archives)
22116 (setq extra (cdr extra))
22117 (setq files (org-add-archive-files files)))
22118 (dolist (f extra)
22119 (unless (member (file-truename f) tnames)
22120 (unless (member f files) (setq files (append files (list f))))
22121 (setq tnames (append tnames (list (file-truename f))))))
22122 (multi-occur
22123 (mapcar (lambda (x)
22124 (with-current-buffer
22125 ;; FIXME: Why not just (find-file-noselect x)?
22126 ;; Is it to avoid the "revert buffer" prompt?
22127 (or (get-file-buffer x) (find-file-noselect x))
22128 (widen)
22129 (current-buffer)))
22130 files)
22131 regexp)))
22133 (add-hook 'occur-mode-find-occurrence-hook
22134 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22136 (defun org-occur-link-in-agenda-files ()
22137 "Create a link and search for it in the agendas.
22138 The link is not stored in `org-stored-links', it is just created
22139 for the search purpose."
22140 (interactive)
22141 (let ((link (condition-case nil
22142 (org-store-link nil)
22143 (error "Unable to create a link to here"))))
22144 (org-occur-in-agenda-files (regexp-quote link))))
22146 (defun org-reverse-string (string)
22147 "Return the reverse of STRING."
22148 (apply 'string (reverse (string-to-list string))))
22150 ;; defsubst org-uniquify must be defined before first use
22152 (defun org-uniquify-alist (alist)
22153 "Merge elements of ALIST with the same key.
22155 For example, in this alist:
22157 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22158 => \\='((a 1 3) (b 2))
22160 merge (a 1) and (a 3) into (a 1 3).
22162 The function returns the new ALIST."
22163 (let (rtn)
22164 (dolist (e alist rtn)
22165 (let (n)
22166 (if (not (assoc (car e) rtn))
22167 (push e rtn)
22168 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22169 (setq rtn (assq-delete-all (car e) rtn))
22170 (push n rtn))))))
22172 (defun org-delete-all (elts list)
22173 "Remove all elements in ELTS from LIST.
22174 Comparison is done with `equal'. It is a destructive operation
22175 that may remove elements by altering the list structure."
22176 (while elts
22177 (setq list (delete (pop elts) list)))
22178 list)
22180 (defun org-back-over-empty-lines ()
22181 "Move backwards over whitespace, to the beginning of the first empty line.
22182 Returns the number of empty lines passed."
22183 (let ((pos (point)))
22184 (if (cdr (assq 'heading org-blank-before-new-entry))
22185 (skip-chars-backward " \t\n\r")
22186 (unless (eobp)
22187 (forward-line -1)))
22188 (beginning-of-line 2)
22189 (goto-char (min (point) pos))
22190 (count-lines (point) pos)))
22192 (defun org-skip-whitespace ()
22193 (skip-chars-forward " \t\n\r"))
22195 (defun org-point-in-group (point group &optional context)
22196 "Check if POINT is in match-group GROUP.
22197 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22198 match. If the match group does not exist or point is not inside it,
22199 return nil."
22200 (and (match-beginning group)
22201 (>= point (match-beginning group))
22202 (<= point (match-end group))
22203 (if context
22204 (list context (match-beginning group) (match-end group))
22205 t)))
22207 (defun org-switch-to-buffer-other-window (&rest args)
22208 "Switch to buffer in a second window on the current frame.
22209 In particular, do not allow pop-up frames.
22210 Returns the newly created buffer."
22211 (org-no-popups
22212 (apply 'switch-to-buffer-other-window args)))
22214 (defun org-combine-plists (&rest plists)
22215 "Create a single property list from all plists in PLISTS.
22216 The process starts by copying the first list, and then setting properties
22217 from the other lists. Settings in the last list are the most significant
22218 ones and overrule settings in the other lists."
22219 (let ((rtn (copy-sequence (pop plists)))
22220 p v ls)
22221 (while plists
22222 (setq ls (pop plists))
22223 (while ls
22224 (setq p (pop ls) v (pop ls))
22225 (setq rtn (plist-put rtn p v))))
22226 rtn))
22228 (defun org-replace-escapes (string table)
22229 "Replace %-escapes in STRING with values in TABLE.
22230 TABLE is an association list with keys like \"%a\" and string values.
22231 The sequences in STRING may contain normal field width and padding information,
22232 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22233 so values can contain further %-escapes if they are define later in TABLE."
22234 (let ((tbl (copy-alist table))
22235 (case-fold-search nil)
22236 (pchg 0)
22237 re rpl)
22238 (dolist (e tbl)
22239 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22240 (when (and (cdr e) (string-match re (cdr e)))
22241 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22242 (safe "SREF"))
22243 (add-text-properties 0 3 (list 'sref sref) safe)
22244 (setcdr e (replace-match safe t t (cdr e)))))
22245 (while (string-match re string)
22246 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22247 (cdr e)))
22248 (setq string (replace-match rpl t t string))))
22249 (while (setq pchg (next-property-change pchg string))
22250 (let ((sref (get-text-property pchg 'sref string)))
22251 (when (and sref (string-match "SREF" string pchg))
22252 (setq string (replace-match sref t t string)))))
22253 string))
22255 (defun org-find-base-buffer-visiting (file)
22256 "Like `find-buffer-visiting' but always return the base buffer and
22257 not an indirect buffer."
22258 (let ((buf (or (get-file-buffer file)
22259 (find-buffer-visiting file))))
22260 (if buf
22261 (or (buffer-base-buffer buf) buf)
22262 nil)))
22264 ;;; TODO: Only called once, from ox-odt which should probably use
22265 ;;; org-export-inline-image-p or something.
22266 (defun org-file-image-p (file)
22267 "Return non-nil if FILE is an image."
22268 (save-match-data
22269 (string-match (image-file-name-regexp) file)))
22271 (defun org-get-cursor-date (&optional with-time)
22272 "Return the date at cursor in as a time.
22273 This works in the calendar and in the agenda, anywhere else it just
22274 returns the current time.
22275 If WITH-TIME is non-nil, returns the time of the event at point (in
22276 the agenda) or the current time of the day."
22277 (let (date day defd tp hod mod)
22278 (when with-time
22279 (setq tp (get-text-property (point) 'time))
22280 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22281 (setq hod (string-to-number (match-string 1 tp))
22282 mod (string-to-number (match-string 2 tp))))
22283 (or tp (let ((now (decode-time)))
22284 (setq hod (nth 2 now)
22285 mod (nth 1 now)))))
22286 (cond
22287 ((eq major-mode 'calendar-mode)
22288 (setq date (calendar-cursor-to-date)
22289 defd (encode-time 0 (or mod 0) (or hod 0)
22290 (nth 1 date) (nth 0 date) (nth 2 date))))
22291 ((eq major-mode 'org-agenda-mode)
22292 (setq day (get-text-property (point) 'day))
22293 (when day
22294 (setq date (calendar-gregorian-from-absolute day)
22295 defd (encode-time 0 (or mod 0) (or hod 0)
22296 (nth 1 date) (nth 0 date) (nth 2 date))))))
22297 (or defd (current-time))))
22299 (defun org-mark-subtree (&optional up)
22300 "Mark the current subtree.
22301 This puts point at the start of the current subtree, and mark at
22302 the end. If a numeric prefix UP is given, move up into the
22303 hierarchy of headlines by UP levels before marking the subtree."
22304 (interactive "P")
22305 (org-with-limited-levels
22306 (cond ((org-at-heading-p) (beginning-of-line))
22307 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22308 (t (outline-previous-visible-heading 1))))
22309 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22310 (if (called-interactively-p 'any)
22311 (call-interactively 'org-mark-element)
22312 (org-mark-element)))
22314 (defun org-file-newer-than-p (file time)
22315 "Non-nil if FILE is newer than TIME.
22316 FILE is a filename, as a string, TIME is a list of integers, as
22317 returned by, e.g., `current-time'."
22318 (and (file-exists-p file)
22319 ;; Only compare times up to whole seconds as some file-systems
22320 ;; (e.g. HFS+) do not retain any finer granularity. As
22321 ;; a consequence, make sure we return non-nil when the two
22322 ;; times are equal.
22323 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22324 (cl-subseq time 0 2)))))
22326 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22327 "Compile a SOURCE file using PROCESS.
22329 PROCESS is either a function or a list of shell commands, as
22330 strings. EXT is a file extension, without the leading dot, as
22331 a string. It is used to check if the process actually succeeded.
22333 PROCESS must create a file with the same base name and directory
22334 as SOURCE, but ending with EXT. The function then returns its
22335 filename. Otherwise, it raises an error. The error message can
22336 then be refined by providing string ERR-MSG, which is appended to
22337 the standard message.
22339 If PROCESS is a function, it is called with a single argument:
22340 the SOURCE file.
22342 If it is a list of commands, each of them is called using
22343 `shell-command'. By default, in each command, %b, %f, %F, %o and
22344 %O are replaced with, respectively, SOURCE base name, name, full
22345 name, directory and absolute output file name. It is possible,
22346 however, to use more place-holders by specifying them in optional
22347 argument SPEC, as an alist following the pattern
22349 (CHARACTER . REPLACEMENT-STRING).
22351 When PROCESS is a list of commands, optional argument LOG-BUF can
22352 be set to a buffer or a buffer name. `shell-command' then uses
22353 it for output."
22354 (let* ((base-name (file-name-base source))
22355 (full-name (file-truename source))
22356 (out-dir (or (file-name-directory source) "./"))
22357 (output (expand-file-name (concat base-name "." ext) out-dir))
22358 (time (current-time))
22359 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22360 (save-window-excursion
22361 (pcase process
22362 ((pred functionp) (funcall process (shell-quote-argument source)))
22363 ((pred consp)
22364 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22365 (spec (append spec
22366 `((?b . ,(shell-quote-argument base-name))
22367 (?f . ,(shell-quote-argument source))
22368 (?F . ,(shell-quote-argument full-name))
22369 (?o . ,(shell-quote-argument out-dir))
22370 (?O . ,(shell-quote-argument output))))))
22371 (dolist (command process)
22372 (shell-command (format-spec command spec) log-buf))
22373 (when log-buf (with-current-buffer log-buf (compilation-mode)))))
22374 (_ (error "No valid command to process %S%s" source err-msg))))
22375 ;; Check for process failure. Output file is expected to be
22376 ;; located in the same directory as SOURCE.
22377 (unless (org-file-newer-than-p output time)
22378 (error (format "File %S wasn't produced%s" output err-msg)))
22379 output))
22381 ;;; Indentation
22383 (defvar org-element-greater-elements)
22384 (defun org--get-expected-indentation (element contentsp)
22385 "Expected indentation column for current line, according to ELEMENT.
22386 ELEMENT is an element containing point. CONTENTSP is non-nil
22387 when indentation is to be computed according to contents of
22388 ELEMENT."
22389 (let ((type (org-element-type element))
22390 (start (org-element-property :begin element))
22391 (post-affiliated (org-element-property :post-affiliated element)))
22392 (org-with-wide-buffer
22393 (cond
22394 (contentsp
22395 (cl-case type
22396 ((diary-sexp footnote-definition) 0)
22397 ((headline inlinetask nil)
22398 (if (not org-adapt-indentation) 0
22399 (let ((level (org-current-level)))
22400 (if level (1+ level) 0))))
22401 ((item plain-list) (org-list-item-body-column post-affiliated))
22403 (goto-char start)
22404 (org-get-indentation))))
22405 ((memq type '(headline inlinetask nil))
22406 (if (org-match-line "[ \t]*$")
22407 (org--get-expected-indentation element t)
22409 ((memq type '(diary-sexp footnote-definition)) 0)
22410 ;; First paragraph of a footnote definition or an item.
22411 ;; Indent like parent.
22412 ((< (line-beginning-position) start)
22413 (org--get-expected-indentation
22414 (org-element-property :parent element) t))
22415 ;; At first line: indent according to previous sibling, if any,
22416 ;; ignoring footnote definitions and inline tasks, or parent's
22417 ;; contents.
22418 ((= (line-beginning-position) start)
22419 (catch 'exit
22420 (while t
22421 (if (= (point-min) start) (throw 'exit 0)
22422 (goto-char (1- start))
22423 (let* ((previous (org-element-at-point))
22424 (parent previous))
22425 (while (and parent (<= (org-element-property :end parent) start))
22426 (setq previous parent
22427 parent (org-element-property :parent parent)))
22428 (cond
22429 ((not previous) (throw 'exit 0))
22430 ((> (org-element-property :end previous) start)
22431 (throw 'exit (org--get-expected-indentation previous t)))
22432 ((memq (org-element-type previous)
22433 '(footnote-definition inlinetask))
22434 (setq start (org-element-property :begin previous)))
22435 (t (goto-char (org-element-property :begin previous))
22436 (throw 'exit
22437 (if (bolp) (org-get-indentation)
22438 ;; At first paragraph in an item or
22439 ;; a footnote definition.
22440 (org--get-expected-indentation
22441 (org-element-property :parent previous) t))))))))))
22442 ;; Otherwise, move to the first non-blank line above.
22444 (beginning-of-line)
22445 (let ((pos (point)))
22446 (skip-chars-backward " \r\t\n")
22447 (cond
22448 ;; Two blank lines end a footnote definition or a plain
22449 ;; list. When we indent an empty line after them, the
22450 ;; containing list or footnote definition is over, so it
22451 ;; qualifies as a previous sibling. Therefore, we indent
22452 ;; like its first line.
22453 ((and (memq type '(footnote-definition plain-list))
22454 (> (count-lines (point) pos) 2))
22455 (goto-char start)
22456 (org-get-indentation))
22457 ;; Line above is the first one of a paragraph at the
22458 ;; beginning of an item or a footnote definition. Indent
22459 ;; like parent.
22460 ((< (line-beginning-position) start)
22461 (org--get-expected-indentation
22462 (org-element-property :parent element) t))
22463 ;; Line above is the beginning of an element, i.e., point
22464 ;; was originally on the blank lines between element's start
22465 ;; and contents.
22466 ((= (line-beginning-position) post-affiliated)
22467 (org--get-expected-indentation element t))
22468 ;; POS is after contents in a greater element. Indent like
22469 ;; the beginning of the element.
22470 ((and (memq type org-element-greater-elements)
22471 (let ((cend (org-element-property :contents-end element)))
22472 (and cend (<= cend pos))))
22473 ;; As a special case, if point is at the end of a footnote
22474 ;; definition or an item, indent like the very last element
22475 ;; within. If that last element is an item, indent like
22476 ;; its contents.
22477 (if (memq type '(footnote-definition item plain-list))
22478 (let ((last (org-element-at-point)))
22479 (goto-char pos)
22480 (org--get-expected-indentation
22481 last (eq (org-element-type last) 'item)))
22482 (goto-char start)
22483 (org-get-indentation)))
22484 ;; In any other case, indent like the current line.
22485 (t (org-get-indentation)))))))))
22487 (defun org--align-node-property ()
22488 "Align node property at point.
22489 Alignment is done according to `org-property-format', which see."
22490 (when (save-excursion
22491 (beginning-of-line)
22492 (looking-at org-property-re))
22493 (replace-match
22494 (concat (match-string 4)
22495 (org-trim
22496 (format org-property-format (match-string 1) (match-string 3))))
22497 t t)))
22499 (defun org-indent-line ()
22500 "Indent line depending on context.
22502 Indentation is done according to the following rules:
22504 - Footnote definitions, diary sexps, headlines and inline tasks
22505 have to start at column 0.
22507 - On the very first line of an element, consider, in order, the
22508 next rules until one matches:
22510 1. If there's a sibling element before, ignoring footnote
22511 definitions and inline tasks, indent like its first line.
22513 2. If element has a parent, indent like its contents. More
22514 precisely, if parent is an item, indent after the
22515 description part, if any, or the bullet (see
22516 `org-list-description-max-indent'). Else, indent like
22517 parent's first line.
22519 3. Otherwise, indent relatively to current level, if
22520 `org-adapt-indentation' is non-nil, or to left margin.
22522 - On a blank line at the end of an element, indent according to
22523 the type of the element. More precisely
22525 1. If element is a plain list, an item, or a footnote
22526 definition, indent like the very last element within.
22528 2. If element is a paragraph, indent like its last non blank
22529 line.
22531 3. Otherwise, indent like its very first line.
22533 - In the code part of a source block, use language major mode
22534 to indent current line if `org-src-tab-acts-natively' is
22535 non-nil. If it is nil, do nothing.
22537 - Otherwise, indent like the first non-blank line above.
22539 The function doesn't indent an item as it could break the whole
22540 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22541 `\\[org-shiftmetaright]'.
22543 Also align node properties according to `org-property-format'."
22544 (interactive)
22545 (cond
22546 (orgstruct-is-++
22547 (let ((indent-line-function
22548 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22549 (indent-according-to-mode)))
22550 ((org-at-heading-p) 'noindent)
22552 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22553 (type (org-element-type element)))
22554 (cond ((and (memq type '(plain-list item))
22555 (= (line-beginning-position)
22556 (org-element-property :post-affiliated element)))
22557 'noindent)
22558 ((and (eq type 'latex-environment)
22559 (>= (point) (org-element-property :post-affiliated element))
22560 (< (point) (org-with-wide-buffer
22561 (goto-char (org-element-property :end element))
22562 (skip-chars-backward " \r\t\n")
22563 (line-beginning-position 2))))
22564 'noindent)
22565 ((and (eq type 'src-block)
22566 org-src-tab-acts-natively
22567 (> (line-beginning-position)
22568 (org-element-property :post-affiliated element))
22569 (< (line-beginning-position)
22570 (org-with-wide-buffer
22571 (goto-char (org-element-property :end element))
22572 (skip-chars-backward " \r\t\n")
22573 (line-beginning-position))))
22574 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22576 (let ((column (org--get-expected-indentation element nil)))
22577 ;; Preserve current column.
22578 (if (<= (current-column) (current-indentation))
22579 (indent-line-to column)
22580 (save-excursion (indent-line-to column))))
22581 ;; Align node property. Also preserve current column.
22582 (when (eq type 'node-property)
22583 (let ((column (current-column)))
22584 (org--align-node-property)
22585 (org-move-to-column column)))))))))
22587 (defun org-indent-region (start end)
22588 "Indent each non-blank line in the region.
22589 Called from a program, START and END specify the region to
22590 indent. The function will not indent contents of example blocks,
22591 verse blocks and export blocks as leading white spaces are
22592 assumed to be significant there."
22593 (interactive "r")
22594 (save-excursion
22595 (goto-char start)
22596 (skip-chars-forward " \r\t\n")
22597 (unless (eobp) (beginning-of-line))
22598 (let ((indent-to
22599 (lambda (ind pos)
22600 ;; Set IND as indentation for all lines between point and
22601 ;; POS. Blank lines are ignored. Leave point after POS
22602 ;; once done.
22603 (let ((limit (copy-marker pos)))
22604 (while (< (point) limit)
22605 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22606 (forward-line))
22607 (set-marker limit nil))))
22608 (end (copy-marker end)))
22609 (while (< (point) end)
22610 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22611 (let* ((element (org-element-at-point))
22612 (type (org-element-type element))
22613 (element-end (copy-marker (org-element-property :end element)))
22614 (ind (org--get-expected-indentation element nil)))
22615 (cond
22616 ;; Element indented as a single block. Example blocks
22617 ;; preserving indentation are a special case since the
22618 ;; "contents" must not be indented whereas the block
22619 ;; boundaries can.
22620 ((or (memq type '(export-block latex-environment))
22621 (and (eq type 'example-block)
22622 (not
22623 (or org-src-preserve-indentation
22624 (org-element-property :preserve-indent element)))))
22625 (let ((offset (- ind (org-get-indentation))))
22626 (unless (zerop offset)
22627 (indent-rigidly (org-element-property :begin element)
22628 (org-element-property :end element)
22629 offset)))
22630 (goto-char element-end))
22631 ;; Elements indented line wise. Be sure to exclude
22632 ;; example blocks (preserving indentation) and source
22633 ;; blocks from this category as they are treated
22634 ;; specially later.
22635 ((or (memq type '(paragraph table table-row))
22636 (not (or (org-element-property :contents-begin element)
22637 (memq type '(example-block src-block)))))
22638 (when (eq type 'node-property)
22639 (org--align-node-property)
22640 (beginning-of-line))
22641 (funcall indent-to ind (min element-end end)))
22642 ;; Elements consisting of three parts: before the
22643 ;; contents, the contents, and after the contents. The
22644 ;; contents are treated specially, according to the
22645 ;; element type, or not indented at all. Other parts are
22646 ;; indented as a single block.
22648 (let* ((post (copy-marker
22649 (org-element-property :post-affiliated element)))
22650 (cbeg
22651 (copy-marker
22652 (cond
22653 ((not (org-element-property :contents-begin element))
22654 ;; Fake contents for source blocks.
22655 (org-with-wide-buffer
22656 (goto-char post)
22657 (line-beginning-position 2)))
22658 ((memq type '(footnote-definition item plain-list))
22659 ;; Contents in these elements could start on
22660 ;; the same line as the beginning of the
22661 ;; element. Make sure we start indenting
22662 ;; from the second line.
22663 (org-with-wide-buffer
22664 (goto-char post)
22665 (end-of-line)
22666 (skip-chars-forward " \r\t\n")
22667 (if (eobp) (point) (line-beginning-position))))
22668 (t (org-element-property :contents-begin element)))))
22669 (cend (copy-marker
22670 (or (org-element-property :contents-end element)
22671 ;; Fake contents for source blocks.
22672 (org-with-wide-buffer
22673 (goto-char element-end)
22674 (skip-chars-backward " \r\t\n")
22675 (line-beginning-position)))
22676 t)))
22677 ;; Do not change items indentation individually as it
22678 ;; might break the list as a whole. On the other
22679 ;; hand, when at a plain list, indent it as a whole.
22680 (cond ((eq type 'plain-list)
22681 (let ((offset (- ind (org-get-indentation))))
22682 (unless (zerop offset)
22683 (indent-rigidly (org-element-property :begin element)
22684 (org-element-property :end element)
22685 offset))
22686 (goto-char cbeg)))
22687 ((eq type 'item) (goto-char cbeg))
22688 (t (funcall indent-to ind (min cbeg end))))
22689 (when (< (point) end)
22690 (cl-case type
22691 ((example-block verse-block))
22692 (src-block
22693 ;; In a source block, indent source code
22694 ;; according to language major mode, but only if
22695 ;; `org-src-tab-acts-natively' is non-nil.
22696 (when (and (< (point) end) org-src-tab-acts-natively)
22697 (ignore-errors
22698 (org-babel-do-in-edit-buffer
22699 (indent-region (point-min) (point-max))))))
22700 (t (org-indent-region (point) (min cend end))))
22701 (goto-char (min cend end))
22702 (when (< (point) end)
22703 (funcall indent-to ind (min element-end end))))
22704 (set-marker post nil)
22705 (set-marker cbeg nil)
22706 (set-marker cend nil))))
22707 (set-marker element-end nil))))
22708 (set-marker end nil))))
22710 (defun org-indent-drawer ()
22711 "Indent the drawer at point."
22712 (interactive)
22713 (unless (save-excursion
22714 (beginning-of-line)
22715 (looking-at-p org-drawer-regexp))
22716 (user-error "Not at a drawer"))
22717 (let ((element (org-element-at-point)))
22718 (unless (memq (org-element-type element) '(drawer property-drawer))
22719 (user-error "Not at a drawer"))
22720 (org-with-wide-buffer
22721 (org-indent-region (org-element-property :begin element)
22722 (org-element-property :end element))))
22723 (message "Drawer at point indented"))
22725 (defun org-indent-block ()
22726 "Indent the block at point."
22727 (interactive)
22728 (unless (save-excursion
22729 (beginning-of-line)
22730 (let ((case-fold-search t))
22731 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
22732 (user-error "Not at a block"))
22733 (let ((element (org-element-at-point)))
22734 (unless (memq (org-element-type element)
22735 '(comment-block center-block dynamic-block example-block
22736 export-block quote-block special-block
22737 src-block verse-block))
22738 (user-error "Not at a block"))
22739 (org-with-wide-buffer
22740 (org-indent-region (org-element-property :begin element)
22741 (org-element-property :end element))))
22742 (message "Block at point indented"))
22745 ;;; Filling
22747 ;; We use our own fill-paragraph and auto-fill functions.
22749 ;; `org-fill-paragraph' relies on adaptive filling and context
22750 ;; checking. Appropriate `fill-prefix' is computed with
22751 ;; `org-adaptive-fill-function'.
22753 ;; `org-auto-fill-function' takes care of auto-filling. It calls
22754 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
22755 ;; `org-adaptive-fill-function' value. Internally,
22756 ;; `org-comment-line-break-function' breaks the line.
22758 ;; `org-setup-filling' installs filling and auto-filling related
22759 ;; variables during `org-mode' initialization.
22761 (defvar org-element-paragraph-separate) ; org-element.el
22762 (defun org-setup-filling ()
22763 (require 'org-element)
22764 ;; Prevent auto-fill from inserting unwanted new items.
22765 (when (boundp 'fill-nobreak-predicate)
22766 (setq-local
22767 fill-nobreak-predicate
22768 (org-uniquify
22769 (append fill-nobreak-predicate
22770 '(org-fill-line-break-nobreak-p
22771 org-fill-n-macro-as-item-nobreak-p
22772 org-fill-paragraph-with-timestamp-nobreak-p)))))
22773 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
22774 (setq-local paragraph-start paragraph-ending)
22775 (setq-local paragraph-separate paragraph-ending))
22776 (setq-local fill-paragraph-function 'org-fill-paragraph)
22777 (setq-local auto-fill-inhibit-regexp nil)
22778 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
22779 (setq-local normal-auto-fill-function 'org-auto-fill-function)
22780 (setq-local comment-line-break-function 'org-comment-line-break-function))
22782 (defun org-fill-line-break-nobreak-p ()
22783 "Non-nil when a new line at point would create an Org line break."
22784 (save-excursion
22785 (skip-chars-backward "[ \t]")
22786 (skip-chars-backward "\\\\")
22787 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
22789 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
22790 "Non-nil when a new line at point would split a timestamp."
22791 (and (org-at-timestamp-p 'lax)
22792 (not (looking-at org-ts-regexp-both))))
22794 (defun org-fill-n-macro-as-item-nobreak-p ()
22795 "Non-nil when a new line at point would create a new list."
22796 ;; During export, a "n" macro followed by a dot or a closing
22797 ;; parenthesis can end up being parsed as a new list item.
22798 (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
22800 (declare-function message-in-body-p "message" ())
22801 (defvar orgtbl-line-start-regexp) ; From org-table.el
22802 (defun org-adaptive-fill-function ()
22803 "Compute a fill prefix for the current line.
22804 Return fill prefix, as a string, or nil if current line isn't
22805 meant to be filled. For convenience, if `adaptive-fill-regexp'
22806 matches in paragraphs or comments, use it."
22807 (catch 'exit
22808 (when (derived-mode-p 'message-mode)
22809 (save-excursion
22810 (beginning-of-line)
22811 (cond ((not (message-in-body-p)) (throw 'exit nil))
22812 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
22813 ((looking-at message-cite-prefix-regexp)
22814 (throw 'exit (match-string-no-properties 0)))
22815 ((looking-at org-outline-regexp)
22816 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
22817 (org-with-wide-buffer
22818 (unless (org-at-heading-p)
22819 (let* ((p (line-beginning-position))
22820 (element (save-excursion
22821 (beginning-of-line)
22822 (org-element-at-point)))
22823 (type (org-element-type element))
22824 (post-affiliated (org-element-property :post-affiliated element)))
22825 (unless (< p post-affiliated)
22826 (cl-case type
22827 (comment
22828 (save-excursion
22829 (beginning-of-line)
22830 (looking-at "[ \t]*")
22831 (concat (match-string 0) "# ")))
22832 (footnote-definition "")
22833 ((item plain-list)
22834 (make-string (org-list-item-body-column post-affiliated) ?\s))
22835 (paragraph
22836 ;; Fill prefix is usually the same as the current line,
22837 ;; unless the paragraph is at the beginning of an item.
22838 (let ((parent (org-element-property :parent element)))
22839 (save-excursion
22840 (beginning-of-line)
22841 (cond ((eq (org-element-type parent) 'item)
22842 (make-string (org-list-item-body-column
22843 (org-element-property :begin parent))
22844 ?\s))
22845 ((and adaptive-fill-regexp
22846 ;; Locally disable
22847 ;; `adaptive-fill-function' to let
22848 ;; `fill-context-prefix' handle
22849 ;; `adaptive-fill-regexp' variable.
22850 (let (adaptive-fill-function)
22851 (fill-context-prefix
22852 post-affiliated
22853 (org-element-property :end element)))))
22854 ((looking-at "[ \t]+") (match-string 0))
22855 (t "")))))
22856 (comment-block
22857 ;; Only fill contents if P is within block boundaries.
22858 (let* ((cbeg (save-excursion (goto-char post-affiliated)
22859 (forward-line)
22860 (point)))
22861 (cend (save-excursion
22862 (goto-char (org-element-property :end element))
22863 (skip-chars-backward " \r\t\n")
22864 (line-beginning-position))))
22865 (when (and (>= p cbeg) (< p cend))
22866 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
22867 (match-string 0)
22868 "")))))))))))
22870 (declare-function message-goto-body "message" ())
22871 (defvar message-cite-prefix-regexp) ; From message.el
22873 (defun org-fill-element (&optional justify)
22874 "Fill element at point, when applicable.
22876 This function only applies to comment blocks, comments, example
22877 blocks and paragraphs. Also, as a special case, re-align table
22878 when point is at one.
22880 If JUSTIFY is non-nil (interactively, with prefix argument),
22881 justify as well. If `sentence-end-double-space' is non-nil, then
22882 period followed by one space does not end a sentence, so don't
22883 break a line there. The variable `fill-column' controls the
22884 width for filling.
22886 For convenience, when point is at a plain list, an item or
22887 a footnote definition, try to fill the first paragraph within."
22888 (with-syntax-table org-mode-transpose-word-syntax-table
22889 ;; Move to end of line in order to get the first paragraph within
22890 ;; a plain list or a footnote definition.
22891 (let ((element (save-excursion (end-of-line) (org-element-at-point))))
22892 ;; First check if point is in a blank line at the beginning of
22893 ;; the buffer. In that case, ignore filling.
22894 (cl-case (org-element-type element)
22895 ;; Use major mode filling function is src blocks.
22896 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
22897 ;; Align Org tables, leave table.el tables as-is.
22898 (table-row (org-table-align) t)
22899 (table
22900 (when (eq (org-element-property :type element) 'org)
22901 (save-excursion
22902 (goto-char (org-element-property :post-affiliated element))
22903 (org-table-align)))
22905 (paragraph
22906 ;; Paragraphs may contain `line-break' type objects.
22907 (let ((beg (max (point-min)
22908 (org-element-property :contents-begin element)))
22909 (end (min (point-max)
22910 (org-element-property :contents-end element))))
22911 ;; Do nothing if point is at an affiliated keyword.
22912 (if (< (line-end-position) beg) t
22913 (when (derived-mode-p 'message-mode)
22914 ;; In `message-mode', do not fill following citation
22915 ;; in current paragraph nor text before message body.
22916 (let ((body-start (save-excursion (message-goto-body))))
22917 (when body-start (setq beg (max body-start beg))))
22918 (when (save-excursion
22919 (re-search-forward
22920 (concat "^" message-cite-prefix-regexp) end t))
22921 (setq end (match-beginning 0))))
22922 ;; Fill paragraph, taking line breaks into account.
22923 (save-excursion
22924 (goto-char beg)
22925 (let ((cuts (list beg)))
22926 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
22927 (when (eq 'line-break
22928 (org-element-type
22929 (save-excursion (backward-char)
22930 (org-element-context))))
22931 (push (point) cuts)))
22932 (dolist (c (delq end cuts))
22933 (fill-region-as-paragraph c end justify)
22934 (setq end c))))
22935 t)))
22936 ;; Contents of `comment-block' type elements should be
22937 ;; filled as plain text, but only if point is within block
22938 ;; markers.
22939 (comment-block
22940 (let* ((case-fold-search t)
22941 (beg (save-excursion
22942 (goto-char (org-element-property :begin element))
22943 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
22944 (forward-line)
22945 (point)))
22946 (end (save-excursion
22947 (goto-char (org-element-property :end element))
22948 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
22949 (line-beginning-position))))
22950 (if (or (< (point) beg) (> (point) end)) t
22951 (fill-region-as-paragraph
22952 (save-excursion (end-of-line)
22953 (re-search-backward "^[ \t]*$" beg 'move)
22954 (line-beginning-position))
22955 (save-excursion (beginning-of-line)
22956 (re-search-forward "^[ \t]*$" end 'move)
22957 (line-beginning-position))
22958 justify))))
22959 ;; Fill comments.
22960 (comment
22961 (let ((begin (org-element-property :post-affiliated element))
22962 (end (org-element-property :end element)))
22963 (when (and (>= (point) begin) (<= (point) end))
22964 (let ((begin (save-excursion
22965 (end-of-line)
22966 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
22967 (progn (forward-line) (point))
22968 begin)))
22969 (end (save-excursion
22970 (end-of-line)
22971 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
22972 (1- (line-beginning-position))
22973 (skip-chars-backward " \r\t\n")
22974 (line-end-position)))))
22975 ;; Do not fill comments when at a blank line.
22976 (when (> end begin)
22977 (let ((fill-prefix
22978 (save-excursion
22979 (beginning-of-line)
22980 (looking-at "[ \t]*#")
22981 (let ((comment-prefix (match-string 0)))
22982 (goto-char (match-end 0))
22983 (if (looking-at adaptive-fill-regexp)
22984 (concat comment-prefix (match-string 0))
22985 (concat comment-prefix " "))))))
22986 (save-excursion
22987 (fill-region-as-paragraph begin end justify))))))
22989 ;; Ignore every other element.
22990 (otherwise t)))))
22992 (defun org-fill-paragraph (&optional justify region)
22993 "Fill element at point, when applicable.
22995 This function only applies to comment blocks, comments, example
22996 blocks and paragraphs. Also, as a special case, re-align table
22997 when point is at one.
22999 For convenience, when point is at a plain list, an item or
23000 a footnote definition, try to fill the first paragraph within.
23002 If JUSTIFY is non-nil (interactively, with prefix argument),
23003 justify as well. If `sentence-end-double-space' is non-nil, then
23004 period followed by one space does not end a sentence, so don't
23005 break a line there. The variable `fill-column' controls the
23006 width for filling.
23008 The REGION argument is non-nil if called interactively; in that
23009 case, if Transient Mark mode is enabled and the mark is active,
23010 fill each of the elements in the active region, instead of just
23011 filling the current element."
23012 (interactive (progn
23013 (barf-if-buffer-read-only)
23014 (list (if current-prefix-arg 'full) t)))
23015 (cond
23016 ((and (derived-mode-p 'message-mode)
23017 (or (not (message-in-body-p))
23018 (save-excursion (move-beginning-of-line 1)
23019 (looking-at message-cite-prefix-regexp))))
23020 ;; First ensure filling is correct in message-mode.
23021 (let ((fill-paragraph-function
23022 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23023 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23024 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23025 (paragraph-separate
23026 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23027 (fill-paragraph nil)))
23028 ((and region transient-mark-mode mark-active
23029 (not (eq (region-beginning) (region-end))))
23030 (let ((origin (point-marker))
23031 (start (region-beginning)))
23032 (unwind-protect
23033 (progn
23034 (goto-char (region-end))
23035 (while (> (point) start)
23036 (org-backward-paragraph)
23037 (org-fill-element justify)))
23038 (goto-char origin)
23039 (set-marker origin nil))))
23040 (t (org-fill-element justify))))
23041 (org-remap org-mode-map 'fill-paragraph 'org-fill-paragraph)
23043 (defun org-auto-fill-function ()
23044 "Auto-fill function."
23045 ;; Check if auto-filling is meaningful.
23046 (let ((fc (current-fill-column)))
23047 (when (and fc (> (current-column) fc))
23048 (let* ((fill-prefix (org-adaptive-fill-function))
23049 ;; Enforce empty fill prefix, if required. Otherwise, it
23050 ;; will be computed again.
23051 (adaptive-fill-mode (not (equal fill-prefix ""))))
23052 (when fill-prefix (do-auto-fill))))))
23054 (defun org-comment-line-break-function (&optional soft)
23055 "Break line at point and indent, continuing comment if within one.
23056 The inserted newline is marked hard if variable
23057 `use-hard-newlines' is true, unless optional argument SOFT is
23058 non-nil."
23059 (if soft (insert-and-inherit ?\n) (newline 1))
23060 (save-excursion (forward-char -1) (delete-horizontal-space))
23061 (delete-horizontal-space)
23062 (indent-to-left-margin)
23063 (insert-before-markers-and-inherit fill-prefix))
23066 ;;; Fixed Width Areas
23068 (defun org-toggle-fixed-width ()
23069 "Toggle fixed-width markup.
23071 Add or remove fixed-width markup on current line, whenever it
23072 makes sense. Return an error otherwise.
23074 If a region is active and if it contains only fixed-width areas
23075 or blank lines, remove all fixed-width markup in it. If the
23076 region contains anything else, convert all non-fixed-width lines
23077 to fixed-width ones.
23079 Blank lines at the end of the region are ignored unless the
23080 region only contains such lines."
23081 (interactive)
23082 (if (not (org-region-active-p))
23083 ;; No region:
23085 ;; Remove fixed width marker only in a fixed-with element.
23087 ;; Add fixed width maker in paragraphs, in blank lines after
23088 ;; elements or at the beginning of a headline or an inlinetask,
23089 ;; and before any one-line elements (e.g., a clock).
23090 (progn
23091 (beginning-of-line)
23092 (let* ((element (org-element-at-point))
23093 (type (org-element-type element)))
23094 (cond
23095 ((and (eq type 'fixed-width)
23096 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23097 (replace-match
23098 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23099 ((and (memq type '(babel-call clock comment diary-sexp headline
23100 horizontal-rule keyword paragraph
23101 planning))
23102 (<= (org-element-property :post-affiliated element) (point)))
23103 (skip-chars-forward " \t")
23104 (insert ": "))
23105 ((and (looking-at-p "[ \t]*$")
23106 (or (eq type 'inlinetask)
23107 (save-excursion
23108 (skip-chars-forward " \r\t\n")
23109 (<= (org-element-property :end element) (point)))))
23110 (delete-region (point) (line-end-position))
23111 (org-indent-line)
23112 (insert ": "))
23113 (t (user-error "Cannot insert a fixed-width line here")))))
23114 ;; Region active.
23115 (let* ((begin (save-excursion
23116 (goto-char (region-beginning))
23117 (line-beginning-position)))
23118 (end (copy-marker
23119 (save-excursion
23120 (goto-char (region-end))
23121 (unless (eolp) (beginning-of-line))
23122 (if (save-excursion (re-search-backward "\\S-" begin t))
23123 (progn (skip-chars-backward " \r\t\n") (point))
23124 (point)))))
23125 (all-fixed-width-p
23126 (catch 'not-all-p
23127 (save-excursion
23128 (goto-char begin)
23129 (skip-chars-forward " \r\t\n")
23130 (when (eobp) (throw 'not-all-p nil))
23131 (while (< (point) end)
23132 (let ((element (org-element-at-point)))
23133 (if (eq (org-element-type element) 'fixed-width)
23134 (goto-char (org-element-property :end element))
23135 (throw 'not-all-p nil))))
23136 t))))
23137 (if all-fixed-width-p
23138 (save-excursion
23139 (goto-char begin)
23140 (while (< (point) end)
23141 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23142 (replace-match
23143 "" nil nil nil
23144 (if (= (line-end-position) (match-end 0)) 0 1)))
23145 (forward-line)))
23146 (let ((min-ind (point-max)))
23147 ;; Find minimum indentation across all lines.
23148 (save-excursion
23149 (goto-char begin)
23150 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23151 (setq min-ind 0)
23152 (catch 'zerop
23153 (while (< (point) end)
23154 (unless (looking-at-p "[ \t]*$")
23155 (let ((ind (org-get-indentation)))
23156 (setq min-ind (min min-ind ind))
23157 (when (zerop ind) (throw 'zerop t))))
23158 (forward-line)))))
23159 ;; Loop over all lines and add fixed-width markup everywhere
23160 ;; but in fixed-width lines.
23161 (save-excursion
23162 (goto-char begin)
23163 (while (< (point) end)
23164 (cond
23165 ((org-at-heading-p)
23166 (insert ": ")
23167 (forward-line)
23168 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23169 (insert ":")
23170 (forward-line)))
23171 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23172 (let* ((element (org-element-at-point))
23173 (element-end (org-element-property :end element)))
23174 (if (eq (org-element-type element) 'fixed-width)
23175 (progn (goto-char element-end)
23176 (skip-chars-backward " \r\t\n")
23177 (forward-line))
23178 (let ((limit (min end element-end)))
23179 (while (< (point) limit)
23180 (org-move-to-column min-ind t)
23181 (insert ": ")
23182 (forward-line))))))
23184 (org-move-to-column min-ind t)
23185 (insert ": ")
23186 (forward-line)))))))
23187 (set-marker end nil))))
23190 ;;; Comments
23192 ;; Org comments syntax is quite complex. It requires the entire line
23193 ;; to be just a comment. Also, even with the right syntax at the
23194 ;; beginning of line, some elements (e.g., verse-block or
23195 ;; example-block) don't accept comments. Usual Emacs comment commands
23196 ;; cannot cope with those requirements. Therefore, Org replaces them.
23198 ;; Org still relies on `comment-dwim', but cannot trust
23199 ;; `comment-only-p'. So, `comment-region-function' and
23200 ;; `uncomment-region-function' both point
23201 ;; to`org-comment-or-uncomment-region'. Eventually,
23202 ;; `org-insert-comment' takes care of insertion of comments at the
23203 ;; beginning of line.
23205 ;; `org-setup-comments-handling' install comments related variables
23206 ;; during `org-mode' initialization.
23208 (defun org-setup-comments-handling ()
23209 (interactive)
23210 (setq-local comment-use-syntax nil)
23211 (setq-local comment-start "# ")
23212 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23213 (setq-local comment-insert-comment-function 'org-insert-comment)
23214 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23215 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23217 (defun org-insert-comment ()
23218 "Insert an empty comment above current line.
23219 If the line is empty, insert comment at its beginning. When
23220 point is within a source block, comment according to the related
23221 major mode."
23222 (if (let ((element (org-element-at-point)))
23223 (and (eq (org-element-type element) 'src-block)
23224 (< (save-excursion
23225 (goto-char (org-element-property :post-affiliated element))
23226 (line-end-position))
23227 (point))
23228 (> (save-excursion
23229 (goto-char (org-element-property :end element))
23230 (skip-chars-backward " \r\t\n")
23231 (line-beginning-position))
23232 (point))))
23233 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23234 (beginning-of-line)
23235 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23236 (open-line 1))
23237 (org-indent-line)
23238 (insert "# ")))
23240 (defvar comment-empty-lines) ; From newcomment.el.
23241 (defun org-comment-or-uncomment-region (beg end &rest _)
23242 "Comment or uncomment each non-blank line in the region.
23243 Uncomment each non-blank line between BEG and END if it only
23244 contains commented lines. Otherwise, comment them. If region is
23245 strictly within a source block, use appropriate comment syntax."
23246 (if (let ((element (org-element-at-point)))
23247 (and (eq (org-element-type element) 'src-block)
23248 (< (save-excursion
23249 (goto-char (org-element-property :post-affiliated element))
23250 (line-end-position))
23251 beg)
23252 (>= (save-excursion
23253 (goto-char (org-element-property :end element))
23254 (skip-chars-backward " \r\t\n")
23255 (line-beginning-position))
23256 end)))
23257 ;; Translate region boundaries for the Org buffer to the source
23258 ;; buffer.
23259 (let ((offset (- end beg)))
23260 (save-excursion
23261 (goto-char beg)
23262 (org-babel-do-in-edit-buffer
23263 (comment-or-uncomment-region (point) (+ offset (point))))))
23264 (save-restriction
23265 ;; Restrict region
23266 (narrow-to-region (save-excursion (goto-char beg)
23267 (skip-chars-forward " \r\t\n" end)
23268 (line-beginning-position))
23269 (save-excursion (goto-char end)
23270 (skip-chars-backward " \r\t\n" beg)
23271 (line-end-position)))
23272 (let ((uncommentp
23273 ;; UNCOMMENTP is non-nil when every non blank line between
23274 ;; BEG and END is a comment.
23275 (save-excursion
23276 (goto-char (point-min))
23277 (while (and (not (eobp))
23278 (let ((element (org-element-at-point)))
23279 (and (eq (org-element-type element) 'comment)
23280 (goto-char (min (point-max)
23281 (org-element-property
23282 :end element)))))))
23283 (eobp))))
23284 (if uncommentp
23285 ;; Only blank lines and comments in region: uncomment it.
23286 (save-excursion
23287 (goto-char (point-min))
23288 (while (not (eobp))
23289 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23290 (replace-match "" nil nil nil 1))
23291 (forward-line)))
23292 ;; Comment each line in region.
23293 (let ((min-indent (point-max)))
23294 ;; First find the minimum indentation across all lines.
23295 (save-excursion
23296 (goto-char (point-min))
23297 (while (and (not (eobp)) (not (zerop min-indent)))
23298 (unless (looking-at "[ \t]*$")
23299 (setq min-indent (min min-indent (current-indentation))))
23300 (forward-line)))
23301 ;; Then loop over all lines.
23302 (save-excursion
23303 (goto-char (point-min))
23304 (while (not (eobp))
23305 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23306 ;; Don't get fooled by invisible text (e.g. link path)
23307 ;; when moving to column MIN-INDENT.
23308 (let ((buffer-invisibility-spec nil))
23309 (org-move-to-column min-indent t))
23310 (insert comment-start))
23311 (forward-line)))))))))
23313 (defun org-comment-dwim (_arg)
23314 "Call `comment-dwim' within a source edit buffer if needed."
23315 (interactive "*P")
23316 (if (org-in-src-block-p)
23317 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23318 (call-interactively 'comment-dwim)))
23321 ;;; Timestamps API
23323 ;; This section contains tools to operate on timestamp objects, as
23324 ;; returned by, e.g. `org-element-context'.
23326 (defun org-timestamp--to-internal-time (timestamp &optional end)
23327 "Encode TIMESTAMP object into Emacs internal time.
23328 Use end of date range or time range when END is non-nil."
23329 (apply #'encode-time
23330 (cons 0
23331 (mapcar
23332 (lambda (prop) (or (org-element-property prop timestamp) 0))
23333 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23334 '(:minute-start :hour-start :day-start :month-start
23335 :year-start))))))
23337 (defun org-timestamp-has-time-p (timestamp)
23338 "Non-nil when TIMESTAMP has a time specified."
23339 (org-element-property :hour-start timestamp))
23341 (defun org-timestamp-format (timestamp format &optional end utc)
23342 "Format a TIMESTAMP object into a string.
23344 FORMAT is a format specifier to be passed to
23345 `format-time-string'.
23347 When optional argument END is non-nil, use end of date-range or
23348 time-range, if possible.
23350 When optional argument UTC is non-nil, time will be expressed as
23351 Universal Time."
23352 (format-time-string
23353 format (org-timestamp--to-internal-time timestamp end)
23354 (and utc t)))
23356 (defun org-timestamp-split-range (timestamp &optional end)
23357 "Extract a TIMESTAMP object from a date or time range.
23359 END, when non-nil, means extract the end of the range.
23360 Otherwise, extract its start.
23362 Return a new timestamp object."
23363 (let ((type (org-element-property :type timestamp)))
23364 (if (memq type '(active inactive diary)) timestamp
23365 (let ((split-ts (org-element-copy timestamp)))
23366 ;; Set new type.
23367 (org-element-put-property
23368 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23369 ;; Copy start properties over end properties if END is
23370 ;; non-nil. Otherwise, copy end properties over `start' ones.
23371 (let ((p-alist '((:minute-start . :minute-end)
23372 (:hour-start . :hour-end)
23373 (:day-start . :day-end)
23374 (:month-start . :month-end)
23375 (:year-start . :year-end))))
23376 (dolist (p-cell p-alist)
23377 (org-element-put-property
23378 split-ts
23379 (funcall (if end #'car #'cdr) p-cell)
23380 (org-element-property
23381 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23382 ;; Eventually refresh `:raw-value'.
23383 (org-element-put-property split-ts :raw-value nil)
23384 (org-element-put-property
23385 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23387 (defun org-timestamp-translate (timestamp &optional boundary)
23388 "Translate TIMESTAMP object to custom format.
23390 Format string is defined in `org-time-stamp-custom-formats',
23391 which see.
23393 When optional argument BOUNDARY is non-nil, it is either the
23394 symbol `start' or `end'. In this case, only translate the
23395 starting or ending part of TIMESTAMP if it is a date or time
23396 range. Otherwise, translate both parts.
23398 Return timestamp as-is if `org-display-custom-times' is nil or if
23399 it has a `diary' type."
23400 (let ((type (org-element-property :type timestamp)))
23401 (if (or (not org-display-custom-times) (eq type 'diary))
23402 (org-element-interpret-data timestamp)
23403 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23404 org-time-stamp-custom-formats)))
23405 (if (and (not boundary) (memq type '(active-range inactive-range)))
23406 (concat (org-timestamp-format timestamp fmt)
23407 "--"
23408 (org-timestamp-format timestamp fmt t))
23409 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23413 ;;; Other stuff.
23415 (defvar reftex-docstruct-symbol)
23416 (defvar org--rds)
23418 (defun org-reftex-citation ()
23419 "Use reftex-citation to insert a citation into the buffer.
23420 This looks for a line like
23422 #+BIBLIOGRAPHY: foo plain option:-d
23424 and derives from it that foo.bib is the bibliography file relevant
23425 for this document. It then installs the necessary environment for RefTeX
23426 to work in this buffer and calls `reftex-citation' to insert a citation
23427 into the buffer.
23429 Export of such citations to both LaTeX and HTML is handled by the contributed
23430 package ox-bibtex by Taru Karttunen."
23431 (interactive)
23432 (let ((reftex-docstruct-symbol 'org--rds)
23433 org--rds bib)
23434 (org-with-wide-buffer
23435 (let ((case-fold-search t)
23436 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23437 (if (not (save-excursion
23438 (or (re-search-forward re nil t)
23439 (re-search-backward re nil t))))
23440 (user-error "No bibliography defined in file")
23441 (setq bib (concat (match-string 1) ".bib")
23442 org--rds (list (list 'bib bib))))))
23443 (call-interactively 'reftex-citation)))
23445 ;;;; Functions extending outline functionality
23447 (defun org-beginning-of-line (&optional n)
23448 "Go to the beginning of the current visible line.
23450 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23451 tags on the first attempt, and only move to after the tags when
23452 the cursor is already beyond the end of the headline.
23454 With argument N not nil or 1, move forward N - 1 lines first."
23455 (interactive "^p")
23456 (let ((origin (point))
23457 (special (pcase org-special-ctrl-a/e
23458 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23459 deactivate-mark)
23460 ;; First move to a visible line.
23461 (if (bound-and-true-p visual-line-mode)
23462 (beginning-of-visual-line n)
23463 (move-beginning-of-line n)
23464 ;; `move-beginning-of-line' may leave point after invisible
23465 ;; characters if line starts with such of these (e.g., with
23466 ;; a link at column 0). Really move to the beginning of the
23467 ;; current visible line.
23468 (beginning-of-line))
23469 (cond
23470 ;; No special behavior. Point is already at the beginning of
23471 ;; a line, logical or visual.
23472 ((not special))
23473 ;; `beginning-of-visual-line' left point before logical beginning
23474 ;; of line: point is at the beginning of a visual line. Bail
23475 ;; out.
23476 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23477 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23478 ;; At a headline, special position is before the title, but
23479 ;; after any TODO keyword or priority cookie.
23480 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23481 (line-end-position)))
23482 (bol (point)))
23483 (if (eq special 'reversed)
23484 (when (and (= origin bol) (eq last-command this-command))
23485 (goto-char refpos))
23486 (when (or (> origin refpos) (= origin bol))
23487 (goto-char refpos)))))
23488 ((and (looking-at org-list-full-item-re)
23489 (memq (org-element-type (save-match-data (org-element-at-point)))
23490 '(item plain-list)))
23491 ;; Set special position at first white space character after
23492 ;; bullet, and check-box, if any.
23493 (let ((after-bullet
23494 (let ((box (match-end 3)))
23495 (cond ((not box) (match-end 1))
23496 ((eq (char-after box) ?\s) (1+ box))
23497 (t box)))))
23498 (if (eq special 'reversed)
23499 (when (and (= (point) origin) (eq last-command this-command))
23500 (goto-char after-bullet))
23501 (when (or (> origin after-bullet) (= (point) origin))
23502 (goto-char after-bullet)))))
23503 ;; No special context. Point is already at beginning of line.
23504 (t nil))))
23506 (defun org-end-of-line (&optional n)
23507 "Go to the end of the line, but before ellipsis, if any.
23509 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23510 tags on the first attempt, and only move to after the tags when
23511 the cursor is already beyond the end of the headline.
23513 With argument N not nil or 1, move forward N - 1 lines first."
23514 (interactive "^p")
23515 (let ((origin (point))
23516 (special (pcase org-special-ctrl-a/e
23517 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23518 deactivate-mark)
23519 ;; First move to a visible line.
23520 (if (bound-and-true-p visual-line-mode)
23521 (beginning-of-visual-line n)
23522 (move-beginning-of-line n))
23523 (cond
23524 ;; At a headline, with tags.
23525 ((and special
23526 (save-excursion
23527 (beginning-of-line)
23528 (let ((case-fold-search nil))
23529 (looking-at org-complex-heading-regexp)))
23530 (match-end 5))
23531 (let ((tags (save-excursion
23532 (goto-char (match-beginning 5))
23533 (skip-chars-backward " \t")
23534 (point)))
23535 (visual-end (and (bound-and-true-p visual-line-mode)
23536 (save-excursion
23537 (end-of-visual-line)
23538 (point)))))
23539 ;; If `end-of-visual-line' brings us before end of line or
23540 ;; even tags, i.e., the headline spans over multiple visual
23541 ;; lines, move there.
23542 (cond ((and visual-end
23543 (< visual-end tags)
23544 (<= origin visual-end))
23545 (goto-char visual-end))
23546 ((eq special 'reversed)
23547 (if (and (= origin (line-end-position))
23548 (eq this-command last-command))
23549 (goto-char tags)
23550 (end-of-line)))
23552 (if (or (< origin tags) (= origin (line-end-position)))
23553 (goto-char tags)
23554 (end-of-line))))))
23555 ((bound-and-true-p visual-line-mode)
23556 (let ((bol (line-beginning-position)))
23557 (end-of-visual-line)
23558 ;; If `end-of-visual-line' gets us past the ellipsis at the
23559 ;; end of a line, backtrack and use `end-of-line' instead.
23560 (when (/= bol (line-beginning-position))
23561 (goto-char bol)
23562 (end-of-line))))
23563 (t (end-of-line)))))
23565 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23566 (define-key org-mode-map "\C-e" 'org-end-of-line)
23568 (defun org-backward-sentence (&optional _arg)
23569 "Go to beginning of sentence, or beginning of table field.
23570 This will call `backward-sentence' or `org-table-beginning-of-field',
23571 depending on context."
23572 (interactive)
23573 (let* ((element (org-element-at-point))
23574 (contents-begin (org-element-property :contents-begin element))
23575 (table (org-element-lineage element '(table) t)))
23576 (if (and table
23577 (> (point) contents-begin)
23578 (<= (point) (org-element-property :contents-end table)))
23579 (call-interactively #'org-table-beginning-of-field)
23580 (save-restriction
23581 (when (and contents-begin
23582 (< (point-min) contents-begin)
23583 (> (point) contents-begin))
23584 (narrow-to-region contents-begin
23585 (org-element-property :contents-end element)))
23586 (call-interactively #'backward-sentence)))))
23588 (defun org-forward-sentence (&optional _arg)
23589 "Go to end of sentence, or end of table field.
23590 This will call `forward-sentence' or `org-table-end-of-field',
23591 depending on context."
23592 (interactive)
23593 (if (and (org-at-heading-p)
23594 (save-restriction (skip-chars-forward " \t") (not (eolp))))
23595 (save-restriction
23596 (narrow-to-region (line-beginning-position) (line-end-position))
23597 (call-interactively #'forward-sentence))
23598 (let* ((element (org-element-at-point))
23599 (contents-end (org-element-property :contents-end element))
23600 (table (org-element-lineage element '(table) t)))
23601 (if (and table
23602 (>= (point) (org-element-property :contents-begin table))
23603 (< (point) contents-end))
23604 (call-interactively #'org-table-end-of-field)
23605 (save-restriction
23606 (when (and contents-end
23607 (> (point-max) contents-end)
23608 ;; Skip blank lines between elements.
23609 (< (org-element-property :end element)
23610 (save-excursion (goto-char contents-end)
23611 (skip-chars-forward " \r\t\n"))))
23612 (narrow-to-region (org-element-property :contents-begin element)
23613 contents-end))
23614 (call-interactively #'forward-sentence))))))
23616 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23617 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23619 (defun org-kill-line (&optional _arg)
23620 "Kill line, to tags or end of line."
23621 (interactive)
23622 (cond
23623 ((or (not org-special-ctrl-k)
23624 (bolp)
23625 (not (org-at-heading-p)))
23626 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23627 org-ctrl-k-protect-subtree
23628 (or (eq org-ctrl-k-protect-subtree 'error)
23629 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23630 (user-error "C-k aborted as it would kill a hidden subtree"))
23631 (call-interactively
23632 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23633 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23634 (kill-region (point) (match-beginning 1))
23635 (org-set-tags nil t))
23636 (t (kill-region (point) (point-at-eol)))))
23638 (define-key org-mode-map "\C-k" 'org-kill-line)
23640 (defun org-yank (&optional arg)
23641 "Yank. If the kill is a subtree, treat it specially.
23642 This command will look at the current kill and check if is a single
23643 subtree, or a series of subtrees[1]. If it passes the test, and if the
23644 cursor is at the beginning of a line or after the stars of a currently
23645 empty headline, then the yank is handled specially. How exactly depends
23646 on the value of the following variables.
23648 `org-yank-folded-subtrees'
23649 By default, this variable is non-nil, which results in
23650 subtree(s) being folded after insertion, except if doing so
23651 would swallow text after the yanked text.
23653 `org-yank-adjusted-subtrees'
23654 When non-nil (the default value is nil), the subtree will be
23655 promoted or demoted in order to fit into the local outline tree
23656 structure, which means that the level will be adjusted so that it
23657 becomes the smaller one of the two *visible* surrounding headings.
23659 Any prefix to this command will cause `yank' to be called directly with
23660 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23661 will just
23662 plainly yank the text as it is.
23664 \[1] The test checks if the first non-white line is a heading
23665 and if there are no other headings with fewer stars."
23666 (interactive "P")
23667 (org-yank-generic 'yank arg))
23669 (defun org-yank-generic (command arg)
23670 "Perform some yank-like command.
23672 This function implements the behavior described in the `org-yank'
23673 documentation. However, it has been generalized to work for any
23674 interactive command with similar behavior."
23676 ;; pretend to be command COMMAND
23677 (setq this-command command)
23679 (if arg
23680 (call-interactively command)
23682 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23683 (and (org-kill-is-subtree-p)
23684 (or (bolp)
23685 (and (looking-at "[ \t]*$")
23686 (string-match
23687 "\\`\\*+\\'"
23688 (buffer-substring (point-at-bol) (point)))))))
23689 swallowp)
23690 (cond
23691 ((and subtreep org-yank-folded-subtrees)
23692 (let ((beg (point))
23693 end)
23694 (if (and subtreep org-yank-adjusted-subtrees)
23695 (org-paste-subtree nil nil 'for-yank)
23696 (call-interactively command))
23698 (setq end (point))
23699 (goto-char beg)
23700 (when (and (bolp) subtreep
23701 (not (setq swallowp
23702 (org-yank-folding-would-swallow-text beg end))))
23703 (org-with-limited-levels
23704 (or (looking-at org-outline-regexp)
23705 (re-search-forward org-outline-regexp-bol end t))
23706 (while (and (< (point) end) (looking-at org-outline-regexp))
23707 (outline-hide-subtree)
23708 (org-cycle-show-empty-lines 'folded)
23709 (condition-case nil
23710 (outline-forward-same-level 1)
23711 (error (goto-char end))))))
23712 (when swallowp
23713 (message
23714 "Inserted text not folded because that would swallow text"))
23716 (goto-char end)
23717 (skip-chars-forward " \t\n\r")
23718 (beginning-of-line 1)
23719 (push-mark beg 'nomsg)))
23720 ((and subtreep org-yank-adjusted-subtrees)
23721 (let ((beg (point-at-bol)))
23722 (org-paste-subtree nil nil 'for-yank)
23723 (push-mark beg 'nomsg)))
23725 (call-interactively command))))))
23727 (defun org-yank-folding-would-swallow-text (beg end)
23728 "Would hide-subtree at BEG swallow any text after END?"
23729 (let (level)
23730 (org-with-limited-levels
23731 (save-excursion
23732 (goto-char beg)
23733 (when (or (looking-at org-outline-regexp)
23734 (re-search-forward org-outline-regexp-bol end t))
23735 (setq level (org-outline-level)))
23736 (goto-char end)
23737 (skip-chars-forward " \t\r\n\v\f")
23738 (not (or (eobp)
23739 (and (bolp) (looking-at-p org-outline-regexp)
23740 (<= (org-outline-level) level))))))))
23742 (define-key org-mode-map "\C-y" 'org-yank)
23744 (defun org-truely-invisible-p ()
23745 "Check if point is at a character currently not visible.
23746 This version does not only check the character property, but also
23747 `visible-mode'."
23748 (unless (bound-and-true-p visible-mode)
23749 (org-invisible-p)))
23751 (defun org-invisible-p2 ()
23752 "Check if point is at a character currently not visible.
23754 If the point is at EOL (and not at the beginning of a buffer too),
23755 move it back by one char before doing this check."
23756 (save-excursion
23757 (when (and (eolp) (not (bobp)))
23758 (backward-char 1))
23759 (org-invisible-p)))
23761 (defun org-back-to-heading (&optional invisible-ok)
23762 "Call `outline-back-to-heading', but provide a better error message."
23763 (condition-case nil
23764 (outline-back-to-heading invisible-ok)
23765 (error (error "Before first headline at position %d in buffer %s"
23766 (point) (current-buffer)))))
23768 (defun org-before-first-heading-p ()
23769 "Before first heading?"
23770 (save-excursion
23771 (end-of-line)
23772 (null (re-search-backward org-outline-regexp-bol nil t))))
23774 (defun org-at-heading-p (&optional ignored)
23775 (outline-on-heading-p t))
23777 (defun org-in-commented-heading-p (&optional no-inheritance)
23778 "Non-nil if point is under a commented heading.
23779 This function also checks ancestors of the current headline,
23780 unless optional argument NO-INHERITANCE is non-nil."
23781 (cond
23782 ((org-before-first-heading-p) nil)
23783 ((let ((headline (nth 4 (org-heading-components))))
23784 (and headline
23785 (let ((case-fold-search nil))
23786 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
23787 headline)))))
23788 (no-inheritance nil)
23790 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
23792 (defun org-at-comment-p nil
23793 "Is cursor in a commented line?"
23794 (save-excursion
23795 (save-match-data
23796 (beginning-of-line)
23797 (looking-at "^[ \t]*# "))))
23799 (defun org-at-drawer-p nil
23800 "Is cursor at a drawer keyword?"
23801 (save-excursion
23802 (move-beginning-of-line 1)
23803 (looking-at org-drawer-regexp)))
23805 (defun org-at-block-p nil
23806 "Is cursor at a block keyword?"
23807 (save-excursion
23808 (move-beginning-of-line 1)
23809 (looking-at org-block-regexp)))
23811 (defun org-point-at-end-of-empty-headline ()
23812 "If point is at the end of an empty headline, return t, else nil.
23813 If the heading only contains a TODO keyword, it is still still considered
23814 empty."
23815 (let ((case-fold-search nil))
23816 (and (looking-at "[ \t]*$")
23817 org-todo-line-regexp
23818 (save-excursion
23819 (beginning-of-line)
23820 (looking-at org-todo-line-regexp)
23821 (string= (match-string 3) "")))))
23823 (defun org-at-heading-or-item-p ()
23824 (or (org-at-heading-p) (org-at-item-p)))
23826 (defun org-at-target-p ()
23827 (or (org-in-regexp org-radio-target-regexp)
23828 (org-in-regexp org-target-regexp)))
23829 ;; Compatibility alias with Org versions < 7.8.03
23830 (defalias 'org-on-target-p 'org-at-target-p)
23832 (defun org-up-heading-all (arg)
23833 "Move to the heading line of which the present line is a subheading.
23834 This function considers both visible and invisible heading lines.
23835 With argument, move up ARG levels."
23836 (outline-up-heading arg t))
23838 (defun org-up-heading-safe ()
23839 "Move to the heading line of which the present line is a subheading.
23840 This version will not throw an error. It will return the level of the
23841 headline found, or nil if no higher level is found.
23843 Also, this function will be a lot faster than `outline-up-heading',
23844 because it relies on stars being the outline starters. This can really
23845 make a significant difference in outlines with very many siblings."
23846 (when (ignore-errors (org-back-to-heading t))
23847 (let ((level-up (1- (funcall outline-level))))
23848 (and (> level-up 0)
23849 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
23850 (funcall outline-level)))))
23852 (defun org-first-sibling-p ()
23853 "Is this heading the first child of its parents?"
23854 (interactive)
23855 (let ((re org-outline-regexp-bol)
23856 level l)
23857 (unless (org-at-heading-p t)
23858 (user-error "Not at a heading"))
23859 (setq level (funcall outline-level))
23860 (save-excursion
23861 (if (not (re-search-backward re nil t))
23863 (setq l (funcall outline-level))
23864 (< l level)))))
23866 (defun org-goto-sibling (&optional previous)
23867 "Goto the next sibling, even if it is invisible.
23868 When PREVIOUS is set, go to the previous sibling instead. Returns t
23869 when a sibling was found. When none is found, return nil and don't
23870 move point."
23871 (let ((fun (if previous 're-search-backward 're-search-forward))
23872 (pos (point))
23873 (re org-outline-regexp-bol)
23874 level l)
23875 (when (ignore-errors (org-back-to-heading t))
23876 (setq level (funcall outline-level))
23877 (catch 'exit
23878 (or previous (forward-char 1))
23879 (while (funcall fun re nil t)
23880 (setq l (funcall outline-level))
23881 (when (< l level) (goto-char pos) (throw 'exit nil))
23882 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
23883 (goto-char pos)
23884 nil))))
23886 (defun org-show-siblings ()
23887 "Show all siblings of the current headline."
23888 (save-excursion
23889 (while (org-goto-sibling) (org-flag-heading nil)))
23890 (save-excursion
23891 (while (org-goto-sibling 'previous)
23892 (org-flag-heading nil))))
23894 (defun org-goto-first-child ()
23895 "Goto the first child, even if it is invisible.
23896 Return t when a child was found. Otherwise don't move point and
23897 return nil."
23898 (let (level (pos (point)) (re org-outline-regexp-bol))
23899 (when (ignore-errors (org-back-to-heading t))
23900 (setq level (outline-level))
23901 (forward-char 1)
23902 (if (and (re-search-forward re nil t) (> (outline-level) level))
23903 (progn (goto-char (match-beginning 0)) t)
23904 (goto-char pos) nil))))
23906 (defun org-show-hidden-entry ()
23907 "Show an entry where even the heading is hidden."
23908 (save-excursion
23909 (org-show-entry)))
23911 (defun org-flag-heading (flag &optional entry)
23912 "Flag the current heading. FLAG non-nil means make invisible.
23913 When ENTRY is non-nil, show the entire entry."
23914 (save-excursion
23915 (org-back-to-heading t)
23916 ;; Check if we should show the entire entry
23917 (if entry
23918 (progn
23919 (org-show-entry)
23920 (save-excursion
23921 (and (outline-next-heading)
23922 (org-flag-heading nil))))
23923 (outline-flag-region (max (point-min) (1- (point)))
23924 (save-excursion (outline-end-of-heading) (point))
23925 flag))))
23927 (defun org-get-next-sibling ()
23928 "Move to next heading of the same level, and return point.
23929 If there is no such heading, return nil.
23930 This is like outline-next-sibling, but invisible headings are ok."
23931 (let ((level (funcall outline-level)))
23932 (outline-next-heading)
23933 (while (and (not (eobp)) (> (funcall outline-level) level))
23934 (outline-next-heading))
23935 (unless (or (eobp) (< (funcall outline-level) level))
23936 (point))))
23938 (defun org-get-last-sibling ()
23939 "Move to previous heading of the same level, and return point.
23940 If there is no such heading, return nil."
23941 (let ((opoint (point))
23942 (level (funcall outline-level)))
23943 (outline-previous-heading)
23944 (when (and (/= (point) opoint) (outline-on-heading-p t))
23945 (while (and (> (funcall outline-level) level)
23946 (not (bobp)))
23947 (outline-previous-heading))
23948 (unless (< (funcall outline-level) level)
23949 (point)))))
23951 (defun org-end-of-subtree (&optional invisible-ok to-heading)
23952 "Goto to the end of a subtree."
23953 ;; This contains an exact copy of the original function, but it uses
23954 ;; `org-back-to-heading', to make it work also in invisible
23955 ;; trees. And is uses an invisible-ok argument.
23956 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
23957 ;; Furthermore, when used inside Org, finding the end of a large subtree
23958 ;; with many children and grandchildren etc, this can be much faster
23959 ;; than the outline version.
23960 (org-back-to-heading invisible-ok)
23961 (let ((first t)
23962 (level (funcall outline-level)))
23963 (if (and (derived-mode-p 'org-mode) (< level 1000))
23964 ;; A true heading (not a plain list item), in Org
23965 ;; This means we can easily find the end by looking
23966 ;; only for the right number of stars. Using a regexp to do
23967 ;; this is so much faster than using a Lisp loop.
23968 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
23969 (forward-char 1)
23970 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
23971 ;; something else, do it the slow way
23972 (while (and (not (eobp))
23973 (or first (> (funcall outline-level) level)))
23974 (setq first nil)
23975 (outline-next-heading)))
23976 (unless to-heading
23977 (when (memq (preceding-char) '(?\n ?\^M))
23978 ;; Go to end of line before heading
23979 (forward-char -1)
23980 (when (memq (preceding-char) '(?\n ?\^M))
23981 ;; leave blank line before heading
23982 (forward-char -1)))))
23983 (point))
23985 (defun org-end-of-meta-data (&optional full)
23986 "Skip planning line and properties drawer in current entry.
23987 When optional argument FULL is non-nil, also skip empty lines,
23988 clocking lines and regular drawers at the beginning of the
23989 entry."
23990 (org-back-to-heading t)
23991 (forward-line)
23992 (when (looking-at-p org-planning-line-re) (forward-line))
23993 (when (looking-at org-property-drawer-re)
23994 (goto-char (match-end 0))
23995 (forward-line))
23996 (when (and full (not (org-at-heading-p)))
23997 (catch 'exit
23998 (let ((end (save-excursion (outline-next-heading) (point)))
23999 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24000 (while (not (eobp))
24001 (cond ((looking-at-p org-drawer-regexp)
24002 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24003 (forward-line)
24004 (throw 'exit t)))
24005 ((looking-at-p re) (forward-line))
24006 (t (throw 'exit t))))))))
24008 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24009 "Move forward to the ARG'th subheading at same level as this one.
24010 Stop at the first and last subheadings of a superior heading.
24011 Normally this only looks at visible headings, but when INVISIBLE-OK is
24012 non-nil it will also look at invisible ones."
24013 (interactive "p")
24014 (let ((backward? (and arg (< arg 0))))
24015 (if (org-before-first-heading-p)
24016 (if backward? (goto-char (point-min)) (outline-next-heading))
24017 (org-back-to-heading invisible-ok)
24018 (unless backward? (end-of-line)) ;do not match current headline
24019 (let ((level (- (match-end 0) (match-beginning 0) 1))
24020 (f (if backward? #'re-search-backward #'re-search-forward))
24021 (count (if arg (abs arg) 1))
24022 (result (point)))
24023 (while (and (> count 0)
24024 (funcall f org-outline-regexp-bol nil 'move))
24025 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24026 (cond ((< l level) (setq count 0))
24027 ((and (= l level)
24028 (or invisible-ok
24029 (not (org-invisible-p
24030 (line-beginning-position)))))
24031 (cl-decf count)
24032 (when (= l level) (setq result (point)))))))
24033 (goto-char result))
24034 (beginning-of-line))))
24036 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24037 "Move backward to the ARG'th subheading at same level as this one.
24038 Stop at the first and last subheadings of a superior heading."
24039 (interactive "p")
24040 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24042 (defun org-next-visible-heading (arg)
24043 "Move to the next visible heading.
24045 This function wraps `outline-next-visible-heading' with
24046 `org-with-limited-levels' in order to skip over inline tasks and
24047 respect customization of `org-odd-levels-only'."
24048 (interactive "p")
24049 (org-with-limited-levels
24050 (outline-next-visible-heading arg)))
24052 (defun org-previous-visible-heading (arg)
24053 "Move to the previous visible heading.
24055 This function wraps `outline-previous-visible-heading' with
24056 `org-with-limited-levels' in order to skip over inline tasks and
24057 respect customization of `org-odd-levels-only'."
24058 (interactive "p")
24059 (org-with-limited-levels
24060 (outline-previous-visible-heading arg)))
24062 (defun org-next-block (arg &optional backward block-regexp)
24063 "Jump to the next block.
24065 With a prefix argument ARG, jump forward ARG many blocks.
24067 When BACKWARD is non-nil, jump to the previous block.
24069 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24070 Match data is set according to this regexp when the function
24071 returns.
24073 Return point at beginning of the opening line of found block.
24074 Throw an error if no block is found."
24075 (interactive "p")
24076 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24077 (case-fold-search t)
24078 (search-fn (if backward #'re-search-backward #'re-search-forward))
24079 (count (or arg 1))
24080 (origin (point))
24081 last-element)
24082 (if backward (beginning-of-line) (end-of-line))
24083 (while (and (> count 0) (funcall search-fn re nil t))
24084 (let ((element (save-excursion
24085 (goto-char (match-beginning 0))
24086 (save-match-data (org-element-at-point)))))
24087 (when (and (memq (org-element-type element)
24088 '(center-block comment-block dynamic-block
24089 example-block export-block quote-block
24090 special-block src-block verse-block))
24091 (<= (match-beginning 0)
24092 (org-element-property :post-affiliated element)))
24093 (setq last-element element)
24094 (cl-decf count))))
24095 (if (= count 0)
24096 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24097 (save-match-data (org-show-context)))
24098 (goto-char origin)
24099 (user-error "No %s code blocks" (if backward "previous" "further")))))
24101 (defun org-previous-block (arg &optional block-regexp)
24102 "Jump to the previous block.
24103 With a prefix argument ARG, jump backward ARG many source blocks.
24104 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24105 (interactive "p")
24106 (org-next-block arg t block-regexp))
24108 (defun org-forward-paragraph ()
24109 "Move forward to beginning of next paragraph or equivalent.
24111 The function moves point to the beginning of the next visible
24112 structural element, which can be a paragraph, a table, a list
24113 item, etc. It also provides some special moves for convenience:
24115 - On an affiliated keyword, jump to the beginning of the
24116 relative element.
24117 - On an item or a footnote definition, move to the second
24118 element inside, if any.
24119 - On a table or a property drawer, jump after it.
24120 - On a verse or source block, stop after blank lines."
24121 (interactive)
24122 (unless (eobp)
24123 (let* ((deactivate-mark nil)
24124 (element (org-element-at-point))
24125 (type (org-element-type element))
24126 (post-affiliated (org-element-property :post-affiliated element))
24127 (contents-begin (org-element-property :contents-begin element))
24128 (contents-end (org-element-property :contents-end element))
24129 (end (let ((end (org-element-property :end element)) (parent element))
24130 (while (and (setq parent (org-element-property :parent parent))
24131 (= (org-element-property :contents-end parent) end))
24132 (setq end (org-element-property :end parent)))
24133 end)))
24134 (cond ((not element)
24135 (skip-chars-forward " \r\t\n")
24136 (or (eobp) (beginning-of-line)))
24137 ;; On affiliated keywords, move to element's beginning.
24138 ((< (point) post-affiliated)
24139 (goto-char post-affiliated))
24140 ;; At a table row, move to the end of the table. Similarly,
24141 ;; at a node property, move to the end of the property
24142 ;; drawer.
24143 ((memq type '(node-property table-row))
24144 (goto-char (org-element-property
24145 :end (org-element-property :parent element))))
24146 ((memq type '(property-drawer table)) (goto-char end))
24147 ;; Consider blank lines as separators in verse and source
24148 ;; blocks to ease editing.
24149 ((memq type '(src-block verse-block))
24150 (when (eq type 'src-block)
24151 (setq contents-end
24152 (save-excursion (goto-char end)
24153 (skip-chars-backward " \r\t\n")
24154 (line-beginning-position))))
24155 (beginning-of-line)
24156 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24157 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24158 (goto-char end)
24159 (skip-chars-forward " \r\t\n")
24160 (if (= (point) contents-end) (goto-char end)
24161 (beginning-of-line))))
24162 ;; With no contents, just skip element.
24163 ((not contents-begin) (goto-char end))
24164 ;; If contents are invisible, skip the element altogether.
24165 ((org-invisible-p (line-end-position))
24166 (cl-case type
24167 (headline
24168 (org-with-limited-levels (outline-next-visible-heading 1)))
24169 ;; At a plain list, make sure we move to the next item
24170 ;; instead of skipping the whole list.
24171 (plain-list (forward-char)
24172 (org-forward-paragraph))
24173 (otherwise (goto-char end))))
24174 ((>= (point) contents-end) (goto-char end))
24175 ((>= (point) contents-begin)
24176 ;; This can only happen on paragraphs and plain lists.
24177 (cl-case type
24178 (paragraph (goto-char end))
24179 ;; At a plain list, try to move to second element in
24180 ;; first item, if possible.
24181 (plain-list (end-of-line)
24182 (org-forward-paragraph))))
24183 ;; When contents start on the middle of a line (e.g. in
24184 ;; items and footnote definitions), try to reach first
24185 ;; element starting after current line.
24186 ((> (line-end-position) contents-begin)
24187 (end-of-line)
24188 (org-forward-paragraph))
24189 (t (goto-char contents-begin))))))
24191 (defun org-backward-paragraph ()
24192 "Move backward to start of previous paragraph or equivalent.
24194 The function moves point to the beginning of the current
24195 structural element, which can be a paragraph, a table, a list
24196 item, etc., or to the beginning of the previous visible one if
24197 point is already there. It also provides some special moves for
24198 convenience:
24200 - On an affiliated keyword, jump to the first one.
24201 - On a table or a property drawer, move to its beginning.
24202 - On a verse or source block, stop before blank lines."
24203 (interactive)
24204 (unless (bobp)
24205 (let* ((deactivate-mark nil)
24206 (element (org-element-at-point))
24207 (type (org-element-type element))
24208 (contents-begin (org-element-property :contents-begin element))
24209 (contents-end (org-element-property :contents-end element))
24210 (post-affiliated (org-element-property :post-affiliated element))
24211 (begin (org-element-property :begin element)))
24212 (cond
24213 ((not element) (goto-char (point-min)))
24214 ((= (point) begin)
24215 (backward-char)
24216 (org-backward-paragraph))
24217 ((<= (point) post-affiliated) (goto-char begin))
24218 ((memq type '(node-property table-row))
24219 (goto-char (org-element-property
24220 :post-affiliated (org-element-property :parent element))))
24221 ((memq type '(property-drawer table)) (goto-char begin))
24222 ((memq type '(src-block verse-block))
24223 (when (eq type 'src-block)
24224 (setq contents-begin
24225 (save-excursion (goto-char begin) (forward-line) (point))))
24226 (if (= (point) contents-begin) (goto-char post-affiliated)
24227 ;; Inside a verse block, see blank lines as paragraph
24228 ;; separators.
24229 (let ((origin (point)))
24230 (skip-chars-backward " \r\t\n" contents-begin)
24231 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24232 (skip-chars-forward " \r\t\n" origin)
24233 (if (= (point) origin) (goto-char contents-begin)
24234 (beginning-of-line))))))
24235 ((not contents-begin) (goto-char (or post-affiliated begin)))
24236 ((eq type 'paragraph)
24237 (goto-char contents-begin)
24238 ;; When at first paragraph in an item or a footnote definition,
24239 ;; move directly to beginning of line.
24240 (let ((parent-contents
24241 (org-element-property
24242 :contents-begin (org-element-property :parent element))))
24243 (when (and parent-contents (= parent-contents contents-begin))
24244 (beginning-of-line))))
24245 ;; At the end of a greater element, move to the beginning of the
24246 ;; last element within.
24247 ((>= (point) contents-end)
24248 (goto-char (1- contents-end))
24249 (org-backward-paragraph))
24250 (t (goto-char (or post-affiliated begin))))
24251 ;; Ensure we never leave point invisible.
24252 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
24254 (defun org-forward-element ()
24255 "Move forward by one element.
24256 Move to the next element at the same level, when possible."
24257 (interactive)
24258 (cond ((eobp) (user-error "Cannot move further down"))
24259 ((org-with-limited-levels (org-at-heading-p))
24260 (let ((origin (point)))
24261 (goto-char (org-end-of-subtree nil t))
24262 (unless (org-with-limited-levels (org-at-heading-p))
24263 (goto-char origin)
24264 (user-error "Cannot move further down"))))
24266 (let* ((elem (org-element-at-point))
24267 (end (org-element-property :end elem))
24268 (parent (org-element-property :parent elem)))
24269 (cond ((and parent (= (org-element-property :contents-end parent) end))
24270 (goto-char (org-element-property :end parent)))
24271 ((integer-or-marker-p end) (goto-char end))
24272 (t (message "No element at point")))))))
24274 (defun org-backward-element ()
24275 "Move backward by one element.
24276 Move to the previous element at the same level, when possible."
24277 (interactive)
24278 (cond ((bobp) (user-error "Cannot move further up"))
24279 ((org-with-limited-levels (org-at-heading-p))
24280 ;; At a headline, move to the previous one, if any, or stay
24281 ;; here.
24282 (let ((origin (point)))
24283 (org-with-limited-levels (org-backward-heading-same-level 1))
24284 ;; When current headline has no sibling above, move to its
24285 ;; parent.
24286 (when (= (point) origin)
24287 (or (org-with-limited-levels (org-up-heading-safe))
24288 (progn (goto-char origin)
24289 (user-error "Cannot move further up"))))))
24291 (let* ((elem (org-element-at-point))
24292 (beg (org-element-property :begin elem)))
24293 (cond
24294 ;; Move to beginning of current element if point isn't
24295 ;; there already.
24296 ((null beg) (message "No element at point"))
24297 ((/= (point) beg) (goto-char beg))
24298 (t (goto-char beg)
24299 (skip-chars-backward " \r\t\n")
24300 (unless (bobp)
24301 (let ((prev (org-element-at-point)))
24302 (goto-char (org-element-property :begin prev))
24303 (while (and (setq prev (org-element-property :parent prev))
24304 (<= (org-element-property :end prev) beg))
24305 (goto-char (org-element-property :begin prev)))))))))))
24307 (defun org-up-element ()
24308 "Move to upper element."
24309 (interactive)
24310 (if (org-with-limited-levels (org-at-heading-p))
24311 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24312 (let* ((elem (org-element-at-point))
24313 (parent (org-element-property :parent elem)))
24314 (if parent (goto-char (org-element-property :begin parent))
24315 (if (org-with-limited-levels (org-before-first-heading-p))
24316 (user-error "No surrounding element")
24317 (org-with-limited-levels (org-back-to-heading)))))))
24319 (defun org-down-element ()
24320 "Move to inner element."
24321 (interactive)
24322 (let ((element (org-element-at-point)))
24323 (cond
24324 ((memq (org-element-type element) '(plain-list table))
24325 (goto-char (org-element-property :contents-begin element))
24326 (forward-char))
24327 ((memq (org-element-type element) org-element-greater-elements)
24328 ;; If contents are hidden, first disclose them.
24329 (when (org-invisible-p (line-end-position)) (org-cycle))
24330 (goto-char (or (org-element-property :contents-begin element)
24331 (user-error "No content for this element"))))
24332 (t (user-error "No inner element")))))
24334 (defun org-drag-element-backward ()
24335 "Move backward element at point."
24336 (interactive)
24337 (let ((elem (or (org-element-at-point)
24338 (user-error "No element at point"))))
24339 (if (eq (org-element-type elem) 'headline)
24340 ;; Preserve point when moving a whole tree, even if point was
24341 ;; on blank lines below the headline.
24342 (let ((offset (skip-chars-backward " \t\n")))
24343 (unwind-protect (org-move-subtree-up)
24344 (forward-char (- offset))))
24345 (let ((prev-elem
24346 (save-excursion
24347 (goto-char (org-element-property :begin elem))
24348 (skip-chars-backward " \r\t\n")
24349 (unless (bobp)
24350 (let* ((beg (org-element-property :begin elem))
24351 (prev (org-element-at-point))
24352 (up prev))
24353 (while (and (setq up (org-element-property :parent up))
24354 (<= (org-element-property :end up) beg))
24355 (setq prev up))
24356 prev)))))
24357 ;; Error out if no previous element or previous element is
24358 ;; a parent of the current one.
24359 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24360 (user-error "Cannot drag element backward")
24361 (let ((pos (point)))
24362 (org-element-swap-A-B prev-elem elem)
24363 (goto-char (+ (org-element-property :begin prev-elem)
24364 (- pos (org-element-property :begin elem))))))))))
24366 (defun org-drag-element-forward ()
24367 "Move forward element at point."
24368 (interactive)
24369 (let* ((pos (point))
24370 (elem (or (org-element-at-point)
24371 (user-error "No element at point"))))
24372 (when (= (point-max) (org-element-property :end elem))
24373 (user-error "Cannot drag element forward"))
24374 (goto-char (org-element-property :end elem))
24375 (let ((next-elem (org-element-at-point)))
24376 (when (or (org-element-nested-p elem next-elem)
24377 (and (eq (org-element-type next-elem) 'headline)
24378 (not (eq (org-element-type elem) 'headline))))
24379 (goto-char pos)
24380 (user-error "Cannot drag element forward"))
24381 ;; Compute new position of point: it's shifted by NEXT-ELEM
24382 ;; body's length (without final blanks) and by the length of
24383 ;; blanks between ELEM and NEXT-ELEM.
24384 (let ((size-next (- (save-excursion
24385 (goto-char (org-element-property :end next-elem))
24386 (skip-chars-backward " \r\t\n")
24387 (forward-line)
24388 ;; Small correction if buffer doesn't end
24389 ;; with a newline character.
24390 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24391 (org-element-property :begin next-elem)))
24392 (size-blank (- (org-element-property :end elem)
24393 (save-excursion
24394 (goto-char (org-element-property :end elem))
24395 (skip-chars-backward " \r\t\n")
24396 (forward-line)
24397 (point)))))
24398 (org-element-swap-A-B elem next-elem)
24399 (goto-char (+ pos size-next size-blank))))))
24401 (defun org-drag-line-forward (arg)
24402 "Drag the line at point ARG lines forward."
24403 (interactive "p")
24404 (dotimes (_ (abs arg))
24405 (let ((c (current-column)))
24406 (if (< 0 arg)
24407 (progn
24408 (beginning-of-line 2)
24409 (transpose-lines 1)
24410 (beginning-of-line 0))
24411 (transpose-lines 1)
24412 (beginning-of-line -1))
24413 (org-move-to-column c))))
24415 (defun org-drag-line-backward (arg)
24416 "Drag the line at point ARG lines backward."
24417 (interactive "p")
24418 (org-drag-line-forward (- arg)))
24420 (defun org-mark-element ()
24421 "Put point at beginning of this element, mark at end.
24423 Interactively, if this command is repeated or (in Transient Mark
24424 mode) if the mark is active, it marks the next element after the
24425 ones already marked."
24426 (interactive)
24427 (let (deactivate-mark)
24428 (if (and (called-interactively-p 'any)
24429 (or (and (eq last-command this-command) (mark t))
24430 (and transient-mark-mode mark-active)))
24431 (set-mark
24432 (save-excursion
24433 (goto-char (mark))
24434 (goto-char (org-element-property :end (org-element-at-point)))))
24435 (let ((element (org-element-at-point)))
24436 (end-of-line)
24437 (push-mark (org-element-property :end element) t t)
24438 (goto-char (org-element-property :begin element))))))
24440 (defun org-narrow-to-element ()
24441 "Narrow buffer to current element."
24442 (interactive)
24443 (let ((elem (org-element-at-point)))
24444 (cond
24445 ((eq (car elem) 'headline)
24446 (narrow-to-region
24447 (org-element-property :begin elem)
24448 (org-element-property :end elem)))
24449 ((memq (car elem) org-element-greater-elements)
24450 (narrow-to-region
24451 (org-element-property :contents-begin elem)
24452 (org-element-property :contents-end elem)))
24454 (narrow-to-region
24455 (org-element-property :begin elem)
24456 (org-element-property :end elem))))))
24458 (defun org-transpose-element ()
24459 "Transpose current and previous elements, keeping blank lines between.
24460 Point is moved after both elements."
24461 (interactive)
24462 (org-skip-whitespace)
24463 (let ((end (org-element-property :end (org-element-at-point))))
24464 (org-drag-element-backward)
24465 (goto-char end)))
24467 (defun org-unindent-buffer ()
24468 "Un-indent the visible part of the buffer.
24469 Relative indentation (between items, inside blocks, etc.) isn't
24470 modified."
24471 (interactive)
24472 (unless (eq major-mode 'org-mode)
24473 (user-error "Cannot un-indent a buffer not in Org mode"))
24474 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24475 (unindent-tree
24476 (lambda (contents)
24477 (dolist (element (reverse contents))
24478 (if (memq (org-element-type element) '(headline section))
24479 (funcall unindent-tree (org-element-contents element))
24480 (save-excursion
24481 (save-restriction
24482 (narrow-to-region
24483 (org-element-property :begin element)
24484 (org-element-property :end element))
24485 (org-do-remove-indentation))))))))
24486 (funcall unindent-tree (org-element-contents parse-tree))))
24488 (defun org-show-children (&optional level)
24489 "Show all direct subheadings of this heading.
24490 Prefix arg LEVEL is how many levels below the current level
24491 should be shown. Default is enough to cause the following
24492 heading to appear."
24493 (interactive "p")
24494 ;; If `orgstruct-mode' is active, use the slower version.
24495 (if orgstruct-mode (call-interactively #'outline-show-children)
24496 (save-excursion
24497 (org-back-to-heading t)
24498 (let* ((current-level (funcall outline-level))
24499 (max-level (org-get-valid-level
24500 current-level
24501 (if level (prefix-numeric-value level) 1)))
24502 (end (save-excursion (org-end-of-subtree t t)))
24503 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24504 (past-first-child nil)
24505 ;; Make sure to skip inlinetasks.
24506 (re (format regexp-fmt
24507 current-level
24508 (cond
24509 ((not (featurep 'org-inlinetask)) "")
24510 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24512 (t (1- org-inlinetask-min-level))))))
24513 ;; Display parent heading.
24514 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24515 (forward-line)
24516 ;; Display children. First child may be deeper than expected
24517 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24518 ;; MAX-LEVEL accordingly.
24519 (while (re-search-forward re end t)
24520 (unless past-first-child
24521 (setq re (format regexp-fmt
24522 current-level
24523 (max (funcall outline-level) max-level)))
24524 (setq past-first-child t))
24525 (outline-flag-region
24526 (line-end-position 0) (line-end-position) nil))))))
24528 (defun org-show-subtree ()
24529 "Show everything after this heading at deeper levels."
24530 (interactive)
24531 (outline-flag-region
24532 (point)
24533 (save-excursion
24534 (org-end-of-subtree t t))
24535 nil))
24537 (defun org-show-entry ()
24538 "Show the body directly following this heading.
24539 Show the heading too, if it is currently invisible."
24540 (interactive)
24541 (save-excursion
24542 (ignore-errors
24543 (org-back-to-heading t)
24544 (outline-flag-region
24545 (max (point-min) (1- (point)))
24546 (save-excursion
24547 (if (re-search-forward
24548 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24549 (match-beginning 1)
24550 (point-max)))
24551 nil)
24552 (org-cycle-hide-drawers 'children))))
24554 (defun org-make-options-regexp (kwds &optional extra)
24555 "Make a regular expression for keyword lines.
24556 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24557 when non-nil, is a regexp matching keywords names."
24558 (concat "^[ \t]*#\\+\\("
24559 (regexp-opt kwds)
24560 (and extra (concat (and kwds "\\|") extra))
24561 "\\):[ \t]*\\(.*\\)"))
24563 ;;;; Integration with and fixes for other packages
24565 ;;; Imenu support
24567 (defvar-local org-imenu-markers nil
24568 "All markers currently used by Imenu.")
24570 (defun org-imenu-new-marker (&optional pos)
24571 "Return a new marker for use by Imenu, and remember the marker."
24572 (let ((m (make-marker)))
24573 (move-marker m (or pos (point)))
24574 (push m org-imenu-markers)
24577 (defun org-imenu-get-tree ()
24578 "Produce the index for Imenu."
24579 (dolist (x org-imenu-markers) (move-marker x nil))
24580 (setq org-imenu-markers nil)
24581 (let* ((case-fold-search nil)
24582 (n org-imenu-depth)
24583 (re (concat "^" (org-get-limited-outline-regexp)))
24584 (subs (make-vector (1+ n) nil))
24585 (last-level 0)
24586 m level head0 head)
24587 (org-with-wide-buffer
24588 (goto-char (point-max))
24589 (while (re-search-backward re nil t)
24590 (setq level (org-reduced-level (funcall outline-level)))
24591 (when (and (<= level n)
24592 (looking-at org-complex-heading-regexp)
24593 (setq head0 (match-string-no-properties 4)))
24594 (setq head (org-link-display-format head0)
24595 m (org-imenu-new-marker))
24596 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24597 (if (>= level last-level)
24598 (push (cons head m) (aref subs level))
24599 (push (cons head (aref subs (1+ level))) (aref subs level))
24600 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24601 (setq last-level level))))
24602 (aref subs 1)))
24604 (eval-after-load "imenu"
24605 '(progn
24606 (add-hook 'imenu-after-jump-hook
24607 (lambda ()
24608 (when (derived-mode-p 'org-mode)
24609 (org-show-context 'org-goto))))))
24611 (defun org-link-display-format (s)
24612 "Replace links in string S with their description.
24613 If there is no description, use the link target."
24614 (save-match-data
24615 (replace-regexp-in-string
24616 org-bracket-link-analytic-regexp
24617 (lambda (m)
24618 (if (match-end 5) (match-string 5 m)
24619 (concat (match-string 1 m) (match-string 3 m))))
24620 s nil t)))
24622 (defun org-toggle-link-display ()
24623 "Toggle the literal or descriptive display of links."
24624 (interactive)
24625 (if org-descriptive-links
24626 (progn (org-remove-from-invisibility-spec '(org-link))
24627 (org-restart-font-lock)
24628 (setq org-descriptive-links nil))
24629 (progn (add-to-invisibility-spec '(org-link))
24630 (org-restart-font-lock)
24631 (setq org-descriptive-links t))))
24633 ;; Speedbar support
24635 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24636 "Overlay marking the agenda restriction line in speedbar.")
24637 (overlay-put org-speedbar-restriction-lock-overlay
24638 'face 'org-agenda-restriction-lock)
24639 (overlay-put org-speedbar-restriction-lock-overlay
24640 'help-echo "Agendas are currently limited to this item.")
24641 (delete-overlay org-speedbar-restriction-lock-overlay)
24643 (defun org-speedbar-set-agenda-restriction ()
24644 "Restrict future agenda commands to the location at point in speedbar.
24645 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24646 (interactive)
24647 (require 'org-agenda)
24648 (let (p m tp np dir txt)
24649 (cond
24650 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24651 'org-imenu t))
24652 (setq m (get-text-property p 'org-imenu-marker))
24653 (with-current-buffer (marker-buffer m)
24654 (goto-char m)
24655 (org-agenda-set-restriction-lock 'subtree)))
24656 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24657 'speedbar-function 'speedbar-find-file))
24658 (setq tp (previous-single-property-change
24659 (1+ p) 'speedbar-function)
24660 np (next-single-property-change
24661 tp 'speedbar-function)
24662 dir (speedbar-line-directory)
24663 txt (buffer-substring-no-properties (or tp (point-min))
24664 (or np (point-max))))
24665 (with-current-buffer (find-file-noselect
24666 (let ((default-directory dir))
24667 (expand-file-name txt)))
24668 (unless (derived-mode-p 'org-mode)
24669 (user-error "Cannot restrict to non-Org mode file"))
24670 (org-agenda-set-restriction-lock 'file)))
24671 (t (user-error "Don't know how to restrict Org mode agenda")))
24672 (move-overlay org-speedbar-restriction-lock-overlay
24673 (point-at-bol) (point-at-eol))
24674 (setq current-prefix-arg nil)
24675 (org-agenda-maybe-redo)))
24677 (defvar speedbar-file-key-map)
24678 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24679 (eval-after-load "speedbar"
24680 '(progn
24681 (speedbar-add-supported-extension ".org")
24682 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24683 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24684 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24685 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24686 (add-hook 'speedbar-visiting-tag-hook
24687 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24689 ;;; Fixes and Hacks for problems with other packages
24691 (defun org--flyspell-object-check-p (element)
24692 "Non-nil when Flyspell can check object at point.
24693 ELEMENT is the element at point."
24694 (let ((object (save-excursion
24695 (when (looking-at-p "\\>") (backward-char))
24696 (org-element-context element))))
24697 (cl-case (org-element-type object)
24698 ;; Prevent checks in links due to keybinding conflict with
24699 ;; Flyspell.
24700 ((code entity export-snippet inline-babel-call
24701 inline-src-block line-break latex-fragment link macro
24702 statistics-cookie target timestamp verbatim)
24703 nil)
24704 (footnote-reference
24705 ;; Only in inline footnotes, within the definition.
24706 (and (eq (org-element-property :type object) 'inline)
24707 (< (save-excursion
24708 (goto-char (org-element-property :begin object))
24709 (search-forward ":" nil t 2))
24710 (point))))
24711 (otherwise t))))
24713 (defun org-mode-flyspell-verify ()
24714 "Function used for `flyspell-generic-check-word-predicate'."
24715 (if (org-at-heading-p)
24716 ;; At a headline or an inlinetask, check title only. This is
24717 ;; faster than relying on `org-element-at-point'.
24718 (and (save-excursion (beginning-of-line)
24719 (and (let ((case-fold-search t))
24720 (not (looking-at-p "\\*+ END[ \t]*$")))
24721 (let ((case-fold-search nil))
24722 (looking-at org-complex-heading-regexp))))
24723 (match-beginning 4)
24724 (>= (point) (match-beginning 4))
24725 (or (not (match-beginning 5))
24726 (< (point) (match-beginning 5))))
24727 (let* ((element (org-element-at-point))
24728 (post-affiliated (org-element-property :post-affiliated element)))
24729 (cond
24730 ;; Ignore checks in all affiliated keywords but captions.
24731 ((< (point) post-affiliated)
24732 (and (save-excursion
24733 (beginning-of-line)
24734 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
24735 (> (point) (match-end 0))
24736 (org--flyspell-object-check-p element)))
24737 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
24738 ((let ((log (org-log-into-drawer)))
24739 (and log
24740 (let ((drawer (org-element-lineage element '(drawer))))
24741 (and drawer
24742 (eq (compare-strings
24743 log nil nil
24744 (org-element-property :drawer-name drawer) nil nil t)
24745 t)))))
24746 nil)
24748 (cl-case (org-element-type element)
24749 ((comment quote-section) t)
24750 (comment-block
24751 ;; Allow checks between block markers, not on them.
24752 (and (> (line-beginning-position) post-affiliated)
24753 (save-excursion
24754 (end-of-line)
24755 (skip-chars-forward " \r\t\n")
24756 (< (point) (org-element-property :end element)))))
24757 ;; Arbitrary list of keywords where checks are meaningful.
24758 ;; Make sure point is on the value part of the element.
24759 (keyword
24760 (and (member (org-element-property :key element)
24761 '("DESCRIPTION" "TITLE"))
24762 (save-excursion
24763 (search-backward ":" (line-beginning-position) t))))
24764 ;; Check is globally allowed in paragraphs verse blocks and
24765 ;; table rows (after affiliated keywords) but some objects
24766 ;; must not be affected.
24767 ((paragraph table-row verse-block)
24768 (let ((cbeg (org-element-property :contents-begin element))
24769 (cend (org-element-property :contents-end element)))
24770 (and cbeg (>= (point) cbeg) (< (point) cend)
24771 (org--flyspell-object-check-p element))))))))))
24772 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
24774 (defun org-remove-flyspell-overlays-in (beg end)
24775 "Remove flyspell overlays in region."
24776 (and (bound-and-true-p flyspell-mode)
24777 (fboundp 'flyspell-delete-region-overlays)
24778 (flyspell-delete-region-overlays beg end)))
24780 (defvar flyspell-delayed-commands)
24781 (eval-after-load "flyspell"
24782 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
24784 ;; Make `bookmark-jump' shows the jump location if it was hidden.
24785 (eval-after-load "bookmark"
24786 '(if (boundp 'bookmark-after-jump-hook)
24787 ;; We can use the hook
24788 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
24789 ;; Hook not available, use advice
24790 (defadvice bookmark-jump (after org-make-visible activate)
24791 "Make the position visible."
24792 (org-bookmark-jump-unhide))))
24794 ;; Make sure saveplace shows the location if it was hidden
24795 (eval-after-load "saveplace"
24796 '(defadvice save-place-find-file-hook (after org-make-visible activate)
24797 "Make the position visible."
24798 (org-bookmark-jump-unhide)))
24800 ;; Make sure ecb shows the location if it was hidden
24801 (eval-after-load "ecb"
24802 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
24803 "Make hierarchy visible when jumping into location from ECB tree buffer."
24804 (when (derived-mode-p 'org-mode)
24805 (org-show-context))))
24807 (defun org-bookmark-jump-unhide ()
24808 "Unhide the current position, to show the bookmark location."
24809 (and (derived-mode-p 'org-mode)
24810 (or (org-invisible-p)
24811 (save-excursion (goto-char (max (point-min) (1- (point))))
24812 (org-invisible-p)))
24813 (org-show-context 'bookmark-jump)))
24815 (defun org-mark-jump-unhide ()
24816 "Make the point visible with `org-show-context' after jumping to the mark."
24817 (when (and (derived-mode-p 'org-mode)
24818 (org-invisible-p))
24819 (org-show-context 'mark-goto)))
24821 (eval-after-load "simple"
24822 '(defadvice pop-to-mark-command (after org-make-visible activate)
24823 "Make the point visible with `org-show-context'."
24824 (org-mark-jump-unhide)))
24826 (eval-after-load "simple"
24827 '(defadvice exchange-point-and-mark (after org-make-visible activate)
24828 "Make the point visible with `org-show-context'."
24829 (org-mark-jump-unhide)))
24831 (eval-after-load "simple"
24832 '(defadvice pop-global-mark (after org-make-visible activate)
24833 "Make the point visible with `org-show-context'."
24834 (org-mark-jump-unhide)))
24836 ;; Make session.el ignore our circular variable
24837 (defvar session-globals-exclude)
24838 (eval-after-load "session"
24839 '(add-to-list 'session-globals-exclude 'org-mark-ring))
24841 ;;;; Finish up
24843 (provide 'org)
24845 (run-hooks 'org-load-hook)
24847 ;;; org.el ends here