Relax the match criteria for MathML header line
[org-mode.git] / lisp / org.el
blob5763829b32ae4f4ad808bcdeb16dbe88f95e6d02
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-2016 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the doc/ directory.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar-local org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (eq this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 (declare-function calendar-check-holidays "holidays" (date))
114 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
115 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
116 (declare-function org-add-archive-files "org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
118 (declare-function org-agenda-list "org-agenda"
119 (&optional arg start-day span with-hour))
120 (declare-function org-agenda-redo "org-agenda" (&optional all))
121 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
122 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
123 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
124 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
125 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
126 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
127 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
128 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
129 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
130 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
131 (declare-function org-clock-update-time-maybe "org-clock" ())
132 (declare-function org-clocktable-shift "org-clock" (dir n))
133 (declare-function org-element-at-point "org-element" ())
134 (declare-function org-element-cache-refresh "org-element" (pos))
135 (declare-function org-element-cache-reset "org-element" (&optional all))
136 (declare-function org-element-contents "org-element" (element))
137 (declare-function org-element-context "org-element" (&optional element))
138 (declare-function org-element-copy "org-element" (datum))
139 (declare-function org-element-interpret-data "org-element" (data))
140 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
141 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
142 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
143 (declare-function org-element-property "org-element" (property element))
144 (declare-function org-element-put-property "org-element" (element property value))
145 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
146 (declare-function org-element-type "org-element" (element))
147 (declare-function org-element-update-syntax "org-element" ())
148 (declare-function org-id-find-id-file "org-id" (id))
149 (declare-function org-id-get-create "org-id" (&optional force))
150 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
151 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
152 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
153 (declare-function org-plot/gnuplot "org-plot" (&optional params))
154 (declare-function org-table-align "org-table" ())
155 (declare-function org-table-begin "org-table" (&optional table-type))
156 (declare-function org-table-beginning-of-field "org-table" (&optional n))
157 (declare-function org-table-blank-field "org-table" ())
158 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
159 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
160 (declare-function org-table-cut-region "org-table" (beg end))
161 (declare-function org-table-edit-field "org-table" (arg))
162 (declare-function org-table-end "org-table" (&optional table-type))
163 (declare-function org-table-end-of-field "org-table" (&optional n))
164 (declare-function org-table-insert-row "org-table" (&optional arg))
165 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
166 (declare-function org-table-maybe-eval-formula "org-table" ())
167 (declare-function org-table-maybe-recalculate-line "org-table" ())
168 (declare-function org-table-next-row "org-table" ())
169 (declare-function org-table-paste-rectangle "org-table" ())
170 (declare-function org-table-recalculate "org-table" (&optional all noalign))
171 (declare-function org-table-wrap-region "org-table" (arg))
172 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
173 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
174 (declare-function orgtbl-mode "org-table" (&optional arg))
176 (defsubst org-uniquify (list)
177 "Non-destructively remove duplicate elements from LIST."
178 (let ((res (copy-sequence list))) (delete-dups res)))
180 (defsubst org-get-at-bol (property)
181 "Get text property PROPERTY at the beginning of line."
182 (get-text-property (point-at-bol) property))
184 (defsubst org-trim (s &optional keep-lead)
185 "Remove whitespace at the beginning and the end of string S.
186 When optional argument KEEP-LEAD is non-nil, removing blank lines
187 at the beginning of the string does not affect leading indentation."
188 (replace-regexp-in-string
189 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
190 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
192 ;; load languages based on value of `org-babel-load-languages'
193 (defvar org-babel-load-languages)
195 ;;;###autoload
196 (defun org-babel-do-load-languages (sym value)
197 "Load the languages defined in `org-babel-load-languages'."
198 (set-default sym value)
199 (dolist (pair org-babel-load-languages)
200 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
201 (if active
202 (require (intern (concat "ob-" lang)))
203 (funcall 'fmakunbound
204 (intern (concat "org-babel-execute:" lang)))
205 (funcall 'fmakunbound
206 (intern (concat "org-babel-expand-body:" lang)))))))
208 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
209 ;;;###autoload
210 (defun org-babel-load-file (file &optional compile)
211 "Load Emacs Lisp source code blocks in the Org FILE.
212 This function exports the source code using `org-babel-tangle'
213 and then loads the resulting file using `load-file'. With prefix
214 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
215 file to byte-code before it is loaded."
216 (interactive "fFile to load: \nP")
217 (let* ((age (lambda (file)
218 (float-time
219 (time-subtract (current-time)
220 (nth 5 (or (file-attributes (file-truename file))
221 (file-attributes file)))))))
222 (base-name (file-name-sans-extension file))
223 (exported-file (concat base-name ".el")))
224 ;; tangle if the Org file is newer than the elisp file
225 (unless (and (file-exists-p exported-file)
226 (> (funcall age file) (funcall age exported-file)))
227 ;; Tangle-file traversal returns reversed list of tangled files
228 ;; and we want to evaluate the first target.
229 (setq exported-file
230 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
231 (message "%s %s"
232 (if compile
233 (progn (byte-compile-file exported-file 'load)
234 "Compiled and loaded")
235 (progn (load-file exported-file) "Loaded"))
236 exported-file)))
238 (defcustom org-babel-load-languages '((emacs-lisp . t))
239 "Languages which can be evaluated in Org buffers.
240 This list can be used to load support for any of the languages
241 below, note that each language will depend on a different set of
242 system executables and/or Emacs modes. When a language is
243 \"loaded\", then code blocks in that language can be evaluated
244 with `org-babel-execute-src-block' bound by default to C-c
245 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
246 be set to remove code block evaluation from the C-c C-c
247 keybinding. By default only Emacs Lisp (which has no
248 requirements) is loaded."
249 :group 'org-babel
250 :set 'org-babel-do-load-languages
251 :version "24.1"
252 :type '(alist :tag "Babel Languages"
253 :key-type
254 (choice
255 (const :tag "Awk" awk)
256 (const :tag "C" C)
257 (const :tag "R" R)
258 (const :tag "Asymptote" asymptote)
259 (const :tag "Calc" calc)
260 (const :tag "Clojure" clojure)
261 (const :tag "CSS" css)
262 (const :tag "Ditaa" ditaa)
263 (const :tag "Dot" dot)
264 (const :tag "Emacs Lisp" emacs-lisp)
265 (const :tag "Forth" forth)
266 (const :tag "Fortran" fortran)
267 (const :tag "Gnuplot" gnuplot)
268 (const :tag "Haskell" haskell)
269 (const :tag "IO" io)
270 (const :tag "J" J)
271 (const :tag "Java" java)
272 (const :tag "Javascript" js)
273 (const :tag "LaTeX" latex)
274 (const :tag "Ledger" ledger)
275 (const :tag "Lilypond" lilypond)
276 (const :tag "Lisp" lisp)
277 (const :tag "Makefile" makefile)
278 (const :tag "Maxima" maxima)
279 (const :tag "Matlab" matlab)
280 (const :tag "Mscgen" mscgen)
281 (const :tag "Ocaml" ocaml)
282 (const :tag "Octave" octave)
283 (const :tag "Org" org)
284 (const :tag "Perl" perl)
285 (const :tag "Pico Lisp" picolisp)
286 (const :tag "PlantUML" plantuml)
287 (const :tag "Python" python)
288 (const :tag "Ruby" ruby)
289 (const :tag "Sass" sass)
290 (const :tag "Scala" scala)
291 (const :tag "Scheme" scheme)
292 (const :tag "Screen" screen)
293 (const :tag "Shell Script" shell)
294 (const :tag "Shen" shen)
295 (const :tag "Sql" sql)
296 (const :tag "Sqlite" sqlite)
297 (const :tag "Stan" stan)
298 (const :tag "ebnf2ps" ebnf2ps))
299 :value-type (boolean :tag "Activate" :value t)))
301 ;;;; Customization variables
302 (defcustom org-clone-delete-id nil
303 "Remove ID property of clones of a subtree.
304 When non-nil, clones of a subtree don't inherit the ID property.
305 Otherwise they inherit the ID property with a new unique
306 identifier."
307 :type 'boolean
308 :version "24.1"
309 :group 'org-id)
311 ;;; Version
312 (org-check-version)
314 ;;;###autoload
315 (defun org-version (&optional here full message)
316 "Show the Org version.
317 Interactively, or when MESSAGE is non-nil, show it in echo area.
318 With prefix argument, or when HERE is non-nil, insert it at point.
319 In non-interactive uses, a reduced version string is output unless
320 FULL is given."
321 (interactive (list current-prefix-arg t (not current-prefix-arg)))
322 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
323 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
324 (load-suffixes (list ".el"))
325 (org-install-dir
326 (ignore-errors (org-find-library-dir "org-loaddefs"))))
327 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
328 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
329 (let* ((load-suffixes save-load-suffixes)
330 (release (org-release))
331 (git-version (org-git-version))
332 (version (format "Org mode version %s (%s @ %s)"
333 release
334 git-version
335 (if org-install-dir
336 (if (string= org-dir org-install-dir)
337 org-install-dir
338 (concat "mixed installation! "
339 org-install-dir
340 " and "
341 org-dir))
342 "org-loaddefs.el can not be found!")))
343 (version1 (if full version release)))
344 (when here (insert version1))
345 (when message (message "%s" version1))
346 version1)))
348 (defconst org-version (org-version))
351 ;;; Syntax Constants
353 ;;;; Block
355 (defconst org-block-regexp
356 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
357 "Regular expression for hiding blocks.")
359 (defconst org-dblock-start-re
360 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
361 "Matches the start line of a dynamic block, with parameters.")
363 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
364 "Matches the end of a dynamic block.")
366 ;;;; Clock and Planning
368 (defconst org-clock-string "CLOCK:"
369 "String used as prefix for timestamps clocking work hours on an item.")
371 (defvar org-closed-string "CLOSED:"
372 "String used as the prefix for timestamps logging closing a TODO entry.")
374 (defvar org-deadline-string "DEADLINE:"
375 "String to mark deadline entries.
376 \\<org-mode-map>
377 A deadline is this string, followed by a time stamp. It must be
378 a word, terminated by a colon. You can insert a schedule keyword
379 and a timestamp with `\\[org-deadline]'.")
381 (defvar org-scheduled-string "SCHEDULED:"
382 "String to mark scheduled TODO entries.
383 \\<org-mode-map>
384 A schedule is this string, followed by a time stamp. It must be
385 a word, terminated by a colon. You can insert a schedule keyword
386 and a timestamp with `\\[org-schedule]'.")
388 (defconst org-ds-keyword-length
389 (+ 2
390 (apply #'max
391 (mapcar #'length
392 (list org-deadline-string org-scheduled-string
393 org-clock-string org-closed-string))))
394 "Maximum length of the DEADLINE and SCHEDULED keywords.")
396 (defconst org-planning-line-re
397 (concat "^[ \t]*"
398 (regexp-opt
399 (list org-closed-string org-deadline-string org-scheduled-string)
401 "Matches a line with planning info.
402 Matched keyword is in group 1.")
404 (defconst org-clock-line-re
405 (concat "^[ \t]*" org-clock-string)
406 "Matches a line with clock info.")
408 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
409 "Matches the DEADLINE keyword.")
411 (defconst org-deadline-time-regexp
412 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
413 "Matches the DEADLINE keyword together with a time stamp.")
415 (defconst org-deadline-time-hour-regexp
416 (concat "\\<" org-deadline-string
417 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
418 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
420 (defconst org-deadline-line-regexp
421 (concat "\\<\\(" org-deadline-string "\\).*")
422 "Matches the DEADLINE keyword and the rest of the line.")
424 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
425 "Matches the SCHEDULED keyword.")
427 (defconst org-scheduled-time-regexp
428 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
429 "Matches the SCHEDULED keyword together with a time stamp.")
431 (defconst org-scheduled-time-hour-regexp
432 (concat "\\<" org-scheduled-string
433 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
434 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
436 (defconst org-closed-time-regexp
437 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
438 "Matches the CLOSED keyword together with a time stamp.")
440 (defconst org-keyword-time-regexp
441 (concat "\\<"
442 (regexp-opt
443 (list org-scheduled-string org-deadline-string org-closed-string
444 org-clock-string)
446 " *[[<]\\([^]>]+\\)[]>]")
447 "Matches any of the 4 keywords, together with the time stamp.")
449 (defconst org-keyword-time-not-clock-regexp
450 (concat
451 "\\<"
452 (regexp-opt
453 (list org-scheduled-string org-deadline-string org-closed-string) t)
454 " *[[<]\\([^]>]+\\)[]>]")
455 "Matches any of the 3 keywords, together with the time stamp.")
457 (defconst org-maybe-keyword-time-regexp
458 (concat "\\(\\<"
459 (regexp-opt
460 (list org-scheduled-string org-deadline-string org-closed-string
461 org-clock-string)
463 "\\)?"
464 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
465 "\\|"
466 "<%%([^\r\n>]*>\\)")
467 "Matches a timestamp, possibly preceded by a keyword.")
469 (defconst org-all-time-keywords
470 (mapcar (lambda (w) (substring w 0 -1))
471 (list org-scheduled-string org-deadline-string
472 org-clock-string org-closed-string))
473 "List of time keywords.")
475 ;;;; Drawer
477 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
478 "Matches first or last line of a hidden block.
479 Group 1 contains drawer's name or \"END\".")
481 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
482 "Regular expression matching the first line of a property drawer.")
484 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
485 "Regular expression matching the last line of a property drawer.")
487 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
488 "Regular expression matching the first line of a clock drawer.")
490 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
491 "Regular expression matching the last line of a clock drawer.")
493 (defconst org-property-drawer-re
494 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
495 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
496 "[ \t]*:END:[ \t]*$")
497 "Matches an entire property drawer.")
499 (defconst org-clock-drawer-re
500 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
501 org-clock-drawer-end-re "\\)\n?")
502 "Matches an entire clock drawer.")
504 ;;;; Headline
506 (defconst org-heading-keyword-regexp-format
507 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
508 "Printf format for a regexp matching a headline with some keyword.
509 This regexp will match the headline of any node which has the
510 exact keyword that is put into the format. The keyword isn't in
511 any group by default, but the stars and the body are.")
513 (defconst org-heading-keyword-maybe-regexp-format
514 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
515 "Printf format for a regexp matching a headline, possibly with some keyword.
516 This regexp can match any headline with the specified keyword, or
517 without a keyword. The keyword isn't in any group by default,
518 but the stars and the body are.")
520 (defconst org-archive-tag "ARCHIVE"
521 "The tag that marks a subtree as archived.
522 An archived subtree does not open during visibility cycling, and does
523 not contribute to the agenda listings.")
525 (defconst org-comment-string "COMMENT"
526 "Entries starting with this keyword will never be exported.
527 \\<org-mode-map>
528 An entry can be toggled between COMMENT and normal with
529 `\\[org-toggle-comment]'.")
532 ;;;; LaTeX Environments and Fragments
534 (defconst org-latex-regexps
535 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
536 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
537 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
538 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
539 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
540 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
541 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
542 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
543 "Regular expressions for matching embedded LaTeX.")
545 ;;;; Node Property
547 (defconst org-effort-property "Effort"
548 "The property that is being used to keep track of effort estimates.
549 Effort estimates given in this property need to have the format H:MM.")
551 ;;;; Table
553 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
554 "Detect an org-type or table-type table.")
556 (defconst org-table-line-regexp "^[ \t]*|"
557 "Detect an org-type table line.")
559 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
560 "Detect an org-type table line.")
562 (defconst org-table-hline-regexp "^[ \t]*|-"
563 "Detect an org-type table hline.")
565 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
566 "Detect a table-type table hline.")
568 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
569 "Detect the first line outside a table when searching from within it.
570 This works for both table types.")
572 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
573 "Detect a #+TBLFM line.")
575 ;;;; Timestamp
577 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
578 "Regular expression for fast time stamp matching.")
580 (defconst org-ts-regexp-inactive
581 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
582 "Regular expression for fast inactive time stamp matching.")
584 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
585 "Regular expression for fast time stamp matching.")
587 (defconst org-ts-regexp0
588 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
589 "Regular expression matching time strings for analysis.
590 This one does not require the space after the date, so it can be used
591 on a string that terminates immediately after the date.")
593 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
594 "Regular expression matching time strings for analysis.")
596 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
597 "Regular expression matching time stamps, with groups.")
599 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
600 "Regular expression matching time stamps (also [..]), with groups.")
602 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
603 "Regular expression matching a time stamp range.")
605 (defconst org-tr-regexp-both
606 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
607 "Regular expression matching a time stamp range.")
609 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
610 org-ts-regexp "\\)?")
611 "Regular expression matching a time stamp or time stamp range.")
613 (defconst org-tsr-regexp-both
614 (concat org-ts-regexp-both "\\(--?-?"
615 org-ts-regexp-both "\\)?")
616 "Regular expression matching a time stamp or time stamp range.
617 The time stamps may be either active or inactive.")
619 (defconst org-repeat-re
620 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
621 "Regular expression for specifying repeated events.
622 After a match, group 1 contains the repeat expression.")
624 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
625 "Formats for `format-time-string' which are used for time stamps.")
628 ;;; The custom variables
630 (defgroup org nil
631 "Outline-based notes management and organizer."
632 :tag "Org"
633 :group 'outlines
634 :group 'calendar)
636 (defcustom org-mode-hook nil
637 "Mode hook for Org mode, run after the mode was turned on."
638 :group 'org
639 :type 'hook)
641 (defcustom org-load-hook nil
642 "Hook that is run after org.el has been loaded."
643 :group 'org
644 :type 'hook)
646 (defcustom org-log-buffer-setup-hook nil
647 "Hook that is run after an Org log buffer is created."
648 :group 'org
649 :version "24.1"
650 :type 'hook)
652 (defvar org-modules) ; defined below
653 (defvar org-modules-loaded nil
654 "Have the modules been loaded already?")
656 (defun org-load-modules-maybe (&optional force)
657 "Load all extensions listed in `org-modules'."
658 (when (or force (not org-modules-loaded))
659 (dolist (ext org-modules)
660 (condition-case nil (require ext)
661 (error (message "Problems while trying to load feature `%s'" ext))))
662 (setq org-modules-loaded t)))
664 (defun org-set-modules (var value)
665 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
666 (set var value)
667 (when (featurep 'org)
668 (org-load-modules-maybe 'force)
669 (org-element-cache-reset 'all)))
671 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
672 "Modules that should always be loaded together with org.el.
674 If a description starts with <C>, the file is not part of Emacs
675 and loading it will require that you have downloaded and properly
676 installed the Org mode distribution.
678 You can also use this system to load external packages (i.e. neither Org
679 core modules, nor modules from the CONTRIB directory). Just add symbols
680 to the end of the list. If the package is called org-xyz.el, then you need
681 to add the symbol `xyz', and the package must have a call to:
683 (provide \\='org-xyz)
685 For export specific modules, see also `org-export-backends'."
686 :group 'org
687 :set 'org-set-modules
688 :version "24.4"
689 :package-version '(Org . "8.0")
690 :type
691 '(set :greedy t
692 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
693 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
694 (const :tag " crypt: Encryption of subtrees" org-crypt)
695 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
696 (const :tag " docview: Links to doc-view buffers" org-docview)
697 (const :tag " eww: Store link to url of eww" org-eww)
698 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
699 (const :tag " habit: Track your consistency with habits" org-habit)
700 (const :tag " id: Global IDs for identifying entries" org-id)
701 (const :tag " info: Links to Info nodes" org-info)
702 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
703 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
704 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
705 (const :tag " mouse: Additional mouse support" org-mouse)
706 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
707 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
708 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
710 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
711 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
712 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
713 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
714 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
715 (const :tag "C collector: Collect properties into tables" org-collector)
716 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
717 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
718 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
719 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
720 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
721 (const :tag "C eval: Include command output as text" org-eval)
722 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
723 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
724 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
725 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
726 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
727 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
728 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
729 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
730 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
731 (const :tag "C man: Support for links to manpages in Org mode" org-man)
732 (const :tag "C mew: Links to Mew folders/messages" org-mew)
733 (const :tag "C mtags: Support for muse-like tags" org-mtags)
734 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
735 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
736 (const :tag "C registry: A registry for Org links" org-registry)
737 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
738 (const :tag "C secretary: Team management with org-mode" org-secretary)
739 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
740 (const :tag "C toc: Table of contents for Org buffer" org-toc)
741 (const :tag "C track: Keep up with Org mode development" org-track)
742 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
743 (const :tag "C vm: Links to VM folders/messages" org-vm)
744 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
745 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
746 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
748 (defvar org-export-registered-backends) ; From ox.el.
749 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
750 (declare-function org-export-backend-name "ox" (backend) t)
751 (defcustom org-export-backends '(ascii html icalendar latex odt)
752 "List of export back-ends that should be always available.
754 If a description starts with <C>, the file is not part of Emacs
755 and loading it will require that you have downloaded and properly
756 installed the Org mode distribution.
758 Unlike to `org-modules', libraries in this list will not be
759 loaded along with Org, but only once the export framework is
760 needed.
762 This variable needs to be set before org.el is loaded. If you
763 need to make a change while Emacs is running, use the customize
764 interface or run the following code, where VAL stands for the new
765 value of the variable, after updating it:
767 (progn
768 (setq org-export-registered-backends
769 (cl-remove-if-not
770 (lambda (backend)
771 (let ((name (org-export-backend-name backend)))
772 (or (memq name val)
773 (catch \\='parentp
774 (dolist (b val)
775 (and (org-export-derived-backend-p b name)
776 (throw \\='parentp t)))))))
777 org-export-registered-backends))
778 (let ((new-list (mapcar #\\='org-export-backend-name
779 org-export-registered-backends)))
780 (dolist (backend val)
781 (cond
782 ((not (load (format \"ox-%s\" backend) t t))
783 (message \"Problems while trying to load export back-end \\=`%s\\='\"
784 backend))
785 ((not (memq backend new-list)) (push backend new-list))))
786 (set-default \\='org-export-backends new-list)))
788 Adding a back-end to this list will also pull the back-end it
789 depends on, if any."
790 :group 'org
791 :group 'org-export
792 :version "25.2"
793 :package-version '(Org . "9.0")
794 :initialize 'custom-initialize-set
795 :set (lambda (var val)
796 (if (not (featurep 'ox)) (set-default var val)
797 ;; Any back-end not required anymore (not present in VAL and not
798 ;; a parent of any back-end in the new value) is removed from the
799 ;; list of registered back-ends.
800 (setq org-export-registered-backends
801 (cl-remove-if-not
802 (lambda (backend)
803 (let ((name (org-export-backend-name backend)))
804 (or (memq name val)
805 (catch 'parentp
806 (dolist (b val)
807 (and (org-export-derived-backend-p b name)
808 (throw 'parentp t)))))))
809 org-export-registered-backends))
810 ;; Now build NEW-LIST of both new back-ends and required
811 ;; parents.
812 (let ((new-list (mapcar #'org-export-backend-name
813 org-export-registered-backends)))
814 (dolist (backend val)
815 (cond
816 ((not (load (format "ox-%s" backend) t t))
817 (message "Problems while trying to load export back-end `%s'"
818 backend))
819 ((not (memq backend new-list)) (push backend new-list))))
820 ;; Set VAR to that list with fixed dependencies.
821 (set-default var new-list))))
822 :type '(set :greedy t
823 (const :tag " ascii Export buffer to ASCII format" ascii)
824 (const :tag " beamer Export buffer to Beamer presentation" beamer)
825 (const :tag " html Export buffer to HTML format" html)
826 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
827 (const :tag " latex Export buffer to LaTeX format" latex)
828 (const :tag " man Export buffer to MAN format" man)
829 (const :tag " md Export buffer to Markdown format" md)
830 (const :tag " odt Export buffer to ODT format" odt)
831 (const :tag " org Export buffer to Org format" org)
832 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
833 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
834 (const :tag "C deck Export buffer to deck.js presentations" deck)
835 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
836 (const :tag "C groff Export buffer to Groff format" groff)
837 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
838 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
839 (const :tag "C s5 Export buffer to s5 presentations" s5)
840 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
842 (eval-after-load 'ox
843 '(dolist (backend org-export-backends)
844 (condition-case nil (require (intern (format "ox-%s" backend)))
845 (error (message "Problems while trying to load export back-end `%s'"
846 backend)))))
848 (defcustom org-support-shift-select nil
849 "Non-nil means make shift-cursor commands select text when possible.
850 \\<org-mode-map>\
852 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
853 start selecting a region, or enlarge regions started in this way.
854 In Org mode, in special contexts, these same keys are used for
855 other purposes, important enough to compete with shift selection.
856 Org tries to balance these needs by supporting `shift-select-mode'
857 outside these special contexts, under control of this variable.
859 The default of this variable is nil, to avoid confusing behavior. Shifted
860 cursor keys will then execute Org commands in the following contexts:
861 - on a headline, changing TODO state (left/right) and priority (up/down)
862 - on a time stamp, changing the time
863 - in a plain list item, changing the bullet type
864 - in a property definition line, switching between allowed values
865 - in the BEGIN line of a clock table (changing the time block).
866 Outside these contexts, the commands will throw an error.
868 When this variable is t and the cursor is not in a special
869 context, Org mode will support shift-selection for making and
870 enlarging regions. To make this more effective, the bullet
871 cycling will no longer happen anywhere in an item line, but only
872 if the cursor is exactly on the bullet.
874 If you set this variable to the symbol `always', then the keys
875 will not be special in headlines, property lines, and item lines,
876 to make shift selection work there as well. If this is what you
877 want, you can use the following alternative commands:
878 `\\[org-todo]' and `\\[org-priority]' \
879 to change TODO state and priority,
880 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
881 can be used to switch TODO sets,
882 `\\[org-ctrl-c-minus]' to cycle item bullet types,
883 and properties can be edited by hand or in column view.
885 However, when the cursor is on a timestamp, shift-cursor commands
886 will still edit the time stamp - this is just too good to give up."
887 :group 'org
888 :type '(choice
889 (const :tag "Never" nil)
890 (const :tag "When outside special context" t)
891 (const :tag "Everywhere except timestamps" always)))
893 (defcustom org-loop-over-headlines-in-active-region nil
894 "Shall some commands act upon headlines in the active region?
896 When set to t, some commands will be performed in all headlines
897 within the active region.
899 When set to `start-level', some commands will be performed in all
900 headlines within the active region, provided that these headlines
901 are of the same level than the first one.
903 When set to a string, those commands will be performed on the
904 matching headlines within the active region. Such string must be
905 a tags/property/todo match as it is used in the agenda tags view.
907 The list of commands is: `org-schedule', `org-deadline',
908 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
909 `org-archive-to-archive-sibling'. The archiving commands skip
910 already archived entries."
911 :type '(choice (const :tag "Don't loop" nil)
912 (const :tag "All headlines in active region" t)
913 (const :tag "In active region, headlines at the same level than the first one" start-level)
914 (string :tag "Tags/Property/Todo matcher"))
915 :version "24.1"
916 :group 'org-todo
917 :group 'org-archive)
919 (defgroup org-startup nil
920 "Options concerning startup of Org mode."
921 :tag "Org Startup"
922 :group 'org)
924 (defcustom org-startup-folded t
925 "Non-nil means entering Org mode will switch to OVERVIEW.
927 This can also be configured on a per-file basis by adding one of
928 the following lines anywhere in the buffer:
930 #+STARTUP: fold (or `overview', this is equivalent)
931 #+STARTUP: nofold (or `showall', this is equivalent)
932 #+STARTUP: content
933 #+STARTUP: showeverything
935 Set `org-agenda-inhibit-startup' to a non-nil value if you want
936 to ignore this option when Org opens agenda files for the first
937 time."
938 :group 'org-startup
939 :type '(choice
940 (const :tag "nofold: show all" nil)
941 (const :tag "fold: overview" t)
942 (const :tag "content: all headlines" content)
943 (const :tag "show everything, even drawers" showeverything)))
945 (defcustom org-startup-truncated t
946 "Non-nil means entering Org mode will set `truncate-lines'.
947 This is useful since some lines containing links can be very long and
948 uninteresting. Also tables look terrible when wrapped.
950 The variable `org-startup-truncated' allows to configure
951 truncation for Org mode different to the other modes that use the
952 variable `truncate-lines' and as a shortcut instead of putting
953 the variable `truncate-lines' into the `org-mode-hook'. If one
954 wants to configure truncation for Org mode not statically but
955 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
956 the variable `truncate-lines' has to be used because in such a
957 case it is too late to set the variable `org-startup-truncated'."
958 :group 'org-startup
959 :type 'boolean)
961 (defcustom org-startup-indented nil
962 "Non-nil means turn on `org-indent-mode' on startup.
963 This can also be configured on a per-file basis by adding one of
964 the following lines anywhere in the buffer:
966 #+STARTUP: indent
967 #+STARTUP: noindent"
968 :group 'org-structure
969 :type '(choice
970 (const :tag "Not" nil)
971 (const :tag "Globally (slow on startup in large files)" t)))
973 (defcustom org-use-sub-superscripts t
974 "Non-nil means interpret \"_\" and \"^\" for display.
976 If you want to control how Org exports those characters, see
977 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
978 used to be an alias for `org-export-with-sub-superscripts' in
979 Org <8.0, it is not anymore.
981 When this option is turned on, you can use TeX-like syntax for
982 sub- and superscripts within the buffer. Several characters after
983 \"_\" or \"^\" will be considered as a single item - so grouping
984 with {} is normally not needed. For example, the following things
985 will be parsed as single sub- or superscripts:
987 10^24 or 10^tau several digits will be considered 1 item.
988 10^-12 or 10^-tau a leading sign with digits or a word
989 x^2-y^3 will be read as x^2 - y^3, because items are
990 terminated by almost any nonword/nondigit char.
991 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
993 Still, ambiguity is possible. So when in doubt, use {} to enclose
994 the sub/superscript. If you set this variable to the symbol `{}',
995 the braces are *required* in order to trigger interpretations as
996 sub/superscript. This can be helpful in documents that need \"_\"
997 frequently in plain text."
998 :group 'org-startup
999 :version "24.4"
1000 :package-version '(Org . "8.0")
1001 :type '(choice
1002 (const :tag "Always interpret" t)
1003 (const :tag "Only with braces" {})
1004 (const :tag "Never interpret" nil)))
1006 (defcustom org-startup-with-beamer-mode nil
1007 "Non-nil means turn on `org-beamer-mode' on startup.
1008 This can also be configured on a per-file basis by adding one of
1009 the following lines anywhere in the buffer:
1011 #+STARTUP: beamer"
1012 :group 'org-startup
1013 :version "24.1"
1014 :type 'boolean)
1016 (defcustom org-startup-align-all-tables nil
1017 "Non-nil means align all tables when visiting a file.
1018 This is useful when the column width in tables is forced with <N> cookies
1019 in table fields. Such tables will look correct only after the first re-align.
1020 This can also be configured on a per-file basis by adding one of
1021 the following lines anywhere in the buffer:
1022 #+STARTUP: align
1023 #+STARTUP: noalign"
1024 :group 'org-startup
1025 :type 'boolean)
1027 (defcustom org-startup-with-inline-images nil
1028 "Non-nil means show inline images when loading a new Org file.
1029 This can also be configured on a per-file basis by adding one of
1030 the following lines anywhere in the buffer:
1031 #+STARTUP: inlineimages
1032 #+STARTUP: noinlineimages"
1033 :group 'org-startup
1034 :version "24.1"
1035 :type 'boolean)
1037 (defcustom org-startup-with-latex-preview nil
1038 "Non-nil means preview LaTeX fragments when loading a new Org file.
1040 This can also be configured on a per-file basis by adding one of
1041 the following lines anywhere in the buffer:
1042 #+STARTUP: latexpreview
1043 #+STARTUP: nolatexpreview"
1044 :group 'org-startup
1045 :version "24.4"
1046 :package-version '(Org . "8.0")
1047 :type 'boolean)
1049 (defcustom org-insert-mode-line-in-empty-file nil
1050 "Non-nil means insert the first line setting Org mode in empty files.
1051 When the function `org-mode' is called interactively in an empty file, this
1052 normally means that the file name does not automatically trigger Org mode.
1053 To ensure that the file will always be in Org mode in the future, a
1054 line enforcing Org mode will be inserted into the buffer, if this option
1055 has been set."
1056 :group 'org-startup
1057 :type 'boolean)
1059 (defcustom org-replace-disputed-keys nil
1060 "Non-nil means use alternative key bindings for some keys.
1061 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1062 These keys are also used by other packages like shift-selection-mode'
1063 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1064 If you want to use Org mode together with one of these other modes,
1065 or more generally if you would like to move some Org mode commands to
1066 other keys, set this variable and configure the keys with the variable
1067 `org-disputed-keys'.
1069 This option is only relevant at load-time of Org mode, and must be set
1070 *before* org.el is loaded. Changing it requires a restart of Emacs to
1071 become effective."
1072 :group 'org-startup
1073 :type 'boolean)
1075 (defcustom org-use-extra-keys nil
1076 "Non-nil means use extra key sequence definitions for certain commands.
1077 This happens automatically if `window-system' is nil. This
1078 variable lets you do the same manually. You must set it before
1079 loading Org."
1080 :group 'org-startup
1081 :type 'boolean)
1083 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1085 (defcustom org-disputed-keys
1086 '(([(shift up)] . [(meta p)])
1087 ([(shift down)] . [(meta n)])
1088 ([(shift left)] . [(meta -)])
1089 ([(shift right)] . [(meta +)])
1090 ([(control shift right)] . [(meta shift +)])
1091 ([(control shift left)] . [(meta shift -)]))
1092 "Keys for which Org mode and other modes compete.
1093 This is an alist, cars are the default keys, second element specifies
1094 the alternative to use when `org-replace-disputed-keys' is t.
1096 Keys can be specified in any syntax supported by `define-key'.
1097 The value of this option takes effect only at Org mode startup,
1098 therefore you'll have to restart Emacs to apply it after changing."
1099 :group 'org-startup
1100 :type 'alist)
1102 (defun org-key (key)
1103 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1104 Or return the original if not disputed."
1105 (when org-replace-disputed-keys
1106 (let* ((nkey (key-description key))
1107 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1108 org-disputed-keys)))
1109 (setq key (if x (cdr x) key))))
1110 key)
1112 (defun org-defkey (keymap key def)
1113 "Define a key, possibly translated, as returned by `org-key'."
1114 (define-key keymap (org-key key) def))
1116 (defcustom org-ellipsis nil
1117 "The ellipsis to use in the Org mode outline.
1119 When nil, just use the standard three dots.
1120 When a string, use that string instead.
1122 The change affects only Org mode (which will then use its own display table).
1123 Changing this requires executing `\\[org-mode]' in a buffer to become
1124 effective."
1125 :group 'org-startup
1126 :type '(choice (const :tag "Default" nil)
1127 (string :tag "String" :value "...#"))
1128 :safe #'string-or-null-p)
1130 (defvar org-display-table nil
1131 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1133 (defgroup org-keywords nil
1134 "Keywords in Org mode."
1135 :tag "Org Keywords"
1136 :group 'org)
1138 (defcustom org-closed-keep-when-no-todo nil
1139 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1140 :group 'org-todo
1141 :group 'org-keywords
1142 :version "24.4"
1143 :package-version '(Org . "8.0")
1144 :type 'boolean)
1146 (defgroup org-structure nil
1147 "Options concerning the general structure of Org files."
1148 :tag "Org Structure"
1149 :group 'org)
1151 (defgroup org-reveal-location nil
1152 "Options about how to make context of a location visible."
1153 :tag "Org Reveal Location"
1154 :group 'org-structure)
1156 (defcustom org-show-context-detail '((agenda . local)
1157 (bookmark-jump . lineage)
1158 (isearch . lineage)
1159 (default . ancestors))
1160 "Alist between context and visibility span when revealing a location.
1162 \\<org-mode-map>Some actions may move point into invisible
1163 locations. As a consequence, Org always expose a neighborhood
1164 around point. How much is shown depends on the initial action,
1165 or context. Valid contexts are
1167 agenda when exposing an entry from the agenda
1168 org-goto when using the command `org-goto' (`\\[org-goto]')
1169 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1170 tags-tree when constructing a sparse tree based on tags matches
1171 link-search when exposing search matches associated with a link
1172 mark-goto when exposing the jump goal of a mark
1173 bookmark-jump when exposing a bookmark location
1174 isearch when exiting from an incremental search
1175 default default for all contexts not set explicitly
1177 Allowed visibility spans are
1179 minimal show current headline; if point is not on headline,
1180 also show entry
1182 local show current headline, entry and next headline
1184 ancestors show current headline and its direct ancestors; if
1185 point is not on headline, also show entry
1187 lineage show current headline, its direct ancestors and all
1188 their children; if point is not on headline, also show
1189 entry and first child
1191 tree show current headline, its direct ancestors and all
1192 their children; if point is not on headline, also show
1193 entry and all children
1195 canonical show current headline, its direct ancestors along with
1196 their entries and children; if point is not located on
1197 the headline, also show current entry and all children
1199 As special cases, a nil or t value means show all contexts in
1200 `minimal' or `canonical' view, respectively.
1202 Some views can make displayed information very compact, but also
1203 make it harder to edit the location of the match. In such
1204 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1205 more context."
1206 :group 'org-reveal-location
1207 :version "25.2"
1208 :package-version '(Org . "9.0")
1209 :type '(choice
1210 (const :tag "Canonical" t)
1211 (const :tag "Minimal" nil)
1212 (repeat :greedy t :tag "Individual contexts"
1213 (cons
1214 (choice :tag "Context"
1215 (const agenda)
1216 (const org-goto)
1217 (const occur-tree)
1218 (const tags-tree)
1219 (const link-search)
1220 (const mark-goto)
1221 (const bookmark-jump)
1222 (const isearch)
1223 (const default))
1224 (choice :tag "Detail level"
1225 (const minimal)
1226 (const local)
1227 (const ancestors)
1228 (const lineage)
1229 (const tree)
1230 (const canonical))))))
1232 (defcustom org-indirect-buffer-display 'other-window
1233 "How should indirect tree buffers be displayed?
1235 This applies to indirect buffers created with the commands
1236 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1238 Valid values are:
1239 current-window Display in the current window
1240 other-window Just display in another window.
1241 dedicated-frame Create one new frame, and re-use it each time.
1242 new-frame Make a new frame each time. Note that in this case
1243 previously-made indirect buffers are kept, and you need to
1244 kill these buffers yourself."
1245 :group 'org-structure
1246 :group 'org-agenda-windows
1247 :type '(choice
1248 (const :tag "In current window" current-window)
1249 (const :tag "In current frame, other window" other-window)
1250 (const :tag "Each time a new frame" new-frame)
1251 (const :tag "One dedicated frame" dedicated-frame)))
1253 (defcustom org-use-speed-commands nil
1254 "Non-nil means activate single letter commands at beginning of a headline.
1255 This may also be a function to test for appropriate locations where speed
1256 commands should be active.
1258 For example, to activate speed commands when the point is on any
1259 star at the beginning of the headline, you can do this:
1261 (setq org-use-speed-commands
1262 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1263 :group 'org-structure
1264 :type '(choice
1265 (const :tag "Never" nil)
1266 (const :tag "At beginning of headline stars" t)
1267 (function)))
1269 (defcustom org-speed-commands-user nil
1270 "Alist of additional speed commands.
1271 This list will be checked before `org-speed-commands-default'
1272 when the variable `org-use-speed-commands' is non-nil
1273 and when the cursor is at the beginning of a headline.
1274 The car if each entry is a string with a single letter, which must
1275 be assigned to `self-insert-command' in the global map.
1276 The cdr is either a command to be called interactively, a function
1277 to be called, or a form to be evaluated.
1278 An entry that is just a list with a single string will be interpreted
1279 as a descriptive headline that will be added when listing the speed
1280 commands in the Help buffer using the `?' speed command."
1281 :group 'org-structure
1282 :type '(repeat :value ("k" . ignore)
1283 (choice :value ("k" . ignore)
1284 (list :tag "Descriptive Headline" (string :tag "Headline"))
1285 (cons :tag "Letter and Command"
1286 (string :tag "Command letter")
1287 (choice
1288 (function)
1289 (sexp))))))
1291 (defcustom org-bookmark-names-plist
1292 '(:last-capture "org-capture-last-stored"
1293 :last-refile "org-refile-last-stored"
1294 :last-capture-marker "org-capture-last-stored-marker")
1295 "Names for bookmarks automatically set by some Org commands.
1296 This can provide strings as names for a number of bookmarks Org sets
1297 automatically. The following keys are currently implemented:
1298 :last-capture
1299 :last-capture-marker
1300 :last-refile
1301 When a key does not show up in the property list, the corresponding bookmark
1302 is not set."
1303 :group 'org-structure
1304 :type 'plist)
1306 (defgroup org-cycle nil
1307 "Options concerning visibility cycling in Org mode."
1308 :tag "Org Cycle"
1309 :group 'org-structure)
1311 (defcustom org-cycle-skip-children-state-if-no-children t
1312 "Non-nil means skip CHILDREN state in entries that don't have any."
1313 :group 'org-cycle
1314 :type 'boolean)
1316 (defcustom org-cycle-max-level nil
1317 "Maximum level which should still be subject to visibility cycling.
1318 Levels higher than this will, for cycling, be treated as text, not a headline.
1319 When `org-odd-levels-only' is set, a value of N in this variable actually
1320 means 2N-1 stars as the limiting headline.
1321 When nil, cycle all levels.
1322 Note that the limiting level of cycling is also influenced by
1323 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1324 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1325 than its value."
1326 :group 'org-cycle
1327 :type '(choice
1328 (const :tag "No limit" nil)
1329 (integer :tag "Maximum level")))
1331 (defcustom org-hide-block-startup nil
1332 "Non-nil means entering Org mode will fold all blocks.
1333 This can also be set in on a per-file basis with
1335 #+STARTUP: hideblocks
1336 #+STARTUP: showblocks"
1337 :group 'org-startup
1338 :group 'org-cycle
1339 :type 'boolean)
1341 (defcustom org-cycle-global-at-bob nil
1342 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1344 This makes it possible to do global cycling without having to use `S-TAB'
1345 or `\\[universal-argument] TAB'. For this special case to work, the first \
1346 line of the buffer
1347 must not be a headline -- it may be empty or some other text.
1349 When used in this way, `org-cycle-hook' is disabled temporarily to make
1350 sure the cursor stays at the beginning of the buffer.
1352 When this option is nil, don't do anything special at the beginning of
1353 the buffer."
1354 :group 'org-cycle
1355 :type 'boolean)
1357 (defcustom org-cycle-level-after-item/entry-creation t
1358 "Non-nil means cycle entry level or item indentation in new empty entries.
1360 When the cursor is at the end of an empty headline, i.e., with only stars
1361 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1362 and then all possible ancestor states, before returning to the original state.
1363 This makes data entry extremely fast: M-RET to create a new headline,
1364 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1366 When the cursor is at the end of an empty plain list item, one TAB will
1367 make it a subitem, two or more tabs will back up to make this an item
1368 higher up in the item hierarchy."
1369 :group 'org-cycle
1370 :type 'boolean)
1372 (defcustom org-cycle-emulate-tab t
1373 "Where should `org-cycle' emulate TAB.
1374 nil Never
1375 white Only in completely white lines
1376 whitestart Only at the beginning of lines, before the first non-white char
1377 t Everywhere except in headlines
1378 exc-hl-bol Everywhere except at the start of a headline
1379 If TAB is used in a place where it does not emulate TAB, the current subtree
1380 visibility is cycled."
1381 :group 'org-cycle
1382 :type '(choice (const :tag "Never" nil)
1383 (const :tag "Only in completely white lines" white)
1384 (const :tag "Before first char in a line" whitestart)
1385 (const :tag "Everywhere except in headlines" t)
1386 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1388 (defcustom org-cycle-separator-lines 2
1389 "Number of empty lines needed to keep an empty line between collapsed trees.
1390 If you leave an empty line between the end of a subtree and the following
1391 headline, this empty line is hidden when the subtree is folded.
1392 Org mode will leave (exactly) one empty line visible if the number of
1393 empty lines is equal or larger to the number given in this variable.
1394 So the default 2 means at least 2 empty lines after the end of a subtree
1395 are needed to produce free space between a collapsed subtree and the
1396 following headline.
1398 If the number is negative, and the number of empty lines is at least -N,
1399 all empty lines are shown.
1401 Special case: when 0, never leave empty lines in collapsed view."
1402 :group 'org-cycle
1403 :type 'integer)
1404 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1406 (defcustom org-pre-cycle-hook nil
1407 "Hook that is run before visibility cycling is happening.
1408 The function(s) in this hook must accept a single argument which indicates
1409 the new state that will be set right after running this hook. The
1410 argument is a symbol. Before a global state change, it can have the values
1411 `overview', `content', or `all'. Before a local state change, it can have
1412 the values `folded', `children', or `subtree'."
1413 :group 'org-cycle
1414 :type 'hook)
1416 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1417 org-cycle-hide-drawers
1418 org-cycle-show-empty-lines
1419 org-optimize-window-after-visibility-change)
1420 "Hook that is run after `org-cycle' has changed the buffer visibility.
1421 The function(s) in this hook must accept a single argument which indicates
1422 the new state that was set by the most recent `org-cycle' command. The
1423 argument is a symbol. After a global state change, it can have the values
1424 `overview', `contents', or `all'. After a local state change, it can have
1425 the values `folded', `children', or `subtree'."
1426 :group 'org-cycle
1427 :type 'hook
1428 :version "25.2"
1429 :package-version '(Org . "8.3"))
1431 (defgroup org-edit-structure nil
1432 "Options concerning structure editing in Org mode."
1433 :tag "Org Edit Structure"
1434 :group 'org-structure)
1436 (defcustom org-odd-levels-only nil
1437 "Non-nil means skip even levels and only use odd levels for the outline.
1438 This has the effect that two stars are being added/taken away in
1439 promotion/demotion commands. It also influences how levels are
1440 handled by the exporters.
1441 Changing it requires restart of `font-lock-mode' to become effective
1442 for fontification also in regions already fontified.
1443 You may also set this on a per-file basis by adding one of the following
1444 lines to the buffer:
1446 #+STARTUP: odd
1447 #+STARTUP: oddeven"
1448 :group 'org-edit-structure
1449 :group 'org-appearance
1450 :type 'boolean)
1452 (defcustom org-adapt-indentation t
1453 "Non-nil means adapt indentation to outline node level.
1455 When this variable is set, Org assumes that you write outlines by
1456 indenting text in each node to align with the headline (after the
1457 stars). The following issues are influenced by this variable:
1459 - The indentation is increased by one space in a demotion
1460 command, and decreased by one in a promotion command. However,
1461 in the latter case, if shifting some line in the entry body
1462 would alter document structure (e.g., insert a new headline),
1463 indentation is not changed at all.
1465 - Property drawers and planning information is inserted indented
1466 when this variable is set. When nil, they will not be indented.
1468 - TAB indents a line relative to current level. The lines below
1469 a headline will be indented when this variable is set.
1471 Note that this is all about true indentation, by adding and
1472 removing space characters. See also `org-indent.el' which does
1473 level-dependent indentation in a virtual way, i.e. at display
1474 time in Emacs."
1475 :group 'org-edit-structure
1476 :type 'boolean)
1478 (defcustom org-special-ctrl-a/e nil
1479 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1481 When t, `C-a' will bring back the cursor to the beginning of the
1482 headline text, i.e. after the stars and after a possible TODO
1483 keyword. In an item, this will be the position after bullet and
1484 check-box, if any. When the cursor is already at that position,
1485 another `C-a' will bring it to the beginning of the line.
1487 `C-e' will jump to the end of the headline, ignoring the presence
1488 of tags in the headline. A second `C-e' will then jump to the
1489 true end of the line, after any tags. This also means that, when
1490 this variable is non-nil, `C-e' also will never jump beyond the
1491 end of the heading of a folded section, i.e. not after the
1492 ellipses.
1494 When set to the symbol `reversed', the first `C-a' or `C-e' works
1495 normally, going to the true line boundary first. Only a directly
1496 following, identical keypress will bring the cursor to the
1497 special positions.
1499 This may also be a cons cell where the behavior for `C-a' and
1500 `C-e' is set separately."
1501 :group 'org-edit-structure
1502 :type '(choice
1503 (const :tag "off" nil)
1504 (const :tag "on: after stars/bullet and before tags first" t)
1505 (const :tag "reversed: true line boundary first" reversed)
1506 (cons :tag "Set C-a and C-e separately"
1507 (choice :tag "Special C-a"
1508 (const :tag "off" nil)
1509 (const :tag "on: after stars/bullet first" t)
1510 (const :tag "reversed: before stars/bullet first" reversed))
1511 (choice :tag "Special C-e"
1512 (const :tag "off" nil)
1513 (const :tag "on: before tags first" t)
1514 (const :tag "reversed: after tags first" reversed)))))
1515 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1517 (defcustom org-special-ctrl-k nil
1518 "Non-nil means `C-k' will behave specially in headlines.
1519 When nil, `C-k' will call the default `kill-line' command.
1520 When t, the following will happen while the cursor is in the headline:
1522 - When the cursor is at the beginning of a headline, kill the entire
1523 line and possible the folded subtree below the line.
1524 - When in the middle of the headline text, kill the headline up to the tags.
1525 - When after the headline text, kill the tags."
1526 :group 'org-edit-structure
1527 :type 'boolean)
1529 (defcustom org-ctrl-k-protect-subtree nil
1530 "Non-nil means, do not delete a hidden subtree with C-k.
1531 When set to the symbol `error', simply throw an error when C-k is
1532 used to kill (part-of) a headline that has hidden text behind it.
1533 Any other non-nil value will result in a query to the user, if it is
1534 OK to kill that hidden subtree. When nil, kill without remorse."
1535 :group 'org-edit-structure
1536 :version "24.1"
1537 :type '(choice
1538 (const :tag "Do not protect hidden subtrees" nil)
1539 (const :tag "Protect hidden subtrees with a security query" t)
1540 (const :tag "Never kill a hidden subtree with C-k" error)))
1542 (defcustom org-special-ctrl-o t
1543 "Non-nil means, make `C-o' insert a row in tables."
1544 :group 'org-edit-structure
1545 :type 'boolean)
1547 (defcustom org-catch-invisible-edits nil
1548 "Check if in invisible region before inserting or deleting a character.
1549 Valid values are:
1551 nil Do not check, so just do invisible edits.
1552 error Throw an error and do nothing.
1553 show Make point visible, and do the requested edit.
1554 show-and-error Make point visible, then throw an error and abort the edit.
1555 smart Make point visible, and do insertion/deletion if it is
1556 adjacent to visible text and the change feels predictable.
1557 Never delete a previously invisible character or add in the
1558 middle or right after an invisible region. Basically, this
1559 allows insertion and backward-delete right before ellipses.
1560 FIXME: maybe in this case we should not even show?"
1561 :group 'org-edit-structure
1562 :version "24.1"
1563 :type '(choice
1564 (const :tag "Do not check" nil)
1565 (const :tag "Throw error when trying to edit" error)
1566 (const :tag "Unhide, but do not do the edit" show-and-error)
1567 (const :tag "Show invisible part and do the edit" show)
1568 (const :tag "Be smart and do the right thing" smart)))
1570 (defcustom org-yank-folded-subtrees t
1571 "Non-nil means when yanking subtrees, fold them.
1572 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1573 it starts with a heading and all other headings in it are either children
1574 or siblings, then fold all the subtrees. However, do this only if no
1575 text after the yank would be swallowed into a folded tree by this action."
1576 :group 'org-edit-structure
1577 :type 'boolean)
1579 (defcustom org-yank-adjusted-subtrees nil
1580 "Non-nil means when yanking subtrees, adjust the level.
1581 With this setting, `org-paste-subtree' is used to insert the subtree, see
1582 this function for details."
1583 :group 'org-edit-structure
1584 :type 'boolean)
1586 (defcustom org-M-RET-may-split-line '((default . t))
1587 "Non-nil means M-RET will split the line at the cursor position.
1588 When nil, it will go to the end of the line before making a
1589 new line.
1590 You may also set this option in a different way for different
1591 contexts. Valid contexts are:
1593 headline when creating a new headline
1594 item when creating a new item
1595 table in a table field
1596 default the value to be used for all contexts not explicitly
1597 customized"
1598 :group 'org-structure
1599 :group 'org-table
1600 :type '(choice
1601 (const :tag "Always" t)
1602 (const :tag "Never" nil)
1603 (repeat :greedy t :tag "Individual contexts"
1604 (cons
1605 (choice :tag "Context"
1606 (const headline)
1607 (const item)
1608 (const table)
1609 (const default))
1610 (boolean)))))
1613 (defcustom org-insert-heading-respect-content nil
1614 "Non-nil means insert new headings after the current subtree.
1615 \\<org-mode-map>
1616 When nil, the new heading is created directly after the current line.
1617 The commands `\\[org-insert-heading-respect-content]' and \
1618 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1619 for the duration of the command."
1620 :group 'org-structure
1621 :type 'boolean)
1623 (defcustom org-blank-before-new-entry '((heading . auto)
1624 (plain-list-item . auto))
1625 "Should `org-insert-heading' leave a blank line before new heading/item?
1626 The value is an alist, with `heading' and `plain-list-item' as CAR,
1627 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1628 which case Org will look at the surrounding headings/items and try to
1629 make an intelligent decision whether to insert a blank line or not."
1630 :group 'org-edit-structure
1631 :type '(list
1632 (cons (const heading)
1633 (choice (const :tag "Never" nil)
1634 (const :tag "Always" t)
1635 (const :tag "Auto" auto)))
1636 (cons (const plain-list-item)
1637 (choice (const :tag "Never" nil)
1638 (const :tag "Always" t)
1639 (const :tag "Auto" auto)))))
1641 (defcustom org-insert-heading-hook nil
1642 "Hook being run after inserting a new heading."
1643 :group 'org-edit-structure
1644 :type 'hook)
1646 (defcustom org-enable-fixed-width-editor t
1647 "Non-nil means lines starting with \":\" are treated as fixed-width.
1648 This currently only means they are never auto-wrapped.
1649 When nil, such lines will be treated like ordinary lines."
1650 :group 'org-edit-structure
1651 :type 'boolean)
1653 (defcustom org-goto-auto-isearch t
1654 "Non-nil means typing characters in `org-goto' starts incremental search.
1655 When nil, you can use these keybindings to navigate the buffer:
1657 q Quit the org-goto interface
1658 n Go to the next visible heading
1659 p Go to the previous visible heading
1660 f Go one heading forward on same level
1661 b Go one heading backward on same level
1662 u Go one heading up"
1663 :group 'org-edit-structure
1664 :type 'boolean)
1666 (defgroup org-sparse-trees nil
1667 "Options concerning sparse trees in Org mode."
1668 :tag "Org Sparse Trees"
1669 :group 'org-structure)
1671 (defcustom org-highlight-sparse-tree-matches t
1672 "Non-nil means highlight all matches that define a sparse tree.
1673 The highlights will automatically disappear the next time the buffer is
1674 changed by an edit command."
1675 :group 'org-sparse-trees
1676 :type 'boolean)
1678 (defcustom org-remove-highlights-with-change t
1679 "Non-nil means any change to the buffer will remove temporary highlights.
1680 \\<org-mode-map>\
1681 Such highlights are created by `org-occur' and `org-clock-display'.
1682 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1683 to get rid of the highlights.
1684 The highlights created by `org-toggle-latex-fragment' always need
1685 `\\[org-toggle-latex-fragment]' to be removed."
1686 :group 'org-sparse-trees
1687 :group 'org-time
1688 :type 'boolean)
1690 (defcustom org-occur-case-fold-search t
1691 "Non-nil means `org-occur' should be case-insensitive.
1692 If set to `smart' the search will be case-insensitive only if it
1693 doesn't specify any upper case character."
1694 :group 'org-sparse-trees
1695 :version "25.2"
1696 :type '(choice
1697 (const :tag "Case-sensitive" nil)
1698 (const :tag "Case-insensitive" t)
1699 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1701 (defcustom org-occur-hook '(org-first-headline-recenter)
1702 "Hook that is run after `org-occur' has constructed a sparse tree.
1703 This can be used to recenter the window to show as much of the structure
1704 as possible."
1705 :group 'org-sparse-trees
1706 :type 'hook)
1708 (defgroup org-imenu-and-speedbar nil
1709 "Options concerning imenu and speedbar in Org mode."
1710 :tag "Org Imenu and Speedbar"
1711 :group 'org-structure)
1713 (defcustom org-imenu-depth 2
1714 "The maximum level for Imenu access to Org headlines.
1715 This also applied for speedbar access."
1716 :group 'org-imenu-and-speedbar
1717 :type 'integer)
1719 (defgroup org-table nil
1720 "Options concerning tables in Org mode."
1721 :tag "Org Table"
1722 :group 'org)
1724 (defcustom org-enable-table-editor 'optimized
1725 "Non-nil means lines starting with \"|\" are handled by the table editor.
1726 When nil, such lines will be treated like ordinary lines.
1728 When equal to the symbol `optimized', the table editor will be optimized to
1729 do the following:
1730 - Automatic overwrite mode in front of whitespace in table fields.
1731 This makes the structure of the table stay in tact as long as the edited
1732 field does not exceed the column width.
1733 - Minimize the number of realigns. Normally, the table is aligned each time
1734 TAB or RET are pressed to move to another field. With optimization this
1735 happens only if changes to a field might have changed the column width.
1736 Optimization requires replacing the functions `self-insert-command',
1737 `delete-char', and `backward-delete-char' in Org buffers, with a
1738 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1739 good at guessing when a re-align will be necessary, but you can always
1740 force one with `\\[org-ctrl-c-ctrl-c]'.
1742 If you would like to use the optimized version in Org mode, but the
1743 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1745 This variable can be used to turn on and off the table editor during a session,
1746 but in order to toggle optimization, a restart is required.
1748 See also the variable `org-table-auto-blank-field'."
1749 :group 'org-table
1750 :type '(choice
1751 (const :tag "off" nil)
1752 (const :tag "on" t)
1753 (const :tag "on, optimized" optimized)))
1755 (defcustom org-self-insert-cluster-for-undo nil
1756 "Non-nil means cluster self-insert commands for undo when possible.
1757 If this is set, then, like in the Emacs command loop, 20 consecutive
1758 characters will be undone together.
1759 This is configurable, because there is some impact on typing performance."
1760 :group 'org-table
1761 :type 'boolean)
1763 (defcustom org-table-tab-recognizes-table.el t
1764 "Non-nil means TAB will automatically notice a table.el table.
1765 When it sees such a table, it moves point into it and - if necessary -
1766 calls `table-recognize-table'."
1767 :group 'org-table-editing
1768 :type 'boolean)
1770 (defgroup org-link nil
1771 "Options concerning links in Org mode."
1772 :tag "Org Link"
1773 :group 'org)
1775 (defvar-local org-link-abbrev-alist-local nil
1776 "Buffer-local version of `org-link-abbrev-alist', which see.
1777 The value of this is taken from the #+LINK lines.")
1779 (defcustom org-link-parameters
1780 '(("doi" :follow org--open-doi-link)
1781 ("elisp" :follow org--open-elisp-link)
1782 ("file" :complete org-file-complete-link)
1783 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1784 ("help" :follow org--open-help-link)
1785 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1786 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1787 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1788 ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
1789 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1790 ("shell" :follow org--open-shell-link))
1791 "An alist of properties that defines all the links in Org mode.
1792 The key in each association is a string of the link type.
1793 Subsequent optional elements make up a p-list of link properties.
1795 :follow - A function that takes the link path as an argument.
1797 :export - A function that takes the link path, description and
1798 export-backend as arguments.
1800 :store - A function responsible for storing the link. See the
1801 function `org-store-link-functions'.
1803 :complete - A function that inserts a link with completion. The
1804 function takes one optional prefix arg.
1806 :face - A face for the link, or a function that returns a face.
1807 The function takes one argument which is the link path. The
1808 default face is `org-link'.
1810 :mouse-face - The mouse-face. The default is `highlight'.
1812 :display - `full' will not fold the link in descriptive
1813 display. Default is `org-link'.
1815 :help-echo - A string or function that takes (window object position)
1816 as arguments and returns a string.
1818 :keymap - A keymap that is active on the link. The default is
1819 `org-mouse-map'.
1821 :htmlize-link - A function for the htmlize-link. Defaults
1822 to (list :uri \"type:path\")
1824 :activate-func - A function to run at the end of font-lock
1825 activation. The function must accept (link-start link-end path bracketp)
1826 as arguments."
1827 :group 'org-link
1828 :type '(alist :tag "Link display parameters"
1829 :value-type plist))
1831 (defun org-link-get-parameter (type key)
1832 "Get TYPE link property for KEY.
1833 TYPE is a string and KEY is a plist keyword."
1834 (plist-get
1835 (cdr (assoc type org-link-parameters))
1836 key))
1838 (defun org-link-set-parameters (type &rest parameters)
1839 "Set link TYPE properties to PARAMETERS.
1840 PARAMETERS should be :key val pairs."
1841 (let ((data (assoc type org-link-parameters)))
1842 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1843 (push (cons type parameters) org-link-parameters)
1844 (org-make-link-regexps)
1845 (org-element-update-syntax))))
1847 (defun org-link-types ()
1848 "Return a list of known link types."
1849 (mapcar #'car org-link-parameters))
1851 (defcustom org-link-abbrev-alist nil
1852 "Alist of link abbreviations.
1853 The car of each element is a string, to be replaced at the start of a link.
1854 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1855 links in Org buffers can have an optional tag after a double colon, e.g.,
1857 [[linkkey:tag][description]]
1859 The `linkkey' must be a single word, starting with a letter, followed
1860 by letters, numbers, `-' or `_'.
1862 If REPLACE is a string, the tag will simply be appended to create the link.
1863 If the string contains \"%s\", the tag will be inserted there. If the string
1864 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1865 at that point (see the function `url-hexify-string'). If the string contains
1866 the specifier \"%(my-function)\", then the custom function `my-function' will
1867 be invoked: this function takes the tag as its only argument and must return
1868 a string.
1870 REPLACE may also be a function that will be called with the tag as the
1871 only argument to create the link, which should be returned as a string.
1873 See the manual for examples."
1874 :group 'org-link
1875 :type '(repeat
1876 (cons
1877 (string :tag "Protocol")
1878 (choice
1879 (string :tag "Format")
1880 (function)))))
1882 (defcustom org-descriptive-links t
1883 "Non-nil means Org will display descriptive links.
1884 E.g. [[http://orgmode.org][Org website]] will be displayed as
1885 \"Org Website\", hiding the link itself and just displaying its
1886 description. When set to nil, Org will display the full links
1887 literally.
1889 You can interactively set the value of this variable by calling
1890 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1891 :group 'org-link
1892 :type 'boolean)
1894 (defcustom org-link-file-path-type 'adaptive
1895 "How the path name in file links should be stored.
1896 Valid values are:
1898 relative Relative to the current directory, i.e. the directory of the file
1899 into which the link is being inserted.
1900 absolute Absolute path, if possible with ~ for home directory.
1901 noabbrev Absolute path, no abbreviation of home directory.
1902 adaptive Use relative path for files in the current directory and sub-
1903 directories of it. For other files, use an absolute path."
1904 :group 'org-link
1905 :type '(choice
1906 (const relative)
1907 (const absolute)
1908 (const noabbrev)
1909 (const adaptive)))
1911 (defvaralias 'org-activate-links 'org-highlight-links)
1912 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1913 "Types of links that should be highlighted in Org files.
1915 This is a list of symbols, each one of them leading to the
1916 highlighting of a certain link type.
1918 You can still open links that are not highlighted.
1920 In principle, it does not hurt to turn on highlighting for all
1921 link types. There may be a small gain when turning off unused
1922 link types. The types are:
1924 bracket The recommended [[link][description]] or [[link]] links with hiding.
1925 angle Links in angular brackets that may contain whitespace like
1926 <bbdb:Carsten Dominik>.
1927 plain Plain links in normal text, no whitespace, like http://google.com.
1928 radio Text that is matched by a radio target, see manual for details.
1929 tag Tag settings in a headline (link to tag search).
1930 date Time stamps (link to calendar).
1931 footnote Footnote labels.
1933 If you set this variable during an Emacs session, use `org-mode-restart'
1934 in the Org buffer so that the change takes effect."
1935 :group 'org-link
1936 :group 'org-appearance
1937 :type '(set :greedy t
1938 (const :tag "Double bracket links" bracket)
1939 (const :tag "Angular bracket links" angle)
1940 (const :tag "Plain text links" plain)
1941 (const :tag "Radio target matches" radio)
1942 (const :tag "Tags" tag)
1943 (const :tag "Timestamps" date)
1944 (const :tag "Footnotes" footnote)))
1946 (defcustom org-make-link-description-function nil
1947 "Function to use for generating link descriptions from links.
1948 When nil, the link location will be used. This function must take
1949 two parameters: the first one is the link, the second one is the
1950 description generated by `org-insert-link'. The function should
1951 return the description to use."
1952 :group 'org-link
1953 :type '(choice (const nil) (function)))
1955 (defgroup org-link-store nil
1956 "Options concerning storing links in Org mode."
1957 :tag "Org Store Link"
1958 :group 'org-link)
1960 (defcustom org-url-hexify-p t
1961 "When non-nil, hexify URL when creating a link."
1962 :type 'boolean
1963 :version "24.3"
1964 :group 'org-link-store)
1966 (defcustom org-email-link-description-format "Email %c: %.30s"
1967 "Format of the description part of a link to an email or usenet message.
1968 The following %-escapes will be replaced by corresponding information:
1970 %F full \"From\" field
1971 %f name, taken from \"From\" field, address if no name
1972 %T full \"To\" field
1973 %t first name in \"To\" field, address if no name
1974 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1975 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1976 %s subject
1977 %d date
1978 %m message-id.
1980 You may use normal field width specification between the % and the letter.
1981 This is for example useful to limit the length of the subject.
1983 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1984 :group 'org-link-store
1985 :type 'string)
1987 (defcustom org-from-is-user-regexp
1988 (let (r1 r2)
1989 (when (and user-mail-address (not (string= user-mail-address "")))
1990 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1991 (when (and user-full-name (not (string= user-full-name "")))
1992 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1993 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1994 "Regexp matched against the \"From:\" header of an email or usenet message.
1995 It should match if the message is from the user him/herself."
1996 :group 'org-link-store
1997 :type 'regexp)
1999 (defcustom org-context-in-file-links t
2000 "Non-nil means file links from `org-store-link' contain context.
2001 \\<org-mode-map>
2002 A search string will be added to the file name with :: as separator
2003 and used to find the context when the link is activated by the command
2004 `org-open-at-point'. When this option is t, the entire active region
2005 will be placed in the search string of the file link. If set to a
2006 positive integer, only the first n lines of context will be stored.
2008 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2009 \\[org-store-link]')
2010 negates this setting for the duration of the command."
2011 :group 'org-link-store
2012 :type '(choice boolean integer))
2014 (defcustom org-keep-stored-link-after-insertion nil
2015 "Non-nil means keep link in list for entire session.
2016 \\<org-mode-map>
2017 The command `org-store-link' adds a link pointing to the current
2018 location to an internal list. These links accumulate during a session.
2019 The command `org-insert-link' can be used to insert links into any
2020 Org file (offering completion for all stored links).
2022 When this option is nil, every link which has been inserted once using
2023 `\\[org-insert-link]' will be removed from the list, to make completing the \
2024 unused
2025 links more efficient."
2026 :group 'org-link-store
2027 :type 'boolean)
2029 (defgroup org-link-follow nil
2030 "Options concerning following links in Org mode."
2031 :tag "Org Follow Link"
2032 :group 'org-link)
2034 (defcustom org-link-translation-function nil
2035 "Function to translate links with different syntax to Org syntax.
2036 This can be used to translate links created for example by the Planner
2037 or emacs-wiki packages to Org syntax.
2038 The function must accept two parameters, a TYPE containing the link
2039 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2040 which is everything after the link protocol. It should return a cons
2041 with possibly modified values of type and path.
2042 Org contains a function for this, so if you set this variable to
2043 `org-translate-link-from-planner', you should be able follow many
2044 links created by planner."
2045 :group 'org-link-follow
2046 :type '(choice (const nil) (function)))
2048 (defcustom org-follow-link-hook nil
2049 "Hook that is run after a link has been followed."
2050 :group 'org-link-follow
2051 :type 'hook)
2053 (defcustom org-tab-follows-link nil
2054 "Non-nil means on links TAB will follow the link.
2055 Needs to be set before org.el is loaded.
2056 This really should not be used, it does not make sense, and the
2057 implementation is bad."
2058 :group 'org-link-follow
2059 :type 'boolean)
2061 (defcustom org-return-follows-link nil
2062 "Non-nil means on links RET will follow the link.
2063 In tables, the special behavior of RET has precedence."
2064 :group 'org-link-follow
2065 :type 'boolean)
2067 (defcustom org-mouse-1-follows-link
2068 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2069 "Non-nil means mouse-1 on a link will follow the link.
2070 A longer mouse click will still set point. Needs to be set
2071 before org.el is loaded."
2072 :group 'org-link-follow
2073 :version "24.4"
2074 :package-version '(Org . "8.3")
2075 :type '(choice
2076 (const :tag "A double click follows the link" double)
2077 (const :tag "Unconditionally follow the link with mouse-1" t)
2078 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2080 (defcustom org-mark-ring-length 4
2081 "Number of different positions to be recorded in the ring.
2082 Changing this requires a restart of Emacs to work correctly."
2083 :group 'org-link-follow
2084 :type 'integer)
2086 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2087 "Non-nil means internal fuzzy links can only match headlines.
2089 When nil, the a fuzzy link may point to a target or a named
2090 construct in the document. When set to the special value
2091 `query-to-create', offer to create a new headline when none
2092 matched.
2094 Spaces and statistics cookies are ignored during heading searches."
2095 :group 'org-link-follow
2096 :version "24.1"
2097 :type '(choice
2098 (const :tag "Use fuzzy text search" nil)
2099 (const :tag "Match only exact headline" t)
2100 (const :tag "Match exact headline or query to create it"
2101 query-to-create))
2102 :safe #'symbolp)
2104 (defcustom org-link-frame-setup
2105 '((vm . vm-visit-folder-other-frame)
2106 (vm-imap . vm-visit-imap-folder-other-frame)
2107 (gnus . org-gnus-no-new-news)
2108 (file . find-file-other-window)
2109 (wl . wl-other-frame))
2110 "Setup the frame configuration for following links.
2111 When following a link with Emacs, it may often be useful to display
2112 this link in another window or frame. This variable can be used to
2113 set this up for the different types of links.
2114 For VM, use any of
2115 `vm-visit-folder'
2116 `vm-visit-folder-other-window'
2117 `vm-visit-folder-other-frame'
2118 For Gnus, use any of
2119 `gnus'
2120 `gnus-other-frame'
2121 `org-gnus-no-new-news'
2122 For FILE, use any of
2123 `find-file'
2124 `find-file-other-window'
2125 `find-file-other-frame'
2126 For Wanderlust use any of
2127 `wl'
2128 `wl-other-frame'
2129 For the calendar, use the variable `calendar-setup'.
2130 For BBDB, it is currently only possible to display the matches in
2131 another window."
2132 :group 'org-link-follow
2133 :type '(list
2134 (cons (const vm)
2135 (choice
2136 (const vm-visit-folder)
2137 (const vm-visit-folder-other-window)
2138 (const vm-visit-folder-other-frame)))
2139 (cons (const vm-imap)
2140 (choice
2141 (const vm-visit-imap-folder)
2142 (const vm-visit-imap-folder-other-window)
2143 (const vm-visit-imap-folder-other-frame)))
2144 (cons (const gnus)
2145 (choice
2146 (const gnus)
2147 (const gnus-other-frame)
2148 (const org-gnus-no-new-news)))
2149 (cons (const file)
2150 (choice
2151 (const find-file)
2152 (const find-file-other-window)
2153 (const find-file-other-frame)))
2154 (cons (const wl)
2155 (choice
2156 (const wl)
2157 (const wl-other-frame)))))
2159 (defcustom org-display-internal-link-with-indirect-buffer nil
2160 "Non-nil means use indirect buffer to display infile links.
2161 Activating internal links (from one location in a file to another location
2162 in the same file) normally just jumps to the location. When the link is
2163 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2164 is displayed in
2165 another window. When this option is set, the other window actually displays
2166 an indirect buffer clone of the current buffer, to avoid any visibility
2167 changes to the current buffer."
2168 :group 'org-link-follow
2169 :type 'boolean)
2171 (defcustom org-open-non-existing-files nil
2172 "Non-nil means `org-open-file' will open non-existing files.
2173 When nil, an error will be generated.
2174 This variable applies only to external applications because they
2175 might choke on non-existing files. If the link is to a file that
2176 will be opened in Emacs, the variable is ignored."
2177 :group 'org-link-follow
2178 :type 'boolean)
2180 (defcustom org-open-directory-means-index-dot-org nil
2181 "Non-nil means a link to a directory really means to index.org.
2182 When nil, following a directory link will run dired or open a finder/explorer
2183 window on that directory."
2184 :group 'org-link-follow
2185 :type 'boolean)
2187 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2188 "Non-nil means ask for confirmation before executing shell links.
2189 Shell links can be dangerous: just think about a link
2191 [[shell:rm -rf ~/*][Google Search]]
2193 This link would show up in your Org document as \"Google Search\",
2194 but really it would remove your entire home directory.
2195 Therefore we advise against setting this variable to nil.
2196 Just change it to `y-or-n-p' if you want to confirm with a
2197 single keystroke rather than having to type \"yes\"."
2198 :group 'org-link-follow
2199 :type '(choice
2200 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2201 (const :tag "with y-or-n (faster)" y-or-n-p)
2202 (const :tag "no confirmation (dangerous)" nil)))
2203 (put 'org-confirm-shell-link-function
2204 'safe-local-variable
2205 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2207 (defcustom org-confirm-shell-link-not-regexp ""
2208 "A regexp to skip confirmation for shell links."
2209 :group 'org-link-follow
2210 :version "24.1"
2211 :type 'regexp)
2213 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2214 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2215 Elisp links can be dangerous: just think about a link
2217 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2219 This link would show up in your Org document as \"Google Search\",
2220 but really it would remove your entire home directory.
2221 Therefore we advise against setting this variable to nil.
2222 Just change it to `y-or-n-p' if you want to confirm with a
2223 single keystroke rather than having to type \"yes\"."
2224 :group 'org-link-follow
2225 :type '(choice
2226 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2227 (const :tag "with y-or-n (faster)" y-or-n-p)
2228 (const :tag "no confirmation (dangerous)" nil)))
2229 (put 'org-confirm-shell-link-function
2230 'safe-local-variable
2231 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2233 (defcustom org-confirm-elisp-link-not-regexp ""
2234 "A regexp to skip confirmation for Elisp links."
2235 :group 'org-link-follow
2236 :version "24.1"
2237 :type 'regexp)
2239 (defconst org-file-apps-defaults-gnu
2240 '((remote . emacs)
2241 (system . mailcap)
2242 (t . mailcap))
2243 "Default file applications on a UNIX or GNU/Linux system.
2244 See `org-file-apps'.")
2246 (defconst org-file-apps-defaults-macosx
2247 '((remote . emacs)
2248 (system . "open %s")
2249 ("ps.gz" . "gv %s")
2250 ("eps.gz" . "gv %s")
2251 ("dvi" . "xdvi %s")
2252 ("fig" . "xfig %s")
2253 (t . "open %s"))
2254 "Default file applications on a macOS system.
2255 The system \"open\" is known as a default, but we use X11 applications
2256 for some files for which the OS does not have a good default.
2257 See `org-file-apps'.")
2259 (defconst org-file-apps-defaults-windowsnt
2260 (list '(remote . emacs)
2261 (cons 'system (lambda (file _path)
2262 (with-no-warnings (w32-shell-execute "open" file))))
2263 (cons t (lambda (file _path)
2264 (with-no-warnings (w32-shell-execute "open" file)))))
2265 "Default file applications on a Windows NT system.
2266 The system \"open\" is used for most files.
2267 See `org-file-apps'.")
2269 (defcustom org-file-apps
2270 '((auto-mode . emacs)
2271 ("\\.mm\\'" . default)
2272 ("\\.x?html?\\'" . default)
2273 ("\\.pdf\\'" . default))
2274 "External applications for opening `file:path' items in a document.
2275 \\<org-mode-map>\
2277 Org mode uses system defaults for different file types, but
2278 you can use this variable to set the application for a given file
2279 extension. The entries in this list are cons cells where the car identifies
2280 files and the cdr the corresponding command.
2282 Possible values for the file identifier are:
2284 \"string\" A string as a file identifier can be interpreted in different
2285 ways, depending on its contents:
2287 - Alphanumeric characters only:
2288 Match links with this file extension.
2289 Example: (\"pdf\" . \"evince %s\")
2290 to open PDFs with evince.
2292 - Regular expression: Match links where the
2293 filename matches the regexp. If you want to
2294 use groups here, use shy groups.
2296 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2297 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2298 to open *.html and *.xhtml with firefox.
2300 - Regular expression which contains (non-shy) groups:
2301 Match links where the whole link, including \"::\", and
2302 anything after that, matches the regexp.
2303 In a custom command string, %1, %2, etc. are replaced with
2304 the parts of the link that were matched by the groups.
2305 For backwards compatibility, if a command string is given
2306 that does not use any of the group matches, this case is
2307 handled identically to the second one (i.e. match against
2308 file name only).
2309 In a custom function, you can access the group matches with
2310 (match-string n link).
2312 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2313 \"evince -p %1 %s\")
2314 to open [[file:document.pdf::5]] with evince at page 5.
2316 `directory' Matches a directory
2317 `remote' Matches a remote file, accessible through tramp or efs.
2318 Remote files most likely should be visited through Emacs
2319 because external applications cannot handle such paths.
2320 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2321 so all files Emacs knows how to handle. Using this with
2322 command `emacs' will open most files in Emacs. Beware that this
2323 will also open html files inside Emacs, unless you add
2324 (\"html\" . default) to the list as well.
2325 `system' The system command to open files, like `open' on Windows
2326 and macOS, and mailcap under GNU/Linux. This is the command
2327 that will be selected if you call `org-open-at-point' with a
2328 double prefix argument (`\\[universal-argument] \
2329 \\[universal-argument] \\[org-open-at-point]').
2330 t Default for files not matched by any of the other options.
2332 Possible values for the command are:
2334 `emacs' The file will be visited by the current Emacs process.
2335 `default' Use the default application for this file type, which is the
2336 association for t in the list, most likely in the system-specific
2337 part. This can be used to overrule an unwanted setting in the
2338 system-specific variable.
2339 `system' Use the system command for opening files, like \"open\".
2340 This command is specified by the entry whose car is `system'.
2341 Most likely, the system-specific version of this variable
2342 does define this command, but you can overrule/replace it
2343 here.
2344 `mailcap' Use command specified in the mailcaps.
2345 string A command to be executed by a shell; %s will be replaced
2346 by the path to the file.
2347 function A Lisp function, which will be called with two arguments:
2348 the file path and the original link string, without the
2349 \"file:\" prefix.
2351 For more examples, see the system specific constants
2352 `org-file-apps-defaults-macosx'
2353 `org-file-apps-defaults-windowsnt'
2354 `org-file-apps-defaults-gnu'."
2355 :group 'org-link-follow
2356 :type '(repeat
2357 (cons (choice :value ""
2358 (string :tag "Extension")
2359 (const :tag "System command to open files" system)
2360 (const :tag "Default for unrecognized files" t)
2361 (const :tag "Remote file" remote)
2362 (const :tag "Links to a directory" directory)
2363 (const :tag "Any files that have Emacs modes"
2364 auto-mode))
2365 (choice :value ""
2366 (const :tag "Visit with Emacs" emacs)
2367 (const :tag "Use default" default)
2368 (const :tag "Use the system command" system)
2369 (string :tag "Command")
2370 (function :tag "Function")))))
2372 (defcustom org-doi-server-url "http://dx.doi.org/"
2373 "The URL of the DOI server."
2374 :type 'string
2375 :version "24.3"
2376 :group 'org-link-follow)
2378 (defgroup org-refile nil
2379 "Options concerning refiling entries in Org mode."
2380 :tag "Org Refile"
2381 :group 'org)
2383 (defcustom org-directory "~/org"
2384 "Directory with Org files.
2385 This is just a default location to look for Org files. There is no need
2386 at all to put your files into this directory. It is used in the
2387 following situations:
2389 1. When a capture template specifies a target file that is not an
2390 absolute path. The path will then be interpreted relative to
2391 `org-directory'
2392 2. When the value of variable `org-agenda-files' is a single file, any
2393 relative paths in this file will be taken as relative to
2394 `org-directory'."
2395 :group 'org-refile
2396 :group 'org-capture
2397 :type 'directory)
2399 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2400 "Default target for storing notes.
2401 Used as a fall back file for org-capture.el, for templates that
2402 do not specify a target file."
2403 :group 'org-refile
2404 :group 'org-capture
2405 :type 'file)
2407 (defcustom org-goto-interface 'outline
2408 "The default interface to be used for `org-goto'.
2409 Allowed values are:
2410 outline The interface shows an outline of the relevant file
2411 and the correct heading is found by moving through
2412 the outline or by searching with incremental search.
2413 outline-path-completion Headlines in the current buffer are offered via
2414 completion. This is the interface also used by
2415 the refile command."
2416 :group 'org-refile
2417 :type '(choice
2418 (const :tag "Outline" outline)
2419 (const :tag "Outline-path-completion" outline-path-completion)))
2421 (defcustom org-goto-max-level 5
2422 "Maximum target level when running `org-goto' with refile interface."
2423 :group 'org-refile
2424 :type 'integer)
2426 (defcustom org-reverse-note-order nil
2427 "Non-nil means store new notes at the beginning of a file or entry.
2428 When nil, new notes will be filed to the end of a file or entry.
2429 This can also be a list with cons cells of regular expressions that
2430 are matched against file names, and values."
2431 :group 'org-capture
2432 :group 'org-refile
2433 :type '(choice
2434 (const :tag "Reverse always" t)
2435 (const :tag "Reverse never" nil)
2436 (repeat :tag "By file name regexp"
2437 (cons regexp boolean))))
2439 (defcustom org-log-refile nil
2440 "Information to record when a task is refiled.
2442 Possible values are:
2444 nil Don't add anything
2445 time Add a time stamp to the task
2446 note Prompt for a note and add it with template `org-log-note-headings'
2448 This option can also be set with on a per-file-basis with
2450 #+STARTUP: nologrefile
2451 #+STARTUP: logrefile
2452 #+STARTUP: lognoterefile
2454 You can have local logging settings for a subtree by setting the LOGGING
2455 property to one or more of these keywords.
2457 When bulk-refiling from the agenda, the value `note' is forbidden and
2458 will temporarily be changed to `time'."
2459 :group 'org-refile
2460 :group 'org-progress
2461 :version "24.1"
2462 :type '(choice
2463 (const :tag "No logging" nil)
2464 (const :tag "Record timestamp" time)
2465 (const :tag "Record timestamp with note." note)))
2467 (defcustom org-refile-targets nil
2468 "Targets for refiling entries with `\\[org-refile]'.
2469 This is a list of cons cells. Each cell contains:
2470 - a specification of the files to be considered, either a list of files,
2471 or a symbol whose function or variable value will be used to retrieve
2472 a file name or a list of file names. If you use `org-agenda-files' for
2473 that, all agenda files will be scanned for targets. Nil means consider
2474 headings in the current buffer.
2475 - A specification of how to find candidate refile targets. This may be
2476 any of:
2477 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2478 This tag has to be present in all target headlines, inheritance will
2479 not be considered.
2480 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2481 todo keyword.
2482 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2483 headlines that are refiling targets.
2484 - a cons cell (:level . N). Any headline of level N is considered a target.
2485 Note that, when `org-odd-levels-only' is set, level corresponds to
2486 order in hierarchy, not to the number of stars.
2487 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2488 Note that, when `org-odd-levels-only' is set, level corresponds to
2489 order in hierarchy, not to the number of stars.
2491 Each element of this list generates a set of possible targets.
2492 The union of these sets is presented (with completion) to
2493 the user by `org-refile'.
2495 You can set the variable `org-refile-target-verify-function' to a function
2496 to verify each headline found by the simple criteria above.
2498 When this variable is nil, all top-level headlines in the current buffer
2499 are used, equivalent to the value `((nil . (:level . 1))'."
2500 :group 'org-refile
2501 :type '(repeat
2502 (cons
2503 (choice :value org-agenda-files
2504 (const :tag "All agenda files" org-agenda-files)
2505 (const :tag "Current buffer" nil)
2506 (function) (variable) (file))
2507 (choice :tag "Identify target headline by"
2508 (cons :tag "Specific tag" (const :value :tag) (string))
2509 (cons :tag "TODO keyword" (const :value :todo) (string))
2510 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2511 (cons :tag "Level number" (const :value :level) (integer))
2512 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2514 (defcustom org-refile-target-verify-function nil
2515 "Function to verify if the headline at point should be a refile target.
2516 The function will be called without arguments, with point at the
2517 beginning of the headline. It should return t and leave point
2518 where it is if the headline is a valid target for refiling.
2520 If the target should not be selected, the function must return nil.
2521 In addition to this, it may move point to a place from where the search
2522 should be continued. For example, the function may decide that the entire
2523 subtree of the current entry should be excluded and move point to the end
2524 of the subtree."
2525 :group 'org-refile
2526 :type '(choice
2527 (const nil)
2528 (function)))
2530 (defcustom org-refile-use-cache nil
2531 "Non-nil means cache refile targets to speed up the process.
2532 \\<org-mode-map>\
2533 The cache for a particular file will be updated automatically when
2534 the buffer has been killed, or when any of the marker used for flagging
2535 refile targets no longer points at a live buffer.
2536 If you have added new entries to a buffer that might themselves be targets,
2537 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2538 if you find that easier, \
2539 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2540 \\[org-refile]'."
2541 :group 'org-refile
2542 :version "24.1"
2543 :type 'boolean)
2545 (defcustom org-refile-use-outline-path nil
2546 "Non-nil means provide refile targets as paths.
2547 So a level 3 headline will be available as level1/level2/level3.
2549 When the value is `file', also include the file name (without directory)
2550 into the path. In this case, you can also stop the completion after
2551 the file name, to get entries inserted as top level in the file.
2553 When `full-file-path', include the full file path."
2554 :group 'org-refile
2555 :type '(choice
2556 (const :tag "Not" nil)
2557 (const :tag "Yes" t)
2558 (const :tag "Start with file name" file)
2559 (const :tag "Start with full file path" full-file-path)))
2561 (defcustom org-outline-path-complete-in-steps t
2562 "Non-nil means complete the outline path in hierarchical steps.
2563 When Org uses the refile interface to select an outline path (see
2564 `org-refile-use-outline-path'), the completion of the path can be
2565 done in a single go, or it can be done in steps down the headline
2566 hierarchy. Going in steps is probably the best if you do not use
2567 a special completion package like `ido' or `icicles'. However,
2568 when using these packages, going in one step can be very fast,
2569 while still showing the whole path to the entry."
2570 :group 'org-refile
2571 :type 'boolean)
2573 (defcustom org-refile-allow-creating-parent-nodes nil
2574 "Non-nil means allow the creation of new nodes as refile targets.
2575 New nodes are then created by adding \"/new node name\" to the completion
2576 of an existing node. When the value of this variable is `confirm',
2577 new node creation must be confirmed by the user (recommended).
2578 When nil, the completion must match an existing entry.
2580 Note that, if the new heading is not seen by the criteria
2581 listed in `org-refile-targets', multiple instances of the same
2582 heading would be created by trying again to file under the new
2583 heading."
2584 :group 'org-refile
2585 :type '(choice
2586 (const :tag "Never" nil)
2587 (const :tag "Always" t)
2588 (const :tag "Prompt for confirmation" confirm)))
2590 (defcustom org-refile-active-region-within-subtree nil
2591 "Non-nil means also refile active region within a subtree.
2593 By default `org-refile' doesn't allow refiling regions if they
2594 don't contain a set of subtrees, but it might be convenient to
2595 do so sometimes: in that case, the first line of the region is
2596 converted to a headline before refiling."
2597 :group 'org-refile
2598 :version "24.1"
2599 :type 'boolean)
2601 (defgroup org-todo nil
2602 "Options concerning TODO items in Org mode."
2603 :tag "Org TODO"
2604 :group 'org)
2606 (defgroup org-progress nil
2607 "Options concerning Progress logging in Org mode."
2608 :tag "Org Progress"
2609 :group 'org-time)
2611 (defvar org-todo-interpretation-widgets
2612 '((:tag "Sequence (cycling hits every state)" sequence)
2613 (:tag "Type (cycling directly to DONE)" type))
2614 "The available interpretation symbols for customizing `org-todo-keywords'.
2615 Interested libraries should add to this list.")
2617 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2618 "List of TODO entry keyword sequences and their interpretation.
2619 \\<org-mode-map>This is a list of sequences.
2621 Each sequence starts with a symbol, either `sequence' or `type',
2622 indicating if the keywords should be interpreted as a sequence of
2623 action steps, or as different types of TODO items. The first
2624 keywords are states requiring action - these states will select a headline
2625 for inclusion into the global TODO list Org produces. If one of the
2626 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2627 signify that no further action is necessary. If \"|\" is not found,
2628 the last keyword is treated as the only DONE state of the sequence.
2630 The command `\\[org-todo]' cycles an entry through these states, and one
2631 additional state where no keyword is present. For details about this
2632 cycling, see the manual.
2634 TODO keywords and interpretation can also be set on a per-file basis with
2635 the special #+SEQ_TODO and #+TYP_TODO lines.
2637 Each keyword can optionally specify a character for fast state selection
2638 \(in combination with the variable `org-use-fast-todo-selection')
2639 and specifiers for state change logging, using the same syntax that
2640 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2641 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2642 indicates to record a time stamp each time this state is selected.
2644 Each keyword may also specify if a timestamp or a note should be
2645 recorded when entering or leaving the state, by adding additional
2646 characters in the parenthesis after the keyword. This looks like this:
2647 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2648 record only the time of the state change. With X and Y being either
2649 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2650 Y when leaving the state if and only if the *target* state does not
2651 define X. You may omit any of the fast-selection key or X or /Y,
2652 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2654 For backward compatibility, this variable may also be just a list
2655 of keywords. In this case the interpretation (sequence or type) will be
2656 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2657 :group 'org-todo
2658 :group 'org-keywords
2659 :type '(choice
2660 (repeat :tag "Old syntax, just keywords"
2661 (string :tag "Keyword"))
2662 (repeat :tag "New syntax"
2663 (cons
2664 (choice
2665 :tag "Interpretation"
2666 ;;Quick and dirty way to see
2667 ;;`org-todo-interpretations'. This takes the
2668 ;;place of item arguments
2669 :convert-widget
2670 (lambda (widget)
2671 (widget-put widget
2672 :args (mapcar
2673 (lambda (x)
2674 (widget-convert
2675 (cons 'const x)))
2676 org-todo-interpretation-widgets))
2677 widget))
2678 (repeat
2679 (string :tag "Keyword"))))))
2681 (defvar-local org-todo-keywords-1 nil
2682 "All TODO and DONE keywords active in a buffer.")
2683 (defvar org-todo-keywords-for-agenda nil)
2684 (defvar org-done-keywords-for-agenda nil)
2685 (defvar org-todo-keyword-alist-for-agenda nil)
2686 (defvar org-tag-alist-for-agenda nil
2687 "Alist of all tags from all agenda files.")
2688 (defvar org-tag-groups-alist-for-agenda nil
2689 "Alist of all groups tags from all current agenda files.")
2690 (defvar-local org-tag-groups-alist nil)
2691 (defvar org-agenda-contributing-files nil)
2692 (defvar-local org-current-tag-alist nil
2693 "Alist of all tag groups in current buffer.
2694 This variable takes into consideration `org-tag-alist',
2695 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2696 (defvar-local org-not-done-keywords nil)
2697 (defvar-local org-done-keywords nil)
2698 (defvar-local org-todo-heads nil)
2699 (defvar-local org-todo-sets nil)
2700 (defvar-local org-todo-log-states nil)
2701 (defvar-local org-todo-kwd-alist nil)
2702 (defvar-local org-todo-key-alist nil)
2703 (defvar-local org-todo-key-trigger nil)
2705 (defcustom org-todo-interpretation 'sequence
2706 "Controls how TODO keywords are interpreted.
2707 This variable is in principle obsolete and is only used for
2708 backward compatibility, if the interpretation of todo keywords is
2709 not given already in `org-todo-keywords'. See that variable for
2710 more information."
2711 :group 'org-todo
2712 :group 'org-keywords
2713 :type '(choice (const sequence)
2714 (const type)))
2716 (defcustom org-use-fast-todo-selection t
2717 "\\<org-mode-map>\
2718 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2719 This variable describes if and under what circumstances the cycling
2720 mechanism for TODO keywords will be replaced by a single-key, direct
2721 selection scheme.
2723 When nil, fast selection is never used.
2725 When the symbol `prefix', it will be used when `org-todo' is called
2726 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2727 in an Org buffer, and
2728 `\\[universal-argument] t' in an agenda buffer.
2730 When t, fast selection is used by default. In this case, the prefix
2731 argument forces cycling instead.
2733 In all cases, the special interface is only used if access keys have
2734 actually been assigned by the user, i.e. if keywords in the configuration
2735 are followed by a letter in parenthesis, like TODO(t)."
2736 :group 'org-todo
2737 :type '(choice
2738 (const :tag "Never" nil)
2739 (const :tag "By default" t)
2740 (const :tag "Only with C-u C-c C-t" prefix)))
2742 (defcustom org-provide-todo-statistics t
2743 "Non-nil means update todo statistics after insert and toggle.
2744 ALL-HEADLINES means update todo statistics by including headlines
2745 with no TODO keyword as well, counting them as not done.
2746 A list of TODO keywords means the same, but skip keywords that are
2747 not in this list.
2748 When set to a list of two lists, the first list contains keywords
2749 to consider as TODO keywords, the second list contains keywords
2750 to consider as DONE keywords.
2752 When this is set, todo statistics is updated in the parent of the
2753 current entry each time a todo state is changed."
2754 :group 'org-todo
2755 :type '(choice
2756 (const :tag "Yes, only for TODO entries" t)
2757 (const :tag "Yes, including all entries" all-headlines)
2758 (repeat :tag "Yes, for TODOs in this list"
2759 (string :tag "TODO keyword"))
2760 (list :tag "Yes, for TODOs and DONEs in these lists"
2761 (repeat (string :tag "TODO keyword"))
2762 (repeat (string :tag "DONE keyword")))
2763 (other :tag "No TODO statistics" nil)))
2765 (defcustom org-hierarchical-todo-statistics t
2766 "Non-nil means TODO statistics covers just direct children.
2767 When nil, all entries in the subtree are considered.
2768 This has only an effect if `org-provide-todo-statistics' is set.
2769 To set this to nil for only a single subtree, use a COOKIE_DATA
2770 property and include the word \"recursive\" into the value."
2771 :group 'org-todo
2772 :type 'boolean)
2774 (defcustom org-after-todo-state-change-hook nil
2775 "Hook which is run after the state of a TODO item was changed.
2776 The new state (a string with a TODO keyword, or nil) is available in the
2777 Lisp variable `org-state'."
2778 :group 'org-todo
2779 :type 'hook)
2781 (defvar org-blocker-hook nil
2782 "Hook for functions that are allowed to block a state change.
2784 Functions in this hook should not modify the buffer.
2785 Each function gets as its single argument a property list,
2786 see `org-trigger-hook' for more information about this list.
2788 If any of the functions in this hook returns nil, the state change
2789 is blocked.")
2791 (defvar org-trigger-hook nil
2792 "Hook for functions that are triggered by a state change.
2794 Each function gets as its single argument a property list with at
2795 least the following elements:
2797 (:type type-of-change :position pos-at-entry-start
2798 :from old-state :to new-state)
2800 Depending on the type, more properties may be present.
2802 This mechanism is currently implemented for:
2804 TODO state changes
2805 ------------------
2806 :type todo-state-change
2807 :from previous state (keyword as a string), or nil, or a symbol
2808 `todo' or `done', to indicate the general type of state.
2809 :to new state, like in :from")
2811 (defcustom org-enforce-todo-dependencies nil
2812 "Non-nil means undone TODO entries will block switching the parent to DONE.
2813 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2814 be blocked if any prior sibling is not yet done.
2815 Finally, if the parent is blocked because of ordered siblings of its own,
2816 the child will also be blocked."
2817 :set (lambda (var val)
2818 (set var val)
2819 (if val
2820 (add-hook 'org-blocker-hook
2821 'org-block-todo-from-children-or-siblings-or-parent)
2822 (remove-hook 'org-blocker-hook
2823 'org-block-todo-from-children-or-siblings-or-parent)))
2824 :group 'org-todo
2825 :type 'boolean)
2827 (defcustom org-enforce-todo-checkbox-dependencies nil
2828 "Non-nil means unchecked boxes will block switching the parent to DONE.
2829 When this is nil, checkboxes have no influence on switching TODO states.
2830 When non-nil, you first need to check off all check boxes before the TODO
2831 entry can be switched to DONE.
2832 This variable needs to be set before org.el is loaded, and you need to
2833 restart Emacs after a change to make the change effective. The only way
2834 to change is while Emacs is running is through the customize interface."
2835 :set (lambda (var val)
2836 (set var val)
2837 (if val
2838 (add-hook 'org-blocker-hook
2839 'org-block-todo-from-checkboxes)
2840 (remove-hook 'org-blocker-hook
2841 'org-block-todo-from-checkboxes)))
2842 :group 'org-todo
2843 :type 'boolean)
2845 (defcustom org-treat-insert-todo-heading-as-state-change nil
2846 "Non-nil means inserting a TODO heading is treated as state change.
2847 So when the command `\\[org-insert-todo-heading]' is used, state change
2848 logging will apply if appropriate. When nil, the new TODO item will
2849 be inserted directly, and no logging will take place."
2850 :group 'org-todo
2851 :type 'boolean)
2853 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2854 "Non-nil means switching TODO states with S-cursor counts as state change.
2855 This is the default behavior. However, setting this to nil allows a
2856 convenient way to select a TODO state and bypass any logging associated
2857 with that."
2858 :group 'org-todo
2859 :type 'boolean)
2861 (defcustom org-todo-state-tags-triggers nil
2862 "Tag changes that should be triggered by TODO state changes.
2863 This is a list. Each entry is
2865 (state-change (tag . flag) .......)
2867 State-change can be a string with a state, and empty string to indicate the
2868 state that has no TODO keyword, or it can be one of the symbols `todo'
2869 or `done', meaning any not-done or done state, respectively."
2870 :group 'org-todo
2871 :group 'org-tags
2872 :type '(repeat
2873 (cons (choice :tag "When changing to"
2874 (const :tag "Not-done state" todo)
2875 (const :tag "Done state" done)
2876 (string :tag "State"))
2877 (repeat
2878 (cons :tag "Tag action"
2879 (string :tag "Tag")
2880 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2882 (defcustom org-log-done nil
2883 "Information to record when a task moves to the DONE state.
2885 Possible values are:
2887 nil Don't add anything, just change the keyword
2888 time Add a time stamp to the task
2889 note Prompt for a note and add it with template `org-log-note-headings'
2891 This option can also be set with on a per-file-basis with
2893 #+STARTUP: nologdone
2894 #+STARTUP: logdone
2895 #+STARTUP: lognotedone
2897 You can have local logging settings for a subtree by setting the LOGGING
2898 property to one or more of these keywords."
2899 :group 'org-todo
2900 :group 'org-progress
2901 :type '(choice
2902 (const :tag "No logging" nil)
2903 (const :tag "Record CLOSED timestamp" time)
2904 (const :tag "Record CLOSED timestamp with note." note)))
2906 ;; Normalize old uses of org-log-done.
2907 (cond
2908 ((eq org-log-done t) (setq org-log-done 'time))
2909 ((and (listp org-log-done) (memq 'done org-log-done))
2910 (setq org-log-done 'note)))
2912 (defcustom org-log-reschedule nil
2913 "Information to record when the scheduling date of a tasks is modified.
2915 Possible values are:
2917 nil Don't add anything, just change the date
2918 time Add a time stamp to the task
2919 note Prompt for a note and add it with template `org-log-note-headings'
2921 This option can also be set with on a per-file-basis with
2923 #+STARTUP: nologreschedule
2924 #+STARTUP: logreschedule
2925 #+STARTUP: lognotereschedule"
2926 :group 'org-todo
2927 :group 'org-progress
2928 :type '(choice
2929 (const :tag "No logging" nil)
2930 (const :tag "Record timestamp" time)
2931 (const :tag "Record timestamp with note." note)))
2933 (defcustom org-log-redeadline nil
2934 "Information to record when the deadline date of a tasks is modified.
2936 Possible values are:
2938 nil Don't add anything, just change the date
2939 time Add a time stamp to the task
2940 note Prompt for a note and add it with template `org-log-note-headings'
2942 This option can also be set with on a per-file-basis with
2944 #+STARTUP: nologredeadline
2945 #+STARTUP: logredeadline
2946 #+STARTUP: lognoteredeadline
2948 You can have local logging settings for a subtree by setting the LOGGING
2949 property to one or more of these keywords."
2950 :group 'org-todo
2951 :group 'org-progress
2952 :type '(choice
2953 (const :tag "No logging" nil)
2954 (const :tag "Record timestamp" time)
2955 (const :tag "Record timestamp with note." note)))
2957 (defcustom org-log-note-clock-out nil
2958 "Non-nil means record a note when clocking out of an item.
2959 This can also be configured on a per-file basis by adding one of
2960 the following lines anywhere in the buffer:
2962 #+STARTUP: lognoteclock-out
2963 #+STARTUP: nolognoteclock-out"
2964 :group 'org-todo
2965 :group 'org-progress
2966 :type 'boolean)
2968 (defcustom org-log-done-with-time t
2969 "Non-nil means the CLOSED time stamp will contain date and time.
2970 When nil, only the date will be recorded."
2971 :group 'org-progress
2972 :type 'boolean)
2974 (defcustom org-log-note-headings
2975 '((done . "CLOSING NOTE %t")
2976 (state . "State %-12s from %-12S %t")
2977 (note . "Note taken on %t")
2978 (reschedule . "Rescheduled from %S on %t")
2979 (delschedule . "Not scheduled, was %S on %t")
2980 (redeadline . "New deadline from %S on %t")
2981 (deldeadline . "Removed deadline, was %S on %t")
2982 (refile . "Refiled on %t")
2983 (clock-out . ""))
2984 "Headings for notes added to entries.
2986 The value is an alist, with the car being a symbol indicating the
2987 note context, and the cdr is the heading to be used. The heading
2988 may also be the empty string. The following placeholders can be
2989 used:
2991 %t a time stamp.
2992 %T an active time stamp instead the default inactive one
2993 %d a short-format time stamp.
2994 %D an active short-format time stamp.
2995 %s the new TODO state or time stamp (inactive), in double quotes.
2996 %S the old TODO state or time stamp (inactive), in double quotes.
2997 %u the user name.
2998 %U full user name.
3000 In fact, it is not a good idea to change the `state' entry,
3001 because Agenda Log mode depends on the format of these entries."
3002 :group 'org-todo
3003 :group 'org-progress
3004 :type '(list :greedy t
3005 (cons (const :tag "Heading when closing an item" done) string)
3006 (cons (const :tag
3007 "Heading when changing todo state (todo sequence only)"
3008 state) string)
3009 (cons (const :tag "Heading when just taking a note" note) string)
3010 (cons (const :tag "Heading when rescheduling" reschedule) string)
3011 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3012 (cons (const :tag "Heading when changing deadline" redeadline) string)
3013 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3014 (cons (const :tag "Heading when refiling" refile) string)
3015 (cons (const :tag "Heading when clocking out" clock-out) string)))
3017 (unless (assq 'note org-log-note-headings)
3018 (push '(note . "%t") org-log-note-headings))
3020 (defcustom org-log-into-drawer nil
3021 "Non-nil means insert state change notes and time stamps into a drawer.
3022 When nil, state changes notes will be inserted after the headline and
3023 any scheduling and clock lines, but not inside a drawer.
3025 The value of this variable should be the name of the drawer to use.
3026 LOGBOOK is proposed as the default drawer for this purpose, you can
3027 also set this to a string to define the drawer of your choice.
3029 A value of t is also allowed, representing \"LOGBOOK\".
3031 A value of t or nil can also be set with on a per-file-basis with
3033 #+STARTUP: logdrawer
3034 #+STARTUP: nologdrawer
3036 If this variable is set, `org-log-state-notes-insert-after-drawers'
3037 will be ignored.
3039 You can set the property LOG_INTO_DRAWER to overrule this setting for
3040 a subtree.
3042 Do not check directly this variable in a Lisp program. Call
3043 function `org-log-into-drawer' instead."
3044 :group 'org-todo
3045 :group 'org-progress
3046 :type '(choice
3047 (const :tag "Not into a drawer" nil)
3048 (const :tag "LOGBOOK" t)
3049 (string :tag "Other")))
3051 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3053 (defun org-log-into-drawer ()
3054 "Name of the log drawer, as a string, or nil.
3055 This is the value of `org-log-into-drawer'. However, if the
3056 current entry has or inherits a LOG_INTO_DRAWER property, it will
3057 be used instead of the default value."
3058 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3059 (cond ((equal p "nil") nil)
3060 ((equal p "t") "LOGBOOK")
3061 ((stringp p) p)
3062 (p "LOGBOOK")
3063 ((stringp org-log-into-drawer) org-log-into-drawer)
3064 (org-log-into-drawer "LOGBOOK"))))
3066 (defcustom org-log-state-notes-insert-after-drawers nil
3067 "Non-nil means insert state change notes after any drawers in entry.
3068 Only the drawers that *immediately* follow the headline and the
3069 deadline/scheduled line are skipped.
3070 When nil, insert notes right after the heading and perhaps the line
3071 with deadline/scheduling if present.
3073 This variable will have no effect if `org-log-into-drawer' is
3074 set."
3075 :group 'org-todo
3076 :group 'org-progress
3077 :type 'boolean)
3079 (defcustom org-log-states-order-reversed t
3080 "Non-nil means the latest state note will be directly after heading.
3081 When nil, the state change notes will be ordered according to time.
3083 This option can also be set with on a per-file-basis with
3085 #+STARTUP: logstatesreversed
3086 #+STARTUP: nologstatesreversed"
3087 :group 'org-todo
3088 :group 'org-progress
3089 :type 'boolean)
3091 (defcustom org-todo-repeat-to-state nil
3092 "The TODO state to which a repeater should return the repeating task.
3093 By default this is the first task in a TODO sequence, or the previous state
3094 in a TODO_TYP set. But you can specify another task here.
3095 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3096 :group 'org-todo
3097 :version "24.1"
3098 :type '(choice (const :tag "Head of sequence" nil)
3099 (string :tag "Specific state")))
3101 (defcustom org-log-repeat 'time
3102 "Non-nil means record moving through the DONE state when triggering repeat.
3103 An auto-repeating task is immediately switched back to TODO when
3104 marked DONE. If you are not logging state changes (by adding \"@\"
3105 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3106 record a closing note, there will be no record of the task moving
3107 through DONE. This variable forces taking a note anyway.
3109 nil Don't force a record
3110 time Record a time stamp
3111 note Prompt for a note and add it with template `org-log-note-headings'
3113 This option can also be set with on a per-file-basis with
3115 #+STARTUP: nologrepeat
3116 #+STARTUP: logrepeat
3117 #+STARTUP: lognoterepeat
3119 You can have local logging settings for a subtree by setting the LOGGING
3120 property to one or more of these keywords."
3121 :group 'org-todo
3122 :group 'org-progress
3123 :type '(choice
3124 (const :tag "Don't force a record" nil)
3125 (const :tag "Force recording the DONE state" time)
3126 (const :tag "Force recording a note with the DONE state" note)))
3129 (defgroup org-priorities nil
3130 "Priorities in Org mode."
3131 :tag "Org Priorities"
3132 :group 'org-todo)
3134 (defcustom org-enable-priority-commands t
3135 "Non-nil means priority commands are active.
3136 When nil, these commands will be disabled, so that you never accidentally
3137 set a priority."
3138 :group 'org-priorities
3139 :type 'boolean)
3141 (defcustom org-highest-priority ?A
3142 "The highest priority of TODO items. A character like ?A, ?B etc.
3143 Must have a smaller ASCII number than `org-lowest-priority'."
3144 :group 'org-priorities
3145 :type 'character)
3147 (defcustom org-lowest-priority ?C
3148 "The lowest priority of TODO items. A character like ?A, ?B etc.
3149 Must have a larger ASCII number than `org-highest-priority'."
3150 :group 'org-priorities
3151 :type 'character)
3153 (defcustom org-default-priority ?B
3154 "The default priority of TODO items.
3155 This is the priority an item gets if no explicit priority is given.
3156 When starting to cycle on an empty priority the first step in the cycle
3157 depends on `org-priority-start-cycle-with-default'. The resulting first
3158 step priority must not exceed the range from `org-highest-priority' to
3159 `org-lowest-priority' which means that `org-default-priority' has to be
3160 in this range exclusive or inclusive the range boundaries. Else the
3161 first step refuses to set the default and the second will fall back
3162 to (depending on the command used) the highest or lowest priority."
3163 :group 'org-priorities
3164 :type 'character)
3166 (defcustom org-priority-start-cycle-with-default t
3167 "Non-nil means start with default priority when starting to cycle.
3168 When this is nil, the first step in the cycle will be (depending on the
3169 command used) one higher or lower than the default priority.
3170 See also `org-default-priority'."
3171 :group 'org-priorities
3172 :type 'boolean)
3174 (defcustom org-get-priority-function nil
3175 "Function to extract the priority from a string.
3176 The string is normally the headline. If this is nil Org computes the
3177 priority from the priority cookie like [#A] in the headline. It returns
3178 an integer, increasing by 1000 for each priority level.
3179 The user can set a different function here, which should take a string
3180 as an argument and return the numeric priority."
3181 :group 'org-priorities
3182 :version "24.1"
3183 :type '(choice
3184 (const nil)
3185 (function)))
3187 (defgroup org-time nil
3188 "Options concerning time stamps and deadlines in Org mode."
3189 :tag "Org Time"
3190 :group 'org)
3192 (defcustom org-time-stamp-rounding-minutes '(0 5)
3193 "Number of minutes to round time stamps to.
3194 \\<org-mode-map>\
3195 These are two values, the first applies when first creating a time stamp.
3196 The second applies when changing it with the commands `S-up' and `S-down'.
3197 When changing the time stamp, this means that it will change in steps
3198 of N minutes, as given by the second value.
3200 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3201 numbers should be factors of 60, so for example 5, 10, 15.
3203 When this is larger than 1, you can still force an exact time stamp by using
3204 a double prefix argument to a time stamp command like \
3205 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3206 and by using a prefix arg to `S-up/down' to specify the exact number
3207 of minutes to shift."
3208 :group 'org-time
3209 :get (lambda (var) ; Make sure both elements are there
3210 (if (integerp (default-value var))
3211 (list (default-value var) 5)
3212 (default-value var)))
3213 :type '(list
3214 (integer :tag "when inserting times")
3215 (integer :tag "when modifying times")))
3217 ;; Normalize old customizations of this variable.
3218 (when (integerp org-time-stamp-rounding-minutes)
3219 (setq org-time-stamp-rounding-minutes
3220 (list org-time-stamp-rounding-minutes
3221 org-time-stamp-rounding-minutes)))
3223 (defcustom org-display-custom-times nil
3224 "Non-nil means overlay custom formats over all time stamps.
3225 The formats are defined through the variable `org-time-stamp-custom-formats'.
3226 To turn this on on a per-file basis, insert anywhere in the file:
3227 #+STARTUP: customtime"
3228 :group 'org-time
3229 :set 'set-default
3230 :type 'sexp)
3231 (make-variable-buffer-local 'org-display-custom-times)
3233 (defcustom org-time-stamp-custom-formats
3234 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3235 "Custom formats for time stamps. See `format-time-string' for the syntax.
3236 These are overlaid over the default ISO format if the variable
3237 `org-display-custom-times' is set. Time like %H:%M should be at the
3238 end of the second format. The custom formats are also honored by export
3239 commands, if custom time display is turned on at the time of export."
3240 :group 'org-time
3241 :type 'sexp)
3243 (defun org-time-stamp-format (&optional long inactive)
3244 "Get the right format for a time string."
3245 (let ((f (if long (cdr org-time-stamp-formats)
3246 (car org-time-stamp-formats))))
3247 (if inactive
3248 (concat "[" (substring f 1 -1) "]")
3249 f)))
3251 (defcustom org-time-clocksum-format
3252 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3253 "The format string used when creating CLOCKSUM lines.
3254 This is also used when Org mode generates a time duration.
3256 The value can be a single format string containing two
3257 %-sequences, which will be filled with the number of hours and
3258 minutes in that order.
3260 Alternatively, the value can be a plist associating any of the
3261 keys :years, :months, :weeks, :days, :hours or :minutes with
3262 format strings. The time duration is formatted using only the
3263 time components that are needed and concatenating the results.
3264 If a time unit in absent, it falls back to the next smallest
3265 unit.
3267 The keys :require-years, :require-months, :require-days,
3268 :require-weeks, :require-hours, :require-minutes are also
3269 meaningful. A non-nil value for these keys indicates that the
3270 corresponding time component should always be included, even if
3271 its value is 0.
3274 For example,
3276 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3277 :require-minutes t)
3279 means durations longer than a day will be expressed in days,
3280 hours and minutes, and durations less than a day will always be
3281 expressed in hours and minutes (even for durations less than an
3282 hour).
3284 The value
3286 (:days \"%dd\" :minutes \"%dm\")
3288 means durations longer than a day will be expressed in days and
3289 minutes, and durations less than a day will be expressed entirely
3290 in minutes (even for durations longer than an hour)."
3291 :group 'org-time
3292 :group 'org-clock
3293 :version "24.4"
3294 :package-version '(Org . "8.0")
3295 :type '(choice (string :tag "Format string")
3296 (set :tag "Plist"
3297 (group :inline t (const :tag "Years" :years)
3298 (string :tag "Format string"))
3299 (group :inline t
3300 (const :tag "Always show years" :require-years)
3301 (const t))
3302 (group :inline t (const :tag "Months" :months)
3303 (string :tag "Format string"))
3304 (group :inline t
3305 (const :tag "Always show months" :require-months)
3306 (const t))
3307 (group :inline t (const :tag "Weeks" :weeks)
3308 (string :tag "Format string"))
3309 (group :inline t
3310 (const :tag "Always show weeks" :require-weeks)
3311 (const t))
3312 (group :inline t (const :tag "Days" :days)
3313 (string :tag "Format string"))
3314 (group :inline t
3315 (const :tag "Always show days" :require-days)
3316 (const t))
3317 (group :inline t (const :tag "Hours" :hours)
3318 (string :tag "Format string"))
3319 (group :inline t
3320 (const :tag "Always show hours" :require-hours)
3321 (const t))
3322 (group :inline t (const :tag "Minutes" :minutes)
3323 (string :tag "Format string"))
3324 (group :inline t
3325 (const :tag "Always show minutes" :require-minutes)
3326 (const t)))))
3328 (defcustom org-time-clocksum-use-fractional nil
3329 "When non-nil, `\\[org-clock-display]' uses fractional times.
3330 See `org-time-clocksum-format' for more on time clock formats."
3331 :group 'org-time
3332 :group 'org-clock
3333 :version "24.3"
3334 :type 'boolean)
3336 (defcustom org-time-clocksum-use-effort-durations nil
3337 "When non-nil, `\\[org-clock-display]' uses effort durations.
3338 E.g. by default, one day is considered to be a 8 hours effort,
3339 so a task that has been clocked for 16 hours will be displayed
3340 as during 2 days in the clock display or in the clocktable.
3342 See `org-effort-durations' on how to set effort durations
3343 and `org-time-clocksum-format' for more on time clock formats."
3344 :group 'org-time
3345 :group 'org-clock
3346 :version "24.4"
3347 :package-version '(Org . "8.0")
3348 :type 'boolean)
3350 (defcustom org-time-clocksum-fractional-format "%.2f"
3351 "The format string used when creating CLOCKSUM lines,
3352 or when Org mode generates a time duration, if
3353 `org-time-clocksum-use-fractional' is enabled.
3355 The value can be a single format string containing one
3356 %-sequence, which will be filled with the number of hours as
3357 a float.
3359 Alternatively, the value can be a plist associating any of the
3360 keys :years, :months, :weeks, :days, :hours or :minutes with
3361 a format string. The time duration is formatted using the
3362 largest time unit which gives a non-zero integer part. If all
3363 specified formats have zero integer part, the smallest time unit
3364 is used."
3365 :group 'org-time
3366 :type '(choice (string :tag "Format string")
3367 (set (group :inline t (const :tag "Years" :years)
3368 (string :tag "Format string"))
3369 (group :inline t (const :tag "Months" :months)
3370 (string :tag "Format string"))
3371 (group :inline t (const :tag "Weeks" :weeks)
3372 (string :tag "Format string"))
3373 (group :inline t (const :tag "Days" :days)
3374 (string :tag "Format string"))
3375 (group :inline t (const :tag "Hours" :hours)
3376 (string :tag "Format string"))
3377 (group :inline t (const :tag "Minutes" :minutes)
3378 (string :tag "Format string")))))
3380 (defcustom org-deadline-warning-days 14
3381 "Number of days before expiration during which a deadline becomes active.
3382 This variable governs the display in sparse trees and in the agenda.
3383 When 0 or negative, it means use this number (the absolute value of it)
3384 even if a deadline has a different individual lead time specified.
3386 Custom commands can set this variable in the options section."
3387 :group 'org-time
3388 :group 'org-agenda-daily/weekly
3389 :type 'integer)
3391 (defcustom org-scheduled-delay-days 0
3392 "Number of days before a scheduled item becomes active.
3393 This variable governs the display in sparse trees and in the agenda.
3394 The default value (i.e. 0) means: don't delay scheduled item.
3395 When negative, it means use this number (the absolute value of it)
3396 even if a scheduled item has a different individual delay time
3397 specified.
3399 Custom commands can set this variable in the options section."
3400 :group 'org-time
3401 :group 'org-agenda-daily/weekly
3402 :version "24.4"
3403 :package-version '(Org . "8.0")
3404 :type 'integer)
3406 (defcustom org-read-date-prefer-future t
3407 "Non-nil means assume future for incomplete date input from user.
3408 This affects the following situations:
3409 1. The user gives a month but not a year.
3410 For example, if it is April and you enter \"feb 2\", this will be read
3411 as Feb 2, *next* year. \"May 5\", however, will be this year.
3412 2. The user gives a day, but no month.
3413 For example, if today is the 15th, and you enter \"3\", Org will read
3414 this as the third of *next* month. However, if you enter \"17\",
3415 it will be considered as *this* month.
3417 If you set this variable to the symbol `time', then also the following
3418 will work:
3420 3. If the user gives a time.
3421 If the time is before now, it will be interpreted as tomorrow.
3423 Currently none of this works for ISO week specifications.
3425 When this option is nil, the current day, month and year will always be
3426 used as defaults.
3428 See also `org-agenda-jump-prefer-future'."
3429 :group 'org-time
3430 :type '(choice
3431 (const :tag "Never" nil)
3432 (const :tag "Check month and day" t)
3433 (const :tag "Check month, day, and time" time)))
3435 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3436 "Should the agenda jump command prefer the future for incomplete dates?
3437 The default is to do the same as configured in `org-read-date-prefer-future'.
3438 But you can also set a deviating value here.
3439 This may t or nil, or the symbol `org-read-date-prefer-future'."
3440 :group 'org-agenda
3441 :group 'org-time
3442 :version "24.1"
3443 :type '(choice
3444 (const :tag "Use org-read-date-prefer-future"
3445 org-read-date-prefer-future)
3446 (const :tag "Never" nil)
3447 (const :tag "Always" t)))
3449 (defcustom org-read-date-force-compatible-dates t
3450 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3452 Depending on the system Emacs is running on, certain dates cannot
3453 be represented with the type used internally to represent time.
3454 Dates between 1970-1-1 and 2038-1-1 can always be represented
3455 correctly. Some systems allow for earlier dates, some for later,
3456 some for both. One way to find out it to insert any date into an
3457 Org buffer, putting the cursor on the year and hitting S-up and
3458 S-down to test the range.
3460 When this variable is set to t, the date/time prompt will not let
3461 you specify dates outside the 1970-2037 range, so it is certain that
3462 these dates will work in whatever version of Emacs you are
3463 running, and also that you can move a file from one Emacs implementation
3464 to another. WHenever Org is forcing the year for you, it will display
3465 a message and beep.
3467 When this variable is nil, Org will check if the date is
3468 representable in the specific Emacs implementation you are using.
3469 If not, it will force a year, usually the current year, and beep
3470 to remind you. Currently this setting is not recommended because
3471 the likelihood that you will open your Org files in an Emacs that
3472 has limited date range is not negligible.
3474 A workaround for this problem is to use diary sexp dates for time
3475 stamps outside of this range."
3476 :group 'org-time
3477 :version "24.1"
3478 :type 'boolean)
3480 (defcustom org-read-date-display-live t
3481 "Non-nil means display current interpretation of date prompt live.
3482 This display will be in an overlay, in the minibuffer."
3483 :group 'org-time
3484 :type 'boolean)
3486 (defcustom org-read-date-popup-calendar t
3487 "Non-nil means pop up a calendar when prompting for a date.
3488 In the calendar, the date can be selected with mouse-1. However, the
3489 minibuffer will also be active, and you can simply enter the date as well.
3490 When nil, only the minibuffer will be available."
3491 :group 'org-time
3492 :type 'boolean)
3493 (defvaralias 'org-popup-calendar-for-date-prompt
3494 'org-read-date-popup-calendar)
3496 (defcustom org-extend-today-until 0
3497 "The hour when your day really ends. Must be an integer.
3498 This has influence for the following applications:
3499 - When switching the agenda to \"today\". It it is still earlier than
3500 the time given here, the day recognized as TODAY is actually yesterday.
3501 - When a date is read from the user and it is still before the time given
3502 here, the current date and time will be assumed to be yesterday, 23:59.
3503 Also, timestamps inserted in capture templates follow this rule.
3505 IMPORTANT: This is a feature whose implementation is and likely will
3506 remain incomplete. Really, it is only here because past midnight seems to
3507 be the favorite working time of John Wiegley :-)"
3508 :group 'org-time
3509 :type 'integer)
3511 (defcustom org-use-effective-time nil
3512 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3513 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3514 \"effective time\" of any timestamps between midnight and 8am will be
3515 23:59 of the previous day."
3516 :group 'org-time
3517 :version "24.1"
3518 :type 'boolean)
3520 (defcustom org-use-last-clock-out-time-as-effective-time nil
3521 "When non-nil, use the last clock out time for `org-todo'.
3522 Note that this option has precedence over the combined use of
3523 `org-use-effective-time' and `org-extend-today-until'."
3524 :group 'org-time
3525 :version "24.4"
3526 :package-version '(Org . "8.0")
3527 :type 'boolean)
3529 (defcustom org-edit-timestamp-down-means-later nil
3530 "Non-nil means S-down will increase the time in a time stamp.
3531 When nil, S-up will increase."
3532 :group 'org-time
3533 :type 'boolean)
3535 (defcustom org-calendar-follow-timestamp-change t
3536 "Non-nil means make the calendar window follow timestamp changes.
3537 When a timestamp is modified and the calendar window is visible, it will be
3538 moved to the new date."
3539 :group 'org-time
3540 :type 'boolean)
3542 (defgroup org-tags nil
3543 "Options concerning tags in Org mode."
3544 :tag "Org Tags"
3545 :group 'org)
3547 (defcustom org-tag-alist nil
3548 "Default tags available in Org files.
3550 The value of this variable is an alist. Associations either:
3552 (TAG)
3553 (TAG . SELECT)
3554 (SPECIAL)
3556 where TAG is a tag as a string, SELECT is character, used to
3557 select that tag through the fast tag selection interface, and
3558 SPECIAL is one of the following keywords: `:startgroup',
3559 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3560 `:newline'. These keywords are used to define a hierarchy of
3561 tags. See manual for details.
3563 When this variable is nil, Org mode bases tag input on what is
3564 already in the buffer. The value can be overridden locally by
3565 using a TAGS keyword, e.g.,
3567 #+TAGS: tag1 tag2
3569 See also `org-tag-persistent-alist' to sidestep this behavior."
3570 :group 'org-tags
3571 :type '(repeat
3572 (choice
3573 (cons (string :tag "Tag name")
3574 (character :tag "Access char"))
3575 (const :tag "Start radio group" (:startgroup))
3576 (const :tag "Start tag group, non distinct" (:startgrouptag))
3577 (const :tag "Group tags delimiter" (:grouptags))
3578 (const :tag "End radio group" (:endgroup))
3579 (const :tag "End tag group, non distinct" (:endgrouptag))
3580 (const :tag "New line" (:newline)))))
3582 (defcustom org-tag-persistent-alist nil
3583 "Tags always available in Org files.
3585 The value of this variable is an alist. Associations either:
3587 (TAG)
3588 (TAG . SELECT)
3589 (SPECIAL)
3591 where TAG is a tag as a string, SELECT is a character, used to
3592 select that tag through the fast tag selection interface, and
3593 SPECIAL is one of the following keywords: `:startgroup',
3594 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3595 `:newline'. These keywords are used to define a hierarchy of
3596 tags. See manual for details.
3598 Unlike to `org-tag-alist', tags defined in this variable do not
3599 depend on a local TAGS keyword. Instead, to disable these tags
3600 on a per-file basis, insert anywhere in the file:
3602 #+STARTUP: noptag"
3603 :group 'org-tags
3604 :type '(repeat
3605 (choice
3606 (cons (string :tag "Tag name")
3607 (character :tag "Access char"))
3608 (const :tag "Start radio group" (:startgroup))
3609 (const :tag "Start tag group, non distinct" (:startgrouptag))
3610 (const :tag "Group tags delimiter" (:grouptags))
3611 (const :tag "End radio group" (:endgroup))
3612 (const :tag "End tag group, non distinct" (:endgrouptag))
3613 (const :tag "New line" (:newline)))))
3615 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3616 "If non-nil, always offer completion for all tags of all agenda files.
3617 Instead of customizing this variable directly, you might want to
3618 set it locally for capture buffers, because there no list of
3619 tags in that file can be created dynamically (there are none).
3621 (add-hook \\='org-capture-mode-hook
3622 (lambda ()
3623 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3624 :group 'org-tags
3625 :version "24.1"
3626 :type 'boolean)
3628 (defvar org-file-tags nil
3629 "List of tags that can be inherited by all entries in the file.
3630 The tags will be inherited if the variable `org-use-tag-inheritance'
3631 says they should be.
3632 This variable is populated from #+FILETAGS lines.")
3634 (defcustom org-use-fast-tag-selection 'auto
3635 "Non-nil means use fast tag selection scheme.
3636 This is a special interface to select and deselect tags with single keys.
3637 When nil, fast selection is never used.
3638 When the symbol `auto', fast selection is used if and only if selection
3639 characters for tags have been configured, either through the variable
3640 `org-tag-alist' or through a #+TAGS line in the buffer.
3641 When t, fast selection is always used and selection keys are assigned
3642 automatically if necessary."
3643 :group 'org-tags
3644 :type '(choice
3645 (const :tag "Always" t)
3646 (const :tag "Never" nil)
3647 (const :tag "When selection characters are configured" auto)))
3649 (defcustom org-fast-tag-selection-single-key nil
3650 "Non-nil means fast tag selection exits after first change.
3651 When nil, you have to press RET to exit it.
3652 During fast tag selection, you can toggle this flag with `C-c'.
3653 This variable can also have the value `expert'. In this case, the window
3654 displaying the tags menu is not even shown, until you press C-c again."
3655 :group 'org-tags
3656 :type '(choice
3657 (const :tag "No" nil)
3658 (const :tag "Yes" t)
3659 (const :tag "Expert" expert)))
3661 (defvar org-fast-tag-selection-include-todo nil
3662 "Non-nil means fast tags selection interface will also offer TODO states.
3663 This is an undocumented feature, you should not rely on it.")
3665 (defcustom org-tags-column -77
3666 "The column to which tags should be indented in a headline.
3667 If this number is positive, it specifies the column. If it is negative,
3668 it means that the tags should be flushright to that column. For example,
3669 -80 works well for a normal 80 character screen.
3670 When 0, place tags directly after headline text, with only one space in
3671 between."
3672 :group 'org-tags
3673 :type 'integer)
3675 (defcustom org-auto-align-tags t
3676 "Non-nil keeps tags aligned when modifying headlines.
3677 Some operations (i.e. demoting) change the length of a headline and
3678 therefore shift the tags around. With this option turned on, after
3679 each such operation the tags are again aligned to `org-tags-column'."
3680 :group 'org-tags
3681 :type 'boolean)
3683 (defcustom org-use-tag-inheritance t
3684 "Non-nil means tags in levels apply also for sublevels.
3685 When nil, only the tags directly given in a specific line apply there.
3686 This may also be a list of tags that should be inherited, or a regexp that
3687 matches tags that should be inherited. Additional control is possible
3688 with the variable `org-tags-exclude-from-inheritance' which gives an
3689 explicit list of tags to be excluded from inheritance, even if the value of
3690 `org-use-tag-inheritance' would select it for inheritance.
3692 If this option is t, a match early-on in a tree can lead to a large
3693 number of matches in the subtree when constructing the agenda or creating
3694 a sparse tree. If you only want to see the first match in a tree during
3695 a search, check out the variable `org-tags-match-list-sublevels'."
3696 :group 'org-tags
3697 :type '(choice
3698 (const :tag "Not" nil)
3699 (const :tag "Always" t)
3700 (repeat :tag "Specific tags" (string :tag "Tag"))
3701 (regexp :tag "Tags matched by regexp")))
3703 (defcustom org-tags-exclude-from-inheritance nil
3704 "List of tags that should never be inherited.
3705 This is a way to exclude a few tags from inheritance. For way to do
3706 the opposite, to actively allow inheritance for selected tags,
3707 see the variable `org-use-tag-inheritance'."
3708 :group 'org-tags
3709 :type '(repeat (string :tag "Tag")))
3711 (defun org-tag-inherit-p (tag)
3712 "Check if TAG is one that should be inherited."
3713 (cond
3714 ((member tag org-tags-exclude-from-inheritance) nil)
3715 ((eq org-use-tag-inheritance t) t)
3716 ((not org-use-tag-inheritance) nil)
3717 ((stringp org-use-tag-inheritance)
3718 (string-match org-use-tag-inheritance tag))
3719 ((listp org-use-tag-inheritance)
3720 (member tag org-use-tag-inheritance))
3721 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3723 (defcustom org-tags-match-list-sublevels t
3724 "Non-nil means list also sublevels of headlines matching a search.
3725 This variable applies to tags/property searches, and also to stuck
3726 projects because this search is based on a tags match as well.
3728 When set to the symbol `indented', sublevels are indented with
3729 leading dots.
3731 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3732 the sublevels of a headline matching a tag search often also match
3733 the same search. Listing all of them can create very long lists.
3734 Setting this variable to nil causes subtrees of a match to be skipped.
3736 This variable is semi-obsolete and probably should always be true. It
3737 is better to limit inheritance to certain tags using the variables
3738 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3739 :group 'org-tags
3740 :type '(choice
3741 (const :tag "No, don't list them" nil)
3742 (const :tag "Yes, do list them" t)
3743 (const :tag "List them, indented with leading dots" indented)))
3745 (defcustom org-tags-sort-function nil
3746 "When set, tags are sorted using this function as a comparator."
3747 :group 'org-tags
3748 :type '(choice
3749 (const :tag "No sorting" nil)
3750 (const :tag "Alphabetical" string<)
3751 (const :tag "Reverse alphabetical" string>)
3752 (function :tag "Custom function" nil)))
3754 (defvar org-tags-history nil
3755 "History of minibuffer reads for tags.")
3756 (defvar org-last-tags-completion-table nil
3757 "The last used completion table for tags.")
3758 (defvar org-after-tags-change-hook nil
3759 "Hook that is run after the tags in a line have changed.")
3761 (defgroup org-properties nil
3762 "Options concerning properties in Org mode."
3763 :tag "Org Properties"
3764 :group 'org)
3766 (defcustom org-property-format "%-10s %s"
3767 "How property key/value pairs should be formatted by `indent-line'.
3768 When `indent-line' hits a property definition, it will format the line
3769 according to this format, mainly to make sure that the values are
3770 lined-up with respect to each other."
3771 :group 'org-properties
3772 :type 'string)
3774 (defcustom org-properties-postprocess-alist nil
3775 "Alist of properties and functions to adjust inserted values.
3776 Elements of this alist must be of the form
3778 ([string] [function])
3780 where [string] must be a property name and [function] must be a
3781 lambda expression: this lambda expression must take one argument,
3782 the value to adjust, and return the new value as a string.
3784 For example, this element will allow the property \"Remaining\"
3785 to be updated wrt the relation between the \"Effort\" property
3786 and the clock summary:
3788 ((\"Remaining\" (lambda(value)
3789 (let ((clocksum (org-clock-sum-current-item))
3790 (effort (org-duration-string-to-minutes
3791 (org-entry-get (point) \"Effort\"))))
3792 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3793 :group 'org-properties
3794 :version "24.1"
3795 :type '(alist :key-type (string :tag "Property")
3796 :value-type (function :tag "Function")))
3798 (defcustom org-use-property-inheritance nil
3799 "Non-nil means properties apply also for sublevels.
3801 This setting is chiefly used during property searches. Turning it on can
3802 cause significant overhead when doing a search, which is why it is not
3803 on by default.
3805 When nil, only the properties directly given in the current entry count.
3806 When t, every property is inherited. The value may also be a list of
3807 properties that should have inheritance, or a regular expression matching
3808 properties that should be inherited.
3810 However, note that some special properties use inheritance under special
3811 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3812 and the properties ending in \"_ALL\" when they are used as descriptor
3813 for valid values of a property.
3815 Note for programmers:
3816 When querying an entry with `org-entry-get', you can control if inheritance
3817 should be used. By default, `org-entry-get' looks only at the local
3818 properties. You can request inheritance by setting the inherit argument
3819 to t (to force inheritance) or to `selective' (to respect the setting
3820 in this variable)."
3821 :group 'org-properties
3822 :type '(choice
3823 (const :tag "Not" nil)
3824 (const :tag "Always" t)
3825 (repeat :tag "Specific properties" (string :tag "Property"))
3826 (regexp :tag "Properties matched by regexp")))
3828 (defun org-property-inherit-p (property)
3829 "Check if PROPERTY is one that should be inherited."
3830 (cond
3831 ((eq org-use-property-inheritance t) t)
3832 ((not org-use-property-inheritance) nil)
3833 ((stringp org-use-property-inheritance)
3834 (string-match org-use-property-inheritance property))
3835 ((listp org-use-property-inheritance)
3836 (member property org-use-property-inheritance))
3837 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3839 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3840 "The default column format, if no other format has been defined.
3841 This variable can be set on the per-file basis by inserting a line
3843 #+COLUMNS: %25ITEM ....."
3844 :group 'org-properties
3845 :type 'string)
3847 (defcustom org-columns-ellipses ".."
3848 "The ellipses to be used when a field in column view is truncated.
3849 When this is the empty string, as many characters as possible are shown,
3850 but then there will be no visual indication that the field has been truncated.
3851 When this is a string of length N, the last N characters of a truncated
3852 field are replaced by this string. If the column is narrower than the
3853 ellipses string, only part of the ellipses string will be shown."
3854 :group 'org-properties
3855 :type 'string)
3857 (defconst org-global-properties-fixed
3858 '(("VISIBILITY_ALL" . "folded children content all")
3859 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3860 "List of property/value pairs that can be inherited by any entry.
3862 These are fixed values, for the preset properties. The user variable
3863 that can be used to add to this list is `org-global-properties'.
3865 The entries in this list are cons cells where the car is a property
3866 name and cdr is a string with the value. If the value represents
3867 multiple items like an \"_ALL\" property, separate the items by
3868 spaces.")
3870 (defcustom org-global-properties nil
3871 "List of property/value pairs that can be inherited by any entry.
3873 This list will be combined with the constant `org-global-properties-fixed'.
3875 The entries in this list are cons cells where the car is a property
3876 name and cdr is a string with the value.
3878 You can set buffer-local values for the same purpose in the variable
3879 `org-file-properties' this by adding lines like
3881 #+PROPERTY: NAME VALUE"
3882 :group 'org-properties
3883 :type '(repeat
3884 (cons (string :tag "Property")
3885 (string :tag "Value"))))
3887 (defvar-local org-file-properties nil
3888 "List of property/value pairs that can be inherited by any entry.
3889 Valid for the current buffer.
3890 This variable is populated from #+PROPERTY lines.")
3892 (defgroup org-agenda nil
3893 "Options concerning agenda views in Org mode."
3894 :tag "Org Agenda"
3895 :group 'org)
3897 (defvar-local org-category nil
3898 "Variable used by org files to set a category for agenda display.
3899 Such files should use a file variable to set it, for example
3901 # -*- mode: org; org-category: \"ELisp\"
3903 or contain a special line
3905 #+CATEGORY: ELisp
3907 If the file does not specify a category, then file's base name
3908 is used instead.")
3909 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3911 (defcustom org-agenda-files nil
3912 "The files to be used for agenda display.
3914 If an entry is a directory, all files in that directory that are matched
3915 by `org-agenda-file-regexp' will be part of the file list.
3917 If the value of the variable is not a list but a single file name, then
3918 the list of agenda files is actually stored and maintained in that file,
3919 one agenda file per line. In this file paths can be given relative to
3920 `org-directory'. Tilde expansion and environment variable substitution
3921 are also made.
3923 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3924 and removed with `\\[org-remove-file]'."
3925 :group 'org-agenda
3926 :type '(choice
3927 (repeat :tag "List of files and directories" file)
3928 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3930 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3931 "Regular expression to match files for `org-agenda-files'.
3932 If any element in the list in that variable contains a directory instead
3933 of a normal file, all files in that directory that are matched by this
3934 regular expression will be included."
3935 :group 'org-agenda
3936 :type 'regexp)
3938 (defcustom org-agenda-text-search-extra-files nil
3939 "List of extra files to be searched by text search commands.
3940 These files will be searched in addition to the agenda files by the
3941 commands `org-search-view' (`\\[org-agenda] s') \
3942 and `org-occur-in-agenda-files'.
3943 Note that these files will only be searched for text search commands,
3944 not for the other agenda views like todo lists, tag searches or the weekly
3945 agenda. This variable is intended to list notes and possibly archive files
3946 that should also be searched by these two commands.
3947 In fact, if the first element in the list is the symbol `agenda-archives',
3948 then all archive files of all agenda files will be added to the search
3949 scope."
3950 :group 'org-agenda
3951 :type '(set :greedy t
3952 (const :tag "Agenda Archives" agenda-archives)
3953 (repeat :inline t (file))))
3955 (defvaralias 'org-agenda-multi-occur-extra-files
3956 'org-agenda-text-search-extra-files)
3958 (defcustom org-agenda-skip-unavailable-files nil
3959 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3960 A nil value means to remove them, after a query, from the list."
3961 :group 'org-agenda
3962 :type 'boolean)
3964 (defcustom org-calendar-to-agenda-key [?c]
3965 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3966 The command `org-calendar-goto-agenda' will be bound to this key. The
3967 default is the character `c' because then `c' can be used to switch back and
3968 forth between agenda and calendar."
3969 :group 'org-agenda
3970 :type 'sexp)
3972 (defcustom org-calendar-insert-diary-entry-key [?i]
3973 "The key to be installed in `calendar-mode-map' for adding diary entries.
3974 This option is irrelevant until `org-agenda-diary-file' has been configured
3975 to point to an Org file. When that is the case, the command
3976 `org-agenda-diary-entry' will be bound to the key given here, by default
3977 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3978 if you want to continue doing this, you need to change this to a different
3979 key."
3980 :group 'org-agenda
3981 :type 'sexp)
3983 (defcustom org-agenda-diary-file 'diary-file
3984 "File to which to add new entries with the `i' key in agenda and calendar.
3985 When this is the symbol `diary-file', the functionality in the Emacs
3986 calendar will be used to add entries to the `diary-file'. But when this
3987 points to a file, `org-agenda-diary-entry' will be used instead."
3988 :group 'org-agenda
3989 :type '(choice
3990 (const :tag "The standard Emacs diary file" diary-file)
3991 (file :tag "Special Org file diary entries")))
3993 (eval-after-load "calendar"
3994 '(progn
3995 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3996 'org-calendar-goto-agenda)
3997 (add-hook 'calendar-mode-hook
3998 (lambda ()
3999 (unless (eq org-agenda-diary-file 'diary-file)
4000 (define-key calendar-mode-map
4001 org-calendar-insert-diary-entry-key
4002 'org-agenda-diary-entry))))))
4004 (defgroup org-latex nil
4005 "Options for embedding LaTeX code into Org mode."
4006 :tag "Org LaTeX"
4007 :group 'org)
4009 (defcustom org-format-latex-options
4010 '(:foreground default :background default :scale 1.0
4011 :html-foreground "Black" :html-background "Transparent"
4012 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
4013 "Options for creating images from LaTeX fragments.
4014 This is a property list with the following properties:
4015 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
4016 `default' means use the foreground of the default face.
4017 `auto' means use the foreground from the text face.
4018 :background the background color, or \"Transparent\".
4019 `default' means use the background of the default face.
4020 `auto' means use the background from the text face.
4021 :scale a scaling factor for the size of the images, to get more pixels
4022 :html-foreground, :html-background, :html-scale
4023 the same numbers for HTML export.
4024 :matchers a list indicating which matchers should be used to
4025 find LaTeX fragments. Valid members of this list are:
4026 \"begin\" find environments
4027 \"$1\" find single characters surrounded by $.$
4028 \"$\" find math expressions surrounded by $...$
4029 \"$$\" find math expressions surrounded by $$....$$
4030 \"\\(\" find math expressions surrounded by \\(...\\)
4031 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
4032 :group 'org-latex
4033 :type 'plist)
4035 (defcustom org-format-latex-signal-error t
4036 "Non-nil means signal an error when image creation of LaTeX snippets fails.
4037 When nil, just push out a message."
4038 :group 'org-latex
4039 :version "24.1"
4040 :type 'boolean)
4042 (defcustom org-latex-to-mathml-jar-file nil
4043 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
4044 Use this to specify additional executable file say a jar file.
4046 When using MathToWeb as the converter, specify the full-path to
4047 your mathtoweb.jar file."
4048 :group 'org-latex
4049 :version "24.1"
4050 :type '(choice
4051 (const :tag "None" nil)
4052 (file :tag "JAR file" :must-match t)))
4054 (defcustom org-latex-to-mathml-convert-command nil
4055 "Command to convert LaTeX fragments to MathML.
4056 Replace format-specifiers in the command as noted below and use
4057 `shell-command' to convert LaTeX to MathML.
4058 %j: Executable file in fully expanded form as specified by
4059 `org-latex-to-mathml-jar-file'.
4060 %I: Input LaTeX file in fully expanded form.
4061 %i: The latex fragment to be converted.
4062 %o: Output MathML file.
4064 This command is used by `org-create-math-formula'.
4066 When using MathToWeb as the converter, set this option to
4067 \"java -jar %j -unicode -force -df %o %I\".
4069 When using LaTeXML set this option to
4070 \"latexmlmath \"%i\" --presentationmathml=%o\"."
4071 :group 'org-latex
4072 :version "24.1"
4073 :type '(choice
4074 (const :tag "None" nil)
4075 (string :tag "\nShell command")))
4077 (defcustom org-preview-latex-default-process 'dvipng
4078 "The default process to convert LaTeX fragments to image files.
4079 All available processes and theirs documents can be found in
4080 `org-preview-latex-process-alist', which see."
4081 :group 'org-latex
4082 :version "25.2"
4083 :package-version '(Org . "9.0")
4084 :type 'symbol)
4086 (defcustom org-preview-latex-process-alist
4087 '((dvipng
4088 :programs ("latex" "dvipng")
4089 :description "dvi > png"
4090 :message "you need to install the programs: latex and dvipng."
4091 :image-input-type "dvi"
4092 :image-output-type "png"
4093 :image-size-adjust (1.0 . 1.0)
4094 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4095 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
4096 (dvisvgm
4097 :programs ("latex" "dvisvgm")
4098 :description "dvi > svg"
4099 :message "you need to install the programs: latex and dvisvgm."
4100 :use-xcolor t
4101 :image-input-type "dvi"
4102 :image-output-type "svg"
4103 :image-size-adjust (1.7 . 1.5)
4104 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4105 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
4106 (imagemagick
4107 :programs ("latex" "convert")
4108 :description "pdf > png"
4109 :message "you need to install the programs: latex and imagemagick."
4110 :use-xcolor t
4111 :image-input-type "pdf"
4112 :image-output-type "png"
4113 :image-size-adjust (1.0 . 1.0)
4114 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4115 :image-converter
4116 ("convert -density %D -trim -antialias %f -quality 100 %O")))
4117 "Definitions of external processes for LaTeX previewing.
4118 Org mode can use some external commands to generate TeX snippet's images for
4119 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4120 `org-create-formula-image' how to call them.
4122 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4123 PROPERTIES accepts the following attributes:
4125 :programs list of strings, required programs.
4126 :description string, describe the process.
4127 :message string, message it when required programs cannot be found.
4128 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4129 :image-output-type string, output file type of image converter (e.g., \"png\").
4130 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4131 deal with background and foreground color of image.
4132 Otherwise, dvipng style background and foregroud color
4133 format are generated. You may then refer to them in
4134 command options with \"%F\" and \"%B\".
4135 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4136 image size showed in buffer and the cdr element is for
4137 HTML file. This option is only useful for process
4138 developers, users should use variable
4139 `org-format-latex-options' instead.
4140 :post-clean list of strings, files matched are to be cleaned up once
4141 the image is generated. When nil, the files with \".dvi\",
4142 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4143 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4144 be cleaned up.
4145 :latex-header list of strings, the LaTeX header of the snippet file.
4146 When nil, the fallback value is used instead, which is
4147 controlled by `org-format-latex-header',
4148 `org-latex-default-packages-alist' and
4149 `org-latex-packages-alist', which see.
4150 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4151 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4152 replaced with values defined below.
4153 :image-converter list of image converter commands strings. Each of them is
4154 given to the shell and supports any of the following
4155 place-holders defined below.
4157 Place-holders used by `:image-converter' and `:latex-compiler':
4159 %f input file name
4160 %b base name of input file
4161 %o base directory of input file
4162 %O absolute output file name
4164 Place-holders only used by `:image-converter':
4166 %F foreground of image
4167 %B background of image
4168 %D dpi, which is used to adjust image size by some processing commands.
4169 %S the image size scale ratio, which is used to adjust image size by some
4170 processing commands."
4171 :group 'org-latex
4172 :version "25.2"
4173 :package-version '(Org . "9.0")
4174 :type '(alist :tag "LaTeX to image backends"
4175 :value-type (plist)))
4177 (defcustom org-preview-latex-image-directory "ltximg/"
4178 "Path to store latex preview images.
4179 A relative path here creates many directories relative to the
4180 processed org files paths. An absolute path puts all preview
4181 images at the same place."
4182 :group 'org-latex
4183 :version "25.2"
4184 :package-version '(Org . "9.0")
4185 :type 'string)
4187 (defun org-format-latex-mathml-available-p ()
4188 "Return t if `org-latex-to-mathml-convert-command' is usable."
4189 (save-match-data
4190 (when (and (boundp 'org-latex-to-mathml-convert-command)
4191 org-latex-to-mathml-convert-command)
4192 (let ((executable (car (split-string
4193 org-latex-to-mathml-convert-command))))
4194 (when (executable-find executable)
4195 (if (string-match
4196 "%j" org-latex-to-mathml-convert-command)
4197 (file-readable-p org-latex-to-mathml-jar-file)
4198 t))))))
4200 (defcustom org-format-latex-header "\\documentclass{article}
4201 \\usepackage[usenames]{color}
4202 \[PACKAGES]
4203 \[DEFAULT-PACKAGES]
4204 \\pagestyle{empty} % do not remove
4205 % The settings below are copied from fullpage.sty
4206 \\setlength{\\textwidth}{\\paperwidth}
4207 \\addtolength{\\textwidth}{-3cm}
4208 \\setlength{\\oddsidemargin}{1.5cm}
4209 \\addtolength{\\oddsidemargin}{-2.54cm}
4210 \\setlength{\\evensidemargin}{\\oddsidemargin}
4211 \\setlength{\\textheight}{\\paperheight}
4212 \\addtolength{\\textheight}{-\\headheight}
4213 \\addtolength{\\textheight}{-\\headsep}
4214 \\addtolength{\\textheight}{-\\footskip}
4215 \\addtolength{\\textheight}{-3cm}
4216 \\setlength{\\topmargin}{1.5cm}
4217 \\addtolength{\\topmargin}{-2.54cm}"
4218 "The document header used for processing LaTeX fragments.
4219 It is imperative that this header make sure that no page number
4220 appears on the page. The package defined in the variables
4221 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4222 will either replace the placeholder \"[PACKAGES]\" in this
4223 header, or they will be appended."
4224 :group 'org-latex
4225 :type 'string)
4227 (defun org-set-packages-alist (var val)
4228 "Set the packages alist and make sure it has 3 elements per entry."
4229 (set var (mapcar (lambda (x)
4230 (if (and (consp x) (= (length x) 2))
4231 (list (car x) (nth 1 x) t)
4233 val)))
4235 (defun org-get-packages-alist (var)
4236 "Get the packages alist and make sure it has 3 elements per entry."
4237 (mapcar (lambda (x)
4238 (if (and (consp x) (= (length x) 2))
4239 (list (car x) (nth 1 x) t)
4241 (default-value var)))
4243 (defcustom org-latex-default-packages-alist
4244 '(("AUTO" "inputenc" t ("pdflatex"))
4245 ("T1" "fontenc" t ("pdflatex"))
4246 ("" "graphicx" t)
4247 ("" "grffile" t)
4248 ("" "longtable" nil)
4249 ("" "wrapfig" nil)
4250 ("" "rotating" nil)
4251 ("normalem" "ulem" t)
4252 ("" "amsmath" t)
4253 ("" "textcomp" t)
4254 ("" "amssymb" t)
4255 ("" "capt-of" nil)
4256 ("" "hyperref" nil))
4257 "Alist of default packages to be inserted in the header.
4259 Change this only if one of the packages here causes an
4260 incompatibility with another package you are using.
4262 The packages in this list are needed by one part or another of
4263 Org mode to function properly:
4265 - inputenc, fontenc: for basic font and character selection
4266 - graphicx: for including images
4267 - grffile: allow periods and spaces in graphics file names
4268 - longtable: For multipage tables
4269 - wrapfig: for figure placement
4270 - rotating: for sideways figures and tables
4271 - ulem: for underline and strike-through
4272 - amsmath: for subscript and superscript and math environments
4273 - textcomp, amssymb: for various symbols used
4274 for interpreting the entities in `org-entities'. You can skip
4275 some of these packages if you don't use any of their symbols.
4276 - capt-of: for captions outside of floats
4277 - hyperref: for cross references
4279 Therefore you should not modify this variable unless you know
4280 what you are doing. The one reason to change it anyway is that
4281 you might be loading some other package that conflicts with one
4282 of the default packages. Each element is either a cell or
4283 a string.
4285 A cell is of the format
4287 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4289 If SNIPPET-FLAG is non-nil, the package also needs to be included
4290 when compiling LaTeX snippets into images for inclusion into
4291 non-LaTeX output. COMPILERS is a list of compilers that should
4292 include the package, see `org-latex-compiler'. If the document
4293 compiler is not in the list, and the list is non-nil, the package
4294 will not be inserted in the final document.
4296 A string will be inserted as-is in the header of the document."
4297 :group 'org-latex
4298 :group 'org-export-latex
4299 :set 'org-set-packages-alist
4300 :get 'org-get-packages-alist
4301 :version "25.2"
4302 :package-version '(Org . "8.3")
4303 :type '(repeat
4304 (choice
4305 (list :tag "options/package pair"
4306 (string :tag "options")
4307 (string :tag "package")
4308 (boolean :tag "Snippet"))
4309 (string :tag "A line of LaTeX"))))
4311 (defcustom org-latex-packages-alist nil
4312 "Alist of packages to be inserted in every LaTeX header.
4314 These will be inserted after `org-latex-default-packages-alist'.
4315 Each element is either a cell or a string.
4317 A cell is of the format:
4319 (\"options\" \"package\" SNIPPET-FLAG)
4321 SNIPPET-FLAG, when non-nil, indicates that this package is also
4322 needed when turning LaTeX snippets into images for inclusion into
4323 non-LaTeX output.
4325 A string will be inserted as-is in the header of the document.
4327 Make sure that you only list packages here which:
4329 - you want in every file;
4330 - do not conflict with the setup in `org-format-latex-header';
4331 - do not conflict with the default packages in
4332 `org-latex-default-packages-alist'."
4333 :group 'org-latex
4334 :group 'org-export-latex
4335 :set 'org-set-packages-alist
4336 :get 'org-get-packages-alist
4337 :type '(repeat
4338 (choice
4339 (list :tag "options/package pair"
4340 (string :tag "options")
4341 (string :tag "package")
4342 (boolean :tag "Snippet"))
4343 (string :tag "A line of LaTeX"))))
4345 (defgroup org-appearance nil
4346 "Settings for Org mode appearance."
4347 :tag "Org Appearance"
4348 :group 'org)
4350 (defcustom org-level-color-stars-only nil
4351 "Non-nil means fontify only the stars in each headline.
4352 When nil, the entire headline is fontified.
4353 Changing it requires restart of `font-lock-mode' to become effective
4354 also in regions already fontified."
4355 :group 'org-appearance
4356 :type 'boolean)
4358 (defcustom org-hide-leading-stars nil
4359 "Non-nil means hide the first N-1 stars in a headline.
4360 This works by using the face `org-hide' for these stars. This
4361 face is white for a light background, and black for a dark
4362 background. You may have to customize the face `org-hide' to
4363 make this work.
4364 Changing it requires restart of `font-lock-mode' to become effective
4365 also in regions already fontified.
4366 You may also set this on a per-file basis by adding one of the following
4367 lines to the buffer:
4369 #+STARTUP: hidestars
4370 #+STARTUP: showstars"
4371 :group 'org-appearance
4372 :type 'boolean)
4374 (defcustom org-hidden-keywords nil
4375 "List of symbols corresponding to keywords to be hidden the org buffer.
4376 For example, a value \\='(title) for this list will make the document's title
4377 appear in the buffer without the initial #+TITLE: keyword."
4378 :group 'org-appearance
4379 :version "24.1"
4380 :type '(set (const :tag "#+AUTHOR" author)
4381 (const :tag "#+DATE" date)
4382 (const :tag "#+EMAIL" email)
4383 (const :tag "#+TITLE" title)))
4385 (defcustom org-custom-properties nil
4386 "List of properties (as strings) with a special meaning.
4387 The default use of these custom properties is to let the user
4388 hide them with `org-toggle-custom-properties-visibility'."
4389 :group 'org-properties
4390 :group 'org-appearance
4391 :version "24.3"
4392 :type '(repeat (string :tag "Property Name")))
4394 (defcustom org-fontify-done-headline nil
4395 "Non-nil means change the face of a headline if it is marked DONE.
4396 Normally, only the TODO/DONE keyword indicates the state of a headline.
4397 When this is non-nil, the headline after the keyword is set to the
4398 `org-headline-done' as an additional indication."
4399 :group 'org-appearance
4400 :type 'boolean)
4402 (defcustom org-fontify-emphasized-text t
4403 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4404 Changing this variable requires a restart of Emacs to take effect."
4405 :group 'org-appearance
4406 :type 'boolean)
4408 (defcustom org-fontify-whole-heading-line nil
4409 "Non-nil means fontify the whole line for headings.
4410 This is useful when setting a background color for the
4411 org-level-* faces."
4412 :group 'org-appearance
4413 :type 'boolean)
4415 (defcustom org-highlight-latex-and-related nil
4416 "Non-nil means highlight LaTeX related syntax in the buffer.
4417 When non nil, the value should be a list containing any of the
4418 following symbols:
4419 `latex' Highlight LaTeX snippets and environments.
4420 `script' Highlight subscript and superscript.
4421 `entities' Highlight entities."
4422 :group 'org-appearance
4423 :version "24.4"
4424 :package-version '(Org . "8.0")
4425 :type '(choice
4426 (const :tag "No highlighting" nil)
4427 (set :greedy t :tag "Highlight"
4428 (const :tag "LaTeX snippets and environments" latex)
4429 (const :tag "Subscript and superscript" script)
4430 (const :tag "Entities" entities))))
4432 (defcustom org-hide-emphasis-markers nil
4433 "Non-nil mean font-lock should hide the emphasis marker characters."
4434 :group 'org-appearance
4435 :type 'boolean)
4437 (defcustom org-hide-macro-markers nil
4438 "Non-nil mean font-lock should hide the brackets marking macro calls."
4439 :group 'org-appearance
4440 :type 'boolean)
4442 (defcustom org-pretty-entities nil
4443 "Non-nil means show entities as UTF8 characters.
4444 When nil, the \\name form remains in the buffer."
4445 :group 'org-appearance
4446 :version "24.1"
4447 :type 'boolean)
4449 (defcustom org-pretty-entities-include-sub-superscripts t
4450 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4451 :group 'org-appearance
4452 :version "24.1"
4453 :type 'boolean)
4455 (defvar org-emph-re nil
4456 "Regular expression for matching emphasis.
4457 After a match, the match groups contain these elements:
4458 0 The match of the full regular expression, including the characters
4459 before and after the proper match
4460 1 The character before the proper match, or empty at beginning of line
4461 2 The proper match, including the leading and trailing markers
4462 3 The leading marker like * or /, indicating the type of highlighting
4463 4 The text between the emphasis markers, not including the markers
4464 5 The character after the match, empty at the end of a line")
4465 (defvar org-verbatim-re nil
4466 "Regular expression for matching verbatim text.")
4467 (defvar org-emphasis-regexp-components) ; defined just below
4468 (defvar org-emphasis-alist) ; defined just below
4469 (defun org-set-emph-re (var val)
4470 "Set variable and compute the emphasis regular expression."
4471 (set var val)
4472 (when (and (boundp 'org-emphasis-alist)
4473 (boundp 'org-emphasis-regexp-components)
4474 org-emphasis-alist org-emphasis-regexp-components)
4475 (let* ((e org-emphasis-regexp-components)
4476 (pre (car e))
4477 (post (nth 1 e))
4478 (border (nth 2 e))
4479 (body (nth 3 e))
4480 (nl (nth 4 e))
4481 (body1 (concat body "*?"))
4482 (markers (mapconcat 'car org-emphasis-alist ""))
4483 (vmarkers (mapconcat
4484 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4485 org-emphasis-alist "")))
4486 ;; make sure special characters appear at the right position in the class
4487 (if (string-match "\\^" markers)
4488 (setq markers (concat (replace-match "" t t markers) "^")))
4489 (if (string-match "-" markers)
4490 (setq markers (concat (replace-match "" t t markers) "-")))
4491 (if (string-match "\\^" vmarkers)
4492 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4493 (if (string-match "-" vmarkers)
4494 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4495 (if (> nl 0)
4496 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4497 (int-to-string nl) "\\}")))
4498 ;; Make the regexp
4499 (setq org-emph-re
4500 (concat "\\([" pre "]\\|^\\)"
4501 "\\("
4502 "\\([" markers "]\\)"
4503 "\\("
4504 "[^" border "]\\|"
4505 "[^" border "]"
4506 body1
4507 "[^" border "]"
4508 "\\)"
4509 "\\3\\)"
4510 "\\([" post "]\\|$\\)"))
4511 (setq org-verbatim-re
4512 (concat "\\([" pre "]\\|^\\)"
4513 "\\("
4514 "\\([" vmarkers "]\\)"
4515 "\\("
4516 "[^" border "]\\|"
4517 "[^" border "]"
4518 body1
4519 "[^" border "]"
4520 "\\)"
4521 "\\3\\)"
4522 "\\([" post "]\\|$\\)")))))
4524 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4525 ;; set this option proved cumbersome. See this message/thread:
4526 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4527 (defvar org-emphasis-regexp-components
4528 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4529 "Components used to build the regular expression for emphasis.
4530 This is a list with five entries. Terminology: In an emphasis string
4531 like \" *strong word* \", we call the initial space PREMATCH, the final
4532 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4533 and \"trong wor\" is the body. The different components in this variable
4534 specify what is allowed/forbidden in each part:
4536 pre Chars allowed as prematch. Beginning of line will be allowed too.
4537 post Chars allowed as postmatch. End of line will be allowed too.
4538 border The chars *forbidden* as border characters.
4539 body-regexp A regexp like \".\" to match a body character. Don't use
4540 non-shy groups here, and don't allow newline here.
4541 newline The maximum number of newlines allowed in an emphasis exp.
4543 You need to reload Org or to restart Emacs after customizing this.")
4545 (defcustom org-emphasis-alist
4546 '(("*" bold)
4547 ("/" italic)
4548 ("_" underline)
4549 ("=" org-verbatim verbatim)
4550 ("~" org-code verbatim)
4551 ("+" (:strike-through t)))
4552 "Alist of characters and faces to emphasize text.
4553 Text starting and ending with a special character will be emphasized,
4554 for example *bold*, _underlined_ and /italic/. This variable sets the
4555 marker characters and the face to be used by font-lock for highlighting
4556 in Org buffers.
4558 You need to reload Org or to restart Emacs after customizing this."
4559 :group 'org-appearance
4560 :set 'org-set-emph-re
4561 :version "24.4"
4562 :package-version '(Org . "8.0")
4563 :type '(repeat
4564 (list
4565 (string :tag "Marker character")
4566 (choice
4567 (face :tag "Font-lock-face")
4568 (plist :tag "Face property list"))
4569 (option (const verbatim)))))
4571 (defvar org-protecting-blocks '("src" "example" "export")
4572 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4573 This is needed for font-lock setup.")
4575 ;;; Functions and variables from their packages
4576 ;; Declared here to avoid compiler warnings
4577 (defvar mark-active)
4579 ;; Various packages
4580 (declare-function calc-eval "calc" (str &optional separator &rest args))
4581 (declare-function calendar-forward-day "cal-move" (arg))
4582 (declare-function calendar-goto-date "cal-move" (date))
4583 (declare-function calendar-goto-today "cal-move" ())
4584 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4585 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4586 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4587 (declare-function cdlatex-tab "ext:cdlatex" ())
4588 (declare-function dired-get-filename
4589 "dired"
4590 (&optional localp no-error-if-not-filep))
4591 (declare-function iswitchb-read-buffer
4592 "iswitchb"
4593 (prompt &optional
4594 default require-match _predicate start matches-set))
4595 (declare-function org-agenda-change-all-lines
4596 "org-agenda"
4597 (newhead hdmarker &optional fixface just-this))
4598 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4599 "org-agenda"
4600 (&optional end))
4601 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4602 (declare-function org-agenda-format-item
4603 "org-agenda"
4604 (extra txt &optional level category tags dotime
4605 remove-re habitp))
4606 (declare-function org-agenda-maybe-redo "org-agenda" ())
4607 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4608 (declare-function org-agenda-save-markers-for-cut-and-paste
4609 "org-agenda"
4610 (beg end))
4611 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4612 (declare-function org-agenda-skip "org-agenda" ())
4613 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4614 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4615 (declare-function org-indent-mode "org-indent" (&optional arg))
4616 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4617 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4618 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4619 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4620 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4621 (declare-function parse-time-string "parse-time" (string))
4622 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4624 (defvar align-mode-rules-list)
4625 (defvar calc-embedded-close-formula)
4626 (defvar calc-embedded-open-formula)
4627 (defvar calc-embedded-open-mode)
4628 (defvar font-lock-unfontify-region-function)
4629 (defvar iswitchb-temp-buflist)
4630 (defvar org-agenda-tags-todo-honor-ignore-options)
4631 (defvar remember-data-file)
4632 (defvar texmathp-why)
4634 ;;;###autoload
4635 (defun turn-on-orgtbl ()
4636 "Unconditionally turn on `orgtbl-mode'."
4637 (require 'org-table)
4638 (orgtbl-mode 1))
4640 (defun org-at-table-p (&optional table-type)
4641 "Non-nil if the cursor is inside an Org table.
4642 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4643 If `org-enable-table-editor' is nil, return nil unconditionally."
4644 (and
4645 org-enable-table-editor
4646 (save-excursion
4647 (beginning-of-line)
4648 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4649 (or (not (derived-mode-p 'org-mode))
4650 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4651 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4653 (defun org-at-table.el-p ()
4654 "Non-nil when point is at a table.el table."
4655 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4656 (let ((element (org-element-at-point)))
4657 (and (eq (org-element-type element) 'table)
4658 (eq (org-element-property :type element) 'table.el)))))
4660 (defun org-at-table-hline-p ()
4661 "Non-nil when point is inside a hline in a table.
4662 Assume point is already in a table. If `org-enable-table-editor'
4663 is nil, return nil unconditionally."
4664 (and org-enable-table-editor
4665 (save-excursion
4666 (beginning-of-line)
4667 (looking-at org-table-hline-regexp))))
4669 (defun org-table-map-tables (function &optional quietly)
4670 "Apply FUNCTION to the start of all tables in the buffer."
4671 (org-with-wide-buffer
4672 (goto-char (point-min))
4673 (while (re-search-forward org-table-any-line-regexp nil t)
4674 (unless quietly
4675 (message "Mapping tables: %d%%"
4676 (floor (* 100.0 (point)) (buffer-size))))
4677 (beginning-of-line 1)
4678 (when (and (looking-at org-table-line-regexp)
4679 ;; Exclude tables in src/example/verbatim/clocktable blocks
4680 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4681 (save-excursion (funcall function))
4682 (or (looking-at org-table-line-regexp)
4683 (forward-char 1)))
4684 (re-search-forward org-table-any-border-regexp nil 1)))
4685 (unless quietly (message "Mapping tables: done")))
4687 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4688 (declare-function org-clock-update-mode-line "org-clock" ())
4689 (declare-function org-resolve-clocks "org-clock"
4690 (&optional also-non-dangling-p prompt last-valid))
4692 (defun org-at-TBLFM-p (&optional pos)
4693 "Non-nil when point (or POS) is in #+TBLFM line."
4694 (save-excursion
4695 (goto-char (or pos (point)))
4696 (beginning-of-line)
4697 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4698 (eq (org-element-type (org-element-at-point)) 'table))))
4700 (defvar org-clock-start-time)
4701 (defvar org-clock-marker (make-marker)
4702 "Marker recording the last clock-in.")
4703 (defvar org-clock-hd-marker (make-marker)
4704 "Marker recording the last clock-in, but the headline position.")
4705 (defvar org-clock-heading ""
4706 "The heading of the current clock entry.")
4707 (defun org-clock-is-active ()
4708 "Return the buffer where the clock is currently running.
4709 Return nil if no clock is running."
4710 (marker-buffer org-clock-marker))
4712 (defun org-check-running-clock ()
4713 "Check if the current buffer contains the running clock.
4714 If yes, offer to stop it and to save the buffer with the changes."
4715 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4716 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4717 (buffer-name))))
4718 (org-clock-out)
4719 (when (y-or-n-p "Save changed buffer?")
4720 (save-buffer))))
4722 (defun org-clocktable-try-shift (dir n)
4723 "Check if this line starts a clock table, if yes, shift the time block."
4724 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4725 (org-clocktable-shift dir n)))
4727 ;;;###autoload
4728 (defun org-clock-persistence-insinuate ()
4729 "Set up hooks for clock persistence."
4730 (require 'org-clock)
4731 (add-hook 'org-mode-hook 'org-clock-load)
4732 (add-hook 'kill-emacs-hook 'org-clock-save))
4734 (defgroup org-archive nil
4735 "Options concerning archiving in Org mode."
4736 :tag "Org Archive"
4737 :group 'org-structure)
4739 (defcustom org-archive-location "%s_archive::"
4740 "The location where subtrees should be archived.
4742 The value of this variable is a string, consisting of two parts,
4743 separated by a double-colon. The first part is a filename and
4744 the second part is a headline.
4746 When the filename is omitted, archiving happens in the same file.
4747 %s in the filename will be replaced by the current file
4748 name (without the directory part). Archiving to a different file
4749 is useful to keep archived entries from contributing to the
4750 Org Agenda.
4752 The archived entries will be filed as subtrees of the specified
4753 headline. When the headline is omitted, the subtrees are simply
4754 filed away at the end of the file, as top-level entries. Also in
4755 the heading you can use %s to represent the file name, this can be
4756 useful when using the same archive for a number of different files.
4758 Here are a few examples:
4759 \"%s_archive::\"
4760 If the current file is Projects.org, archive in file
4761 Projects.org_archive, as top-level trees. This is the default.
4763 \"::* Archived Tasks\"
4764 Archive in the current file, under the top-level headline
4765 \"* Archived Tasks\".
4767 \"~/org/archive.org::\"
4768 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4770 \"~/org/archive.org::* From %s\"
4771 Archive in file ~/org/archive.org (absolute path), under headlines
4772 \"From FILENAME\" where file name is the current file name.
4774 \"~/org/datetree.org::datetree/* Finished Tasks\"
4775 The \"datetree/\" string is special, signifying to archive
4776 items to the datetree. Items are placed in either the CLOSED
4777 date of the item, or the current date if there is no CLOSED date.
4778 The heading will be a subentry to the current date. There doesn't
4779 need to be a heading, but there always needs to be a slash after
4780 datetree. For example, to store archived items directly in the
4781 datetree, use \"~/org/datetree.org::datetree/\".
4783 \"basement::** Finished Tasks\"
4784 Archive in file ./basement (relative path), as level 3 trees
4785 below the level 2 heading \"** Finished Tasks\".
4787 You may set this option on a per-file basis by adding to the buffer a
4788 line like
4790 #+ARCHIVE: basement::** Finished Tasks
4792 You may also define it locally for a subtree by setting an ARCHIVE property
4793 in the entry. If such a property is found in an entry, or anywhere up
4794 the hierarchy, it will be used."
4795 :group 'org-archive
4796 :type 'string)
4798 (defcustom org-agenda-skip-archived-trees t
4799 "Non-nil means the agenda will skip any items located in archived trees.
4800 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4801 variable is no longer recommended, you should leave it at the value t.
4802 Instead, use the key `v' to cycle the archives-mode in the agenda."
4803 :group 'org-archive
4804 :group 'org-agenda-skip
4805 :type 'boolean)
4807 (defcustom org-columns-skip-archived-trees t
4808 "Non-nil means ignore archived trees when creating column view."
4809 :group 'org-archive
4810 :group 'org-properties
4811 :type 'boolean)
4813 (defcustom org-cycle-open-archived-trees nil
4814 "Non-nil means `org-cycle' will open archived trees.
4815 An archived tree is a tree marked with the tag ARCHIVE.
4816 When nil, archived trees will stay folded. You can still open them with
4817 normal outline commands like `show-all', but not with the cycling commands."
4818 :group 'org-archive
4819 :group 'org-cycle
4820 :type 'boolean)
4822 (defcustom org-sparse-tree-open-archived-trees nil
4823 "Non-nil means sparse tree construction shows matches in archived trees.
4824 When nil, matches in these trees are highlighted, but the trees are kept in
4825 collapsed state."
4826 :group 'org-archive
4827 :group 'org-sparse-trees
4828 :type 'boolean)
4830 (defcustom org-sparse-tree-default-date-type nil
4831 "The default date type when building a sparse tree.
4832 When this is nil, a date is a scheduled or a deadline timestamp.
4833 Otherwise, these types are allowed:
4835 all: all timestamps
4836 active: only active timestamps (<...>)
4837 inactive: only inactive timestamps ([...])
4838 scheduled: only scheduled timestamps
4839 deadline: only deadline timestamps"
4840 :type '(choice (const :tag "Scheduled or deadline" nil)
4841 (const :tag "All timestamps" all)
4842 (const :tag "Only active timestamps" active)
4843 (const :tag "Only inactive timestamps" inactive)
4844 (const :tag "Only scheduled timestamps" scheduled)
4845 (const :tag "Only deadline timestamps" deadline)
4846 (const :tag "Only closed timestamps" closed))
4847 :version "25.2"
4848 :package-version '(Org . "8.3")
4849 :group 'org-sparse-trees)
4851 (defun org-cycle-hide-archived-subtrees (state)
4852 "Re-hide all archived subtrees after a visibility state change."
4853 (when (and (not org-cycle-open-archived-trees)
4854 (not (memq state '(overview folded))))
4855 (save-excursion
4856 (let* ((globalp (memq state '(contents all)))
4857 (beg (if globalp (point-min) (point)))
4858 (end (if globalp (point-max) (org-end-of-subtree t))))
4859 (org-hide-archived-subtrees beg end)
4860 (goto-char beg)
4861 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4862 (message "%s" (substitute-command-keys
4863 "Subtree is archived and stays closed. Use \
4864 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4866 (defun org-force-cycle-archived ()
4867 "Cycle subtree even if it is archived."
4868 (interactive)
4869 (setq this-command 'org-cycle)
4870 (let ((org-cycle-open-archived-trees t))
4871 (call-interactively 'org-cycle)))
4873 (defun org-hide-archived-subtrees (beg end)
4874 "Re-hide all archived subtrees after a visibility state change."
4875 (org-with-wide-buffer
4876 (let ((case-fold-search nil)
4877 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4878 (goto-char beg)
4879 ;; Include headline point is currently on.
4880 (beginning-of-line)
4881 (while (and (< (point) end) (re-search-forward re end t))
4882 (when (member org-archive-tag (org-get-tags))
4883 (org-flag-subtree t)
4884 (org-end-of-subtree t))))))
4886 (declare-function outline-end-of-heading "outline" ())
4887 (declare-function outline-flag-region "outline" (from to flag))
4888 (defun org-flag-subtree (flag)
4889 (save-excursion
4890 (org-back-to-heading t)
4891 (outline-end-of-heading)
4892 (outline-flag-region (point)
4893 (progn (org-end-of-subtree t) (point))
4894 flag)))
4896 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4898 ;; Declare Column View Code
4900 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4901 (declare-function org-columns-compute "org-colview" (property))
4903 ;; Declare ID code
4905 (declare-function org-id-store-link "org-id")
4906 (declare-function org-id-locations-load "org-id")
4907 (declare-function org-id-locations-save "org-id")
4908 (defvar org-id-track-globally)
4910 ;;; Variables for pre-computed regular expressions, all buffer local
4912 (defvar-local org-todo-regexp nil
4913 "Matches any of the TODO state keywords.
4914 Since TODO keywords are case-sensitive, `case-fold-search' is
4915 expected to be bound to nil when matching against this regexp.")
4917 (defvar-local org-not-done-regexp nil
4918 "Matches any of the TODO state keywords except the last one.
4919 Since TODO keywords are case-sensitive, `case-fold-search' is
4920 expected to be bound to nil when matching against this regexp.")
4922 (defvar-local org-not-done-heading-regexp nil
4923 "Matches a TODO headline that is not done.
4924 Since TODO keywords are case-sensitive, `case-fold-search' is
4925 expected to be bound to nil when matching against this regexp.")
4927 (defvar-local org-todo-line-regexp nil
4928 "Matches a headline and puts TODO state into group 2 if present.
4929 Since TODO keywords are case-sensitive, `case-fold-search' is
4930 expected to be bound to nil when matching against this regexp.")
4932 (defvar-local org-complex-heading-regexp nil
4933 "Matches a headline and puts everything into groups:
4935 group 1: Stars
4936 group 2: The TODO keyword, maybe
4937 group 3: Priority cookie
4938 group 4: True headline
4939 group 5: Tags
4941 Since TODO keywords are case-sensitive, `case-fold-search' is
4942 expected to be bound to nil when matching against this regexp.")
4944 (defvar-local org-complex-heading-regexp-format nil
4945 "Printf format to make regexp to match an exact headline.
4946 This regexp will match the headline of any node which has the
4947 exact headline text that is put into the format, but may have any
4948 TODO state, priority and tags.")
4950 (defvar-local org-todo-line-tags-regexp nil
4951 "Matches a headline and puts TODO state into group 2 if present.
4952 Also put tags into group 4 if tags are present.")
4954 (defconst org-plain-time-of-day-regexp
4955 (concat
4956 "\\(\\<[012]?[0-9]"
4957 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4958 "\\(--?"
4959 "\\(\\<[012]?[0-9]"
4960 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4961 "\\)?")
4962 "Regular expression to match a plain time or time range.
4963 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4964 groups carry important information:
4965 0 the full match
4966 1 the first time, range or not
4967 8 the second time, if it is a range.")
4969 (defconst org-plain-time-extension-regexp
4970 (concat
4971 "\\(\\<[012]?[0-9]"
4972 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4973 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4974 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4975 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4976 groups carry important information:
4977 0 the full match
4978 7 hours of duration
4979 9 minutes of duration")
4981 (defconst org-stamp-time-of-day-regexp
4982 (concat
4983 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4984 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4985 "\\(--?"
4986 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4987 "Regular expression to match a timestamp time or time range.
4988 After a match, the following groups carry important information:
4989 0 the full match
4990 1 date plus weekday, for back referencing to make sure both times are on the same day
4991 2 the first time, range or not
4992 4 the second time, if it is a range.")
4994 (defconst org-startup-options
4995 '(("fold" org-startup-folded t)
4996 ("overview" org-startup-folded t)
4997 ("nofold" org-startup-folded nil)
4998 ("showall" org-startup-folded nil)
4999 ("showeverything" org-startup-folded showeverything)
5000 ("content" org-startup-folded content)
5001 ("indent" org-startup-indented t)
5002 ("noindent" org-startup-indented nil)
5003 ("hidestars" org-hide-leading-stars t)
5004 ("showstars" org-hide-leading-stars nil)
5005 ("odd" org-odd-levels-only t)
5006 ("oddeven" org-odd-levels-only nil)
5007 ("align" org-startup-align-all-tables t)
5008 ("noalign" org-startup-align-all-tables nil)
5009 ("inlineimages" org-startup-with-inline-images t)
5010 ("noinlineimages" org-startup-with-inline-images nil)
5011 ("latexpreview" org-startup-with-latex-preview t)
5012 ("nolatexpreview" org-startup-with-latex-preview nil)
5013 ("customtime" org-display-custom-times t)
5014 ("logdone" org-log-done time)
5015 ("lognotedone" org-log-done note)
5016 ("nologdone" org-log-done nil)
5017 ("lognoteclock-out" org-log-note-clock-out t)
5018 ("nolognoteclock-out" org-log-note-clock-out nil)
5019 ("logrepeat" org-log-repeat state)
5020 ("lognoterepeat" org-log-repeat note)
5021 ("logdrawer" org-log-into-drawer t)
5022 ("nologdrawer" org-log-into-drawer nil)
5023 ("logstatesreversed" org-log-states-order-reversed t)
5024 ("nologstatesreversed" org-log-states-order-reversed nil)
5025 ("nologrepeat" org-log-repeat nil)
5026 ("logreschedule" org-log-reschedule time)
5027 ("lognotereschedule" org-log-reschedule note)
5028 ("nologreschedule" org-log-reschedule nil)
5029 ("logredeadline" org-log-redeadline time)
5030 ("lognoteredeadline" org-log-redeadline note)
5031 ("nologredeadline" org-log-redeadline nil)
5032 ("logrefile" org-log-refile time)
5033 ("lognoterefile" org-log-refile note)
5034 ("nologrefile" org-log-refile nil)
5035 ("fninline" org-footnote-define-inline t)
5036 ("nofninline" org-footnote-define-inline nil)
5037 ("fnlocal" org-footnote-section nil)
5038 ("fnauto" org-footnote-auto-label t)
5039 ("fnprompt" org-footnote-auto-label nil)
5040 ("fnconfirm" org-footnote-auto-label confirm)
5041 ("fnplain" org-footnote-auto-label plain)
5042 ("fnadjust" org-footnote-auto-adjust t)
5043 ("nofnadjust" org-footnote-auto-adjust nil)
5044 ("constcgs" constants-unit-system cgs)
5045 ("constSI" constants-unit-system SI)
5046 ("noptag" org-tag-persistent-alist nil)
5047 ("hideblocks" org-hide-block-startup t)
5048 ("nohideblocks" org-hide-block-startup nil)
5049 ("beamer" org-startup-with-beamer-mode t)
5050 ("entitiespretty" org-pretty-entities t)
5051 ("entitiesplain" org-pretty-entities nil))
5052 "Variable associated with STARTUP options for org-mode.
5053 Each element is a list of three items: the startup options (as written
5054 in the #+STARTUP line), the corresponding variable, and the value to set
5055 this variable to if the option is found. An optional forth element PUSH
5056 means to push this value onto the list in the variable.")
5058 (defcustom org-group-tags t
5059 "When non-nil (the default), use group tags.
5060 This can be turned on/off through `org-toggle-tags-groups'."
5061 :group 'org-tags
5062 :group 'org-startup
5063 :type 'boolean)
5065 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5067 (defun org-toggle-tags-groups ()
5068 "Toggle support for group tags.
5069 Support for group tags is controlled by the option
5070 `org-group-tags', which is non-nil by default."
5071 (interactive)
5072 (setq org-group-tags (not org-group-tags))
5073 (cond ((and (derived-mode-p 'org-agenda-mode)
5074 org-group-tags)
5075 (org-agenda-redo))
5076 ((derived-mode-p 'org-mode)
5077 (let ((org-inhibit-startup t)) (org-mode))))
5078 (message "Groups tags support has been turned %s"
5079 (if org-group-tags "on" "off")))
5081 (defun org-set-regexps-and-options (&optional tags-only)
5082 "Precompute regular expressions used in the current buffer.
5083 When optional argument TAGS-ONLY is non-nil, only compute tags
5084 related expressions."
5085 (when (derived-mode-p 'org-mode)
5086 (let ((alist (org--setup-collect-keywords
5087 (org-make-options-regexp
5088 (append '("FILETAGS" "TAGS" "SETUPFILE")
5089 (and (not tags-only)
5090 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
5091 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
5092 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
5093 ;; Startup options. Get this early since it does change
5094 ;; behavior for other options (e.g., tags).
5095 (let ((startup (cdr (assq 'startup alist))))
5096 (dolist (option startup)
5097 (let ((entry (assoc-string option org-startup-options t)))
5098 (when entry
5099 (let ((var (nth 1 entry))
5100 (val (nth 2 entry)))
5101 (if (not (nth 3 entry)) (set (make-local-variable var) val)
5102 (unless (listp (symbol-value var))
5103 (set (make-local-variable var) nil))
5104 (add-to-list var val)))))))
5105 (setq-local org-file-tags
5106 (mapcar #'org-add-prop-inherited
5107 (cdr (assq 'filetags alist))))
5108 (setq org-current-tag-alist
5109 (append org-tag-persistent-alist
5110 (let ((tags (cdr (assq 'tags alist))))
5111 (if tags (org-tag-string-to-alist tags)
5112 org-tag-alist))))
5113 (setq org-tag-groups-alist
5114 (org-tag-alist-to-groups org-current-tag-alist))
5115 (unless tags-only
5116 ;; File properties.
5117 (setq-local org-file-properties (cdr (assq 'property alist)))
5118 ;; Archive location.
5119 (let ((archive (cdr (assq 'archive alist))))
5120 (when archive (setq-local org-archive-location archive)))
5121 ;; Category.
5122 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
5123 (when cat
5124 (setq-local org-category (intern cat))
5125 (setq-local org-file-properties
5126 (org--update-property-plist
5127 "CATEGORY" cat org-file-properties))))
5128 ;; Columns.
5129 (let ((column (cdr (assq 'columns alist))))
5130 (when column (setq-local org-columns-default-format column)))
5131 ;; Constants.
5132 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
5133 ;; Link abbreviations.
5134 (let ((links (cdr (assq 'link alist))))
5135 (when links (setq org-link-abbrev-alist-local (nreverse links))))
5136 ;; Priorities.
5137 (let ((priorities (cdr (assq 'priorities alist))))
5138 (when priorities
5139 (setq-local org-highest-priority (nth 0 priorities))
5140 (setq-local org-lowest-priority (nth 1 priorities))
5141 (setq-local org-default-priority (nth 2 priorities))))
5142 ;; Scripts.
5143 (let ((scripts (assq 'scripts alist)))
5144 (when scripts
5145 (setq-local org-use-sub-superscripts (cdr scripts))))
5146 ;; TODO keywords.
5147 (setq-local org-todo-kwd-alist nil)
5148 (setq-local org-todo-key-alist nil)
5149 (setq-local org-todo-key-trigger nil)
5150 (setq-local org-todo-keywords-1 nil)
5151 (setq-local org-done-keywords nil)
5152 (setq-local org-todo-heads nil)
5153 (setq-local org-todo-sets nil)
5154 (setq-local org-todo-log-states nil)
5155 (let ((todo-sequences
5156 (or (nreverse (cdr (assq 'todo alist)))
5157 (let ((d (default-value 'org-todo-keywords)))
5158 (if (not (stringp (car d))) d
5159 ;; XXX: Backward compatibility code.
5160 (list (cons org-todo-interpretation d)))))))
5161 (dolist (sequence todo-sequences)
5162 (let* ((sequence (or (run-hook-with-args-until-success
5163 'org-todo-setup-filter-hook sequence)
5164 sequence))
5165 (sequence-type (car sequence))
5166 (keywords (cdr sequence))
5167 (sep (member "|" keywords))
5168 names alist)
5169 (dolist (k (remove "|" keywords))
5170 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5172 (error "Invalid TODO keyword %s" k))
5173 (let ((name (match-string 1 k))
5174 (key (match-string 2 k))
5175 (log (org-extract-log-state-settings k)))
5176 (push name names)
5177 (push (cons name (and key (string-to-char key))) alist)
5178 (when log (push log org-todo-log-states))))
5179 (let* ((names (nreverse names))
5180 (done (if sep (org-remove-keyword-keys (cdr sep))
5181 (last names)))
5182 (head (car names))
5183 (tail (list sequence-type head (car done) (org-last done))))
5184 (add-to-list 'org-todo-heads head 'append)
5185 (push names org-todo-sets)
5186 (setq org-done-keywords (append org-done-keywords done nil))
5187 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5188 (setq org-todo-key-alist
5189 (append org-todo-key-alist
5190 (and alist
5191 (append '((:startgroup))
5192 (nreverse alist)
5193 '((:endgroup))))))
5194 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5195 (setq org-todo-sets (nreverse org-todo-sets)
5196 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5197 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5198 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5199 ;; Compute the regular expressions and other local variables.
5200 ;; Using `org-outline-regexp-bol' would complicate them much,
5201 ;; because of the fixed white space at the end of that string.
5202 (unless org-done-keywords
5203 (setq org-done-keywords
5204 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5205 (setq org-not-done-keywords
5206 (org-delete-all org-done-keywords
5207 (copy-sequence org-todo-keywords-1))
5208 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5209 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5210 org-not-done-heading-regexp
5211 (format org-heading-keyword-regexp-format org-not-done-regexp)
5212 org-todo-line-regexp
5213 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5214 org-complex-heading-regexp
5215 (concat "^\\(\\*+\\)"
5216 "\\(?: +" org-todo-regexp "\\)?"
5217 "\\(?: +\\(\\[#.\\]\\)\\)?"
5218 "\\(?: +\\(.*?\\)\\)??"
5219 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5220 "[ \t]*$")
5221 org-complex-heading-regexp-format
5222 (concat "^\\(\\*+\\)"
5223 "\\(?: +" org-todo-regexp "\\)?"
5224 "\\(?: +\\(\\[#.\\]\\)\\)?"
5225 "\\(?: +"
5226 ;; Stats cookies can be stuck to body.
5227 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5228 "\\(%s\\)"
5229 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5230 "\\)"
5231 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5232 "[ \t]*$")
5233 org-todo-line-tags-regexp
5234 (concat "^\\(\\*+\\)"
5235 "\\(?: +" org-todo-regexp "\\)?"
5236 "\\(?: +\\(.*?\\)\\)??"
5237 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5238 "[ \t]*$"))
5239 (org-compute-latex-and-related-regexp)))))
5241 (defun org--setup-collect-keywords (regexp &optional files alist)
5242 "Return setup keywords values as an alist.
5244 REGEXP matches a subset of setup keywords. FILES is a list of
5245 file names already visited. It is used to avoid circular setup
5246 files. ALIST, when non-nil, is the alist computed so far.
5248 Return value contains the following keys: `archive', `category',
5249 `columns', `constants', `filetags', `link', `priorities',
5250 `property', `scripts', `startup', `tags' and `todo'."
5251 (org-with-wide-buffer
5252 (goto-char (point-min))
5253 (let ((case-fold-search t))
5254 (while (re-search-forward regexp nil t)
5255 (let ((element (org-element-at-point)))
5256 (when (eq (org-element-type element) 'keyword)
5257 (let ((key (org-element-property :key element))
5258 (value (org-element-property :value element)))
5259 (cond
5260 ((equal key "ARCHIVE")
5261 (when (org-string-nw-p value)
5262 (push (cons 'archive value) alist)))
5263 ((equal key "CATEGORY") (push (cons 'category value) alist))
5264 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5265 ((equal key "CONSTANTS")
5266 (let* ((constants (assq 'constants alist))
5267 (store (cdr constants)))
5268 (dolist (pair (org-split-string value))
5269 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5270 pair)
5271 (let* ((name (match-string 1 pair))
5272 (value (match-string 2 pair))
5273 (old (assoc name store)))
5274 (if old (setcdr old value)
5275 (push (cons name value) store)))))
5276 (if constants (setcdr constants store)
5277 (push (cons 'constants store) alist))))
5278 ((equal key "FILETAGS")
5279 (when (org-string-nw-p value)
5280 (let ((old (assq 'filetags alist))
5281 (new (apply #'nconc
5282 (mapcar (lambda (x) (org-split-string x ":"))
5283 (org-split-string value)))))
5284 (if old (setcdr old (append new (cdr old)))
5285 (push (cons 'filetags new) alist)))))
5286 ((equal key "LINK")
5287 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5288 (let ((links (assq 'link alist))
5289 (pair (cons (match-string-no-properties 1 value)
5290 (match-string-no-properties 2 value))))
5291 (if links (push pair (cdr links))
5292 (push (list 'link pair) alist)))))
5293 ((equal key "OPTIONS")
5294 (when (and (org-string-nw-p value)
5295 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5296 (push (cons 'scripts (read (match-string 1 value))) alist)))
5297 ((equal key "PRIORITIES")
5298 (push (cons 'priorities
5299 (let ((prio (org-split-string value)))
5300 (if (< (length prio) 3) '(?A ?C ?B)
5301 (mapcar #'string-to-char prio))))
5302 alist))
5303 ((equal key "PROPERTY")
5304 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5305 (let* ((property (assq 'property alist))
5306 (value (org--update-property-plist
5307 (match-string-no-properties 1 value)
5308 (match-string-no-properties 2 value)
5309 (cdr property))))
5310 (if property (setcdr property value)
5311 (push (cons 'property value) alist)))))
5312 ((equal key "STARTUP")
5313 (let ((startup (assq 'startup alist)))
5314 (if startup
5315 (setcdr startup
5316 (append (cdr startup) (org-split-string value)))
5317 (push (cons 'startup (org-split-string value)) alist))))
5318 ((equal key "TAGS")
5319 (let ((tag-cell (assq 'tags alist)))
5320 (if tag-cell
5321 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5322 (push (cons 'tags value) alist))))
5323 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5324 (let ((todo (assq 'todo alist))
5325 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5326 (org-split-string value))))
5327 (if todo (push value (cdr todo))
5328 (push (list 'todo value) alist))))
5329 ((equal key "SETUPFILE")
5330 (unless buffer-read-only ; Do not check in Gnus messages.
5331 (let ((f (and (org-string-nw-p value)
5332 (expand-file-name
5333 (org-unbracket-string "\"" "\"" value)))))
5334 (when (and f (file-readable-p f) (not (member f files)))
5335 (with-temp-buffer
5336 (setq default-directory (file-name-directory f))
5337 (insert-file-contents f)
5338 (setq alist
5339 ;; Fake Org mode to benefit from cache
5340 ;; without recurring needlessly.
5341 (let ((major-mode 'org-mode))
5342 (org--setup-collect-keywords
5343 regexp (cons f files) alist)))))))))))))))
5344 alist)
5346 (defun org-tag-string-to-alist (s)
5347 "Return tag alist associated to string S.
5348 S is a value for TAGS keyword or produced with
5349 `org-tag-alist-to-string'. Return value is an alist suitable for
5350 `org-tag-alist' or `org-tag-persistent-alist'."
5351 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5352 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5353 "\\|{.+?}\\)" ; regular expression
5354 "\\(?:(\\(.\\))\\)?\\'"))
5355 alist group-flag)
5356 (dolist (tokens lines (cdr (nreverse alist)))
5357 (push '(:newline) alist)
5358 (while tokens
5359 (let ((token (pop tokens)))
5360 (pcase token
5361 ("{"
5362 (push '(:startgroup) alist)
5363 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5364 ("}"
5365 (push '(:endgroup) alist)
5366 (setq group-flag nil))
5367 ("["
5368 (push '(:startgrouptag) alist)
5369 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5370 ("]"
5371 (push '(:endgrouptag) alist)
5372 (setq group-flag nil))
5373 (":"
5374 (push '(:grouptags) alist))
5375 ((guard (string-match tag-re token))
5376 (let ((tag (match-string 1 token))
5377 (key (and (match-beginning 2)
5378 (string-to-char (match-string 2 token)))))
5379 ;; Push all tags in groups, no matter if they already
5380 ;; appear somewhere else in the list.
5381 (when (or group-flag (not (assoc tag alist)))
5382 (push (cons tag key) alist))))))))))
5384 (defun org-tag-alist-to-string (alist &optional skip-key)
5385 "Return tag string associated to ALIST.
5387 ALIST is an alist, as defined in `org-tag-alist' or
5388 `org-tag-persistent-alist', or produced with
5389 `org-tag-string-to-alist'.
5391 Return value is a string suitable as a value for \"TAGS\"
5392 keyword.
5394 When optional argument SKIP-KEY is non-nil, skip selection keys
5395 next to tags."
5396 (mapconcat (lambda (token)
5397 (pcase token
5398 (`(:startgroup) "{")
5399 (`(:endgroup) "}")
5400 (`(:startgrouptag) "[")
5401 (`(:endgrouptag) "]")
5402 (`(:grouptags) ":")
5403 (`(:newline) "\\n")
5404 ((and
5405 (guard (not skip-key))
5406 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5407 (format "%s(%c)" tag key))
5408 (`(,(and tag (pred stringp)) . ,_) tag)
5409 (_ (user-error "Invalid tag token: %S" token))))
5410 alist
5411 " "))
5413 (defun org-tag-alist-to-groups (alist)
5414 "Return group alist from tag ALIST.
5415 ALIST is an alist, as defined in `org-tag-alist' or
5416 `org-tag-persistent-alist', or produced with
5417 `org-tag-string-to-alist'. Return value is an alist following
5418 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5419 a string, summarizing TAGS, as a list of strings."
5420 (let (groups group-status current-group)
5421 (dolist (token alist (nreverse groups))
5422 (pcase token
5423 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5424 (`(,(or :endgroup :endgrouptag))
5425 (when (eq group-status 'append)
5426 (push (nreverse current-group) groups))
5427 (setq group-status nil))
5428 (`(:grouptags) (setq group-status 'append))
5429 ((and `(,tag . ,_) (guard group-status))
5430 (if (eq group-status 'append) (push tag current-group)
5431 (setq current-group (list tag))))
5432 (_ nil)))))
5434 (defun org-file-contents (file &optional noerror)
5435 "Return the contents of FILE, as a string."
5436 (if (and file (file-readable-p file))
5437 (with-temp-buffer
5438 (insert-file-contents file)
5439 (buffer-string))
5440 (funcall (if noerror 'message 'error)
5441 "Cannot read file \"%s\"%s"
5442 file
5443 (let ((from (buffer-file-name (buffer-base-buffer))))
5444 (if from (concat " (referenced in file \"" from "\")") "")))))
5446 (defun org-extract-log-state-settings (x)
5447 "Extract the log state setting from a TODO keyword string.
5448 This will extract info from a string like \"WAIT(w@/!)\"."
5449 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5450 (let ((kw (match-string 1 x))
5451 (log1 (and (match-end 3) (match-string 3 x)))
5452 (log2 (and (match-end 4) (match-string 4 x))))
5453 (and (or log1 log2)
5454 (list kw
5455 (and log1 (if (equal log1 "!") 'time 'note))
5456 (and log2 (if (equal log2 "!") 'time 'note)))))))
5458 (defun org-remove-keyword-keys (list)
5459 "Remove a pair of parenthesis at the end of each string in LIST."
5460 (mapcar (lambda (x)
5461 (if (string-match "(.*)$" x)
5462 (substring x 0 (match-beginning 0))
5464 list))
5466 (defun org-assign-fast-keys (alist)
5467 "Assign fast keys to a keyword-key alist.
5468 Respect keys that are already there."
5469 (let (new e (alt ?0))
5470 (while (setq e (pop alist))
5471 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5472 (cdr e)) ;; Key already assigned.
5473 (push e new)
5474 (let ((clist (string-to-list (downcase (car e))))
5475 (used (append new alist)))
5476 (when (= (car clist) ?@)
5477 (pop clist))
5478 (while (and clist (rassoc (car clist) used))
5479 (pop clist))
5480 (unless clist
5481 (while (rassoc alt used)
5482 (cl-incf alt)))
5483 (push (cons (car e) (or (car clist) alt)) new))))
5484 (nreverse new)))
5486 ;;; Some variables used in various places
5488 (defvar org-window-configuration nil
5489 "Used in various places to store a window configuration.")
5490 (defvar org-selected-window nil
5491 "Used in various places to store a window configuration.")
5492 (defvar org-finish-function nil
5493 "Function to be called when `C-c C-c' is used.
5494 This is for getting out of special buffers like capture.")
5495 (defvar org-last-state)
5497 ;; Defined somewhere in this file, but used before definition.
5498 (defvar org-entities) ;; defined in org-entities.el
5499 (defvar org-struct-menu)
5500 (defvar org-org-menu)
5501 (defvar org-tbl-menu)
5503 ;;;; Define the Org mode
5505 ;; We use a before-change function to check if a table might need
5506 ;; an update.
5507 (defvar org-table-may-need-update t
5508 "Indicates that a table might need an update.
5509 This variable is set by `org-before-change-function'.
5510 `org-table-align' sets it back to nil.")
5511 (defun org-before-change-function (_beg _end)
5512 "Every change indicates that a table might need an update."
5513 (setq org-table-may-need-update t))
5514 (defvar org-mode-map)
5515 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5516 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5517 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5518 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5519 (defvar org-table-buffer-is-an nil)
5521 (defvar bidi-paragraph-direction)
5522 (defvar buffer-face-mode-face)
5524 (require 'outline)
5526 ;; Other stuff we need.
5527 (require 'time-date)
5528 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5529 (require 'easymenu)
5530 (autoload 'easy-menu-add "easymenu")
5531 (require 'overlay)
5533 ;; (require 'org-macs) moved higher up in the file before it is first used
5534 (require 'org-entities)
5535 ;; (require 'org-compat) moved higher up in the file before it is first used
5536 (require 'org-faces)
5537 (require 'org-list)
5538 (require 'org-pcomplete)
5539 (require 'org-src)
5540 (require 'org-footnote)
5541 (require 'org-macro)
5543 ;; babel
5544 (require 'ob)
5546 ;;;###autoload
5547 (define-derived-mode org-mode outline-mode "Org"
5548 "Outline-based notes management and organizer, alias
5549 \"Carsten's outline-mode for keeping track of everything.\"
5551 Org mode develops organizational tasks around a NOTES file which
5552 contains information about projects as plain text. Org mode is
5553 implemented on top of Outline mode, which is ideal to keep the content
5554 of large files well structured. It supports ToDo items, deadlines and
5555 time stamps, which magically appear in the diary listing of the Emacs
5556 calendar. Tables are easily created with a built-in table editor.
5557 Plain text URL-like links connect to websites, emails (VM), Usenet
5558 messages (Gnus), BBDB entries, and any files related to the project.
5559 For printing and sharing of notes, an Org file (or a part of it)
5560 can be exported as a structured ASCII or HTML file.
5562 The following commands are available:
5564 \\{org-mode-map}"
5566 ;; Get rid of Outline menus, they are not needed
5567 ;; Need to do this here because define-derived-mode sets up
5568 ;; the keymap so late. Still, it is a waste to call this each time
5569 ;; we switch another buffer into Org mode.
5570 (define-key org-mode-map [menu-bar headings] 'undefined)
5571 (define-key org-mode-map [menu-bar hide] 'undefined)
5572 (define-key org-mode-map [menu-bar show] 'undefined)
5574 (org-load-modules-maybe)
5575 (org-install-agenda-files-menu)
5576 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5577 (add-to-invisibility-spec '(org-cwidth))
5578 (add-to-invisibility-spec '(org-hide-block . t))
5579 (setq-local outline-regexp org-outline-regexp)
5580 (setq-local outline-level 'org-outline-level)
5581 (setq bidi-paragraph-direction 'left-to-right)
5582 (when (and org-ellipsis
5583 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5584 (fboundp 'make-glyph-code))
5585 (unless org-display-table
5586 (setq org-display-table (make-display-table)))
5587 (set-display-table-slot
5588 org-display-table 4
5589 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5590 (if (stringp org-ellipsis) org-ellipsis "..."))))
5591 (setq buffer-display-table org-display-table))
5592 (org-set-regexps-and-options)
5593 (org-set-font-lock-defaults)
5594 (when (and org-tag-faces (not org-tags-special-faces-re))
5595 ;; tag faces set outside customize.... force initialization.
5596 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5597 ;; Calc embedded
5598 (setq-local calc-embedded-open-mode "# ")
5599 ;; Modify a few syntax entries
5600 (modify-syntax-entry ?@ "w")
5601 (modify-syntax-entry ?\" "\"")
5602 (modify-syntax-entry ?\\ "_")
5603 (modify-syntax-entry ?~ "_")
5604 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5605 ;; Activate before-change-function
5606 (setq-local org-table-may-need-update t)
5607 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5608 ;; Check for running clock before killing a buffer
5609 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5610 ;; Initialize macros templates.
5611 (org-macro-initialize-templates)
5612 ;; Initialize radio targets.
5613 (org-update-radio-target-regexp)
5614 ;; Indentation.
5615 (setq-local indent-line-function 'org-indent-line)
5616 (setq-local indent-region-function 'org-indent-region)
5617 ;; Filling and auto-filling.
5618 (org-setup-filling)
5619 ;; Comments.
5620 (org-setup-comments-handling)
5621 ;; Initialize cache.
5622 (org-element-cache-reset)
5623 ;; Beginning/end of defun
5624 (setq-local beginning-of-defun-function 'org-backward-element)
5625 (setq-local end-of-defun-function
5626 (lambda ()
5627 (if (not (org-at-heading-p))
5628 (org-forward-element)
5629 (org-forward-element)
5630 (forward-char -1))))
5631 ;; Next error for sparse trees
5632 (setq-local next-error-function 'org-occur-next-match)
5633 ;; Make sure dependence stuff works reliably, even for users who set it
5634 ;; too late :-(
5635 (if org-enforce-todo-dependencies
5636 (add-hook 'org-blocker-hook
5637 'org-block-todo-from-children-or-siblings-or-parent)
5638 (remove-hook 'org-blocker-hook
5639 'org-block-todo-from-children-or-siblings-or-parent))
5640 (if org-enforce-todo-checkbox-dependencies
5641 (add-hook 'org-blocker-hook
5642 'org-block-todo-from-checkboxes)
5643 (remove-hook 'org-blocker-hook
5644 'org-block-todo-from-checkboxes))
5646 ;; Align options lines
5647 (setq-local
5648 align-mode-rules-list
5649 '((org-in-buffer-settings
5650 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5651 (modes . '(org-mode)))))
5653 ;; Imenu
5654 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5656 ;; Make isearch reveal context
5657 (setq-local outline-isearch-open-invisible-function
5658 (lambda (&rest _) (org-show-context 'isearch)))
5660 ;; Setup the pcomplete hooks
5661 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5662 (setq-local pcomplete-command-name-function 'org-command-at-point)
5663 (setq-local pcomplete-default-completion-function 'ignore)
5664 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5665 (setq-local pcomplete-termination-string "")
5666 (setq-local buffer-face-mode-face 'org-default)
5668 ;; If empty file that did not turn on Org mode automatically, make
5669 ;; it to.
5670 (when (and org-insert-mode-line-in-empty-file
5671 (called-interactively-p 'any)
5672 (= (point-min) (point-max)))
5673 (insert "# -*- mode: org -*-\n\n"))
5674 (unless org-inhibit-startup
5675 (org-unmodified
5676 (when org-startup-with-beamer-mode (org-beamer-mode))
5677 (when org-startup-align-all-tables
5678 (org-table-map-tables #'org-table-align t))
5679 (when org-startup-with-inline-images (org-display-inline-images))
5680 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5681 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5682 (when org-startup-truncated (setq truncate-lines t))
5683 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5684 (org-refresh-effort-properties)))
5685 ;; Try to set `org-hide' face correctly.
5686 (let ((foreground (org-find-invisible-foreground)))
5687 (when foreground
5688 (set-face-foreground 'org-hide foreground))))
5690 ;; Update `customize-package-emacs-version-alist'
5691 (add-to-list 'customize-package-emacs-version-alist
5692 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5693 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5694 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5695 ("9.0" . "25.2")))
5697 (defvar org-mode-transpose-word-syntax-table
5698 (let ((st (make-syntax-table text-mode-syntax-table)))
5699 (dolist (c org-emphasis-alist st)
5700 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5702 (when (fboundp 'abbrev-table-put)
5703 (abbrev-table-put org-mode-abbrev-table
5704 :parents (list text-mode-abbrev-table)))
5706 (defun org-find-invisible-foreground ()
5707 (let ((candidates (remove
5708 "unspecified-bg"
5709 (nconc
5710 (list (face-background 'default)
5711 (face-background 'org-default))
5712 (mapcar
5713 (lambda (alist)
5714 (when (boundp alist)
5715 (cdr (assq 'background-color (symbol-value alist)))))
5716 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5717 (list (face-foreground 'org-hide))))))
5718 (car (remove nil candidates))))
5720 (defun org-current-time (&optional rounding-minutes past)
5721 "Current time, possibly rounded to ROUNDING-MINUTES.
5722 When ROUNDING-MINUTES is not an integer, fall back on the car of
5723 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5724 the rounding returns a past time."
5725 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5726 (car org-time-stamp-rounding-minutes)))
5727 (time (decode-time)) res)
5728 (if (< r 1)
5729 (current-time)
5730 (setq res
5731 (apply 'encode-time
5732 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5733 (nthcdr 2 time))))
5734 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5735 (seconds-to-time (- (float-time res) (* r 60)))
5736 res))))
5738 (defun org-today ()
5739 "Return today date, considering `org-extend-today-until'."
5740 (time-to-days
5741 (time-subtract (current-time)
5742 (list 0 (* 3600 org-extend-today-until) 0))))
5744 ;;;; Font-Lock stuff, including the activators
5746 (defvar org-mouse-map (make-sparse-keymap))
5747 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5748 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5749 (when org-mouse-1-follows-link
5750 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5751 (when org-tab-follows-link
5752 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5753 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5755 (require 'font-lock)
5757 (defconst org-non-link-chars "]\t\n\r<>")
5758 (defvar org-link-types-re nil
5759 "Matches a link that has a url-like prefix like \"http:\"")
5760 (defvar org-link-re-with-space nil
5761 "Matches a link with spaces, optional angular brackets around it.")
5762 (defvar org-link-re-with-space2 nil
5763 "Matches a link with spaces, optional angular brackets around it.")
5764 (defvar org-link-re-with-space3 nil
5765 "Matches a link with spaces, only for internal part in bracket links.")
5766 (defvar org-angle-link-re nil
5767 "Matches link with angular brackets, spaces are allowed.")
5768 (defvar org-plain-link-re nil
5769 "Matches plain link, without spaces.")
5770 (defvar org-bracket-link-regexp nil
5771 "Matches a link in double brackets.")
5772 (defvar org-bracket-link-analytic-regexp nil
5773 "Regular expression used to analyze links.
5774 Here is what the match groups contain after a match:
5775 1: http:
5776 2: http
5777 3: path
5778 4: [desc]
5779 5: desc")
5780 (defvar org-bracket-link-analytic-regexp++ nil
5781 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5782 (defvar org-any-link-re nil
5783 "Regular expression matching any link.")
5785 (defconst org-match-sexp-depth 3
5786 "Number of stacked braces for sub/superscript matching.")
5788 (defun org-create-multibrace-regexp (left right n)
5789 "Create a regular expression which will match a balanced sexp.
5790 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5791 as single character strings.
5792 The regexp returned will match the entire expression including the
5793 delimiters. It will also define a single group which contains the
5794 match except for the outermost delimiters. The maximum depth of
5795 stacked delimiters is N. Escaping delimiters is not possible."
5796 (let* ((nothing (concat "[^" left right "]*?"))
5797 (or "\\|")
5798 (re nothing)
5799 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5800 (while (> n 1)
5801 (setq n (1- n)
5802 re (concat re or next)
5803 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5804 (concat left "\\(" re "\\)" right)))
5806 (defconst org-match-substring-regexp
5807 (concat
5808 "\\(\\S-\\)\\([_^]\\)\\("
5809 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5810 "\\|"
5811 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5812 "\\|"
5813 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5814 "The regular expression matching a sub- or superscript.")
5816 (defconst org-match-substring-with-braces-regexp
5817 (concat
5818 "\\(\\S-\\)\\([_^]\\)"
5819 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5820 "The regular expression matching a sub- or superscript, forcing braces.")
5822 (defun org-make-link-regexps ()
5823 "Update the link regular expressions.
5824 This should be called after the variable `org-link-parameters' has changed."
5825 (let ((types-re (regexp-opt (org-link-types) t)))
5826 (setq org-link-types-re
5827 (concat "\\`" types-re ":")
5828 org-link-re-with-space
5829 (concat "<?" types-re ":"
5830 "\\([^" org-non-link-chars " ]"
5831 "[^" org-non-link-chars "]*"
5832 "[^" org-non-link-chars " ]\\)>?")
5833 org-link-re-with-space2
5834 (concat "<?" types-re ":"
5835 "\\([^" org-non-link-chars " ]"
5836 "[^\t\n\r]*"
5837 "[^" org-non-link-chars " ]\\)>?")
5838 org-link-re-with-space3
5839 (concat "<?" types-re ":"
5840 "\\([^" org-non-link-chars " ]"
5841 "[^\t\n\r]*\\)")
5842 org-angle-link-re
5843 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5844 types-re)
5845 org-plain-link-re
5846 (concat
5847 "\\<" types-re ":"
5848 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5849 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5850 org-bracket-link-regexp
5851 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5852 org-bracket-link-analytic-regexp
5853 (concat
5854 "\\[\\["
5855 "\\(" types-re ":\\)?"
5856 "\\([^]]+\\)"
5857 "\\]"
5858 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5859 "\\]")
5860 org-bracket-link-analytic-regexp++
5861 (concat
5862 "\\[\\["
5863 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5864 "\\([^]]+\\)"
5865 "\\]"
5866 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5867 "\\]")
5868 org-any-link-re
5869 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5870 org-angle-link-re "\\)\\|\\("
5871 org-plain-link-re "\\)"))))
5873 (org-make-link-regexps)
5875 (defvar org-emph-face nil)
5877 (defun org-do-emphasis-faces (limit)
5878 "Run through the buffer and emphasize strings."
5879 (let (rtn a)
5880 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5881 (let* ((border (char-after (match-beginning 3)))
5882 (bre (regexp-quote (char-to-string border))))
5883 (when (and (not (= border (char-after (match-beginning 4))))
5884 (not (string-match-p (concat bre ".*" bre)
5885 (replace-regexp-in-string
5886 "\n" " "
5887 (substring (match-string 2) 1 -1)))))
5888 (setq rtn t)
5889 (setq a (assoc (match-string 3) org-emphasis-alist))
5890 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5891 'face
5892 (nth 1 a))
5893 (and (nth 2 a)
5894 (org-remove-flyspell-overlays-in
5895 (match-beginning 0) (match-end 0)))
5896 (add-text-properties (match-beginning 2) (match-end 2)
5897 '(font-lock-multiline t org-emphasis t))
5898 (when org-hide-emphasis-markers
5899 (add-text-properties (match-end 4) (match-beginning 5)
5900 '(invisible org-link))
5901 (add-text-properties (match-beginning 3) (match-end 3)
5902 '(invisible org-link)))))
5903 (goto-char (1+ (match-beginning 0))))
5904 rtn))
5906 (defun org-emphasize (&optional char)
5907 "Insert or change an emphasis, i.e. a font like bold or italic.
5908 If there is an active region, change that region to a new emphasis.
5909 If there is no region, just insert the marker characters and position
5910 the cursor between them.
5911 CHAR should be the marker character. If it is a space, it means to
5912 remove the emphasis of the selected region.
5913 If CHAR is not given (for example in an interactive call) it will be
5914 prompted for."
5915 (interactive)
5916 (let ((erc org-emphasis-regexp-components)
5917 (string "") beg end move s)
5918 (if (org-region-active-p)
5919 (setq beg (region-beginning)
5920 end (region-end)
5921 string (buffer-substring beg end))
5922 (setq move t))
5924 (unless char
5925 (message "Emphasis marker or tag: [%s]"
5926 (mapconcat #'car org-emphasis-alist ""))
5927 (setq char (read-char-exclusive)))
5928 (if (equal char ?\s)
5929 (setq s ""
5930 move nil)
5931 (unless (assoc (char-to-string char) org-emphasis-alist)
5932 (user-error "No such emphasis marker: \"%c\"" char))
5933 (setq s (char-to-string char)))
5934 (while (and (> (length string) 1)
5935 (equal (substring string 0 1) (substring string -1))
5936 (assoc (substring string 0 1) org-emphasis-alist))
5937 (setq string (substring string 1 -1)))
5938 (setq string (concat s string s))
5939 (when beg (delete-region beg end))
5940 (unless (or (bolp)
5941 (string-match (concat "[" (nth 0 erc) "\n]")
5942 (char-to-string (char-before (point)))))
5943 (insert " "))
5944 (unless (or (eobp)
5945 (string-match (concat "[" (nth 1 erc) "\n]")
5946 (char-to-string (char-after (point)))))
5947 (insert " ") (backward-char 1))
5948 (insert string)
5949 (and move (backward-char 1))))
5951 (defconst org-nonsticky-props
5952 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5954 (defsubst org-rear-nonsticky-at (pos)
5955 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5957 (defun org-activate-plain-links (limit)
5958 "Add link properties for plain links."
5959 (when (and (re-search-forward org-plain-link-re limit t)
5960 (not (org-in-src-block-p)))
5962 (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5963 'face))
5964 (link (match-string-no-properties 0))
5965 (type (match-string-no-properties 1))
5966 (path (match-string-no-properties 2))
5967 (link-start (match-beginning 0))
5968 (link-end (match-end 0))
5969 (link-face (org-link-get-parameter type :face))
5970 (help-echo (org-link-get-parameter type :help-echo))
5971 (htmlize-link (org-link-get-parameter type :htmlize-link))
5972 (activate-func (org-link-get-parameter type :activate-func)))
5973 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5974 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5975 (add-text-properties (match-beginning 0) (match-end 0)
5976 (list
5977 'mouse-face (or (org-link-get-parameter type :mouse-face)
5978 'highlight)
5979 'face (cond
5980 ;; A function that returns a face
5981 ((functionp link-face)
5982 (funcall link-face path))
5983 ;; a face
5984 ((facep link-face)
5985 link-face)
5986 ;; An anonymous face
5987 ((consp link-face)
5988 link-face)
5989 ;; default
5991 'org-link))
5992 'help-echo (cond
5993 ((stringp help-echo)
5994 help-echo)
5995 ((functionp help-echo)
5996 help-echo)
5998 (concat "LINK: "
5999 (save-match-data
6000 (org-link-unescape link)))))
6001 'htmlize-link (cond
6002 ((functionp htmlize-link)
6003 (funcall htmlize-link path))
6005 `(:uri ,link)))
6006 'keymap (or (org-link-get-parameter type :keymap)
6007 org-mouse-map)
6008 'org-link-start (match-beginning 0)))
6009 (org-rear-nonsticky-at (match-end 0))
6010 (when activate-func
6011 (funcall activate-func link-start link-end path nil))
6012 t))))
6014 (defun org-activate-code (limit)
6015 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
6016 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6017 (remove-text-properties (match-beginning 0) (match-end 0)
6018 '(display t invisible t intangible t))
6021 (defcustom org-src-fontify-natively t
6022 "When non-nil, fontify code in code blocks.
6023 See also the `org-block' face."
6024 :type 'boolean
6025 :version "24.4"
6026 :package-version '(Org . "8.3")
6027 :group 'org-appearance
6028 :group 'org-babel)
6030 (defcustom org-allow-promoting-top-level-subtree nil
6031 "When non-nil, allow promoting a top level subtree.
6032 The leading star of the top level headline will be replaced
6033 by a #."
6034 :type 'boolean
6035 :version "24.1"
6036 :group 'org-appearance)
6038 (defun org-fontify-meta-lines-and-blocks (limit)
6039 (condition-case nil
6040 (org-fontify-meta-lines-and-blocks-1 limit)
6041 (error (message "org-mode fontification error in %S at %d"
6042 (current-buffer)
6043 (line-number-at-pos)))))
6045 (defun org-fontify-meta-lines-and-blocks-1 (limit)
6046 "Fontify #+ lines and blocks."
6047 (let ((case-fold-search t))
6048 (when (re-search-forward
6049 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
6050 limit t)
6051 (let ((beg (match-beginning 0))
6052 (block-start (match-end 0))
6053 (block-end nil)
6054 (lang (match-string 7))
6055 (beg1 (line-beginning-position 2))
6056 (dc1 (downcase (match-string 2)))
6057 (dc3 (downcase (match-string 3)))
6058 end end1 quoting block-type)
6059 (cond
6060 ((and (match-end 4) (equal dc3 "+begin"))
6061 ;; Truly a block
6062 (setq block-type (downcase (match-string 5))
6063 quoting (member block-type org-protecting-blocks))
6064 (when (re-search-forward
6065 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
6066 nil t) ;; on purpose, we look further than LIMIT
6067 (setq end (min (point-max) (match-end 0))
6068 end1 (min (point-max) (1- (match-beginning 0))))
6069 (setq block-end (match-beginning 0))
6070 (when quoting
6071 (org-remove-flyspell-overlays-in beg1 end1)
6072 (remove-text-properties beg end
6073 '(display t invisible t intangible t)))
6074 (add-text-properties
6075 beg end '(font-lock-fontified t font-lock-multiline t))
6076 (add-text-properties beg beg1 '(face org-meta-line))
6077 (org-remove-flyspell-overlays-in beg beg1)
6078 (add-text-properties ; For end_src
6079 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6080 (org-remove-flyspell-overlays-in end1 end)
6081 (cond
6082 ((and lang (not (string= lang "")) org-src-fontify-natively)
6083 (org-src-font-lock-fontify-block lang block-start block-end)
6084 (add-text-properties beg1 block-end '(src-block t)))
6085 (quoting
6086 (add-text-properties beg1 (min (point-max) (1+ end1))
6087 (list 'face
6088 (list :inherit
6089 (let ((face-name
6090 (intern (format "org-block-%s" lang))))
6091 (append (and (facep face-name) (list face-name))
6092 '(org-block))))))) ; end of source block
6093 ((not org-fontify-quote-and-verse-blocks))
6094 ((string= block-type "quote")
6095 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
6096 ((string= block-type "verse")
6097 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
6098 (add-text-properties beg beg1 '(face org-block-begin-line))
6099 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6100 '(face org-block-end-line))
6102 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6103 (org-remove-flyspell-overlays-in
6104 (match-beginning 0)
6105 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6106 (add-text-properties
6107 beg (match-end 3)
6108 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6109 '(font-lock-fontified t invisible t)
6110 '(font-lock-fontified t face org-document-info-keyword)))
6111 (add-text-properties
6112 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6113 (if (string-equal dc1 "+title:")
6114 '(font-lock-fontified t face org-document-title)
6115 '(font-lock-fontified t face org-document-info))))
6116 ((string-prefix-p "+caption" dc1)
6117 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6118 (remove-text-properties (match-beginning 0) (match-end 0)
6119 '(display t invisible t intangible t))
6120 ;; Handle short captions.
6121 (save-excursion
6122 (beginning-of-line)
6123 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6124 (add-text-properties (line-beginning-position) (match-end 1)
6125 '(font-lock-fontified t face org-meta-line))
6126 (add-text-properties (match-end 0) (line-end-position)
6127 '(font-lock-fontified t face org-block))
6129 ((member dc3 '(" " ""))
6130 (org-remove-flyspell-overlays-in beg (match-end 0))
6131 (add-text-properties
6132 beg (match-end 0)
6133 '(font-lock-fontified t face font-lock-comment-face)))
6134 (t ;; just any other in-buffer setting, but not indented
6135 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6136 (remove-text-properties (match-beginning 0) (match-end 0)
6137 '(display t invisible t intangible t))
6138 (add-text-properties beg (match-end 0)
6139 '(font-lock-fontified t face org-meta-line))
6140 t))))))
6142 (defun org-fontify-drawers (limit)
6143 "Fontify drawers."
6144 (when (re-search-forward org-drawer-regexp limit t)
6145 (add-text-properties
6146 (match-beginning 0) (match-end 0)
6147 '(font-lock-fontified t face org-special-keyword))
6148 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6151 (defun org-fontify-macros (limit)
6152 "Fontify macros."
6153 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6154 (add-text-properties
6155 (match-beginning 0) (match-end 0)
6156 '(font-lock-fontified t face org-macro))
6157 (when org-hide-macro-markers
6158 (add-text-properties (match-end 2) (match-beginning 2)
6159 '(invisible t))
6160 (add-text-properties (match-beginning 1) (match-end 1)
6161 '(invisible t)))
6162 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6165 (defun org-activate-angle-links (limit)
6166 "Add text properties for angle links."
6167 (when (and (re-search-forward org-angle-link-re limit t)
6168 (not (org-in-src-block-p)))
6169 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6170 (add-text-properties (match-beginning 0) (match-end 0)
6171 (list 'mouse-face 'highlight
6172 'keymap org-mouse-map
6173 'font-lock-multiline t))
6174 (org-rear-nonsticky-at (match-end 0))
6177 (defun org-activate-footnote-links (limit)
6178 "Add text properties for footnotes."
6179 (let ((fn (org-footnote-next-reference-or-definition limit)))
6180 (when fn
6181 (let* ((beg (nth 1 fn))
6182 (end (nth 2 fn))
6183 (label (car fn))
6184 (referencep (/= (line-beginning-position) beg)))
6185 (when (and referencep (nth 3 fn))
6186 (save-excursion
6187 (goto-char beg)
6188 (search-forward (or label "fn:"))
6189 (org-remove-flyspell-overlays-in beg (match-end 0))))
6190 (add-text-properties beg end
6191 (list 'mouse-face 'highlight
6192 'keymap org-mouse-map
6193 'help-echo
6194 (if referencep "Footnote reference"
6195 "Footnote definition")
6196 'font-lock-fontified t
6197 'font-lock-multiline t
6198 'face 'org-footnote))))))
6200 (defun org-activate-bracket-links (limit)
6201 "Add text properties for bracketed links."
6202 (when (and (re-search-forward org-bracket-link-regexp limit t)
6203 (not (org-in-src-block-p)))
6204 (let* ((hl (save-match-data
6205 (org-link-expand-abbrev (match-string-no-properties 1))))
6206 (type (save-match-data
6207 (and (string-match org-plain-link-re hl)
6208 (match-string-no-properties 1 hl))))
6209 (path (save-match-data
6210 (and (string-match org-plain-link-re hl)
6211 (match-string-no-properties 2 hl))))
6212 (link-start (match-beginning 0))
6213 (link-end (match-end 0))
6214 (bracketp t)
6215 (help-echo (org-link-get-parameter type :help-echo))
6216 (help (cond
6217 ((stringp help-echo)
6218 help-echo)
6219 ((functionp help-echo)
6220 help-echo)
6222 (concat "LINK: "
6223 (save-match-data
6224 (org-link-unescape hl))))))
6225 (link-face (org-link-get-parameter type :face))
6226 (face (cond
6227 ;; A function that returns a face
6228 ((functionp link-face)
6229 (funcall link-face path))
6230 ;; a face
6231 ((facep link-face)
6232 link-face)
6233 ;; An anonymous face
6234 ((consp link-face)
6235 link-face)
6236 ;; default
6238 'org-link)))
6239 (keymap (or (org-link-get-parameter type :keymap)
6240 org-mouse-map))
6241 (mouse-face (or (org-link-get-parameter type :mouse-face)
6242 'highlight))
6243 (htmlize (org-link-get-parameter type :htmlize-link))
6244 (htmlize-link (cond
6245 ((functionp htmlize)
6246 (funcall htmlize))
6248 `(:uri ,(format "%s:%s" type path)))))
6249 (activate-func (org-link-get-parameter type :activate-func))
6250 ;; invisible part
6251 (ip (list 'invisible (or
6252 (org-link-get-parameter type :display)
6253 'org-link)
6254 'face face
6255 'keymap keymap
6256 'mouse-face mouse-face
6257 'font-lock-multiline t
6258 'help-echo help
6259 'htmlize-link htmlize-link))
6260 ;; visible part
6261 (vp (list 'keymap keymap
6262 'face face
6263 'mouse-face mouse-face
6264 'font-lock-multiline t
6265 'help-echo help
6266 'htmlize-link htmlize-link)))
6267 ;; We need to remove the invisible property here. Table narrowing
6268 ;; may have made some of this invisible.
6269 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6270 (remove-text-properties (match-beginning 0) (match-end 0)
6271 '(invisible nil))
6272 (if (match-end 3)
6273 (progn
6274 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6275 (org-rear-nonsticky-at (match-beginning 3))
6276 (add-text-properties (match-beginning 3) (match-end 3) vp)
6277 (org-rear-nonsticky-at (match-end 3))
6278 (add-text-properties (match-end 3) (match-end 0) ip)
6279 (org-rear-nonsticky-at (match-end 0)))
6280 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6281 (org-rear-nonsticky-at (match-beginning 1))
6282 (add-text-properties (match-beginning 1) (match-end 1) vp)
6283 (org-rear-nonsticky-at (match-end 1))
6284 (add-text-properties (match-end 1) (match-end 0) ip)
6285 (org-rear-nonsticky-at (match-end 0)))
6286 (when activate-func
6287 (funcall activate-func link-start link-end path bracketp))
6288 t)))
6290 (defun org-activate-dates (limit)
6291 "Add text properties for dates."
6292 (when (and (re-search-forward org-tsr-regexp-both limit t)
6293 (not (equal (char-before (match-beginning 0)) 91)))
6294 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6295 (add-text-properties (match-beginning 0) (match-end 0)
6296 (list 'mouse-face 'highlight
6297 'keymap org-mouse-map))
6298 (org-rear-nonsticky-at (match-end 0))
6299 (when org-display-custom-times
6300 (if (match-end 3)
6301 (org-display-custom-time (match-beginning 3) (match-end 3))
6302 (org-display-custom-time (match-beginning 1) (match-end 1))))
6305 (defvar-local org-target-link-regexp nil
6306 "Regular expression matching radio targets in plain text.")
6308 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6309 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6310 border border border))
6311 "Regular expression matching a link target.")
6313 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6314 "Regular expression matching a radio target.")
6316 (defconst org-any-target-regexp
6317 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6318 "Regular expression matching any target.")
6320 (defun org-activate-target-links (limit)
6321 "Add text properties for target matches."
6322 (when org-target-link-regexp
6323 (let ((case-fold-search t))
6324 (when (re-search-forward org-target-link-regexp limit t)
6325 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6326 (add-text-properties (match-beginning 1) (match-end 1)
6327 (list 'mouse-face 'highlight
6328 'keymap org-mouse-map
6329 'help-echo "Radio target link"
6330 'org-linked-text t))
6331 (org-rear-nonsticky-at (match-end 1))
6332 t))))
6334 (defun org-update-radio-target-regexp ()
6335 "Find all radio targets in this file and update the regular expression.
6336 Also refresh fontification if needed."
6337 (interactive)
6338 (let ((old-regexp org-target-link-regexp)
6339 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6340 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6341 (targets
6342 (org-with-wide-buffer
6343 (goto-char (point-min))
6344 (let (rtn)
6345 (while (re-search-forward org-radio-target-regexp nil t)
6346 ;; Make sure point is really within the object.
6347 (backward-char)
6348 (let ((obj (org-element-context)))
6349 (when (eq (org-element-type obj) 'radio-target)
6350 (cl-pushnew (org-element-property :value obj) rtn
6351 :test #'equal))))
6352 rtn))))
6353 (setq org-target-link-regexp
6354 (and targets
6355 (concat before-re
6356 (mapconcat
6357 (lambda (x)
6358 (replace-regexp-in-string
6359 " +" "\\s-+" (regexp-quote x) t t))
6360 targets
6361 "\\|")
6362 after-re)))
6363 (unless (equal old-regexp org-target-link-regexp)
6364 ;; Clean-up cache.
6365 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6366 ((not org-target-link-regexp) old-regexp)
6368 (concat before-re
6369 (mapconcat
6370 (lambda (re)
6371 (substring re (length before-re)
6372 (- (length after-re))))
6373 (list old-regexp org-target-link-regexp)
6374 "\\|")
6375 after-re)))))
6376 (org-with-wide-buffer
6377 (goto-char (point-min))
6378 (while (re-search-forward regexp nil t)
6379 (org-element-cache-refresh (match-beginning 1)))))
6380 ;; Re fontify buffer.
6381 (when (memq 'radio org-highlight-links)
6382 (org-restart-font-lock)))))
6384 (defun org-hide-wide-columns (limit)
6385 (let (s e)
6386 (setq s (text-property-any (point) (or limit (point-max))
6387 'org-cwidth t))
6388 (when s
6389 (setq e (next-single-property-change s 'org-cwidth))
6390 (add-text-properties s e '(invisible org-cwidth))
6391 (goto-char e)
6392 t)))
6394 (defvar org-latex-and-related-regexp nil
6395 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6397 (defun org-compute-latex-and-related-regexp ()
6398 "Compute regular expression for LaTeX, entities and sub/superscript.
6399 Result depends on variable `org-highlight-latex-and-related'."
6400 (setq-local
6401 org-latex-and-related-regexp
6402 (let* ((re-sub
6403 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6404 ((eq org-use-sub-superscripts '{})
6405 (list org-match-substring-with-braces-regexp))
6406 (org-use-sub-superscripts (list org-match-substring-regexp))))
6407 (re-latex
6408 (when (memq 'latex org-highlight-latex-and-related)
6409 (let ((matchers (plist-get org-format-latex-options :matchers)))
6410 (delq nil
6411 (mapcar (lambda (x)
6412 (and (member (car x) matchers) (nth 1 x)))
6413 org-latex-regexps)))))
6414 (re-entities
6415 (when (memq 'entities org-highlight-latex-and-related)
6416 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6417 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6419 (defun org-do-latex-and-related (limit)
6420 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6421 LIMIT bounds the search for syntax to highlight. Stop at first
6422 highlighted object, if any. Return t if some highlighting was
6423 done, nil otherwise."
6424 (when (org-string-nw-p org-latex-and-related-regexp)
6425 (catch 'found
6426 (while (re-search-forward org-latex-and-related-regexp limit t)
6427 (unless
6428 (cl-some
6429 (lambda (f)
6430 (memq f '(org-code org-verbatim underline org-special-keyword)))
6431 (save-excursion
6432 (goto-char (1+ (match-beginning 0)))
6433 (face-at-point nil t)))
6434 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6435 '(?_ ?^))
6437 0)))
6438 (font-lock-prepend-text-property
6439 (+ offset (match-beginning 0)) (match-end 0)
6440 'face 'org-latex-and-related)
6441 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6442 '(font-lock-multiline t)))
6443 (throw 'found t)))
6444 nil)))
6446 (defun org-restart-font-lock ()
6447 "Restart `font-lock-mode', to force refontification."
6448 (when (and (boundp 'font-lock-mode) font-lock-mode)
6449 (font-lock-mode -1)
6450 (font-lock-mode 1)))
6452 (defun org-activate-tags (limit)
6453 (when (re-search-forward
6454 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6455 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6456 (add-text-properties (match-beginning 1) (match-end 1)
6457 (list 'mouse-face 'highlight
6458 'keymap org-mouse-map))
6459 (org-rear-nonsticky-at (match-end 1))
6462 (defun org-outline-level ()
6463 "Compute the outline level of the heading at point.
6465 If this is called at a normal headline, the level is the number
6466 of stars. Use `org-reduced-level' to remove the effect of
6467 `org-odd-levels'. Unlike to `org-current-level', this function
6468 takes into consideration inlinetasks."
6469 (org-with-wide-buffer
6470 (end-of-line)
6471 (if (re-search-backward org-outline-regexp-bol nil t)
6472 (1- (- (match-end 0) (match-beginning 0)))
6473 0)))
6475 (defvar org-font-lock-keywords nil)
6477 (defsubst org-re-property (property &optional literal allow-null value)
6478 "Return a regexp matching a PROPERTY line.
6480 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6481 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6482 non-nil, match properties even without a value.
6484 Match group 3 is set to the value when it exists. If there is no
6485 value and ALLOW-NULL is non-nil, it is set to the empty string.
6487 With optional argument VALUE, match only property lines with
6488 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6489 unless LITERAL is non-nil."
6490 (concat
6491 "^\\(?4:[ \t]*\\)"
6492 (format "\\(?1::\\(?2:%s\\):\\)"
6493 (if literal property (regexp-quote property)))
6494 (cond (value
6495 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6496 (if literal value (regexp-quote value))))
6497 (allow-null
6498 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6500 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6502 (defconst org-property-re
6503 (org-re-property "\\S-+" 'literal t)
6504 "Regular expression matching a property line.
6505 There are four matching groups:
6506 1: :PROPKEY: including the leading and trailing colon,
6507 2: PROPKEY without the leading and trailing colon,
6508 3: PROPVAL without leading or trailing spaces,
6509 4: the indentation of the current line,
6510 5: trailing whitespace.")
6512 (defvar org-font-lock-hook nil
6513 "Functions to be called for special font lock stuff.")
6515 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6517 (defvar org-font-lock-set-keywords-hook nil
6518 "Functions that can manipulate `org-font-lock-extra-keywords'.
6519 This is called after `org-font-lock-extra-keywords' is defined, but before
6520 it is installed to be used by font lock. This can be useful if something
6521 needs to be inserted at a specific position in the font-lock sequence.")
6523 (defun org-font-lock-hook (limit)
6524 "Run `org-font-lock-hook' within LIMIT."
6525 (run-hook-with-args 'org-font-lock-hook limit))
6527 (defun org-set-font-lock-defaults ()
6528 "Set font lock defaults for the current buffer."
6529 (let* ((em org-fontify-emphasized-text)
6530 (lk org-highlight-links)
6531 (org-font-lock-extra-keywords
6532 (list
6533 ;; Call the hook
6534 '(org-font-lock-hook)
6535 ;; Headlines
6536 `(,(if org-fontify-whole-heading-line
6537 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6538 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6539 (1 (org-get-level-face 1))
6540 (2 (org-get-level-face 2))
6541 (3 (org-get-level-face 3)))
6542 ;; Table lines
6543 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6544 (1 'org-table t))
6545 ;; Table internals
6546 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6547 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6548 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6549 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6550 ;; Drawers
6551 '(org-fontify-drawers)
6552 ;; Properties
6553 (list org-property-re
6554 '(1 'org-special-keyword t)
6555 '(3 'org-property-value t))
6556 ;; Links
6557 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6558 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6559 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
6560 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
6561 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6562 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6563 (when (memq 'footnote lk) '(org-activate-footnote-links))
6564 ;; Targets.
6565 (list org-any-target-regexp '(0 'org-target t))
6566 ;; Diary sexps.
6567 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6568 ;; Macro
6569 '(org-fontify-macros)
6570 '(org-hide-wide-columns (0 nil append))
6571 ;; TODO keyword
6572 (list (format org-heading-keyword-regexp-format
6573 org-todo-regexp)
6574 '(2 (org-get-todo-face 2) t))
6575 ;; DONE
6576 (if org-fontify-done-headline
6577 (list (format org-heading-keyword-regexp-format
6578 (concat
6579 "\\(?:"
6580 (mapconcat 'regexp-quote org-done-keywords "\\|")
6581 "\\)"))
6582 '(2 'org-headline-done t))
6583 nil)
6584 ;; Priorities
6585 '(org-font-lock-add-priority-faces)
6586 ;; Tags
6587 '(org-font-lock-add-tag-faces)
6588 ;; Tags groups
6589 (when (and org-group-tags org-tag-groups-alist)
6590 (list (concat org-outline-regexp-bol ".+\\(:"
6591 (regexp-opt (mapcar 'car org-tag-groups-alist))
6592 ":\\).*$")
6593 '(1 'org-tag-group prepend)))
6594 ;; Special keywords
6595 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6596 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6597 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6598 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6599 ;; Emphasis
6600 (when em '(org-do-emphasis-faces))
6601 ;; Checkboxes
6602 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6603 1 'org-checkbox prepend)
6604 (when (cdr (assq 'checkbox org-list-automatic-rules))
6605 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6606 (0 (org-get-checkbox-statistics-face) t)))
6607 ;; Description list items
6608 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6609 1 'org-list-dt prepend)
6610 ;; ARCHIVEd headings
6611 (list (concat
6612 org-outline-regexp-bol
6613 "\\(.*:" org-archive-tag ":.*\\)")
6614 '(1 'org-archived prepend))
6615 ;; Specials
6616 '(org-do-latex-and-related)
6617 '(org-fontify-entities)
6618 '(org-raise-scripts)
6619 ;; Code
6620 '(org-activate-code (1 'org-code t))
6621 ;; COMMENT
6622 (list (format
6623 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6624 org-todo-regexp
6625 org-comment-string)
6626 '(9 'org-special-keyword t))
6627 ;; Blocks and meta lines
6628 '(org-fontify-meta-lines-and-blocks))))
6629 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6630 (run-hooks 'org-font-lock-set-keywords-hook)
6631 ;; Now set the full font-lock-keywords
6632 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6633 (setq-local font-lock-defaults
6634 '(org-font-lock-keywords t nil nil backward-paragraph))
6635 (kill-local-variable 'font-lock-keywords)
6636 nil))
6638 (defun org-toggle-pretty-entities ()
6639 "Toggle the composition display of entities as UTF8 characters."
6640 (interactive)
6641 (setq-local org-pretty-entities (not org-pretty-entities))
6642 (org-restart-font-lock)
6643 (if org-pretty-entities
6644 (message "Entities are now displayed as UTF8 characters")
6645 (save-restriction
6646 (widen)
6647 (decompose-region (point-min) (point-max))
6648 (message "Entities are now displayed as plain text"))))
6650 (defvar-local org-custom-properties-overlays nil
6651 "List of overlays used for custom properties.")
6653 (defun org-toggle-custom-properties-visibility ()
6654 "Display or hide properties in `org-custom-properties'."
6655 (interactive)
6656 (if org-custom-properties-overlays
6657 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6658 (setq org-custom-properties-overlays nil))
6659 (when org-custom-properties
6660 (org-with-wide-buffer
6661 (goto-char (point-min))
6662 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6663 (while (re-search-forward regexp nil t)
6664 (let ((end (cdr (save-match-data (org-get-property-block)))))
6665 (when (and end (< (point) end))
6666 ;; Hide first custom property in current drawer.
6667 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6668 (overlay-put o 'invisible t)
6669 (overlay-put o 'org-custom-property t)
6670 (push o org-custom-properties-overlays))
6671 ;; Hide additional custom properties in the same drawer.
6672 (while (re-search-forward regexp end t)
6673 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6674 (overlay-put o 'invisible t)
6675 (overlay-put o 'org-custom-property t)
6676 (push o org-custom-properties-overlays)))))
6677 ;; Each entry is limited to a single property drawer.
6678 (outline-next-heading)))))))
6680 (defun org-fontify-entities (limit)
6681 "Find an entity to fontify."
6682 (let (ee)
6683 (when org-pretty-entities
6684 (catch 'match
6685 ;; "\_ "-family is left out on purpose. Only the first one,
6686 ;; i.e., "\_ ", could be fontified anyway, and it would be
6687 ;; confusing when adding a second white space character.
6688 (while (re-search-forward
6689 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6690 limit t)
6691 (when (and (not (org-at-comment-p))
6692 (setq ee (org-entity-get (match-string 1)))
6693 (= (length (nth 6 ee)) 1))
6694 (let* ((end (if (equal (match-string 2) "{}")
6695 (match-end 2)
6696 (match-end 1))))
6697 (add-text-properties
6698 (match-beginning 0) end
6699 (list 'font-lock-fontified t))
6700 (compose-region (match-beginning 0) end
6701 (nth 6 ee) nil)
6702 (backward-char 1)
6703 (throw 'match t))))
6704 nil))))
6706 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6707 "Fontify string S like in Org mode."
6708 (with-temp-buffer
6709 (insert s)
6710 (let ((org-odd-levels-only odd-levels))
6711 (org-mode)
6712 (org-font-lock-ensure)
6713 (buffer-string))))
6715 (defvar org-m nil)
6716 (defvar org-l nil)
6717 (defvar org-f nil)
6718 (defun org-get-level-face (n)
6719 "Get the right face for match N in font-lock matching of headlines."
6720 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6721 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6722 (if org-cycle-level-faces
6723 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6724 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6725 (cond
6726 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6727 ((eq n 2) org-f)
6728 (t (unless org-level-color-stars-only org-f))))
6730 (defun org-face-from-face-or-color (context inherit face-or-color)
6731 "Create a face list that inherits INHERIT, but sets the foreground color.
6732 When FACE-OR-COLOR is not a string, just return it."
6733 (if (stringp face-or-color)
6734 (list :inherit inherit
6735 (cdr (assoc context org-faces-easy-properties))
6736 face-or-color)
6737 face-or-color))
6739 (defun org-get-todo-face (kwd)
6740 "Get the right face for a TODO keyword KWD.
6741 If KWD is a number, get the corresponding match group."
6742 (when (numberp kwd) (setq kwd (match-string kwd)))
6743 (or (org-face-from-face-or-color
6744 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6745 (and (member kwd org-done-keywords) 'org-done)
6746 'org-todo))
6748 (defun org-get-priority-face (priority)
6749 "Get the right face for PRIORITY.
6750 PRIORITY is a character."
6751 (or (org-face-from-face-or-color
6752 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6753 'org-priority))
6755 (defun org-get-tag-face (tag)
6756 "Get the right face for TAG.
6757 If TAG is a number, get the corresponding match group."
6758 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6759 (or (org-face-from-face-or-color
6760 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6761 'org-tag)))
6763 (defun org-font-lock-add-priority-faces (limit)
6764 "Add the special priority faces."
6765 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6766 (add-text-properties
6767 (match-beginning 1) (match-end 1)
6768 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6769 'font-lock-fontified t))))
6771 (defun org-font-lock-add-tag-faces (limit)
6772 "Add the special tag faces."
6773 (when (and org-tag-faces org-tags-special-faces-re)
6774 (while (re-search-forward org-tags-special-faces-re limit t)
6775 (add-text-properties (match-beginning 1) (match-end 1)
6776 (list 'face (org-get-tag-face 1)
6777 'font-lock-fontified t))
6778 (backward-char 1))))
6780 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6781 "Remove fontification and activation overlays from links."
6782 (font-lock-default-unfontify-region beg end)
6783 (let* ((buffer-undo-list t)
6784 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6785 (inhibit-modification-hooks t)
6786 deactivate-mark buffer-file-name buffer-file-truename)
6787 (decompose-region beg end)
6788 (remove-text-properties beg end
6789 '(mouse-face t keymap t org-linked-text t
6790 invisible t intangible t
6791 org-emphasis t))
6792 (org-remove-font-lock-display-properties beg end)))
6794 (defconst org-script-display '(((raise -0.3) (height 0.7))
6795 ((raise 0.3) (height 0.7))
6796 ((raise -0.5))
6797 ((raise 0.5)))
6798 "Display properties for showing superscripts and subscripts.")
6800 (defun org-remove-font-lock-display-properties (beg end)
6801 "Remove specific display properties that have been added by font lock.
6802 The will remove the raise properties that are used to show superscripts
6803 and subscripts."
6804 (let (next prop)
6805 (while (< beg end)
6806 (setq next (next-single-property-change beg 'display nil end)
6807 prop (get-text-property beg 'display))
6808 (when (member prop org-script-display)
6809 (put-text-property beg next 'display nil))
6810 (setq beg next))))
6812 (defun org-raise-scripts (limit)
6813 "Add raise properties to sub/superscripts."
6814 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6815 (re-search-forward
6816 (if (eq org-use-sub-superscripts t)
6817 org-match-substring-regexp
6818 org-match-substring-with-braces-regexp)
6819 limit t))
6820 (let* ((pos (point)) table-p comment-p
6821 (mpos (match-beginning 3))
6822 (emph-p (get-text-property mpos 'org-emphasis))
6823 (link-p (get-text-property mpos 'mouse-face))
6824 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6825 (goto-char (point-at-bol))
6826 (setq table-p (looking-at-p org-table-dataline-regexp)
6827 comment-p (looking-at-p "^[ \t]*#[ +]"))
6828 (goto-char pos)
6829 ;; Handle a_b^c
6830 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6831 (unless (or comment-p emph-p link-p keyw-p)
6832 (put-text-property (match-beginning 3) (match-end 0)
6833 'display
6834 (if (equal (char-after (match-beginning 2)) ?^)
6835 (nth (if table-p 3 1) org-script-display)
6836 (nth (if table-p 2 0) org-script-display)))
6837 (add-text-properties (match-beginning 2) (match-end 2)
6838 (list 'invisible t
6839 'org-dwidth t 'org-dwidth-n 1))
6840 (if (and (eq (char-after (match-beginning 3)) ?{)
6841 (eq (char-before (match-end 3)) ?}))
6842 (progn
6843 (add-text-properties
6844 (match-beginning 3) (1+ (match-beginning 3))
6845 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6846 (add-text-properties
6847 (1- (match-end 3)) (match-end 3)
6848 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6849 t)))
6851 ;;;; Visibility cycling, including org-goto and indirect buffer
6853 ;;; Cycling
6855 (defvar-local org-cycle-global-status nil)
6856 (put 'org-cycle-global-status 'org-state t)
6857 (defvar-local org-cycle-subtree-status nil)
6858 (put 'org-cycle-subtree-status 'org-state t)
6860 (defvar org-inlinetask-min-level)
6862 (defun org-unlogged-message (&rest args)
6863 "Display a message, but avoid logging it in the *Messages* buffer."
6864 (let ((message-log-max nil))
6865 (apply 'message args)))
6867 ;;;###autoload
6868 (defun org-cycle (&optional arg)
6869 "TAB-action and visibility cycling for Org mode.
6871 This is the command invoked in Org mode by the `TAB' key. Its main
6872 purpose is outline visibility cycling, but it also invokes other actions
6873 in special contexts.
6875 When this function is called with a `\\[universal-argument]' prefix, rotate \
6876 the entire
6877 buffer through 3 states (global cycling)
6878 1. OVERVIEW: Show only top-level headlines.
6879 2. CONTENTS: Show all headlines of all levels, but no body text.
6880 3. SHOW ALL: Show everything.
6882 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6883 switch to the startup visibility,
6884 determined by the variable `org-startup-folded', and by any VISIBILITY
6885 properties in the buffer.
6887 With a `\\[universal-argument] \\[universal-argument] \
6888 \\[universal-argument]' prefix argument, show the entire buffer, including
6889 any drawers.
6891 When inside a table, re-align the table and move to the next field.
6893 When point is at the beginning of a headline, rotate the subtree started
6894 by this line through 3 different states (local cycling)
6895 1. FOLDED: Only the main headline is shown.
6896 2. CHILDREN: The main headline and the direct children are shown.
6897 From this state, you can move to one of the children
6898 and zoom in further.
6899 3. SUBTREE: Show the entire subtree, including body text.
6900 If there is no subtree, switch directly from CHILDREN to FOLDED.
6902 When point is at the beginning of an empty headline and the variable
6903 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6904 of the headline by demoting and promoting it to likely levels. This
6905 speeds up creation document structure by pressing `TAB' once or several
6906 times right after creating a new headline.
6908 When there is a numeric prefix, go up to a heading with level ARG, do
6909 a `show-subtree' and return to the previous cursor position. If ARG
6910 is negative, go up that many levels.
6912 When point is not at the beginning of a headline, execute the global
6913 binding for `TAB', which is re-indenting the line. See the option
6914 `org-cycle-emulate-tab' for details.
6916 As a special case, if point is at the beginning of the buffer and there is
6917 no headline in line 1, this function will act as if called with prefix arg
6918 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6919 prefix arg, but only
6920 if the variable `org-cycle-global-at-bob' is t."
6921 (interactive "P")
6922 (org-load-modules-maybe)
6923 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6924 (and org-cycle-level-after-item/entry-creation
6925 (or (org-cycle-level)
6926 (org-cycle-item-indentation))))
6927 (let* ((limit-level
6928 (or org-cycle-max-level
6929 (and (boundp 'org-inlinetask-min-level)
6930 org-inlinetask-min-level
6931 (1- org-inlinetask-min-level))))
6932 (nstars (and limit-level
6933 (if org-odd-levels-only
6934 (and limit-level (1- (* limit-level 2)))
6935 limit-level)))
6936 (org-outline-regexp
6937 (if (not (derived-mode-p 'org-mode))
6938 outline-regexp
6939 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6940 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6941 (not (looking-at org-outline-regexp))))
6942 (org-cycle-hook
6943 (if bob-special
6944 (delq 'org-optimize-window-after-visibility-change
6945 (copy-sequence org-cycle-hook))
6946 org-cycle-hook))
6947 (pos (point)))
6949 (cond
6951 ((equal arg '(16))
6952 (setq last-command 'dummy)
6953 (org-set-startup-visibility)
6954 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6956 ((equal arg '(64))
6957 (outline-show-all)
6958 (org-unlogged-message "Entire buffer visible, including drawers"))
6960 ((equal arg '(4)) (org-cycle-internal-global))
6962 ;; Try hiding block at point.
6963 ((org-hide-block-toggle-maybe))
6965 ;; Try cdlatex TAB completion
6966 ((org-try-cdlatex-tab))
6968 ;; Table: enter it or move to the next field.
6969 ((org-at-table-p 'any)
6970 (if (org-at-table.el-p)
6971 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6972 Use `\\[org-edit-special]' to edit table.el tables"))
6973 (if arg (org-table-edit-field t)
6974 (org-table-justify-field-maybe)
6975 (call-interactively 'org-table-next-field))))
6977 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6979 ;; Global cycling: delegate to `org-cycle-internal-global'.
6980 (bob-special (org-cycle-internal-global))
6982 ;; Drawers: delegate to `org-flag-drawer'.
6983 ((save-excursion
6984 (beginning-of-line 1)
6985 (looking-at org-drawer-regexp))
6986 (org-flag-drawer ; toggle block visibility
6987 (not (get-char-property (match-end 0) 'invisible))))
6989 ;; Show-subtree, ARG levels up from here.
6990 ((integerp arg)
6991 (save-excursion
6992 (org-back-to-heading)
6993 (outline-up-heading (if (< arg 0) (- arg)
6994 (- (funcall outline-level) arg)))
6995 (org-show-subtree)))
6997 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6998 ((and (featurep 'org-inlinetask)
6999 (org-inlinetask-at-task-p)
7000 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
7001 (org-inlinetask-toggle-visibility))
7003 ;; At an item/headline: delegate to `org-cycle-internal-local'.
7004 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
7005 (save-excursion (move-beginning-of-line 1)
7006 (looking-at org-outline-regexp)))
7007 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
7008 (org-cycle-internal-local))
7010 ;; From there: TAB emulation and template completion.
7011 (buffer-read-only (org-back-to-heading))
7013 ((run-hook-with-args-until-success
7014 'org-tab-after-check-for-cycling-hook))
7016 ((org-try-structure-completion))
7018 ((run-hook-with-args-until-success
7019 'org-tab-before-tab-emulation-hook))
7021 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
7022 (or (not (bolp))
7023 (not (looking-at org-outline-regexp))))
7024 (call-interactively (global-key-binding "\t")))
7026 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
7027 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
7028 (or (and (eq org-cycle-emulate-tab 'white)
7029 (= (match-end 0) (point-at-eol)))
7030 (and (eq org-cycle-emulate-tab 'whitestart)
7031 (>= (match-end 0) pos))))
7033 (eq org-cycle-emulate-tab t))
7034 (call-interactively (global-key-binding "\t")))
7036 (t (save-excursion
7037 (org-back-to-heading)
7038 (org-cycle)))))))
7040 (defun org-cycle-internal-global ()
7041 "Do the global cycling action."
7042 ;; Hack to avoid display of messages for .org attachments in Gnus
7043 (let ((ga (string-match "\\*fontification" (buffer-name))))
7044 (cond
7045 ((and (eq last-command this-command)
7046 (eq org-cycle-global-status 'overview))
7047 ;; We just created the overview - now do table of contents
7048 ;; This can be slow in very large buffers, so indicate action
7049 (run-hook-with-args 'org-pre-cycle-hook 'contents)
7050 (unless ga (org-unlogged-message "CONTENTS..."))
7051 (org-content)
7052 (unless ga (org-unlogged-message "CONTENTS...done"))
7053 (setq org-cycle-global-status 'contents)
7054 (run-hook-with-args 'org-cycle-hook 'contents))
7056 ((and (eq last-command this-command)
7057 (eq org-cycle-global-status 'contents))
7058 ;; We just showed the table of contents - now show everything
7059 (run-hook-with-args 'org-pre-cycle-hook 'all)
7060 (outline-show-all)
7061 (unless ga (org-unlogged-message "SHOW ALL"))
7062 (setq org-cycle-global-status 'all)
7063 (run-hook-with-args 'org-cycle-hook 'all))
7066 ;; Default action: go to overview
7067 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7068 (org-overview)
7069 (unless ga (org-unlogged-message "OVERVIEW"))
7070 (setq org-cycle-global-status 'overview)
7071 (run-hook-with-args 'org-cycle-hook 'overview)))))
7073 (defvar org-called-with-limited-levels nil
7074 "Non-nil when `org-with-limited-levels' is currently active.")
7076 (defun org-cycle-internal-local ()
7077 "Do the local cycling action."
7078 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7079 ;; First, determine end of headline (EOH), end of subtree or item
7080 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7081 (save-excursion
7082 (if (org-at-item-p)
7083 (progn
7084 (beginning-of-line)
7085 (setq struct (org-list-struct))
7086 (setq eoh (point-at-eol))
7087 (setq eos (org-list-get-item-end-before-blank (point) struct))
7088 (setq has-children (org-list-has-child-p (point) struct)))
7089 (org-back-to-heading)
7090 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7091 (setq eos (save-excursion (org-end-of-subtree t t)
7092 (when (bolp) (backward-char)) (point)))
7093 (setq has-children
7094 (or (save-excursion
7095 (let ((level (funcall outline-level)))
7096 (outline-next-heading)
7097 (and (org-at-heading-p t)
7098 (> (funcall outline-level) level))))
7099 (save-excursion
7100 (org-list-search-forward (org-item-beginning-re) eos t)))))
7101 ;; Determine end invisible part of buffer (EOL)
7102 (beginning-of-line 2)
7103 (while (and (not (eobp)) ;This is like `next-line'.
7104 (get-char-property (1- (point)) 'invisible))
7105 (goto-char (next-single-char-property-change (point) 'invisible))
7106 (and (eolp) (beginning-of-line 2)))
7107 (setq eol (point)))
7108 ;; Find out what to do next and set `this-command'
7109 (cond
7110 ((= eos eoh)
7111 ;; Nothing is hidden behind this heading
7112 (unless (org-before-first-heading-p)
7113 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7114 (org-unlogged-message "EMPTY ENTRY")
7115 (setq org-cycle-subtree-status nil)
7116 (save-excursion
7117 (goto-char eos)
7118 (outline-next-heading)
7119 (when (outline-invisible-p) (org-flag-heading nil))))
7120 ((and (or (>= eol eos)
7121 (not (string-match "\\S-" (buffer-substring eol eos))))
7122 (or has-children
7123 (not (setq children-skipped
7124 org-cycle-skip-children-state-if-no-children))))
7125 ;; Entire subtree is hidden in one line: children view
7126 (unless (org-before-first-heading-p)
7127 (run-hook-with-args 'org-pre-cycle-hook 'children))
7128 (if (org-at-item-p)
7129 (org-list-set-item-visibility (point-at-bol) struct 'children)
7130 (org-show-entry)
7131 (org-with-limited-levels (org-show-children))
7132 ;; FIXME: This slows down the func way too much.
7133 ;; How keep drawers hidden in subtree anyway?
7134 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
7135 ;; (org-cycle-hide-drawers 'subtree))
7137 ;; Fold every list in subtree to top-level items.
7138 (when (eq org-cycle-include-plain-lists 'integrate)
7139 (save-excursion
7140 (org-back-to-heading)
7141 (while (org-list-search-forward (org-item-beginning-re) eos t)
7142 (beginning-of-line 1)
7143 (let* ((struct (org-list-struct))
7144 (prevs (org-list-prevs-alist struct))
7145 (end (org-list-get-bottom-point struct)))
7146 (dolist (e (org-list-get-all-items (point) struct prevs))
7147 (org-list-set-item-visibility e struct 'folded))
7148 (goto-char (if (< end eos) end eos)))))))
7149 (org-unlogged-message "CHILDREN")
7150 (save-excursion
7151 (goto-char eos)
7152 (outline-next-heading)
7153 (when (outline-invisible-p) (org-flag-heading nil)))
7154 (setq org-cycle-subtree-status 'children)
7155 (unless (org-before-first-heading-p)
7156 (run-hook-with-args 'org-cycle-hook 'children)))
7157 ((or children-skipped
7158 (and (eq last-command this-command)
7159 (eq org-cycle-subtree-status 'children)))
7160 ;; We just showed the children, or no children are there,
7161 ;; now show everything.
7162 (unless (org-before-first-heading-p)
7163 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7164 (outline-flag-region eoh eos nil)
7165 (org-unlogged-message
7166 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7167 (setq org-cycle-subtree-status 'subtree)
7168 (unless (org-before-first-heading-p)
7169 (run-hook-with-args 'org-cycle-hook 'subtree)))
7171 ;; Default action: hide the subtree.
7172 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7173 (outline-flag-region eoh eos t)
7174 (org-unlogged-message "FOLDED")
7175 (setq org-cycle-subtree-status 'folded)
7176 (unless (org-before-first-heading-p)
7177 (run-hook-with-args 'org-cycle-hook 'folded))))))
7179 ;;;###autoload
7180 (defun org-global-cycle (&optional arg)
7181 "Cycle the global visibility. For details see `org-cycle'.
7182 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7183 With a numeric prefix, show all headlines up to that level."
7184 (interactive "P")
7185 (let ((org-cycle-include-plain-lists
7186 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7187 (cond
7188 ((integerp arg)
7189 (outline-show-all)
7190 (outline-hide-sublevels arg)
7191 (setq org-cycle-global-status 'contents))
7192 ((equal arg '(4))
7193 (org-set-startup-visibility)
7194 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7196 (org-cycle '(4))))))
7198 (defun org-set-startup-visibility ()
7199 "Set the visibility required by startup options and properties."
7200 (cond
7201 ((eq org-startup-folded t)
7202 (org-overview))
7203 ((eq org-startup-folded 'content)
7204 (org-content))
7205 ((or (eq org-startup-folded 'showeverything)
7206 (eq org-startup-folded nil))
7207 (outline-show-all)))
7208 (unless (eq org-startup-folded 'showeverything)
7209 (when org-hide-block-startup (org-hide-block-all))
7210 (org-set-visibility-according-to-property 'no-cleanup)
7211 (org-cycle-hide-archived-subtrees 'all)
7212 (org-cycle-hide-drawers 'all)
7213 (org-cycle-show-empty-lines t)))
7215 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7216 "Switch subtree visibilities according to :VISIBILITY: property."
7217 (interactive)
7218 (org-with-wide-buffer
7219 (goto-char (point-min))
7220 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7221 (if (not (org-at-property-p)) (outline-next-heading)
7222 (let ((state (match-string 3)))
7223 (save-excursion
7224 (org-back-to-heading t)
7225 (outline-hide-subtree)
7226 (org-reveal)
7227 (cond
7228 ((equal state "folded")
7229 (outline-hide-subtree))
7230 ((equal state "children")
7231 (org-show-hidden-entry)
7232 (org-show-children))
7233 ((equal state "content")
7234 (save-excursion
7235 (save-restriction
7236 (org-narrow-to-subtree)
7237 (org-content))))
7238 ((member state '("all" "showall"))
7239 (outline-show-subtree)))))))
7240 (unless no-cleanup
7241 (org-cycle-hide-archived-subtrees 'all)
7242 (org-cycle-hide-drawers 'all)
7243 (org-cycle-show-empty-lines 'all))))
7245 ;; This function uses outline-regexp instead of the more fundamental
7246 ;; org-outline-regexp so that org-cycle-global works outside of Org
7247 ;; buffers, where outline-regexp is needed.
7248 (defun org-overview ()
7249 "Switch to overview mode, showing only top-level headlines.
7250 This shows all headlines with a level equal or greater than the level
7251 of the first headline in the buffer. This is important, because if the
7252 first headline is not level one, then (hide-sublevels 1) gives confusing
7253 results."
7254 (interactive)
7255 (save-excursion
7256 (let ((level
7257 (save-excursion
7258 (goto-char (point-min))
7259 (when (re-search-forward (concat "^" outline-regexp) nil t)
7260 (goto-char (match-beginning 0))
7261 (funcall outline-level)))))
7262 (and level (outline-hide-sublevels level)))))
7264 (defun org-content (&optional arg)
7265 "Show all headlines in the buffer, like a table of contents.
7266 With numerical argument N, show content up to level N."
7267 (interactive "P")
7268 (org-overview)
7269 (save-excursion
7270 ;; Visit all headings and show their offspring
7271 (and (integerp arg) (org-overview))
7272 (goto-char (point-max))
7273 (catch 'exit
7274 (while (and (progn (condition-case nil
7275 (outline-previous-visible-heading 1)
7276 (error (goto-char (point-min))))
7278 (looking-at org-outline-regexp))
7279 (if (integerp arg)
7280 (org-show-children (1- arg))
7281 (outline-show-branches))
7282 (when (bobp) (throw 'exit nil))))))
7284 (defun org-optimize-window-after-visibility-change (state)
7285 "Adjust the window after a change in outline visibility.
7286 This function is the default value of the hook `org-cycle-hook'."
7287 (when (get-buffer-window (current-buffer))
7288 (cond
7289 ((eq state 'content) nil)
7290 ((eq state 'all) nil)
7291 ((eq state 'folded) nil)
7292 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7293 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7295 (defun org-remove-empty-overlays-at (pos)
7296 "Remove outline overlays that do not contain non-white stuff."
7297 (dolist (o (overlays-at pos))
7298 (and (eq 'outline (overlay-get o 'invisible))
7299 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7300 (overlay-end o))))
7301 (delete-overlay o))))
7303 (defun org-clean-visibility-after-subtree-move ()
7304 "Fix visibility issues after moving a subtree."
7305 ;; First, find a reasonable region to look at:
7306 ;; Start two siblings above, end three below
7307 (let* ((beg (save-excursion
7308 (and (org-get-last-sibling)
7309 (org-get-last-sibling))
7310 (point)))
7311 (end (save-excursion
7312 (and (org-get-next-sibling)
7313 (org-get-next-sibling)
7314 (org-get-next-sibling))
7315 (if (org-at-heading-p)
7316 (point-at-eol)
7317 (point))))
7318 (level (looking-at "\\*+"))
7319 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7320 (save-excursion
7321 (save-restriction
7322 (narrow-to-region beg end)
7323 (when re
7324 ;; Properly fold already folded siblings
7325 (goto-char (point-min))
7326 (while (re-search-forward re nil t)
7327 (when (and (not (outline-invisible-p))
7328 (save-excursion
7329 (goto-char (point-at-eol)) (outline-invisible-p)))
7330 (outline-hide-entry))))
7331 (org-cycle-show-empty-lines 'overview)
7332 (org-cycle-hide-drawers 'overview)))))
7334 (defun org-cycle-show-empty-lines (state)
7335 "Show empty lines above all visible headlines.
7336 The region to be covered depends on STATE when called through
7337 `org-cycle-hook'. Lisp program can use t for STATE to get the
7338 entire buffer covered. Note that an empty line is only shown if there
7339 are at least `org-cycle-separator-lines' empty lines before the headline."
7340 (when (/= org-cycle-separator-lines 0)
7341 (save-excursion
7342 (let* ((n (abs org-cycle-separator-lines))
7343 (re (cond
7344 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7345 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7346 (t (let ((ns (number-to-string (- n 2))))
7347 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7348 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7349 beg end)
7350 (cond
7351 ((memq state '(overview contents t))
7352 (setq beg (point-min) end (point-max)))
7353 ((memq state '(children folded))
7354 (setq beg (point)
7355 end (progn (org-end-of-subtree t t)
7356 (line-beginning-position 2)))))
7357 (when beg
7358 (goto-char beg)
7359 (while (re-search-forward re end t)
7360 (unless (get-char-property (match-end 1) 'invisible)
7361 (let ((e (match-end 1))
7362 (b (if (>= org-cycle-separator-lines 0)
7363 (match-beginning 1)
7364 (save-excursion
7365 (goto-char (match-beginning 0))
7366 (skip-chars-backward " \t\n")
7367 (line-end-position)))))
7368 (outline-flag-region b e nil))))))))
7369 ;; Never hide empty lines at the end of the file.
7370 (save-excursion
7371 (goto-char (point-max))
7372 (outline-previous-heading)
7373 (outline-end-of-heading)
7374 (when (and (looking-at "[ \t\n]+")
7375 (= (match-end 0) (point-max)))
7376 (outline-flag-region (point) (match-end 0) nil))))
7378 (defun org-show-empty-lines-in-parent ()
7379 "Move to the parent and re-show empty lines before visible headlines."
7380 (save-excursion
7381 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7382 (org-cycle-show-empty-lines context))))
7384 (defun org-files-list ()
7385 "Return `org-agenda-files' list, plus all open Org files.
7386 This is useful for operations that need to scan all of a user's
7387 open and agenda-wise Org files."
7388 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7389 (dolist (buf (buffer-list))
7390 (with-current-buffer buf
7391 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7392 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7393 files))
7395 (defsubst org-entry-beginning-position ()
7396 "Return the beginning position of the current entry."
7397 (save-excursion (org-back-to-heading t) (point)))
7399 (defsubst org-entry-end-position ()
7400 "Return the end position of the current entry."
7401 (save-excursion (outline-next-heading) (point)))
7403 (defun org-cycle-hide-drawers (state &optional exceptions)
7404 "Re-hide all drawers after a visibility state change.
7405 When non-nil, optional argument EXCEPTIONS is a list of strings
7406 specifying which drawers should not be hidden."
7407 (when (and (derived-mode-p 'org-mode)
7408 (not (memq state '(overview folded contents))))
7409 (save-excursion
7410 (let* ((globalp (memq state '(contents all)))
7411 (beg (if globalp (point-min) (point)))
7412 (end (if globalp (point-max)
7413 (if (eq state 'children)
7414 (save-excursion (outline-next-heading) (point))
7415 (org-end-of-subtree t)))))
7416 (goto-char beg)
7417 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7418 (unless (member-ignore-case (match-string 1) exceptions)
7419 (let ((drawer (org-element-at-point)))
7420 (when (memq (org-element-type drawer) '(drawer property-drawer))
7421 (org-flag-drawer t drawer)
7422 ;; Make sure to skip drawer entirely or we might flag
7423 ;; it another time when matching its ending line with
7424 ;; `org-drawer-regexp'.
7425 (goto-char (org-element-property :end drawer))))))))))
7427 (defun org-flag-drawer (flag &optional element)
7428 "When FLAG is non-nil, hide the drawer we are at.
7429 Otherwise make it visible. When optional argument ELEMENT is
7430 a parsed drawer, as returned by `org-element-at-point', hide or
7431 show that drawer instead."
7432 (let ((drawer (or element
7433 (and (save-excursion
7434 (beginning-of-line)
7435 (looking-at-p org-drawer-regexp))
7436 (org-element-at-point)))))
7437 (when (memq (org-element-type drawer) '(drawer property-drawer))
7438 (let ((post (org-element-property :post-affiliated drawer)))
7439 (save-excursion
7440 (outline-flag-region
7441 (progn (goto-char post) (line-end-position))
7442 (progn (goto-char (org-element-property :end drawer))
7443 (skip-chars-backward " \r\t\n")
7444 (line-end-position))
7445 flag))
7446 ;; When the drawer is hidden away, make sure point lies in
7447 ;; a visible part of the buffer.
7448 (when (and flag (> (line-beginning-position) post))
7449 (goto-char post))))))
7451 (defun org-subtree-end-visible-p ()
7452 "Is the end of the current subtree visible?"
7453 (pos-visible-in-window-p
7454 (save-excursion (org-end-of-subtree t) (point))))
7456 (defun org-first-headline-recenter ()
7457 "Move cursor to the first headline and recenter the headline."
7458 (let ((window (get-buffer-window)))
7459 (when window
7460 (goto-char (point-min))
7461 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7462 (set-window-start window (line-beginning-position))))))
7464 ;;; Saving and restoring visibility
7466 (defun org-outline-overlay-data (&optional use-markers)
7467 "Return a list of the locations of all outline overlays.
7468 These are overlays with the `invisible' property value `outline'.
7469 The return value is a list of cons cells, with start and stop
7470 positions for each overlay.
7471 If USE-MARKERS is set, return the positions as markers."
7472 (let (beg end)
7473 (org-with-wide-buffer
7474 (delq nil
7475 (mapcar (lambda (o)
7476 (when (eq (overlay-get o 'invisible) 'outline)
7477 (setq beg (overlay-start o)
7478 end (overlay-end o))
7479 (and beg end (> end beg)
7480 (if use-markers
7481 (cons (copy-marker beg)
7482 (copy-marker end t))
7483 (cons beg end)))))
7484 (overlays-in (point-min) (point-max)))))))
7486 (defun org-set-outline-overlay-data (data)
7487 "Create visibility overlays for all positions in DATA.
7488 DATA should have been made by `org-outline-overlay-data'."
7489 (org-with-wide-buffer
7490 (outline-show-all)
7491 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7493 ;;; Folding of blocks
7495 (defvar-local org-hide-block-overlays nil
7496 "Overlays hiding blocks.")
7498 (defun org-block-map (function &optional start end)
7499 "Call FUNCTION at the head of all source blocks in the current buffer.
7500 Optional arguments START and END can be used to limit the range."
7501 (let ((start (or start (point-min)))
7502 (end (or end (point-max))))
7503 (save-excursion
7504 (goto-char start)
7505 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7506 (save-excursion
7507 (save-match-data
7508 (goto-char (match-beginning 0))
7509 (funcall function)))))))
7511 (defun org-hide-block-toggle-all ()
7512 "Toggle the visibility of all blocks in the current buffer."
7513 (org-block-map 'org-hide-block-toggle))
7515 (defun org-hide-block-all ()
7516 "Fold all blocks in the current buffer."
7517 (interactive)
7518 (org-show-block-all)
7519 (org-block-map 'org-hide-block-toggle-maybe))
7521 (defun org-show-block-all ()
7522 "Unfold all blocks in the current buffer."
7523 (interactive)
7524 (mapc #'delete-overlay org-hide-block-overlays)
7525 (setq org-hide-block-overlays nil))
7527 (defun org-hide-block-toggle-maybe ()
7528 "Toggle visibility of block at point.
7529 Unlike to `org-hide-block-toggle', this function does not throw
7530 an error. Return a non-nil value when toggling is successful."
7531 (interactive)
7532 (ignore-errors (org-hide-block-toggle)))
7534 (defun org-hide-block-toggle (&optional force)
7535 "Toggle the visibility of the current block.
7536 When optional argument FORCE is `off', make block visible. If it
7537 is non-nil, hide it unconditionally. Throw an error when not at
7538 a block. Return a non-nil value when toggling is successful."
7539 (interactive)
7540 (let ((element (org-element-at-point)))
7541 (unless (memq (org-element-type element)
7542 '(center-block comment-block dynamic-block example-block
7543 export-block quote-block special-block
7544 src-block verse-block))
7545 (user-error "Not at a block"))
7546 (let* ((start (save-excursion
7547 (goto-char (org-element-property :post-affiliated element))
7548 (line-end-position)))
7549 (end (save-excursion
7550 (goto-char (org-element-property :end element))
7551 (skip-chars-backward " \r\t\n")
7552 (line-end-position)))
7553 (overlays (overlays-at start)))
7554 (cond
7555 ;; Do nothing when not before or at the block opening line or
7556 ;; at the block closing line.
7557 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7558 ((and (not (eq force 'off))
7559 (not (memq t (mapcar
7560 (lambda (o)
7561 (eq (overlay-get o 'invisible) 'org-hide-block))
7562 overlays))))
7563 (let ((ov (make-overlay start end)))
7564 (overlay-put ov 'invisible 'org-hide-block)
7565 ;; Make the block accessible to `isearch'.
7566 (overlay-put
7567 ov 'isearch-open-invisible
7568 (lambda (ov)
7569 (when (memq ov org-hide-block-overlays)
7570 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7571 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7572 (delete-overlay ov))))
7573 (push ov org-hide-block-overlays)
7574 ;; When the block is hidden away, make sure point is left in
7575 ;; a visible part of the buffer.
7576 (when (> (line-beginning-position) start)
7577 (goto-char start)
7578 (beginning-of-line))
7579 ;; Signal successful toggling.
7581 ((or (not force) (eq force 'off))
7582 (dolist (ov overlays t)
7583 (when (memq ov org-hide-block-overlays)
7584 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7585 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7586 (delete-overlay ov))))))))
7588 ;; Remove overlays when changing major mode
7589 (add-hook 'org-mode-hook
7590 (lambda () (add-hook 'change-major-mode-hook
7591 'org-show-block-all 'append 'local)))
7593 ;;; Org-goto
7595 (defvar org-goto-window-configuration nil)
7596 (defvar org-goto-marker nil)
7597 (defvar org-goto-map)
7598 (defun org-goto-map ()
7599 "Set the keymap `org-goto'."
7600 (setq org-goto-map
7601 (let ((map (make-sparse-keymap)))
7602 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7603 mouse-drag-region universal-argument org-occur)))
7604 (dolist (cmd cmds)
7605 (substitute-key-definition cmd cmd map global-map)))
7606 (suppress-keymap map)
7607 (org-defkey map "\C-m" 'org-goto-ret)
7608 (org-defkey map [(return)] 'org-goto-ret)
7609 (org-defkey map [(left)] 'org-goto-left)
7610 (org-defkey map [(right)] 'org-goto-right)
7611 (org-defkey map [(control ?g)] 'org-goto-quit)
7612 (org-defkey map "\C-i" 'org-cycle)
7613 (org-defkey map [(tab)] 'org-cycle)
7614 (org-defkey map [(down)] 'outline-next-visible-heading)
7615 (org-defkey map [(up)] 'outline-previous-visible-heading)
7616 (if org-goto-auto-isearch
7617 (if (fboundp 'define-key-after)
7618 (define-key-after map [t] 'org-goto-local-auto-isearch)
7619 nil)
7620 (org-defkey map "q" 'org-goto-quit)
7621 (org-defkey map "n" 'outline-next-visible-heading)
7622 (org-defkey map "p" 'outline-previous-visible-heading)
7623 (org-defkey map "f" 'outline-forward-same-level)
7624 (org-defkey map "b" 'outline-backward-same-level)
7625 (org-defkey map "u" 'outline-up-heading))
7626 (org-defkey map "/" 'org-occur)
7627 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7628 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7629 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7630 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7631 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7632 map)))
7634 (defconst org-goto-help
7635 "Browse buffer copy, to find location or copy text.%s
7636 RET=jump to location C-g=quit and return to previous location
7637 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7639 (defvar org-goto-start-pos) ; dynamically scoped parameter
7641 (defun org-goto (&optional alternative-interface)
7642 "Look up a different location in the current file, keeping current visibility.
7644 When you want look-up or go to a different location in a
7645 document, the fastest way is often to fold the entire buffer and
7646 then dive into the tree. This method has the disadvantage, that
7647 the previous location will be folded, which may not be what you
7648 want.
7650 This command works around this by showing a copy of the current
7651 buffer in an indirect buffer, in overview mode. You can dive
7652 into the tree in that copy, use org-occur and incremental search
7653 to find a location. When pressing RET or `Q', the command
7654 returns to the original buffer in which the visibility is still
7655 unchanged. After RET it will also jump to the location selected
7656 in the indirect buffer and expose the headline hierarchy above.
7658 With a prefix argument, use the alternative interface: e.g., if
7659 `org-goto-interface' is `outline' use `outline-path-completion'."
7660 (interactive "P")
7661 (org-goto-map)
7662 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7663 (org-refile-use-outline-path t)
7664 (org-refile-target-verify-function nil)
7665 (interface
7666 (if (not alternative-interface)
7667 org-goto-interface
7668 (if (eq org-goto-interface 'outline)
7669 'outline-path-completion
7670 'outline)))
7671 (org-goto-start-pos (point))
7672 (selected-point
7673 (if (eq interface 'outline)
7674 (car (org-get-location (current-buffer) org-goto-help))
7675 (let ((pa (org-refile-get-location "Goto")))
7676 (org-refile-check-position pa)
7677 (nth 3 pa)))))
7678 (if selected-point
7679 (progn
7680 (org-mark-ring-push org-goto-start-pos)
7681 (goto-char selected-point)
7682 (when (or (outline-invisible-p) (org-invisible-p2))
7683 (org-show-context 'org-goto)))
7684 (message "Quit"))))
7686 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7687 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7688 (defvar org-goto-local-auto-isearch-map) ; defined below
7690 (defun org-get-location (_buf help)
7691 "Let the user select a location in current buffer.
7692 This function uses a recursive edit. It returns the selected position
7693 or nil."
7694 (org-no-popups
7695 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7696 (isearch-hide-immediately nil)
7697 (isearch-search-fun-function
7698 (lambda () 'org-goto-local-search-headings))
7699 (org-goto-selected-point org-goto-exit-command))
7700 (save-excursion
7701 (save-window-excursion
7702 (delete-other-windows)
7703 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7704 (pop-to-buffer-same-window
7705 (condition-case nil
7706 (make-indirect-buffer (current-buffer) "*org-goto*")
7707 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7708 (with-output-to-temp-buffer "*Org Help*"
7709 (princ (format help (if org-goto-auto-isearch
7710 " Just type for auto-isearch."
7711 " n/p/f/b/u to navigate, q to quit."))))
7712 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7713 (setq buffer-read-only nil)
7714 (let ((org-startup-truncated t)
7715 (org-startup-folded nil)
7716 (org-startup-align-all-tables nil))
7717 (org-mode)
7718 (org-overview))
7719 (setq buffer-read-only t)
7720 (if (and (boundp 'org-goto-start-pos)
7721 (integer-or-marker-p org-goto-start-pos))
7722 (progn (goto-char org-goto-start-pos)
7723 (when (outline-invisible-p)
7724 (org-show-set-visibility 'lineage)))
7725 (goto-char (point-min)))
7726 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7727 (message "Select location and press RET")
7728 (use-local-map org-goto-map)
7729 (recursive-edit)))
7730 (kill-buffer "*org-goto*")
7731 (cons org-goto-selected-point org-goto-exit-command))))
7733 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7734 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7735 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7736 (if (fboundp 'isearch-other-control-char)
7737 (progn
7738 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7739 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7740 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7741 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7742 (define-key org-goto-local-auto-isearch-map [return] nil))
7744 (defun org-goto-local-search-headings (string bound noerror)
7745 "Search and make sure that any matches are in headlines."
7746 (catch 'return
7747 (while (if isearch-forward
7748 (search-forward string bound noerror)
7749 (search-backward string bound noerror))
7750 (when (save-match-data
7751 (and (save-excursion
7752 (beginning-of-line)
7753 (looking-at org-complex-heading-regexp))
7754 (or (not (match-beginning 5))
7755 (< (point) (match-beginning 5)))))
7756 (throw 'return (point))))))
7758 (defun org-goto-local-auto-isearch ()
7759 "Start isearch."
7760 (interactive)
7761 (goto-char (point-min))
7762 (let ((keys (this-command-keys)))
7763 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7764 (isearch-mode t)
7765 (isearch-process-search-char (string-to-char keys)))))
7767 (defun org-goto-ret (&optional _arg)
7768 "Finish `org-goto' by going to the new location."
7769 (interactive "P")
7770 (setq org-goto-selected-point (point))
7771 (setq org-goto-exit-command 'return)
7772 (throw 'exit nil))
7774 (defun org-goto-left ()
7775 "Finish `org-goto' by going to the new location."
7776 (interactive)
7777 (if (org-at-heading-p)
7778 (progn
7779 (beginning-of-line 1)
7780 (setq org-goto-selected-point (point)
7781 org-goto-exit-command 'left)
7782 (throw 'exit nil))
7783 (user-error "Not on a heading")))
7785 (defun org-goto-right ()
7786 "Finish `org-goto' by going to the new location."
7787 (interactive)
7788 (if (org-at-heading-p)
7789 (progn
7790 (setq org-goto-selected-point (point)
7791 org-goto-exit-command 'right)
7792 (throw 'exit nil))
7793 (user-error "Not on a heading")))
7795 (defun org-goto-quit ()
7796 "Finish `org-goto' without cursor motion."
7797 (interactive)
7798 (setq org-goto-selected-point nil)
7799 (setq org-goto-exit-command 'quit)
7800 (throw 'exit nil))
7802 ;;; Indirect buffer display of subtrees
7804 (defvar org-indirect-dedicated-frame nil
7805 "This is the frame being used for indirect tree display.")
7806 (defvar org-last-indirect-buffer nil)
7808 (defun org-tree-to-indirect-buffer (&optional arg)
7809 "Create indirect buffer and narrow it to current subtree.
7811 With a numerical prefix ARG, go up to this level and then take that tree.
7812 If ARG is negative, go up that many levels.
7814 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7815 indirect buffer previously made with this command, to avoid proliferation of
7816 indirect buffers. However, when you call the command with a \
7817 `\\[universal-argument]' prefix, or
7818 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7819 so that you can work with several indirect buffers at the same time. If
7820 `org-indirect-buffer-display' is `dedicated-frame', the \
7821 `\\[universal-argument]' prefix also
7822 requests that a new frame be made for the new buffer, so that the dedicated
7823 frame is not changed."
7824 (interactive "P")
7825 (let ((cbuf (current-buffer))
7826 (cwin (selected-window))
7827 (pos (point))
7828 beg end level heading ibuf)
7829 (save-excursion
7830 (org-back-to-heading t)
7831 (when (numberp arg)
7832 (setq level (org-outline-level))
7833 (when (< arg 0) (setq arg (+ level arg)))
7834 (while (> (setq level (org-outline-level)) arg)
7835 (org-up-heading-safe)))
7836 (setq beg (point)
7837 heading (org-get-heading 'no-tags))
7838 (org-end-of-subtree t t)
7839 (when (org-at-heading-p) (backward-char 1))
7840 (setq end (point)))
7841 (when (and (buffer-live-p org-last-indirect-buffer)
7842 (not (eq org-indirect-buffer-display 'new-frame))
7843 (not arg))
7844 (kill-buffer org-last-indirect-buffer))
7845 (setq ibuf (org-get-indirect-buffer cbuf heading)
7846 org-last-indirect-buffer ibuf)
7847 (cond
7848 ((or (eq org-indirect-buffer-display 'new-frame)
7849 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7850 (select-frame (make-frame))
7851 (delete-other-windows)
7852 (pop-to-buffer-same-window ibuf)
7853 (org-set-frame-title heading))
7854 ((eq org-indirect-buffer-display 'dedicated-frame)
7855 (raise-frame
7856 (select-frame (or (and org-indirect-dedicated-frame
7857 (frame-live-p org-indirect-dedicated-frame)
7858 org-indirect-dedicated-frame)
7859 (setq org-indirect-dedicated-frame (make-frame)))))
7860 (delete-other-windows)
7861 (pop-to-buffer-same-window ibuf)
7862 (org-set-frame-title (concat "Indirect: " heading)))
7863 ((eq org-indirect-buffer-display 'current-window)
7864 (pop-to-buffer-same-window ibuf))
7865 ((eq org-indirect-buffer-display 'other-window)
7866 (pop-to-buffer ibuf))
7867 (t (error "Invalid value")))
7868 (narrow-to-region beg end)
7869 (outline-show-all)
7870 (goto-char pos)
7871 (run-hook-with-args 'org-cycle-hook 'all)
7872 (and (window-live-p cwin) (select-window cwin))))
7874 (defun org-get-indirect-buffer (&optional buffer heading)
7875 (setq buffer (or buffer (current-buffer)))
7876 (let ((n 1) (base (buffer-name buffer)) bname)
7877 (while (buffer-live-p
7878 (get-buffer
7879 (setq bname
7880 (concat base "-"
7881 (if heading (concat heading "-" (number-to-string n))
7882 (number-to-string n))))))
7883 (setq n (1+ n)))
7884 (condition-case nil
7885 (make-indirect-buffer buffer bname 'clone)
7886 (error (make-indirect-buffer buffer bname)))))
7888 (defun org-set-frame-title (title)
7889 "Set the title of the current frame to the string TITLE."
7890 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7892 ;;;; Structure editing
7894 ;;; Inserting headlines
7896 (defun org--line-empty-p (n)
7897 "Is the Nth next line empty?
7899 Counts the current line as N = 1 and the previous line as N = 0;
7900 see `beginning-of-line'."
7901 (save-excursion
7902 (and (not (bobp))
7903 (or (beginning-of-line n) t)
7904 (save-match-data
7905 (looking-at "[ \t]*$")))))
7907 (defun org-previous-line-empty-p ()
7908 "Is the previous line a blank line?
7909 When NEXT is non-nil, check the next line instead."
7910 (org--line-empty-p 0))
7912 (defun org-next-line-empty-p ()
7913 "Is the previous line a blank line?
7914 When NEXT is non-nil, check the next line instead."
7915 (org--line-empty-p 2))
7917 (defun org-insert-heading (&optional arg invisible-ok top)
7918 "Insert a new heading or an item with the same depth at point.
7920 If point is at the beginning of a heading or a list item, insert
7921 a new heading or a new item above the current one. When at the
7922 beginning of a regular line of text, turn it into a heading.
7924 If point is in the middle of a line, split it and create a new
7925 headline/item with the text in the current line after point (see
7926 `org-M-RET-may-split-line' on how to modify this behavior). As
7927 a special case, on a headline, splitting can only happen on the
7928 title itself. E.g., this excludes breaking stars or tags.
7930 With a `\\[universal-argument]' prefix, set \
7931 `org-insert-heading-respect-content' to
7932 a non-nil value for the duration of the command. This forces the
7933 insertion of a heading after the current subtree, independently
7934 on the location of point.
7936 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7937 insert the heading at the end of the tree
7938 above the current heading. For example, if point is within a
7939 2nd-level heading, then it will insert a 2nd-level heading at
7940 the end of the 1st-level parent subtree.
7942 When INVISIBLE-OK is set, stop at invisible headlines when going
7943 back. This is important for non-interactive uses of the
7944 command.
7946 When optional argument TOP is non-nil, insert a level 1 heading,
7947 unconditionally."
7948 (interactive "P")
7949 (let ((itemp (and (not top) (org-in-item-p)))
7950 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7951 (respect-content (or org-insert-heading-respect-content
7952 (equal arg '(4))))
7953 (initial-content ""))
7955 (cond
7957 ((or (= (buffer-size) 0)
7958 (and (not (save-excursion
7959 (and (ignore-errors (org-back-to-heading invisible-ok))
7960 (org-at-heading-p))))
7961 (or arg (not itemp))))
7962 ;; At beginning of buffer or so high up that only a heading
7963 ;; makes sense.
7964 (cond ((and (bolp) (not respect-content)) (insert "* "))
7965 ((not respect-content)
7966 (unless may-split (end-of-line))
7967 (insert "\n* "))
7968 ((re-search-forward org-outline-regexp-bol nil t)
7969 (beginning-of-line)
7970 (insert "* \n")
7971 (backward-char))
7972 (t (goto-char (point-max))
7973 (insert "\n* ")))
7974 (run-hooks 'org-insert-heading-hook))
7976 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7979 ;; Maybe move at the end of the subtree
7980 (when (equal arg '(16))
7981 (org-up-heading-safe)
7982 (org-end-of-subtree t))
7983 ;; Insert a heading
7984 (save-restriction
7985 (widen)
7986 (let* ((level nil)
7987 (on-heading (org-at-heading-p))
7988 (empty-line-p (if on-heading
7989 (org-previous-line-empty-p)
7990 ;; We will decide later
7991 nil))
7992 ;; Get a level string to fall back on.
7993 (fix-level
7994 (if (org-before-first-heading-p) "*"
7995 (save-excursion
7996 (org-back-to-heading t)
7997 (when (org-previous-line-empty-p) (setq empty-line-p t))
7998 (looking-at org-outline-regexp)
7999 (make-string (1- (length (match-string 0))) ?*))))
8000 (stars
8001 (save-excursion
8002 (condition-case nil
8003 (if top "* "
8004 (org-back-to-heading invisible-ok)
8005 (when (and (not on-heading)
8006 (featurep 'org-inlinetask)
8007 (integerp org-inlinetask-min-level)
8008 (>= (length (match-string 0))
8009 org-inlinetask-min-level))
8010 ;; Find a heading level before the inline
8011 ;; task.
8012 (while (and (setq level (org-up-heading-safe))
8013 (>= level org-inlinetask-min-level)))
8014 (if (org-at-heading-p)
8015 (org-back-to-heading invisible-ok)
8016 (error "This should not happen")))
8017 (unless (and (save-excursion
8018 (save-match-data
8019 (org-backward-heading-same-level
8020 1 invisible-ok))
8021 (= (point) (match-beginning 0)))
8022 (not (org-next-line-empty-p)))
8023 (setq empty-line-p (or empty-line-p
8024 (org-previous-line-empty-p))))
8025 (match-string 0))
8026 (error (or fix-level "* ")))))
8027 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
8028 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
8030 ;; If we insert after content, move there and clean up
8031 ;; whitespace.
8032 (when respect-content
8033 (if (not (org-before-first-heading-p))
8034 (org-end-of-subtree nil t)
8035 (re-search-forward org-outline-regexp-bol)
8036 (beginning-of-line 0))
8037 (skip-chars-backward " \r\t\n")
8038 (and (not (looking-back "^\\*+" (line-beginning-position)))
8039 (looking-at "[ \t]+") (replace-match ""))
8040 (unless (eobp) (forward-char 1))
8041 (when (looking-at "^\\*")
8042 (unless (bobp) (backward-char 1))
8043 (insert "\n")))
8045 ;; If we are splitting, grab the text that should be moved
8046 ;; to the new headline.
8047 (when may-split
8048 (if (org-at-heading-p)
8049 ;; This is a heading: split intelligently (keeping
8050 ;; tags).
8051 (let ((pos (point)))
8052 (beginning-of-line)
8053 (let ((case-fold-search nil))
8054 (unless (looking-at org-complex-heading-regexp)
8055 (error "This should not happen")))
8056 (when (and (match-beginning 4)
8057 (> pos (match-beginning 4))
8058 (< pos (match-end 4)))
8059 (setq initial-content (buffer-substring pos (match-end 4)))
8060 (goto-char pos)
8061 (delete-region (point) (match-end 4))
8062 (if (looking-at "[ \t]*$")
8063 (replace-match "")
8064 (insert (make-string (length initial-content) ?\s)))
8065 (setq initial-content (org-trim initial-content)))
8066 (goto-char pos))
8067 ;; A normal line.
8068 (setq initial-content
8069 (org-trim
8070 (delete-and-extract-region (point) (line-end-position))))))
8072 ;; If we are at the beginning of the line, insert before it.
8073 ;; Otherwise, after it.
8074 (cond
8075 ((and (bolp) (looking-at "[ \t]*$")))
8076 ((bolp) (save-excursion (insert "\n")))
8077 (t (end-of-line)
8078 (insert "\n")))
8080 ;; Insert the new heading
8081 (insert stars)
8082 (just-one-space)
8083 (insert initial-content)
8084 (unless (and blank (org-previous-line-empty-p))
8085 (org-N-empty-lines-before-current (if blank 1 0)))
8086 ;; Adjust visibility, which may be messed up if we removed
8087 ;; blank lines while previous entry was hidden.
8088 (let ((bol (line-beginning-position)))
8089 (dolist (o (overlays-at (1- bol)))
8090 (when (and (eq (overlay-get o 'invisible) 'outline)
8091 (eq (overlay-end o) bol))
8092 (move-overlay o (overlay-start o) (1- bol)))))
8093 (run-hooks 'org-insert-heading-hook)))))))
8095 (defun org-N-empty-lines-before-current (N)
8096 "Make the number of empty lines before current exactly N.
8097 So this will delete or add empty lines."
8098 (save-excursion
8099 (beginning-of-line)
8100 (let ((p (point)))
8101 (skip-chars-backward " \r\t\n")
8102 (unless (bolp) (forward-line))
8103 (delete-region (point) p))
8104 (when (> N 0) (insert (make-string N ?\n)))))
8106 (defun org-get-heading (&optional no-tags no-todo)
8107 "Return the heading of the current entry, without the stars.
8108 When NO-TAGS is non-nil, don't include tags.
8109 When NO-TODO is non-nil, don't include TODO keywords."
8110 (save-excursion
8111 (org-back-to-heading t)
8112 (let ((case-fold-search nil))
8113 (cond
8114 ((and no-tags no-todo)
8115 (looking-at org-complex-heading-regexp)
8116 ;; Return value has to be a string, but match group 4 is
8117 ;; optional.
8118 (or (match-string 4) ""))
8119 (no-tags
8120 (looking-at (concat org-outline-regexp
8121 "\\(.*?\\)"
8122 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8123 (match-string 1))
8124 (no-todo
8125 (looking-at org-todo-line-regexp)
8126 (match-string 3))
8127 (t (looking-at org-heading-regexp)
8128 (match-string 2))))))
8130 (defvar orgstruct-mode) ; defined below
8132 (defun org-heading-components ()
8133 "Return the components of the current heading.
8134 This is a list with the following elements:
8135 - the level as an integer
8136 - the reduced level, different if `org-odd-levels-only' is set.
8137 - the TODO keyword, or nil
8138 - the priority character, like ?A, or nil if no priority is given
8139 - the headline text itself, or the tags string if no headline text
8140 - the tags string, or nil."
8141 (save-excursion
8142 (org-back-to-heading t)
8143 (when (let (case-fold-search)
8144 (looking-at
8145 (if orgstruct-mode
8146 org-heading-regexp
8147 org-complex-heading-regexp)))
8148 (if orgstruct-mode
8149 (list (length (match-string 1))
8150 (org-reduced-level (length (match-string 1)))
8153 (match-string 2)
8154 nil)
8155 (list (length (match-string 1))
8156 (org-reduced-level (length (match-string 1)))
8157 (match-string-no-properties 2)
8158 (and (match-end 3) (aref (match-string 3) 2))
8159 (match-string-no-properties 4)
8160 (match-string-no-properties 5))))))
8162 (defun org-get-entry ()
8163 "Get the entry text, after heading, entire subtree."
8164 (save-excursion
8165 (org-back-to-heading t)
8166 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8168 (defun org-edit-headline (&optional heading)
8169 "Edit the current headline.
8170 Set it to HEADING when provided."
8171 (interactive)
8172 (org-with-wide-buffer
8173 (org-back-to-heading t)
8174 (let ((case-fold-search nil))
8175 (when (looking-at org-complex-heading-regexp)
8176 (let* ((old (match-string-no-properties 4))
8177 (new (save-match-data
8178 (org-trim (or heading (read-string "Edit: " old))))))
8179 (unless (equal old new)
8180 (if old (replace-match new t t nil 4)
8181 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8182 (insert " " new))
8183 (org-set-tags nil t)
8184 (when (looking-at "[ \t]*$") (replace-match ""))))))))
8186 (defun org-insert-heading-after-current ()
8187 "Insert a new heading with same level as current, after current subtree."
8188 (interactive)
8189 (org-back-to-heading)
8190 (org-insert-heading)
8191 (org-move-subtree-down)
8192 (end-of-line 1))
8194 (defun org-insert-heading-respect-content (&optional invisible-ok)
8195 "Insert heading with `org-insert-heading-respect-content' set to t."
8196 (interactive)
8197 (org-insert-heading '(4) invisible-ok))
8199 (defun org-insert-todo-heading-respect-content (&optional force-state)
8200 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8201 (interactive)
8202 (org-insert-todo-heading force-state '(4)))
8204 (defun org-insert-todo-heading (arg &optional force-heading)
8205 "Insert a new heading with the same level and TODO state as current heading.
8207 If the heading has no TODO state, or if the state is DONE, use
8208 the first state (TODO by default). Also with one prefix arg,
8209 force first state. With two prefix args, force inserting at the
8210 end of the parent subtree.
8212 When called at a plain list item, insert a new item with an
8213 unchecked check box."
8214 (interactive "P")
8215 (when (or force-heading (not (org-insert-item 'checkbox)))
8216 (org-insert-heading (or (and (equal arg '(16)) '(16))
8217 force-heading))
8218 (save-excursion
8219 (org-back-to-heading)
8220 (outline-previous-heading)
8221 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
8222 (let* ((new-mark-x
8223 (if (or (equal arg '(4))
8224 (not (match-beginning 2))
8225 (member (match-string 2) org-done-keywords))
8226 (car org-todo-keywords-1)
8227 (match-string 2)))
8228 (new-mark
8230 (run-hook-with-args-until-success
8231 'org-todo-get-default-hook new-mark-x nil)
8232 new-mark-x)))
8233 (beginning-of-line 1)
8234 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8235 (if org-treat-insert-todo-heading-as-state-change
8236 (org-todo new-mark)
8237 (insert new-mark " "))))
8238 (when org-provide-todo-statistics
8239 (org-update-parent-todo-statistics))))
8241 (defun org-insert-subheading (arg)
8242 "Insert a new subheading and demote it.
8243 Works for outline headings and for plain lists alike."
8244 (interactive "P")
8245 (org-insert-heading arg)
8246 (cond
8247 ((org-at-heading-p) (org-do-demote))
8248 ((org-at-item-p) (org-indent-item))))
8250 (defun org-insert-todo-subheading (arg)
8251 "Insert a new subheading with TODO keyword or checkbox and demote it.
8252 Works for outline headings and for plain lists alike."
8253 (interactive "P")
8254 (org-insert-todo-heading arg)
8255 (cond
8256 ((org-at-heading-p) (org-do-demote))
8257 ((org-at-item-p) (org-indent-item))))
8259 ;;; Promotion and Demotion
8261 (defvar org-after-demote-entry-hook nil
8262 "Hook run after an entry has been demoted.
8263 The cursor will be at the beginning of the entry.
8264 When a subtree is being demoted, the hook will be called for each node.")
8266 (defvar org-after-promote-entry-hook nil
8267 "Hook run after an entry has been promoted.
8268 The cursor will be at the beginning of the entry.
8269 When a subtree is being promoted, the hook will be called for each node.")
8271 (defun org-promote-subtree ()
8272 "Promote the entire subtree.
8273 See also `org-promote'."
8274 (interactive)
8275 (save-excursion
8276 (org-with-limited-levels (org-map-tree 'org-promote)))
8277 (org-fix-position-after-promote))
8279 (defun org-demote-subtree ()
8280 "Demote the entire subtree.
8281 See `org-demote' and `org-promote'."
8282 (interactive)
8283 (save-excursion
8284 (org-with-limited-levels (org-map-tree 'org-demote)))
8285 (org-fix-position-after-promote))
8287 (defun org-do-promote ()
8288 "Promote the current heading higher up the tree.
8289 If the region is active in `transient-mark-mode', promote all
8290 headings in the region."
8291 (interactive)
8292 (save-excursion
8293 (if (org-region-active-p)
8294 (org-map-region 'org-promote (region-beginning) (region-end))
8295 (org-promote)))
8296 (org-fix-position-after-promote))
8298 (defun org-do-demote ()
8299 "Demote the current heading lower down the tree.
8300 If the region is active in `transient-mark-mode', demote all
8301 headings in the region."
8302 (interactive)
8303 (save-excursion
8304 (if (org-region-active-p)
8305 (org-map-region 'org-demote (region-beginning) (region-end))
8306 (org-demote)))
8307 (org-fix-position-after-promote))
8309 (defun org-fix-position-after-promote ()
8310 "Fix cursor position and indentation after demoting/promoting."
8311 (let ((pos (point)))
8312 (when (save-excursion
8313 (beginning-of-line)
8314 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8315 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8316 (cond ((eobp) (insert " "))
8317 ((eolp) (insert " "))
8318 ((equal (char-after) ?\s) (forward-char 1))))))
8320 (defun org-current-level ()
8321 "Return the level of the current entry, or nil if before the first headline.
8322 The level is the number of stars at the beginning of the
8323 headline. Use `org-reduced-level' to remove the effect of
8324 `org-odd-levels'. Unlike to `org-outline-level', this function
8325 ignores inlinetasks."
8326 (let ((level (org-with-limited-levels (org-outline-level))))
8327 (and (> level 0) level)))
8329 (defun org-get-previous-line-level ()
8330 "Return the outline depth of the last headline before the current line.
8331 Returns 0 for the first headline in the buffer, and nil if before the
8332 first headline."
8333 (and (org-current-level)
8334 (or (and (/= (line-beginning-position) (point-min))
8335 (save-excursion (beginning-of-line 0) (org-current-level)))
8336 0)))
8338 (defun org-reduced-level (l)
8339 "Compute the effective level of a heading.
8340 This takes into account the setting of `org-odd-levels-only'."
8341 (cond
8342 ((zerop l) 0)
8343 (org-odd-levels-only (1+ (floor (/ l 2))))
8344 (t l)))
8346 (defun org-level-increment ()
8347 "Return the number of stars that will be added or removed at a
8348 time to headlines when structure editing, based on the value of
8349 `org-odd-levels-only'."
8350 (if org-odd-levels-only 2 1))
8352 (defun org-get-valid-level (level &optional change)
8353 "Rectify a level change under the influence of `org-odd-levels-only'
8354 LEVEL is a current level, CHANGE is by how much the level should be
8355 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8356 even level numbers will become the next higher odd number."
8357 (if org-odd-levels-only
8358 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8359 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8360 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8361 (max 1 (+ level (or change 0)))))
8363 (defun org-promote ()
8364 "Promote the current heading higher up the tree."
8365 (org-with-wide-buffer
8366 (org-back-to-heading t)
8367 (let* ((after-change-functions (remq 'flyspell-after-change-function
8368 after-change-functions))
8369 (level (save-match-data (funcall outline-level)))
8370 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8371 (diff (abs (- level (length up-head) -1))))
8372 (cond
8373 ((and (= level 1) org-allow-promoting-top-level-subtree)
8374 (replace-match "# " nil t))
8375 ((= level 1)
8376 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8377 (t (replace-match up-head nil t)))
8378 (unless (= level 1)
8379 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8380 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8381 (run-hooks 'org-after-promote-entry-hook))))
8383 (defun org-demote ()
8384 "Demote the current heading lower down the tree."
8385 (org-with-wide-buffer
8386 (org-back-to-heading t)
8387 (let* ((after-change-functions (remq 'flyspell-after-change-function
8388 after-change-functions))
8389 (level (save-match-data (funcall outline-level)))
8390 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8391 (diff (abs (- level (length down-head) -1))))
8392 (replace-match down-head nil t)
8393 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8394 (when org-adapt-indentation (org-fixup-indentation diff))
8395 (run-hooks 'org-after-demote-entry-hook))))
8397 (defun org-cycle-level ()
8398 "Cycle the level of an empty headline through possible states.
8399 This goes first to child, then to parent, level, then up the hierarchy.
8400 After top level, it switches back to sibling level."
8401 (interactive)
8402 (let ((org-adapt-indentation nil))
8403 (when (org-point-at-end-of-empty-headline)
8404 (setq this-command 'org-cycle-level) ; Only needed for caching
8405 (let ((cur-level (org-current-level))
8406 (prev-level (org-get-previous-line-level)))
8407 (cond
8408 ;; If first headline in file, promote to top-level.
8409 ((= prev-level 0)
8410 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8411 do (org-do-promote)))
8412 ;; If same level as prev, demote one.
8413 ((= prev-level cur-level)
8414 (org-do-demote))
8415 ;; If parent is top-level, promote to top level if not already.
8416 ((= prev-level 1)
8417 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8418 do (org-do-promote)))
8419 ;; If top-level, return to prev-level.
8420 ((= cur-level 1)
8421 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8422 do (org-do-demote)))
8423 ;; If less than prev-level, promote one.
8424 ((< cur-level prev-level)
8425 (org-do-promote))
8426 ;; If deeper than prev-level, promote until higher than
8427 ;; prev-level.
8428 ((> cur-level prev-level)
8429 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8430 do (org-do-promote))))
8431 t))))
8433 (defun org-map-tree (fun)
8434 "Call FUN for every heading underneath the current one."
8435 (org-back-to-heading t)
8436 (let ((level (funcall outline-level)))
8437 (save-excursion
8438 (funcall fun)
8439 (while (and (progn
8440 (outline-next-heading)
8441 (> (funcall outline-level) level))
8442 (not (eobp)))
8443 (funcall fun)))))
8445 (defun org-map-region (fun beg end)
8446 "Call FUN for every heading between BEG and END."
8447 (let ((org-ignore-region t))
8448 (save-excursion
8449 (setq end (copy-marker end))
8450 (goto-char beg)
8451 (when (and (re-search-forward org-outline-regexp-bol nil t)
8452 (< (point) end))
8453 (funcall fun))
8454 (while (and (progn
8455 (outline-next-heading)
8456 (< (point) end))
8457 (not (eobp)))
8458 (funcall fun)))))
8460 (defun org-fixup-indentation (diff)
8461 "Change the indentation in the current entry by DIFF.
8463 DIFF is an integer. Indentation is done according to the
8464 following rules:
8466 - Planning information and property drawers are always indented
8467 according to the new level of the headline;
8469 - Footnote definitions and their contents are ignored;
8471 - Inlinetasks' boundaries are not shifted;
8473 - Empty lines are ignored;
8475 - Other lines' indentation are shifted by DIFF columns, unless
8476 it would introduce a structural change in the document, in
8477 which case no shifting is done at all.
8479 Assume point is at a heading or an inlinetask beginning."
8480 (org-with-wide-buffer
8481 (narrow-to-region (line-beginning-position)
8482 (save-excursion
8483 (if (org-with-limited-levels (org-at-heading-p))
8484 (org-with-limited-levels (outline-next-heading))
8485 (org-inlinetask-goto-end))
8486 (point)))
8487 (forward-line)
8488 ;; Indent properly planning info and property drawer.
8489 (when (looking-at-p org-planning-line-re)
8490 (org-indent-line)
8491 (forward-line))
8492 (when (looking-at org-property-drawer-re)
8493 (goto-char (match-end 0))
8494 (forward-line)
8495 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8496 (catch 'no-shift
8497 (when (zerop diff) (throw 'no-shift nil))
8498 ;; If DIFF is negative, first check if a shift is possible at all
8499 ;; (e.g., it doesn't break structure). This can only happen if
8500 ;; some contents are not properly indented.
8501 (let ((case-fold-search t))
8502 (when (< diff 0)
8503 (let ((diff (- diff))
8504 (forbidden-re (concat org-outline-regexp
8505 "\\|"
8506 (substring org-footnote-definition-re 1))))
8507 (save-excursion
8508 (while (not (eobp))
8509 (cond
8510 ((looking-at-p "[ \t]*$") (forward-line))
8511 ((and (looking-at-p org-footnote-definition-re)
8512 (let ((e (org-element-at-point)))
8513 (and (eq (org-element-type e) 'footnote-definition)
8514 (goto-char (org-element-property :end e))))))
8515 ((looking-at-p org-outline-regexp) (forward-line))
8516 ;; Give up if shifting would move before column 0 or
8517 ;; if it would introduce a headline or a footnote
8518 ;; definition.
8520 (skip-chars-forward " \t")
8521 (let ((ind (current-column)))
8522 (when (or (< ind diff)
8523 (and (= ind diff) (looking-at-p forbidden-re)))
8524 (throw 'no-shift nil)))
8525 ;; Ignore contents of example blocks and source
8526 ;; blocks if their indentation is meant to be
8527 ;; preserved. Jump to block's closing line.
8528 (beginning-of-line)
8529 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8530 (let ((e (org-element-at-point)))
8531 (and (memq (org-element-type e)
8532 '(example-block src-block))
8533 (or org-src-preserve-indentation
8534 (org-element-property :preserve-indent e))
8535 (goto-char (org-element-property :end e))
8536 (progn (skip-chars-backward " \r\t\n")
8537 (beginning-of-line)
8538 t))))
8539 (forward-line))))))))
8540 ;; Shift lines but footnote definitions, inlinetasks boundaries
8541 ;; by DIFF. Also skip contents of source or example blocks
8542 ;; when indentation is meant to be preserved.
8543 (while (not (eobp))
8544 (cond
8545 ((and (looking-at-p org-footnote-definition-re)
8546 (let ((e (org-element-at-point)))
8547 (and (eq (org-element-type e) 'footnote-definition)
8548 (goto-char (org-element-property :end e))))))
8549 ((looking-at-p org-outline-regexp) (forward-line))
8550 ((looking-at-p "[ \t]*$") (forward-line))
8552 (indent-line-to (+ (org-get-indentation) diff))
8553 (beginning-of-line)
8554 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8555 (let ((e (org-element-at-point)))
8556 (and (memq (org-element-type e)
8557 '(example-block src-block))
8558 (or org-src-preserve-indentation
8559 (org-element-property :preserve-indent e))
8560 (goto-char (org-element-property :end e))
8561 (progn (skip-chars-backward " \r\t\n")
8562 (beginning-of-line)
8563 t))))
8564 (forward-line)))))))))
8566 (defun org-convert-to-odd-levels ()
8567 "Convert an Org file with all levels allowed to one with odd levels.
8568 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8569 level 5 etc."
8570 (interactive)
8571 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8572 (let ((outline-level 'org-outline-level)
8573 (org-odd-levels-only nil) n)
8574 (save-excursion
8575 (goto-char (point-min))
8576 (while (re-search-forward "^\\*\\*+ " nil t)
8577 (setq n (- (length (match-string 0)) 2))
8578 (while (>= (setq n (1- n)) 0)
8579 (org-demote))
8580 (end-of-line 1))))))
8582 (defun org-convert-to-oddeven-levels ()
8583 "Convert an Org file with only odd levels to one with odd/even levels.
8584 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8585 file contains a section with an even level, conversion would
8586 destroy the structure of the file. An error is signaled in this
8587 case."
8588 (interactive)
8589 (goto-char (point-min))
8590 ;; First check if there are no even levels
8591 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8592 (org-show-set-visibility 'canonical)
8593 (error "Not all levels are odd in this file. Conversion not possible"))
8594 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8595 (let ((outline-regexp org-outline-regexp)
8596 (outline-level 'org-outline-level)
8597 (org-odd-levels-only nil) n)
8598 (save-excursion
8599 (goto-char (point-min))
8600 (while (re-search-forward "^\\*\\*+ " nil t)
8601 (setq n (/ (1- (length (match-string 0))) 2))
8602 (while (>= (setq n (1- n)) 0)
8603 (org-promote))
8604 (end-of-line 1))))))
8606 (defun org-tr-level (n)
8607 "Make N odd if required."
8608 (if org-odd-levels-only (1+ (/ n 2)) n))
8610 ;;; Vertical tree motion, cutting and pasting of subtrees
8612 (defun org-move-subtree-up (&optional arg)
8613 "Move the current subtree up past ARG headlines of the same level."
8614 (interactive "p")
8615 (org-move-subtree-down (- (prefix-numeric-value arg))))
8617 (defun org-move-subtree-down (&optional arg)
8618 "Move the current subtree down past ARG headlines of the same level."
8619 (interactive "p")
8620 (setq arg (prefix-numeric-value arg))
8621 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8622 'org-get-last-sibling))
8623 (ins-point (make-marker))
8624 (cnt (abs arg))
8625 (col (current-column))
8626 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8627 ;; Select the tree
8628 (org-back-to-heading)
8629 (setq beg0 (point))
8630 (save-excursion
8631 (setq ne-beg (org-back-over-empty-lines))
8632 (setq beg (point)))
8633 (save-match-data
8634 (save-excursion (outline-end-of-heading)
8635 (setq folded (outline-invisible-p)))
8636 (progn (org-end-of-subtree nil t)
8637 (unless (eobp) (backward-char))))
8638 (outline-next-heading)
8639 (setq ne-end (org-back-over-empty-lines))
8640 (setq end (point))
8641 (goto-char beg0)
8642 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8643 ;; include less whitespace
8644 (save-excursion
8645 (goto-char beg)
8646 (forward-line (- ne-beg ne-end))
8647 (setq beg (point))))
8648 ;; Find insertion point, with error handling
8649 (while (> cnt 0)
8650 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8651 (progn (goto-char beg0)
8652 (user-error "Cannot move past superior level or buffer limit")))
8653 (setq cnt (1- cnt)))
8654 (when (> arg 0)
8655 ;; Moving forward - still need to move over subtree
8656 (org-end-of-subtree t t)
8657 (save-excursion
8658 (org-back-over-empty-lines)
8659 (or (bolp) (newline))))
8660 (setq ne-ins (org-back-over-empty-lines))
8661 (move-marker ins-point (point))
8662 (setq txt (buffer-substring beg end))
8663 (org-save-markers-in-region beg end)
8664 (delete-region beg end)
8665 (org-remove-empty-overlays-at beg)
8666 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8667 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8668 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8669 (let ((bbb (point)))
8670 (insert-before-markers txt)
8671 (org-reinstall-markers-in-region bbb)
8672 (move-marker ins-point bbb))
8673 (or (bolp) (insert "\n"))
8674 (setq ins-end (point))
8675 (goto-char ins-point)
8676 (org-skip-whitespace)
8677 (when (and (< arg 0)
8678 (org-first-sibling-p)
8679 (> ne-ins ne-beg))
8680 ;; Move whitespace back to beginning
8681 (save-excursion
8682 (goto-char ins-end)
8683 (let ((kill-whole-line t))
8684 (kill-line (- ne-ins ne-beg)) (point)))
8685 (insert (make-string (- ne-ins ne-beg) ?\n)))
8686 (move-marker ins-point nil)
8687 (if folded
8688 (outline-hide-subtree)
8689 (org-show-entry)
8690 (org-show-children)
8691 (org-cycle-hide-drawers 'children))
8692 (org-clean-visibility-after-subtree-move)
8693 ;; move back to the initial column we were at
8694 (move-to-column col)))
8696 (defvar org-subtree-clip ""
8697 "Clipboard for cut and paste of subtrees.
8698 This is actually only a copy of the kill, because we use the normal kill
8699 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8701 (defvar org-subtree-clip-folded nil
8702 "Was the last copied subtree folded?
8703 This is used to fold the tree back after pasting.")
8705 (defun org-cut-subtree (&optional n)
8706 "Cut the current subtree into the clipboard.
8707 With prefix arg N, cut this many sequential subtrees.
8708 This is a short-hand for marking the subtree and then cutting it."
8709 (interactive "p")
8710 (org-copy-subtree n 'cut))
8712 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8713 "Copy the current subtree it in the clipboard.
8714 With prefix arg N, copy this many sequential subtrees.
8715 This is a short-hand for marking the subtree and then copying it.
8716 If CUT is non-nil, actually cut the subtree.
8717 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8718 of some markers in the region, even if CUT is non-nil. This is
8719 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8720 (interactive "p")
8721 (let (beg end folded (beg0 (point)))
8722 (if (called-interactively-p 'any)
8723 (org-back-to-heading nil) ; take what looks like a subtree
8724 (org-back-to-heading t)) ; take what is really there
8725 (setq beg (point))
8726 (skip-chars-forward " \t\r\n")
8727 (save-match-data
8728 (if nosubtrees
8729 (outline-next-heading)
8730 (save-excursion (outline-end-of-heading)
8731 (setq folded (outline-invisible-p)))
8732 (ignore-errors (org-forward-heading-same-level (1- n) t))
8733 (org-end-of-subtree t t)))
8734 ;; Include the end of an inlinetask
8735 (when (and (featurep 'org-inlinetask)
8736 (looking-at-p (concat (org-inlinetask-outline-regexp)
8737 "END[ \t]*$")))
8738 (end-of-line))
8739 (setq end (point))
8740 (goto-char beg0)
8741 (when (> end beg)
8742 (setq org-subtree-clip-folded folded)
8743 (when (or cut force-store-markers)
8744 (org-save-markers-in-region beg end))
8745 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8746 (setq org-subtree-clip (current-kill 0))
8747 (message "%s: Subtree(s) with %d characters"
8748 (if cut "Cut" "Copied")
8749 (length org-subtree-clip)))))
8751 (defun org-paste-subtree (&optional level tree for-yank remove)
8752 "Paste the clipboard as a subtree, with modification of headline level.
8753 The entire subtree is promoted or demoted in order to match a new headline
8754 level.
8756 If the cursor is at the beginning of a headline, the same level as
8757 that headline is used to paste the tree.
8759 If not, the new level is derived from the *visible* headings
8760 before and after the insertion point, and taken to be the inferior headline
8761 level of the two. So if the previous visible heading is level 3 and the
8762 next is level 4 (or vice versa), level 4 will be used for insertion.
8763 This makes sure that the subtree remains an independent subtree and does
8764 not swallow low level entries.
8766 You can also force a different level, either by using a numeric prefix
8767 argument, or by inserting the heading marker by hand. For example, if the
8768 cursor is after \"*****\", then the tree will be shifted to level 5.
8770 If optional TREE is given, use this text instead of the kill ring.
8772 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8773 move back over whitespace before inserting, and move point to the end of
8774 the inserted text when done.
8776 When REMOVE is non-nil, remove the subtree from the clipboard."
8777 (interactive "P")
8778 (setq tree (or tree (and kill-ring (current-kill 0))))
8779 (unless (org-kill-is-subtree-p tree)
8780 (user-error "%s"
8781 (substitute-command-keys
8782 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8783 (org-with-limited-levels
8784 (let* ((visp (not (outline-invisible-p)))
8785 (txt tree)
8786 (^re_ "\\(\\*+\\)[ \t]*")
8787 (old-level (if (string-match org-outline-regexp-bol txt)
8788 (- (match-end 0) (match-beginning 0) 1)
8789 -1))
8790 (force-level (cond (level (prefix-numeric-value level))
8791 ((and (looking-at "[ \t]*$")
8792 (string-match
8793 "^\\*+$" (buffer-substring
8794 (point-at-bol) (point))))
8795 (- (match-end 0) (match-beginning 0)))
8796 ((and (bolp)
8797 (looking-at org-outline-regexp))
8798 (- (match-end 0) (point) 1))))
8799 (previous-level (save-excursion
8800 (condition-case nil
8801 (progn
8802 (outline-previous-visible-heading 1)
8803 (if (looking-at ^re_)
8804 (- (match-end 0) (match-beginning 0) 1)
8806 (error 1))))
8807 (next-level (save-excursion
8808 (condition-case nil
8809 (progn
8810 (or (looking-at org-outline-regexp)
8811 (outline-next-visible-heading 1))
8812 (if (looking-at ^re_)
8813 (- (match-end 0) (match-beginning 0) 1)
8815 (error 1))))
8816 (new-level (or force-level (max previous-level next-level)))
8817 (shift (if (or (= old-level -1)
8818 (= new-level -1)
8819 (= old-level new-level))
8821 (- new-level old-level)))
8822 (delta (if (> shift 0) -1 1))
8823 (func (if (> shift 0) 'org-demote 'org-promote))
8824 (org-odd-levels-only nil)
8825 beg end newend)
8826 ;; Remove the forced level indicator
8827 (when force-level
8828 (delete-region (point-at-bol) (point)))
8829 ;; Paste
8830 (beginning-of-line (if (bolp) 1 2))
8831 (setq beg (point))
8832 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8833 (insert-before-markers txt)
8834 (unless (string-suffix-p "\n" txt) (insert "\n"))
8835 (setq newend (point))
8836 (org-reinstall-markers-in-region beg)
8837 (setq end (point))
8838 (goto-char beg)
8839 (skip-chars-forward " \t\n\r")
8840 (setq beg (point))
8841 (when (and (outline-invisible-p) visp)
8842 (save-excursion (outline-show-heading)))
8843 ;; Shift if necessary
8844 (unless (= shift 0)
8845 (save-restriction
8846 (narrow-to-region beg end)
8847 (while (not (= shift 0))
8848 (org-map-region func (point-min) (point-max))
8849 (setq shift (+ delta shift)))
8850 (goto-char (point-min))
8851 (setq newend (point-max))))
8852 (when (or (called-interactively-p 'interactive) for-yank)
8853 (message "Clipboard pasted as level %d subtree" new-level))
8854 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8855 kill-ring
8856 (eq org-subtree-clip (current-kill 0))
8857 org-subtree-clip-folded)
8858 ;; The tree was folded before it was killed/copied
8859 (outline-hide-subtree))
8860 (and for-yank (goto-char newend))
8861 (and remove (setq kill-ring (cdr kill-ring))))))
8863 (defun org-kill-is-subtree-p (&optional txt)
8864 "Check if the current kill is an outline subtree, or a set of trees.
8865 Returns nil if kill does not start with a headline, or if the first
8866 headline level is not the largest headline level in the tree.
8867 So this will actually accept several entries of equal levels as well,
8868 which is OK for `org-paste-subtree'.
8869 If optional TXT is given, check this string instead of the current kill."
8870 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8871 (re (org-get-limited-outline-regexp))
8872 (^re (concat "^" re))
8873 (start-level (and kill
8874 (string-match
8875 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8876 kill)
8877 (- (match-end 2) (match-beginning 2) 1)))
8878 (start (1+ (or (match-beginning 2) -1))))
8879 (if (not start-level)
8880 (progn
8881 nil) ;; does not even start with a heading
8882 (catch 'exit
8883 (while (setq start (string-match ^re kill (1+ start)))
8884 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8885 (throw 'exit nil)))
8886 t))))
8888 (defvar org-markers-to-move nil
8889 "Markers that should be moved with a cut-and-paste operation.
8890 Those markers are stored together with their positions relative to
8891 the start of the region.")
8893 (defun org-save-markers-in-region (beg end)
8894 "Check markers in region.
8895 If these markers are between BEG and END, record their position relative
8896 to BEG, so that after moving the block of text, we can put the markers back
8897 into place.
8898 This function gets called just before an entry or tree gets cut from the
8899 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8900 called immediately, to move the markers with the entries."
8901 (setq org-markers-to-move nil)
8902 (when (featurep 'org-clock)
8903 (org-clock-save-markers-for-cut-and-paste beg end))
8904 (when (featurep 'org-agenda)
8905 (org-agenda-save-markers-for-cut-and-paste beg end)))
8907 (defun org-check-and-save-marker (marker beg end)
8908 "Check if MARKER is between BEG and END.
8909 If yes, remember the marker and the distance to BEG."
8910 (when (and (marker-buffer marker)
8911 (equal (marker-buffer marker) (current-buffer))
8912 (>= marker beg) (< marker end))
8913 (push (cons marker (- marker beg)) org-markers-to-move)))
8915 (defun org-reinstall-markers-in-region (beg)
8916 "Move all remembered markers to their position relative to BEG."
8917 (dolist (x org-markers-to-move)
8918 (move-marker (car x) (+ beg (cdr x))))
8919 (setq org-markers-to-move nil))
8921 (defun org-narrow-to-subtree ()
8922 "Narrow buffer to the current subtree."
8923 (interactive)
8924 (save-excursion
8925 (save-match-data
8926 (org-with-limited-levels
8927 (narrow-to-region
8928 (progn (org-back-to-heading t) (point))
8929 (progn (org-end-of-subtree t t)
8930 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8931 (point)))))))
8933 (defun org-narrow-to-block ()
8934 "Narrow buffer to the current block."
8935 (interactive)
8936 (let* ((case-fold-search t)
8937 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8938 "^[ \t]*#\\+end_.*")))
8939 (if blockp
8940 (narrow-to-region (car blockp) (cdr blockp))
8941 (user-error "Not in a block"))))
8943 (defun org-clone-subtree-with-time-shift (n &optional shift)
8944 "Clone the task (subtree) at point N times.
8945 The clones will be inserted as siblings.
8947 In interactive use, the user will be prompted for the number of
8948 clones to be produced. If the entry has a timestamp, the user
8949 will also be prompted for a time shift, which may be a repeater
8950 as used in time stamps, for example `+3d'. To disable this,
8951 you can call the function with a universal prefix argument.
8953 When a valid repeater is given and the entry contains any time
8954 stamps, the clones will become a sequence in time, with time
8955 stamps in the subtree shifted for each clone produced. If SHIFT
8956 is nil or the empty string, time stamps will be left alone. The
8957 ID property of the original subtree is removed.
8959 In each clone, all the CLOCK entries will be removed. This
8960 prevents Org from considering that the clocked times overlap.
8962 If the original subtree did contain time stamps with a repeater,
8963 the following will happen:
8964 - the repeater will be removed in each clone
8965 - an additional clone will be produced, with the current, unshifted
8966 date(s) in the entry.
8967 - the original entry will be placed *after* all the clones, with
8968 repeater intact.
8969 - the start days in the repeater in the original entry will be shifted
8970 to past the last clone.
8971 In this way you can spell out a number of instances of a repeating task,
8972 and still retain the repeater to cover future instances of the task.
8974 As described above, N+1 clones are produced when the original
8975 subtree has a repeater. Setting N to 0, then, can be used to
8976 remove the repeater from a subtree and create a shifted clone
8977 with the original repeater."
8978 (interactive "nNumber of clones to produce: ")
8979 (let ((shift
8980 (or shift
8981 (if (and (not (equal current-prefix-arg '(4)))
8982 (save-excursion
8983 (re-search-forward org-ts-regexp-both
8984 (save-excursion
8985 (org-end-of-subtree t)
8986 (point)) t)))
8987 (read-from-minibuffer
8988 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8989 ""))) ;; No time shift
8990 (n-no-remove -1)
8991 (drawer-re org-drawer-regexp)
8992 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8993 beg end template task idprop
8994 shift-n shift-what doshift nmin nmax)
8995 (unless (wholenump n)
8996 (user-error "Invalid number of replications %s" n))
8997 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8998 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8999 shift)))
9000 (user-error "Invalid shift specification %s" shift))
9001 (when doshift
9002 (setq shift-n (string-to-number (match-string 1 shift))
9003 shift-what (cdr (assoc (match-string 2 shift)
9004 '(("d" . day) ("w" . week)
9005 ("m" . month) ("y" . year))))))
9006 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
9007 (setq nmin 1 nmax n)
9008 (org-back-to-heading t)
9009 (setq beg (point))
9010 (setq idprop (org-entry-get nil "ID"))
9011 (org-end-of-subtree t t)
9012 (or (bolp) (insert "\n"))
9013 (setq end (point))
9014 (setq template (buffer-substring beg end))
9015 (when (and doshift
9016 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
9017 (delete-region beg end)
9018 (setq end beg)
9019 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
9020 (goto-char end)
9021 (cl-loop for n from nmin to nmax do
9022 ;; prepare clone
9023 (with-temp-buffer
9024 (insert template)
9025 (org-mode)
9026 (goto-char (point-min))
9027 (org-show-subtree)
9028 (and idprop (if org-clone-delete-id
9029 (org-entry-delete nil "ID")
9030 (org-id-get-create t)))
9031 (unless (= n 0)
9032 (while (re-search-forward org-clock-re nil t)
9033 (kill-whole-line))
9034 (goto-char (point-min))
9035 (while (re-search-forward drawer-re nil t)
9036 (org-remove-empty-drawer-at (point))))
9037 (goto-char (point-min))
9038 (when doshift
9039 (while (re-search-forward org-ts-regexp-both nil t)
9040 (org-timestamp-change (* n shift-n) shift-what))
9041 (unless (= n n-no-remove)
9042 (goto-char (point-min))
9043 (while (re-search-forward org-ts-regexp nil t)
9044 (save-excursion
9045 (goto-char (match-beginning 0))
9046 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
9047 (delete-region (match-beginning 1) (match-end 1)))))))
9048 (setq task (buffer-string)))
9049 (insert task))
9050 (goto-char beg)))
9052 ;;; Outline Sorting
9054 (defun org-sort (with-case)
9055 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
9056 Optional argument WITH-CASE means sort case-sensitively."
9057 (interactive "P")
9058 (cond
9059 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
9060 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
9062 (org-call-with-arg 'org-sort-entries with-case))))
9064 (defun org-sort-remove-invisible (s)
9065 "Remove invisible links from string S."
9066 (remove-text-properties 0 (length s) org-rm-props s)
9067 (while (string-match org-bracket-link-regexp s)
9068 (setq s (replace-match (if (match-end 2)
9069 (match-string 3 s)
9070 (match-string 1 s))
9071 t t s)))
9072 (let ((st (format " %s " s)))
9073 (while (string-match org-emph-re st)
9074 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
9075 (setq s (substring st 1 -1)))
9078 (defvar org-priority-regexp) ; defined later in the file
9080 (defvar org-after-sorting-entries-or-items-hook nil
9081 "Hook that is run after a bunch of entries or items have been sorted.
9082 When children are sorted, the cursor is in the parent line when this
9083 hook gets called. When a region or a plain list is sorted, the cursor
9084 will be in the first entry of the sorted region/list.")
9086 (defun org-sort-entries
9087 (&optional with-case sorting-type getkey-func compare-func property)
9088 "Sort entries on a certain level of an outline tree.
9089 If there is an active region, the entries in the region are sorted.
9090 Else, if the cursor is before the first entry, sort the top-level items.
9091 Else, the children of the entry at point are sorted.
9093 Sorting can be alphabetically, numerically, by date/time as given by
9094 a time stamp, by a property, by priority order, or by a custom function.
9096 The command prompts for the sorting type unless it has been given to the
9097 function through the SORTING-TYPE argument, which needs to be a character,
9098 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9099 the precise meaning of each character:
9101 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9102 c By creation time, which is assumed to be the first inactive time stamp
9103 at the beginning of a line.
9104 d By deadline date/time.
9105 k By clocking time.
9106 n Numerically, by converting the beginning of the entry/item to a number.
9107 o By order of TODO keywords.
9108 p By priority according to the cookie.
9109 r By the value of a property.
9110 s By scheduled date/time.
9111 t By date/time, either the first active time stamp in the entry, or, if
9112 none exist, by the first inactive one.
9114 Capital letters will reverse the sort order.
9116 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9117 called with point at the beginning of the record. It must return either
9118 a string or a number that should serve as the sorting key for that record.
9120 Comparing entries ignores case by default. However, with an optional argument
9121 WITH-CASE, the sorting considers case as well.
9123 Sorting is done against the visible part of the headlines, it ignores hidden
9124 links.
9126 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
9127 (interactive "P")
9128 (let ((case-func (if with-case 'identity 'downcase))
9129 (cmstr
9130 ;; The clock marker is lost when using `sort-subr', let's
9131 ;; store the clocking string.
9132 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9133 (save-excursion
9134 (goto-char org-clock-marker)
9135 (buffer-substring-no-properties (line-beginning-position)
9136 (point)))))
9137 start beg end stars re re2
9138 txt what tmp)
9139 ;; Find beginning and end of region to sort
9140 (cond
9141 ((org-region-active-p)
9142 ;; we will sort the region
9143 (setq end (region-end)
9144 what "region")
9145 (goto-char (region-beginning))
9146 (unless (org-at-heading-p) (outline-next-heading))
9147 (setq start (point)))
9148 ((or (org-at-heading-p)
9149 (ignore-errors (progn (org-back-to-heading) t)))
9150 ;; we will sort the children of the current headline
9151 (org-back-to-heading)
9152 (setq start (point)
9153 end (progn (org-end-of-subtree t t)
9154 (or (bolp) (insert "\n"))
9155 (when (>= (org-back-over-empty-lines) 1)
9156 (forward-line 1))
9157 (point))
9158 what "children")
9159 (goto-char start)
9160 (outline-show-subtree)
9161 (outline-next-heading))
9163 ;; we will sort the top-level entries in this file
9164 (goto-char (point-min))
9165 (or (org-at-heading-p) (outline-next-heading))
9166 (setq start (point))
9167 (goto-char (point-max))
9168 (beginning-of-line 1)
9169 (when (looking-at ".*?\\S-")
9170 ;; File ends in a non-white line
9171 (end-of-line 1)
9172 (insert "\n"))
9173 (setq end (point-max))
9174 (setq what "top-level")
9175 (goto-char start)
9176 (outline-show-all)))
9178 (setq beg (point))
9179 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9181 (looking-at "\\(\\*+\\)")
9182 (setq stars (match-string 1)
9183 re (concat "^" (regexp-quote stars) " +")
9184 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9185 txt (buffer-substring beg end))
9186 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9187 (when (and (not (equal stars "*")) (string-match re2 txt))
9188 (user-error "Region to sort contains a level above the first entry"))
9190 (unless sorting-type
9191 (message
9192 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9193 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9194 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9195 what)
9196 (setq sorting-type (read-char-exclusive))
9198 (unless getkey-func
9199 (and (= (downcase sorting-type) ?f)
9200 (setq getkey-func
9201 (completing-read "Sort using function: "
9202 obarray 'fboundp t nil nil))
9203 (setq getkey-func (intern getkey-func))))
9205 (and (= (downcase sorting-type) ?r)
9206 (not property)
9207 (setq property
9208 (completing-read "Property: "
9209 (mapcar #'list (org-buffer-property-keys t))
9210 nil t))))
9212 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9213 (message "Sorting entries...")
9215 (save-restriction
9216 (narrow-to-region start end)
9217 (let ((dcst (downcase sorting-type))
9218 (case-fold-search nil)
9219 (now (current-time)))
9220 (sort-subr
9221 (/= dcst sorting-type)
9222 ;; This function moves to the beginning character of the "record" to
9223 ;; be sorted.
9224 (lambda nil
9225 (if (re-search-forward re nil t)
9226 (goto-char (match-beginning 0))
9227 (goto-char (point-max))))
9228 ;; This function moves to the last character of the "record" being
9229 ;; sorted.
9230 (lambda nil
9231 (save-match-data
9232 (condition-case nil
9233 (outline-forward-same-level 1)
9234 (error
9235 (goto-char (point-max))))))
9236 ;; This function returns the value that gets sorted against.
9237 (lambda nil
9238 (cond
9239 ((= dcst ?n)
9240 (if (looking-at org-complex-heading-regexp)
9241 (string-to-number (org-sort-remove-invisible (match-string 4)))
9242 nil))
9243 ((= dcst ?a)
9244 (if (looking-at org-complex-heading-regexp)
9245 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9246 nil))
9247 ((= dcst ?k)
9248 (or (get-text-property (point) :org-clock-minutes) 0))
9249 ((= dcst ?t)
9250 (let ((end (save-excursion (outline-next-heading) (point))))
9251 (if (or (re-search-forward org-ts-regexp end t)
9252 (re-search-forward org-ts-regexp-both end t))
9253 (org-time-string-to-seconds (match-string 0))
9254 (float-time now))))
9255 ((= dcst ?c)
9256 (let ((end (save-excursion (outline-next-heading) (point))))
9257 (if (re-search-forward
9258 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9259 end t)
9260 (org-time-string-to-seconds (match-string 0))
9261 (float-time now))))
9262 ((= dcst ?s)
9263 (let ((end (save-excursion (outline-next-heading) (point))))
9264 (if (re-search-forward org-scheduled-time-regexp end t)
9265 (org-time-string-to-seconds (match-string 1))
9266 (float-time now))))
9267 ((= dcst ?d)
9268 (let ((end (save-excursion (outline-next-heading) (point))))
9269 (if (re-search-forward org-deadline-time-regexp end t)
9270 (org-time-string-to-seconds (match-string 1))
9271 (float-time now))))
9272 ((= dcst ?p)
9273 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9274 (string-to-char (match-string 2))
9275 org-default-priority))
9276 ((= dcst ?r)
9277 (or (org-entry-get nil property) ""))
9278 ((= dcst ?o)
9279 (when (looking-at org-complex-heading-regexp)
9280 (let* ((m (match-string 2))
9281 (s (if (member m org-done-keywords) '- '+)))
9282 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9283 ((= dcst ?f)
9284 (if getkey-func
9285 (progn
9286 (setq tmp (funcall getkey-func))
9287 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9288 tmp)
9289 (error "Invalid key function `%s'" getkey-func)))
9290 (t (error "Invalid sorting type `%c'" sorting-type))))
9292 (cond
9293 ((= dcst ?a) 'string<)
9294 ((= dcst ?f) compare-func)
9295 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9296 (run-hooks 'org-after-sorting-entries-or-items-hook)
9297 ;; Reset the clock marker if needed
9298 (when cmstr
9299 (save-excursion
9300 (goto-char start)
9301 (search-forward cmstr nil t)
9302 (move-marker org-clock-marker (point))))
9303 (message "Sorting entries...done")))
9305 ;;; The orgstruct minor mode
9307 ;; Define a minor mode which can be used in other modes in order to
9308 ;; integrate the Org mode structure editing commands.
9310 ;; This is really a hack, because the Org mode structure commands use
9311 ;; keys which normally belong to the major mode. Here is how it
9312 ;; works: The minor mode defines all the keys necessary to operate the
9313 ;; structure commands, but wraps the commands into a function which
9314 ;; tests if the cursor is currently at a headline or a plain list
9315 ;; item. If that is the case, the structure command is used,
9316 ;; temporarily setting many Org mode variables like regular
9317 ;; expressions for filling etc. However, when any of those keys is
9318 ;; used at a different location, function uses `key-binding' to look
9319 ;; up if the key has an associated command in another currently active
9320 ;; keymap (minor modes, major mode, global), and executes that
9321 ;; command. There might be problems if any of the keys is otherwise
9322 ;; used as a prefix key.
9324 (defcustom orgstruct-heading-prefix-regexp ""
9325 "Regexp that matches the custom prefix of Org headlines in
9326 orgstruct(++)-mode."
9327 :group 'org
9328 :version "24.4"
9329 :package-version '(Org . "8.3")
9330 :type 'regexp)
9331 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9333 (defcustom orgstruct-setup-hook nil
9334 "Hook run after orgstruct-mode-map is filled."
9335 :group 'org
9336 :version "24.4"
9337 :package-version '(Org . "8.0")
9338 :type 'hook)
9340 (defvar orgstruct-initialized nil)
9342 (defvar org-local-vars nil
9343 "List of local variables, for use by `orgstruct-mode'.")
9345 ;;;###autoload
9346 (define-minor-mode orgstruct-mode
9347 "Toggle the minor mode `orgstruct-mode'.
9348 This mode is for using Org mode structure commands in other
9349 modes. The following keys behave as if Org mode were active, if
9350 the cursor is on a headline, or on a plain list item (both as
9351 defined by Org mode)."
9352 nil " OrgStruct" (make-sparse-keymap)
9353 (funcall (if orgstruct-mode
9354 'add-to-invisibility-spec
9355 'remove-from-invisibility-spec)
9356 '(outline . t))
9357 (when orgstruct-mode
9358 (org-load-modules-maybe)
9359 (unless orgstruct-initialized
9360 (orgstruct-setup)
9361 (setq orgstruct-initialized t))))
9363 ;;;###autoload
9364 (defun turn-on-orgstruct ()
9365 "Unconditionally turn on `orgstruct-mode'."
9366 (orgstruct-mode 1))
9368 (defvar-local orgstruct-is-++ nil
9369 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9370 (defvar-local org-fb-vars nil)
9371 (defun orgstruct++-mode (&optional arg)
9372 "Toggle `orgstruct-mode', the enhanced version of it.
9373 In addition to setting orgstruct-mode, this also exports all
9374 indentation and autofilling variables from Org mode into the
9375 buffer. It will also recognize item context in multiline items."
9376 (interactive "P")
9377 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9378 (if (< arg 1)
9379 (progn (orgstruct-mode -1)
9380 (dolist (v org-fb-vars)
9381 (set (make-local-variable (car v))
9382 (if (eq (car-safe (cadr v)) 'quote)
9383 (cl-cadadr v)
9384 (nth 1 v)))))
9385 (orgstruct-mode 1)
9386 (setq org-fb-vars nil)
9387 (unless org-local-vars
9388 (setq org-local-vars (org-get-local-variables)))
9389 (let (var val)
9390 (dolist (x org-local-vars)
9391 (when (string-match
9392 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9393 \\|fill-prefix\\|indent-\\)"
9394 (symbol-name (car x)))
9395 (setq var (car x) val (nth 1 x))
9396 (push (list var `(quote ,(eval var))) org-fb-vars)
9397 (set (make-local-variable var)
9398 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9399 (setq-local orgstruct-is-++ t))))
9401 ;;;###autoload
9402 (defun turn-on-orgstruct++ ()
9403 "Unconditionally turn on `orgstruct++-mode'."
9404 (orgstruct++-mode 1))
9406 (defun orgstruct-error ()
9407 "Error when there is no default binding for a structure key."
9408 (interactive)
9409 (funcall (if (fboundp 'user-error)
9410 'user-error
9411 'error)
9412 "This key has no function outside structure elements"))
9414 (defun orgstruct-setup ()
9415 "Setup orgstruct keymap."
9416 (dolist (cell '((org-demote . t)
9417 (org-metaleft . t)
9418 (org-metaright . t)
9419 (org-promote . t)
9420 (org-shiftmetaleft . t)
9421 (org-shiftmetaright . t)
9422 org-backward-element
9423 org-backward-heading-same-level
9424 org-ctrl-c-ret
9425 org-ctrl-c-minus
9426 org-ctrl-c-star
9427 org-cycle
9428 org-force-cycle-archived
9429 org-forward-heading-same-level
9430 org-insert-heading
9431 org-insert-heading-respect-content
9432 org-kill-note-or-show-branches
9433 org-mark-subtree
9434 org-meta-return
9435 org-metadown
9436 org-metaup
9437 org-narrow-to-subtree
9438 org-promote-subtree
9439 org-reveal
9440 org-shiftdown
9441 org-shiftleft
9442 org-shiftmetadown
9443 org-shiftmetaup
9444 org-shiftright
9445 org-shifttab
9446 org-shifttab
9447 org-shiftup
9448 org-show-children
9449 org-show-subtree
9450 org-sort
9451 org-up-element
9452 outline-demote
9453 outline-next-visible-heading
9454 outline-previous-visible-heading
9455 outline-promote
9456 outline-up-heading))
9457 (let ((f (or (car-safe cell) cell))
9458 (disable-when-heading-prefix (cdr-safe cell)))
9459 (when (fboundp f)
9460 (let ((new-bindings))
9461 (dolist (binding (nconc (where-is-internal f org-mode-map)
9462 (where-is-internal f outline-mode-map)))
9463 (push binding new-bindings)
9464 ;; TODO use local-function-key-map
9465 (dolist (rep '(("<tab>" . "TAB")
9466 ("<return>" . "RET")
9467 ("<escape>" . "ESC")
9468 ("<delete>" . "DEL")))
9469 (setq binding (read-kbd-macro
9470 (let ((case-fold-search))
9471 (replace-regexp-in-string
9472 (regexp-quote (cdr rep))
9473 (car rep)
9474 (key-description binding)))))
9475 (cl-pushnew binding new-bindings :test 'equal)))
9476 (dolist (binding new-bindings)
9477 (let ((key (lookup-key orgstruct-mode-map binding)))
9478 (when (or (not key) (numberp key))
9479 (ignore-errors
9480 (org-defkey orgstruct-mode-map
9481 binding
9482 (orgstruct-make-binding
9483 f binding disable-when-heading-prefix))))))))))
9484 (run-hooks 'orgstruct-setup-hook))
9486 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9487 "Create a function for binding in the structure minor mode.
9488 FUN is the command to call inside a table. KEY is the key that
9489 should be checked in for a command to execute outside of tables.
9490 Non-nil `disable-when-heading-prefix' means to disable the command
9491 if `orgstruct-heading-prefix-regexp' is not empty."
9492 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9493 (let ((nname name)
9494 (i 0))
9495 (while (fboundp (intern nname))
9496 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9497 (setq name (intern nname)))
9498 (eval
9499 (let ((bindings '((org-heading-regexp
9500 (concat "^"
9501 orgstruct-heading-prefix-regexp
9502 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9503 (org-outline-regexp
9504 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9505 (org-outline-regexp-bol
9506 (concat "^" org-outline-regexp))
9507 (outline-regexp org-outline-regexp)
9508 (outline-heading-end-regexp "\n")
9509 (outline-level 'org-outline-level)
9510 (outline-heading-alist))))
9511 `(defun ,name (arg)
9512 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9513 "Outside of structure, run the binding of `"
9514 (key-description key) "'."
9515 (when disable-when-heading-prefix
9516 (concat
9517 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9518 "back to the default binding due to limitations of Org's implementation of\n"
9519 "`" (symbol-name fun) "'.")))
9520 (interactive "p")
9521 (let* ((disable
9522 ,(and disable-when-heading-prefix
9523 '(not (string= orgstruct-heading-prefix-regexp ""))))
9524 (fallback
9525 (or disable
9526 (not
9527 (let* ,bindings
9528 (org-context-p 'headline 'item
9529 ,(when (memq fun
9530 '(org-insert-heading
9531 org-insert-heading-respect-content
9532 org-meta-return))
9533 '(when orgstruct-is-++
9534 'item-body))))))))
9535 (if fallback
9536 (let* ((orgstruct-mode)
9537 (binding
9538 (let ((key ,key))
9539 (catch 'exit
9540 (dolist
9541 (rep
9542 '(nil
9543 ("<\\([^>]*\\)tab>" . "\\1TAB")
9544 ("<\\([^>]*\\)return>" . "\\1RET")
9545 ("<\\([^>]*\\)escape>" . "\\1ESC")
9546 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9547 nil)
9548 (when rep
9549 (setq key (read-kbd-macro
9550 (let ((case-fold-search))
9551 (replace-regexp-in-string
9552 (car rep)
9553 (cdr rep)
9554 (key-description key))))))
9555 (when (key-binding key)
9556 (throw 'exit (key-binding key))))))))
9557 (if (keymapp binding)
9558 (org-set-transient-map binding)
9559 (let ((func (or binding
9560 (unless disable
9561 'orgstruct-error))))
9562 (when func
9563 (call-interactively func)))))
9564 (org-run-like-in-org-mode
9565 (lambda ()
9566 (interactive)
9567 (let* ,bindings
9568 (call-interactively ',fun)))))))))
9569 name))
9571 (defun org-contextualize-keys (alist contexts)
9572 "Return valid elements in ALIST depending on CONTEXTS.
9574 `org-agenda-custom-commands' or `org-capture-templates' are the
9575 values used for ALIST, and `org-agenda-custom-commands-contexts'
9576 or `org-capture-templates-contexts' are the associated contexts
9577 definitions."
9578 (let ((contexts
9579 ;; normalize contexts
9580 (mapcar
9581 (lambda(c) (cond ((listp (cadr c))
9582 (list (car c) (car c) (nth 1 c)))
9583 ((string= "" (cadr c))
9584 (list (car c) (car c) (nth 2 c)))
9585 (t c)))
9586 contexts))
9587 (a alist) r s)
9588 ;; loop over all commands or templates
9589 (dolist (c a)
9590 (let (vrules repl)
9591 (cond
9592 ((not (assoc (car c) contexts))
9593 (push c r))
9594 ((and (assoc (car c) contexts)
9595 (setq vrules (org-contextualize-validate-key
9596 (car c) contexts)))
9597 (mapc (lambda (vr)
9598 (unless (equal (car vr) (cadr vr))
9599 (setq repl vr)))
9600 vrules)
9601 (if (not repl) (push c r)
9602 (push (cadr repl) s)
9603 (push
9604 (cons (car c)
9605 (cdr (or (assoc (cadr repl) alist)
9606 (error "Undefined key `%s' as contextual replacement for `%s'"
9607 (cadr repl) (car c)))))
9608 r))))))
9609 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9610 (delq
9612 (delete-dups
9613 (mapcar (lambda (x)
9614 (let ((tpl (car x)))
9615 (unless (delq
9617 (mapcar (lambda (y)
9618 (equal y tpl))
9620 x)))
9621 (reverse r))))))
9623 (defun org-contextualize-validate-key (key contexts)
9624 "Check CONTEXTS for agenda or capture KEY."
9625 (let (res)
9626 (dolist (r contexts)
9627 (dolist (rr (car (last r)))
9628 (when
9629 (and (equal key (car r))
9630 (if (functionp rr) (funcall rr)
9631 (or (and (eq (car rr) 'in-file)
9632 (buffer-file-name)
9633 (string-match (cdr rr) (buffer-file-name)))
9634 (and (eq (car rr) 'in-mode)
9635 (string-match (cdr rr) (symbol-name major-mode)))
9636 (and (eq (car rr) 'in-buffer)
9637 (string-match (cdr rr) (buffer-name)))
9638 (when (and (eq (car rr) 'not-in-file)
9639 (buffer-file-name))
9640 (not (string-match (cdr rr) (buffer-file-name))))
9641 (when (eq (car rr) 'not-in-mode)
9642 (not (string-match (cdr rr) (symbol-name major-mode))))
9643 (when (eq (car rr) 'not-in-buffer)
9644 (not (string-match (cdr rr) (buffer-name)))))))
9645 (push r res))))
9646 (delete-dups (delq nil res))))
9648 (defun org-context-p (&rest contexts)
9649 "Check if local context is any of CONTEXTS.
9650 Possible values in the list of contexts are `table', `headline', and `item'."
9651 (let ((pos (point)))
9652 (goto-char (point-at-bol))
9653 (prog1 (or (and (memq 'table contexts)
9654 (looking-at "[ \t]*|"))
9655 (and (memq 'headline contexts)
9656 (looking-at org-outline-regexp))
9657 (and (memq 'item contexts)
9658 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9659 (and (memq 'item-body contexts)
9660 (org-in-item-p)))
9661 (goto-char pos))))
9663 (defconst org-unique-local-variables
9664 '(org-element--cache
9665 org-element--cache-objects
9666 org-element--cache-sync-keys
9667 org-element--cache-sync-requests
9668 org-element--cache-sync-timer)
9669 "List of local variables that cannot be transferred to another buffer.")
9671 (defun org-get-local-variables ()
9672 "Return a list of all local variables in an Org mode buffer."
9673 (delq nil
9674 (mapcar
9675 (lambda (x)
9676 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9677 (name (car binding)))
9678 (and (not (get name 'org-state))
9679 (not (memq name org-unique-local-variables))
9680 (string-match-p
9681 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9682 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9683 (symbol-name name))
9684 binding)))
9685 (with-temp-buffer
9686 (org-mode)
9687 (buffer-local-variables)))))
9689 (defun org-clone-local-variables (from-buffer &optional regexp)
9690 "Clone local variables from FROM-BUFFER.
9691 Optional argument REGEXP selects variables to clone."
9692 (dolist (pair (buffer-local-variables from-buffer))
9693 (let ((name (car pair)))
9694 (when (and (symbolp name)
9695 (not (memq name org-unique-local-variables))
9696 (or (null regexp) (string-match regexp (symbol-name name))))
9697 (set (make-local-variable name) (cdr pair))))))
9699 ;;;###autoload
9700 (defun org-run-like-in-org-mode (cmd)
9701 "Run a command, pretending that the current buffer is in Org mode.
9702 This will temporarily bind local variables that are typically bound in
9703 Org mode to the values they have in Org mode, and then interactively
9704 call CMD."
9705 (org-load-modules-maybe)
9706 (unless org-local-vars
9707 (setq org-local-vars (org-get-local-variables)))
9708 (let (binds)
9709 (dolist (var org-local-vars)
9710 (when (or (not (boundp (car var)))
9711 (eq (symbol-value (car var))
9712 (default-value (car var))))
9713 (push (list (car var) `(quote ,(cadr var))) binds)))
9714 (eval `(let ,binds
9715 (call-interactively (quote ,cmd))))))
9717 (defun org-get-category (&optional pos force-refresh)
9718 "Get the category applying to position POS."
9719 (save-match-data
9720 (when force-refresh (org-refresh-category-properties))
9721 (let ((pos (or pos (point))))
9722 (or (get-text-property pos 'org-category)
9723 (progn (org-refresh-category-properties)
9724 (get-text-property pos 'org-category))))))
9726 ;;; Refresh properties
9728 (defun org-refresh-properties (dprop tprop)
9729 "Refresh buffer text properties.
9730 DPROP is the drawer property and TPROP is either the
9731 corresponding text property to set, or an alist with each element
9732 being a text property (as a symbol) and a function to apply to
9733 the value of the drawer property."
9734 (let ((case-fold-search t)
9735 (inhibit-read-only t))
9736 (org-with-silent-modifications
9737 (org-with-wide-buffer
9738 (goto-char (point-min))
9739 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9740 (org-refresh-property tprop (match-string-no-properties 1)))))))
9742 (defun org-refresh-property (tprop p)
9743 "Refresh the buffer text property TPROP from the drawer property P.
9744 The refresh happens only for the current tree (not subtree)."
9745 (unless (org-before-first-heading-p)
9746 (save-excursion
9747 (org-back-to-heading t)
9748 (if (symbolp tprop)
9749 ;; TPROP is a text property symbol
9750 (put-text-property
9751 (point) (or (outline-next-heading) (point-max)) tprop p)
9752 ;; TPROP is an alist with (properties . function) elements
9753 (dolist (al tprop)
9754 (save-excursion
9755 (put-text-property
9756 (line-beginning-position) (or (outline-next-heading) (point-max))
9757 (car al)
9758 (funcall (cdr al) p))))))))
9760 (defun org-refresh-category-properties ()
9761 "Refresh category text properties in the buffer."
9762 (let ((case-fold-search t)
9763 (inhibit-read-only t)
9764 (default-category
9765 (cond ((null org-category)
9766 (if buffer-file-name
9767 (file-name-sans-extension
9768 (file-name-nondirectory buffer-file-name))
9769 "???"))
9770 ((symbolp org-category) (symbol-name org-category))
9771 (t org-category))))
9772 (org-with-silent-modifications
9773 (org-with-wide-buffer
9774 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9775 ;; This is the default category for the buffer. If none is
9776 ;; found, fall-back to `org-category' or buffer file name.
9777 (put-text-property
9778 (point-min) (point-max)
9779 'org-category
9780 (catch 'buffer-category
9781 (goto-char (point-max))
9782 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9783 (let ((element (org-element-at-point)))
9784 (when (eq (org-element-type element) 'keyword)
9785 (throw 'buffer-category
9786 (org-element-property :value element)))))
9787 default-category))
9788 ;; Set sub-tree specific categories.
9789 (goto-char (point-min))
9790 (let ((regexp (org-re-property "CATEGORY")))
9791 (while (re-search-forward regexp nil t)
9792 (let ((value (match-string-no-properties 3)))
9793 (when (org-at-property-p)
9794 (put-text-property
9795 (save-excursion (org-back-to-heading t) (point))
9796 (save-excursion (org-end-of-subtree t t) (point))
9797 'org-category
9798 value)))))))))
9800 (defun org-refresh-stats-properties ()
9801 "Refresh stats text properties in the buffer."
9802 (let (stats)
9803 (org-with-silent-modifications
9804 (org-with-wide-buffer
9805 (goto-char (point-min))
9806 (while (re-search-forward
9807 (concat org-outline-regexp-bol ".*"
9808 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9809 nil t)
9810 (setq stats (cond ((equal (match-string 3) "0") 0)
9811 ((match-string 2)
9812 (/ (* (string-to-number (match-string 2)) 100)
9813 (string-to-number (match-string 3))))
9814 (t (string-to-number (match-string 1)))))
9815 (org-back-to-heading t)
9816 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9817 'org-stats stats))))))
9819 (defun org-refresh-effort-properties ()
9820 "Refresh effort properties"
9821 (org-refresh-properties
9822 org-effort-property
9823 '((effort . identity)
9824 (effort-minutes . org-duration-string-to-minutes))))
9826 ;;;; Link Stuff
9828 ;;; Link abbreviations
9830 (defun org-link-expand-abbrev (link)
9831 "Apply replacements as defined in `org-link-abbrev-alist'."
9832 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9833 (let* ((key (match-string 1 link))
9834 (as (or (assoc key org-link-abbrev-alist-local)
9835 (assoc key org-link-abbrev-alist)))
9836 (tag (and (match-end 2) (match-string 3 link)))
9837 rpl)
9838 (if (not as)
9839 link
9840 (setq rpl (cdr as))
9841 (cond
9842 ((symbolp rpl) (funcall rpl tag))
9843 ((string-match "%(\\([^)]+\\))" rpl)
9844 (replace-match
9845 (save-match-data
9846 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9847 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9848 ((string-match "%h" rpl)
9849 (replace-match (url-hexify-string (or tag "")) t t rpl))
9850 (t (concat rpl tag)))))
9851 link))
9853 ;;; Storing and inserting links
9855 (defvar org-insert-link-history nil
9856 "Minibuffer history for links inserted with `org-insert-link'.")
9858 (defvar org-stored-links nil
9859 "Contains the links stored with `org-store-link'.")
9861 (defvar org-store-link-plist nil
9862 "Plist with info about the most recently link created with `org-store-link'.")
9864 (defun org-store-link-functions ()
9865 "Return a list of functions that are called to create and store a link.
9866 The functions defined in the :store property of
9867 `org-link-parameters'.
9869 Each function will be called in turn until one returns a non-nil
9870 value. Each function should check if it is responsible for
9871 creating this link (for example by looking at the major mode).
9872 If not, it must exit and return nil. If yes, it should return
9873 a non-nil value after calling `org-store-link-props' with a list
9874 of properties and values. Special properties are:
9876 :type The link prefix, like \"http\". This must be given.
9877 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9878 This is obligatory as well.
9879 :description Optional default description for the second pair
9880 of brackets in an Org mode link. The user can still change
9881 this when inserting this link into an Org mode buffer.
9883 In addition to these, any additional properties can be specified
9884 and then used in capture templates."
9885 (cl-loop for link in org-link-parameters
9886 with store-func
9887 do (setq store-func (org-link-get-parameter (car link) :store))
9888 if store-func
9889 collect store-func))
9891 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9892 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9894 ;;;###autoload
9895 (defun org-store-link (arg)
9896 "Store an org-link to the current location.
9897 \\<org-mode-map>
9898 This link is added to `org-stored-links' and can later be inserted
9899 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9901 For some link types, a `\\[universal-argument]' prefix ARG is interpreted.
9902 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9903 For file links, ARG negates `org-context-in-file-links'.
9905 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9906 skipping storing functions that are not
9907 part of Org core.
9909 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9910 prefix ARG forces storing a link for each line in the
9911 active region."
9912 (interactive "P")
9913 (org-load-modules-maybe)
9914 (if (and (equal arg '(64)) (org-region-active-p))
9915 (save-excursion
9916 (let ((end (region-end)))
9917 (goto-char (region-beginning))
9918 (set-mark (point))
9919 (while (< (point-at-eol) end)
9920 (move-end-of-line 1) (activate-mark)
9921 (let (current-prefix-arg)
9922 (call-interactively 'org-store-link))
9923 (move-beginning-of-line 2)
9924 (set-mark (point)))))
9925 (setq org-store-link-plist nil)
9926 (let (link cpltxt desc description search
9927 txt custom-id agenda-link sfuns sfunsn)
9928 (cond
9930 ;; Store a link using an external link type
9931 ((and (not (equal arg '(16)))
9932 (setq sfuns
9933 (delq
9934 nil (mapcar (lambda (f)
9935 (let (fs) (if (funcall f) (push f fs))))
9936 (org-store-link-functions)))
9937 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9938 (or (and (cdr sfuns)
9939 (funcall (intern
9940 (completing-read
9941 "Which function for creating the link? "
9942 sfunsn nil t (car sfunsn)))))
9943 (funcall (caar sfuns)))
9944 (setq link (plist-get org-store-link-plist :link)
9945 desc (or (plist-get org-store-link-plist
9946 :description)
9947 link))))
9949 ;; Store a link from a source code buffer.
9950 ((org-src-edit-buffer-p)
9951 (let ((coderef-format (org-src-coderef-format)))
9952 (cond ((save-excursion
9953 (beginning-of-line)
9954 (looking-at (org-src-coderef-regexp coderef-format)))
9955 (setq link (format "(%s)" (match-string-no-properties 3))))
9956 ((called-interactively-p 'any)
9957 (let ((label (read-string "Code line label: ")))
9958 (end-of-line)
9959 (setq link (format coderef-format label))
9960 (let ((gc (- 79 (length link))))
9961 (if (< (current-column) gc)
9962 (org-move-to-column gc t)
9963 (insert " ")))
9964 (insert link)
9965 (setq link (concat "(" label ")"))
9966 (setq desc nil)))
9967 (t (setq link nil)))))
9969 ;; We are in the agenda, link to referenced location
9970 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9971 (let ((m (or (get-text-property (point) 'org-hd-marker)
9972 (get-text-property (point) 'org-marker))))
9973 (when m
9974 (org-with-point-at m
9975 (setq agenda-link
9976 (if (called-interactively-p 'any)
9977 (call-interactively 'org-store-link)
9978 (org-store-link nil)))))))
9980 ((eq major-mode 'calendar-mode)
9981 (let ((cd (calendar-cursor-to-date)))
9982 (setq link
9983 (format-time-string
9984 (car org-time-stamp-formats)
9985 (apply 'encode-time
9986 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9987 nil nil nil))))
9988 (org-store-link-props :type "calendar" :date cd)))
9990 ((eq major-mode 'help-mode)
9991 (setq link (concat "help:" (save-excursion
9992 (goto-char (point-min))
9993 (looking-at "^[^ ]+")
9994 (match-string 0))))
9995 (org-store-link-props :type "help"))
9997 ((eq major-mode 'w3-mode)
9998 (setq cpltxt (if (and (buffer-name)
9999 (not (string-match "Untitled" (buffer-name))))
10000 (buffer-name)
10001 (url-view-url t))
10002 link (url-view-url t))
10003 (org-store-link-props :type "w3" :url (url-view-url t)))
10005 ((eq major-mode 'image-mode)
10006 (setq cpltxt (concat "file:"
10007 (abbreviate-file-name buffer-file-name))
10008 link cpltxt)
10009 (org-store-link-props :type "image" :file buffer-file-name))
10011 ;; In dired, store a link to the file of the current line
10012 ((derived-mode-p 'dired-mode)
10013 (let ((file (dired-get-filename nil t)))
10014 (setq file (if file
10015 (abbreviate-file-name
10016 (expand-file-name (dired-get-filename nil t)))
10017 ;; otherwise, no file so use current directory.
10018 default-directory))
10019 (setq cpltxt (concat "file:" file)
10020 link cpltxt)))
10022 ((setq search (run-hook-with-args-until-success
10023 'org-create-file-search-functions))
10024 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
10025 "::" search))
10026 (setq cpltxt (or description link)))
10028 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
10029 (org-with-limited-levels
10030 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
10031 (cond
10032 ;; Store a link using the target at point
10033 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
10034 (setq cpltxt
10035 (concat "file:"
10036 (abbreviate-file-name
10037 (buffer-file-name (buffer-base-buffer)))
10038 "::" (match-string 1))
10039 link cpltxt))
10040 ((and (featurep 'org-id)
10041 (or (eq org-id-link-to-org-use-id t)
10042 (and (called-interactively-p 'any)
10043 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
10044 (and (eq org-id-link-to-org-use-id
10045 'create-if-interactive-and-no-custom-id)
10046 (not custom-id))))
10047 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
10048 ;; Store a link using the ID at point
10049 (setq link (condition-case nil
10050 (prog1 (org-id-store-link)
10051 (setq desc (or (plist-get org-store-link-plist
10052 :description)
10053 "")))
10054 (error
10055 ;; Probably before first headline, link only to file
10056 (concat "file:"
10057 (abbreviate-file-name
10058 (buffer-file-name (buffer-base-buffer))))))))
10060 ;; Just link to current headline
10061 (setq cpltxt (concat "file:"
10062 (abbreviate-file-name
10063 (buffer-file-name (buffer-base-buffer)))))
10064 ;; Add a context search string
10065 (when (org-xor org-context-in-file-links arg)
10066 (let* ((element (org-element-at-point))
10067 (name (org-element-property :name element)))
10068 (setq txt (cond
10069 ((org-at-heading-p) nil)
10070 (name)
10071 ((org-region-active-p)
10072 (buffer-substring (region-beginning) (region-end)))))
10073 (when (or (null txt) (string-match "\\S-" txt))
10074 (setq cpltxt
10075 (concat cpltxt "::"
10076 (condition-case nil
10077 (org-make-org-heading-search-string txt)
10078 (error "")))
10079 desc (or name
10080 (nth 4 (ignore-errors (org-heading-components)))
10081 "NONE")))))
10082 (when (string-match "::\\'" cpltxt)
10083 (setq cpltxt (substring cpltxt 0 -2)))
10084 (setq link cpltxt)))))
10086 ((buffer-file-name (buffer-base-buffer))
10087 ;; Just link to this file here.
10088 (setq cpltxt (concat "file:"
10089 (abbreviate-file-name
10090 (buffer-file-name (buffer-base-buffer)))))
10091 ;; Add a context string.
10092 (when (org-xor org-context-in-file-links arg)
10093 (setq txt (if (org-region-active-p)
10094 (buffer-substring (region-beginning) (region-end))
10095 (buffer-substring (point-at-bol) (point-at-eol))))
10096 ;; Only use search option if there is some text.
10097 (when (string-match "\\S-" txt)
10098 (setq cpltxt
10099 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10100 desc "NONE")))
10101 (setq link cpltxt))
10103 ((called-interactively-p 'interactive)
10104 (user-error "No method for storing a link from this buffer"))
10106 (t (setq link nil)))
10108 ;; We're done setting link and desc, clean up
10109 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10110 (setq link (or link cpltxt)
10111 desc (or desc cpltxt))
10112 (cond ((not desc))
10113 ((equal desc "NONE") (setq desc nil))
10114 (t (setq desc
10115 (replace-regexp-in-string
10116 org-bracket-link-analytic-regexp
10117 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10118 desc))))
10119 ;; Return the link
10120 (if (not (and (or (called-interactively-p 'any)
10121 executing-kbd-macro)
10122 link))
10123 (or agenda-link (and link (org-make-link-string link desc)))
10124 (push (list link desc) org-stored-links)
10125 (message "Stored: %s" (or desc link))
10126 (when custom-id
10127 (setq link (concat "file:" (abbreviate-file-name
10128 (buffer-file-name)) "::#" custom-id))
10129 (push (list link desc) org-stored-links))
10130 (car org-stored-links)))))
10132 (defun org-store-link-props (&rest plist)
10133 "Store link properties, extract names, addresses and dates."
10134 (let ((x (plist-get plist :from)))
10135 (when x
10136 (let ((adr (mail-extract-address-components x)))
10137 (setq plist (plist-put plist :fromname (car adr)))
10138 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10139 (let ((x (plist-get plist :to)))
10140 (when x
10141 (let ((adr (mail-extract-address-components x)))
10142 (setq plist (plist-put plist :toname (car adr)))
10143 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10144 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10145 (when x
10146 (setq plist (plist-put plist :date-timestamp
10147 (format-time-string
10148 (org-time-stamp-format t) x)))
10149 (setq plist (plist-put plist :date-timestamp-inactive
10150 (format-time-string
10151 (org-time-stamp-format t t) x)))))
10152 (let ((from (plist-get plist :from))
10153 (to (plist-get plist :to)))
10154 (when (and from to org-from-is-user-regexp)
10155 (setq plist
10156 (plist-put plist :fromto
10157 (if (string-match org-from-is-user-regexp from)
10158 (concat "to %t")
10159 (concat "from %f"))))))
10160 (setq org-store-link-plist plist))
10162 (defun org-add-link-props (&rest plist)
10163 "Add these properties to the link property list."
10164 (let (key value)
10165 (while plist
10166 (setq key (pop plist) value (pop plist))
10167 (setq org-store-link-plist
10168 (plist-put org-store-link-plist key value)))))
10170 (defun org-email-link-description (&optional fmt)
10171 "Return the description part of an email link.
10172 This takes information from `org-store-link-plist' and formats it
10173 according to FMT (default from `org-email-link-description-format')."
10174 (setq fmt (or fmt org-email-link-description-format))
10175 (let* ((p org-store-link-plist)
10176 (to (plist-get p :toaddress))
10177 (from (plist-get p :fromaddress))
10178 (table
10179 (list
10180 (cons "%c" (plist-get p :fromto))
10181 (cons "%F" (plist-get p :from))
10182 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10183 (cons "%T" (plist-get p :to))
10184 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10185 (cons "%s" (plist-get p :subject))
10186 (cons "%d" (plist-get p :date))
10187 (cons "%m" (plist-get p :message-id)))))
10188 (when (string-match "%c" fmt)
10189 ;; Check if the user wrote this message
10190 (if (and org-from-is-user-regexp from to
10191 (save-match-data (string-match org-from-is-user-regexp from)))
10192 (setq fmt (replace-match "to %t" t t fmt))
10193 (setq fmt (replace-match "from %f" t t fmt))))
10194 (org-replace-escapes fmt table)))
10196 (defun org-make-org-heading-search-string (&optional string)
10197 "Make search string for the current headline or STRING."
10198 (let ((s (or string
10199 (and (derived-mode-p 'org-mode)
10200 (save-excursion
10201 (org-back-to-heading t)
10202 (org-element-property :raw-value (org-element-at-point))))))
10203 (lines org-context-in-file-links))
10204 (or string (setq s (concat "*" s))) ; Add * for headlines
10205 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10206 (when (and string (integerp lines) (> lines 0))
10207 (let ((slines (org-split-string s "\n")))
10208 (when (< lines (length slines))
10209 (setq s (mapconcat
10210 'identity
10211 (reverse (nthcdr (- (length slines) lines)
10212 (reverse slines))) "\n")))))
10213 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10215 (defun org-make-link-string (link &optional description)
10216 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10217 (unless (org-string-nw-p link) (error "Empty link"))
10218 (let ((uri (cond ((string-match org-link-types-re link)
10219 (concat (match-string 1 link)
10220 (org-link-escape (substring link (match-end 1)))))
10221 ;; For readability, url-encode internal links only
10222 ;; when absolutely needed (i.e, when they contain
10223 ;; square brackets). File links however, are
10224 ;; encoded since, e.g., spaces are significant.
10225 ((or (file-name-absolute-p link)
10226 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10227 (org-link-escape link))
10228 (t link)))
10229 (description
10230 (and (org-string-nw-p description)
10231 ;; Remove brackets from description, as they are fatal.
10232 (replace-regexp-in-string
10233 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10234 (org-trim description)))))
10235 (format "[[%s]%s]"
10237 (if description (format "[%s]" description) ""))))
10239 (defconst org-link-escape-chars
10240 ;;%20 %5B %5D %25
10241 '(?\s ?\[ ?\] ?%)
10242 "List of characters that should be escaped in a link when stored to Org.
10243 This is the list that is used for internal purposes.")
10245 (defun org-link-escape (text &optional table merge)
10246 "Return percent escaped representation of TEXT.
10247 TEXT is a string with the text to escape.
10248 Optional argument TABLE is a list with characters that should be
10249 escaped. When nil, `org-link-escape-chars' is used.
10250 If optional argument MERGE is set, merge TABLE into
10251 `org-link-escape-chars'."
10252 (let ((characters-to-encode
10253 (cond ((null table) org-link-escape-chars)
10254 (merge (append org-link-escape-chars table))
10255 (t table))))
10256 (mapconcat
10257 (lambda (c)
10258 (if (or (memq c characters-to-encode)
10259 (and org-url-hexify-p (or (< c 32) (> c 126))))
10260 (mapconcat (lambda (e) (format "%%%.2X" e))
10261 (or (encode-coding-char c 'utf-8)
10262 (error "Unable to percent escape character: %c" c))
10264 (char-to-string c)))
10265 text "")))
10267 (defun org-link-unescape (str)
10268 "Unhex hexified Unicode parts in string STR.
10269 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10270 reciprocal of `org-link-escape', which see."
10271 (if (org-string-nw-p str)
10272 (replace-regexp-in-string
10273 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10274 str))
10276 (defun org-link-unescape-compound (hex)
10277 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10278 Note: this function also decodes single byte encodings like
10279 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10280 (save-match-data
10281 (let* ((bytes (cdr (split-string hex "%")))
10282 (ret "")
10283 (eat 0)
10284 (sum 0))
10285 (while bytes
10286 (let* ((val (string-to-number (pop bytes) 16))
10287 (shift-xor
10288 (if (= 0 eat)
10289 (cond
10290 ((>= val 252) (cons 6 252))
10291 ((>= val 248) (cons 5 248))
10292 ((>= val 240) (cons 4 240))
10293 ((>= val 224) (cons 3 224))
10294 ((>= val 192) (cons 2 192))
10295 (t (cons 0 0)))
10296 (cons 6 128))))
10297 (when (>= val 192) (setq eat (car shift-xor)))
10298 (setq val (logxor val (cdr shift-xor)))
10299 (setq sum (+ (lsh sum (car shift-xor)) val))
10300 (when (> eat 0) (setq eat (- eat 1)))
10301 (cond
10302 ((= 0 eat) ;multi byte
10303 (setq ret (concat ret (char-to-string sum)))
10304 (setq sum 0))
10305 ((not bytes) ; single byte(s)
10306 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10307 ret)))
10309 (defun org-link-unescape-single-byte-sequence (hex)
10310 "Unhexify hex-encoded single byte character sequences."
10311 (mapconcat (lambda (byte)
10312 (char-to-string (string-to-number byte 16)))
10313 (cdr (split-string hex "%")) ""))
10315 (defun org-xor (a b)
10316 "Exclusive or."
10317 (if a (not b) b))
10319 (defun org-fixup-message-id-for-http (s)
10320 "Replace special characters in a message id, so it can be used in an http query."
10321 (when (string-match "%" s)
10322 (setq s (mapconcat (lambda (c)
10323 (if (eq c ?%)
10324 "%25"
10325 (char-to-string c)))
10326 s "")))
10327 (while (string-match "<" s)
10328 (setq s (replace-match "%3C" t t s)))
10329 (while (string-match ">" s)
10330 (setq s (replace-match "%3E" t t s)))
10331 (while (string-match "@" s)
10332 (setq s (replace-match "%40" t t s)))
10335 (defun org-link-prettify (link)
10336 "Return a human-readable representation of LINK.
10337 The car of LINK must be a raw link.
10338 The cdr of LINK must be either a link description or nil."
10339 (let ((desc (or (cadr link) "<no description>")))
10340 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10341 "<" (car link) ">")))
10343 ;;;###autoload
10344 (defun org-insert-link-global ()
10345 "Insert a link like Org mode does.
10346 This command can be called in any mode to insert a link in Org syntax."
10347 (interactive)
10348 (org-load-modules-maybe)
10349 (org-run-like-in-org-mode 'org-insert-link))
10351 (defun org-insert-all-links (arg &optional pre post)
10352 "Insert all links in `org-stored-links'.
10353 When a universal prefix, do not delete the links from `org-stored-links'.
10354 When `ARG' is a number, insert the last N link(s).
10355 `PRE' and `POST' are optional arguments to define a string to
10356 prepend or to append."
10357 (interactive "P")
10358 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10359 (links (copy-sequence org-stored-links))
10360 (pr (or pre "- "))
10361 (po (or post "\n"))
10362 (cnt 1) l)
10363 (if (null org-stored-links)
10364 (message "No link to insert")
10365 (while (and (or (listp arg) (>= arg cnt))
10366 (setq l (if (listp arg)
10367 (pop links)
10368 (pop org-stored-links))))
10369 (setq cnt (1+ cnt))
10370 (insert pr)
10371 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10372 (insert po)))))
10374 (defun org-insert-last-stored-link (arg)
10375 "Insert the last link stored in `org-stored-links'."
10376 (interactive "p")
10377 (org-insert-all-links arg "" "\n"))
10379 (defun org-link-fontify-links-to-this-file ()
10380 "Fontify links to the current file in `org-stored-links'."
10381 (let ((f (buffer-file-name)) a b)
10382 (setq a (mapcar (lambda(l)
10383 (let ((ll (car l)))
10384 (when (and (string-match "^file:\\(.+\\)::" ll)
10385 (equal f (expand-file-name (match-string 1 ll))))
10386 ll)))
10387 org-stored-links))
10388 (when (featurep 'org-id)
10389 (setq b (mapcar (lambda(l)
10390 (let ((ll (car l)))
10391 (when (and (string-match "^id:\\(.+\\)$" ll)
10392 (equal f (expand-file-name
10393 (or (org-id-find-id-file
10394 (match-string 1 ll)) ""))))
10395 ll)))
10396 org-stored-links)))
10397 (mapcar (lambda(l)
10398 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10399 (delq nil (append a b)))))
10401 (defvar org--links-history nil)
10402 (defun org-insert-link (&optional complete-file link-location default-description)
10403 "Insert a link. At the prompt, enter the link.
10405 Completion can be used to insert any of the link protocol prefixes in use.
10407 The history can be used to select a link previously stored with
10408 `org-store-link'. When the empty string is entered (i.e. if you just
10409 press `RET' at the prompt), the link defaults to the most recently
10410 stored link. As `SPC' triggers completion in the minibuffer, you need to
10411 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10413 You will also be prompted for a description, and if one is given, it will
10414 be displayed in the buffer instead of the link.
10416 If there is already a link at point, this command will allow you to edit
10417 link and description parts.
10419 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10420 file name can be
10421 selected using completion. The path to the file will be relative to the
10422 current directory if the file is in the current directory or a subdirectory.
10423 Otherwise, the link will be the absolute path as completed in the minibuffer
10424 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10425 option `org-link-file-path-type'.
10427 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10428 absolute path even if the file is in
10429 the current directory or below.
10431 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10432 prefix negates `org-keep-stored-link-after-insertion'.
10434 If `org-make-link-description-function' is non-nil, this function will be
10435 called with the link target, and the result will be the default
10436 link description.
10438 If the LINK-LOCATION parameter is non-nil, this value will be used as
10439 the link location instead of reading one interactively.
10441 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10442 as the default description."
10443 (interactive "P")
10444 (let* ((wcf (current-window-configuration))
10445 (origbuf (current-buffer))
10446 (region (when (org-region-active-p)
10447 (buffer-substring (region-beginning) (region-end))))
10448 (remove (and region (list (region-beginning) (region-end))))
10449 (desc region)
10450 (link link-location)
10451 (abbrevs org-link-abbrev-alist-local)
10452 entry all-prefixes auto-desc)
10453 (cond
10454 (link-location) ; specified by arg, just use it.
10455 ((org-in-regexp org-bracket-link-regexp 1)
10456 ;; We do have a link at point, and we are going to edit it.
10457 (setq remove (list (match-beginning 0) (match-end 0)))
10458 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10459 (setq link (read-string "Link: "
10460 (org-link-unescape
10461 (match-string-no-properties 1)))))
10462 ((or (org-in-regexp org-angle-link-re)
10463 (org-in-regexp org-plain-link-re))
10464 ;; Convert to bracket link
10465 (setq remove (list (match-beginning 0) (match-end 0))
10466 link (read-string "Link: "
10467 (org-unbracket-string "<" ">" (match-string 0)))))
10468 ((member complete-file '((4) (16)))
10469 ;; Completing read for file names.
10470 (setq link (org-file-complete-link complete-file)))
10472 ;; Read link, with completion for stored links.
10473 (org-link-fontify-links-to-this-file)
10474 (org-switch-to-buffer-other-window "*Org Links*")
10475 (with-current-buffer "*Org Links*"
10476 (erase-buffer)
10477 (insert "Insert a link.
10478 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10479 (when org-stored-links
10480 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10481 (insert (mapconcat 'org-link-prettify
10482 (reverse org-stored-links) "\n")))
10483 (goto-char (point-min)))
10484 (let ((cw (selected-window)))
10485 (select-window (get-buffer-window "*Org Links*" 'visible))
10486 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10487 (unless (pos-visible-in-window-p (point-max))
10488 (org-fit-window-to-buffer))
10489 (and (window-live-p cw) (select-window cw)))
10490 (setq all-prefixes (append (mapcar 'car abbrevs)
10491 (mapcar 'car org-link-abbrev-alist)
10492 (org-link-types)))
10493 (unwind-protect
10494 ;; Fake a link history, containing the stored links.
10495 (let ((org--links-history
10496 (append (mapcar #'car org-stored-links)
10497 org-insert-link-history)))
10498 (setq link
10499 (org-completing-read
10500 "Link: "
10501 (append
10502 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10503 (mapcar #'car org-stored-links))
10504 nil nil nil
10505 'org--links-history
10506 (caar org-stored-links)))
10507 (unless (org-string-nw-p link) (user-error "No link selected"))
10508 (dolist (l org-stored-links)
10509 (when (equal link (cadr l))
10510 (setq link (car l))
10511 (setq auto-desc t)))
10512 (when (or (member link all-prefixes)
10513 (and (equal ":" (substring link -1))
10514 (member (substring link 0 -1) all-prefixes)
10515 (setq link (substring link 0 -1))))
10516 (setq link (with-current-buffer origbuf
10517 (org-link-try-special-completion link)))))
10518 (set-window-configuration wcf)
10519 (kill-buffer "*Org Links*"))
10520 (setq entry (assoc link org-stored-links))
10521 (or entry (push link org-insert-link-history))
10522 (setq desc (or desc (nth 1 entry)))))
10524 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10525 (not org-keep-stored-link-after-insertion))
10526 (setq org-stored-links (delq (assoc link org-stored-links)
10527 org-stored-links)))
10529 (when (and (string-match org-plain-link-re link)
10530 (not (string-match org-ts-regexp link)))
10531 ;; URL-like link, normalize the use of angular brackets.
10532 (setq link (org-unbracket-string "<" ">" link)))
10534 ;; Check if we are linking to the current file with a search
10535 ;; option If yes, simplify the link by using only the search
10536 ;; option.
10537 (when (and buffer-file-name
10538 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10539 (let* ((path (match-string 1 link))
10540 (case-fold-search nil)
10541 (search (match-string 2 link)))
10542 (save-match-data
10543 (when (equal (file-truename buffer-file-name) (file-truename path))
10544 ;; We are linking to this same file, with a search option
10545 (setq link search)))))
10547 ;; Check if we can/should use a relative path. If yes, simplify the link
10548 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10549 (let* ((type (match-string 1 link))
10550 (path (match-string 2 link))
10551 (origpath path)
10552 (case-fold-search nil))
10553 (cond
10554 ((or (eq org-link-file-path-type 'absolute)
10555 (equal complete-file '(16)))
10556 (setq path (abbreviate-file-name (expand-file-name path))))
10557 ((eq org-link-file-path-type 'noabbrev)
10558 (setq path (expand-file-name path)))
10559 ((eq org-link-file-path-type 'relative)
10560 (setq path (file-relative-name path)))
10562 (save-match-data
10563 (if (string-match (concat "^" (regexp-quote
10564 (expand-file-name
10565 (file-name-as-directory
10566 default-directory))))
10567 (expand-file-name path))
10568 ;; We are linking a file with relative path name.
10569 (setq path (substring (expand-file-name path)
10570 (match-end 0)))
10571 (setq path (abbreviate-file-name (expand-file-name path)))))))
10572 (setq link (concat type path))
10573 (when (equal desc origpath)
10574 (setq desc path))))
10576 (if org-make-link-description-function
10577 (setq desc
10578 (or (condition-case nil
10579 (funcall org-make-link-description-function link desc)
10580 (error (progn (message "Can't get link description from `%s'"
10581 (symbol-name org-make-link-description-function))
10582 (sit-for 2) nil)))
10583 (read-string "Description: " default-description)))
10584 (if default-description (setq desc default-description)
10585 (setq desc (or (and auto-desc desc)
10586 (read-string "Description: " desc)))))
10588 (unless (string-match "\\S-" desc) (setq desc nil))
10589 (when remove (apply 'delete-region remove))
10590 (insert (org-make-link-string link desc))
10591 ;; Redisplay so as the new link has proper invisible characters.
10592 (sit-for 0)))
10594 (defun org-link-try-special-completion (type)
10595 "If there is completion support for link type TYPE, offer it."
10596 (let ((fun (org-link-get-parameter type :complete)))
10597 (if (functionp fun)
10598 (funcall fun)
10599 (read-string "Link (no completion support): " (concat type ":")))))
10601 (defun org-file-complete-link (&optional arg)
10602 "Create a file link using completion."
10603 (let ((file (read-file-name "File: "))
10604 (pwd (file-name-as-directory (expand-file-name ".")))
10605 (pwd1 (file-name-as-directory (abbreviate-file-name
10606 (expand-file-name ".")))))
10607 (cond ((equal arg '(16))
10608 (concat "file:"
10609 (abbreviate-file-name (expand-file-name file))))
10610 ((string-match
10611 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10612 (concat "file:" (match-string 1 file)))
10613 ((string-match
10614 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10615 (expand-file-name file))
10616 (concat "file:"
10617 (match-string 1 (expand-file-name file))))
10618 (t (concat "file:" file)))))
10620 (defun org-completing-read (&rest args)
10621 "Completing-read with SPACE being a normal character."
10622 (let ((enable-recursive-minibuffers t)
10623 (minibuffer-local-completion-map
10624 (copy-keymap minibuffer-local-completion-map)))
10625 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10626 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10627 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10628 'org-time-stamp-inactive)
10629 (apply #'completing-read args)))
10631 ;;; Opening/following a link
10633 (defvar org-link-search-failed nil)
10635 (defvar org-open-link-functions nil
10636 "Hook for functions finding a plain text link.
10637 These functions must take a single argument, the link content.
10638 They will be called for links that look like [[link text][description]]
10639 when LINK TEXT does not have a protocol like \"http:\" and does not look
10640 like a filename (e.g. \"./blue.png\").
10642 These functions will be called *before* Org attempts to resolve the
10643 link by doing text searches in the current buffer - so if you want a
10644 link \"[[target]]\" to still find \"<<target>>\", your function should
10645 handle this as a special case.
10647 When the function does handle the link, it must return a non-nil value.
10648 If it decides that it is not responsible for this link, it must return
10649 nil to indicate that that Org can continue with other options like
10650 exact and fuzzy text search.")
10652 (defun org-next-link (&optional search-backward)
10653 "Move forward to the next link.
10654 If the link is in hidden text, expose it."
10655 (interactive "P")
10656 (when (and org-link-search-failed (eq this-command last-command))
10657 (goto-char (point-min))
10658 (message "Link search wrapped back to beginning of buffer"))
10659 (setq org-link-search-failed nil)
10660 (let* ((pos (point))
10661 (ct (org-context))
10662 (a (assq :link ct))
10663 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10664 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10665 ((looking-at org-any-link-re)
10666 ;; Don't stay stuck at link without an org-link face
10667 (forward-char (if search-backward -1 1))))
10668 (if (funcall srch-fun org-any-link-re nil t)
10669 (progn
10670 (goto-char (match-beginning 0))
10671 (when (outline-invisible-p) (org-show-context)))
10672 (goto-char pos)
10673 (setq org-link-search-failed t)
10674 (message "No further link found"))))
10676 (defun org-previous-link ()
10677 "Move backward to the previous link.
10678 If the link is in hidden text, expose it."
10679 (interactive)
10680 (funcall 'org-next-link t))
10682 (defun org-translate-link (s)
10683 "Translate a link string if a translation function has been defined."
10684 (with-temp-buffer
10685 (insert (org-trim s))
10686 (org-trim (org-element-interpret-data (org-element-context)))))
10688 (defun org-translate-link-from-planner (type path)
10689 "Translate a link from Emacs Planner syntax so that Org can follow it.
10690 This is still an experimental function, your mileage may vary."
10691 (cond
10692 ((member type '("http" "https" "news" "ftp"))
10693 ;; standard Internet links are the same.
10694 nil)
10695 ((and (equal type "irc") (string-match "^//" path))
10696 ;; Planner has two / at the beginning of an irc link, we have 1.
10697 ;; We should have zero, actually....
10698 (setq path (substring path 1)))
10699 ((and (equal type "lisp") (string-match "^/" path))
10700 ;; Planner has a slash, we do not.
10701 (setq type "elisp" path (substring path 1)))
10702 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10703 ;; A typical message link. Planner has the id after the final slash,
10704 ;; we separate it with a hash mark
10705 (setq path (concat (match-string 1 path) "#"
10706 (org-unbracket-string "<" ">" (match-string 2 path))))))
10707 (cons type path))
10709 (defun org-find-file-at-mouse (ev)
10710 "Open file link or URL at mouse."
10711 (interactive "e")
10712 (mouse-set-point ev)
10713 (org-open-at-point 'in-emacs))
10715 (defun org-open-at-mouse (ev)
10716 "Open file link or URL at mouse.
10717 See the docstring of `org-open-file' for details."
10718 (interactive "e")
10719 (mouse-set-point ev)
10720 (when (eq major-mode 'org-agenda-mode)
10721 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10722 (org-open-at-point))
10724 (defvar org-window-config-before-follow-link nil
10725 "The window configuration before following a link.
10726 This is saved in case the need arises to restore it.")
10728 ;;;###autoload
10729 (defun org-open-at-point-global ()
10730 "Follow a link or time-stamp like Org mode does.
10731 This command can be called in any mode to follow an external link
10732 or a time-stamp that has Org mode syntax. Its behavior is
10733 undefined when called on internal links (e.g., fuzzy links).
10734 Raise an error when there is nothing to follow. "
10735 (interactive)
10736 (cond ((org-in-regexp org-any-link-re)
10737 (org-open-link-from-string (match-string-no-properties 0)))
10738 ((or (org-in-regexp org-ts-regexp-both nil t)
10739 (org-in-regexp org-tsr-regexp-both nil t))
10740 (org-follow-timestamp-link))
10741 (t (user-error "No link found"))))
10743 ;;;###autoload
10744 (defun org-open-link-from-string (s &optional arg reference-buffer)
10745 "Open a link in the string S, as if it was in Org mode."
10746 (interactive "sLink: \nP")
10747 (let ((reference-buffer (or reference-buffer (current-buffer))))
10748 (with-temp-buffer
10749 (let ((org-inhibit-startup (not reference-buffer)))
10750 (org-mode)
10751 (insert s)
10752 (goto-char (point-min))
10753 (when reference-buffer
10754 (setq org-link-abbrev-alist-local
10755 (with-current-buffer reference-buffer
10756 org-link-abbrev-alist-local)))
10757 (org-open-at-point arg reference-buffer)))))
10759 (defvar org-open-at-point-functions nil
10760 "Hook that is run when following a link at point.
10762 Functions in this hook must return t if they identify and follow
10763 a link at point. If they don't find anything interesting at point,
10764 they must return nil.")
10766 (defvar org-link-search-inhibit-query nil)
10767 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10768 (defun org--open-doi-link (path)
10769 "Open a \"doi\" type link.
10770 PATH is a the path to search for, as a string."
10771 (browse-url (url-encode-url (concat org-doi-server-url path))))
10773 (defun org--open-elisp-link (path)
10774 "Open a \"elisp\" type link.
10775 PATH is the sexp to evaluate, as a string."
10776 (let ((cmd path))
10777 (if (or (and (org-string-nw-p
10778 org-confirm-elisp-link-not-regexp)
10779 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10780 (not org-confirm-elisp-link-function)
10781 (funcall org-confirm-elisp-link-function
10782 (format "Execute \"%s\" as elisp? "
10783 (org-add-props cmd nil 'face 'org-warning))))
10784 (message "%s => %s" cmd
10785 (if (eq (string-to-char cmd) ?\()
10786 (eval (read cmd))
10787 (call-interactively (read cmd))))
10788 (user-error "Abort"))))
10790 (defun org--open-help-link (path)
10791 "Open a \"help\" type link.
10792 PATH is a symbol name, as a string."
10793 (pcase (intern path)
10794 ((and (pred fboundp) variable) (describe-function variable))
10795 ((and (pred boundp) function) (describe-variable function))
10796 (name (user-error "Unknown function or variable: %s" name))))
10798 (defun org--open-shell-link (path)
10799 "Open a \"shell\" type link.
10800 PATH is the command to execute, as a string."
10801 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10802 (cmd path))
10803 (if (or (and (org-string-nw-p
10804 org-confirm-shell-link-not-regexp)
10805 (string-match
10806 org-confirm-shell-link-not-regexp cmd))
10807 (not org-confirm-shell-link-function)
10808 (funcall org-confirm-shell-link-function
10809 (format "Execute \"%s\" in shell? "
10810 (org-add-props cmd nil
10811 'face 'org-warning))))
10812 (progn
10813 (message "Executing %s" cmd)
10814 (shell-command cmd buf)
10815 (when (featurep 'midnight)
10816 (setq clean-buffer-list-kill-buffer-names
10817 (cons (buffer-name buf)
10818 clean-buffer-list-kill-buffer-names))))
10819 (user-error "Abort"))))
10821 (defun org-open-at-point (&optional arg reference-buffer)
10822 "Open link, timestamp, footnote or tags at point.
10824 When point is on a link, follow it. Normally, files will be
10825 opened by an appropriate application. If the optional prefix
10826 argument ARG is non-nil, Emacs will visit the file. With
10827 a double prefix argument, try to open outside of Emacs, in the
10828 application the system uses for this file type.
10830 When point is on a timestamp, open the agenda at the day
10831 specified.
10833 When point is a footnote definition, move to the first reference
10834 found. If it is on a reference, move to the associated
10835 definition.
10837 When point is on a headline, display a list of every link in the
10838 entry, so it is possible to pick one, or all, of them. If point
10839 is on a tag, call `org-tags-view' instead.
10841 When optional argument REFERENCE-BUFFER is non-nil, it should
10842 specify a buffer from where the link search should happen. This
10843 is used internally by `org-open-link-from-string'.
10845 On top of syntactically correct links, this function will open
10846 the link at point in comments or comment blocks and the first
10847 link in a property drawer line."
10848 (interactive "P")
10849 ;; On a code block, open block's results.
10850 (unless (call-interactively 'org-babel-open-src-block-result)
10851 (org-load-modules-maybe)
10852 (setq org-window-config-before-follow-link (current-window-configuration))
10853 (org-remove-occur-highlights nil nil t)
10854 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10855 (let* ((context
10856 ;; Only consider supported types, even if they are not
10857 ;; the closest one.
10858 (org-element-lineage
10859 (org-element-context)
10860 '(clock comment comment-block footnote-definition
10861 footnote-reference headline inlinetask keyword link
10862 node-property timestamp)
10864 (type (org-element-type context))
10865 (value (org-element-property :value context)))
10866 (cond
10867 ((not context) (user-error "No link found"))
10868 ;; Exception: open timestamps and links in properties
10869 ;; drawers, keywords and comments.
10870 ((memq type '(comment comment-block keyword node-property))
10871 (call-interactively #'org-open-at-point-global))
10872 ;; On a headline or an inlinetask, but not on a timestamp,
10873 ;; a link, a footnote reference or on tags.
10874 ((and (memq type '(headline inlinetask))
10875 ;; Not on tags.
10876 (let ((case-fold-search nil))
10877 (save-excursion
10878 (beginning-of-line)
10879 (looking-at org-complex-heading-regexp))
10880 (or (not (match-beginning 5))
10881 (< (point) (match-beginning 5)))))
10882 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10883 (links (car data))
10884 (links-end (cdr data)))
10885 (if links
10886 (dolist (link (if (stringp links) (list links) links))
10887 (search-forward link nil links-end)
10888 (goto-char (match-beginning 0))
10889 (org-open-at-point))
10890 (require 'org-attach)
10891 (org-attach-reveal 'if-exists))))
10892 ;; On a clock line, make sure point is on the timestamp
10893 ;; before opening it.
10894 ((and (eq type 'clock)
10895 value
10896 (>= (point) (org-element-property :begin value))
10897 (<= (point) (org-element-property :end value)))
10898 (org-follow-timestamp-link))
10899 ;; Do nothing on white spaces after an object.
10900 ((>= (point)
10901 (save-excursion
10902 (goto-char (org-element-property :end context))
10903 (skip-chars-backward " \t")
10904 (point)))
10905 (user-error "No link found"))
10906 ((eq type 'timestamp) (org-follow-timestamp-link))
10907 ;; On tags within a headline or an inlinetask.
10908 ((and (memq type '(headline inlinetask))
10909 (let ((case-fold-search nil))
10910 (save-excursion (beginning-of-line)
10911 (looking-at org-complex-heading-regexp))
10912 (and (match-beginning 5)
10913 (>= (point) (match-beginning 5)))))
10914 (org-tags-view arg (substring (match-string 5) 0 -1)))
10915 ((eq type 'link)
10916 ;; When link is located within the description of another
10917 ;; link (e.g., an inline image), always open the parent
10918 ;; link.
10919 (let* ((link (let ((up (org-element-property :parent context)))
10920 (if (eq (org-element-type up) 'link) up context)))
10921 (type (org-element-property :type link))
10922 (path (org-link-unescape (org-element-property :path link))))
10923 ;; Switch back to REFERENCE-BUFFER needed when called in
10924 ;; a temporary buffer through `org-open-link-from-string'.
10925 (with-current-buffer (or reference-buffer (current-buffer))
10926 (cond
10927 ((equal type "file")
10928 (if (string-match "[*?{]" (file-name-nondirectory path))
10929 (dired path)
10930 ;; Look into `org-link-parameters' in order to find
10931 ;; a DEDICATED-FUNCTION to open file. The function
10932 ;; will be applied on raw link instead of parsed
10933 ;; link due to the limitation in `org-add-link-type'
10934 ;; ("open" function called with a single argument).
10935 ;; If no such function is found, fallback to
10936 ;; `org-open-file'.
10937 (let* ((option (org-element-property :search-option link))
10938 (app (org-element-property :application link))
10939 (dedicated-function
10940 (org-link-get-parameter
10941 (if app (concat type "+" app) type)
10942 :follow)))
10943 (if dedicated-function
10944 (funcall dedicated-function
10945 (concat path
10946 (and option (concat "::" option))))
10947 (apply #'org-open-file
10948 path
10949 (cond (arg)
10950 ((equal app "emacs") 'emacs)
10951 ((equal app "sys") 'system))
10952 (cond ((not option) nil)
10953 ((string-match-p "\\`[0-9]+\\'" option)
10954 (list (string-to-number option)))
10955 (t (list nil
10956 (org-link-unescape option)))))))))
10957 ((functionp (org-link-get-parameter type :follow))
10958 (funcall (org-link-get-parameter type :follow) path))
10959 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10960 (unless (run-hook-with-args-until-success
10961 'org-open-link-functions path)
10962 (if (not arg) (org-mark-ring-push)
10963 (switch-to-buffer-other-window
10964 (org-get-buffer-for-internal-link (current-buffer))))
10965 (let ((destination
10966 (org-with-wide-buffer
10967 (if (equal type "radio")
10968 (org-search-radio-target
10969 (org-element-property :path link))
10970 (org-link-search
10971 (if (member type '("custom-id" "coderef"))
10972 (org-element-property :raw-link link)
10973 path)
10974 ;; Prevent fuzzy links from matching
10975 ;; themselves.
10976 (and (equal type "fuzzy")
10977 (+ 2 (org-element-property :begin link)))))
10978 (point))))
10979 (unless (and (<= (point-min) destination)
10980 (>= (point-max) destination))
10981 (widen))
10982 (goto-char destination))))
10983 (t (browse-url-at-point))))))
10984 ;; On a footnote reference or at a footnote definition's label.
10985 ((or (eq type 'footnote-reference)
10986 (and (eq type 'footnote-definition)
10987 (save-excursion
10988 ;; Do not validate action when point is on the
10989 ;; spaces right after the footnote label, in
10990 ;; order to be on par with behaviour on links.
10991 (skip-chars-forward " \t")
10992 (let ((begin
10993 (org-element-property :contents-begin context)))
10994 (if begin (< (point) begin)
10995 (= (org-element-property :post-affiliated context)
10996 (line-beginning-position)))))))
10997 (org-footnote-action))
10998 (t (user-error "No link found")))))
10999 (run-hook-with-args 'org-follow-link-hook)))
11001 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
11002 "Offer links in the current entry and return the selected link.
11003 If there is only one link, return it.
11004 If NTH is an integer, return the NTH link found.
11005 If ZERO is a string, check also this string for a link, and if
11006 there is one, return it."
11007 (with-current-buffer buffer
11008 (org-with-wide-buffer
11009 (goto-char marker)
11010 (let ((cnt ?0)
11011 have-zero end links link c)
11012 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
11013 (push (match-string 0 zero) links)
11014 (setq cnt (1- cnt) have-zero t))
11015 (save-excursion
11016 (org-back-to-heading t)
11017 (setq end (save-excursion (outline-next-heading) (point)))
11018 (while (re-search-forward org-any-link-re end t)
11019 (push (match-string 0) links))
11020 (setq links (org-uniquify (reverse links))))
11021 (cond
11022 ((null links)
11023 (message "No links"))
11024 ((equal (length links) 1)
11025 (setq link (car links)))
11026 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
11027 (setq link (nth (if have-zero nth (1- nth)) links)))
11028 (t ; we have to select a link
11029 (save-excursion
11030 (save-window-excursion
11031 (delete-other-windows)
11032 (with-output-to-temp-buffer "*Select Link*"
11033 (dolist (l links)
11034 (cond
11035 ((not (string-match org-bracket-link-regexp l))
11036 (princ (format "[%c] %s\n" (cl-incf cnt)
11037 (org-unbracket-string "<" ">" l))))
11038 ((match-end 3)
11039 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
11040 (match-string 3 l) (match-string 1 l))))
11041 (t (princ (format "[%c] %s\n" (cl-incf cnt)
11042 (match-string 1 l)))))))
11043 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
11044 (message "Select link to open, RET to open all:")
11045 (setq c (read-char-exclusive))
11046 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
11047 (when (equal c ?q) (user-error "Abort"))
11048 (if (equal c ?\C-m)
11049 (setq link links)
11050 (setq nth (- c ?0))
11051 (when have-zero (setq nth (1+ nth)))
11052 (unless (and (integerp nth) (>= (length links) nth))
11053 (user-error "Invalid link selection"))
11054 (setq link (nth (1- nth) links)))))
11055 (cons link end)))))
11057 ;; TODO: These functions are deprecated since `org-open-at-point'
11058 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
11059 (defun org-open-file-with-system (path)
11060 "Open file at PATH using the system way of opening it."
11061 (org-open-file path 'system))
11062 (defun org-open-file-with-emacs (path)
11063 "Open file at PATH in Emacs."
11064 (org-open-file path 'emacs))
11067 ;;; File search
11069 (defvar org-create-file-search-functions nil
11070 "List of functions to construct the right search string for a file link.
11071 These functions are called in turn with point at the location to
11072 which the link should point.
11074 A function in the hook should first test if it would like to
11075 handle this file type, for example by checking the `major-mode'
11076 or the file extension. If it decides not to handle this file, it
11077 should just return nil to give other functions a chance. If it
11078 does handle the file, it must return the search string to be used
11079 when following the link. The search string will be part of the
11080 file link, given after a double colon, and `org-open-at-point'
11081 will automatically search for it. If special measures must be
11082 taken to make the search successful, another function should be
11083 added to the companion hook `org-execute-file-search-functions',
11084 which see.
11086 A function in this hook may also use `setq' to set the variable
11087 `description' to provide a suggestion for the descriptive text to
11088 be used for this link when it gets inserted into an Org buffer
11089 with \\[org-insert-link].")
11091 (defvar org-execute-file-search-functions nil
11092 "List of functions to execute a file search triggered by a link.
11094 Functions added to this hook must accept a single argument, the
11095 search string that was part of the file link, the part after the
11096 double colon. The function must first check if it would like to
11097 handle this search, for example by checking the `major-mode' or
11098 the file extension. If it decides not to handle this search, it
11099 should just return nil to give other functions a chance. If it
11100 does handle the search, it must return a non-nil value to keep
11101 other functions from trying.
11103 Each function can access the current prefix argument through the
11104 variable `current-prefix-arg'. Note that a single prefix is used
11105 to force opening a link in Emacs, so it may be good to only use a
11106 numeric or double prefix to guide the search function.
11108 In case this is needed, a function in this hook can also restore
11109 the window configuration before `org-open-at-point' was called using:
11111 (set-window-configuration org-window-config-before-follow-link)")
11113 (defun org-search-radio-target (target)
11114 "Search a radio target matching TARGET in current buffer.
11115 White spaces are not significant."
11116 (let ((re (format "<<<%s>>>"
11117 (mapconcat #'regexp-quote
11118 (org-split-string target "[ \t\n]+")
11119 "[ \t]+\\(?:\n[ \t]*\\)?")))
11120 (origin (point)))
11121 (goto-char (point-min))
11122 (catch :radio-match
11123 (while (re-search-forward re nil t)
11124 (backward-char)
11125 (let ((object (org-element-context)))
11126 (when (eq (org-element-type object) 'radio-target)
11127 (goto-char (org-element-property :begin object))
11128 (org-show-context 'link-search)
11129 (throw :radio-match nil))))
11130 (goto-char origin)
11131 (user-error "No match for radio target: %s" target))))
11133 (defun org-link-search (s &optional avoid-pos stealth)
11134 "Search for a search string S.
11136 If S starts with \"#\", it triggers a custom ID search.
11138 If S is enclosed within parenthesis, it initiates a coderef
11139 search.
11141 If S is surrounded by forward slashes, it is interpreted as
11142 a regular expression. In Org mode files, this will create an
11143 `org-occur' sparse tree. In ordinary files, `occur' will be used
11144 to list matches. If the current buffer is in `dired-mode', grep
11145 will be used to search in all files.
11147 When AVOID-POS is given, ignore matches near that position.
11149 When optional argument STEALTH is non-nil, do not modify
11150 visibility around point, thus ignoring `org-show-context-detail'
11151 variable.
11153 Search is case-insensitive and ignores white spaces. Return type
11154 of matched result, which is either `dedicated' or `fuzzy'."
11155 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11156 (let* ((case-fold-search t)
11157 (origin (point))
11158 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11159 (words (org-split-string s "[ \t\n]+"))
11160 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11161 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11162 type)
11163 (cond
11164 ;; Check if there are any special search functions.
11165 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11166 ((eq (string-to-char s) ?#)
11167 ;; Look for a custom ID S if S starts with "#".
11168 (let* ((id (substring normalized 1))
11169 (match (org-find-property "CUSTOM_ID" id)))
11170 (if match (progn (goto-char match) (setf type 'dedicated))
11171 (error "No match for custom ID: %s" id))))
11172 ((string-match "\\`(\\(.*\\))\\'" normalized)
11173 ;; Look for coderef targets if S is enclosed within parenthesis.
11174 (let ((coderef (match-string-no-properties 1 normalized))
11175 (re (substring s-single-re 1 -1)))
11176 (goto-char (point-min))
11177 (catch :coderef-match
11178 (while (re-search-forward re nil t)
11179 (let ((element (org-element-at-point)))
11180 (when (and (memq (org-element-type element)
11181 '(example-block src-block))
11182 ;; Build proper regexp according to current
11183 ;; block's label format.
11184 (let ((label-fmt
11185 (regexp-quote
11186 (or (org-element-property :label-fmt element)
11187 org-coderef-label-format))))
11188 (save-excursion
11189 (beginning-of-line)
11190 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11191 (format label-fmt coderef))))))
11192 (setq type 'dedicated)
11193 (goto-char (match-beginning 1))
11194 (throw :coderef-match nil))))
11195 (goto-char origin)
11196 (error "No match for coderef: %s" coderef))))
11197 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11198 ;; Look for a regular expression.
11199 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11200 (match-string 1 s)))
11201 ;; Fuzzy links.
11203 (let ((starred (eq (string-to-char normalized) ?*)))
11204 (cond
11205 ;; Look for targets, only if not in a headline search.
11206 ((and (not starred)
11207 (let ((target (format "<<%s>>" s-multi-re)))
11208 (catch :target-match
11209 (goto-char (point-min))
11210 (while (re-search-forward target nil t)
11211 (backward-char)
11212 (let ((context (org-element-context)))
11213 (when (eq (org-element-type context) 'target)
11214 (setq type 'dedicated)
11215 (goto-char (org-element-property :begin context))
11216 (throw :target-match t))))
11217 nil))))
11218 ;; Look for elements named after S, only if not in a headline
11219 ;; search.
11220 ((and (not starred)
11221 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11222 (catch :name-match
11223 (goto-char (point-min))
11224 (while (re-search-forward name nil t)
11225 (let ((element (org-element-at-point)))
11226 (when (equal (org-split-string
11227 (org-element-property :name element)
11228 "[ \t]+")
11229 words)
11230 (setq type 'dedicated)
11231 (beginning-of-line)
11232 (throw :name-match t))))
11233 nil))))
11234 ;; Regular text search. Prefer headlines in Org mode
11235 ;; buffers.
11236 ((and (derived-mode-p 'org-mode)
11237 (let* ((wspace "[ \t]")
11238 (wspaceopt (concat wspace "*"))
11239 (cookie (concat "\\(?:"
11240 wspaceopt
11241 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11242 wspaceopt
11243 "\\)"))
11244 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11245 (title
11246 (format "\\(?:%s[ \t]+\\)?%s?%s%s?"
11247 org-comment-string
11249 (let ((re (mapconcat #'regexp-quote words sep)))
11250 (if starred (substring re 1) re))
11251 sep))
11252 (exact-title (format "\\`%s\\'" title))
11253 (re (concat org-outline-regexp-bol "+.*" title)))
11254 (goto-char (point-min))
11255 (catch :found
11256 (while (re-search-forward re nil t)
11257 (when (string-match-p exact-title (org-get-heading t t))
11258 (throw :found t)))
11259 nil)))
11260 (beginning-of-line)
11261 (setq type 'dedicated))
11262 ;; Offer to create non-existent headline depending on
11263 ;; `org-link-search-must-match-exact-headline'.
11264 ((and (derived-mode-p 'org-mode)
11265 (not org-link-search-inhibit-query)
11266 (eq org-link-search-must-match-exact-headline 'query-to-create)
11267 (yes-or-no-p "No match - create this as a new heading? "))
11268 (goto-char (point-max))
11269 (unless (bolp) (newline))
11270 (org-insert-heading nil t t)
11271 (insert s "\n")
11272 (beginning-of-line 0))
11273 ;; Only headlines are looked after. No need to process
11274 ;; further: throw an error.
11275 ((and (derived-mode-p 'org-mode)
11276 (or starred org-link-search-must-match-exact-headline))
11277 (goto-char origin)
11278 (error "No match for fuzzy expression: %s" normalized))
11279 ;; Regular text search.
11280 ((catch :fuzzy-match
11281 (goto-char (point-min))
11282 (while (re-search-forward s-multi-re nil t)
11283 ;; Skip match if it contains AVOID-POS or it is included
11284 ;; in a link with a description but outside the
11285 ;; description.
11286 (unless (or (and avoid-pos
11287 (<= (match-beginning 0) avoid-pos)
11288 (> (match-end 0) avoid-pos))
11289 (and (save-match-data
11290 (org-in-regexp org-bracket-link-regexp))
11291 (match-beginning 3)
11292 (or (> (match-beginning 3) (point))
11293 (<= (match-end 3) (point)))
11294 (org-element-lineage
11295 (save-match-data (org-element-context))
11296 '(link) t)))
11297 (goto-char (match-beginning 0))
11298 (setq type 'fuzzy)
11299 (throw :fuzzy-match t)))
11300 nil))
11301 ;; All failed. Throw an error.
11302 (t (goto-char origin)
11303 (error "No match for fuzzy expression: %s" normalized))))))
11304 ;; Disclose surroundings of match, if appropriate.
11305 (when (and (derived-mode-p 'org-mode) (not stealth))
11306 (org-show-context 'link-search))
11307 type))
11309 (defun org-get-buffer-for-internal-link (buffer)
11310 "Return a buffer to be used for displaying the link target of internal links."
11311 (cond
11312 ((not org-display-internal-link-with-indirect-buffer)
11313 buffer)
11314 ((string-suffix-p "(Clone)" (buffer-name buffer))
11315 (message "Buffer is already a clone, not making another one")
11316 ;; we also do not modify visibility in this case
11317 buffer)
11318 (t ; make a new indirect buffer for displaying the link
11319 (let* ((bn (buffer-name buffer))
11320 (ibn (concat bn "(Clone)"))
11321 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11322 (with-current-buffer ib (org-overview))
11323 ib))))
11325 (defun org-do-occur (regexp &optional cleanup)
11326 "Call the Emacs command `occur'.
11327 If CLEANUP is non-nil, remove the printout of the regular expression
11328 in the *Occur* buffer. This is useful if the regex is long and not useful
11329 to read."
11330 (occur regexp)
11331 (when cleanup
11332 (let ((cwin (selected-window)) win beg end)
11333 (when (setq win (get-buffer-window "*Occur*"))
11334 (select-window win))
11335 (goto-char (point-min))
11336 (when (re-search-forward "match[a-z]+" nil t)
11337 (setq beg (match-end 0))
11338 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11339 (setq end (1- (match-beginning 0)))))
11340 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11341 (goto-char (point-min))
11342 (select-window cwin))))
11344 ;;; The mark ring for links jumps
11346 (defvar org-mark-ring nil
11347 "Mark ring for positions before jumps in Org mode.")
11348 (defvar org-mark-ring-last-goto nil
11349 "Last position in the mark ring used to go back.")
11350 ;; Fill and close the ring
11351 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11352 (dotimes (_ org-mark-ring-length)
11353 (push (make-marker) org-mark-ring))
11354 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11355 org-mark-ring)
11357 (defun org-mark-ring-push (&optional pos buffer)
11358 "Put the current position or POS into the mark ring and rotate it."
11359 (interactive)
11360 (setq pos (or pos (point)))
11361 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11362 (move-marker (car org-mark-ring)
11363 (or pos (point))
11364 (or buffer (current-buffer)))
11365 (message "%s"
11366 (substitute-command-keys
11367 "Position saved to mark ring, go back with \
11368 `\\[org-mark-ring-goto]'.")))
11370 (defun org-mark-ring-goto (&optional n)
11371 "Jump to the previous position in the mark ring.
11372 With prefix arg N, jump back that many stored positions. When
11373 called several times in succession, walk through the entire ring.
11374 Org mode commands jumping to a different position in the current file,
11375 or to another Org file, automatically push the old position onto the ring."
11376 (interactive "p")
11377 (let (p m)
11378 (if (eq last-command this-command)
11379 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11380 (setq p org-mark-ring))
11381 (setq org-mark-ring-last-goto p)
11382 (setq m (car p))
11383 (pop-to-buffer-same-window (marker-buffer m))
11384 (goto-char m)
11385 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11387 (defun org-add-angle-brackets (s)
11388 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11389 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11392 ;;; Following specific links
11394 (defvar org-agenda-buffer-tmp-name)
11395 (defvar org-agenda-start-on-weekday)
11396 (defun org-follow-timestamp-link ()
11397 "Open an agenda view for the time-stamp date/range at point."
11398 (cond
11399 ((org-at-date-range-p t)
11400 (let ((org-agenda-start-on-weekday)
11401 (t1 (match-string 1))
11402 (t2 (match-string 2)) tt1 tt2)
11403 (setq tt1 (time-to-days (org-time-string-to-time t1))
11404 tt2 (time-to-days (org-time-string-to-time t2)))
11405 (let ((org-agenda-buffer-tmp-name
11406 (format "*Org Agenda(a:%s)"
11407 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11408 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11409 ((org-at-timestamp-p t)
11410 (let ((org-agenda-buffer-tmp-name
11411 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11412 (org-agenda-list nil (time-to-days (org-time-string-to-time
11413 (substring (match-string 1) 0 10)))
11414 1)))
11415 (t (error "This should not happen"))))
11418 ;;; Following file links
11419 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11420 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11421 (declare-function mailcap-mime-info
11422 "mailcap" (string &optional request no-decode))
11423 (defvar org-wait nil)
11424 (defun org-open-file (path &optional in-emacs line search)
11425 "Open the file at PATH.
11426 First, this expands any special file name abbreviations. Then the
11427 configuration variable `org-file-apps' is checked if it contains an
11428 entry for this file type, and if yes, the corresponding command is launched.
11430 If no application is found, Emacs simply visits the file.
11432 With optional prefix argument IN-EMACS, Emacs will visit the file.
11433 With a double \\[universal-argument] \\[universal-argument] \
11434 prefix arg, Org tries to avoid opening in Emacs
11435 and to use an external application to visit the file.
11437 Optional LINE specifies a line to go to, optional SEARCH a string
11438 to search for. If LINE or SEARCH is given, the file will be
11439 opened in Emacs, unless an entry from org-file-apps that makes
11440 use of groups in a regexp matches.
11442 If you want to change the way frames are used when following a
11443 link, please customize `org-link-frame-setup'.
11445 If the file does not exist, an error is thrown."
11446 (let* ((file (if (equal path "")
11447 buffer-file-name
11448 (substitute-in-file-name (expand-file-name path))))
11449 (file-apps (append org-file-apps (org-default-apps)))
11450 (apps (cl-remove-if
11451 'org-file-apps-entry-match-against-dlink-p file-apps))
11452 (apps-dlink (cl-remove-if-not
11453 'org-file-apps-entry-match-against-dlink-p file-apps))
11454 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11455 (dirp (unless remp (file-directory-p file)))
11456 (file (if (and dirp org-open-directory-means-index-dot-org)
11457 (concat (file-name-as-directory file) "index.org")
11458 file))
11459 (a-m-a-p (assq 'auto-mode apps))
11460 (dfile (downcase file))
11461 ;; Reconstruct the original link from the PATH, LINE and
11462 ;; SEARCH args.
11463 (link (cond (line (concat file "::" (number-to-string line)))
11464 (search (concat file "::" search))
11465 (t file)))
11466 (dlink (downcase link))
11467 (old-buffer (current-buffer))
11468 (old-pos (point))
11469 (old-mode major-mode)
11470 (ext
11471 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11472 (match-string 1 dfile)))
11473 cmd link-match-data)
11474 (cond
11475 ((member in-emacs '((16) system))
11476 (setq cmd (cdr (assq 'system apps))))
11477 (in-emacs (setq cmd 'emacs))
11479 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11480 (and dirp (cdr (assq 'directory apps)))
11481 ;; First, try matching against apps-dlink if we
11482 ;; get a match here, store the match data for
11483 ;; later.
11484 (let ((match (assoc-default dlink apps-dlink
11485 'string-match)))
11486 (if match
11487 (progn (setq link-match-data (match-data))
11488 match)
11489 (progn (setq in-emacs (or in-emacs line search))
11490 nil))) ; if we have no match in apps-dlink,
11491 ; always open the file in emacs if line or search
11492 ; is given (for backwards compatibility)
11493 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11494 'string-match)
11495 (cdr (assoc ext apps))
11496 (cdr (assq t apps))))))
11497 (when (eq cmd 'system)
11498 (setq cmd (cdr (assq 'system apps))))
11499 (when (eq cmd 'default)
11500 (setq cmd (cdr (assoc t apps))))
11501 (when (eq cmd 'mailcap)
11502 (require 'mailcap)
11503 (mailcap-parse-mailcaps)
11504 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11505 (command (mailcap-mime-info mime-type)))
11506 (if (stringp command)
11507 (setq cmd command)
11508 (setq cmd 'emacs))))
11509 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11510 (not (file-exists-p file))
11511 (not org-open-non-existing-files))
11512 (user-error "No such file: %s" file))
11513 (cond
11514 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11515 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11516 (while (string-match "['\"]%s['\"]" cmd)
11517 (setq cmd (replace-match "%s" t t cmd)))
11518 (setq cmd (replace-regexp-in-string
11519 "%s"
11520 (shell-quote-argument (convert-standard-filename file))
11522 nil t))
11524 ;; Replace "%1", "%2" etc. in command with group matches from regex
11525 (save-match-data
11526 (let ((match-index 1)
11527 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11528 (set-match-data link-match-data)
11529 (while (<= match-index number-of-groups)
11530 (let ((regex (concat "%" (number-to-string match-index)))
11531 (replace-with (match-string match-index dlink)))
11532 (while (string-match regex cmd)
11533 (setq cmd (replace-match replace-with t t cmd))))
11534 (setq match-index (+ match-index 1)))))
11536 (save-window-excursion
11537 (message "Running %s...done" cmd)
11538 (start-process-shell-command cmd nil cmd)
11539 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11540 ((or (stringp cmd)
11541 (eq cmd 'emacs))
11542 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11543 (widen)
11544 (cond (line (org-goto-line line)
11545 (when (derived-mode-p 'org-mode) (org-reveal)))
11546 (search (org-link-search search))))
11547 ((functionp cmd)
11548 (save-match-data
11549 (set-match-data link-match-data)
11550 (condition-case nil
11551 (funcall cmd file link)
11552 ;; FIXME: Remove this check when most default installations
11553 ;; of Emacs have at least Org 9.0.
11554 ((debug wrong-number-of-arguments wrong-type-argument
11555 invalid-function)
11556 (user-error "Please see Org News for version 9.0 about \
11557 `org-file-apps'--Lisp error: %S" cmd)))))
11558 ((consp cmd)
11559 ;; FIXME: Remove this check when most default installations of
11560 ;; Emacs have at least Org 9.0.
11561 ;; Heads-up instead of silently fall back to
11562 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11563 ;; with sexp instead of a function for `cmd'.
11564 (user-error "Please see Org News for version 9.0 about \
11565 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11566 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11567 (and (derived-mode-p 'org-mode)
11568 (eq old-mode 'org-mode)
11569 (or (not (eq old-buffer (current-buffer)))
11570 (not (eq old-pos (point))))
11571 (org-mark-ring-push old-pos old-buffer))))
11573 (defun org-file-apps-entry-match-against-dlink-p (entry)
11574 "This function returns non-nil if `entry' uses a regular
11575 expression which should be matched against the whole link by
11576 org-open-file.
11578 It assumes that is the case when the entry uses a regular
11579 expression which has at least one grouping construct and the
11580 action is either a lisp form or a command string containing
11581 `%1', i.e. using at least one subexpression match as a
11582 parameter."
11583 (let ((selector (car entry))
11584 (action (cdr entry)))
11585 (if (stringp selector)
11586 (and (> (regexp-opt-depth selector) 0)
11587 (or (and (stringp action)
11588 (string-match "%[0-9]" action))
11589 (consp action)))
11590 nil)))
11592 (defun org-default-apps ()
11593 "Return the default applications for this operating system."
11594 (cond
11595 ((eq system-type 'darwin)
11596 org-file-apps-defaults-macosx)
11597 ((eq system-type 'windows-nt)
11598 org-file-apps-defaults-windowsnt)
11599 (t org-file-apps-defaults-gnu)))
11601 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11602 "Convert extensions to regular expressions in the cars of LIST.
11603 Also, weed out any non-string entries, because the return value is used
11604 only for regexp matching.
11605 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11606 point to the symbol `emacs', indicating that the file should
11607 be opened in Emacs."
11608 (append
11609 (delq nil
11610 (mapcar (lambda (x)
11611 (unless (not (stringp (car x)))
11612 (if (string-match "\\W" (car x))
11614 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11615 list))
11616 (when add-auto-mode
11617 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11619 (defvar ange-ftp-name-format)
11620 (defun org-file-remote-p (file)
11621 "Test whether FILE specifies a location on a remote system.
11622 Return non-nil if the location is indeed remote.
11624 For example, the filename \"/user@host:/foo\" specifies a location
11625 on the system \"/user@host:\"."
11626 (cond ((fboundp 'file-remote-p)
11627 (file-remote-p file))
11628 ((fboundp 'tramp-handle-file-remote-p)
11629 (tramp-handle-file-remote-p file))
11630 ((and (boundp 'ange-ftp-name-format)
11631 (string-match (car ange-ftp-name-format) file))
11632 t)))
11635 ;;;; Refiling
11637 (defun org-get-org-file ()
11638 "Read a filename, with default directory `org-directory'."
11639 (let ((default (or org-default-notes-file remember-data-file)))
11640 (read-file-name (format "File name [%s]: " default)
11641 (file-name-as-directory org-directory)
11642 default)))
11644 (defun org-notes-order-reversed-p ()
11645 "Check if the current file should receive notes in reversed order."
11646 (cond
11647 ((not org-reverse-note-order) nil)
11648 ((eq t org-reverse-note-order) t)
11649 ((not (listp org-reverse-note-order)) nil)
11650 (t (catch 'exit
11651 (dolist (entry org-reverse-note-order)
11652 (when (string-match (car entry) buffer-file-name)
11653 (throw 'exit (cdr entry))))))))
11655 (defvar org-refile-target-table nil
11656 "The list of refile targets, created by `org-refile'.")
11658 (defvar org-agenda-new-buffers nil
11659 "Buffers created to visit agenda files.")
11661 (defvar org-refile-cache nil
11662 "Cache for refile targets.")
11664 (defvar org-refile-markers nil
11665 "All the markers used for caching refile locations.")
11667 (defun org-refile-marker (pos)
11668 "Get a new refile marker, but only if caching is in use."
11669 (if (not org-refile-use-cache)
11671 (let ((m (make-marker)))
11672 (move-marker m pos)
11673 (push m org-refile-markers)
11674 m)))
11676 (defun org-refile-cache-clear ()
11677 "Clear the refile cache and disable all the markers."
11678 (dolist (m org-refile-markers) (move-marker m nil))
11679 (setq org-refile-markers nil)
11680 (setq org-refile-cache nil)
11681 (message "Refile cache has been cleared"))
11683 (defun org-refile-cache-check-set (set)
11684 "Check if all the markers in the cache still have live buffers."
11685 (let (marker)
11686 (catch 'exit
11687 (while (and set (setq marker (nth 3 (pop set))))
11688 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11689 (when (and marker (null (marker-buffer marker)))
11690 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11691 (sit-for 3)
11692 (throw 'exit nil)))
11693 t)))
11695 (defun org-refile-cache-put (set &rest identifiers)
11696 "Push the refile targets SET into the cache, under IDENTIFIERS."
11697 (let* ((key (sha1 (prin1-to-string identifiers)))
11698 (entry (assoc key org-refile-cache)))
11699 (if entry
11700 (setcdr entry set)
11701 (push (cons key set) org-refile-cache))))
11703 (defun org-refile-cache-get (&rest identifiers)
11704 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11705 (cond
11706 ((not org-refile-cache) nil)
11707 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11709 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11710 org-refile-cache))))
11711 (and set (org-refile-cache-check-set set) set)))))
11713 (defvar org-outline-path-cache nil
11714 "Alist between buffer positions and outline paths.
11715 It value is an alist (POSITION . PATH) where POSITION is the
11716 buffer position at the beginning of an entry and PATH is a list
11717 of strings describing the outline path for that entry, in reverse
11718 order.")
11720 (defun org-refile-get-targets (&optional default-buffer)
11721 "Produce a table with refile targets."
11722 (let ((case-fold-search nil)
11723 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11724 (entries (or org-refile-targets '((nil . (:level . 1)))))
11725 targets tgs files desc descre)
11726 (message "Getting targets...")
11727 (with-current-buffer (or default-buffer (current-buffer))
11728 (dolist (entry entries)
11729 (setq files (car entry) desc (cdr entry))
11730 (cond
11731 ((null files) (setq files (list (current-buffer))))
11732 ((eq files 'org-agenda-files)
11733 (setq files (org-agenda-files 'unrestricted)))
11734 ((and (symbolp files) (fboundp files))
11735 (setq files (funcall files)))
11736 ((and (symbolp files) (boundp files))
11737 (setq files (symbol-value files))))
11738 (when (stringp files) (setq files (list files)))
11739 (cond
11740 ((eq (car desc) :tag)
11741 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11742 ((eq (car desc) :todo)
11743 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11744 ((eq (car desc) :regexp)
11745 (setq descre (cdr desc)))
11746 ((eq (car desc) :level)
11747 (setq descre (concat "^\\*\\{" (number-to-string
11748 (if org-odd-levels-only
11749 (1- (* 2 (cdr desc)))
11750 (cdr desc)))
11751 "\\}[ \t]")))
11752 ((eq (car desc) :maxlevel)
11753 (setq descre (concat "^\\*\\{1," (number-to-string
11754 (if org-odd-levels-only
11755 (1- (* 2 (cdr desc)))
11756 (cdr desc)))
11757 "\\}[ \t]")))
11758 (t (error "Bad refiling target description %s" desc)))
11759 (dolist (f files)
11760 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11762 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11763 (progn
11764 (when (bufferp f)
11765 (setq f (buffer-file-name (buffer-base-buffer f))))
11766 (setq f (and f (expand-file-name f)))
11767 (when (eq org-refile-use-outline-path 'file)
11768 (push (list (file-name-nondirectory f) f nil nil) tgs))
11769 (org-with-wide-buffer
11770 (goto-char (point-min))
11771 (setq org-outline-path-cache nil)
11772 (while (re-search-forward descre nil t)
11773 (beginning-of-line)
11774 (let ((case-fold-search nil))
11775 (looking-at org-complex-heading-regexp))
11776 (let ((begin (point))
11777 (heading (match-string-no-properties 4)))
11778 (unless (or (and
11779 org-refile-target-verify-function
11780 (not
11781 (funcall org-refile-target-verify-function)))
11782 (not heading))
11783 (let ((re (format org-complex-heading-regexp-format
11784 (regexp-quote heading)))
11785 (target
11786 (if (not org-refile-use-outline-path) heading
11787 (mapconcat
11788 #'org-protect-slash
11789 (append
11790 (pcase org-refile-use-outline-path
11791 (`file (list (file-name-nondirectory
11792 (buffer-file-name
11793 (buffer-base-buffer)))))
11794 (`full-file-path
11795 (list (buffer-file-name
11796 (buffer-base-buffer))))
11797 (_ nil))
11798 (org-get-outline-path t t))
11799 "/"))))
11800 (push (list target f re (org-refile-marker (point)))
11801 tgs)))
11802 (when (= (point) begin)
11803 ;; Verification function has not moved point.
11804 (end-of-line)))))))
11805 (when org-refile-use-cache
11806 (org-refile-cache-put tgs (buffer-file-name) descre))
11807 (setq targets (append tgs targets))))))
11808 (message "Getting targets...done")
11809 (nreverse targets)))
11811 (defun org-protect-slash (s)
11812 (replace-regexp-in-string "/" "\\/" s nil t))
11814 (defun org--get-outline-path-1 (&optional use-cache)
11815 "Return outline path to current headline.
11817 Outline path is a list of strings, in reverse order. When
11818 optional argument USE-CACHE is non-nil, make use of a cache. See
11819 `org-get-outline-path' for details.
11821 Assume buffer is widened and point is on a headline."
11822 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11823 (let ((p (point))
11824 (heading (let ((case-fold-search nil))
11825 (looking-at org-complex-heading-regexp)
11826 (if (not (match-end 4)) ""
11827 ;; Remove statistics cookies.
11828 (org-trim
11829 (org-link-display-format
11830 (replace-regexp-in-string
11831 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11832 (match-string-no-properties 4))))))))
11833 (if (org-up-heading-safe)
11834 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11835 (when use-cache
11836 (push (cons p path) org-outline-path-cache))
11837 path)
11838 ;; This is a new root node. Since we assume we are moving
11839 ;; forward, we can drop previous cache so as to limit number
11840 ;; of associations there.
11841 (let ((path (list heading)))
11842 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11843 path)))))
11845 (defun org-get-outline-path (&optional with-self use-cache)
11846 "Return the outline path to the current entry.
11848 An outline path is a list of ancestors for current headline, as
11849 a list of strings. Statistics cookies are removed and links are
11850 replaced with their description, if any, or their path otherwise.
11852 When optional argument WITH-SELF is non-nil, the path also
11853 includes the current headline.
11855 When optional argument USE-CACHE is non-nil, cache outline paths
11856 between calls to this function so as to avoid backtracking. This
11857 argument is useful when planning to find more than one outline
11858 path in the same document. In that case, there are two
11859 conditions to satisfy:
11860 - `org-outline-path-cache' is set to nil before starting the
11861 process;
11862 - outline paths are computed by increasing buffer positions."
11863 (org-with-wide-buffer
11864 (and (or (and with-self (org-back-to-heading t))
11865 (org-up-heading-safe))
11866 (reverse (org--get-outline-path-1 use-cache)))))
11868 (defun org-format-outline-path (path &optional width prefix separator)
11869 "Format the outline path PATH for display.
11870 WIDTH is the maximum number of characters that is available.
11871 PREFIX is a prefix to be included in the returned string,
11872 such as the file name.
11873 SEPARATOR is inserted between the different parts of the path,
11874 the default is \"/\"."
11875 (setq width (or width 79))
11876 (setq path (delq nil path))
11877 (unless (> width 0)
11878 (user-error "Argument `width' must be positive"))
11879 (setq separator (or separator "/"))
11880 (let* ((org-odd-levels-only nil)
11881 (fpath (concat
11882 prefix (and prefix path separator)
11883 (mapconcat
11884 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11885 (cl-loop for head in path
11886 for n from 0
11887 collect (org-add-props
11888 head nil 'face
11889 (nth (% n org-n-level-faces) org-level-faces)))
11890 separator))))
11891 (when (> (length fpath) width)
11892 (if (< width 7)
11893 ;; It's unlikely that `width' will be this small, but don't
11894 ;; waste characters by adding ".." if it is.
11895 (setq fpath (substring fpath 0 width))
11896 (setf (substring fpath (- width 2)) "..")))
11897 fpath))
11899 (defun org-display-outline-path (&optional file current separator just-return-string)
11900 "Display the current outline path in the echo area.
11902 If FILE is non-nil, prepend the output with the file name.
11903 If CURRENT is non-nil, append the current heading to the output.
11904 SEPARATOR is passed through to `org-format-outline-path'. It separates
11905 the different parts of the path and defaults to \"/\".
11906 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11907 (interactive "P")
11908 (let* (case-fold-search
11909 (bfn (buffer-file-name (buffer-base-buffer)))
11910 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11911 res)
11912 (when current (setq path (append path
11913 (save-excursion
11914 (org-back-to-heading t)
11915 (when (looking-at org-complex-heading-regexp)
11916 (list (match-string 4)))))))
11917 (setq res
11918 (org-format-outline-path
11919 path
11920 (1- (frame-width))
11921 (and file bfn (concat (file-name-nondirectory bfn) separator))
11922 separator))
11923 (if just-return-string
11924 (org-no-properties res)
11925 (org-unlogged-message "%s" res))))
11927 (defvar org-refile-history nil
11928 "History for refiling operations.")
11930 (defvar org-after-refile-insert-hook nil
11931 "Hook run after `org-refile' has inserted its stuff at the new location.
11932 Note that this is still *before* the stuff will be removed from
11933 the *old* location.")
11935 (defvar org-capture-last-stored-marker)
11936 (defvar org-refile-keep nil
11937 "Non-nil means `org-refile' will copy instead of refile.")
11939 (defun org-copy ()
11940 "Like `org-refile', but copy."
11941 (interactive)
11942 (let ((org-refile-keep t))
11943 (funcall 'org-refile nil nil nil "Copy")))
11945 (defun org-refile (&optional arg default-buffer rfloc msg)
11946 "Move the entry or entries at point to another heading.
11948 The list of target headings is compiled using the information in
11949 `org-refile-targets', which see.
11951 At the target location, the entry is filed as a subitem of the
11952 target heading. Depending on `org-reverse-note-order', the new
11953 subitem will either be the first or the last subitem.
11955 If there is an active region, all entries in that region will be
11956 refiled. However, the region must fulfill the requirement that
11957 the first heading sets the top-level of the moved text.
11959 With a `\\[universal-argument]' ARG, the command will only visit the target \
11960 location
11961 and not actually move anything.
11963 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11964 location where the last
11965 refiling operation has put the subtree.
11967 With a numeric prefix argument of `2', refile to the running clock.
11969 With a numeric prefix argument of `3', emulate `org-refile-keep'
11970 being set to t and copy to the target location, don't move it.
11971 Beware that keeping refiled entries may result in duplicated ID
11972 properties.
11974 RFLOC can be a refile location obtained in a different way.
11976 MSG is a string to replace \"Refile\" in the default prompt with
11977 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11979 See also `org-refile-use-outline-path'.
11981 If you are using target caching (see `org-refile-use-cache'), you
11982 have to clear the target cache in order to find new targets.
11983 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11984 prefix argument (`C-u C-u C-u C-c C-w')."
11985 (interactive "P")
11986 (if (member arg '(0 (64)))
11987 (org-refile-cache-clear)
11988 (let* ((actionmsg (cond (msg msg)
11989 ((equal arg 3) "Refile (and keep)")
11990 (t "Refile")))
11991 (regionp (org-region-active-p))
11992 (region-start (and regionp (region-beginning)))
11993 (region-end (and regionp (region-end)))
11994 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11995 pos it nbuf file level reversed)
11996 (setq last-command nil)
11997 (when regionp
11998 (goto-char region-start)
11999 (or (bolp) (goto-char (point-at-bol)))
12000 (setq region-start (point))
12001 (unless (or (org-kill-is-subtree-p
12002 (buffer-substring region-start region-end))
12003 (prog1 org-refile-active-region-within-subtree
12004 (let ((s (point-at-eol)))
12005 (org-toggle-heading)
12006 (setq region-end (+ (- (point-at-eol) s) region-end)))))
12007 (user-error "The region is not a (sequence of) subtree(s)")))
12008 (if (equal arg '(16))
12009 (org-refile-goto-last-stored)
12010 (when (or
12011 (and (equal arg 2)
12012 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
12013 (prog1
12014 (setq it (list (or org-clock-heading "running clock")
12015 (buffer-file-name
12016 (marker-buffer org-clock-hd-marker))
12018 (marker-position org-clock-hd-marker)))
12019 (setq arg nil)))
12020 (setq it
12021 (or rfloc
12022 (let (heading-text)
12023 (save-excursion
12024 (unless (and arg (listp arg))
12025 (org-back-to-heading t)
12026 (setq heading-text
12027 (replace-regexp-in-string
12028 org-bracket-link-regexp
12029 "\\3"
12030 (or (nth 4 (org-heading-components))
12031 ""))))
12032 (org-refile-get-location
12033 (cond ((and arg (listp arg)) "Goto")
12034 (regionp (concat actionmsg " region to"))
12035 (t (concat actionmsg " subtree \""
12036 heading-text "\" to")))
12037 default-buffer
12038 (and (not (equal '(4) arg))
12039 org-refile-allow-creating-parent-nodes)))))))
12040 (setq file (nth 1 it)
12041 pos (nth 3 it))
12042 (when (and (not arg)
12044 (equal (buffer-file-name) file)
12045 (if regionp
12046 (and (>= pos region-start)
12047 (<= pos region-end))
12048 (and (>= pos (point))
12049 (< pos (save-excursion
12050 (org-end-of-subtree t t))))))
12051 (error "Cannot refile to position inside the tree or region"))
12052 (setq nbuf (or (find-buffer-visiting file)
12053 (find-file-noselect file)))
12054 (if (and arg (not (equal arg 3)))
12055 (progn
12056 (pop-to-buffer-same-window nbuf)
12057 (goto-char pos)
12058 (org-show-context 'org-goto))
12059 (if regionp
12060 (progn
12061 (org-kill-new (buffer-substring region-start region-end))
12062 (org-save-markers-in-region region-start region-end))
12063 (org-copy-subtree 1 nil t))
12064 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
12065 (find-file-noselect file)))
12066 (setq reversed (org-notes-order-reversed-p))
12067 (org-with-wide-buffer
12068 (if pos
12069 (progn
12070 (goto-char pos)
12071 (looking-at org-outline-regexp)
12072 (setq level (org-get-valid-level (funcall outline-level) 1))
12073 (goto-char
12074 (if reversed
12075 (or (outline-next-heading) (point-max))
12076 (or (save-excursion (org-get-next-sibling))
12077 (org-end-of-subtree t t)
12078 (point-max)))))
12079 (setq level 1)
12080 (if (not reversed)
12081 (goto-char (point-max))
12082 (goto-char (point-min))
12083 (or (outline-next-heading) (goto-char (point-max)))))
12084 (unless (bolp) (newline))
12085 (org-paste-subtree level nil nil t)
12086 (when org-log-refile
12087 (org-add-log-setup 'refile nil nil org-log-refile)
12088 (unless (eq org-log-refile 'note)
12089 (save-excursion (org-add-log-note))))
12090 (and org-auto-align-tags
12091 (let ((org-loop-over-headlines-in-active-region nil))
12092 (org-set-tags nil t)))
12093 (let ((bookmark-name (plist-get org-bookmark-names-plist
12094 :last-refile)))
12095 (when bookmark-name
12096 (with-demoted-errors
12097 (bookmark-set bookmark-name))))
12098 ;; If we are refiling for capture, make sure that the
12099 ;; last-capture pointers point here
12100 (when (bound-and-true-p org-capture-is-refiling)
12101 (let ((bookmark-name (plist-get org-bookmark-names-plist
12102 :last-capture-marker)))
12103 (when bookmark-name
12104 (with-demoted-errors
12105 (bookmark-set bookmark-name))))
12106 (move-marker org-capture-last-stored-marker (point)))
12107 (when (fboundp 'deactivate-mark) (deactivate-mark))
12108 (run-hooks 'org-after-refile-insert-hook)))
12109 (unless org-refile-keep
12110 (if regionp
12111 (delete-region (point) (+ (point) (- region-end region-start)))
12112 (delete-region
12113 (and (org-back-to-heading t) (point))
12114 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12115 (when (featurep 'org-inlinetask)
12116 (org-inlinetask-remove-END-maybe))
12117 (setq org-markers-to-move nil)
12118 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12120 (defun org-refile-goto-last-stored ()
12121 "Go to the location where the last refile was stored."
12122 (interactive)
12123 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12124 (message "This is the location of the last refile"))
12126 (defun org-refile--get-location (refloc tbl)
12127 "When user refile to REFLOC, find the associated target in TBL.
12128 Also check `org-refile-target-table'."
12129 (car (delq
12131 (mapcar
12132 (lambda (r) (or (assoc r tbl)
12133 (assoc r org-refile-target-table)))
12134 (list (replace-regexp-in-string "/$" "" refloc)
12135 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12137 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12138 "Prompt the user for a refile location, using PROMPT.
12139 PROMPT should not be suffixed with a colon and a space, because
12140 this function appends the default value from
12141 `org-refile-history' automatically, if that is not empty."
12142 (let ((org-refile-targets org-refile-targets)
12143 (org-refile-use-outline-path org-refile-use-outline-path))
12144 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12145 (unless org-refile-target-table
12146 (user-error "No refile targets"))
12147 (let* ((cbuf (current-buffer))
12148 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12149 (cfunc (if (and org-refile-use-outline-path
12150 org-outline-path-complete-in-steps)
12151 #'org-olpath-completing-read
12152 #'completing-read))
12153 (extra (if org-refile-use-outline-path "/" ""))
12154 (cbnex (concat (buffer-name) extra))
12155 (filename (and cfn (expand-file-name cfn)))
12156 (tbl (mapcar
12157 (lambda (x)
12158 (if (and (not (member org-refile-use-outline-path
12159 '(file full-file-path)))
12160 (not (equal filename (nth 1 x))))
12161 (cons (concat (car x) extra " ("
12162 (file-name-nondirectory (nth 1 x)) ")")
12163 (cdr x))
12164 (cons (concat (car x) extra) (cdr x))))
12165 org-refile-target-table))
12166 (completion-ignore-case t)
12167 cdef
12168 (prompt (concat prompt
12169 (or (and (car org-refile-history)
12170 (concat " (default " (car org-refile-history) ")"))
12171 (and (assoc cbnex tbl) (setq cdef cbnex)
12172 (concat " (default " cbnex ")"))) ": "))
12173 pa answ parent-target child parent old-hist)
12174 (setq old-hist org-refile-history)
12175 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12176 nil 'org-refile-history (or cdef (car org-refile-history))))
12177 (if (setq pa (org-refile--get-location answ tbl))
12178 (progn
12179 (org-refile-check-position pa)
12180 (when (or (not org-refile-history)
12181 (not (eq old-hist org-refile-history))
12182 (not (equal (car pa) (car org-refile-history))))
12183 (setq org-refile-history
12184 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12185 org-refile-history
12186 (cdr org-refile-history))))
12187 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12188 (pop org-refile-history)))
12190 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12191 (progn
12192 (setq parent (match-string 1 answ)
12193 child (match-string 2 answ))
12194 (setq parent-target (org-refile--get-location parent tbl))
12195 (when (and parent-target
12196 (or (eq new-nodes t)
12197 (and (eq new-nodes 'confirm)
12198 (y-or-n-p (format "Create new node \"%s\"? "
12199 child)))))
12200 (org-refile-new-child parent-target child)))
12201 (user-error "Invalid target location")))))
12203 (declare-function org-string-nw-p "org-macs" (s))
12204 (defun org-refile-check-position (refile-pointer)
12205 "Check if the refile pointer matches the headline to which it points."
12206 (let* ((file (nth 1 refile-pointer))
12207 (re (nth 2 refile-pointer))
12208 (pos (nth 3 refile-pointer))
12209 buffer)
12210 (if (and (not (markerp pos)) (not file))
12211 (user-error "Please indicate a target file in the refile path")
12212 (when (org-string-nw-p re)
12213 (setq buffer (if (markerp pos)
12214 (marker-buffer pos)
12215 (or (find-buffer-visiting file)
12216 (find-file-noselect file))))
12217 (with-current-buffer buffer
12218 (org-with-wide-buffer
12219 (goto-char pos)
12220 (beginning-of-line 1)
12221 (unless (looking-at-p re)
12222 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12224 (defun org-refile-new-child (parent-target child)
12225 "Use refile target PARENT-TARGET to add new CHILD below it."
12226 (unless parent-target
12227 (error "Cannot find parent for new node"))
12228 (let ((file (nth 1 parent-target))
12229 (pos (nth 3 parent-target))
12230 level)
12231 (with-current-buffer (or (find-buffer-visiting file)
12232 (find-file-noselect file))
12233 (org-with-wide-buffer
12234 (if pos
12235 (goto-char pos)
12236 (goto-char (point-max))
12237 (unless (bolp) (newline)))
12238 (when (looking-at org-outline-regexp)
12239 (setq level (funcall outline-level))
12240 (org-end-of-subtree t t))
12241 (org-back-over-empty-lines)
12242 (insert "\n" (make-string
12243 (if pos (org-get-valid-level level 1) 1) ?*)
12244 " " child "\n")
12245 (beginning-of-line 0)
12246 (list (concat (car parent-target) "/" child) file "" (point))))))
12248 (defun org-olpath-completing-read (prompt collection &rest args)
12249 "Read an outline path like a file name."
12250 (let ((thetable collection))
12251 (apply #'completing-read
12252 prompt
12253 (lambda (string predicate &optional flag)
12254 (cond
12255 ((eq flag nil) (try-completion string thetable))
12256 ((eq flag t)
12257 (let ((l (length string)))
12258 (mapcar (lambda (x)
12259 (let ((r (substring x l))
12260 (f (if (string-match " ([^)]*)$" x)
12261 (match-string 0 x)
12262 "")))
12263 (if (string-match "/" r)
12264 (concat string (substring r 0 (match-end 0)) f)
12265 x)))
12266 (all-completions string thetable predicate))))
12267 ;; Exact match?
12268 ((eq flag 'lambda) (assoc string thetable))))
12269 args)))
12271 ;;;; Dynamic blocks
12273 (defun org-find-dblock (name)
12274 "Find the first dynamic block with name NAME in the buffer.
12275 If not found, stay at current position and return nil."
12276 (let ((case-fold-search t) pos)
12277 (save-excursion
12278 (goto-char (point-min))
12279 (setq pos (and (re-search-forward
12280 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12281 (match-beginning 0))))
12282 (when pos (goto-char pos))
12283 pos))
12285 (defun org-create-dblock (plist)
12286 "Create a dynamic block section, with parameters taken from PLIST.
12287 PLIST must contain a :name entry which is used as the name of the block."
12288 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12289 (end-of-line 1)
12290 (newline))
12291 (let ((col (current-column))
12292 (name (plist-get plist :name)))
12293 (insert "#+BEGIN: " name)
12294 (while plist
12295 (if (eq (car plist) :name)
12296 (setq plist (cddr plist))
12297 (insert " " (prin1-to-string (pop plist)))))
12298 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12299 (beginning-of-line -2)))
12301 (defun org-prepare-dblock ()
12302 "Prepare dynamic block for refresh.
12303 This empties the block, puts the cursor at the insert position and returns
12304 the property list including an extra property :name with the block name."
12305 (unless (looking-at org-dblock-start-re)
12306 (user-error "Not at a dynamic block"))
12307 (let* ((begdel (1+ (match-end 0)))
12308 (name (org-no-properties (match-string 1)))
12309 (params (append (list :name name)
12310 (read (concat "(" (match-string 3) ")")))))
12311 (save-excursion
12312 (beginning-of-line 1)
12313 (skip-chars-forward " \t")
12314 (setq params (plist-put params :indentation-column (current-column))))
12315 (unless (re-search-forward org-dblock-end-re nil t)
12316 (error "Dynamic block not terminated"))
12317 (setq params
12318 (append params
12319 (list :content (buffer-substring
12320 begdel (match-beginning 0)))))
12321 (delete-region begdel (match-beginning 0))
12322 (goto-char begdel)
12323 (open-line 1)
12324 params))
12326 (defun org-map-dblocks (&optional command)
12327 "Apply COMMAND to all dynamic blocks in the current buffer.
12328 If COMMAND is not given, use `org-update-dblock'."
12329 (let ((cmd (or command 'org-update-dblock)))
12330 (save-excursion
12331 (goto-char (point-min))
12332 (while (re-search-forward org-dblock-start-re nil t)
12333 (goto-char (match-beginning 0))
12334 (save-excursion
12335 (condition-case nil
12336 (funcall cmd)
12337 (error (message "Error during update of dynamic block"))))
12338 (unless (re-search-forward org-dblock-end-re nil t)
12339 (error "Dynamic block not terminated"))))))
12341 (defun org-dblock-update (&optional arg)
12342 "User command for updating dynamic blocks.
12343 Update the dynamic block at point. With prefix ARG, update all dynamic
12344 blocks in the buffer."
12345 (interactive "P")
12346 (if arg
12347 (org-update-all-dblocks)
12348 (or (looking-at org-dblock-start-re)
12349 (org-beginning-of-dblock))
12350 (org-update-dblock)))
12352 (defun org-update-dblock ()
12353 "Update the dynamic block at point.
12354 This means to empty the block, parse for parameters and then call
12355 the correct writing function."
12356 (interactive)
12357 (save-excursion
12358 (let* ((win (selected-window))
12359 (pos (point))
12360 (line (org-current-line))
12361 (params (org-prepare-dblock))
12362 (name (plist-get params :name))
12363 (indent (plist-get params :indentation-column))
12364 (cmd (intern (concat "org-dblock-write:" name))))
12365 (message "Updating dynamic block `%s' at line %d..." name line)
12366 (funcall cmd params)
12367 (message "Updating dynamic block `%s' at line %d...done" name line)
12368 (goto-char pos)
12369 (when (and indent (> indent 0))
12370 (setq indent (make-string indent ?\ ))
12371 (save-excursion
12372 (select-window win)
12373 (org-beginning-of-dblock)
12374 (forward-line 1)
12375 (while (not (looking-at org-dblock-end-re))
12376 (insert indent)
12377 (beginning-of-line 2))
12378 (when (looking-at org-dblock-end-re)
12379 (and (looking-at "[ \t]+")
12380 (replace-match ""))
12381 (insert indent)))))))
12383 (defun org-beginning-of-dblock ()
12384 "Find the beginning of the dynamic block at point.
12385 Error if there is no such block at point."
12386 (let ((pos (point))
12387 beg)
12388 (end-of-line 1)
12389 (if (and (re-search-backward org-dblock-start-re nil t)
12390 (setq beg (match-beginning 0))
12391 (re-search-forward org-dblock-end-re nil t)
12392 (> (match-end 0) pos))
12393 (goto-char beg)
12394 (goto-char pos)
12395 (error "Not in a dynamic block"))))
12397 (defun org-update-all-dblocks ()
12398 "Update all dynamic blocks in the buffer.
12399 This function can be used in a hook."
12400 (interactive)
12401 (when (derived-mode-p 'org-mode)
12402 (org-map-dblocks 'org-update-dblock)))
12405 ;;;; Completion
12407 (declare-function org-export-backend-options "ox" (cl-x) t)
12408 (defun org-get-export-keywords ()
12409 "Return a list of all currently understood export keywords.
12410 Export keywords include options, block names, attributes and
12411 keywords relative to each registered export back-end."
12412 (let (keywords)
12413 (dolist (backend
12414 (bound-and-true-p org-export-registered-backends)
12415 (delq nil keywords))
12416 ;; Back-end name (for keywords, like #+LATEX:)
12417 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12418 (dolist (option-entry (org-export-backend-options backend))
12419 ;; Back-end options.
12420 (push (nth 1 option-entry) keywords)))))
12422 (defconst org-options-keywords
12423 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12424 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12425 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12426 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12427 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12429 (defcustom org-structure-template-alist
12430 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12431 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12432 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12433 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12434 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12435 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12436 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12437 ("L" "#+LaTeX: ")
12438 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12439 ("H" "#+HTML: ")
12440 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12441 ("A" "#+ASCII: ")
12442 ("i" "#+INDEX: ?")
12443 ("I" "#+INCLUDE: %file ?"))
12444 "Structure completion elements.
12445 This is a list of abbreviation keys and values. The value gets inserted
12446 if you type `<' followed by the key and then press the completion key,
12447 usually `TAB'. %file will be replaced by a file name after prompting
12448 for the file using completion. The cursor will be placed at the position
12449 of the `?' in the template.
12450 There are two templates for each key, the first uses the original Org syntax,
12451 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12452 the default when the /org-mtags.el/ module has been loaded. See also the
12453 variable `org-mtags-prefer-muse-templates'."
12454 :group 'org-completion
12455 :type '(repeat
12456 (list
12457 (string :tag "Key")
12458 (string :tag "Template")))
12459 :version "25.2"
12460 :package-version '(Org . "8.3"))
12462 (defun org-try-structure-completion ()
12463 "Try to complete a structure template before point.
12464 This looks for strings like \"<e\" on an otherwise empty line and
12465 expands them."
12466 (let ((l (buffer-substring (point-at-bol) (point)))
12468 (when (and (looking-at "[ \t]*$")
12469 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12470 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12471 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12472 (match-beginning 1)) a)
12473 t)))
12475 (defun org-complete-expand-structure-template (start cell)
12476 "Expand a structure template."
12477 (let ((rpl (nth 1 cell))
12478 (ind ""))
12479 (delete-region start (point))
12480 (when (string-match "\\`[ \t]*#\\+" rpl)
12481 (cond
12482 ((bolp))
12483 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12484 (setq ind (buffer-substring (point-at-bol) (point))))
12485 (t (newline))))
12486 (setq start (point))
12487 (when (string-match "%file" rpl)
12488 (setq rpl (replace-match
12489 (concat
12490 "\""
12491 (save-match-data
12492 (abbreviate-file-name (read-file-name "Include file: ")))
12493 "\"")
12494 t t rpl)))
12495 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12496 (concat "\n" ind)))
12497 (insert rpl)
12498 (when (re-search-backward "\\?" start t) (delete-char 1))))
12500 ;;;; TODO, DEADLINE, Comments
12502 (defun org-toggle-comment ()
12503 "Change the COMMENT state of an entry."
12504 (interactive)
12505 (save-excursion
12506 (org-back-to-heading)
12507 (let ((case-fold-search nil))
12508 (looking-at org-complex-heading-regexp))
12509 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12510 (skip-chars-forward " \t")
12511 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12512 (if (org-in-commented-heading-p t)
12513 (delete-region (point)
12514 (progn (search-forward " " (line-end-position) 'move)
12515 (skip-chars-forward " \t")
12516 (point)))
12517 (insert org-comment-string)
12518 (unless (eolp) (insert " ")))))
12520 (defvar org-last-todo-state-is-todo nil
12521 "This is non-nil when the last TODO state change led to a TODO state.
12522 If the last change removed the TODO tag or switched to DONE, then
12523 this is nil.")
12525 (defvar org-setting-tags nil) ; dynamically skipped
12527 (defvar org-todo-setup-filter-hook nil
12528 "Hook for functions that pre-filter todo specs.
12529 Each function takes a todo spec and returns either nil or the spec
12530 transformed into canonical form." )
12532 (defvar org-todo-get-default-hook nil
12533 "Hook for functions that get a default item for todo.
12534 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12535 nil or a string to be used for the todo mark." )
12537 (defvar org-agenda-headline-snapshot-before-repeat)
12539 (defun org-current-effective-time ()
12540 "Return current time adjusted for `org-extend-today-until' variable."
12541 (let* ((ct (org-current-time))
12542 (dct (decode-time ct))
12543 (ct1
12544 (cond
12545 (org-use-last-clock-out-time-as-effective-time
12546 (or (org-clock-get-last-clock-out-time) ct))
12547 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12548 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12549 (t ct))))
12550 ct1))
12552 (defun org-todo-yesterday (&optional arg)
12553 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12554 (interactive "P")
12555 (if (eq major-mode 'org-agenda-mode)
12556 (apply 'org-agenda-todo-yesterday arg)
12557 (let* ((org-use-effective-time t)
12558 (hour (nth 2 (decode-time (org-current-time))))
12559 (org-extend-today-until (1+ hour)))
12560 (org-todo arg))))
12562 (defvar org-block-entry-blocking ""
12563 "First entry preventing the TODO state change.")
12565 (defun org-cancel-repeater ()
12566 "Cancel a repeater by setting its numeric value to zero."
12567 (interactive)
12568 (save-excursion
12569 (org-back-to-heading t)
12570 (let ((bound1 (point))
12571 (bound0 (save-excursion (outline-next-heading) (point))))
12572 (when (and (re-search-forward
12573 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12574 org-deadline-time-regexp "\\)\\|\\("
12575 org-ts-regexp "\\)")
12576 bound0 t)
12577 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12578 bound1 t))
12579 (replace-match "0" t nil nil 1)))))
12581 (defvar org-state) ;; dynamically scoped into this function
12582 (defun org-todo (&optional arg)
12583 "Change the TODO state of an item.
12585 The state of an item is given by a keyword at the start of the heading,
12586 like
12587 *** TODO Write paper
12588 *** DONE Call mom
12590 The different keywords are specified in the variable `org-todo-keywords'.
12591 By default the available states are \"TODO\" and \"DONE\". So, for this
12592 example: when the item starts with TODO, it is changed to DONE.
12593 When it starts with DONE, the DONE is removed. And when neither TODO nor
12594 DONE are present, add TODO at the beginning of the heading.
12596 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12597 state.
12598 With numeric prefix ARG, switch to that state.
12599 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12600 next set of TODO \
12601 keywords (nextset).
12602 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12603 prefix, circumvent any state blocking.
12604 With a numeric prefix arg of 0, inhibit note taking for the change.
12605 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12607 When called through ELisp, arg is also interpreted in the following way:
12608 `none' -> empty state
12609 \"\" -> switch to empty state
12610 `done' -> switch to DONE
12611 `nextset' -> switch to the next set of keywords
12612 `previousset' -> switch to the previous set of keywords
12613 \"WAITING\" -> switch to the specified keyword, but only if it
12614 really is a member of `org-todo-keywords'."
12615 (interactive "P")
12616 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12617 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12618 'region-start-level 'region))
12619 org-loop-over-headlines-in-active-region)
12620 (org-map-entries
12621 `(org-todo ,arg)
12622 org-loop-over-headlines-in-active-region
12623 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12624 (when (equal arg '(16)) (setq arg 'nextset))
12625 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12626 (let ((org-blocker-hook org-blocker-hook)
12627 commentp
12628 case-fold-search)
12629 (when (equal arg '(64))
12630 (setq arg nil org-blocker-hook nil))
12631 (when (and org-blocker-hook
12632 (or org-inhibit-blocking
12633 (org-entry-get nil "NOBLOCKING")))
12634 (setq org-blocker-hook nil))
12635 (save-excursion
12636 (catch 'exit
12637 (org-back-to-heading t)
12638 (when (org-in-commented-heading-p t)
12639 (org-toggle-comment)
12640 (setq commentp t))
12641 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12642 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12643 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12644 (let* ((match-data (match-data))
12645 (startpos (point-at-bol))
12646 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12647 (org-log-done org-log-done)
12648 (org-log-repeat org-log-repeat)
12649 (org-todo-log-states org-todo-log-states)
12650 (org-inhibit-logging
12651 (if (equal arg 0)
12652 (progn (setq arg nil) 'note) org-inhibit-logging))
12653 (this (match-string 1))
12654 (hl-pos (match-beginning 0))
12655 (head (org-get-todo-sequence-head this))
12656 (ass (assoc head org-todo-kwd-alist))
12657 (interpret (nth 1 ass))
12658 (done-word (nth 3 ass))
12659 (final-done-word (nth 4 ass))
12660 (org-last-state (or this ""))
12661 (completion-ignore-case t)
12662 (member (member this org-todo-keywords-1))
12663 (tail (cdr member))
12664 (org-state (cond
12665 ((and org-todo-key-trigger
12666 (or (and (equal arg '(4))
12667 (eq org-use-fast-todo-selection 'prefix))
12668 (and (not arg) org-use-fast-todo-selection
12669 (not (eq org-use-fast-todo-selection
12670 'prefix)))))
12671 ;; Use fast selection
12672 (org-fast-todo-selection))
12673 ((and (equal arg '(4))
12674 (or (not org-use-fast-todo-selection)
12675 (not org-todo-key-trigger)))
12676 ;; Read a state with completion
12677 (completing-read
12678 "State: " (mapcar #'list org-todo-keywords-1)
12679 nil t))
12680 ((eq arg 'right)
12681 (if this
12682 (if tail (car tail) nil)
12683 (car org-todo-keywords-1)))
12684 ((eq arg 'left)
12685 (unless (equal member org-todo-keywords-1)
12686 (if this
12687 (nth (- (length org-todo-keywords-1)
12688 (length tail) 2)
12689 org-todo-keywords-1)
12690 (org-last org-todo-keywords-1))))
12691 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12692 (setq arg nil))) ; hack to fall back to cycling
12693 (arg
12694 ;; user or caller requests a specific state
12695 (cond
12696 ((equal arg "") nil)
12697 ((eq arg 'none) nil)
12698 ((eq arg 'done) (or done-word (car org-done-keywords)))
12699 ((eq arg 'nextset)
12700 (or (car (cdr (member head org-todo-heads)))
12701 (car org-todo-heads)))
12702 ((eq arg 'previousset)
12703 (let ((org-todo-heads (reverse org-todo-heads)))
12704 (or (car (cdr (member head org-todo-heads)))
12705 (car org-todo-heads))))
12706 ((car (member arg org-todo-keywords-1)))
12707 ((stringp arg)
12708 (user-error "State `%s' not valid in this file" arg))
12709 ((nth (1- (prefix-numeric-value arg))
12710 org-todo-keywords-1))))
12711 ((null member) (or head (car org-todo-keywords-1)))
12712 ((equal this final-done-word) nil) ;; -> make empty
12713 ((null tail) nil) ;; -> first entry
12714 ((memq interpret '(type priority))
12715 (if (eq this-command last-command)
12716 (car tail)
12717 (if (> (length tail) 0)
12718 (or done-word (car org-done-keywords))
12719 nil)))
12721 (car tail))))
12722 (org-state (or
12723 (run-hook-with-args-until-success
12724 'org-todo-get-default-hook org-state org-last-state)
12725 org-state))
12726 (next (if org-state (concat " " org-state " ") " "))
12727 (change-plist (list :type 'todo-state-change :from this :to org-state
12728 :position startpos))
12729 dolog now-done-p)
12730 (when org-blocker-hook
12731 (setq org-last-todo-state-is-todo
12732 (not (member this org-done-keywords)))
12733 (unless (save-excursion
12734 (save-match-data
12735 (org-with-wide-buffer
12736 (run-hook-with-args-until-failure
12737 'org-blocker-hook change-plist))))
12738 (if (called-interactively-p 'interactive)
12739 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12740 this org-state org-block-entry-blocking)
12741 ;; fail silently
12742 (message "TODO state change from %s to %s blocked (by \"%s\")"
12743 this org-state org-block-entry-blocking)
12744 (throw 'exit nil))))
12745 (store-match-data match-data)
12746 (replace-match next t t)
12747 (cond ((equal this org-state)
12748 (message "TODO state was already %s" (org-trim next)))
12749 ((pos-visible-in-window-p hl-pos)
12750 (message "TODO state changed to %s" (org-trim next))))
12751 (unless head
12752 (setq head (org-get-todo-sequence-head org-state)
12753 ass (assoc head org-todo-kwd-alist)
12754 interpret (nth 1 ass)
12755 done-word (nth 3 ass)
12756 final-done-word (nth 4 ass)))
12757 (when (memq arg '(nextset previousset))
12758 (message "Keyword-Set %d/%d: %s"
12759 (- (length org-todo-sets) -1
12760 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12761 (length org-todo-sets)
12762 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12763 (setq org-last-todo-state-is-todo
12764 (not (member org-state org-done-keywords)))
12765 (setq now-done-p (and (member org-state org-done-keywords)
12766 (not (member this org-done-keywords))))
12767 (and logging (org-local-logging logging))
12768 (when (and (or org-todo-log-states org-log-done)
12769 (not (eq org-inhibit-logging t))
12770 (not (memq arg '(nextset previousset))))
12771 ;; we need to look at recording a time and note
12772 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12773 (nth 2 (assoc this org-todo-log-states))))
12774 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12775 (setq dolog 'time))
12776 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12777 (and org-state
12778 (member org-state org-not-done-keywords)
12779 (not (member this org-not-done-keywords))))
12780 ;; This is now a todo state and was not one before
12781 ;; If there was a CLOSED time stamp, get rid of it.
12782 (org-add-planning-info nil nil 'closed))
12783 (when (and now-done-p org-log-done)
12784 ;; It is now done, and it was not done before
12785 (org-add-planning-info 'closed (org-current-effective-time))
12786 (when (and (not dolog) (eq 'note org-log-done))
12787 (org-add-log-setup 'done org-state this 'note)))
12788 (when (and org-state dolog)
12789 ;; This is a non-nil state, and we need to log it
12790 (org-add-log-setup 'state org-state this dolog)))
12791 ;; Fixup tag positioning
12792 (org-todo-trigger-tag-changes org-state)
12793 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12794 (when org-provide-todo-statistics
12795 (org-update-parent-todo-statistics))
12796 (run-hooks 'org-after-todo-state-change-hook)
12797 (when (and arg (not (member org-state org-done-keywords)))
12798 (setq head (org-get-todo-sequence-head org-state)))
12799 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12800 ;; Do we need to trigger a repeat?
12801 (when now-done-p
12802 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12803 ;; This is for the agenda, take a snapshot of the headline.
12804 (save-match-data
12805 (setq org-agenda-headline-snapshot-before-repeat
12806 (org-get-heading))))
12807 (org-auto-repeat-maybe org-state))
12808 ;; Fixup cursor location if close to the keyword
12809 (when (and (outline-on-heading-p)
12810 (not (bolp))
12811 (save-excursion (beginning-of-line 1)
12812 (looking-at org-todo-line-regexp))
12813 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12814 (goto-char (or (match-end 2) (match-end 1)))
12815 (and (looking-at " ") (just-one-space)))
12816 (when org-trigger-hook
12817 (save-excursion
12818 (run-hook-with-args 'org-trigger-hook change-plist)))
12819 (when commentp (org-toggle-comment))))))))
12821 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12822 "Block turning an entry into a TODO, using the hierarchy.
12823 This checks whether the current task should be blocked from state
12824 changes. Such blocking occurs when:
12826 1. The task has children which are not all in a completed state.
12828 2. A task has a parent with the property :ORDERED:, and there
12829 are siblings prior to the current task with incomplete
12830 status.
12832 3. The parent of the task is blocked because it has siblings that should
12833 be done first, or is child of a block grandparent TODO entry."
12835 (if (not org-enforce-todo-dependencies)
12836 t ; if locally turned off don't block
12837 (catch 'dont-block
12838 ;; If this is not a todo state change, or if this entry is already DONE,
12839 ;; do not block
12840 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12841 (member (plist-get change-plist :from)
12842 (cons 'done org-done-keywords))
12843 (member (plist-get change-plist :to)
12844 (cons 'todo org-not-done-keywords))
12845 (not (plist-get change-plist :to)))
12846 (throw 'dont-block t))
12847 ;; If this task has children, and any are undone, it's blocked
12848 (save-excursion
12849 (org-back-to-heading t)
12850 (let ((this-level (funcall outline-level)))
12851 (outline-next-heading)
12852 (let ((child-level (funcall outline-level)))
12853 (while (and (not (eobp))
12854 (> child-level this-level))
12855 ;; this todo has children, check whether they are all
12856 ;; completed
12857 (when (and (not (org-entry-is-done-p))
12858 (org-entry-is-todo-p))
12859 (setq org-block-entry-blocking (org-get-heading))
12860 (throw 'dont-block nil))
12861 (outline-next-heading)
12862 (setq child-level (funcall outline-level))))))
12863 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12864 ;; any previous siblings are undone, it's blocked
12865 (save-excursion
12866 (org-back-to-heading t)
12867 (let* ((pos (point))
12868 (parent-pos (and (org-up-heading-safe) (point)))
12869 (case-fold-search nil))
12870 (unless parent-pos (throw 'dont-block t)) ; no parent
12871 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12872 (forward-line 1)
12873 (re-search-forward org-not-done-heading-regexp pos t))
12874 (setq org-block-entry-blocking (match-string 0))
12875 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12876 ;; Search further up the hierarchy, to see if an ancestor is blocked
12877 (while t
12878 (goto-char parent-pos)
12879 (unless (looking-at org-not-done-heading-regexp)
12880 (throw 'dont-block t)) ; do not block, parent is not a TODO
12881 (setq pos (point))
12882 (setq parent-pos (and (org-up-heading-safe) (point)))
12883 (unless parent-pos (throw 'dont-block t)) ; no parent
12884 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12885 (forward-line 1)
12886 (re-search-forward org-not-done-heading-regexp pos t)
12887 (setq org-block-entry-blocking (org-get-heading)))
12888 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12890 (defcustom org-track-ordered-property-with-tag nil
12891 "Should the ORDERED property also be shown as a tag?
12892 The ORDERED property decides if an entry should require subtasks to be
12893 completed in sequence. Since a property is not very visible, setting
12894 this option means that toggling the ORDERED property with the command
12895 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12896 not relevant for the behavior, but it makes things more visible.
12898 Note that toggling the tag with tags commands will not change the property
12899 and therefore not influence behavior!
12901 This can be t, meaning the tag ORDERED should be used, It can also be a
12902 string to select a different tag for this task."
12903 :group 'org-todo
12904 :type '(choice
12905 (const :tag "No tracking" nil)
12906 (const :tag "Track with ORDERED tag" t)
12907 (string :tag "Use other tag")))
12909 (defun org-toggle-ordered-property ()
12910 "Toggle the ORDERED property of the current entry.
12911 For better visibility, you can track the value of this property with a tag.
12912 See variable `org-track-ordered-property-with-tag'."
12913 (interactive)
12914 (let* ((t1 org-track-ordered-property-with-tag)
12915 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12916 (save-excursion
12917 (org-back-to-heading)
12918 (if (org-entry-get nil "ORDERED")
12919 (progn
12920 (org-delete-property "ORDERED")
12921 (and tag (org-toggle-tag tag 'off))
12922 (message "Subtasks can be completed in arbitrary order"))
12923 (org-entry-put nil "ORDERED" "t")
12924 (and tag (org-toggle-tag tag 'on))
12925 (message "Subtasks must be completed in sequence")))))
12927 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12928 (defun org-block-todo-from-checkboxes (change-plist)
12929 "Block turning an entry into a TODO, using checkboxes.
12930 This checks whether the current task should be blocked from state
12931 changes because there are unchecked boxes in this entry."
12932 (if (not org-enforce-todo-checkbox-dependencies)
12933 t ; if locally turned off don't block
12934 (catch 'dont-block
12935 ;; If this is not a todo state change, or if this entry is already DONE,
12936 ;; do not block
12937 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12938 (member (plist-get change-plist :from)
12939 (cons 'done org-done-keywords))
12940 (member (plist-get change-plist :to)
12941 (cons 'todo org-not-done-keywords))
12942 (not (plist-get change-plist :to)))
12943 (throw 'dont-block t))
12944 ;; If this task has checkboxes that are not checked, it's blocked
12945 (save-excursion
12946 (org-back-to-heading t)
12947 (let ((beg (point)) end)
12948 (outline-next-heading)
12949 (setq end (point))
12950 (goto-char beg)
12951 (when (org-list-search-forward
12952 (concat (org-item-beginning-re)
12953 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12954 "\\[[- ]\\]")
12955 end t)
12956 (when (boundp 'org-blocked-by-checkboxes)
12957 (setq org-blocked-by-checkboxes t))
12958 (throw 'dont-block nil))))
12959 t))) ; do not block
12961 (defun org-entry-blocked-p ()
12962 "Non-nil if entry at point is blocked."
12963 (and (not (org-entry-get nil "NOBLOCKING"))
12964 (member (org-entry-get nil "TODO") org-not-done-keywords)
12965 (not (run-hook-with-args-until-failure
12966 'org-blocker-hook
12967 (list :type 'todo-state-change
12968 :position (point)
12969 :from 'todo
12970 :to 'done)))))
12972 (defun org-update-statistics-cookies (all)
12973 "Update the statistics cookie, either from TODO or from checkboxes.
12974 This should be called with the cursor in a line with a statistics
12975 cookie. When called with a \\[universal-argument] prefix, update
12976 all statistics cookies in the buffer."
12977 (interactive "P")
12978 (if all
12979 (progn
12980 (org-update-checkbox-count 'all)
12981 (org-map-entries 'org-update-parent-todo-statistics))
12982 (if (not (org-at-heading-p))
12983 (org-update-checkbox-count)
12984 (let ((pos (point-marker))
12985 end l1 l2)
12986 (ignore-errors (org-back-to-heading t))
12987 (if (not (org-at-heading-p))
12988 (org-update-checkbox-count)
12989 (setq l1 (org-outline-level))
12990 (setq end (save-excursion
12991 (outline-next-heading)
12992 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12993 (point)))
12994 (if (and (save-excursion
12995 (re-search-forward
12996 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12997 (not (save-excursion (re-search-forward
12998 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12999 (org-update-checkbox-count)
13000 (if (and l2 (> l2 l1))
13001 (progn
13002 (goto-char end)
13003 (org-update-parent-todo-statistics))
13004 (goto-char pos)
13005 (beginning-of-line 1)
13006 (while (re-search-forward
13007 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
13008 (point-at-eol) t)
13009 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
13010 (goto-char pos)
13011 (move-marker pos nil)))))
13013 (defvar org-entry-property-inherited-from) ;; defined below
13014 (defun org-update-parent-todo-statistics ()
13015 "Update any statistics cookie in the parent of the current headline.
13016 When `org-hierarchical-todo-statistics' is nil, statistics will cover
13017 the entire subtree and this will travel up the hierarchy and update
13018 statistics everywhere."
13019 (let* ((prop (save-excursion (org-up-heading-safe)
13020 (org-entry-get nil "COOKIE_DATA" 'inherit)))
13021 (recursive (or (not org-hierarchical-todo-statistics)
13022 (and prop (string-match "\\<recursive\\>" prop))))
13023 (lim (or (and prop (marker-position org-entry-property-inherited-from))
13025 (first t)
13026 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
13027 level ltoggle l1 new ndel
13028 (cnt-all 0) (cnt-done 0) is-percent kwd
13029 checkbox-beg cookie-present)
13030 (catch 'exit
13031 (save-excursion
13032 (beginning-of-line 1)
13033 (setq ltoggle (funcall outline-level))
13034 ;; Three situations are to consider:
13036 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
13037 ;; to the top-level ancestor on the headline;
13039 ;; 2. If parent has "recursive" property, repeat up to the
13040 ;; headline setting that property, taking inheritance into
13041 ;; account;
13043 ;; 3. Else, move up to direct parent and proceed only once.
13044 (while (and (setq level (org-up-heading-safe))
13045 (or recursive first)
13046 (>= (point) lim))
13047 (setq first nil cookie-present nil)
13048 (unless (and level
13049 (not (string-match
13050 "\\<checkbox\\>"
13051 (downcase (or (org-entry-get nil "COOKIE_DATA")
13052 "")))))
13053 (throw 'exit nil))
13054 (while (re-search-forward box-re (point-at-eol) t)
13055 (setq cnt-all 0 cnt-done 0 cookie-present t)
13056 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
13057 (save-match-data
13058 (unless (outline-next-heading) (throw 'exit nil))
13059 (while (and (looking-at org-complex-heading-regexp)
13060 (> (setq l1 (length (match-string 1))) level))
13061 (setq kwd (and (or recursive (= l1 ltoggle))
13062 (match-string 2)))
13063 (if (or (eq org-provide-todo-statistics 'all-headlines)
13064 (and (eq org-provide-todo-statistics t)
13065 (or (member kwd org-done-keywords)))
13066 (and (listp org-provide-todo-statistics)
13067 (stringp (car org-provide-todo-statistics))
13068 (or (member kwd org-provide-todo-statistics)
13069 (member kwd org-done-keywords)))
13070 (and (listp org-provide-todo-statistics)
13071 (listp (car org-provide-todo-statistics))
13072 (or (member kwd (car org-provide-todo-statistics))
13073 (and (member kwd org-done-keywords)
13074 (member kwd (cadr org-provide-todo-statistics))))))
13075 (setq cnt-all (1+ cnt-all))
13076 (and (eq org-provide-todo-statistics t)
13078 (setq cnt-all (1+ cnt-all))))
13079 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
13080 (member kwd org-done-keywords))
13081 (and (listp org-provide-todo-statistics)
13082 (listp (car org-provide-todo-statistics))
13083 (member kwd org-done-keywords)
13084 (member kwd (cadr org-provide-todo-statistics)))
13085 (and (listp org-provide-todo-statistics)
13086 (stringp (car org-provide-todo-statistics))
13087 (member kwd org-done-keywords)))
13088 (setq cnt-done (1+ cnt-done)))
13089 (outline-next-heading)))
13090 (setq new
13091 (if is-percent
13092 (format "[%d%%]" (floor (* 100.0 cnt-done)
13093 (max 1 cnt-all)))
13094 (format "[%d/%d]" cnt-done cnt-all))
13095 ndel (- (match-end 0) checkbox-beg))
13096 (goto-char checkbox-beg)
13097 (insert new)
13098 (delete-region (point) (+ (point) ndel))
13099 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
13100 (when cookie-present
13101 (run-hook-with-args 'org-after-todo-statistics-hook
13102 cnt-done (- cnt-all cnt-done))))))
13103 (run-hooks 'org-todo-statistics-hook)))
13105 (defvar org-after-todo-statistics-hook nil
13106 "Hook that is called after a TODO statistics cookie has been updated.
13107 Each function is called with two arguments: the number of not-done entries
13108 and the number of done entries.
13110 For example, the following function, when added to this hook, will switch
13111 an entry to DONE when all children are done, and back to TODO when new
13112 entries are set to a TODO status. Note that this hook is only called
13113 when there is a statistics cookie in the headline!
13115 (defun org-summary-todo (n-done n-not-done)
13116 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13117 (let (org-log-done org-log-states) ; turn off logging
13118 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13121 (defvar org-todo-statistics-hook nil
13122 "Hook that is run whenever Org thinks TODO statistics should be updated.
13123 This hook runs even if there is no statistics cookie present, in which case
13124 `org-after-todo-statistics-hook' would not run.")
13126 (defun org-todo-trigger-tag-changes (state)
13127 "Apply the changes defined in `org-todo-state-tags-triggers'."
13128 (let ((l org-todo-state-tags-triggers)
13129 changes)
13130 (when (or (not state) (equal state ""))
13131 (setq changes (append changes (cdr (assoc "" l)))))
13132 (when (and (stringp state) (> (length state) 0))
13133 (setq changes (append changes (cdr (assoc state l)))))
13134 (when (member state org-not-done-keywords)
13135 (setq changes (append changes (cdr (assq 'todo l)))))
13136 (when (member state org-done-keywords)
13137 (setq changes (append changes (cdr (assq 'done l)))))
13138 (dolist (c changes)
13139 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13141 (defun org-local-logging (value)
13142 "Get logging settings from a property VALUE."
13143 ;; Directly set the variables, they are already local.
13144 (setq org-log-done nil
13145 org-log-repeat nil
13146 org-todo-log-states nil)
13147 (dolist (w (org-split-string value))
13148 (let (a)
13149 (cond
13150 ((setq a (assoc w org-startup-options))
13151 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13152 (set (nth 1 a) (nth 2 a))))
13153 ((setq a (org-extract-log-state-settings w))
13154 (and (member (car a) org-todo-keywords-1)
13155 (push a org-todo-log-states)))))))
13157 (defun org-get-todo-sequence-head (kwd)
13158 "Return the head of the TODO sequence to which KWD belongs.
13159 If KWD is not set, check if there is a text property remembering the
13160 right sequence."
13161 (let (p)
13162 (cond
13163 ((not kwd)
13164 (or (get-text-property (point-at-bol) 'org-todo-head)
13165 (progn
13166 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13167 nil (point-at-eol)))
13168 (get-text-property p 'org-todo-head))))
13169 ((not (member kwd org-todo-keywords-1))
13170 (car org-todo-keywords-1))
13171 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13173 (defun org-fast-todo-selection ()
13174 "Fast TODO keyword selection with single keys.
13175 Returns the new TODO keyword, or nil if no state change should occur."
13176 (let* ((fulltable org-todo-key-alist)
13177 (done-keywords org-done-keywords) ;; needed for the faces.
13178 (maxlen (apply 'max (mapcar
13179 (lambda (x)
13180 (if (stringp (car x)) (string-width (car x)) 0))
13181 fulltable)))
13182 (expert nil)
13183 (fwidth (+ maxlen 3 1 3))
13184 (ncol (/ (- (window-width) 4) fwidth))
13185 tg cnt e c tbl
13186 groups ingroup)
13187 (save-excursion
13188 (save-window-excursion
13189 (if expert
13190 (set-buffer (get-buffer-create " *Org todo*"))
13191 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13192 (erase-buffer)
13193 (setq-local org-done-keywords done-keywords)
13194 (setq tbl fulltable cnt 0)
13195 (while (setq e (pop tbl))
13196 (cond
13197 ((equal e '(:startgroup))
13198 (push '() groups) (setq ingroup t)
13199 (unless (= cnt 0)
13200 (setq cnt 0)
13201 (insert "\n"))
13202 (insert "{ "))
13203 ((equal e '(:endgroup))
13204 (setq ingroup nil cnt 0)
13205 (insert "}\n"))
13206 ((equal e '(:newline))
13207 (unless (= cnt 0)
13208 (setq cnt 0)
13209 (insert "\n")
13210 (setq e (car tbl))
13211 (while (equal (car tbl) '(:newline))
13212 (insert "\n")
13213 (setq tbl (cdr tbl)))))
13215 (setq tg (car e) c (cdr e))
13216 (when ingroup (push tg (car groups)))
13217 (setq tg (org-add-props tg nil 'face
13218 (org-get-todo-face tg)))
13219 (when (and (= cnt 0) (not ingroup)) (insert " "))
13220 (insert "[" c "] " tg (make-string
13221 (- fwidth 4 (length tg)) ?\ ))
13222 (when (= (setq cnt (1+ cnt)) ncol)
13223 (insert "\n")
13224 (when ingroup (insert " "))
13225 (setq cnt 0)))))
13226 (insert "\n")
13227 (goto-char (point-min))
13228 (unless expert (org-fit-window-to-buffer))
13229 (message "[a-z..]:Set [SPC]:clear")
13230 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13231 (cond
13232 ((or (= c ?\C-g)
13233 (and (= c ?q) (not (rassoc c fulltable))))
13234 (setq quit-flag t))
13235 ((= c ?\ ) nil)
13236 ((setq e (rassoc c fulltable) tg (car e))
13238 (t (setq quit-flag t)))))))
13240 (defun org-entry-is-todo-p ()
13241 (member (org-get-todo-state) org-not-done-keywords))
13243 (defun org-entry-is-done-p ()
13244 (member (org-get-todo-state) org-done-keywords))
13246 (defun org-get-todo-state ()
13247 "Return the TODO keyword of the current subtree."
13248 (save-excursion
13249 (org-back-to-heading t)
13250 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13251 (match-end 2)
13252 (match-string 2))))
13254 (defun org-at-date-range-p (&optional inactive-ok)
13255 "Non-nil if point is inside a date range.
13257 When optional argument INACTIVE-OK is non-nil, also consider
13258 inactive time ranges.
13260 When this function returns a non-nil value, match data is set
13261 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13262 on INACTIVE-OK."
13263 (interactive)
13264 (save-excursion
13265 (catch 'exit
13266 (let ((pos (point)))
13267 (skip-chars-backward "^[<\r\n")
13268 (skip-chars-backward "<[")
13269 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13270 (>= (match-end 0) pos)
13271 (throw 'exit t))
13272 (skip-chars-backward "^<[\r\n")
13273 (skip-chars-backward "<[")
13274 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13275 (>= (match-end 0) pos)
13276 (throw 'exit t)))
13277 nil)))
13279 (defun org-get-repeat (&optional tagline)
13280 "Check if there is a deadline/schedule with repeater in this entry."
13281 (save-match-data
13282 (save-excursion
13283 (org-back-to-heading t)
13284 (and (re-search-forward (if tagline
13285 (concat tagline "\\s-*" org-repeat-re)
13286 org-repeat-re)
13287 (org-entry-end-position) t)
13288 (match-string-no-properties 1)))))
13290 (defvar org-last-changed-timestamp)
13291 (defvar org-last-inserted-timestamp)
13292 (defvar org-log-post-message)
13293 (defvar org-log-note-purpose)
13294 (defvar org-log-note-how nil)
13295 (defvar org-log-note-extra)
13296 (defun org-auto-repeat-maybe (done-word)
13297 "Check if the current headline contains a repeated time-stamp.
13299 If yes, set TODO state back to what it was and change the base date
13300 of repeating deadline/scheduled time stamps to new date.
13302 This function is run automatically after each state change to a DONE state."
13303 (let* ((repeat (org-get-repeat))
13304 (aa (assoc org-last-state org-todo-kwd-alist))
13305 (interpret (nth 1 aa))
13306 (head (nth 2 aa))
13307 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13308 (msg "Entry repeats: ")
13309 (org-log-done nil)
13310 (org-todo-log-states nil))
13311 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13312 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13313 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13314 org-todo-repeat-to-state)))
13315 (unless (and to-state (member to-state org-todo-keywords-1))
13316 (setq to-state (if (eq interpret 'type) org-last-state head)))
13317 (org-todo to-state))
13318 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13319 (org-entry-put nil "LAST_REPEAT" (format-time-string
13320 (org-time-stamp-format t t))))
13321 (when org-log-repeat
13322 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13323 (memq 'org-add-log-note post-command-hook))
13324 ;; We are already setup for some record.
13325 (when (eq org-log-repeat 'note)
13326 ;; Make sure we take a note, not only a time stamp.
13327 (setq org-log-note-how 'note))
13328 ;; Set up for taking a record.
13329 (org-add-log-setup 'state
13330 (or done-word (car org-done-keywords))
13331 org-last-state
13332 org-log-repeat)))
13333 (org-back-to-heading t)
13334 (org-add-planning-info nil nil 'closed)
13335 (let ((end (save-excursion (outline-next-heading) (point))))
13336 (while (re-search-forward org-ts-regexp end t)
13337 (when (save-match-data
13338 (or (org-at-planning-p)
13339 (org-at-property-p)
13340 (eq (org-element-type (save-excursion
13341 (backward-char)
13342 (org-element-context)))
13343 'timestamp)))
13344 (let ((type (cond ((match-end 1) org-scheduled-string)
13345 ((match-end 3) org-deadline-string)
13346 (t "Plain:")))
13347 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13348 (cond
13349 ((not
13350 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13351 ;; Time-stamps without a repeater are usually skipped.
13352 ;; However, a SCHEDULED time-stamp without one is
13353 ;; removed, as it is considered as no longer relevant.
13354 (when (equal type org-scheduled-string)
13355 (org-remove-timestamp-with-keyword type)))
13357 (let ((n (string-to-number (match-string 2 ts)))
13358 (what (match-string 3 ts)))
13359 (when (equal what "w") (setq n (* n 7) what "d"))
13360 (when (and (equal what "h")
13361 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13362 ts)))
13363 (user-error
13364 "Cannot repeat in Repeat in %d hour(s) because no hour \
13365 has been set"
13367 ;; Preparation, see if we need to modify the start
13368 ;; date for the change.
13369 (when (match-end 1)
13370 (let ((time (save-match-data (org-time-string-to-time ts))))
13371 (cond
13372 ((equal (match-string 1 ts) ".")
13373 ;; Shift starting date to today
13374 (org-timestamp-change
13375 (- (org-today) (time-to-days time))
13376 'day))
13377 ((equal (match-string 1 ts) "+")
13378 (let ((nshiftmax 10)
13379 (nshift 0))
13380 (while (or (= nshift 0)
13381 (not (time-less-p (current-time) time)))
13382 (when (= (cl-incf nshift) nshiftmax)
13383 (or (y-or-n-p
13384 (format "%d repeater intervals were not \
13385 enough to shift date past today. Continue? "
13386 nshift))
13387 (user-error "Abort")))
13388 (org-timestamp-change n (cdr (assoc what whata)))
13389 (org-at-timestamp-p t)
13390 (setq ts (match-string 1))
13391 (setq time
13392 (save-match-data
13393 (org-time-string-to-time ts)))))
13394 (org-timestamp-change (- n) (cdr (assoc what whata)))
13395 ;; Rematch, so that we have everything in
13396 ;; place for the real shift.
13397 (org-at-timestamp-p t)
13398 (setq ts (match-string 1))
13399 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13400 ts)))))
13401 (save-excursion
13402 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13403 (setq msg
13404 (concat
13405 msg type " " org-last-changed-timestamp " ")))))))))
13406 (setq org-log-post-message msg)
13407 (message "%s" msg))))
13409 (defun org-show-todo-tree (arg)
13410 "Make a compact tree which shows all headlines marked with TODO.
13411 The tree will show the lines where the regexp matches, and all higher
13412 headlines above the match.
13413 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13414 With a numeric prefix N, construct a sparse tree for the Nth element
13415 of `org-todo-keywords-1'."
13416 (interactive "P")
13417 (let ((case-fold-search nil)
13418 (kwd-re
13419 (cond ((null arg) org-not-done-regexp)
13420 ((equal arg '(4))
13421 (let ((kwd
13422 (completing-read "Keyword (or KWD1|KWD2|...): "
13423 (mapcar #'list org-todo-keywords-1))))
13424 (concat "\\("
13425 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13426 "\\)\\>")))
13427 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13428 (regexp-quote (nth (1- (prefix-numeric-value arg))
13429 org-todo-keywords-1)))
13430 (t (user-error "Invalid prefix argument: %s" arg)))))
13431 (message "%d TODO entries found"
13432 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13434 (defun org-deadline (arg &optional time)
13435 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13436 With one universal prefix argument, remove any deadline from the item.
13437 With two universal prefix arguments, prompt for a warning delay.
13438 With argument TIME, set the deadline at the corresponding date. TIME
13439 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13440 (interactive "P")
13441 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13442 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13443 'region-start-level 'region))
13444 org-loop-over-headlines-in-active-region)
13445 (org-map-entries
13446 `(org-deadline ',arg ,time)
13447 org-loop-over-headlines-in-active-region
13448 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13449 (let* ((old-date (org-entry-get nil "DEADLINE"))
13450 (old-date-time (when old-date (org-time-string-to-time old-date)))
13451 (repeater (and old-date
13452 (string-match
13453 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13454 old-date)
13455 (match-string 1 old-date))))
13456 (cond
13457 ((equal arg '(4))
13458 (when (and old-date org-log-redeadline)
13459 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13460 (org-remove-timestamp-with-keyword org-deadline-string)
13461 (message "Item no longer has a deadline."))
13462 ((equal arg '(16))
13463 (save-excursion
13464 (org-back-to-heading t)
13465 (if (re-search-forward
13466 org-deadline-time-regexp
13467 (save-excursion (outline-next-heading) (point)) t)
13468 (let* ((rpl0 (match-string 1))
13469 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13470 (replace-match
13471 (concat org-deadline-string
13472 " <" rpl
13473 (format " -%dd"
13474 (abs
13475 (- (time-to-days
13476 (save-match-data
13477 (org-read-date nil t nil "Warn starting from" old-date-time)))
13478 (time-to-days old-date-time))))
13479 ">") t t))
13480 (user-error "No deadline information to update"))))
13482 (org-add-planning-info 'deadline time 'closed)
13483 (when (and old-date
13484 org-log-redeadline
13485 (not (equal old-date org-last-inserted-timestamp)))
13486 (org-add-log-setup
13487 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13488 (when repeater
13489 (save-excursion
13490 (org-back-to-heading t)
13491 (when (re-search-forward (concat org-deadline-string " "
13492 org-last-inserted-timestamp)
13493 (save-excursion
13494 (outline-next-heading) (point)) t)
13495 (goto-char (1- (match-end 0)))
13496 (insert " " repeater)
13497 (setq org-last-inserted-timestamp
13498 (concat (substring org-last-inserted-timestamp 0 -1)
13499 " " repeater
13500 (substring org-last-inserted-timestamp -1))))))
13501 (message "Deadline on %s" org-last-inserted-timestamp))))))
13503 (defun org-schedule (arg &optional time)
13504 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13505 With one universal prefix argument, remove any scheduling date from the item.
13506 With two universal prefix arguments, prompt for a delay cookie.
13507 With argument TIME, scheduled at the corresponding date. TIME can
13508 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13509 (interactive "P")
13510 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13511 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13512 'region-start-level 'region))
13513 org-loop-over-headlines-in-active-region)
13514 (org-map-entries
13515 `(org-schedule ',arg ,time)
13516 org-loop-over-headlines-in-active-region
13517 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13518 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13519 (old-date-time (when old-date (org-time-string-to-time old-date)))
13520 (repeater (and old-date
13521 (string-match
13522 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13523 old-date)
13524 (match-string 1 old-date))))
13525 (cond
13526 ((equal arg '(4))
13527 (progn
13528 (when (and old-date org-log-reschedule)
13529 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13530 (org-remove-timestamp-with-keyword org-scheduled-string)
13531 (message "Item is no longer scheduled.")))
13532 ((equal arg '(16))
13533 (save-excursion
13534 (org-back-to-heading t)
13535 (if (re-search-forward
13536 org-scheduled-time-regexp
13537 (save-excursion (outline-next-heading) (point)) t)
13538 (let* ((rpl0 (match-string 1))
13539 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13540 (replace-match
13541 (concat org-scheduled-string
13542 " <" rpl
13543 (format " -%dd"
13544 (abs
13545 (- (time-to-days
13546 (save-match-data
13547 (org-read-date nil t nil "Delay until" old-date-time)))
13548 (time-to-days old-date-time))))
13549 ">") t t))
13550 (user-error "No scheduled information to update"))))
13552 (org-add-planning-info 'scheduled time 'closed)
13553 (when (and old-date
13554 org-log-reschedule
13555 (not (equal old-date org-last-inserted-timestamp)))
13556 (org-add-log-setup
13557 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13558 (when repeater
13559 (save-excursion
13560 (org-back-to-heading t)
13561 (when (re-search-forward (concat org-scheduled-string " "
13562 org-last-inserted-timestamp)
13563 (save-excursion
13564 (outline-next-heading) (point)) t)
13565 (goto-char (1- (match-end 0)))
13566 (insert " " repeater)
13567 (setq org-last-inserted-timestamp
13568 (concat (substring org-last-inserted-timestamp 0 -1)
13569 " " repeater
13570 (substring org-last-inserted-timestamp -1))))))
13571 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13573 (defun org-get-scheduled-time (pom &optional inherit)
13574 "Get the scheduled time as a time tuple, of a format suitable
13575 for calling org-schedule with, or if there is no scheduling,
13576 returns nil."
13577 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13578 (when time
13579 (apply 'encode-time (org-parse-time-string time)))))
13581 (defun org-get-deadline-time (pom &optional inherit)
13582 "Get the deadline as a time tuple, of a format suitable for
13583 calling org-deadline with, or if there is no scheduling, returns
13584 nil."
13585 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13586 (when time
13587 (apply 'encode-time (org-parse-time-string time)))))
13589 (defun org-remove-timestamp-with-keyword (keyword)
13590 "Remove all time stamps with KEYWORD in the current entry."
13591 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13592 beg)
13593 (save-excursion
13594 (org-back-to-heading t)
13595 (setq beg (point))
13596 (outline-next-heading)
13597 (while (re-search-backward re beg t)
13598 (replace-match "")
13599 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13600 (equal (char-before) ?\ ))
13601 (backward-delete-char 1)
13602 (when (string-match "^[ \t]*$" (buffer-substring
13603 (point-at-bol) (point-at-eol)))
13604 (delete-region (point-at-bol)
13605 (min (point-max) (1+ (point-at-eol))))))))))
13607 (defvar org-time-was-given) ; dynamically scoped parameter
13608 (defvar org-end-time-was-given) ; dynamically scoped parameter
13610 (defun org-at-planning-p ()
13611 "Non-nil when point is on a planning info line."
13612 ;; This is as accurate and faster than `org-element-at-point' since
13613 ;; planning info location is fixed in the section.
13614 (org-with-wide-buffer
13615 (beginning-of-line)
13616 (and (looking-at-p org-planning-line-re)
13617 (eq (point)
13618 (ignore-errors
13619 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13620 (org-back-to-heading t)
13621 (org-with-limited-levels (org-back-to-heading t)))
13622 (line-beginning-position 2))))))
13624 (defun org-add-planning-info (what &optional time &rest remove)
13625 "Insert new timestamp with keyword in the planning line.
13626 WHAT indicates what kind of time stamp to add. It is a symbol
13627 among `closed', `deadline', `scheduled' and nil. TIME indicates
13628 the time to use. If none is given, the user is prompted for
13629 a date. REMOVE indicates what kind of entries to remove. An old
13630 WHAT entry will also be removed."
13631 (let (org-time-was-given org-end-time-was-given default-time default-input)
13632 (catch 'exit
13633 (when (and (memq what '(scheduled deadline))
13634 (or (not time)
13635 (and (stringp time)
13636 (string-match "^[-+]+[0-9]" time))))
13637 ;; Try to get a default date/time from existing timestamp
13638 (save-excursion
13639 (org-back-to-heading t)
13640 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13641 (when (re-search-forward (if (eq what 'scheduled)
13642 org-scheduled-time-regexp
13643 org-deadline-time-regexp)
13644 end t)
13645 (setq ts (match-string 1)
13646 default-time (apply 'encode-time (org-parse-time-string ts))
13647 default-input (and ts (org-get-compact-tod ts)))))))
13648 (when what
13649 (setq time
13650 (if (stringp time)
13651 ;; This is a string (relative or absolute), set
13652 ;; proper date.
13653 (apply #'encode-time
13654 (org-read-date-analyze
13655 time default-time (decode-time default-time)))
13656 ;; If necessary, get the time from the user
13657 (or time (org-read-date nil 'to-time nil nil
13658 default-time default-input)))))
13660 (org-with-wide-buffer
13661 (org-back-to-heading t)
13662 (forward-line)
13663 (unless (bolp) (insert "\n"))
13664 (cond ((looking-at-p org-planning-line-re)
13665 ;; Move to current indentation.
13666 (skip-chars-forward " \t")
13667 ;; Check if we have to remove something.
13668 (dolist (type (if what (cons what remove) remove))
13669 (save-excursion
13670 (when (re-search-forward
13671 (cl-case type
13672 (closed org-closed-time-regexp)
13673 (deadline org-deadline-time-regexp)
13674 (scheduled org-scheduled-time-regexp)
13675 (otherwise
13676 (error "Invalid planning type: %s" type)))
13677 (line-end-position) t)
13678 ;; Delete until next keyword or end of line.
13679 (delete-region
13680 (match-beginning 0)
13681 (if (re-search-forward org-keyword-time-not-clock-regexp
13682 (line-end-position)
13684 (match-beginning 0)
13685 (line-end-position))))))
13686 ;; If there is nothing more to add and no more keyword
13687 ;; is left, remove the line completely.
13688 (if (and (looking-at-p "[ \t]*$") (not what))
13689 (delete-region (line-beginning-position)
13690 (line-beginning-position 2))
13691 ;; If we removed last keyword, do not leave trailing
13692 ;; white space at the end of line.
13693 (let ((p (point)))
13694 (save-excursion
13695 (end-of-line)
13696 (unless (= (skip-chars-backward " \t" p) 0)
13697 (delete-region (point) (line-end-position)))))))
13698 ((not what) (throw 'exit nil)) ; Nothing to do.
13699 (t (insert-before-markers "\n")
13700 (backward-char 1)
13701 (when org-adapt-indentation
13702 (indent-to-column (1+ (org-outline-level))))))
13703 (when what
13704 ;; Insert planning keyword.
13705 (insert (cl-case what
13706 (closed org-closed-string)
13707 (deadline org-deadline-string)
13708 (scheduled org-scheduled-string)
13709 (otherwise (error "Invalid planning type: %s" what)))
13710 " ")
13711 ;; Insert associated timestamp.
13712 (let ((ts (org-insert-time-stamp
13713 time
13714 (or org-time-was-given
13715 (and (eq what 'closed) org-log-done-with-time))
13716 (eq what 'closed)
13717 nil nil (list org-end-time-was-given))))
13718 (unless (eolp) (insert " "))
13719 ts))))))
13721 (defvar org-log-note-marker (make-marker)
13722 "Marker pointing at the entry where the note is to be inserted.")
13723 (defvar org-log-note-purpose nil)
13724 (defvar org-log-note-state nil)
13725 (defvar org-log-note-previous-state nil)
13726 (defvar org-log-note-extra nil)
13727 (defvar org-log-note-window-configuration nil)
13728 (defvar org-log-note-return-to (make-marker))
13729 (defvar org-log-note-effective-time nil
13730 "Remembered current time so that dynamically scoped
13731 `org-extend-today-until' affects timestamps in state change log")
13733 (defvar org-log-post-message nil
13734 "Message to be displayed after a log note has been stored.
13735 The auto-repeater uses this.")
13737 (defun org-add-note ()
13738 "Add a note to the current entry.
13739 This is done in the same way as adding a state change note."
13740 (interactive)
13741 (org-add-log-setup 'note))
13743 (defun org-log-beginning (&optional create)
13744 "Return expected start of log notes in current entry.
13745 When optional argument CREATE is non-nil, the function creates
13746 a drawer to store notes, if necessary. Returned position ignores
13747 narrowing."
13748 (org-with-wide-buffer
13749 (let ((drawer (org-log-into-drawer)))
13750 (cond
13751 (drawer
13752 (org-end-of-meta-data)
13753 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13754 (end (if (org-at-heading-p) (point)
13755 (save-excursion (outline-next-heading) (point))))
13756 (case-fold-search t))
13757 (catch 'exit
13758 ;; Try to find existing drawer.
13759 (while (re-search-forward regexp end t)
13760 (let ((element (org-element-at-point)))
13761 (when (eq (org-element-type element) 'drawer)
13762 (let ((cend (org-element-property :contents-end element)))
13763 (when (and (not org-log-states-order-reversed) cend)
13764 (goto-char cend)))
13765 (throw 'exit nil))))
13766 ;; No drawer found. Create one, if permitted.
13767 (when create
13768 (unless (bolp) (insert "\n"))
13769 (let ((beg (point)))
13770 (insert ":" drawer ":\n:END:\n")
13771 (org-indent-region beg (point)))
13772 (end-of-line -1)))))
13774 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13775 (skip-chars-forward " \t\n")
13776 (beginning-of-line)
13777 (unless org-log-states-order-reversed
13778 (org-skip-over-state-notes)
13779 (skip-chars-backward " \t\n")
13780 (forward-line)))))
13781 (if (bolp) (point) (line-beginning-position 2))))
13783 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13784 "Set up the post command hook to take a note.
13785 If this is about to TODO state change, the new state is expected in STATE.
13786 HOW is an indicator what kind of note should be created.
13787 EXTRA is additional text that will be inserted into the notes buffer."
13788 (move-marker org-log-note-marker (point))
13789 (setq org-log-note-purpose purpose
13790 org-log-note-state state
13791 org-log-note-previous-state prev-state
13792 org-log-note-how how
13793 org-log-note-extra extra
13794 org-log-note-effective-time (org-current-effective-time))
13795 (add-hook 'post-command-hook 'org-add-log-note 'append))
13797 (defun org-skip-over-state-notes ()
13798 "Skip past the list of State notes in an entry."
13799 (when (ignore-errors (goto-char (org-in-item-p)))
13800 (let* ((struct (org-list-struct))
13801 (prevs (org-list-prevs-alist struct))
13802 (regexp
13803 (concat "[ \t]*- +"
13804 (replace-regexp-in-string
13805 " +" " +"
13806 (org-replace-escapes
13807 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13808 `(("%d" . ,org-ts-regexp-inactive)
13809 ("%D" . ,org-ts-regexp)
13810 ("%s" . "\"\\S-+\"")
13811 ("%S" . "\"\\S-+\"")
13812 ("%t" . ,org-ts-regexp-inactive)
13813 ("%T" . ,org-ts-regexp)
13814 ("%u" . ".*?")
13815 ("%U" . ".*?")))))))
13816 (while (looking-at-p regexp)
13817 (goto-char (or (org-list-get-next-item (point) struct prevs)
13818 (org-list-get-item-end (point) struct)))))))
13820 (defun org-add-log-note (&optional _purpose)
13821 "Pop up a window for taking a note, and add this note later."
13822 (remove-hook 'post-command-hook 'org-add-log-note)
13823 (setq org-log-note-window-configuration (current-window-configuration))
13824 (delete-other-windows)
13825 (move-marker org-log-note-return-to (point))
13826 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13827 (goto-char org-log-note-marker)
13828 (org-switch-to-buffer-other-window "*Org Note*")
13829 (erase-buffer)
13830 (if (memq org-log-note-how '(time state))
13831 (let (current-prefix-arg) (org-store-log-note))
13832 (let ((org-inhibit-startup t)) (org-mode))
13833 (insert (format "# Insert note for %s.
13834 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13835 (cond
13836 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13837 ((eq org-log-note-purpose 'done) "closed todo item")
13838 ((eq org-log-note-purpose 'state)
13839 (format "state change from \"%s\" to \"%s\""
13840 (or org-log-note-previous-state "")
13841 (or org-log-note-state "")))
13842 ((eq org-log-note-purpose 'reschedule)
13843 "rescheduling")
13844 ((eq org-log-note-purpose 'delschedule)
13845 "no longer scheduled")
13846 ((eq org-log-note-purpose 'redeadline)
13847 "changing deadline")
13848 ((eq org-log-note-purpose 'deldeadline)
13849 "removing deadline")
13850 ((eq org-log-note-purpose 'refile)
13851 "refiling")
13852 ((eq org-log-note-purpose 'note)
13853 "this entry")
13854 (t (error "This should not happen")))))
13855 (when org-log-note-extra (insert org-log-note-extra))
13856 (setq-local org-finish-function 'org-store-log-note)
13857 (run-hooks 'org-log-buffer-setup-hook)))
13859 (defvar org-note-abort nil) ; dynamically scoped
13860 (defun org-store-log-note ()
13861 "Finish taking a log note, and insert it to where it belongs."
13862 (let ((txt (prog1 (buffer-string)
13863 (kill-buffer)))
13864 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13865 lines)
13866 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13867 (setq txt (replace-match "" t t txt)))
13868 (when (string-match "\\s-+\\'" txt)
13869 (setq txt (replace-match "" t t txt)))
13870 (setq lines (org-split-string txt "\n"))
13871 (when (org-string-nw-p note)
13872 (setq note
13873 (org-replace-escapes
13874 note
13875 (list (cons "%u" (user-login-name))
13876 (cons "%U" user-full-name)
13877 (cons "%t" (format-time-string
13878 (org-time-stamp-format 'long 'inactive)
13879 org-log-note-effective-time))
13880 (cons "%T" (format-time-string
13881 (org-time-stamp-format 'long nil)
13882 org-log-note-effective-time))
13883 (cons "%d" (format-time-string
13884 (org-time-stamp-format nil 'inactive)
13885 org-log-note-effective-time))
13886 (cons "%D" (format-time-string
13887 (org-time-stamp-format nil nil)
13888 org-log-note-effective-time))
13889 (cons "%s" (cond
13890 ((not org-log-note-state) "")
13891 ((string-match-p org-ts-regexp
13892 org-log-note-state)
13893 (format "\"[%s]\""
13894 (substring org-log-note-state 1 -1)))
13895 (t (format "\"%s\"" org-log-note-state))))
13896 (cons "%S"
13897 (cond
13898 ((not org-log-note-previous-state) "")
13899 ((string-match-p org-ts-regexp
13900 org-log-note-previous-state)
13901 (format "\"[%s]\""
13902 (substring
13903 org-log-note-previous-state 1 -1)))
13904 (t (format "\"%s\""
13905 org-log-note-previous-state)))))))
13906 (when lines (setq note (concat note " \\\\")))
13907 (push note lines))
13908 (when (and lines (not (or current-prefix-arg org-note-abort)))
13909 (with-current-buffer (marker-buffer org-log-note-marker)
13910 (org-with-wide-buffer
13911 ;; Find location for the new note.
13912 (goto-char org-log-note-marker)
13913 (set-marker org-log-note-marker nil)
13914 (goto-char (org-log-beginning t))
13915 ;; Make sure point is at the beginning of an empty line.
13916 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13917 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13918 ;; In an existing list, add a new item at the top level.
13919 ;; Otherwise, indent line like a regular one.
13920 (let ((itemp (org-in-item-p)))
13921 (if itemp
13922 (indent-line-to
13923 (let ((struct (save-excursion
13924 (goto-char itemp) (org-list-struct))))
13925 (org-list-get-ind (org-list-get-top-point struct) struct)))
13926 (org-indent-line)))
13927 (insert (org-list-bullet-string "-") (pop lines))
13928 (let ((ind (org-list-item-body-column (line-beginning-position))))
13929 (dolist (line lines)
13930 (insert "\n")
13931 (indent-line-to ind)
13932 (insert line)))
13933 (message "Note stored")
13934 (org-back-to-heading t)
13935 (org-cycle-hide-drawers 'children))
13936 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13937 ;; from within `org-add-log-note' because `buffer-undo-list'
13938 ;; is then modified outside of `org-with-remote-undo'.
13939 (when (eq this-command 'org-agenda-todo)
13940 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13941 ;; Don't add undo information when called from `org-agenda-todo'.
13942 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13943 (set-window-configuration org-log-note-window-configuration)
13944 (with-current-buffer (marker-buffer org-log-note-return-to)
13945 (goto-char org-log-note-return-to))
13946 (move-marker org-log-note-return-to nil)
13947 (when org-log-post-message (message "%s" org-log-post-message))))
13949 (defun org-remove-empty-drawer-at (pos)
13950 "Remove an empty drawer at position POS.
13951 POS may also be a marker."
13952 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13953 (org-with-wide-buffer
13954 (goto-char pos)
13955 (let ((drawer (org-element-at-point)))
13956 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13957 (not (org-element-property :contents-begin drawer)))
13958 (delete-region (org-element-property :begin drawer)
13959 (progn (goto-char (org-element-property :end drawer))
13960 (skip-chars-backward " \r\t\n")
13961 (forward-line)
13962 (point))))))))
13964 (defvar org-ts-type nil)
13965 (defun org-sparse-tree (&optional arg type)
13966 "Create a sparse tree, prompt for the details.
13967 This command can create sparse trees. You first need to select the type
13968 of match used to create the tree:
13970 t Show all TODO entries.
13971 T Show entries with a specific TODO keyword.
13972 m Show entries selected by a tags/property match.
13973 p Enter a property name and its value (both with completion on existing
13974 names/values) and show entries with that property.
13975 r Show entries matching a regular expression (`/' can be used as well).
13976 b Show deadlines and scheduled items before a date.
13977 a Show deadlines and scheduled items after a date.
13978 d Show deadlines due within `org-deadline-warning-days'.
13979 D Show deadlines and scheduled items between a date range."
13980 (interactive "P")
13981 (setq type (or type org-sparse-tree-default-date-type))
13982 (setq org-ts-type type)
13983 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13984 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13985 \[c]ycle through date types: %s"
13986 (cl-case type
13987 (all "all timestamps")
13988 (scheduled "only scheduled")
13989 (deadline "only deadline")
13990 (active "only active timestamps")
13991 (inactive "only inactive timestamps")
13992 (closed "with a closed time-stamp")
13993 (otherwise "scheduled/deadline")))
13994 (let ((answer (read-char-exclusive)))
13995 (cl-case answer
13997 (org-sparse-tree
13999 (cadr
14000 (memq type '(nil all scheduled deadline active inactive closed)))))
14001 (?d (call-interactively 'org-check-deadlines))
14002 (?b (call-interactively 'org-check-before-date))
14003 (?a (call-interactively 'org-check-after-date))
14004 (?D (call-interactively 'org-check-dates-range))
14005 (?t (call-interactively 'org-show-todo-tree))
14006 (?T (org-show-todo-tree '(4)))
14007 (?m (call-interactively 'org-match-sparse-tree))
14008 ((?p ?P)
14009 (let* ((kwd (completing-read
14010 "Property: " (mapcar #'list (org-buffer-property-keys))))
14011 (value (completing-read
14012 "Value: " (mapcar #'list (org-property-values kwd)))))
14013 (unless (string-match "\\`{.*}\\'" value)
14014 (setq value (concat "\"" value "\"")))
14015 (org-match-sparse-tree arg (concat kwd "=" value))))
14016 ((?r ?R ?/) (call-interactively 'org-occur))
14017 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
14019 (defvar-local org-occur-highlights nil
14020 "List of overlays used for occur matches.")
14021 (defvar-local org-occur-parameters nil
14022 "Parameters of the active org-occur calls.
14023 This is a list, each call to org-occur pushes as cons cell,
14024 containing the regular expression and the callback, onto the list.
14025 The list can contain several entries if `org-occur' has been called
14026 several time with the KEEP-PREVIOUS argument. Otherwise, this list
14027 will only contain one set of parameters. When the highlights are
14028 removed (for example with `C-c C-c', or with the next edit (depending
14029 on `org-remove-highlights-with-change'), this variable is emptied
14030 as well.")
14032 (defun org-occur (regexp &optional keep-previous callback)
14033 "Make a compact tree which shows all matches of REGEXP.
14035 The tree will show the lines where the regexp matches, and any other context
14036 defined in `org-show-context-detail', which see.
14038 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
14039 done by a previous call to `org-occur' will be kept, to allow stacking of
14040 calls to this command.
14042 Optional argument CALLBACK can be a function of no argument. In this case,
14043 it is called with point at the end of the match, match data being set
14044 accordingly. Current match is shown only if the return value is non-nil.
14045 The function must neither move point nor alter narrowing."
14046 (interactive "sRegexp: \nP")
14047 (when (equal regexp "")
14048 (user-error "Regexp cannot be empty"))
14049 (unless keep-previous
14050 (org-remove-occur-highlights nil nil t))
14051 (push (cons regexp callback) org-occur-parameters)
14052 (let ((cnt 0))
14053 (save-excursion
14054 (goto-char (point-min))
14055 (when (or (not keep-previous) ; do not want to keep
14056 (not org-occur-highlights)) ; no previous matches
14057 ;; hide everything
14058 (org-overview))
14059 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
14060 (isearch-no-upper-case-p regexp t)
14061 org-occur-case-fold-search)))
14062 (while (re-search-forward regexp nil t)
14063 (when (or (not callback)
14064 (save-match-data (funcall callback)))
14065 (setq cnt (1+ cnt))
14066 (when org-highlight-sparse-tree-matches
14067 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14068 (org-show-context 'occur-tree)))))
14069 (when org-remove-highlights-with-change
14070 (add-hook 'before-change-functions 'org-remove-occur-highlights
14071 nil 'local))
14072 (unless org-sparse-tree-open-archived-trees
14073 (org-hide-archived-subtrees (point-min) (point-max)))
14074 (run-hooks 'org-occur-hook)
14075 (when (called-interactively-p 'interactive)
14076 (message "%d match(es) for regexp %s" cnt regexp))
14077 cnt))
14079 (defun org-occur-next-match (&optional n _reset)
14080 "Function for `next-error-function' to find sparse tree matches.
14081 N is the number of matches to move, when negative move backwards.
14082 This function always goes back to the starting point when no
14083 match is found."
14084 (let* ((limit (if (< n 0) (point-min) (point-max)))
14085 (search-func (if (< n 0)
14086 'previous-single-char-property-change
14087 'next-single-char-property-change))
14088 (n (abs n))
14089 (pos (point))
14091 (catch 'exit
14092 (while (setq p1 (funcall search-func (point) 'org-type))
14093 (when (equal p1 limit)
14094 (goto-char pos)
14095 (user-error "No more matches"))
14096 (when (equal (get-char-property p1 'org-type) 'org-occur)
14097 (setq n (1- n))
14098 (when (= n 0)
14099 (goto-char p1)
14100 (throw 'exit (point))))
14101 (goto-char p1))
14102 (goto-char p1)
14103 (user-error "No more matches"))))
14105 (defun org-show-context (&optional key)
14106 "Make sure point and context are visible.
14107 Optional argument KEY, when non-nil, is a symbol. See
14108 `org-show-context-detail' for allowed values and how much is to
14109 be shown."
14110 (org-show-set-visibility
14111 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14112 ((cdr (assq key org-show-context-detail)))
14113 (t (cdr (assq 'default org-show-context-detail))))))
14115 (defun org-show-set-visibility (detail)
14116 "Set visibility around point according to DETAIL.
14117 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14118 `tree', `canonical' or t. See `org-show-context-detail' for more
14119 information."
14120 ;; Show current heading and possibly its entry, following headline
14121 ;; or all children.
14122 (if (and (org-at-heading-p) (not (eq detail 'local)))
14123 (org-flag-heading nil)
14124 (org-show-entry)
14125 ;; If point is hidden within a drawer or a block, make sure to
14126 ;; expose it.
14127 (dolist (o (overlays-at (point)))
14128 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14129 (delete-overlay o)))
14130 (unless (org-before-first-heading-p)
14131 (org-with-limited-levels
14132 (cl-case detail
14133 ((tree canonical t) (org-show-children))
14134 ((nil minimal ancestors))
14135 (t (save-excursion
14136 (outline-next-heading)
14137 (org-flag-heading nil)))))))
14138 ;; Show all siblings.
14139 (when (eq detail 'lineage) (org-show-siblings))
14140 ;; Show ancestors, possibly with their children.
14141 (when (memq detail '(ancestors lineage tree canonical t))
14142 (save-excursion
14143 (while (org-up-heading-safe)
14144 (org-flag-heading nil)
14145 (when (memq detail '(canonical t)) (org-show-entry))
14146 (when (memq detail '(tree canonical t)) (org-show-children))))))
14148 (defvar org-reveal-start-hook nil
14149 "Hook run before revealing a location.")
14151 (defun org-reveal (&optional siblings)
14152 "Show current entry, hierarchy above it, and the following headline.
14154 This can be used to show a consistent set of context around
14155 locations exposed with `org-show-context'.
14157 With optional argument SIBLINGS, on each level of the hierarchy all
14158 siblings are shown. This repairs the tree structure to what it would
14159 look like when opened with hierarchical calls to `org-cycle'.
14161 With a \\[universal-argument] \\[universal-argument] prefix, \
14162 go to the parent and show the entire tree."
14163 (interactive "P")
14164 (run-hooks 'org-reveal-start-hook)
14165 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14166 ((equal siblings '(16))
14167 (save-excursion
14168 (when (org-up-heading-safe)
14169 (org-show-subtree)
14170 (run-hook-with-args 'org-cycle-hook 'subtree))))
14171 (t (org-show-set-visibility 'lineage))))
14173 (defun org-highlight-new-match (beg end)
14174 "Highlight from BEG to END and mark the highlight is an occur headline."
14175 (let ((ov (make-overlay beg end)))
14176 (overlay-put ov 'face 'secondary-selection)
14177 (overlay-put ov 'org-type 'org-occur)
14178 (push ov org-occur-highlights)))
14180 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14181 "Remove the occur highlights from the buffer.
14182 BEG and END are ignored. If NOREMOVE is nil, remove this function
14183 from the `before-change-functions' in the current buffer."
14184 (interactive)
14185 (unless org-inhibit-highlight-removal
14186 (mapc #'delete-overlay org-occur-highlights)
14187 (setq org-occur-highlights nil)
14188 (setq org-occur-parameters nil)
14189 (unless noremove
14190 (remove-hook 'before-change-functions
14191 'org-remove-occur-highlights 'local))))
14193 ;;;; Priorities
14195 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14196 "Regular expression matching the priority indicator.")
14198 (defvar org-remove-priority-next-time nil)
14200 (defun org-priority-up ()
14201 "Increase the priority of the current item."
14202 (interactive)
14203 (org-priority 'up))
14205 (defun org-priority-down ()
14206 "Decrease the priority of the current item."
14207 (interactive)
14208 (org-priority 'down))
14210 (defun org-priority (&optional action _show)
14211 "Change the priority of an item.
14212 ACTION can be `set', `up', `down', or a character."
14213 (interactive "P")
14214 (if (equal action '(4))
14215 (org-show-priority)
14216 (unless org-enable-priority-commands
14217 (user-error "Priority commands are disabled"))
14218 (setq action (or action 'set))
14219 (let (current new news have remove)
14220 (save-excursion
14221 (org-back-to-heading t)
14222 (when (looking-at org-priority-regexp)
14223 (setq current (string-to-char (match-string 2))
14224 have t))
14225 (cond
14226 ((eq action 'remove)
14227 (setq remove t new ?\ ))
14228 ((or (eq action 'set)
14229 (integerp action))
14230 (if (not (eq action 'set))
14231 (setq new action)
14232 (message "Priority %c-%c, SPC to remove: "
14233 org-highest-priority org-lowest-priority)
14234 (save-match-data
14235 (setq new (read-char-exclusive))))
14236 (when (and (= (upcase org-highest-priority) org-highest-priority)
14237 (= (upcase org-lowest-priority) org-lowest-priority))
14238 (setq new (upcase new)))
14239 (cond ((equal new ?\ ) (setq remove t))
14240 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14241 (user-error "Priority must be between `%c' and `%c'"
14242 org-highest-priority org-lowest-priority))))
14243 ((eq action 'up)
14244 (setq new (if have
14245 (1- current) ; normal cycling
14246 ;; last priority was empty
14247 (if (eq last-command this-command)
14248 org-lowest-priority ; wrap around empty to lowest
14249 ;; default
14250 (if org-priority-start-cycle-with-default
14251 org-default-priority
14252 (1- org-default-priority))))))
14253 ((eq action 'down)
14254 (setq new (if have
14255 (1+ current) ; normal cycling
14256 ;; last priority was empty
14257 (if (eq last-command this-command)
14258 org-highest-priority ; wrap around empty to highest
14259 ;; default
14260 (if org-priority-start-cycle-with-default
14261 org-default-priority
14262 (1+ org-default-priority))))))
14263 (t (user-error "Invalid action")))
14264 (when (or (< (upcase new) org-highest-priority)
14265 (> (upcase new) org-lowest-priority))
14266 (if (and (memq action '(up down))
14267 (not have) (not (eq last-command this-command)))
14268 ;; `new' is from default priority
14269 (error
14270 "The default can not be set, see `org-default-priority' why")
14271 ;; normal cycling: `new' is beyond highest/lowest priority
14272 ;; and is wrapped around to the empty priority
14273 (setq remove t)))
14274 (setq news (format "%c" new))
14275 (if have
14276 (if remove
14277 (replace-match "" t t nil 1)
14278 (replace-match news t t nil 2))
14279 (if remove
14280 (user-error "No priority cookie found in line")
14281 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14282 (if (match-end 2)
14283 (progn
14284 (goto-char (match-end 2))
14285 (insert " [#" news "]"))
14286 (goto-char (match-beginning 3))
14287 (insert "[#" news "] "))))
14288 (org-set-tags nil 'align))
14289 (if remove
14290 (message "Priority removed")
14291 (message "Priority of current item set to %s" news)))))
14293 (defun org-show-priority ()
14294 "Show the priority of the current item.
14295 This priority is composed of the main priority given with the [#A] cookies,
14296 and by additional input from the age of a schedules or deadline entry."
14297 (interactive)
14298 (let ((pri (if (eq major-mode 'org-agenda-mode)
14299 (org-get-at-bol 'priority)
14300 (save-excursion
14301 (save-match-data
14302 (beginning-of-line)
14303 (and (looking-at org-heading-regexp)
14304 (org-get-priority (match-string 0))))))))
14305 (message "Priority is %d" (if pri pri -1000))))
14307 (defun org-get-priority (s)
14308 "Find priority cookie and return priority."
14309 (save-match-data
14310 (if (functionp org-get-priority-function)
14311 (funcall org-get-priority-function)
14312 (if (not (string-match org-priority-regexp s))
14313 (* 1000 (- org-lowest-priority org-default-priority))
14314 (* 1000 (- org-lowest-priority
14315 (string-to-char (match-string 2 s))))))))
14317 ;;;; Tags
14319 (defvar org-agenda-archives-mode)
14320 (defvar org-map-continue-from nil
14321 "Position from where mapping should continue.
14322 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14324 (defvar org-scanner-tags nil
14325 "The current tag list while the tags scanner is running.")
14327 (defvar org-trust-scanner-tags nil
14328 "Should `org-get-tags-at' use the tags for the scanner.
14329 This is for internal dynamical scoping only.
14330 When this is non-nil, the function `org-get-tags-at' will return the value
14331 of `org-scanner-tags' instead of building the list by itself. This
14332 can lead to large speed-ups when the tags scanner is used in a file with
14333 many entries, and when the list of tags is retrieved, for example to
14334 obtain a list of properties. Building the tags list for each entry in such
14335 a file becomes an N^2 operation - but with this variable set, it scales
14336 as N.")
14338 (defvar org--matcher-tags-todo-only nil)
14340 (defun org-scan-tags (action matcher todo-only &optional start-level)
14341 "Scan headline tags with inheritance and produce output ACTION.
14343 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14344 or `agenda' to produce an entry list for an agenda view. It can also be
14345 a Lisp form or a function that should be called at each matched headline, in
14346 this case the return value is a list of all return values from these calls.
14348 MATCHER is a function accepting three arguments, returning
14349 a non-nil value whenever a given set of tags qualifies a headline
14350 for inclusion. See `org-make-tags-matcher' for more information.
14351 As a special case, it can also be set to t (respectively nil) in
14352 order to match all (respectively none) headline.
14354 When TODO-ONLY is non-nil, only lines with a not-done TODO
14355 keyword are included in the output.
14357 START-LEVEL can be a string with asterisks, reducing the scope to
14358 headlines matching this string."
14359 (require 'org-agenda)
14360 (let* ((re (concat "^"
14361 (if start-level
14362 ;; Get the correct level to match
14363 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14364 org-outline-regexp)
14365 " *\\(\\<\\("
14366 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14367 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14368 (props (list 'face 'default
14369 'done-face 'org-agenda-done
14370 'undone-face 'default
14371 'mouse-face 'highlight
14372 'org-not-done-regexp org-not-done-regexp
14373 'org-todo-regexp org-todo-regexp
14374 'org-complex-heading-regexp org-complex-heading-regexp
14375 'help-echo
14376 (format "mouse-2 or RET jump to org file %s"
14377 (abbreviate-file-name
14378 (or (buffer-file-name (buffer-base-buffer))
14379 (buffer-name (buffer-base-buffer)))))))
14380 (org-map-continue-from nil)
14381 lspos tags tags-list
14382 (tags-alist (list (cons 0 org-file-tags)))
14383 (llast 0) rtn rtn1 level category i txt
14384 todo marker entry priority
14385 ts-date ts-date-type ts-date-pair)
14386 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14387 (setq action (list 'lambda nil action)))
14388 (save-excursion
14389 (goto-char (point-min))
14390 (when (eq action 'sparse-tree)
14391 (org-overview)
14392 (org-remove-occur-highlights))
14393 (while (let (case-fold-search)
14394 (re-search-forward re nil t))
14395 (setq org-map-continue-from nil)
14396 (catch :skip
14397 (setq todo
14398 ;; TODO: is the 1-2 difference a bug?
14399 (when (match-end 1) (match-string-no-properties 2))
14400 tags (when (match-end 4) (match-string-no-properties 4)))
14401 (goto-char (setq lspos (match-beginning 0)))
14402 (setq level (org-reduced-level (org-outline-level))
14403 category (org-get-category))
14404 (when (eq action 'agenda)
14405 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14406 ts-date (car ts-date-pair)
14407 ts-date-type (cdr ts-date-pair)))
14408 (setq i llast llast level)
14409 ;; remove tag lists from same and sublevels
14410 (while (>= i level)
14411 (when (setq entry (assoc i tags-alist))
14412 (setq tags-alist (delete entry tags-alist)))
14413 (setq i (1- i)))
14414 ;; add the next tags
14415 (when tags
14416 (setq tags (org-split-string tags ":")
14417 tags-alist
14418 (cons (cons level tags) tags-alist)))
14419 ;; compile tags for current headline
14420 (setq tags-list
14421 (if org-use-tag-inheritance
14422 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14423 tags)
14424 org-scanner-tags tags-list)
14425 (when org-use-tag-inheritance
14426 (setcdr (car tags-alist)
14427 (mapcar (lambda (x)
14428 (setq x (copy-sequence x))
14429 (org-add-prop-inherited x))
14430 (cdar tags-alist))))
14431 (when (and tags org-use-tag-inheritance
14432 (or (not (eq t org-use-tag-inheritance))
14433 org-tags-exclude-from-inheritance))
14434 ;; Selective inheritance, remove uninherited ones.
14435 (setcdr (car tags-alist)
14436 (org-remove-uninherited-tags (cdar tags-alist))))
14437 (when (and
14439 ;; eval matcher only when the todo condition is OK
14440 (and (or (not todo-only) (member todo org-not-done-keywords))
14441 (if (functionp matcher)
14442 (let ((case-fold-search t) (org-trust-scanner-tags t))
14443 (funcall matcher todo tags-list level))
14444 matcher))
14446 ;; Call the skipper, but return t if it does not
14447 ;; skip, so that the `and' form continues evaluating.
14448 (progn
14449 (unless (eq action 'sparse-tree) (org-agenda-skip))
14452 ;; Check if timestamps are deselecting this entry
14453 (or (not todo-only)
14454 (and (member todo org-not-done-keywords)
14455 (or (not org-agenda-tags-todo-honor-ignore-options)
14456 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14458 ;; select this headline
14459 (cond
14460 ((eq action 'sparse-tree)
14461 (and org-highlight-sparse-tree-matches
14462 (org-get-heading) (match-end 0)
14463 (org-highlight-new-match
14464 (match-beginning 1) (match-end 1)))
14465 (org-show-context 'tags-tree))
14466 ((eq action 'agenda)
14467 (setq txt (org-agenda-format-item
14469 (concat
14470 (if (eq org-tags-match-list-sublevels 'indented)
14471 (make-string (1- level) ?.) "")
14472 (org-get-heading))
14473 (make-string level ?\s)
14474 category
14475 tags-list)
14476 priority (org-get-priority txt))
14477 (goto-char lspos)
14478 (setq marker (org-agenda-new-marker))
14479 (org-add-props txt props
14480 'org-marker marker 'org-hd-marker marker 'org-category category
14481 'todo-state todo
14482 'ts-date ts-date
14483 'priority priority
14484 'type (concat "tagsmatch" ts-date-type))
14485 (push txt rtn))
14486 ((functionp action)
14487 (setq org-map-continue-from nil)
14488 (save-excursion
14489 (setq rtn1 (funcall action))
14490 (push rtn1 rtn)))
14491 (t (user-error "Invalid action")))
14493 ;; if we are to skip sublevels, jump to end of subtree
14494 (unless org-tags-match-list-sublevels
14495 (org-end-of-subtree t)
14496 (backward-char 1))))
14497 ;; Get the correct position from where to continue
14498 (if org-map-continue-from
14499 (goto-char org-map-continue-from)
14500 (and (= (point) lspos) (end-of-line 1)))))
14501 (when (and (eq action 'sparse-tree)
14502 (not org-sparse-tree-open-archived-trees))
14503 (org-hide-archived-subtrees (point-min) (point-max)))
14504 (nreverse rtn)))
14506 (defun org-remove-uninherited-tags (tags)
14507 "Remove all tags that are not inherited from the list TAGS."
14508 (cond
14509 ((eq org-use-tag-inheritance t)
14510 (if org-tags-exclude-from-inheritance
14511 (org-delete-all org-tags-exclude-from-inheritance tags)
14512 tags))
14513 ((not org-use-tag-inheritance) nil)
14514 ((stringp org-use-tag-inheritance)
14515 (delq nil (mapcar
14516 (lambda (x)
14517 (if (and (string-match org-use-tag-inheritance x)
14518 (not (member x org-tags-exclude-from-inheritance)))
14519 x nil))
14520 tags)))
14521 ((listp org-use-tag-inheritance)
14522 (delq nil (mapcar
14523 (lambda (x)
14524 (if (member x org-use-tag-inheritance) x nil))
14525 tags)))))
14527 (defun org-match-sparse-tree (&optional todo-only match)
14528 "Create a sparse tree according to tags string MATCH.
14530 MATCH is a string with match syntax. It can contain a selection
14531 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14532 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14533 those. See the manual for details.
14535 If optional argument TODO-ONLY is non-nil, only select lines that
14536 are also TODO tasks."
14537 (interactive "P")
14538 (org-agenda-prepare-buffers (list (current-buffer)))
14539 (let ((org--matcher-tags-todo-only todo-only))
14540 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14541 org--matcher-tags-todo-only)))
14543 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14545 (defvar org-cached-props nil)
14546 (defun org-cached-entry-get (pom property)
14547 (if (or (eq t org-use-property-inheritance)
14548 (and (stringp org-use-property-inheritance)
14549 (let ((case-fold-search t))
14550 (string-match-p org-use-property-inheritance property)))
14551 (and (listp org-use-property-inheritance)
14552 (member-ignore-case property org-use-property-inheritance)))
14553 ;; Caching is not possible, check it directly.
14554 (org-entry-get pom property 'inherit)
14555 ;; Get all properties, so we can do complicated checks easily.
14556 (cdr (assoc-string property
14557 (or org-cached-props
14558 (setq org-cached-props (org-entry-properties pom)))
14559 t))))
14561 (defun org-global-tags-completion-table (&optional files)
14562 "Return the list of all tags in all agenda buffer/files.
14563 Optional FILES argument is a list of files which can be used
14564 instead of the agenda files."
14565 (save-excursion
14566 (org-uniquify
14567 (delq nil
14568 (apply #'append
14569 (mapcar
14570 (lambda (file)
14571 (set-buffer (find-file-noselect file))
14572 (mapcar (lambda (x)
14573 (and (stringp (car-safe x))
14574 (list (car-safe x))))
14575 (or org-current-tag-alist (org-get-buffer-tags))))
14576 (if (car-safe files) files
14577 (org-agenda-files))))))))
14579 (defun org-make-tags-matcher (match)
14580 "Create the TAGS/TODO matcher form for the selection string MATCH.
14582 Returns a cons of the selection string MATCH and a function
14583 implementing the matcher.
14585 The matcher is to be called at an Org entry, with point on the
14586 headline, and returns non-nil if the entry matches the selection
14587 string MATCH. It must be called with three arguments: the TODO
14588 keyword at the entry (or nil if none), the list of all tags at
14589 the entry including inherited ones and the reduced level of the
14590 headline. Additionally, the category of the entry, if any, must
14591 be specified as the text property `org-category' on the headline.
14593 This function sets the variable `org--matcher-tags-todo-only' to
14594 a non-nil value if the matcher restricts matching to TODO
14595 entries, otherwise it is not touched.
14597 See also `org-scan-tags'."
14598 (unless match
14599 ;; Get a new match request, with completion against the global
14600 ;; tags table and the local tags in current buffer.
14601 (let ((org-last-tags-completion-table
14602 (org-uniquify
14603 (delq nil (append (org-get-buffer-tags)
14604 (org-global-tags-completion-table))))))
14605 (setq match
14606 (completing-read
14607 "Match: "
14608 'org-tags-completion-function nil nil nil 'org-tags-history))))
14610 (let ((match0 match)
14611 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14612 (start 0)
14613 tagsmatch todomatch tagsmatcher todomatcher)
14615 ;; Expand group tags.
14616 (setq match (org-tags-expand match))
14618 ;; Check if there is a TODO part of this match, which would be the
14619 ;; part after a "/". To make sure that this slash is not part of
14620 ;; a property value to be matched against, we also check that
14621 ;; there is no / after that slash. First, find the last slash.
14622 (let ((s 0))
14623 (while (string-match "/+" match s)
14624 (setq start (match-beginning 0))
14625 (setq s (match-end 0))))
14626 (if (and (string-match "/+" match start)
14627 (not (string-match-p "\"" match start)))
14628 ;; Match contains also a TODO-matching request.
14629 (progn
14630 (setq tagsmatch (substring match 0 (match-beginning 0)))
14631 (setq todomatch (substring match (match-end 0)))
14632 (when (string-prefix-p "!" todomatch)
14633 (setq org--matcher-tags-todo-only t)
14634 (setq todomatch (substring todomatch 1)))
14635 (when (string-match "\\`\\s-*\\'" todomatch)
14636 (setq todomatch nil)))
14637 ;; Only matching tags.
14638 (setq tagsmatch match)
14639 (setq todomatch nil))
14641 ;; Make the tags matcher.
14642 (when (org-string-nw-p tagsmatch)
14643 (let ((orlist nil)
14644 (orterms (org-split-string tagsmatch "|"))
14645 term)
14646 (while (setq term (pop orterms))
14647 (while (and (equal (substring term -1) "\\") orterms)
14648 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14649 (while (string-match re term)
14650 (let* ((rest (substring term (match-end 0)))
14651 (minus (and (match-end 1)
14652 (equal (match-string 1 term) "-")))
14653 (tag (save-match-data
14654 (replace-regexp-in-string
14655 "\\\\-" "-" (match-string 2 term))))
14656 (regexp (eq (string-to-char tag) ?{))
14657 (levelp (match-end 4))
14658 (propp (match-end 5))
14660 (cond
14661 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14662 (levelp
14663 `(,(org-op-to-function (match-string 3 term))
14664 level
14665 ,(string-to-number (match-string 4 term))))
14666 (propp
14667 (let* ((gv (pcase (upcase (match-string 5 term))
14668 ("CATEGORY"
14669 '(get-text-property (point) 'org-category))
14670 ("TODO" 'todo)
14671 (p `(org-cached-entry-get nil ,p))))
14672 (pv (match-string 7 term))
14673 (regexp (eq (string-to-char pv) ?{))
14674 (strp (eq (string-to-char pv) ?\"))
14675 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14676 (po (org-op-to-function (match-string 6 term)
14677 (if timep 'time strp))))
14678 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14679 (when timep (setq pv (org-matcher-time pv)))
14680 (cond ((and regexp (eq po 'org<>))
14681 `(not (string-match ,pv (or ,gv ""))))
14682 (regexp `(string-match ,pv (or ,gv "")))
14683 (strp `(,po (or ,gv "") ,pv))
14685 `(,po
14686 (string-to-number (or ,gv ""))
14687 ,(string-to-number pv))))))
14688 (t `(member ,tag tags-list)))))
14689 (push (if minus `(not ,mm) mm) tagsmatcher)
14690 (setq term rest)))
14691 (push `(and ,@tagsmatcher) orlist)
14692 (setq tagsmatcher nil))
14693 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14695 ;; Make the TODO matcher.
14696 (when (org-string-nw-p todomatch)
14697 (let ((orlist nil))
14698 (dolist (term (org-split-string todomatch "|"))
14699 (while (string-match re term)
14700 (let* ((minus (and (match-end 1)
14701 (equal (match-string 1 term) "-")))
14702 (kwd (match-string 2 term))
14703 (regexp (eq (string-to-char kwd) ?{))
14704 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14705 `(equal todo ,kwd))))
14706 (push (if minus `(not ,mm) mm) todomatcher))
14707 (setq term (substring term (match-end 0))))
14708 (push (if (> (length todomatcher) 1)
14709 (cons 'and todomatcher)
14710 (car todomatcher))
14711 orlist)
14712 (setq todomatcher nil))
14713 (setq todomatcher (cons 'or orlist))))
14715 ;; Return the string and function of the matcher. If no
14716 ;; tags-specific or todo-specific matcher exists, match
14717 ;; everything.
14718 (let ((matcher (if (and tagsmatcher todomatcher)
14719 `(and ,tagsmatcher ,todomatcher)
14720 (or tagsmatcher todomatcher t))))
14721 (when org--matcher-tags-todo-only
14722 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14723 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14725 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14726 "Expand group tags in MATCH.
14728 This replaces every group tag in MATCH with a regexp tag search.
14729 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14730 will be replaced like this:
14732 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14733 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14734 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14736 Replacing by a regexp preserves the structure of the match.
14737 E.g., this expansion
14739 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14741 will match anything tagged with \"Lab\" and \"Home\", or tagged
14742 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14744 A group tag in MATCH can contain regular expressions of its own.
14745 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14746 will be replaced like this:
14748 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14750 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14751 assumed to be a single group tag, and the function will return
14752 the list of tags in this group.
14754 When DOWNCASE is non-nil, expand downcased TAGS."
14755 (if org-group-tags
14756 (let* ((case-fold-search t)
14757 (stable org-mode-syntax-table)
14758 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14759 (taggroups (if downcased
14760 (mapcar (lambda (tg) (mapcar #'downcase tg))
14761 taggroups)
14762 taggroups))
14763 (taggroups-keys (mapcar #'car taggroups))
14764 (return-match (if downcased (downcase match) match))
14765 (count 0)
14766 (work-already-expanded tags-already-expanded)
14767 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14768 ;; @ and _ are allowed as word-components in tags.
14769 (modify-syntax-entry ?@ "w" stable)
14770 (modify-syntax-entry ?_ "w" stable)
14771 ;; Temporarily replace regexp-expressions in the match-expression.
14772 (while (string-match "{.+?}" return-match)
14773 (cl-incf count)
14774 (push (match-string 0 return-match) regexps-in-match)
14775 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14776 (while (and taggroups-keys
14777 (with-syntax-table stable
14778 (string-match
14779 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14780 (regexp-opt taggroups-keys) "\\>\\)")
14781 return-match)))
14782 (let* ((dir (match-string 1 return-match))
14783 (tag (match-string 2 return-match))
14784 (tag (if downcased (downcase tag) tag)))
14785 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14786 (member tag work-already-expanded))
14787 (setq tags-in-group (assoc tag taggroups))
14788 (push tag work-already-expanded)
14789 ;; Recursively expand each tag in the group, if the tag hasn't
14790 ;; already been expanded. Restore the match-data after all recursive calls.
14791 (save-match-data
14792 (let (tags-expanded)
14793 (dolist (x (cdr tags-in-group))
14794 (if (and (member x taggroups-keys)
14795 (not (member x work-already-expanded)))
14796 (setq tags-expanded
14797 (delete-dups
14798 (append
14799 (org-tags-expand x t downcased
14800 work-already-expanded)
14801 tags-expanded)))
14802 (setq tags-expanded
14803 (append (list x) tags-expanded)))
14804 (setq work-already-expanded
14805 (delete-dups
14806 (append tags-expanded
14807 work-already-expanded))))
14808 (setq tags-in-group
14809 (delete-dups (cons (car tags-in-group)
14810 tags-expanded)))))
14811 ;; Filter tag-regexps from tags.
14812 (setq regexp-in-group-escaped
14813 (delq nil (mapcar (lambda (x)
14814 (if (stringp x)
14815 (and (equal "{" (substring x 0 1))
14816 (equal "}" (substring x -1))
14819 tags-in-group))
14820 regexp-in-group
14821 (mapcar (lambda (x)
14822 (substring x 1 -1))
14823 regexp-in-group-escaped)
14824 tags-in-group
14825 (delq nil (mapcar (lambda (x)
14826 (if (stringp x)
14827 (and (not (equal "{" (substring x 0 1)))
14828 (not (equal "}" (substring x -1)))
14831 tags-in-group)))
14832 ;; If single-as-list, do no more in the while-loop.
14833 (if (not single-as-list)
14834 (progn
14835 (when regexp-in-group
14836 (setq regexp-in-group
14837 (concat "\\|"
14838 (mapconcat 'identity regexp-in-group
14839 "\\|"))))
14840 (setq tags-in-group
14841 (concat dir
14842 "{\\<"
14843 (regexp-opt tags-in-group)
14844 "\\>"
14845 regexp-in-group
14846 "}"))
14847 (when (stringp tags-in-group)
14848 (org-add-props tags-in-group '(grouptag t)))
14849 (setq return-match
14850 (replace-match tags-in-group t t return-match)))
14851 (setq tags-in-group
14852 (append regexp-in-group-escaped tags-in-group))))
14853 (setq taggroups-keys (delete tag taggroups-keys))))
14854 ;; Add the regular expressions back into the match-expression again.
14855 (while regexps-in-match
14856 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14857 (pop regexps-in-match)
14858 return-match t t))
14859 (cl-decf count))
14860 (if single-as-list
14861 (if tags-in-group tags-in-group (list return-match))
14862 return-match))
14863 (if single-as-list
14864 (list (if downcased (downcase match) match))
14865 match)))
14867 (defun org-op-to-function (op &optional stringp)
14868 "Turn an operator into the appropriate function."
14869 (setq op
14870 (cond
14871 ((equal op "<" ) '(< string< org-time<))
14872 ((equal op ">" ) '(> org-string> org-time>))
14873 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14874 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14875 ((member op '("=" "==")) '(= string= org-time=))
14876 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14877 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14879 (defun org<> (a b) (not (= a b)))
14880 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14881 (defun org-string>= (a b) (not (string< a b)))
14882 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14883 (defun org-string<> (a b) (not (string= a b)))
14884 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14885 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14886 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14887 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14888 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14889 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14890 (defun org-2ft (s)
14891 "Convert S to a floating point time.
14892 If S is already a number, just return it. If it is a string, parse
14893 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14894 (cond
14895 ((numberp s) s)
14896 ((stringp s)
14897 (condition-case nil
14898 (float-time (apply 'encode-time (org-parse-time-string s)))
14899 (error 0.)))
14900 (t 0.)))
14902 (defun org-time-today ()
14903 "Time in seconds today at 0:00.
14904 Returns the float number of seconds since the beginning of the
14905 epoch to the beginning of today (00:00)."
14906 (float-time (apply 'encode-time
14907 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14909 (defun org-matcher-time (s)
14910 "Interpret a time comparison value."
14911 (save-match-data
14912 (cond
14913 ((string= s "<now>") (float-time))
14914 ((string= s "<today>") (org-time-today))
14915 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14916 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14917 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14918 (+ (org-time-today)
14919 (* (string-to-number (match-string 1 s))
14920 (cdr (assoc (match-string 2 s)
14921 '(("d" . 86400.0) ("w" . 604800.0)
14922 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14923 (t (org-2ft s)))))
14925 (defun org-match-any-p (re list)
14926 "Does re match any element of list?"
14927 (setq list (mapcar (lambda (x) (string-match re x)) list))
14928 (delq nil list))
14930 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14931 (defvar org-tags-overlay (make-overlay 1 1))
14932 (delete-overlay org-tags-overlay)
14934 (defun org-get-local-tags-at (&optional pos)
14935 "Get a list of tags defined in the current headline."
14936 (org-get-tags-at pos 'local))
14938 (defun org-get-local-tags ()
14939 "Get a list of tags defined in the current headline."
14940 (org-get-tags-at nil 'local))
14942 (defun org-get-tags-at (&optional pos local)
14943 "Get a list of all headline tags applicable at POS.
14944 POS defaults to point. If tags are inherited, the list contains
14945 the targets in the same sequence as the headlines appear, i.e.
14946 the tags of the current headline come last.
14947 When LOCAL is non-nil, only return tags from the current headline,
14948 ignore inherited ones."
14949 (interactive)
14950 (if (and org-trust-scanner-tags
14951 (or (not pos) (equal pos (point)))
14952 (not local))
14953 org-scanner-tags
14954 (let (tags ltags lastpos parent)
14955 (save-excursion
14956 (save-restriction
14957 (widen)
14958 (goto-char (or pos (point)))
14959 (save-match-data
14960 (catch 'done
14961 (condition-case nil
14962 (progn
14963 (org-back-to-heading t)
14964 (while (not (equal lastpos (point)))
14965 (setq lastpos (point))
14966 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14967 (setq ltags (org-split-string
14968 (match-string-no-properties 1) ":"))
14969 (when parent
14970 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14971 (setq tags (append
14972 (if parent
14973 (org-remove-uninherited-tags ltags)
14974 ltags)
14975 tags)))
14976 (or org-use-tag-inheritance (throw 'done t))
14977 (when local (throw 'done t))
14978 (or (org-up-heading-safe) (error nil))
14979 (setq parent t)))
14980 (error nil)))))
14981 (if local
14982 tags
14983 (reverse (delete-dups
14984 (reverse (append
14985 (org-remove-uninherited-tags
14986 org-file-tags)
14987 tags)))))))))
14989 (defun org-add-prop-inherited (s)
14990 (add-text-properties 0 (length s) '(inherited t) s)
14993 (defun org-toggle-tag (tag &optional onoff)
14994 "Toggle the tag TAG for the current line.
14995 If ONOFF is `on' or `off', don't toggle but set to this state."
14996 (let (res current)
14997 (save-excursion
14998 (org-back-to-heading t)
14999 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
15000 (point-at-eol) t)
15001 (progn
15002 (setq current (match-string 1))
15003 (replace-match ""))
15004 (setq current ""))
15005 (setq current (nreverse (org-split-string current ":")))
15006 (cond
15007 ((eq onoff 'on)
15008 (setq res t)
15009 (or (member tag current) (push tag current)))
15010 ((eq onoff 'off)
15011 (or (not (member tag current)) (setq current (delete tag current))))
15012 (t (if (member tag current)
15013 (setq current (delete tag current))
15014 (setq res t)
15015 (push tag current))))
15016 (end-of-line 1)
15017 (if current
15018 (progn
15019 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
15020 (org-set-tags nil t))
15021 (delete-horizontal-space))
15022 (run-hooks 'org-after-tags-change-hook))
15023 res))
15025 (defun org--align-tags-here (to-col)
15026 "Align tags on the current headline to TO-COL.
15027 Assume point is on a headline."
15028 (let ((pos (point)))
15029 (beginning-of-line)
15030 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15031 (>= pos (match-beginning 2)))
15032 ;; No tags or point within tags: do not align.
15033 (goto-char pos)
15034 (goto-char (match-beginning 1))
15035 (let ((shift (max (- (if (>= to-col 0) to-col
15036 (- (abs to-col) (string-width (match-string 2))))
15037 (current-column))
15038 1)))
15039 (replace-match (make-string shift ?\s) nil nil nil 1)
15040 ;; Preserve initial position, if possible. In any case, stop
15041 ;; before tags.
15042 (when (< pos (point)) (goto-char pos))))))
15044 (defun org-set-tags-command (&optional arg just-align)
15045 "Call the set-tags command for the current entry."
15046 (interactive "P")
15047 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
15048 (org-set-tags arg just-align)
15049 (save-excursion
15050 (unless (and (org-region-active-p)
15051 org-loop-over-headlines-in-active-region)
15052 (org-back-to-heading t))
15053 (org-set-tags arg just-align))))
15055 (defun org-set-tags-to (data)
15056 "Set the tags of the current entry to DATA, replacing the current tags.
15057 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
15058 If DATA is nil or the empty string, any tags will be removed."
15059 (interactive "sTags: ")
15060 (setq data
15061 (cond
15062 ((eq data nil) "")
15063 ((equal data "") "")
15064 ((stringp data)
15065 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
15066 ":"))
15067 ((listp data)
15068 (concat ":" (mapconcat 'identity data ":") ":"))))
15069 (when data
15070 (save-excursion
15071 (org-back-to-heading t)
15072 (when (let ((case-fold-search nil))
15073 (looking-at org-complex-heading-regexp))
15074 (if (match-end 5)
15075 (progn
15076 (goto-char (match-beginning 5))
15077 (insert data)
15078 (delete-region (point) (point-at-eol))
15079 (org-set-tags nil 'align))
15080 (goto-char (point-at-eol))
15081 (insert " " data)
15082 (org-set-tags nil 'align)))
15083 (beginning-of-line 1)
15084 (when (looking-at ".*?\\([ \t]+\\)$")
15085 (delete-region (match-beginning 1) (match-end 1))))))
15087 (defun org-align-all-tags ()
15088 "Align the tags in all headings."
15089 (interactive)
15090 (save-excursion
15091 (or (ignore-errors (org-back-to-heading t))
15092 (outline-next-heading))
15093 (if (org-at-heading-p)
15094 (org-set-tags t)
15095 (message "No headings"))))
15097 (defvar org-indent-indentation-per-level)
15098 (defun org-set-tags (&optional arg just-align)
15099 "Set the tags for the current headline.
15100 With prefix ARG, realign all tags in headings in the current buffer.
15101 When JUST-ALIGN is non-nil, only align tags."
15102 (interactive "P")
15103 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15104 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15105 'region-start-level
15106 'region))
15107 org-loop-over-headlines-in-active-region)
15108 (org-map-entries
15109 ;; We don't use ARG and JUST-ALIGN here because these args
15110 ;; are not useful when looping over headlines.
15111 #'org-set-tags
15112 org-loop-over-headlines-in-active-region
15114 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15115 (let ((org-setting-tags t))
15116 (if arg
15117 (save-excursion
15118 (goto-char (point-min))
15119 (while (re-search-forward org-outline-regexp-bol nil t)
15120 (org-set-tags nil t)
15121 (end-of-line))
15122 (message "All tags realigned to column %d" org-tags-column))
15123 (let* ((current (org-get-tags-string))
15124 (tags
15125 (if just-align current
15126 ;; Get a new set of tags from the user.
15127 (save-excursion
15128 (let* ((seen)
15129 (table
15130 (setq
15131 org-last-tags-completion-table
15132 ;; Uniquify tags in alists, yet preserve
15133 ;; structure (i.e., keywords).
15134 (delq nil
15135 (mapcar
15136 (lambda (pair)
15137 (let ((head (car pair)))
15138 (cond ((symbolp head) pair)
15139 ((member head seen) nil)
15140 (t (push head seen)
15141 pair))))
15142 (append
15143 (or org-current-tag-alist
15144 (org-get-buffer-tags))
15145 (and
15146 org-complete-tags-always-offer-all-agenda-tags
15147 (org-global-tags-completion-table
15148 (org-agenda-files))))))))
15149 (current-tags (org-split-string current ":"))
15150 (inherited-tags
15151 (nreverse (nthcdr (length current-tags)
15152 (nreverse (org-get-tags-at))))))
15153 (replace-regexp-in-string
15154 "\\([-+&]+\\|,\\)"
15156 (if (or (eq t org-use-fast-tag-selection)
15157 (and org-use-fast-tag-selection
15158 (delq nil (mapcar #'cdr table))))
15159 (org-fast-tag-selection
15160 current-tags inherited-tags table
15161 (and org-fast-tag-selection-include-todo
15162 org-todo-key-alist))
15163 (let ((org-add-colon-after-tag-completion
15164 (< 1 (length table))))
15165 (org-trim
15166 (completing-read
15167 "Tags: "
15168 #'org-tags-completion-function
15169 nil nil current 'org-tags-history))))))))))
15171 (when org-tags-sort-function
15172 (setq tags
15173 (mapconcat
15174 #'identity
15175 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15176 org-tags-sort-function)
15177 ":")))
15179 (if (not (org-string-nw-p tags)) (setq tags "")
15180 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
15181 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
15183 ;; Insert new tags at the correct column.
15184 (unless (equal current tags)
15185 (save-excursion
15186 (beginning-of-line)
15187 (let ((case-fold-search nil))
15188 (looking-at org-complex-heading-regexp))
15189 ;; Remove current tags, if any.
15190 (when (match-end 5) (replace-match "" nil nil nil 5))
15191 ;; Insert new tags, if any. Otherwise, remove trailing
15192 ;; white spaces.
15193 (end-of-line)
15194 (if (not (equal tags ""))
15195 (insert " " tags)
15196 (skip-chars-backward " \t")
15197 (delete-region (point) (line-end-position)))))
15198 ;; Align tags, if any. Fix tags column if `org-indent-mode'
15199 ;; is on.
15200 (unless (equal tags "")
15201 (let* ((level (save-excursion
15202 (beginning-of-line)
15203 (skip-chars-forward "\\*")))
15204 (offset (if (bound-and-true-p org-indent-mode)
15205 (* (1- org-indent-indentation-per-level)
15206 (1- level))
15208 (tags-column
15209 (+ org-tags-column
15210 (if (> org-tags-column 0) (- offset) offset))))
15211 (org--align-tags-here tags-column))))
15212 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15214 (defun org-change-tag-in-region (beg end tag off)
15215 "Add or remove TAG for each entry in the region.
15216 This works in the agenda, and also in an Org buffer."
15217 (interactive
15218 (list (region-beginning) (region-end)
15219 (let ((org-last-tags-completion-table
15220 (if (derived-mode-p 'org-mode)
15221 (org-uniquify
15222 (delq nil (append (org-get-buffer-tags)
15223 (org-global-tags-completion-table))))
15224 (org-global-tags-completion-table))))
15225 (completing-read
15226 "Tag: " 'org-tags-completion-function nil nil nil
15227 'org-tags-history))
15228 (progn
15229 (message "[s]et or [r]emove? ")
15230 (equal (read-char-exclusive) ?r))))
15231 (when (fboundp 'deactivate-mark) (deactivate-mark))
15232 (let ((agendap (equal major-mode 'org-agenda-mode))
15233 l1 l2 m buf pos newhead (cnt 0))
15234 (goto-char end)
15235 (setq l2 (1- (org-current-line)))
15236 (goto-char beg)
15237 (setq l1 (org-current-line))
15238 (cl-loop for l from l1 to l2 do
15239 (org-goto-line l)
15240 (setq m (get-text-property (point) 'org-hd-marker))
15241 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15242 (and agendap m))
15243 (setq buf (if agendap (marker-buffer m) (current-buffer))
15244 pos (if agendap m (point)))
15245 (with-current-buffer buf
15246 (save-excursion
15247 (save-restriction
15248 (goto-char pos)
15249 (setq cnt (1+ cnt))
15250 (org-toggle-tag tag (if off 'off 'on))
15251 (setq newhead (org-get-heading)))))
15252 (and agendap (org-agenda-change-all-lines newhead m))))
15253 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15255 (defun org-tags-completion-function (string _predicate &optional flag)
15256 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15257 (confirm (lambda (x) (stringp (car x)))))
15258 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15259 (setq s1 (match-string 1 string)
15260 s2 (match-string 2 string))
15261 (setq s1 "" s2 string))
15262 (cond
15263 ((eq flag nil)
15264 ;; try completion
15265 (setq rtn (try-completion s2 ctable confirm))
15266 (when (stringp rtn)
15267 (setq rtn
15268 (concat s1 s2 (substring rtn (length s2))
15269 (if (and org-add-colon-after-tag-completion
15270 (assoc rtn ctable))
15271 ":" ""))))
15272 rtn)
15273 ((eq flag t)
15274 ;; all-completions
15275 (all-completions s2 ctable confirm))
15276 ((eq flag 'lambda)
15277 ;; exact match?
15278 (assoc s2 ctable)))))
15280 (defun org-fast-tag-insert (kwd tags face &optional end)
15281 "Insert KDW, and the TAGS, the latter with face FACE.
15282 Also insert END."
15283 (insert (format "%-12s" (concat kwd ":"))
15284 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15285 (or end "")))
15287 (defun org-fast-tag-show-exit (flag)
15288 (save-excursion
15289 (org-goto-line 3)
15290 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15291 (replace-match ""))
15292 (when flag
15293 (end-of-line 1)
15294 (org-move-to-column (- (window-width) 19) t)
15295 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15297 (defun org-set-current-tags-overlay (current prefix)
15298 "Add an overlay to CURRENT tag with PREFIX."
15299 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15300 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15301 (org-overlay-display org-tags-overlay (concat prefix s))))
15303 (defvar org-last-tag-selection-key nil)
15304 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15305 "Fast tag selection with single keys.
15306 CURRENT is the current list of tags in the headline, INHERITED is the
15307 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15308 possibly with grouping information. TODO-TABLE is a similar table with
15309 TODO keywords, should these have keys assigned to them.
15310 If the keys are nil, a-z are automatically assigned.
15311 Returns the new tags string, or nil to not change the current settings."
15312 (let* ((fulltable (append table todo-table))
15313 (maxlen (apply 'max (mapcar
15314 (lambda (x)
15315 (if (stringp (car x)) (string-width (car x)) 0))
15316 fulltable)))
15317 (buf (current-buffer))
15318 (expert (eq org-fast-tag-selection-single-key 'expert))
15319 (buffer-tags nil)
15320 (fwidth (+ maxlen 3 1 3))
15321 (ncol (/ (- (window-width) 4) fwidth))
15322 (i-face 'org-done)
15323 (c-face 'org-todo)
15324 tg cnt e c char c1 c2 ntable tbl rtn
15325 ov-start ov-end ov-prefix
15326 (exit-after-next org-fast-tag-selection-single-key)
15327 (done-keywords org-done-keywords)
15328 groups ingroup intaggroup)
15329 (save-excursion
15330 (beginning-of-line 1)
15331 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15332 (setq ov-start (match-beginning 1)
15333 ov-end (match-end 1)
15334 ov-prefix "")
15335 (setq ov-start (1- (point-at-eol))
15336 ov-end (1+ ov-start))
15337 (skip-chars-forward "^\n\r")
15338 (setq ov-prefix
15339 (concat
15340 (buffer-substring (1- (point)) (point))
15341 (if (> (current-column) org-tags-column)
15343 (make-string (- org-tags-column (current-column)) ?\ ))))))
15344 (move-overlay org-tags-overlay ov-start ov-end)
15345 (save-window-excursion
15346 (if expert
15347 (set-buffer (get-buffer-create " *Org tags*"))
15348 (delete-other-windows)
15349 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15350 (org-switch-to-buffer-other-window " *Org tags*"))
15351 (erase-buffer)
15352 (setq-local org-done-keywords done-keywords)
15353 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15354 (org-fast-tag-insert "Current" current c-face "\n\n")
15355 (org-fast-tag-show-exit exit-after-next)
15356 (org-set-current-tags-overlay current ov-prefix)
15357 (setq tbl fulltable char ?a cnt 0)
15358 (while (setq e (pop tbl))
15359 (cond
15360 ((eq (car e) :startgroup)
15361 (push '() groups) (setq ingroup t)
15362 (unless (zerop cnt)
15363 (setq cnt 0)
15364 (insert "\n"))
15365 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15366 ((eq (car e) :endgroup)
15367 (setq ingroup nil cnt 0)
15368 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15369 ((eq (car e) :startgrouptag)
15370 (setq intaggroup t)
15371 (unless (zerop cnt)
15372 (setq cnt 0)
15373 (insert "\n"))
15374 (insert "[ "))
15375 ((eq (car e) :endgrouptag)
15376 (setq intaggroup nil cnt 0)
15377 (insert "]\n"))
15378 ((equal e '(:newline))
15379 (unless (zerop cnt)
15380 (setq cnt 0)
15381 (insert "\n")
15382 (setq e (car tbl))
15383 (while (equal (car tbl) '(:newline))
15384 (insert "\n")
15385 (setq tbl (cdr tbl)))))
15386 ((equal e '(:grouptags)) (insert " : "))
15388 (setq tg (copy-sequence (car e)) c2 nil)
15389 (if (cdr e)
15390 (setq c (cdr e))
15391 ;; automatically assign a character.
15392 (setq c1 (string-to-char
15393 (downcase (substring
15394 tg (if (= (string-to-char tg) ?@) 1 0)))))
15395 (if (or (rassoc c1 ntable) (rassoc c1 table))
15396 (while (or (rassoc char ntable) (rassoc char table))
15397 (setq char (1+ char)))
15398 (setq c2 c1))
15399 (setq c (or c2 char)))
15400 (when ingroup (push tg (car groups)))
15401 (setq tg (org-add-props tg nil 'face
15402 (cond
15403 ((not (assoc tg table))
15404 (org-get-todo-face tg))
15405 ((member tg current) c-face)
15406 ((member tg inherited) i-face))))
15407 (when (equal (caar tbl) :grouptags)
15408 (org-add-props tg nil 'face 'org-tag-group))
15409 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15410 (insert "[" c "] " tg (make-string
15411 (- fwidth 4 (length tg)) ?\ ))
15412 (push (cons tg c) ntable)
15413 (when (= (cl-incf cnt) ncol)
15414 (insert "\n")
15415 (when (or ingroup intaggroup) (insert " "))
15416 (setq cnt 0)))))
15417 (setq ntable (nreverse ntable))
15418 (insert "\n")
15419 (goto-char (point-min))
15420 (unless expert (org-fit-window-to-buffer))
15421 (setq rtn
15422 (catch 'exit
15423 (while t
15424 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15425 (if (not groups) "no " "")
15426 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15427 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15428 (setq org-last-tag-selection-key c)
15429 (cond
15430 ((= c ?\r) (throw 'exit t))
15431 ((= c ?!)
15432 (setq groups (not groups))
15433 (goto-char (point-min))
15434 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15435 ((= c ?\C-c)
15436 (if (not expert)
15437 (org-fast-tag-show-exit
15438 (setq exit-after-next (not exit-after-next)))
15439 (setq expert nil)
15440 (delete-other-windows)
15441 (set-window-buffer (split-window-vertically) " *Org tags*")
15442 (org-switch-to-buffer-other-window " *Org tags*")
15443 (org-fit-window-to-buffer)))
15444 ((or (= c ?\C-g)
15445 (and (= c ?q) (not (rassoc c ntable))))
15446 (delete-overlay org-tags-overlay)
15447 (setq quit-flag t))
15448 ((= c ?\ )
15449 (setq current nil)
15450 (when exit-after-next (setq exit-after-next 'now)))
15451 ((= c ?\t)
15452 (condition-case nil
15453 (setq tg (completing-read
15454 "Tag: "
15455 (or buffer-tags
15456 (with-current-buffer buf
15457 (setq buffer-tags
15458 (org-get-buffer-tags))))))
15459 (quit (setq tg "")))
15460 (when (string-match "\\S-" tg)
15461 (cl-pushnew (list tg) buffer-tags :test #'equal)
15462 (if (member tg current)
15463 (setq current (delete tg current))
15464 (push tg current)))
15465 (when exit-after-next (setq exit-after-next 'now)))
15466 ((setq e (rassoc c todo-table) tg (car e))
15467 (with-current-buffer buf
15468 (save-excursion (org-todo tg)))
15469 (when exit-after-next (setq exit-after-next 'now)))
15470 ((setq e (rassoc c ntable) tg (car e))
15471 (if (member tg current)
15472 (setq current (delete tg current))
15473 (cl-loop for g in groups do
15474 (when (member tg g)
15475 (dolist (x g) (setq current (delete x current)))))
15476 (push tg current))
15477 (when exit-after-next (setq exit-after-next 'now))))
15479 ;; Create a sorted list
15480 (setq current
15481 (sort current
15482 (lambda (a b)
15483 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15484 (when (eq exit-after-next 'now) (throw 'exit t))
15485 (goto-char (point-min))
15486 (beginning-of-line 2)
15487 (delete-region (point) (point-at-eol))
15488 (org-fast-tag-insert "Current" current c-face)
15489 (org-set-current-tags-overlay current ov-prefix)
15490 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15491 (setq tg (match-string 1))
15492 (add-text-properties
15493 (match-beginning 1) (match-end 1)
15494 (list 'face
15495 (cond
15496 ((member tg current) c-face)
15497 ((member tg inherited) i-face)
15498 (t (get-text-property (match-beginning 1) 'face))))))
15499 (goto-char (point-min)))))
15500 (delete-overlay org-tags-overlay)
15501 (if rtn
15502 (mapconcat 'identity current ":")
15503 nil))))
15505 (defun org-get-tags-string ()
15506 "Get the TAGS string in the current headline."
15507 (unless (org-at-heading-p t)
15508 (user-error "Not on a heading"))
15509 (save-excursion
15510 (beginning-of-line 1)
15511 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15512 (match-string-no-properties 1)
15513 "")))
15515 (defun org-get-tags ()
15516 "Get the list of tags specified in the current headline."
15517 (org-split-string (org-get-tags-string) ":"))
15519 (defun org-get-buffer-tags ()
15520 "Get a table of all tags used in the buffer, for completion."
15521 (org-with-wide-buffer
15522 (goto-char (point-min))
15523 (let ((tag-re (concat org-outline-regexp-bol
15524 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15525 tags)
15526 (while (re-search-forward tag-re nil t)
15527 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15528 (push tag tags)))
15529 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15531 ;;;; The mapping API
15533 (defvar org-agenda-skip-comment-trees)
15534 (defvar org-agenda-skip-function)
15535 (defun org-map-entries (func &optional match scope &rest skip)
15536 "Call FUNC at each headline selected by MATCH in SCOPE.
15538 FUNC is a function or a lisp form. The function will be called without
15539 arguments, with the cursor positioned at the beginning of the headline.
15540 The return values of all calls to the function will be collected and
15541 returned as a list.
15543 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15544 does not need to preserve point. After evaluation, the cursor will be
15545 moved to the end of the line (presumably of the headline of the
15546 processed entry) and search continues from there. Under some
15547 circumstances, this may not produce the wanted results. For example,
15548 if you have removed (e.g. archived) the current (sub)tree it could
15549 mean that the next entry will be skipped entirely. In such cases, you
15550 can specify the position from where search should continue by making
15551 FUNC set the variable `org-map-continue-from' to the desired buffer
15552 position.
15554 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15555 Only headlines that are matched by this query will be considered during
15556 the iteration. When MATCH is nil or t, all headlines will be
15557 visited by the iteration.
15559 SCOPE determines the scope of this command. It can be any of:
15561 nil The current buffer, respecting the restriction if any
15562 tree The subtree started with the entry at point
15563 region The entries within the active region, if any
15564 region-start-level
15565 The entries within the active region, but only those at
15566 the same level than the first one.
15567 file The current buffer, without restriction
15568 file-with-archives
15569 The current buffer, and any archives associated with it
15570 agenda All agenda files
15571 agenda-with-archives
15572 All agenda files with any archive files associated with them
15573 \(file1 file2 ...)
15574 If this is a list, all files in the list will be scanned
15576 The remaining args are treated as settings for the skipping facilities of
15577 the scanner. The following items can be given here:
15579 archive skip trees with the archive tag
15580 comment skip trees with the COMMENT keyword
15581 function or Emacs Lisp form:
15582 will be used as value for `org-agenda-skip-function', so
15583 whenever the function returns a position, FUNC will not be
15584 called for that entry and search will continue from the
15585 position returned
15587 If your function needs to retrieve the tags including inherited tags
15588 at the *current* entry, you can use the value of the variable
15589 `org-scanner-tags' which will be much faster than getting the value
15590 with `org-get-tags-at'. If your function gets properties with
15591 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15592 to t around the call to `org-entry-properties' to get the same speedup.
15593 Note that if your function moves around to retrieve tags and properties at
15594 a *different* entry, you cannot use these techniques."
15595 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15596 (not (org-region-active-p)))
15597 (let* ((org-agenda-archives-mode nil) ; just to make sure
15598 (org-agenda-skip-archived-trees (memq 'archive skip))
15599 (org-agenda-skip-comment-trees (memq 'comment skip))
15600 (org-agenda-skip-function
15601 (car (org-delete-all '(comment archive) skip)))
15602 (org-tags-match-list-sublevels t)
15603 (start-level (eq scope 'region-start-level))
15604 matcher res
15605 org-todo-keywords-for-agenda
15606 org-done-keywords-for-agenda
15607 org-todo-keyword-alist-for-agenda
15608 org-tag-alist-for-agenda
15609 org--matcher-tags-todo-only)
15611 (cond
15612 ((eq match t) (setq matcher t))
15613 ((eq match nil) (setq matcher t))
15614 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15616 (save-excursion
15617 (save-restriction
15618 (cond ((eq scope 'tree)
15619 (org-back-to-heading t)
15620 (org-narrow-to-subtree)
15621 (setq scope nil))
15622 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15623 (org-region-active-p))
15624 ;; If needed, set start-level to a string like "2"
15625 (when start-level
15626 (save-excursion
15627 (goto-char (region-beginning))
15628 (unless (org-at-heading-p) (outline-next-heading))
15629 (setq start-level (org-current-level))))
15630 (narrow-to-region (region-beginning)
15631 (save-excursion
15632 (goto-char (region-end))
15633 (unless (and (bolp) (org-at-heading-p))
15634 (outline-next-heading))
15635 (point)))
15636 (setq scope nil)))
15638 (if (not scope)
15639 (progn
15640 (org-agenda-prepare-buffers
15641 (and buffer-file-name (list buffer-file-name)))
15642 (setq res
15643 (org-scan-tags
15644 func matcher org--matcher-tags-todo-only start-level)))
15645 ;; Get the right scope
15646 (cond
15647 ((and scope (listp scope) (symbolp (car scope)))
15648 (setq scope (eval scope)))
15649 ((eq scope 'agenda)
15650 (setq scope (org-agenda-files t)))
15651 ((eq scope 'agenda-with-archives)
15652 (setq scope (org-agenda-files t))
15653 (setq scope (org-add-archive-files scope)))
15654 ((eq scope 'file)
15655 (setq scope (and buffer-file-name (list buffer-file-name))))
15656 ((eq scope 'file-with-archives)
15657 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15658 (org-agenda-prepare-buffers scope)
15659 (dolist (file scope)
15660 (with-current-buffer (org-find-base-buffer-visiting file)
15661 (org-with-wide-buffer
15662 (goto-char (point-min))
15663 (setq res
15664 (append
15666 (org-scan-tags
15667 func matcher org--matcher-tags-todo-only)))))))))
15668 res)))
15670 ;;; Properties API
15672 (defconst org-special-properties
15673 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15674 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15675 "The special properties valid in Org mode.
15676 These are properties that are not defined in the property drawer,
15677 but in some other way.")
15679 (defconst org-default-properties
15680 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15681 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15682 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15683 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15684 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15685 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15686 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15687 "Some properties that are used by Org mode for various purposes.
15688 Being in this list makes sure that they are offered for completion.")
15690 (defun org--valid-property-p (property)
15691 "Non nil when string PROPERTY is a valid property name."
15692 (not
15693 (or (equal property "")
15694 (string-match-p "\\s-" property))))
15696 (defun org--update-property-plist (key val props)
15697 "Associate KEY to VAL in alist PROPS.
15698 Modifications are made by side-effect. Return new alist."
15699 (let* ((appending (string= (substring key -1) "+"))
15700 (key (if appending (substring key 0 -1) key))
15701 (old (assoc-string key props t)))
15702 (if (not old) (cons (cons key val) props)
15703 (setcdr old (if appending (concat (cdr old) " " val) val))
15704 props)))
15706 (defun org-get-property-block (&optional beg force)
15707 "Return the (beg . end) range of the body of the property drawer.
15708 BEG is the beginning of the current subtree, or of the part
15709 before the first headline. If it is not given, it will be found.
15710 If the drawer does not exist, create it if FORCE is non-nil, or
15711 return nil."
15712 (org-with-wide-buffer
15713 (when beg (goto-char beg))
15714 (unless (org-before-first-heading-p)
15715 (let ((beg (cond (beg)
15716 ((or (not (featurep 'org-inlinetask))
15717 (org-inlinetask-in-task-p))
15718 (org-back-to-heading t))
15719 (t (org-with-limited-levels (org-back-to-heading t))))))
15720 (forward-line)
15721 (when (looking-at-p org-planning-line-re) (forward-line))
15722 (cond ((looking-at org-property-drawer-re)
15723 (forward-line)
15724 (cons (point) (progn (goto-char (match-end 0))
15725 (line-beginning-position))))
15726 (force
15727 (goto-char beg)
15728 (org-insert-property-drawer)
15729 (let ((pos (save-excursion (search-forward ":END:")
15730 (line-beginning-position))))
15731 (cons pos pos))))))))
15733 (defun org-at-property-p ()
15734 "Non-nil when point is inside a property drawer.
15735 See `org-property-re' for match data, if applicable."
15736 (save-excursion
15737 (beginning-of-line)
15738 (and (looking-at org-property-re)
15739 (let ((property-drawer (save-match-data (org-get-property-block))))
15740 (and property-drawer
15741 (>= (point) (car property-drawer))
15742 (< (point) (cdr property-drawer)))))))
15744 (defun org-property-action ()
15745 "Do an action on properties."
15746 (interactive)
15747 (unless (org-at-property-p) (user-error "Not at a property"))
15748 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15749 (let ((c (read-char-exclusive)))
15750 (cl-case c
15751 (?s (call-interactively #'org-set-property))
15752 (?d (call-interactively #'org-delete-property))
15753 (?D (call-interactively #'org-delete-property-globally))
15754 (?c (call-interactively #'org-compute-property-at-point))
15755 (otherwise (user-error "No such property action %c" c)))))
15757 (defun org-inc-effort ()
15758 "Increment the value of the effort property in the current entry."
15759 (interactive)
15760 (org-set-effort nil t))
15762 (defvar org-clock-effort) ; Defined in org-clock.el.
15763 (defvar org-clock-current-task) ; Defined in org-clock.el.
15764 (defun org-set-effort (&optional value increment)
15765 "Set the effort property of the current entry.
15766 With numerical prefix arg, use the nth allowed value, 0 stands for the
15767 10th allowed value.
15769 When INCREMENT is non-nil, set the property to the next allowed value."
15770 (interactive "P")
15771 (when (equal value 0) (setq value 10))
15772 (let* ((completion-ignore-case t)
15773 (prop org-effort-property)
15774 (cur (org-entry-get nil prop))
15775 (allowed (org-property-get-allowed-values nil prop 'table))
15776 (existing (mapcar 'list (org-property-values prop)))
15777 (heading (nth 4 (org-heading-components)))
15779 (val (cond
15780 ((stringp value) value)
15781 ((and allowed (integerp value))
15782 (or (car (nth (1- value) allowed))
15783 (car (org-last allowed))))
15784 ((and allowed increment)
15785 (or (cl-caadr (member (list cur) allowed))
15786 (user-error "Allowed effort values are not set")))
15787 (allowed
15788 (message "Select 1-9,0, [RET%s]: %s"
15789 (if cur (concat "=" cur) "")
15790 (mapconcat 'car allowed " "))
15791 (setq rpl (read-char-exclusive))
15792 (if (equal rpl ?\r)
15794 (setq rpl (- rpl ?0))
15795 (when (equal rpl 0) (setq rpl 10))
15796 (if (and (> rpl 0) (<= rpl (length allowed)))
15797 (car (nth (1- rpl) allowed))
15798 (org-completing-read "Effort: " allowed nil))))
15800 (org-completing-read
15801 (concat "Effort" (and cur (string-match "\\S-" cur)
15802 (concat " [" cur "]"))
15803 ": ")
15804 existing nil nil "" nil cur)))))
15805 (unless (equal (org-entry-get nil prop) val)
15806 (org-entry-put nil prop val))
15807 (org-refresh-property
15808 '((effort . identity)
15809 (effort-minutes . org-duration-string-to-minutes))
15810 val)
15811 (when (equal heading (bound-and-true-p org-clock-current-task))
15812 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15813 (org-clock-update-mode-line))
15814 (message "%s is now %s" prop val)))
15816 (defun org-entry-properties (&optional pom which)
15817 "Get all properties of the current entry.
15819 When POM is a buffer position, get all properties from the entry
15820 there instead.
15822 This includes the TODO keyword, the tags, time strings for
15823 deadline, scheduled, and clocking, and any additional properties
15824 defined in the entry.
15826 If WHICH is nil or `all', get all properties. If WHICH is
15827 `special' or `standard', only get that subclass. If WHICH is
15828 a string, only get that property.
15830 Return value is an alist. Keys are properties, as upcased
15831 strings."
15832 (org-with-point-at pom
15833 (when (and (derived-mode-p 'org-mode)
15834 (ignore-errors (org-back-to-heading t)))
15835 (catch 'exit
15836 (let* ((beg (point))
15837 (specific (and (stringp which) (upcase which)))
15838 (which (cond ((not specific) which)
15839 ((member specific org-special-properties) 'special)
15840 (t 'standard)))
15841 props)
15842 ;; Get the special properties, like TODO and TAGS.
15843 (when (memq which '(nil all special))
15844 (when (or (not specific) (string= specific "CLOCKSUM"))
15845 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15846 (when clocksum
15847 (push (cons "CLOCKSUM"
15848 (org-minutes-to-clocksum-string clocksum))
15849 props)))
15850 (when specific (throw 'exit props)))
15851 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15852 (let ((clocksumt (get-text-property (point)
15853 :org-clock-minutes-today)))
15854 (when clocksumt
15855 (push (cons "CLOCKSUM_T"
15856 (org-minutes-to-clocksum-string clocksumt))
15857 props)))
15858 (when specific (throw 'exit props)))
15859 (when (or (not specific) (string= specific "ITEM"))
15860 (let ((case-fold-search nil))
15861 (when (looking-at org-complex-heading-regexp)
15862 (push (cons "ITEM"
15863 (let ((title (match-string-no-properties 4)))
15864 (if (org-string-nw-p title)
15865 (org-remove-tabs title)
15866 "")))
15867 props)))
15868 (when specific (throw 'exit props)))
15869 (when (or (not specific) (string= specific "TODO"))
15870 (let ((case-fold-search nil))
15871 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15872 (push (cons "TODO" (match-string-no-properties 2)) props)))
15873 (when specific (throw 'exit props)))
15874 (when (or (not specific) (string= specific "PRIORITY"))
15875 (push (cons "PRIORITY"
15876 (if (looking-at org-priority-regexp)
15877 (match-string-no-properties 2)
15878 (char-to-string org-default-priority)))
15879 props)
15880 (when specific (throw 'exit props)))
15881 (when (or (not specific) (string= specific "FILE"))
15882 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15883 props)
15884 (when specific (throw 'exit props)))
15885 (when (or (not specific) (string= specific "TAGS"))
15886 (let ((value (org-string-nw-p (org-get-tags-string))))
15887 (when value (push (cons "TAGS" value) props)))
15888 (when specific (throw 'exit props)))
15889 (when (or (not specific) (string= specific "ALLTAGS"))
15890 (let ((value (org-get-tags-at)))
15891 (when value
15892 (push (cons "ALLTAGS"
15893 (format ":%s:" (mapconcat #'identity value ":")))
15894 props)))
15895 (when specific (throw 'exit props)))
15896 (when (or (not specific) (string= specific "BLOCKED"))
15897 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15898 (when specific (throw 'exit props)))
15899 (when (or (not specific)
15900 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15901 (forward-line)
15902 (when (looking-at-p org-planning-line-re)
15903 (end-of-line)
15904 (let ((bol (line-beginning-position))
15905 ;; Backward compatibility: time keywords used to
15906 ;; be configurable (before 8.3). Make sure we
15907 ;; get the correct keyword.
15908 (key-assoc `(("CLOSED" . ,org-closed-string)
15909 ("DEADLINE" . ,org-deadline-string)
15910 ("SCHEDULED" . ,org-scheduled-string))))
15911 (dolist (pair (if specific (list (assoc specific key-assoc))
15912 key-assoc))
15913 (save-excursion
15914 (when (search-backward (cdr pair) bol t)
15915 (goto-char (match-end 0))
15916 (skip-chars-forward " \t")
15917 (and (looking-at org-ts-regexp-both)
15918 (push (cons (car pair)
15919 (match-string-no-properties 0))
15920 props)))))))
15921 (when specific (throw 'exit props)))
15922 (when (or (not specific)
15923 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15924 (let ((find-ts
15925 (lambda (end ts)
15926 ;; Fix next time-stamp before END. TS is the
15927 ;; list of time-stamps found so far.
15928 (let ((ts ts)
15929 (regexp (cond
15930 ((string= specific "TIMESTAMP")
15931 org-ts-regexp)
15932 ((string= specific "TIMESTAMP_IA")
15933 org-ts-regexp-inactive)
15934 ((assoc "TIMESTAMP_IA" ts)
15935 org-ts-regexp)
15936 ((assoc "TIMESTAMP" ts)
15937 org-ts-regexp-inactive)
15938 (t org-ts-regexp-both))))
15939 (catch 'next
15940 (while (re-search-forward regexp end t)
15941 (backward-char)
15942 (let ((object (org-element-context)))
15943 ;; Accept to match timestamps in node
15944 ;; properties, too.
15945 (when (memq (org-element-type object)
15946 '(node-property timestamp))
15947 (let ((type
15948 (org-element-property :type object)))
15949 (cond
15950 ((and (memq type '(active active-range))
15951 (not (equal specific "TIMESTAMP_IA")))
15952 (unless (assoc "TIMESTAMP" ts)
15953 (push (cons "TIMESTAMP"
15954 (org-element-property
15955 :raw-value object))
15957 (when specific (throw 'exit ts))))
15958 ((and (memq type '(inactive inactive-range))
15959 (not (string= specific "TIMESTAMP")))
15960 (unless (assoc "TIMESTAMP_IA" ts)
15961 (push (cons "TIMESTAMP_IA"
15962 (org-element-property
15963 :raw-value object))
15965 (when specific (throw 'exit ts))))))
15966 ;; Both timestamp types are found,
15967 ;; move to next part.
15968 (when (= (length ts) 2) (throw 'next ts)))))
15969 ts)))))
15970 (goto-char beg)
15971 ;; First look for timestamps within headline.
15972 (let ((ts (funcall find-ts (line-end-position) nil)))
15973 (if (= (length ts) 2) (setq props (nconc ts props))
15974 (forward-line)
15975 ;; Then find timestamps in the section, skipping
15976 ;; planning line.
15977 (when (looking-at-p org-planning-line-re)
15978 (forward-line))
15979 (let ((end (save-excursion (outline-next-heading))))
15980 (setq props (nconc (funcall find-ts end ts) props))))))))
15981 ;; Get the standard properties, like :PROP:.
15982 (when (memq which '(nil all standard))
15983 ;; If we are looking after a specific property, delegate
15984 ;; to `org-entry-get', which is faster. However, make an
15985 ;; exception for "CATEGORY", since it can be also set
15986 ;; through keywords (i.e. #+CATEGORY).
15987 (if (and specific (not (equal specific "CATEGORY")))
15988 (let ((value (org-entry-get beg specific nil t)))
15989 (throw 'exit (and value (list (cons specific value)))))
15990 (let ((range (org-get-property-block beg)))
15991 (when range
15992 (let ((end (cdr range)) seen-base)
15993 (goto-char (car range))
15994 ;; Unlike to `org--update-property-plist', we
15995 ;; handle the case where base values is found
15996 ;; after its extension. We also forbid standard
15997 ;; properties to be named as special properties.
15998 (while (re-search-forward org-property-re end t)
15999 (let* ((key (upcase (match-string-no-properties 2)))
16000 (extendp (string-match-p "\\+\\'" key))
16001 (key-base (if extendp (substring key 0 -1) key))
16002 (value (match-string-no-properties 3)))
16003 (cond
16004 ((member-ignore-case key-base org-special-properties))
16005 (extendp
16006 (setq props
16007 (org--update-property-plist key value props)))
16008 ((member key seen-base))
16009 (t (push key seen-base)
16010 (let ((p (assoc-string key props t)))
16011 (if p (setcdr p (concat value " " (cdr p)))
16012 (push (cons key value) props))))))))))))
16013 (unless (assoc "CATEGORY" props)
16014 (push (cons "CATEGORY" (org-get-category beg)) props)
16015 (when (string= specific "CATEGORY") (throw 'exit props)))
16016 ;; Return value.
16017 props)))))
16019 (defun org-property--local-values (property literal-nil)
16020 "Return value for PROPERTY in current entry.
16021 Value is a list whose car is the base value for PROPERTY and cdr
16022 a list of accumulated values. Return nil if neither is found in
16023 the entry. Also return nil when PROPERTY is set to \"nil\",
16024 unless LITERAL-NIL is non-nil."
16025 (let ((range (org-get-property-block)))
16026 (when range
16027 (goto-char (car range))
16028 (let* ((case-fold-search t)
16029 (end (cdr range))
16030 (value
16031 ;; Base value.
16032 (save-excursion
16033 (let ((v (and (re-search-forward
16034 (org-re-property property nil t) end t)
16035 (match-string-no-properties 3))))
16036 (list (if literal-nil v (org-not-nil v)))))))
16037 ;; Find additional values.
16038 (let* ((property+ (org-re-property (concat property "+") nil t)))
16039 (while (re-search-forward property+ end t)
16040 (push (match-string-no-properties 3) value)))
16041 ;; Return final values.
16042 (and (not (equal value '(nil))) (nreverse value))))))
16044 (defun org-entry-get (pom property &optional inherit literal-nil)
16045 "Get value of PROPERTY for entry or content at point-or-marker POM.
16047 If INHERIT is non-nil and the entry does not have the property,
16048 then also check higher levels of the hierarchy. If INHERIT is
16049 the symbol `selective', use inheritance only if the setting in
16050 `org-use-property-inheritance' selects PROPERTY for inheritance.
16052 If the property is present but empty, the return value is the
16053 empty string. If the property is not present at all, nil is
16054 returned. In any other case, return the value as a string.
16055 Search is case-insensitive.
16057 If LITERAL-NIL is set, return the string value \"nil\" as
16058 a string, do not interpret it as the list atom nil. This is used
16059 for inheritance when a \"nil\" value can supersede a non-nil
16060 value higher up the hierarchy."
16061 (org-with-point-at pom
16062 (cond
16063 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
16064 ;; We need a special property. Use `org-entry-properties' to
16065 ;; retrieve it, but specify the wanted property.
16066 (cdr (assoc-string property (org-entry-properties nil property))))
16067 ((and inherit
16068 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
16069 (org-entry-get-with-inheritance property literal-nil))
16071 (let* ((local (org-property--local-values property literal-nil))
16072 (value (and local (mapconcat #'identity (delq nil local) " "))))
16073 (if literal-nil value (org-not-nil value)))))))
16075 (defun org-property-or-variable-value (var &optional inherit)
16076 "Check if there is a property fixing the value of VAR.
16077 If yes, return this value. If not, return the current value of the variable."
16078 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
16079 (if (and prop (stringp prop) (string-match "\\S-" prop))
16080 (read prop)
16081 (symbol-value var))))
16083 (defun org-entry-delete (pom property)
16084 "Delete PROPERTY from entry at point-or-marker POM.
16085 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16086 non-nil when a property was removed."
16087 (unless (member property org-special-properties)
16088 (org-with-point-at pom
16089 (let ((range (org-get-property-block)))
16090 (when range
16091 (let* ((begin (car range))
16092 (origin (cdr range))
16093 (end (copy-marker origin))
16094 (re (org-re-property
16095 (concat (regexp-quote property) "\\+?") t t)))
16096 (goto-char begin)
16097 (while (re-search-forward re end t)
16098 (delete-region (match-beginning 0) (line-beginning-position 2)))
16099 ;; If drawer is empty, remove it altogether.
16100 (when (= begin end)
16101 (delete-region (line-beginning-position 0)
16102 (line-beginning-position 2)))
16103 ;; Return non-nil if some property was removed.
16104 (prog1 (/= end origin) (set-marker end nil))))))))
16106 ;; Multi-values properties are properties that contain multiple values
16107 ;; These values are assumed to be single words, separated by whitespace.
16108 (defun org-entry-add-to-multivalued-property (pom property value)
16109 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16110 (let* ((old (org-entry-get pom property))
16111 (values (and old (org-split-string old "[ \t]"))))
16112 (setq value (org-entry-protect-space value))
16113 (unless (member value values)
16114 (setq values (append values (list value)))
16115 (org-entry-put pom property
16116 (mapconcat 'identity values " ")))))
16118 (defun org-entry-remove-from-multivalued-property (pom property value)
16119 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16120 (let* ((old (org-entry-get pom property))
16121 (values (and old (org-split-string old "[ \t]"))))
16122 (setq value (org-entry-protect-space value))
16123 (when (member value values)
16124 (setq values (delete value values))
16125 (org-entry-put pom property
16126 (mapconcat 'identity values " ")))))
16128 (defun org-entry-member-in-multivalued-property (pom property value)
16129 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16130 (let* ((old (org-entry-get pom property))
16131 (values (and old (org-split-string old "[ \t]"))))
16132 (setq value (org-entry-protect-space value))
16133 (member value values)))
16135 (defun org-entry-get-multivalued-property (pom property)
16136 "Return a list of values in a multivalued property."
16137 (let* ((value (org-entry-get pom property))
16138 (values (and value (org-split-string value "[ \t]"))))
16139 (mapcar 'org-entry-restore-space values)))
16141 (defun org-entry-put-multivalued-property (pom property &rest values)
16142 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16143 VALUES should be a list of strings. Spaces will be protected."
16144 (org-entry-put pom property
16145 (mapconcat 'org-entry-protect-space values " "))
16146 (let* ((value (org-entry-get pom property))
16147 (values (and value (org-split-string value "[ \t]"))))
16148 (mapcar 'org-entry-restore-space values)))
16150 (defun org-entry-protect-space (s)
16151 "Protect spaces and newline in string S."
16152 (while (string-match " " s)
16153 (setq s (replace-match "%20" t t s)))
16154 (while (string-match "\n" s)
16155 (setq s (replace-match "%0A" t t s)))
16158 (defun org-entry-restore-space (s)
16159 "Restore spaces and newline in string S."
16160 (while (string-match "%20" s)
16161 (setq s (replace-match " " t t s)))
16162 (while (string-match "%0A" s)
16163 (setq s (replace-match "\n" t t s)))
16166 (defvar org-entry-property-inherited-from (make-marker)
16167 "Marker pointing to the entry from where a property was inherited.
16168 Each call to `org-entry-get-with-inheritance' will set this marker to the
16169 location of the entry where the inheritance search matched. If there was
16170 no match, the marker will point nowhere.
16171 Note that also `org-entry-get' calls this function, if the INHERIT flag
16172 is set.")
16174 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16175 "Get PROPERTY of entry or content at point, search higher levels if needed.
16176 The search will stop at the first ancestor which has the property defined.
16177 If the value found is \"nil\", return nil to show that the property
16178 should be considered as undefined (this is the meaning of nil here).
16179 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16180 (move-marker org-entry-property-inherited-from nil)
16181 (org-with-wide-buffer
16182 (let (value)
16183 (catch 'exit
16184 (while t
16185 (let ((v (org-property--local-values property literal-nil)))
16186 (when v
16187 (setq value
16188 (concat (mapconcat #'identity (delq nil v) " ")
16189 (and value " ")
16190 value)))
16191 (cond
16192 ((car v)
16193 (org-back-to-heading t)
16194 (move-marker org-entry-property-inherited-from (point))
16195 (throw 'exit nil))
16196 ((org-up-heading-safe))
16198 (let ((global
16199 (cdr (or (assoc-string property org-file-properties t)
16200 (assoc-string property org-global-properties t)
16201 (assoc-string property org-global-properties-fixed t)))))
16202 (cond ((not global))
16203 (value (setq value (concat global " " value)))
16204 (t (setq value global))))
16205 (throw 'exit nil))))))
16206 (if literal-nil value (org-not-nil value)))))
16208 (defvar org-property-changed-functions nil
16209 "Hook called when the value of a property has changed.
16210 Each hook function should accept two arguments, the name of the property
16211 and the new value.")
16213 (defun org-entry-put (pom property value)
16214 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16216 If the value is nil, it is converted to the empty string. If it
16217 is not a string, an error is raised. Also raise an error on
16218 invalid property names.
16220 PROPERTY can be any regular property (see
16221 `org-special-properties'). It can also be \"TODO\",
16222 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16224 For the last two properties, VALUE may have any of the special
16225 values \"earlier\" and \"later\". The function then increases or
16226 decreases scheduled or deadline date by one day."
16227 (cond ((null value) (setq value ""))
16228 ((not (stringp value)) (error "Properties values should be strings"))
16229 ((not (org--valid-property-p property))
16230 (user-error "Invalid property name: \"%s\"" property)))
16231 (org-with-point-at pom
16232 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16233 (org-back-to-heading t)
16234 (org-with-limited-levels (org-back-to-heading t)))
16235 (let ((beg (point)))
16236 (cond
16237 ((equal property "TODO")
16238 (cond ((not (org-string-nw-p value)) (setq value 'none))
16239 ((not (member value org-todo-keywords-1))
16240 (user-error "\"%s\" is not a valid TODO state" value)))
16241 (org-todo value)
16242 (org-set-tags nil 'align))
16243 ((equal property "PRIORITY")
16244 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16245 (org-set-tags nil 'align))
16246 ((equal property "SCHEDULED")
16247 (forward-line)
16248 (if (and (looking-at-p org-planning-line-re)
16249 (re-search-forward
16250 org-scheduled-time-regexp (line-end-position) t))
16251 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16252 ((string= value "later") (org-timestamp-change 1 'day))
16253 ((string= value "") (org-schedule '(4)))
16254 (t (org-schedule nil value)))
16255 (if (member value '("earlier" "later" ""))
16256 (call-interactively #'org-schedule)
16257 (org-schedule nil value))))
16258 ((equal property "DEADLINE")
16259 (forward-line)
16260 (if (and (looking-at-p org-planning-line-re)
16261 (re-search-forward
16262 org-deadline-time-regexp (line-end-position) t))
16263 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16264 ((string= value "later") (org-timestamp-change 1 'day))
16265 ((string= value "") (org-deadline '(4)))
16266 (t (org-deadline nil value)))
16267 (if (member value '("earlier" "later" ""))
16268 (call-interactively #'org-deadline)
16269 (org-deadline nil value))))
16270 ((member property org-special-properties)
16271 (error "The %s property cannot be set with `org-entry-put'" property))
16273 (let* ((range (org-get-property-block beg 'force))
16274 (end (cdr range))
16275 (case-fold-search t))
16276 (goto-char (car range))
16277 (if (re-search-forward (org-re-property property nil t) end t)
16278 (progn (delete-region (match-beginning 0) (match-end 0))
16279 (goto-char (match-beginning 0)))
16280 (goto-char end)
16281 (insert "\n")
16282 (backward-char))
16283 (insert ":" property ":")
16284 (when value (insert " " value))
16285 (org-indent-line)))))
16286 (run-hook-with-args 'org-property-changed-functions property value)))
16288 (defun org-buffer-property-keys
16289 (&optional specials defaults columns ignore-malformed)
16290 "Get all property keys in the current buffer.
16292 When SPECIALS is non-nil, also list the special properties that
16293 reflect things like tags and TODO state.
16295 When DEFAULTS is non-nil, also include properties that has
16296 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16297 DESCRIPTION, LOCATION, and LOGGING and others.
16299 When COLUMNS in non-nil, also include property names given in
16300 COLUMN formats in the current buffer.
16302 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16303 automatically performed, such drawers will be silently ignored."
16304 (let ((case-fold-search t)
16305 (props (append
16306 (and specials org-special-properties)
16307 (and defaults (cons org-effort-property org-default-properties))
16308 nil)))
16309 (org-with-wide-buffer
16310 (goto-char (point-min))
16311 (while (re-search-forward org-property-start-re nil t)
16312 (let ((range (org-get-property-block)))
16313 (catch 'skip
16314 (unless range
16315 (when (and (not ignore-malformed)
16316 (not (org-before-first-heading-p))
16317 (y-or-n-p (format "Malformed drawer at %d, repair?"
16318 (line-beginning-position))))
16319 (org-get-property-block nil t))
16320 (throw 'skip nil))
16321 (goto-char (car range))
16322 (let ((begin (car range))
16323 (end (cdr range)))
16324 ;; Make sure that found property block is not located
16325 ;; before current point, as it would generate an infloop.
16326 ;; It can happen, for example, in the following
16327 ;; situation:
16329 ;; * Headline
16330 ;; :PROPERTIES:
16331 ;; ...
16332 ;; :END:
16333 ;; *************** Inlinetask
16334 ;; #+BEGIN_EXAMPLE
16335 ;; :PROPERTIES:
16336 ;; #+END_EXAMPLE
16338 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16339 (while (< (point) end)
16340 (let ((p (progn (looking-at org-property-re)
16341 (match-string-no-properties 2))))
16342 ;; Only add true property name, not extension symbol.
16343 (push (if (not (string-match-p "\\+\\'" p)) p
16344 (substring p 0 -1))
16345 props))
16346 (forward-line))))
16347 (outline-next-heading)))
16348 (when columns
16349 (goto-char (point-min))
16350 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16351 (let ((element (org-element-at-point)))
16352 (when (memq (org-element-type element) '(keyword node-property))
16353 (let ((value (org-element-property :value element))
16354 (start 0))
16355 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16356 (setq start (match-end 0))
16357 (let ((p (match-string-no-properties 1 value)))
16358 (unless (member-ignore-case p org-special-properties)
16359 (push p props))))))))))
16360 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16362 (defun org-property-values (key)
16363 "List all non-nil values of property KEY in current buffer."
16364 (org-with-wide-buffer
16365 (goto-char (point-min))
16366 (let ((case-fold-search t)
16367 (re (org-re-property key))
16368 values)
16369 (while (re-search-forward re nil t)
16370 (push (org-entry-get (point) key) values))
16371 (delete-dups values))))
16373 (defun org-insert-property-drawer ()
16374 "Insert a property drawer into the current entry."
16375 (org-with-wide-buffer
16376 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16377 (org-back-to-heading t)
16378 (org-with-limited-levels (org-back-to-heading t)))
16379 (forward-line)
16380 (when (looking-at-p org-planning-line-re) (forward-line))
16381 (unless (looking-at-p org-property-drawer-re)
16382 ;; Make sure we start editing a line from current entry, not from
16383 ;; next one. It prevents extending text properties or overlays
16384 ;; belonging to the latter.
16385 (when (bolp) (backward-char))
16386 (let ((begin (1+ (point)))
16387 (inhibit-read-only t))
16388 (insert "\n:PROPERTIES:\n:END:")
16389 (when (eobp) (insert "\n"))
16390 (org-indent-region begin (point))))))
16392 (defun org-insert-drawer (&optional arg drawer)
16393 "Insert a drawer at point.
16395 When optional argument ARG is non-nil, insert a property drawer.
16397 Optional argument DRAWER, when non-nil, is a string representing
16398 drawer's name. Otherwise, the user is prompted for a name.
16400 If a region is active, insert the drawer around that region
16401 instead.
16403 Point is left between drawer's boundaries."
16404 (interactive "P")
16405 (let* ((drawer (if arg "PROPERTIES"
16406 (or drawer (read-from-minibuffer "Drawer: ")))))
16407 (cond
16408 ;; With C-u, fall back on `org-insert-property-drawer'
16409 (arg (org-insert-property-drawer))
16410 ;; Check validity of suggested drawer's name.
16411 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16412 (user-error "Invalid drawer name"))
16413 ;; With an active region, insert a drawer at point.
16414 ((not (org-region-active-p))
16415 (progn
16416 (unless (bolp) (insert "\n"))
16417 (insert (format ":%s:\n\n:END:\n" drawer))
16418 (forward-line -2)))
16419 ;; Otherwise, insert the drawer at point
16421 (let ((rbeg (region-beginning))
16422 (rend (copy-marker (region-end))))
16423 (unwind-protect
16424 (progn
16425 (goto-char rbeg)
16426 (beginning-of-line)
16427 (when (save-excursion
16428 (re-search-forward org-outline-regexp-bol rend t))
16429 (user-error "Drawers cannot contain headlines"))
16430 ;; Position point at the beginning of the first
16431 ;; non-blank line in region. Insert drawer's opening
16432 ;; there, then indent it.
16433 (org-skip-whitespace)
16434 (beginning-of-line)
16435 (insert ":" drawer ":\n")
16436 (forward-line -1)
16437 (indent-for-tab-command)
16438 ;; Move point to the beginning of the first blank line
16439 ;; after the last non-blank line in region. Insert
16440 ;; drawer's closing, then indent it.
16441 (goto-char rend)
16442 (skip-chars-backward " \r\t\n")
16443 (insert "\n:END:")
16444 (deactivate-mark t)
16445 (indent-for-tab-command)
16446 (unless (eolp) (insert "\n")))
16447 ;; Clear marker, whatever the outcome of insertion is.
16448 (set-marker rend nil)))))))
16450 (defvar org-property-set-functions-alist nil
16451 "Property set function alist.
16452 Each entry should have the following format:
16454 (PROPERTY . READ-FUNCTION)
16456 The read function will be called with the same argument as
16457 `org-completing-read'.")
16459 (defun org-set-property-function (property)
16460 "Get the function that should be used to set PROPERTY.
16461 This is computed according to `org-property-set-functions-alist'."
16462 (or (cdr (assoc property org-property-set-functions-alist))
16463 'org-completing-read))
16465 (defun org-read-property-value (property)
16466 "Read PROPERTY value from user."
16467 (let* ((completion-ignore-case t)
16468 (allowed (org-property-get-allowed-values nil property 'table))
16469 (cur (org-entry-get nil property))
16470 (prompt (concat property " value"
16471 (if (and cur (string-match "\\S-" cur))
16472 (concat " [" cur "]") "") ": "))
16473 (set-function (org-set-property-function property))
16474 (val (if allowed
16475 (funcall set-function prompt allowed nil
16476 (not (get-text-property 0 'org-unrestricted
16477 (caar allowed))))
16478 (funcall set-function prompt
16479 (mapcar 'list (org-property-values property))
16480 nil nil "" nil cur))))
16481 (org-trim val)))
16483 (defvar org-last-set-property nil)
16484 (defvar org-last-set-property-value nil)
16485 (defun org-read-property-name ()
16486 "Read a property name."
16487 (let ((completion-ignore-case t)
16488 (default-prop (or (and (org-at-property-p)
16489 (match-string-no-properties 2))
16490 org-last-set-property)))
16491 (org-completing-read
16492 (concat "Property"
16493 (if default-prop (concat " [" default-prop "]") "")
16494 ": ")
16495 (mapcar #'list (org-buffer-property-keys nil t t))
16496 nil nil nil nil default-prop)))
16498 (defun org-set-property-and-value (use-last)
16499 "Allow to set [PROPERTY]: [value] direction from prompt.
16500 When use-default, don't even ask, just use the last
16501 \"[PROPERTY]: [value]\" string from the history."
16502 (interactive "P")
16503 (let* ((completion-ignore-case t)
16504 (pv (or (and use-last org-last-set-property-value)
16505 (org-completing-read
16506 "Enter a \"[Property]: [value]\" pair: "
16507 nil nil nil nil nil
16508 org-last-set-property-value)))
16509 prop val)
16510 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16511 (setq prop (match-string 1 pv)
16512 val (match-string 2 pv))
16513 (org-set-property prop val))))
16515 (defun org-set-property (property value)
16516 "In the current entry, set PROPERTY to VALUE.
16518 When called interactively, this will prompt for a property name, offering
16519 completion on existing and default properties. And then it will prompt
16520 for a value, offering completion either on allowed values (via an inherited
16521 xxx_ALL property) or on existing values in other instances of this property
16522 in the current file.
16524 Throw an error when trying to set a property with an invalid name."
16525 (interactive (list nil nil))
16526 (let ((property (or property (org-read-property-name))))
16527 ;; `org-entry-put' also makes the following check, but this one
16528 ;; avoids polluting `org-last-set-property' and
16529 ;; `org-last-set-property-value' needlessly.
16530 (unless (org--valid-property-p property)
16531 (user-error "Invalid property name: \"%s\"" property))
16532 (let ((value (or value (org-read-property-value property)))
16533 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16534 (setq org-last-set-property property)
16535 (setq org-last-set-property-value (concat property ": " value))
16536 ;; Possibly postprocess the inserted value:
16537 (when fn (setq value (funcall fn value)))
16538 (unless (equal (org-entry-get nil property) value)
16539 (org-entry-put nil property value)))))
16541 (defun org-find-property (property &optional value)
16542 "Find first entry in buffer that sets PROPERTY.
16544 When optional argument VALUE is non-nil, only consider an entry
16545 if it contains PROPERTY set to this value. If PROPERTY should be
16546 explicitly set to nil, use string \"nil\" for VALUE.
16548 Return position where the entry begins, or nil if there is no
16549 such entry. If narrowing is in effect, only search the visible
16550 part of the buffer."
16551 (save-excursion
16552 (goto-char (point-min))
16553 (let ((case-fold-search t)
16554 (re (org-re-property property nil (not value) value)))
16555 (catch 'exit
16556 (while (re-search-forward re nil t)
16557 (when (if value (org-at-property-p)
16558 (org-entry-get (point) property nil t))
16559 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16561 (defun org-delete-property (property)
16562 "In the current entry, delete PROPERTY."
16563 (interactive
16564 (let* ((completion-ignore-case t)
16565 (cat (org-entry-get (point) "CATEGORY"))
16566 (props0 (org-entry-properties nil 'standard))
16567 (props (if cat props0
16568 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16569 (prop (if (< 1 (length props))
16570 (completing-read "Property: " props nil t)
16571 (caar props))))
16572 (list prop)))
16573 (if (not property)
16574 (message "No property to delete in this entry")
16575 (org-entry-delete nil property)
16576 (message "Property \"%s\" deleted" property)))
16578 (defun org-delete-property-globally (property)
16579 "Remove PROPERTY globally, from all entries.
16580 This function ignores narrowing, if any."
16581 (interactive
16582 (let* ((completion-ignore-case t)
16583 (prop (completing-read
16584 "Globally remove property: "
16585 (mapcar #'list (org-buffer-property-keys)))))
16586 (list prop)))
16587 (org-with-wide-buffer
16588 (goto-char (point-min))
16589 (let ((count 0)
16590 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16591 (while (re-search-forward re nil t)
16592 (when (org-entry-delete (point) property) (cl-incf count)))
16593 (message "Property \"%s\" removed from %d entries" property count))))
16595 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16597 (defun org-compute-property-at-point ()
16598 "Compute the property at point.
16599 This looks for an enclosing column format, extracts the operator and
16600 then applies it to the property in the column format's scope."
16601 (interactive)
16602 (unless (org-at-property-p)
16603 (user-error "Not at a property"))
16604 (let ((prop (match-string-no-properties 2)))
16605 (org-columns-get-format-and-top-level)
16606 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16607 (user-error "No operator defined for property %s" prop))
16608 (org-columns-compute prop)))
16610 (defvar org-property-allowed-value-functions nil
16611 "Hook for functions supplying allowed values for a specific property.
16612 The functions must take a single argument, the name of the property, and
16613 return a flat list of allowed values. If \":ETC\" is one of
16614 the values, this means that these values are intended as defaults for
16615 completion, but that other values should be allowed too.
16616 The functions must return nil if they are not responsible for this
16617 property.")
16619 (defun org-property-get-allowed-values (pom property &optional table)
16620 "Get allowed values for the property PROPERTY.
16621 When TABLE is non-nil, return an alist that can directly be used for
16622 completion."
16623 (let (vals)
16624 (cond
16625 ((equal property "TODO")
16626 (setq vals (org-with-point-at pom
16627 (append org-todo-keywords-1 '("")))))
16628 ((equal property "PRIORITY")
16629 (let ((n org-lowest-priority))
16630 (while (>= n org-highest-priority)
16631 (push (char-to-string n) vals)
16632 (setq n (1- n)))))
16633 ((equal property "CATEGORY"))
16634 ((member property org-special-properties))
16635 ((setq vals (run-hook-with-args-until-success
16636 'org-property-allowed-value-functions property)))
16638 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16639 (when (and vals (string-match "\\S-" vals))
16640 (setq vals (car (read-from-string (concat "(" vals ")"))))
16641 (setq vals (mapcar (lambda (x)
16642 (cond ((stringp x) x)
16643 ((numberp x) (number-to-string x))
16644 ((symbolp x) (symbol-name x))
16645 (t "???")))
16646 vals)))))
16647 (when (member ":ETC" vals)
16648 (setq vals (remove ":ETC" vals))
16649 (org-add-props (car vals) '(org-unrestricted t)))
16650 (if table (mapcar 'list vals) vals)))
16652 (defun org-property-previous-allowed-value (&optional _previous)
16653 "Switch to the next allowed value for this property."
16654 (interactive)
16655 (org-property-next-allowed-value t))
16657 (defun org-property-next-allowed-value (&optional previous)
16658 "Switch to the next allowed value for this property."
16659 (interactive)
16660 (unless (org-at-property-p)
16661 (user-error "Not at a property"))
16662 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16663 (key (match-string 2))
16664 (value (match-string 3))
16665 (allowed (or (org-property-get-allowed-values (point) key)
16666 (and (member value '("[ ]" "[-]" "[X]"))
16667 '("[ ]" "[X]"))))
16668 (heading (save-match-data (nth 4 (org-heading-components))))
16669 nval)
16670 (unless allowed
16671 (user-error "Allowed values for this property have not been defined"))
16672 (when previous (setq allowed (reverse allowed)))
16673 (when (member value allowed)
16674 (setq nval (car (cdr (member value allowed)))))
16675 (setq nval (or nval (car allowed)))
16676 (when (equal nval value)
16677 (user-error "Only one allowed value for this property"))
16678 (org-at-property-p)
16679 (replace-match (concat " :" key ": " nval) t t)
16680 (org-indent-line)
16681 (beginning-of-line 1)
16682 (skip-chars-forward " \t")
16683 (when (equal prop org-effort-property)
16684 (org-refresh-property
16685 '((effort . identity)
16686 (effort-minutes . org-duration-string-to-minutes))
16687 nval)
16688 (when (string= org-clock-current-task heading)
16689 (setq org-clock-effort nval)
16690 (org-clock-update-mode-line)))
16691 (run-hook-with-args 'org-property-changed-functions key nval)))
16693 (defun org-find-olp (path &optional this-buffer)
16694 "Return a marker pointing to the entry at outline path OLP.
16695 If anything goes wrong, throw an error.
16696 You can wrap this call to catch the error like this:
16698 (condition-case msg
16699 (org-mobile-locate-entry (match-string 4))
16700 (error (nth 1 msg)))
16702 The return value will then be either a string with the error message,
16703 or a marker if everything is OK.
16705 If THIS-BUFFER is set, the outline path does not contain a file,
16706 only headings."
16707 (let* ((file (if this-buffer buffer-file-name (pop path)))
16708 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16709 (level 1)
16710 (lmin 1)
16711 (lmax 1)
16712 end found flevel)
16713 (unless buffer (error "File not found :%s" file))
16714 (with-current-buffer buffer
16715 (org-with-wide-buffer
16716 (goto-char (point-min))
16717 (dolist (heading path)
16718 (let ((re (format org-complex-heading-regexp-format
16719 (regexp-quote heading)))
16720 (cnt 0))
16721 (while (re-search-forward re end t)
16722 (setq level (- (match-end 1) (match-beginning 1)))
16723 (when (and (>= level lmin) (<= level lmax))
16724 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16725 (when (= cnt 0)
16726 (error "Heading not found on level %d: %s" lmax heading))
16727 (when (> cnt 1)
16728 (error "Heading not unique on level %d: %s" lmax heading))
16729 (goto-char found)
16730 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16731 (setq end (save-excursion (org-end-of-subtree t t)))))
16732 (when (org-at-heading-p)
16733 (point-marker))))))
16735 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16736 "Find node HEADING in BUFFER.
16737 Return a marker to the heading if it was found, or nil if not.
16738 If POS-ONLY is set, return just the position instead of a marker.
16740 The heading text must match exact, but it may have a TODO keyword,
16741 a priority cookie and tags in the standard locations."
16742 (with-current-buffer (or buffer (current-buffer))
16743 (org-with-wide-buffer
16744 (goto-char (point-min))
16745 (let (case-fold-search)
16746 (when (re-search-forward
16747 (format org-complex-heading-regexp-format
16748 (regexp-quote heading)) nil t)
16749 (if pos-only
16750 (match-beginning 0)
16751 (move-marker (make-marker) (match-beginning 0))))))))
16753 (defun org-find-exact-heading-in-directory (heading &optional dir)
16754 "Find Org node headline HEADING in all .org files in directory DIR.
16755 When the target headline is found, return a marker to this location."
16756 (let ((files (directory-files (or dir default-directory)
16757 t "\\`[^.#].*\\.org\\'"))
16758 visiting m buffer)
16759 (catch 'found
16760 (dolist (file files)
16761 (message "trying %s" file)
16762 (setq visiting (org-find-base-buffer-visiting file))
16763 (setq buffer (or visiting (find-file-noselect file)))
16764 (setq m (org-find-exact-headline-in-buffer
16765 heading buffer))
16766 (when (and (not m) (not visiting)) (kill-buffer buffer))
16767 (and m (throw 'found m))))))
16769 (defun org-find-entry-with-id (ident)
16770 "Locate the entry that contains the ID property with exact value IDENT.
16771 IDENT can be a string, a symbol or a number, this function will search for
16772 the string representation of it.
16773 Return the position where this entry starts, or nil if there is no such entry."
16774 (interactive "sID: ")
16775 (let ((id (cond
16776 ((stringp ident) ident)
16777 ((symbolp ident) (symbol-name ident))
16778 ((numberp ident) (number-to-string ident))
16779 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16780 (org-with-wide-buffer (org-find-property "ID" id))))
16782 ;;;; Timestamps
16784 (defvar org-last-changed-timestamp nil)
16785 (defvar org-last-inserted-timestamp nil
16786 "The last time stamp inserted with `org-insert-time-stamp'.")
16787 (defvar org-ts-what) ; dynamically scoped parameter
16789 (defun org-time-stamp (arg &optional inactive)
16790 "Prompt for a date/time and insert a time stamp.
16792 If the user specifies a time like HH:MM or if this command is
16793 called with at least one prefix argument, the time stamp contains
16794 the date and the time. Otherwise, only the date is included.
16796 All parts of a date not specified by the user are filled in from
16797 the timestamp at point, if any, or the current date/time
16798 otherwise.
16800 If there is already a timestamp at the cursor, it is replaced.
16802 With two universal prefix arguments, insert an active timestamp
16803 with the current time without prompting the user.
16805 When called from lisp, the timestamp is inactive if INACTIVE is
16806 non-nil."
16807 (interactive "P")
16808 (let* ((ts (cond
16809 ((org-at-date-range-p t)
16810 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16811 ((org-at-timestamp-p t) (match-string 0))))
16812 ;; Default time is either the timestamp at point or today.
16813 ;; When entering a range, only the range start is considered.
16814 (default-time (if (not ts) (current-time)
16815 (apply #'encode-time (org-parse-time-string ts))))
16816 (default-input (and ts (org-get-compact-tod ts)))
16817 (repeater (and ts
16818 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16819 (match-string 0 ts)))
16820 org-time-was-given
16821 org-end-time-was-given
16822 (time
16823 (and (if (equal arg '(16)) (current-time)
16824 ;; Preserve `this-command' and `last-command'.
16825 (let ((this-command this-command)
16826 (last-command last-command))
16827 (org-read-date
16828 arg 'totime nil nil default-time default-input
16829 inactive))))))
16830 (cond
16831 ((and ts
16832 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16833 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16834 (insert "--")
16835 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16837 ;; Make sure we're on a timestamp. When in the middle of a date
16838 ;; range, move arbitrarily to range end.
16839 (unless (org-at-timestamp-p t)
16840 (skip-chars-forward "-")
16841 (org-at-timestamp-p t))
16842 (replace-match "")
16843 (setq org-last-changed-timestamp
16844 (org-insert-time-stamp
16845 time (or org-time-was-given arg)
16846 inactive nil nil (list org-end-time-was-given)))
16847 (when repeater
16848 (backward-char)
16849 (insert " " repeater)
16850 (setq org-last-changed-timestamp
16851 (concat (substring org-last-inserted-timestamp 0 -1)
16852 " " repeater ">")))
16853 (message "Timestamp updated"))
16854 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16855 (t (org-insert-time-stamp
16856 time (or org-time-was-given arg) inactive nil nil
16857 (list org-end-time-was-given))))))
16859 ;; FIXME: can we use this for something else, like computing time differences?
16860 (defun org-get-compact-tod (s)
16861 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16862 (let* ((t1 (match-string 1 s))
16863 (h1 (string-to-number (match-string 2 s)))
16864 (m1 (string-to-number (match-string 3 s)))
16865 (t2 (and (match-end 4) (match-string 5 s)))
16866 (h2 (and t2 (string-to-number (match-string 6 s))))
16867 (m2 (and t2 (string-to-number (match-string 7 s))))
16868 dh dm)
16869 (if (not t2)
16871 (setq dh (- h2 h1) dm (- m2 m1))
16872 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16873 (concat t1 "+" (number-to-string dh)
16874 (and (/= 0 dm) (format ":%02d" dm)))))))
16876 (defun org-time-stamp-inactive (&optional arg)
16877 "Insert an inactive time stamp.
16878 An inactive time stamp is enclosed in square brackets instead of angle
16879 brackets. It is inactive in the sense that it does not trigger agenda entries,
16880 does not link to the calendar and cannot be changed with the S-cursor keys.
16881 So these are more for recording a certain time/date."
16882 (interactive "P")
16883 (org-time-stamp arg 'inactive))
16885 (defvar org-date-ovl (make-overlay 1 1))
16886 (overlay-put org-date-ovl 'face 'org-date-selected)
16887 (delete-overlay org-date-ovl)
16889 (defvar org-ans1) ; dynamically scoped parameter
16890 (defvar org-ans2) ; dynamically scoped parameter
16892 (defvar org-plain-time-of-day-regexp) ; defined below
16894 (defvar org-overriding-default-time nil) ; dynamically scoped
16895 (defvar org-read-date-overlay nil)
16896 (defvar org-dcst nil) ; dynamically scoped
16897 (defvar org-read-date-history nil)
16898 (defvar org-read-date-final-answer nil)
16899 (defvar org-read-date-analyze-futurep nil)
16900 (defvar org-read-date-analyze-forced-year nil)
16901 (defvar org-read-date-inactive)
16903 (defvar org-read-date-minibuffer-local-map
16904 (let* ((map (make-sparse-keymap)))
16905 (set-keymap-parent map minibuffer-local-map)
16906 (org-defkey map (kbd ".")
16907 (lambda () (interactive)
16908 ;; Are we at the beginning of the prompt?
16909 (if (looking-back "^[^:]+: "
16910 (let ((inhibit-field-text-motion t))
16911 (line-beginning-position)))
16912 (org-eval-in-calendar '(calendar-goto-today))
16913 (insert "."))))
16914 (org-defkey map (kbd "C-.")
16915 (lambda () (interactive)
16916 (org-eval-in-calendar '(calendar-goto-today))))
16917 (org-defkey map [(meta shift left)]
16918 (lambda () (interactive)
16919 (org-eval-in-calendar '(calendar-backward-month 1))))
16920 (org-defkey map [(meta shift right)]
16921 (lambda () (interactive)
16922 (org-eval-in-calendar '(calendar-forward-month 1))))
16923 (org-defkey map [(meta shift up)]
16924 (lambda () (interactive)
16925 (org-eval-in-calendar '(calendar-backward-year 1))))
16926 (org-defkey map [(meta shift down)]
16927 (lambda () (interactive)
16928 (org-eval-in-calendar '(calendar-forward-year 1))))
16929 (org-defkey map [?\e (shift left)]
16930 (lambda () (interactive)
16931 (org-eval-in-calendar '(calendar-backward-month 1))))
16932 (org-defkey map [?\e (shift right)]
16933 (lambda () (interactive)
16934 (org-eval-in-calendar '(calendar-forward-month 1))))
16935 (org-defkey map [?\e (shift up)]
16936 (lambda () (interactive)
16937 (org-eval-in-calendar '(calendar-backward-year 1))))
16938 (org-defkey map [?\e (shift down)]
16939 (lambda () (interactive)
16940 (org-eval-in-calendar '(calendar-forward-year 1))))
16941 (org-defkey map [(shift up)]
16942 (lambda () (interactive)
16943 (org-eval-in-calendar '(calendar-backward-week 1))))
16944 (org-defkey map [(shift down)]
16945 (lambda () (interactive)
16946 (org-eval-in-calendar '(calendar-forward-week 1))))
16947 (org-defkey map [(shift left)]
16948 (lambda () (interactive)
16949 (org-eval-in-calendar '(calendar-backward-day 1))))
16950 (org-defkey map [(shift right)]
16951 (lambda () (interactive)
16952 (org-eval-in-calendar '(calendar-forward-day 1))))
16953 (org-defkey map "!"
16954 (lambda () (interactive)
16955 (org-eval-in-calendar '(diary-view-entries))
16956 (message "")))
16957 (org-defkey map ">"
16958 (lambda () (interactive)
16959 (org-eval-in-calendar '(calendar-scroll-left 1))))
16960 (org-defkey map "<"
16961 (lambda () (interactive)
16962 (org-eval-in-calendar '(calendar-scroll-right 1))))
16963 (org-defkey map "\C-v"
16964 (lambda () (interactive)
16965 (org-eval-in-calendar
16966 '(calendar-scroll-left-three-months 1))))
16967 (org-defkey map "\M-v"
16968 (lambda () (interactive)
16969 (org-eval-in-calendar
16970 '(calendar-scroll-right-three-months 1))))
16971 map)
16972 "Keymap for minibuffer commands when using `org-read-date'.")
16974 (defvar org-def)
16975 (defvar org-defdecode)
16976 (defvar org-with-time)
16978 (defvar calendar-setup) ; Dynamically scoped.
16979 (defun org-read-date (&optional with-time to-time from-string prompt
16980 default-time default-input inactive)
16981 "Read a date, possibly a time, and make things smooth for the user.
16982 The prompt will suggest to enter an ISO date, but you can also enter anything
16983 which will at least partially be understood by `parse-time-string'.
16984 Unrecognized parts of the date will default to the current day, month, year,
16985 hour and minute. If this command is called to replace a timestamp at point,
16986 or to enter the second timestamp of a range, the default time is taken
16987 from the existing stamp. Furthermore, the command prefers the future,
16988 so if you are giving a date where the year is not given, and the day-month
16989 combination is already past in the current year, it will assume you
16990 mean next year. For details, see the manual. A few examples:
16992 3-2-5 --> 2003-02-05
16993 feb 15 --> currentyear-02-15
16994 2/15 --> currentyear-02-15
16995 sep 12 9 --> 2009-09-12
16996 12:45 --> today 12:45
16997 22 sept 0:34 --> currentyear-09-22 0:34
16998 12 --> currentyear-currentmonth-12
16999 Fri --> nearest Friday after today
17000 -Tue --> last Tuesday
17001 etc.
17003 Furthermore you can specify a relative date by giving, as the *first* thing
17004 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
17005 change in days weeks, months, years.
17006 With a single plus or minus, the date is relative to today. With a double
17007 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17008 +4d --> four days from today
17009 +4 --> same as above
17010 +2w --> two weeks from today
17011 ++5 --> five days from default date
17013 The function understands only English month and weekday abbreviations.
17015 While prompting, a calendar is popped up - you can also select the
17016 date with the mouse (button 1). The calendar shows a period of three
17017 months. To scroll it to other months, use the keys `>' and `<'.
17018 If you don't like the calendar, turn it off with
17019 (setq org-read-date-popup-calendar nil)
17021 With optional argument TO-TIME, the date will immediately be converted
17022 to an internal time.
17023 With an optional argument WITH-TIME, the prompt will suggest to
17024 also insert a time. Note that when WITH-TIME is not set, you can
17025 still enter a time, and this function will inform the calling routine
17026 about this change. The calling routine may then choose to change the
17027 format used to insert the time stamp into the buffer to include the time.
17028 With optional argument FROM-STRING, read from this string instead from
17029 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17030 the time/date that is used for everything that is not specified by the
17031 user."
17032 (require 'parse-time)
17033 (let* ((org-with-time with-time)
17034 (org-time-stamp-rounding-minutes
17035 (if (equal org-with-time '(16))
17036 '(0 0)
17037 org-time-stamp-rounding-minutes))
17038 (org-dcst org-display-custom-times)
17039 (ct (org-current-time))
17040 (org-def (or org-overriding-default-time default-time ct))
17041 (org-defdecode (decode-time org-def))
17042 (cur-frame (selected-frame))
17043 (mouse-autoselect-window nil) ; Don't let the mouse jump
17044 (calendar-setup
17045 (and (eq calendar-setup 'calendar-only) 'calendar-only))
17046 (calendar-move-hook nil)
17047 (calendar-view-diary-initially-flag nil)
17048 (calendar-view-holidays-initially-flag nil)
17049 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
17050 ;; Rationalize `org-def' and `org-defdecode', if required.
17051 (when (< (nth 2 org-defdecode) org-extend-today-until)
17052 (setf (nth 2 org-defdecode) -1)
17053 (setf (nth 1 org-defdecode) 59)
17054 (setq org-def (apply #'encode-time org-defdecode))
17055 (setq org-defdecode (decode-time org-def)))
17056 (let* ((timestr (format-time-string
17057 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
17058 org-def))
17059 (prompt (concat (if prompt (concat prompt " ") "")
17060 (format "Date+time [%s]: " timestr))))
17061 (cond
17062 (from-string (setq ans from-string))
17063 (org-read-date-popup-calendar
17064 (save-excursion
17065 (save-window-excursion
17066 (calendar)
17067 (when (eq calendar-setup 'calendar-only)
17068 (setq cal-frame
17069 (window-frame (get-buffer-window "*Calendar*" 'visible)))
17070 (select-frame cal-frame))
17071 (org-eval-in-calendar '(setq cursor-type nil) t)
17072 (unwind-protect
17073 (progn
17074 (calendar-forward-day (- (time-to-days org-def)
17075 (calendar-absolute-from-gregorian
17076 (calendar-current-date))))
17077 (org-eval-in-calendar nil t)
17078 (let* ((old-map (current-local-map))
17079 (map (copy-keymap calendar-mode-map))
17080 (minibuffer-local-map
17081 (copy-keymap org-read-date-minibuffer-local-map)))
17082 (org-defkey map (kbd "RET") 'org-calendar-select)
17083 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17084 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17085 (unwind-protect
17086 (progn
17087 (use-local-map map)
17088 (setq org-read-date-inactive inactive)
17089 (add-hook 'post-command-hook 'org-read-date-display)
17090 (setq org-ans0
17091 (read-string prompt
17092 default-input
17093 'org-read-date-history
17094 nil))
17095 ;; org-ans0: from prompt
17096 ;; org-ans1: from mouse click
17097 ;; org-ans2: from calendar motion
17098 (setq ans
17099 (concat org-ans0 " " (or org-ans1 org-ans2))))
17100 (remove-hook 'post-command-hook 'org-read-date-display)
17101 (use-local-map old-map)
17102 (when org-read-date-overlay
17103 (delete-overlay org-read-date-overlay)
17104 (setq org-read-date-overlay nil)))))
17105 (bury-buffer "*Calendar*")
17106 (when cal-frame
17107 (delete-frame cal-frame)
17108 (select-frame-set-input-focus cur-frame))))))
17110 (t ; Naked prompt only
17111 (unwind-protect
17112 (setq ans (read-string prompt default-input
17113 'org-read-date-history timestr))
17114 (when org-read-date-overlay
17115 (delete-overlay org-read-date-overlay)
17116 (setq org-read-date-overlay nil))))))
17118 (setq final (org-read-date-analyze ans org-def org-defdecode))
17120 (when org-read-date-analyze-forced-year
17121 (message "Year was forced into %s"
17122 (if org-read-date-force-compatible-dates
17123 "compatible range (1970-2037)"
17124 "range representable on this machine"))
17125 (ding))
17127 ;; One round trip to get rid of 34th of August and stuff like that....
17128 (setq final (decode-time (apply 'encode-time final)))
17130 (setq org-read-date-final-answer ans)
17132 (if to-time
17133 (apply 'encode-time final)
17134 (if (and (boundp 'org-time-was-given) org-time-was-given)
17135 (format "%04d-%02d-%02d %02d:%02d"
17136 (nth 5 final) (nth 4 final) (nth 3 final)
17137 (nth 2 final) (nth 1 final))
17138 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17140 (defun org-read-date-display ()
17141 "Display the current date prompt interpretation in the minibuffer."
17142 (when org-read-date-display-live
17143 (when org-read-date-overlay
17144 (delete-overlay org-read-date-overlay))
17145 (when (minibufferp (current-buffer))
17146 (save-excursion
17147 (end-of-line 1)
17148 (while (not (equal (buffer-substring
17149 (max (point-min) (- (point) 4)) (point))
17150 " "))
17151 (insert " ")))
17152 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17153 " " (or org-ans1 org-ans2)))
17154 (org-end-time-was-given nil)
17155 (f (org-read-date-analyze ans org-def org-defdecode))
17156 (fmts (if org-dcst
17157 org-time-stamp-custom-formats
17158 org-time-stamp-formats))
17159 (fmt (if (or org-with-time
17160 (and (boundp 'org-time-was-given) org-time-was-given))
17161 (cdr fmts)
17162 (car fmts)))
17163 (txt (format-time-string fmt (apply 'encode-time f)))
17164 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17165 (txt (concat "=> " txt)))
17166 (when (and org-end-time-was-given
17167 (string-match org-plain-time-of-day-regexp txt))
17168 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17169 org-end-time-was-given
17170 (substring txt (match-end 0)))))
17171 (when org-read-date-analyze-futurep
17172 (setq txt (concat txt " (=>F)")))
17173 (setq org-read-date-overlay
17174 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17175 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17177 (defun org-read-date-analyze (ans def defdecode)
17178 "Analyze the combined answer of the date prompt."
17179 ;; FIXME: cleanup and comment
17180 ;; Pass `current-time' result to `decode-time' (instead of calling
17181 ;; without arguments) so that only `current-time' has to be
17182 ;; overriden in tests.
17183 (let ((org-def def)
17184 (org-defdecode defdecode)
17185 (nowdecode (decode-time (current-time)))
17186 delta deltan deltaw deltadef year month day
17187 hour minute second wday pm h2 m2 tl wday1
17188 iso-year iso-weekday iso-week iso-date futurep kill-year)
17189 (setq org-read-date-analyze-futurep nil
17190 org-read-date-analyze-forced-year nil)
17191 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17192 (setq ans "+0"))
17194 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17195 (setq ans (replace-match "" t t ans)
17196 deltan (car delta)
17197 deltaw (nth 1 delta)
17198 deltadef (nth 2 delta)))
17200 ;; Check if there is an iso week date in there. If yes, store the
17201 ;; info and postpone interpreting it until the rest of the parsing
17202 ;; is done.
17203 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17204 (setq iso-year (when (match-end 1)
17205 (org-small-year-to-year
17206 (string-to-number (match-string 1 ans))))
17207 iso-weekday (when (match-end 3)
17208 (string-to-number (match-string 3 ans)))
17209 iso-week (string-to-number (match-string 2 ans)))
17210 (setq ans (replace-match "" t t ans)))
17212 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17213 (when (string-match
17214 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17215 (setq year (if (match-end 2)
17216 (string-to-number (match-string 2 ans))
17217 (progn (setq kill-year t)
17218 (string-to-number (format-time-string "%Y"))))
17219 month (string-to-number (match-string 3 ans))
17220 day (string-to-number (match-string 4 ans)))
17221 (setq year (org-small-year-to-year year))
17222 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17223 t nil ans)))
17225 ;; Help matching dotted european dates
17226 (when (string-match
17227 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17228 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17229 (setq kill-year t)
17230 (string-to-number (format-time-string "%Y")))
17231 day (string-to-number (match-string 1 ans))
17232 month (string-to-number (match-string 2 ans))
17233 ans (replace-match (format "%04d-%02d-%02d" year month day)
17234 t nil ans)))
17236 ;; Help matching american dates, like 5/30 or 5/30/7
17237 (when (string-match
17238 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17239 (setq year (if (match-end 4)
17240 (string-to-number (match-string 4 ans))
17241 (progn (setq kill-year t)
17242 (string-to-number (format-time-string "%Y"))))
17243 month (string-to-number (match-string 1 ans))
17244 day (string-to-number (match-string 2 ans)))
17245 (setq year (org-small-year-to-year year))
17246 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17247 t nil ans)))
17248 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17249 ;; If there is a time with am/pm, and *no* time without it, we convert
17250 ;; so that matching will be successful.
17251 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17252 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17253 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17254 (setq hour (string-to-number (match-string 1 ans))
17255 minute (if (match-end 3)
17256 (string-to-number (match-string 3 ans))
17258 pm (equal ?p
17259 (string-to-char (downcase (match-string 4 ans)))))
17260 (if (and (= hour 12) (not pm))
17261 (setq hour 0)
17262 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17263 (setq ans (replace-match (format "%02d:%02d" hour minute)
17264 t t ans))))
17266 ;; Check if a time range is given as a duration
17267 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17268 (setq hour (string-to-number (match-string 1 ans))
17269 h2 (+ hour (string-to-number (match-string 3 ans)))
17270 minute (string-to-number (match-string 2 ans))
17271 m2 (+ minute (if (match-end 5) (string-to-number
17272 (match-string 5 ans))0)))
17273 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17274 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17275 t t ans)))
17277 ;; Check if there is a time range
17278 (when (boundp 'org-end-time-was-given)
17279 (setq org-time-was-given nil)
17280 (when (and (string-match org-plain-time-of-day-regexp ans)
17281 (match-end 8))
17282 (setq org-end-time-was-given (match-string 8 ans))
17283 (setq ans (concat (substring ans 0 (match-beginning 7))
17284 (substring ans (match-end 7))))))
17286 (setq tl (parse-time-string ans)
17287 day (or (nth 3 tl) (nth 3 org-defdecode))
17288 month
17289 (cond ((nth 4 tl))
17290 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17291 ;; Day was specified. Make sure DAY+MONTH
17292 ;; combination happens in the future.
17293 ((nth 3 tl)
17294 (setq futurep t)
17295 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17296 (nth 4 nowdecode)))
17297 (t (nth 4 org-defdecode)))
17298 year
17299 (cond ((and (not kill-year) (nth 5 tl)))
17300 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17301 ;; Month was guessed in the future and is at least
17302 ;; equal to NOWDECODE's. Fix year accordingly.
17303 (futurep
17304 (if (or (> month (nth 4 nowdecode))
17305 (>= day (nth 3 nowdecode)))
17306 (nth 5 nowdecode)
17307 (1+ (nth 5 nowdecode))))
17308 ;; Month was specified. Make sure MONTH+YEAR
17309 ;; combination happens in the future.
17310 ((nth 4 tl)
17311 (setq futurep t)
17312 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17313 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17314 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17315 (t (nth 5 nowdecode))))
17316 (t (nth 5 org-defdecode)))
17317 hour (or (nth 2 tl) (nth 2 org-defdecode))
17318 minute (or (nth 1 tl) (nth 1 org-defdecode))
17319 second (or (nth 0 tl) 0)
17320 wday (nth 6 tl))
17322 (when (and (eq org-read-date-prefer-future 'time)
17323 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17324 (equal day (nth 3 nowdecode))
17325 (equal month (nth 4 nowdecode))
17326 (equal year (nth 5 nowdecode))
17327 (nth 2 tl)
17328 (or (< (nth 2 tl) (nth 2 nowdecode))
17329 (and (= (nth 2 tl) (nth 2 nowdecode))
17330 (nth 1 tl)
17331 (< (nth 1 tl) (nth 1 nowdecode)))))
17332 (setq day (1+ day)
17333 futurep t))
17335 ;; Special date definitions below
17336 (cond
17337 (iso-week
17338 ;; There was an iso week
17339 (require 'cal-iso)
17340 (setq futurep nil)
17341 (setq year (or iso-year year)
17342 day (or iso-weekday wday 1)
17343 wday nil ; to make sure that the trigger below does not match
17344 iso-date (calendar-gregorian-from-absolute
17345 (calendar-iso-to-absolute
17346 (list iso-week day year))))
17347 ; FIXME: Should we also push ISO weeks into the future?
17348 ; (when (and org-read-date-prefer-future
17349 ; (not iso-year)
17350 ; (< (calendar-absolute-from-gregorian iso-date)
17351 ; (time-to-days (current-time))))
17352 ; (setq year (1+ year)
17353 ; iso-date (calendar-gregorian-from-absolute
17354 ; (calendar-iso-to-absolute
17355 ; (list iso-week day year)))))
17356 (setq month (car iso-date)
17357 year (nth 2 iso-date)
17358 day (nth 1 iso-date)))
17359 (deltan
17360 (setq futurep nil)
17361 (unless deltadef
17362 ;; Pass `current-time' result to `decode-time' (instead of
17363 ;; calling without arguments) so that only `current-time' has
17364 ;; to be overriden in tests.
17365 (let ((now (decode-time (current-time))))
17366 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17367 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17368 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17369 ((equal deltaw "m") (setq month (+ month deltan)))
17370 ((equal deltaw "y") (setq year (+ year deltan)))))
17371 ((and wday (not (nth 3 tl)))
17372 ;; Weekday was given, but no day, so pick that day in the week
17373 ;; on or after the derived date.
17374 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17375 (unless (equal wday wday1)
17376 (setq day (+ day (% (- wday wday1 -7) 7))))))
17377 (when (and (boundp 'org-time-was-given)
17378 (nth 2 tl))
17379 (setq org-time-was-given t))
17380 (when (< year 100) (setq year (+ 2000 year)))
17381 ;; Check of the date is representable
17382 (if org-read-date-force-compatible-dates
17383 (progn
17384 (when (< year 1970)
17385 (setq year 1970 org-read-date-analyze-forced-year t))
17386 (when (> year 2037)
17387 (setq year 2037 org-read-date-analyze-forced-year t)))
17388 (condition-case nil
17389 (ignore (encode-time second minute hour day month year))
17390 (error
17391 (setq year (nth 5 org-defdecode))
17392 (setq org-read-date-analyze-forced-year t))))
17393 (setq org-read-date-analyze-futurep futurep)
17394 (list second minute hour day month year)))
17396 (defvar parse-time-weekdays)
17397 (defun org-read-date-get-relative (s today default)
17398 "Check string S for special relative date string.
17399 TODAY and DEFAULT are internal times, for today and for a default.
17400 Return shift list (N what def-flag)
17401 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17402 N is the number of WHATs to shift.
17403 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17404 the DEFAULT date rather than TODAY."
17405 (require 'parse-time)
17406 (when (and
17407 (string-match
17408 (concat
17409 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17410 "\\([0-9]+\\)?"
17411 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17412 "\\([ \t]\\|$\\)") s)
17413 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17414 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17415 (string-to-char (substring (match-string 1 s) -1))
17416 ?+))
17417 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17418 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17419 (what (if (match-end 3) (match-string 3 s) "d"))
17420 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17421 (date (if rel default today))
17422 (wday (nth 6 (decode-time date)))
17423 delta)
17424 (if wday1
17425 (progn
17426 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17427 (when (= delta 0) (setq delta 7))
17428 (when (= dir ?-)
17429 (setq delta (- delta 7))
17430 (when (= delta 0) (setq delta -7)))
17431 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17432 (list delta "d" rel))
17433 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17435 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17436 "Turn a user-specified date into the internal representation.
17437 The internal representation needed by the calendar is (month day year).
17438 This is a wrapper to handle the brain-dead convention in calendar that
17439 user function argument order change dependent on argument order."
17440 (pcase calendar-date-style
17441 (`american (list arg1 arg2 arg3))
17442 (`european (list arg2 arg1 arg3))
17443 (`iso (list arg2 arg3 arg1))))
17445 (defun org-eval-in-calendar (form &optional keepdate)
17446 "Eval FORM in the calendar window and return to current window.
17447 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17448 (let ((sf (selected-frame))
17449 (sw (selected-window)))
17450 (select-window (get-buffer-window "*Calendar*" t))
17451 (eval form)
17452 (when (and (not keepdate) (calendar-cursor-to-date))
17453 (let* ((date (calendar-cursor-to-date))
17454 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17455 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17456 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17457 (select-window sw)
17458 (select-frame-set-input-focus sf)))
17460 (defun org-calendar-select ()
17461 "Return to `org-read-date' with the date currently selected.
17462 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17463 (interactive)
17464 (when (calendar-cursor-to-date)
17465 (let* ((date (calendar-cursor-to-date))
17466 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17467 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17468 (when (active-minibuffer-window) (exit-minibuffer))))
17470 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17471 "Insert a date stamp for the date given by the internal TIME.
17472 See `format-time-string' for the format of TIME.
17473 WITH-HM means use the stamp format that includes the time of the day.
17474 INACTIVE means use square brackets instead of angular ones, so that the
17475 stamp will not contribute to the agenda.
17476 PRE and POST are optional strings to be inserted before and after the
17477 stamp.
17478 The command returns the inserted time stamp."
17479 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17480 stamp)
17481 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17482 (insert-before-markers (or pre ""))
17483 (when (listp extra)
17484 (setq extra (car extra))
17485 (if (and (stringp extra)
17486 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17487 (setq extra (format "-%02d:%02d"
17488 (string-to-number (match-string 1 extra))
17489 (string-to-number (match-string 2 extra))))
17490 (setq extra nil)))
17491 (when extra
17492 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17493 (insert-before-markers (setq stamp (format-time-string fmt time)))
17494 (insert-before-markers (or post ""))
17495 (setq org-last-inserted-timestamp stamp)))
17497 (defun org-toggle-time-stamp-overlays ()
17498 "Toggle the use of custom time stamp formats."
17499 (interactive)
17500 (setq org-display-custom-times (not org-display-custom-times))
17501 (unless org-display-custom-times
17502 (let ((p (point-min)) (bmp (buffer-modified-p)))
17503 (while (setq p (next-single-property-change p 'display))
17504 (when (and (get-text-property p 'display)
17505 (eq (get-text-property p 'face) 'org-date))
17506 (remove-text-properties
17507 p (setq p (next-single-property-change p 'display))
17508 '(display t))))
17509 (set-buffer-modified-p bmp)))
17510 (org-restart-font-lock)
17511 (setq org-table-may-need-update t)
17512 (if org-display-custom-times
17513 (message "Time stamps are overlaid with custom format")
17514 (message "Time stamp overlays removed")))
17516 (defun org-display-custom-time (beg end)
17517 "Overlay modified time stamp format over timestamp between BEG and END."
17518 (let* ((ts (buffer-substring beg end))
17519 t1 w1 with-hm tf time str w2 (off 0))
17520 (save-match-data
17521 (setq t1 (org-parse-time-string ts t))
17522 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17523 (setq off (- (match-end 0) (match-beginning 0)))))
17524 (setq end (- end off))
17525 (setq w1 (- end beg)
17526 with-hm (and (nth 1 t1) (nth 2 t1))
17527 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17528 time (org-fix-decoded-time t1)
17529 str (org-add-props
17530 (format-time-string
17531 (substring tf 1 -1) (apply 'encode-time time))
17532 nil 'mouse-face 'highlight)
17533 w2 (length str))
17534 (unless (= w2 w1)
17535 (add-text-properties (1+ beg) (+ 2 beg)
17536 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17537 (put-text-property beg end 'display str)))
17539 (defun org-fix-decoded-time (time)
17540 "Set 0 instead of nil for the first 6 elements of time.
17541 Don't touch the rest."
17542 (let ((n 0))
17543 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17545 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17546 "Difference between TIMESTAMP-STRING and now in days.
17547 If SECONDS is non-nil, return the difference in seconds."
17548 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17549 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17550 (funcall fdiff (current-time)))))
17552 (defun org-deadline-close-p (timestamp-string &optional ndays)
17553 "Is the time in TIMESTAMP-STRING close to the current date?"
17554 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17555 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17556 (not (org-entry-is-done-p))))
17558 (defun org-get-wdays (ts &optional delay zero-delay)
17559 "Get the deadline lead time appropriate for timestring TS.
17560 When DELAY is non-nil, get the delay time for scheduled items
17561 instead of the deadline lead time. When ZERO-DELAY is non-nil
17562 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17563 don't try to find the delay cookie in the scheduled timestamp."
17564 (let ((tv (if delay org-scheduled-delay-days
17565 org-deadline-warning-days)))
17566 (cond
17567 ((or (and delay (< tv 0))
17568 (and delay zero-delay (<= tv 0))
17569 (and (not delay) (<= tv 0)))
17570 ;; Enforce this value no matter what
17571 (- tv))
17572 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17573 ;; lead time is specified.
17574 (floor (* (string-to-number (match-string 1 ts))
17575 (cdr (assoc (match-string 2 ts)
17576 '(("d" . 1) ("w" . 7)
17577 ("m" . 30.4) ("y" . 365.25)
17578 ("h" . 0.041667)))))))
17579 ;; go for the default.
17580 (t tv))))
17582 (defun org-calendar-select-mouse (ev)
17583 "Return to `org-read-date' with the date currently selected.
17584 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17585 (interactive "e")
17586 (mouse-set-point ev)
17587 (when (calendar-cursor-to-date)
17588 (let* ((date (calendar-cursor-to-date))
17589 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17590 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17591 (when (active-minibuffer-window) (exit-minibuffer))))
17593 (defun org-check-deadlines (ndays)
17594 "Check if there are any deadlines due or past due.
17595 A deadline is considered due if it happens within `org-deadline-warning-days'
17596 days from today's date. If the deadline appears in an entry marked DONE,
17597 it is not shown. A numeric prefix argument NDAYS can be used to test that
17598 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17599 are shown."
17600 (interactive "P")
17601 (let* ((org-warn-days
17602 (cond
17603 ((equal ndays '(4)) 100000)
17604 (ndays (prefix-numeric-value ndays))
17605 (t (abs org-deadline-warning-days))))
17606 (case-fold-search nil)
17607 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17608 (callback
17609 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17610 (message "%d deadlines past-due or due within %d days"
17611 (org-occur regexp nil callback)
17612 org-warn-days)))
17614 (defsubst org-re-timestamp (type)
17615 "Return a regexp for timestamp TYPE.
17616 Allowed values for TYPE are:
17618 all: all timestamps
17619 active: only active timestamps (<...>)
17620 inactive: only inactive timestamps ([...])
17621 scheduled: only scheduled timestamps
17622 deadline: only deadline timestamps
17623 closed: only closed time-stamps
17625 When TYPE is nil, fall back on returning a regexp that matches
17626 both scheduled and deadline timestamps."
17627 (cl-case type
17628 (all org-ts-regexp-both)
17629 (active org-ts-regexp)
17630 (inactive org-ts-regexp-inactive)
17631 (scheduled org-scheduled-time-regexp)
17632 (deadline org-deadline-time-regexp)
17633 (closed org-closed-time-regexp)
17634 (otherwise
17635 (concat "\\<"
17636 (regexp-opt (list org-deadline-string org-scheduled-string))
17637 " *<\\([^>]+\\)>"))))
17639 (defun org-check-before-date (d)
17640 "Check if there are deadlines or scheduled entries before date D."
17641 (interactive (list (org-read-date)))
17642 (let* ((case-fold-search nil)
17643 (regexp (org-re-timestamp org-ts-type))
17644 (ts-type org-ts-type)
17645 (callback
17646 (lambda ()
17647 (let ((match (match-string 1)))
17648 (and (if (memq ts-type '(active inactive all))
17649 (eq (org-element-type (save-excursion
17650 (backward-char)
17651 (org-element-context)))
17652 'timestamp)
17653 (org-at-planning-p))
17654 (time-less-p
17655 (org-time-string-to-time match)
17656 (org-time-string-to-time d)))))))
17657 (message "%d entries before %s"
17658 (org-occur regexp nil callback)
17659 d)))
17661 (defun org-check-after-date (d)
17662 "Check if there are deadlines or scheduled entries after date D."
17663 (interactive (list (org-read-date)))
17664 (let* ((case-fold-search nil)
17665 (regexp (org-re-timestamp org-ts-type))
17666 (ts-type org-ts-type)
17667 (callback
17668 (lambda ()
17669 (let ((match (match-string 1)))
17670 (and (if (memq ts-type '(active inactive all))
17671 (eq (org-element-type (save-excursion
17672 (backward-char)
17673 (org-element-context)))
17674 'timestamp)
17675 (org-at-planning-p))
17676 (not (time-less-p
17677 (org-time-string-to-time match)
17678 (org-time-string-to-time d))))))))
17679 (message "%d entries after %s"
17680 (org-occur regexp nil callback)
17681 d)))
17683 (defun org-check-dates-range (start-date end-date)
17684 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17685 (interactive (list (org-read-date nil nil nil "Range starts")
17686 (org-read-date nil nil nil "Range end")))
17687 (let ((case-fold-search nil)
17688 (regexp (org-re-timestamp org-ts-type))
17689 (callback
17690 (let ((type org-ts-type))
17691 (lambda ()
17692 (let ((match (match-string 1)))
17693 (and
17694 (if (memq type '(active inactive all))
17695 (eq (org-element-type (save-excursion
17696 (backward-char)
17697 (org-element-context)))
17698 'timestamp)
17699 (org-at-planning-p))
17700 (not (time-less-p
17701 (org-time-string-to-time match)
17702 (org-time-string-to-time start-date)))
17703 (time-less-p
17704 (org-time-string-to-time match)
17705 (org-time-string-to-time end-date))))))))
17706 (message "%d entries between %s and %s"
17707 (org-occur regexp nil callback) start-date end-date)))
17709 (defun org-evaluate-time-range (&optional to-buffer)
17710 "Evaluate a time range by computing the difference between start and end.
17711 Normally the result is just printed in the echo area, but with prefix arg
17712 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17713 If the time range is actually in a table, the result is inserted into the
17714 next column.
17715 For time difference computation, a year is assumed to be exactly 365
17716 days in order to avoid rounding problems."
17717 (interactive "P")
17719 (org-clock-update-time-maybe)
17720 (save-excursion
17721 (unless (org-at-date-range-p t)
17722 (goto-char (point-at-bol))
17723 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17724 (unless (org-at-date-range-p t)
17725 (user-error "Not at a time-stamp range, and none found in current line")))
17726 (let* ((ts1 (match-string 1))
17727 (ts2 (match-string 2))
17728 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17729 (match-end (match-end 0))
17730 (time1 (org-time-string-to-time ts1))
17731 (time2 (org-time-string-to-time ts2))
17732 (t1 (float-time time1))
17733 (t2 (float-time time2))
17734 (diff (abs (- t2 t1)))
17735 (negative (< (- t2 t1) 0))
17736 ;; (ys (floor (* 365 24 60 60)))
17737 (ds (* 24 60 60))
17738 (hs (* 60 60))
17739 (fy "%dy %dd %02d:%02d")
17740 (fy1 "%dy %dd")
17741 (fd "%dd %02d:%02d")
17742 (fd1 "%dd")
17743 (fh "%02d:%02d")
17744 y d h m align)
17745 (if havetime
17746 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17748 d (floor (/ diff ds)) diff (mod diff ds)
17749 h (floor (/ diff hs)) diff (mod diff hs)
17750 m (floor (/ diff 60)))
17751 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17753 d (floor (+ (/ diff ds) 0.5))
17754 h 0 m 0))
17755 (if (not to-buffer)
17756 (message "%s" (org-make-tdiff-string y d h m))
17757 (if (org-at-table-p)
17758 (progn
17759 (goto-char match-end)
17760 (setq align t)
17761 (and (looking-at " *|") (goto-char (match-end 0))))
17762 (goto-char match-end))
17763 (when (looking-at
17764 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17765 (replace-match ""))
17766 (when negative (insert " -"))
17767 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17768 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17769 (insert " " (format fh h m))))
17770 (when align (org-table-align))
17771 (message "Time difference inserted")))))
17773 (defun org-make-tdiff-string (y d h m)
17774 (let ((fmt "")
17775 (l nil))
17776 (when (> y 0)
17777 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17778 (push y l))
17779 (when (> d 0)
17780 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17781 (push d l))
17782 (when (> h 0)
17783 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17784 (push h l))
17785 (when (> m 0)
17786 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17787 (push m l))
17788 (apply 'format fmt (nreverse l))))
17790 (defun org-time-string-to-time (s &optional buffer pos)
17791 "Convert a timestamp string into internal time."
17792 (condition-case errdata
17793 (apply 'encode-time (org-parse-time-string s))
17794 (error (error "Bad timestamp `%s'%s\nError was: %s"
17795 s (if (not (and buffer pos))
17797 (format-message " at %d in buffer `%s'" pos buffer))
17798 (cdr errdata)))))
17800 (defun org-time-string-to-seconds (s)
17801 "Convert a timestamp string to a number of seconds."
17802 (float-time (org-time-string-to-time s)))
17804 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17806 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17807 "Convert time stamp S to an absolute day number.
17809 If DAYNR in non-nil, and there is a specifier for a cyclic time
17810 stamp, get the closest date to DAYNR. If PREFER is
17811 `past' (respectively `future') return a date past (respectively
17812 after) or equal to DAYNR.
17814 POS is the location of time stamp S, as a buffer position in
17815 BUFFER.
17817 Diary sexp timestamps are matched against DAYNR, when non-nil.
17818 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17819 signalled."
17820 (cond
17821 ((string-match "\\`%%\\((.*)\\)" s)
17822 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17823 ;; only able to match individual dates. If it fails, raise an
17824 ;; error.
17825 (if (and daynr
17826 (org-diary-sexp-entry
17827 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17828 daynr
17829 (signal 'org-diary-sexp-no-match (list s))))
17830 (daynr (org-closest-date s daynr prefer))
17831 (t (time-to-days
17832 (condition-case errdata
17833 (apply #'encode-time (org-parse-time-string s))
17834 (error (error "Bad timestamp `%s'%s\nError was: %s"
17836 (if (not (and buffer pos)) ""
17837 (format-message " at %d in buffer `%s'" pos buffer))
17838 (cdr errdata))))))))
17840 (defun org-days-to-iso-week (days)
17841 "Return the iso week number."
17842 (require 'cal-iso)
17843 (car (calendar-iso-from-absolute days)))
17845 (defun org-small-year-to-year (year)
17846 "Convert 2-digit years into 4-digit years.
17847 YEAR is expanded into one of the 30 next years, if possible, or
17848 into a past one. Any year larger than 99 is returned unchanged."
17849 (if (>= year 100) year
17850 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17851 (century (/ current 100))
17852 (offset (- year (% current 100))))
17853 (cond ((> offset 30) (+ (* (1- century) 100) year))
17854 ((> offset -70) (+ (* century 100) year))
17855 (t (+ (* (1+ century) 100) year))))))
17857 (defun org-time-from-absolute (d)
17858 "Return the time corresponding to date D.
17859 D may be an absolute day number, or a calendar-type list (month day year)."
17860 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17861 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17863 (defvar org-agenda-current-date)
17864 (defun org-calendar-holiday ()
17865 "List of holidays, for Diary display in Org mode."
17866 (require 'holidays)
17867 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17868 (and hl (mapconcat #'identity hl "; "))))
17870 (defun org-diary-sexp-entry (sexp entry d)
17871 "Process a SEXP diary ENTRY for date D."
17872 (require 'diary-lib)
17873 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17874 ;; dynamically.
17875 (let* ((sexp `(let ((entry ,entry)
17876 (date ',d))
17877 ,(car (read-from-string sexp))))
17878 (result (if calendar-debug-sexp (eval sexp)
17879 (condition-case nil
17880 (eval sexp)
17881 (error
17882 (beep)
17883 (message "Bad sexp at line %d in %s: %s"
17884 (org-current-line)
17885 (buffer-file-name) sexp)
17886 (sleep-for 2))))))
17887 (cond ((stringp result) (split-string result "; "))
17888 ((and (consp result)
17889 (not (consp (cdr result)))
17890 (stringp (cdr result))) (cdr result))
17891 ((and (consp result)
17892 (stringp (car result))) result)
17893 (result entry))))
17895 (defun org-diary-to-ical-string (frombuf)
17896 "Get iCalendar entries from diary entries in buffer FROMBUF.
17897 This uses the icalendar.el library."
17898 (let* ((tmpdir temporary-file-directory)
17899 (tmpfile (make-temp-name
17900 (expand-file-name "orgics" tmpdir)))
17901 buf rtn b e)
17902 (with-current-buffer frombuf
17903 (icalendar-export-region (point-min) (point-max) tmpfile)
17904 (setq buf (find-buffer-visiting tmpfile))
17905 (set-buffer buf)
17906 (goto-char (point-min))
17907 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17908 (setq b (match-beginning 0)))
17909 (goto-char (point-max))
17910 (when (re-search-backward "^END:VEVENT" nil t)
17911 (setq e (match-end 0)))
17912 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17913 (kill-buffer buf)
17914 (delete-file tmpfile)
17915 rtn))
17917 (defun org-closest-date (start current prefer)
17918 "Return closest date to CURRENT starting from START.
17920 CURRENT and START are both time stamps.
17922 When PREFER is `past', return a date that is either CURRENT or
17923 past. When PREFER is `future', return a date that is either
17924 CURRENT or future.
17926 Only time stamps with a repeater are modified. Any other time
17927 stamp stay unchanged. In any case, return value is an absolute
17928 day number."
17929 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17930 ;; No repeater. Do not shift time stamp.
17931 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17932 (let ((value (string-to-number (match-string 1 start)))
17933 (type (match-string 2 start)))
17934 (if (= 0 value)
17935 ;; Repeater with a 0-value is considered as void.
17936 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17937 (let* ((base (org-date-to-gregorian start))
17938 (target (org-date-to-gregorian current))
17939 (sday (calendar-absolute-from-gregorian base))
17940 (cday (calendar-absolute-from-gregorian target))
17941 n1 n2)
17942 ;; If START is already past CURRENT, just return START.
17943 (if (<= cday sday) sday
17944 ;; Compute closest date before (N1) and closest date past
17945 ;; (N2) CURRENT.
17946 (pcase type
17947 ("h"
17948 (let ((missing-hours
17949 (mod (+ (- (* 24 (- cday sday))
17950 (nth 2 (org-parse-time-string start)))
17951 org-extend-today-until)
17952 value)))
17953 (setf n1 (if (= missing-hours 0) cday
17954 (- cday (1+ (/ missing-hours 24)))))
17955 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17956 ((or "d" "w")
17957 (let ((value (if (equal type "w") (* 7 value) value)))
17958 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17959 (setf n2 (+ n1 value))))
17960 ("m"
17961 (let* ((add-months
17962 (lambda (d n)
17963 ;; Add N months to gregorian date D, i.e.,
17964 ;; a list (MONTH DAY YEAR). Return a valid
17965 ;; gregorian date.
17966 (let ((m (+ (nth 0 d) n)))
17967 (list (mod m 12)
17968 (nth 1 d)
17969 (+ (/ m 12) (nth 2 d))))))
17970 (months ; Complete months to TARGET.
17971 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17972 (- (nth 0 target) (nth 0 base))
17973 ;; If START's day is greater than
17974 ;; TARGET's, remove incomplete month.
17975 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17976 value)
17977 value))
17978 (before (funcall add-months base months)))
17979 (setf n1 (calendar-absolute-from-gregorian before))
17980 (setf n2
17981 (calendar-absolute-from-gregorian
17982 (funcall add-months before value)))))
17984 (let* ((d (nth 1 base))
17985 (m (nth 0 base))
17986 (y (nth 2 base))
17987 (years ; Complete years to TARGET.
17988 (* (/ (- (nth 2 target)
17990 ;; If START's month and day are
17991 ;; greater than TARGET's, remove
17992 ;; incomplete year.
17993 (if (or (> (nth 0 target) m)
17994 (and (= (nth 0 target) m)
17995 (> (nth 1 target) d)))
17998 value)
17999 value))
18000 (before (list m d (+ y years))))
18001 (setf n1 (calendar-absolute-from-gregorian before))
18002 (setf n2 (calendar-absolute-from-gregorian
18003 (list m d (+ (nth 2 before) value)))))))
18004 ;; Handle PREFER parameter, if any.
18005 (cond
18006 ((eq prefer 'past) (if (= cday n2) n2 n1))
18007 ((eq prefer 'future) (if (= cday n1) n1 n2))
18008 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
18010 (defun org-date-to-gregorian (d)
18011 "Turn any specification of date D into a Gregorian date for the calendar."
18012 (cond ((integerp d) (calendar-gregorian-from-absolute d))
18013 ((and (listp d) (= (length d) 3)) d)
18014 ((stringp d)
18015 (let ((d (org-parse-time-string d)))
18016 (list (nth 4 d) (nth 3 d) (nth 5 d))))
18017 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
18019 (defun org-parse-time-string (s &optional nodefault)
18020 "Parse the standard Org time string.
18021 This should be a lot faster than the normal `parse-time-string'.
18022 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18023 hour and minute fields will be nil if not given."
18024 (cond ((string-match org-ts-regexp0 s)
18025 (list 0
18026 (when (or (match-beginning 8) (not nodefault))
18027 (string-to-number (or (match-string 8 s) "0")))
18028 (when (or (match-beginning 7) (not nodefault))
18029 (string-to-number (or (match-string 7 s) "0")))
18030 (string-to-number (match-string 4 s))
18031 (string-to-number (match-string 3 s))
18032 (string-to-number (match-string 2 s))
18033 nil nil nil))
18034 ((string-match "^<[^>]+>$" s)
18035 (decode-time (seconds-to-time (org-matcher-time s))))
18036 (t (error "Not a standard Org time string: %s" s))))
18038 (defun org-timestamp-up (&optional arg)
18039 "Increase the date item at the cursor by one.
18040 If the cursor is on the year, change the year. If it is on the month,
18041 the day or the time, change that.
18042 With prefix ARG, change by that many units."
18043 (interactive "p")
18044 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
18046 (defun org-timestamp-down (&optional arg)
18047 "Decrease the date item at the cursor by one.
18048 If the cursor is on the year, change the year. If it is on the month,
18049 the day or the time, change that.
18050 With prefix ARG, change by that many units."
18051 (interactive "p")
18052 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
18054 (defun org-timestamp-up-day (&optional arg)
18055 "Increase the date in the time stamp by one day.
18056 With prefix ARG, change that many days."
18057 (interactive "p")
18058 (if (and (not (org-at-timestamp-p t))
18059 (org-at-heading-p))
18060 (org-todo 'up)
18061 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
18063 (defun org-timestamp-down-day (&optional arg)
18064 "Decrease the date in the time stamp by one day.
18065 With prefix ARG, change that many days."
18066 (interactive "p")
18067 (if (and (not (org-at-timestamp-p t))
18068 (org-at-heading-p))
18069 (org-todo 'down)
18070 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
18072 (defun org-at-timestamp-p (&optional inactive-ok)
18073 "Non-nil if point is inside a timestamp.
18075 When optional argument INACTIVE-OK is non-nil, also consider
18076 inactive timestamps.
18078 When this function returns a non-nil value, match data is set
18079 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18080 INACTIVE-OK."
18081 (interactive)
18082 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18083 (pos (point))
18084 (ans (or (looking-at tsr)
18085 (save-excursion
18086 (skip-chars-backward "^[<\n\r\t")
18087 (when (> (point) (point-min)) (backward-char 1))
18088 (and (looking-at tsr)
18089 (> (- (match-end 0) pos) -1))))))
18090 (and ans
18091 (boundp 'org-ts-what)
18092 (setq org-ts-what
18093 (cond
18094 ((= pos (match-beginning 0)) 'bracket)
18095 ;; Point is considered to be "on the bracket" whether
18096 ;; it's really on it or right after it.
18097 ((= pos (1- (match-end 0))) 'bracket)
18098 ((= pos (match-end 0)) 'after)
18099 ((org-pos-in-match-range pos 2) 'year)
18100 ((org-pos-in-match-range pos 3) 'month)
18101 ((org-pos-in-match-range pos 7) 'hour)
18102 ((org-pos-in-match-range pos 8) 'minute)
18103 ((or (org-pos-in-match-range pos 4)
18104 (org-pos-in-match-range pos 5)) 'day)
18105 ((and (> pos (or (match-end 8) (match-end 5)))
18106 (< pos (match-end 0)))
18107 (- pos (or (match-end 8) (match-end 5))))
18108 (t 'day))))
18109 ans))
18111 (defun org-toggle-timestamp-type ()
18112 "Toggle the type (<active> or [inactive]) of a time stamp."
18113 (interactive)
18114 (when (org-at-timestamp-p t)
18115 (let ((beg (match-beginning 0)) (end (match-end 0))
18116 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18117 (save-excursion
18118 (goto-char beg)
18119 (while (re-search-forward "[][<>]" end t)
18120 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18121 t t)))
18122 (message "Timestamp is now %sactive"
18123 (if (equal (char-after beg) ?<) "" "in")))))
18125 (defun org-at-clock-log-p nil
18126 "Is the cursor on the clock log line?"
18127 (save-excursion
18128 (beginning-of-line)
18129 (looking-at org-clock-line-re)))
18131 (defvar org-clock-history) ; defined in org-clock.el
18132 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18133 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18134 "Change the date in the time stamp at point.
18135 The date will be changed by N times WHAT. WHAT can be `day', `month',
18136 `year', `minute', `second'. If WHAT is not given, the cursor position
18137 in the timestamp determines what will be changed.
18138 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18139 (let ((origin (point)) origin-cat
18140 with-hm inactive
18141 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18142 org-ts-what
18143 extra rem
18144 ts time time0 fixnext clrgx)
18145 (unless (org-at-timestamp-p t)
18146 (user-error "Not at a timestamp"))
18147 (if (and (not what) (eq org-ts-what 'bracket))
18148 (org-toggle-timestamp-type)
18149 ;; Point isn't on brackets. Remember the part of the time-stamp
18150 ;; the point was in. Indeed, size of time-stamps may change,
18151 ;; but point must be kept in the same category nonetheless.
18152 (setq origin-cat org-ts-what)
18153 (when (and (not what) (not (eq org-ts-what 'day))
18154 org-display-custom-times
18155 (get-text-property (point) 'display)
18156 (not (get-text-property (1- (point)) 'display)))
18157 (setq org-ts-what 'day))
18158 (setq org-ts-what (or what org-ts-what)
18159 inactive (= (char-after (match-beginning 0)) ?\[)
18160 ts (match-string 0))
18161 (replace-match "")
18162 (when (string-match
18163 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18165 (setq extra (match-string 1 ts))
18166 (when suppress-tmp-delay
18167 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18168 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18169 (setq with-hm t))
18170 (setq time0 (org-parse-time-string ts))
18171 (when (and updown
18172 (eq org-ts-what 'minute)
18173 (not current-prefix-arg))
18174 ;; This looks like s-up and s-down. Change by one rounding step.
18175 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18176 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18177 (setcar (cdr time0) (+ (nth 1 time0)
18178 (if (> n 0) (- rem) (- dm rem))))))
18179 (setq time
18180 (apply #'encode-time
18181 (or (car time0) 0)
18182 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18183 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18184 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18185 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18186 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18187 (nthcdr 6 time0)))
18188 (when (and (member org-ts-what '(hour minute))
18189 extra
18190 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18191 (setq extra (org-modify-ts-extra
18192 extra
18193 (if (eq org-ts-what 'hour) 2 5)
18194 n dm)))
18195 (when (integerp org-ts-what)
18196 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18197 (when (eq what 'calendar)
18198 (let ((cal-date (org-get-date-from-calendar)))
18199 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18200 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18201 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18202 (setcar time0 (or (car time0) 0))
18203 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18204 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18205 (setq time (apply 'encode-time time0))))
18206 ;; Insert the new time-stamp, and ensure point stays in the same
18207 ;; category as before (i.e. not after the last position in that
18208 ;; category).
18209 (let ((pos (point)))
18210 ;; Stay before inserted string. `save-excursion' is of no use.
18211 (setq org-last-changed-timestamp
18212 (org-insert-time-stamp time with-hm inactive nil nil extra))
18213 (goto-char pos))
18214 (save-match-data
18215 (looking-at org-ts-regexp3)
18216 (goto-char
18217 (pcase origin-cat
18218 ;; `day' category ends before `hour' if any, or at the end
18219 ;; of the day name.
18220 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18221 (`hour (min (match-end 7) origin))
18222 (`minute (min (1- (match-end 8)) origin))
18223 ((pred integerp) (min (1- (match-end 0)) origin))
18224 ;; Point was right after the time-stamp. However, the
18225 ;; time-stamp length might have changed, so refer to
18226 ;; (match-end 0) instead.
18227 (`after (match-end 0))
18228 ;; `year' and `month' have both fixed size: point couldn't
18229 ;; have moved into another part.
18230 (_ origin))))
18231 ;; Update clock if on a CLOCK line.
18232 (org-clock-update-time-maybe)
18233 ;; Maybe adjust the closest clock in `org-clock-history'
18234 (when org-clock-adjust-closest
18235 (if (not (and (org-at-clock-log-p)
18236 (< 1 (length (delq nil (mapcar 'marker-position
18237 org-clock-history))))))
18238 (message "No clock to adjust")
18239 (cond ((save-excursion ; fix previous clock?
18240 (re-search-backward org-ts-regexp0 nil t)
18241 (looking-back (concat org-clock-string " \\[")
18242 (line-beginning-position)))
18243 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18244 ((save-excursion ; fix next clock?
18245 (re-search-backward org-ts-regexp0 nil t)
18246 (looking-at (concat org-ts-regexp0 "\\] =>")))
18247 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18248 (save-window-excursion
18249 ;; Find closest clock to point, adjust the previous/next one in history
18250 (let* ((p (save-excursion (org-back-to-heading t)))
18251 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18252 (clfixnth
18253 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18254 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18255 (if (not clfixpos)
18256 (message "No clock to adjust")
18257 (save-excursion
18258 (org-goto-marker-or-bmk clfixpos)
18259 (org-show-subtree)
18260 (when (re-search-forward clrgx nil t)
18261 (goto-char (match-beginning 1))
18262 (let (org-clock-adjust-closest)
18263 (org-timestamp-change n org-ts-what updown))
18264 (message "Clock adjusted in %s for heading: %s"
18265 (file-name-nondirectory (buffer-file-name))
18266 (org-get-heading t t)))))))))
18267 ;; Try to recenter the calendar window, if any.
18268 (when (and org-calendar-follow-timestamp-change
18269 (get-buffer-window "*Calendar*" t)
18270 (memq org-ts-what '(day month year)))
18271 (org-recenter-calendar (time-to-days time))))))
18273 (defun org-modify-ts-extra (s pos n dm)
18274 "Change the different parts of the lead-time and repeat fields in timestamp."
18275 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18276 ng h m new rem)
18277 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18278 (cond
18279 ((or (org-pos-in-match-range pos 2)
18280 (org-pos-in-match-range pos 3))
18281 (setq m (string-to-number (match-string 3 s))
18282 h (string-to-number (match-string 2 s)))
18283 (if (org-pos-in-match-range pos 2)
18284 (setq h (+ h n))
18285 (setq n (* dm (with-no-warnings (signum n))))
18286 (unless (= 0 (setq rem (% m dm)))
18287 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18288 (setq m (+ m n)))
18289 (when (< m 0) (setq m (+ m 60) h (1- h)))
18290 (when (> m 59) (setq m (- m 60) h (1+ h)))
18291 (setq h (mod h 24))
18292 (setq ng 1 new (format "-%02d:%02d" h m)))
18293 ((org-pos-in-match-range pos 6)
18294 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18295 ((org-pos-in-match-range pos 5)
18296 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18298 ((org-pos-in-match-range pos 9)
18299 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18300 ((org-pos-in-match-range pos 8)
18301 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18303 (when ng
18304 (setq s (concat
18305 (substring s 0 (match-beginning ng))
18307 (substring s (match-end ng))))))
18310 (defun org-recenter-calendar (d)
18311 "If the calendar is visible, recenter it to date D."
18312 (let ((cwin (get-buffer-window "*Calendar*" t)))
18313 (when cwin
18314 (let ((calendar-move-hook nil))
18315 (with-selected-window cwin
18316 (calendar-goto-date
18317 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18319 (defun org-goto-calendar (&optional arg)
18320 "Go to the Emacs calendar at the current date.
18321 If there is a time stamp in the current line, go to that date.
18322 A prefix ARG can be used to force the current date."
18323 (interactive "P")
18324 (let ((tsr org-ts-regexp) diff
18325 (calendar-move-hook nil)
18326 (calendar-view-holidays-initially-flag nil)
18327 (calendar-view-diary-initially-flag nil))
18328 (when (or (org-at-timestamp-p)
18329 (save-excursion
18330 (beginning-of-line 1)
18331 (looking-at (concat ".*" tsr))))
18332 (let ((d1 (time-to-days (current-time)))
18333 (d2 (time-to-days
18334 (org-time-string-to-time (match-string 1)))))
18335 (setq diff (- d2 d1))))
18336 (calendar)
18337 (calendar-goto-today)
18338 (when (and diff (not arg)) (calendar-forward-day diff))))
18340 (defun org-get-date-from-calendar ()
18341 "Return a list (month day year) of date at point in calendar."
18342 (with-current-buffer "*Calendar*"
18343 (save-match-data
18344 (calendar-cursor-to-date))))
18346 (defun org-date-from-calendar ()
18347 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18348 If there is already a time stamp at the cursor position, update it."
18349 (interactive)
18350 (if (org-at-timestamp-p t)
18351 (org-timestamp-change 0 'calendar)
18352 (let ((cal-date (org-get-date-from-calendar)))
18353 (org-insert-time-stamp
18354 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18356 (defcustom org-effort-durations
18357 `(("min" . 1)
18358 ("h" . 60)
18359 ("d" . ,(* 60 8))
18360 ("w" . ,(* 60 8 5))
18361 ("m" . ,(* 60 8 5 4))
18362 ("y" . ,(* 60 8 5 40)))
18363 "Conversion factor to minutes for an effort modifier.
18365 Each entry has the form (MODIFIER . MINUTES).
18367 In an effort string, a number followed by MODIFIER is multiplied
18368 by the specified number of MINUTES to obtain an effort in
18369 minutes.
18371 For example, if the value of this variable is ((\"hours\" . 60)), then an
18372 effort string \"2hours\" is equivalent to 120 minutes."
18373 :group 'org-agenda
18374 :version "25.2"
18375 :package-version '(Org . "8.3")
18376 :type '(alist :key-type (string :tag "Modifier")
18377 :value-type (number :tag "Minutes")))
18379 (defun org-minutes-to-clocksum-string (m)
18380 "Format number of minutes as a clocksum string.
18381 The format is determined by `org-time-clocksum-format',
18382 `org-time-clocksum-use-fractional' and
18383 `org-time-clocksum-fractional-format' and
18384 `org-time-clocksum-use-effort-durations'."
18385 (let ((clocksum "")
18386 (m (round m)) ; Don't allow fractions of minutes
18387 h d w mo y fmt n)
18388 (setq h (if org-time-clocksum-use-effort-durations
18389 (cdr (assoc "h" org-effort-durations)) 60)
18390 d (if org-time-clocksum-use-effort-durations
18391 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18392 w (if org-time-clocksum-use-effort-durations
18393 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18394 mo (if org-time-clocksum-use-effort-durations
18395 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18396 y (if org-time-clocksum-use-effort-durations
18397 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18398 ;; fractional format
18399 (if org-time-clocksum-use-fractional
18400 (cond
18401 ;; single format string
18402 ((stringp org-time-clocksum-fractional-format)
18403 (format org-time-clocksum-fractional-format (/ m (float h))))
18404 ;; choice of fractional formats for different time units
18405 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18406 (> (/ (truncate m) (* y d h)) 0))
18407 (format fmt (/ m (* y d (float h)))))
18408 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18409 (> (/ (truncate m) (* mo d h)) 0))
18410 (format fmt (/ m (* mo d (float h)))))
18411 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18412 (> (/ (truncate m) (* w d h)) 0))
18413 (format fmt (/ m (* w d (float h)))))
18414 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18415 (> (/ (truncate m) (* d h)) 0))
18416 (format fmt (/ m (* d (float h)))))
18417 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18418 (> (/ (truncate m) h) 0))
18419 (format fmt (/ m (float h))))
18420 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18421 (format fmt m))
18422 ;; fall back to smallest time unit with a format
18423 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18424 (format fmt (/ m (float h))))
18425 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18426 (format fmt (/ m (* d (float h)))))
18427 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18428 (format fmt (/ m (* w d (float h)))))
18429 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18430 (format fmt (/ m (* mo d (float h)))))
18431 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18432 (format fmt (/ m (* y d (float h))))))
18433 ;; standard (non-fractional) format, with single format string
18434 (if (stringp org-time-clocksum-format)
18435 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18436 ;; separate formats components
18437 (and (setq fmt (plist-get org-time-clocksum-format :years))
18438 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18439 (plist-get org-time-clocksum-format :require-years))
18440 (setq clocksum (concat clocksum (format fmt n))
18441 m (- m (* n y d h))))
18442 (and (setq fmt (plist-get org-time-clocksum-format :months))
18443 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18444 (plist-get org-time-clocksum-format :require-months))
18445 (setq clocksum (concat clocksum (format fmt n))
18446 m (- m (* n mo d h))))
18447 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18448 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18449 (plist-get org-time-clocksum-format :require-weeks))
18450 (setq clocksum (concat clocksum (format fmt n))
18451 m (- m (* n w d h))))
18452 (and (setq fmt (plist-get org-time-clocksum-format :days))
18453 (or (> (setq n (/ (truncate m) (* d h))) 0)
18454 (plist-get org-time-clocksum-format :require-days))
18455 (setq clocksum (concat clocksum (format fmt n))
18456 m (- m (* n d h))))
18457 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18458 (or (> (setq n (/ (truncate m) h)) 0)
18459 (plist-get org-time-clocksum-format :require-hours))
18460 (setq clocksum (concat clocksum (format fmt n))
18461 m (- m (* n h))))
18462 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18463 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18464 (setq clocksum (concat clocksum (format fmt m))))
18465 ;; return formatted time duration
18466 clocksum))))
18468 (defun org-hours-to-clocksum-string (n)
18469 (org-minutes-to-clocksum-string (* n 60)))
18471 (defun org-hh:mm-string-to-minutes (s)
18472 "Convert a string H:MM to a number of minutes.
18473 If the string is just a number, interpret it as minutes.
18474 In fact, the first hh:mm or number in the string will be taken,
18475 there can be extra stuff in the string.
18476 If no number is found, the return value is 0."
18477 (cond
18478 ((integerp s) s)
18479 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18480 (+ (* (string-to-number (match-string 1 s)) 60)
18481 (string-to-number (match-string 2 s))))
18482 ((string-match "\\([0-9]+\\)" s)
18483 (string-to-number (match-string 1 s)))
18484 (t 0)))
18486 (defcustom org-image-actual-width t
18487 "Should we use the actual width of images when inlining them?
18489 When set to t, always use the image width.
18491 When set to a number, use imagemagick (when available) to set
18492 the image's width to this value.
18494 When set to a number in a list, try to get the width from any
18495 #+ATTR.* keyword if it matches a width specification like
18497 #+ATTR_HTML: :width 300px
18499 and fall back on that number if none is found.
18501 When set to nil, try to get the width from an #+ATTR.* keyword
18502 and fall back on the original width if none is found.
18504 This requires Emacs >= 24.1, build with imagemagick support."
18505 :group 'org-appearance
18506 :version "24.4"
18507 :package-version '(Org . "8.0")
18508 :type '(choice
18509 (const :tag "Use the image width" t)
18510 (integer :tag "Use a number of pixels")
18511 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18512 (const :tag "Use #+ATTR* or don't resize" nil)))
18514 (defcustom org-agenda-inhibit-startup nil
18515 "Inhibit startup when preparing agenda buffers.
18516 When this variable is t, the initialization of the Org agenda
18517 buffers is inhibited: e.g. the visibility state is not set, the
18518 tables are not re-aligned, etc."
18519 :type 'boolean
18520 :version "24.3"
18521 :group 'org-agenda)
18523 (defcustom org-agenda-ignore-properties nil
18524 "Avoid updating text properties when building the agenda.
18525 Properties are used to prepare buffers for effort estimates,
18526 appointments, statistics and subtree-local categories.
18527 If you don't use these in the agenda, you can add them to this
18528 list and agenda building will be a bit faster.
18529 The value is a list, with zero or more of the symbols `effort', `appt',
18530 `stats' or `category'."
18531 :type '(set :greedy t
18532 (const effort)
18533 (const appt)
18534 (const stats)
18535 (const category))
18536 :version "25.2"
18537 :package-version '(Org . "8.3")
18538 :group 'org-agenda)
18540 (defun org-duration-string-to-minutes (s &optional output-to-string)
18541 "Convert a duration string S to minutes.
18543 A bare number is interpreted as minutes, modifiers can be set by
18544 customizing `org-effort-durations' (which see).
18546 Entries containing a colon are interpreted as H:MM by
18547 `org-hh:mm-string-to-minutes'."
18548 (let ((result 0)
18549 (re (concat "\\([0-9.]+\\) *\\("
18550 (regexp-opt (mapcar 'car org-effort-durations))
18551 "\\)")))
18552 (while (string-match re s)
18553 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18554 (string-to-number (match-string 1 s))))
18555 (setq s (replace-match "" nil t s)))
18556 (setq result (floor result))
18557 (cl-incf result (org-hh:mm-string-to-minutes s))
18558 (if output-to-string (number-to-string result) result)))
18560 ;;;; Files
18562 (defun org-save-all-org-buffers ()
18563 "Save all Org buffers without user confirmation."
18564 (interactive)
18565 (message "Saving all Org buffers...")
18566 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18567 (when (featurep 'org-id) (org-id-locations-save))
18568 (message "Saving all Org buffers... done"))
18570 (defun org-revert-all-org-buffers ()
18571 "Revert all Org buffers.
18572 Prompt for confirmation when there are unsaved changes.
18573 Be sure you know what you are doing before letting this function
18574 overwrite your changes.
18576 This function is useful in a setup where one tracks org files
18577 with a version control system, to revert on one machine after pulling
18578 changes from another. I believe the procedure must be like this:
18580 1. M-x org-save-all-org-buffers
18581 2. Pull changes from the other machine, resolve conflicts
18582 3. M-x org-revert-all-org-buffers"
18583 (interactive)
18584 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18585 (user-error "Abort"))
18586 (save-excursion
18587 (save-window-excursion
18588 (dolist (b (buffer-list))
18589 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18590 (with-current-buffer b buffer-file-name))
18591 (pop-to-buffer-same-window b)
18592 (revert-buffer t 'no-confirm)))
18593 (when (and (featurep 'org-id) org-id-track-globally)
18594 (org-id-locations-load)))))
18596 ;;;; Agenda files
18598 ;;;###autoload
18599 (defun org-switchb (&optional arg)
18600 "Switch between Org buffers.
18602 With `\\[universal-argument]' prefix, restrict available buffers to files.
18604 With `\\[universal-argument] \\[universal-argument]' \
18605 prefix, restrict available buffers to agenda files."
18606 (interactive "P")
18607 (let ((blist (org-buffer-list
18608 (cond ((equal arg '(4)) 'files)
18609 ((equal arg '(16)) 'agenda)))))
18610 (pop-to-buffer-same-window
18611 (completing-read "Org buffer: "
18612 (mapcar #'list (mapcar #'buffer-name blist))
18613 nil t))))
18615 (defun org-buffer-list (&optional predicate exclude-tmp)
18616 "Return a list of Org buffers.
18617 PREDICATE can be `export', `files' or `agenda'.
18619 export restrict the list to Export buffers.
18620 files restrict the list to buffers visiting Org files.
18621 agenda restrict the list to buffers visiting agenda files.
18623 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18624 (let* ((bfn nil)
18625 (agenda-files (and (eq predicate 'agenda)
18626 (mapcar 'file-truename (org-agenda-files t))))
18627 (filter
18628 (cond
18629 ((eq predicate 'files)
18630 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18631 ((eq predicate 'export)
18632 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18633 ((eq predicate 'agenda)
18634 (lambda (b)
18635 (with-current-buffer b
18636 (and (derived-mode-p 'org-mode)
18637 (setq bfn (buffer-file-name b))
18638 (member (file-truename bfn) agenda-files)))))
18639 (t (lambda (b) (with-current-buffer b
18640 (or (derived-mode-p 'org-mode)
18641 (string-match "\\*Org .*Export"
18642 (buffer-name b)))))))))
18643 (delq nil
18644 (mapcar
18645 (lambda(b)
18646 (if (and (funcall filter b)
18647 (or (not exclude-tmp)
18648 (not (string-match "tmp" (buffer-name b)))))
18650 nil))
18651 (buffer-list)))))
18653 (defun org-agenda-files (&optional unrestricted archives)
18654 "Get the list of agenda files.
18655 Optional UNRESTRICTED means return the full list even if a restriction
18656 is currently in place.
18657 When ARCHIVES is t, include all archive files that are really being
18658 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18659 `org-agenda-archives-mode' is t."
18660 (let ((files
18661 (cond
18662 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18663 ((stringp org-agenda-files) (org-read-agenda-file-list))
18664 ((listp org-agenda-files) org-agenda-files)
18665 (t (error "Invalid value of `org-agenda-files'")))))
18666 (setq files (apply 'append
18667 (mapcar (lambda (f)
18668 (if (file-directory-p f)
18669 (directory-files
18670 f t org-agenda-file-regexp)
18671 (list f)))
18672 files)))
18673 (when org-agenda-skip-unavailable-files
18674 (setq files (delq nil
18675 (mapcar (function
18676 (lambda (file)
18677 (and (file-readable-p file) file)))
18678 files))))
18679 (when (or (eq archives t)
18680 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18681 (setq files (org-add-archive-files files)))
18682 files))
18684 (defun org-agenda-file-p (&optional file)
18685 "Return non-nil, if FILE is an agenda file.
18686 If FILE is omitted, use the file associated with the current
18687 buffer."
18688 (let ((fname (or file (buffer-file-name))))
18689 (and fname
18690 (member (file-truename fname)
18691 (mapcar #'file-truename (org-agenda-files t))))))
18693 (defun org-edit-agenda-file-list ()
18694 "Edit the list of agenda files.
18695 Depending on setup, this either uses customize to edit the variable
18696 `org-agenda-files', or it visits the file that is holding the list. In the
18697 latter case, the buffer is set up in a way that saving it automatically kills
18698 the buffer and restores the previous window configuration."
18699 (interactive)
18700 (if (stringp org-agenda-files)
18701 (let ((cw (current-window-configuration)))
18702 (find-file org-agenda-files)
18703 (setq-local org-window-configuration cw)
18704 (add-hook 'after-save-hook
18705 (lambda ()
18706 (set-window-configuration
18707 (prog1 org-window-configuration
18708 (kill-buffer (current-buffer))))
18709 (org-install-agenda-files-menu)
18710 (message "New agenda file list installed"))
18711 nil 'local)
18712 (message "%s" (substitute-command-keys
18713 "Edit list and finish with \\[save-buffer]")))
18714 (customize-variable 'org-agenda-files)))
18716 (defun org-store-new-agenda-file-list (list)
18717 "Set new value for the agenda file list and save it correctly."
18718 (if (stringp org-agenda-files)
18719 (let ((fe (org-read-agenda-file-list t)) b u)
18720 (while (setq b (find-buffer-visiting org-agenda-files))
18721 (kill-buffer b))
18722 (with-temp-file org-agenda-files
18723 (insert
18724 (mapconcat
18725 (lambda (f) ;; Keep un-expanded entries.
18726 (if (setq u (assoc f fe))
18727 (cdr u)
18729 list "\n")
18730 "\n")))
18731 (let ((org-mode-hook nil) (org-inhibit-startup t)
18732 (org-insert-mode-line-in-empty-file nil))
18733 (setq org-agenda-files list)
18734 (customize-save-variable 'org-agenda-files org-agenda-files))))
18736 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18737 "Read the list of agenda files from a file.
18738 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18739 filenames, used by `org-store-new-agenda-file-list' to write back
18740 un-expanded file names."
18741 (when (file-directory-p org-agenda-files)
18742 (error "`org-agenda-files' cannot be a single directory"))
18743 (when (stringp org-agenda-files)
18744 (with-temp-buffer
18745 (insert-file-contents org-agenda-files)
18746 (mapcar
18747 (lambda (f)
18748 (let ((e (expand-file-name (substitute-in-file-name f)
18749 org-directory)))
18750 (if pair-with-expansion
18751 (cons e f)
18752 e)))
18753 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18755 ;;;###autoload
18756 (defun org-cycle-agenda-files ()
18757 "Cycle through the files in `org-agenda-files'.
18758 If the current buffer visits an agenda file, find the next one in the list.
18759 If the current buffer does not, find the first agenda file."
18760 (interactive)
18761 (let* ((fs (or (org-agenda-files t)
18762 (user-error "No agenda files")))
18763 (files (copy-sequence fs))
18764 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18765 file)
18766 (when tcf
18767 (while (and (setq file (pop files))
18768 (not (equal (file-truename file) tcf)))))
18769 (find-file (car (or files fs)))
18770 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18772 (defun org-agenda-file-to-front (&optional to-end)
18773 "Move/add the current file to the top of the agenda file list.
18774 If the file is not present in the list, it is added to the front. If it is
18775 present, it is moved there. With optional argument TO-END, add/move to the
18776 end of the list."
18777 (interactive "P")
18778 (let ((org-agenda-skip-unavailable-files nil)
18779 (file-alist (mapcar (lambda (x)
18780 (cons (file-truename x) x))
18781 (org-agenda-files t)))
18782 (ctf (file-truename
18783 (or buffer-file-name
18784 (user-error "Please save the current buffer to a file"))))
18785 x had)
18786 (setq x (assoc ctf file-alist) had x)
18788 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18789 (if to-end
18790 (setq file-alist (append (delq x file-alist) (list x)))
18791 (setq file-alist (cons x (delq x file-alist))))
18792 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18793 (org-install-agenda-files-menu)
18794 (message "File %s to %s of agenda file list"
18795 (if had "moved" "added") (if to-end "end" "front"))))
18797 (defun org-remove-file (&optional file)
18798 "Remove current file from the list of files in variable `org-agenda-files'.
18799 These are the files which are being checked for agenda entries.
18800 Optional argument FILE means use this file instead of the current."
18801 (interactive)
18802 (let* ((org-agenda-skip-unavailable-files nil)
18803 (file (or file buffer-file-name
18804 (user-error "Current buffer does not visit a file")))
18805 (true-file (file-truename file))
18806 (afile (abbreviate-file-name file))
18807 (files (delq nil (mapcar
18808 (lambda (x)
18809 (unless (equal true-file
18810 (file-truename x))
18812 (org-agenda-files t)))))
18813 (if (not (= (length files) (length (org-agenda-files t))))
18814 (progn
18815 (org-store-new-agenda-file-list files)
18816 (org-install-agenda-files-menu)
18817 (message "Removed from Org Agenda list: %s" afile))
18818 (message "File was not in list: %s (not removed)" afile))))
18820 (defun org-file-menu-entry (file)
18821 (vector file (list 'find-file file) t))
18823 (defun org-check-agenda-file (file)
18824 "Make sure FILE exists. If not, ask user what to do."
18825 (unless (file-exists-p file)
18826 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18827 (abbreviate-file-name file))
18828 (let ((r (downcase (read-char-exclusive))))
18829 (cond
18830 ((equal r ?r)
18831 (org-remove-file file)
18832 (throw 'nextfile t))
18833 (t (user-error "Abort"))))))
18835 (defun org-get-agenda-file-buffer (file)
18836 "Get an agenda buffer visiting FILE.
18837 If the buffer needs to be created, add it to the list of buffers
18838 which might be released later."
18839 (let ((buf (org-find-base-buffer-visiting file)))
18840 (if buf
18841 buf ; just return it
18842 ;; Make a new buffer and remember it
18843 (setq buf (find-file-noselect file))
18844 (when buf (push buf org-agenda-new-buffers))
18845 buf)))
18847 (defun org-release-buffers (blist)
18848 "Release all buffers in list, asking the user for confirmation when needed.
18849 When a buffer is unmodified, it is just killed. When modified, it is saved
18850 \(if the user agrees) and then killed."
18851 (let (file)
18852 (dolist (buf blist)
18853 (setq file (buffer-file-name buf))
18854 (when (and (buffer-modified-p buf)
18855 file
18856 (y-or-n-p (format "Save file %s? " file)))
18857 (with-current-buffer buf (save-buffer)))
18858 (kill-buffer buf))))
18860 (defun org-agenda-prepare-buffers (files)
18861 "Create buffers for all agenda files, protect archived trees and comments."
18862 (interactive)
18863 (let ((pa '(:org-archived t))
18864 (pc '(:org-comment t))
18865 (pall '(:org-archived t :org-comment t))
18866 (inhibit-read-only t)
18867 (org-inhibit-startup org-agenda-inhibit-startup)
18868 (rea (concat ":" org-archive-tag ":"))
18869 re pos)
18870 (setq org-tag-alist-for-agenda nil
18871 org-tag-groups-alist-for-agenda nil)
18872 (save-excursion
18873 (save-restriction
18874 (dolist (file files)
18875 (catch 'nextfile
18876 (if (bufferp file)
18877 (set-buffer file)
18878 (org-check-agenda-file file)
18879 (set-buffer (org-get-agenda-file-buffer file)))
18880 (widen)
18881 (org-set-regexps-and-options 'tags-only)
18882 (setq pos (point))
18883 (or (memq 'category org-agenda-ignore-properties)
18884 (org-refresh-category-properties))
18885 (or (memq 'stats org-agenda-ignore-properties)
18886 (org-refresh-stats-properties))
18887 (or (memq 'effort org-agenda-ignore-properties)
18888 (org-refresh-effort-properties))
18889 (or (memq 'appt org-agenda-ignore-properties)
18890 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18891 (setq org-todo-keywords-for-agenda
18892 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18893 (setq org-done-keywords-for-agenda
18894 (append org-done-keywords-for-agenda org-done-keywords))
18895 (setq org-todo-keyword-alist-for-agenda
18896 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18897 (setq org-tag-alist-for-agenda
18898 (org-uniquify
18899 (append org-tag-alist-for-agenda
18900 org-current-tag-alist)))
18901 ;; Merge current file's tag groups into global
18902 ;; `org-tag-groups-alist-for-agenda'.
18903 (when org-group-tags
18904 (dolist (alist org-tag-groups-alist)
18905 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18906 (if old
18907 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18908 (push alist org-tag-groups-alist-for-agenda)))))
18909 (org-with-silent-modifications
18910 (save-excursion
18911 (remove-text-properties (point-min) (point-max) pall)
18912 (when org-agenda-skip-archived-trees
18913 (goto-char (point-min))
18914 (while (re-search-forward rea nil t)
18915 (when (org-at-heading-p t)
18916 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18917 (goto-char (point-min))
18918 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18919 (while (re-search-forward re nil t)
18920 (when (save-match-data (org-in-commented-heading-p t))
18921 (add-text-properties
18922 (match-beginning 0) (org-end-of-subtree t) pc)))))
18923 (goto-char pos)))))
18924 (setq org-todo-keywords-for-agenda
18925 (org-uniquify org-todo-keywords-for-agenda))
18926 (setq org-todo-keyword-alist-for-agenda
18927 (org-uniquify org-todo-keyword-alist-for-agenda))))
18930 ;;;; CDLaTeX minor mode
18932 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18933 "Keymap for the minor `org-cdlatex-mode'.")
18935 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18936 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18937 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18938 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18939 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18941 (defvar org-cdlatex-texmathp-advice-is-done nil
18942 "Flag remembering if we have applied the advice to texmathp already.")
18944 (define-minor-mode org-cdlatex-mode
18945 "Toggle the minor `org-cdlatex-mode'.
18946 This mode supports entering LaTeX environment and math in LaTeX fragments
18947 in Org mode.
18948 \\{org-cdlatex-mode-map}"
18949 nil " OCDL" nil
18950 (when org-cdlatex-mode
18951 (require 'cdlatex)
18952 (run-hooks 'cdlatex-mode-hook)
18953 (cdlatex-compute-tables))
18954 (unless org-cdlatex-texmathp-advice-is-done
18955 (setq org-cdlatex-texmathp-advice-is-done t)
18956 (defadvice texmathp (around org-math-always-on activate)
18957 "Always return t in Org buffers.
18958 This is because we want to insert math symbols without dollars even outside
18959 the LaTeX math segments. If Org mode thinks that point is actually inside
18960 an embedded LaTeX fragment, let `texmathp' do its job.
18961 `\\[org-cdlatex-mode-map]'"
18962 (interactive)
18963 (let (p)
18964 (cond
18965 ((not (derived-mode-p 'org-mode)) ad-do-it)
18966 ((eq this-command 'cdlatex-math-symbol)
18967 (setq ad-return-value t
18968 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18970 (let ((p (org-inside-LaTeX-fragment-p)))
18971 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18972 (setq ad-return-value t
18973 texmathp-why '("Org mode embedded math" . 0))
18974 (when p ad-do-it)))))))))
18976 (defun turn-on-org-cdlatex ()
18977 "Unconditionally turn on `org-cdlatex-mode'."
18978 (org-cdlatex-mode 1))
18980 (defun org-try-cdlatex-tab ()
18981 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18982 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18983 - inside a LaTeX fragment, or
18984 - after the first word in a line, where an abbreviation expansion could
18985 insert a LaTeX environment."
18986 (when org-cdlatex-mode
18987 (cond
18988 ;; Before any word on the line: No expansion possible.
18989 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18990 ;; Just after first word on the line: Expand it. Make sure it
18991 ;; cannot happen on headlines, though.
18992 ((save-excursion
18993 (skip-chars-backward "a-zA-Z0-9*")
18994 (skip-chars-backward " \t")
18995 (and (bolp) (not (org-at-heading-p))))
18996 (cdlatex-tab) t)
18997 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18999 (defun org-cdlatex-underscore-caret (&optional _arg)
19000 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
19001 Revert to the normal definition outside of these fragments."
19002 (interactive "P")
19003 (if (org-inside-LaTeX-fragment-p)
19004 (call-interactively 'cdlatex-sub-superscript)
19005 (let (org-cdlatex-mode)
19006 (call-interactively (key-binding (vector last-input-event))))))
19008 (defun org-cdlatex-math-modify (&optional _arg)
19009 "Execute `cdlatex-math-modify' in LaTeX fragments.
19010 Revert to the normal definition outside of these fragments."
19011 (interactive "P")
19012 (if (org-inside-LaTeX-fragment-p)
19013 (call-interactively 'cdlatex-math-modify)
19014 (let (org-cdlatex-mode)
19015 (call-interactively (key-binding (vector last-input-event))))))
19017 (defun org-cdlatex-environment-indent (&optional environment item)
19018 "Execute `cdlatex-environment' and indent the inserted environment.
19020 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
19022 The inserted environment is indented to current indentation
19023 unless point is at the beginning of the line, in which the
19024 environment remains unintended."
19025 (interactive)
19026 ;; cdlatex-environment always return nil. Therefore, capture output
19027 ;; first and determine if an environment was selected.
19028 (let* ((beg (point-marker))
19029 (end (copy-marker (point) t))
19030 (inserted (progn
19031 (ignore-errors (cdlatex-environment environment item))
19032 (< beg end)))
19033 ;; Figure out how many lines to move forward after the
19034 ;; environment has been inserted.
19035 (lines (when inserted
19036 (save-excursion
19037 (- (cl-loop while (< beg (point))
19038 with x = 0
19039 do (forward-line -1)
19040 (cl-incf x)
19041 finally return x)
19042 (if (progn (goto-char beg)
19043 (and (progn (skip-chars-forward " \t") (eolp))
19044 (progn (skip-chars-backward " \t") (bolp))))
19045 1 0)))))
19046 (env (org-trim (delete-and-extract-region beg end))))
19047 (when inserted
19048 ;; Get indentation of next line unless at column 0.
19049 (let ((ind (if (bolp) 0
19050 (save-excursion
19051 (org-return-indent)
19052 (prog1 (org-get-indentation)
19053 (when (progn (skip-chars-forward " \t") (eolp))
19054 (delete-region beg (point)))))))
19055 (bol (progn (skip-chars-backward " \t") (bolp))))
19056 ;; Insert a newline before environment unless at column zero
19057 ;; to "escape" the current line. Insert a newline if
19058 ;; something is one the same line as \end{ENVIRONMENT}.
19059 (insert
19060 (concat (unless bol "\n") env
19061 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
19062 (unless (zerop ind)
19063 (save-excursion
19064 (goto-char beg)
19065 (while (< (point) end)
19066 (unless (eolp) (indent-line-to ind))
19067 (forward-line))))
19068 (goto-char beg)
19069 (forward-line lines)
19070 (indent-line-to ind)))
19071 (set-marker beg nil)
19072 (set-marker end nil)))
19075 ;;;; LaTeX fragments
19077 (defun org-inside-LaTeX-fragment-p ()
19078 "Test if point is inside a LaTeX fragment.
19079 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19080 sequence appearing also before point.
19081 Even though the matchers for math are configurable, this function assumes
19082 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19083 delimiters are skipped when they have been removed by customization.
19084 The return value is nil, or a cons cell with the delimiter and the
19085 position of this delimiter.
19087 This function does a reasonably good job, but can locally be fooled by
19088 for example currency specifications. For example it will assume being in
19089 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19090 fragments that are properly closed, but during editing, we have to live
19091 with the uncertainty caused by missing closing delimiters. This function
19092 looks only before point, not after."
19093 (catch 'exit
19094 (let ((pos (point))
19095 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19096 (lim (progn
19097 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19098 (point)))
19099 dd-on str (start 0) m re)
19100 (goto-char pos)
19101 (when dodollar
19102 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19103 re (nth 1 (assoc "$" org-latex-regexps)))
19104 (while (string-match re str start)
19105 (cond
19106 ((= (match-end 0) (length str))
19107 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19108 ((= (match-end 0) (- (length str) 5))
19109 (throw 'exit nil))
19110 (t (setq start (match-end 0))))))
19111 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19112 (goto-char pos)
19113 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19114 (and (match-beginning 2) (throw 'exit nil))
19115 ;; count $$
19116 (while (re-search-backward "\\$\\$" lim t)
19117 (setq dd-on (not dd-on)))
19118 (goto-char pos)
19119 (when dd-on (cons "$$" m))))))
19121 (defun org-inside-latex-macro-p ()
19122 "Is point inside a LaTeX macro or its arguments?"
19123 (save-match-data
19124 (org-in-regexp
19125 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19127 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19128 "Build an overlay between BEG and END using IMAGE file.
19129 Argument IMAGETYPE is the extension of the displayed image,
19130 as a string. It defaults to \"png\"."
19131 (let ((ov (make-overlay beg end))
19132 (imagetype (or (intern imagetype) 'png)))
19133 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19134 (overlay-put ov 'evaporate t)
19135 (overlay-put ov
19136 'modification-hooks
19137 (list (lambda (o _flag _beg _end &optional _l)
19138 (delete-overlay o))))
19139 (overlay-put ov
19140 'display
19141 (list 'image :type imagetype :file image :ascent 'center))))
19143 (defun org--list-latex-overlays (&optional beg end)
19144 "List all Org LaTeX overlays in current buffer.
19145 Limit to overlays between BEG and END when those are provided."
19146 (cl-remove-if-not
19147 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19148 (overlays-in (or beg (point-min)) (or end (point-max)))))
19150 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19151 "Remove all overlays with LaTeX fragment images in current buffer.
19152 When optional arguments BEG and END are non-nil, remove all
19153 overlays between them instead. Return a non-nil value when some
19154 overlays were removed, nil otherwise."
19155 (let ((overlays (org--list-latex-overlays beg end)))
19156 (mapc #'delete-overlay overlays)
19157 overlays))
19159 (defun org-toggle-latex-fragment (&optional arg)
19160 "Preview the LaTeX fragment at point, or all locally or globally.
19162 If the cursor is on a LaTeX fragment, create the image and overlay
19163 it over the source code, if there is none. Remove it otherwise.
19164 If there is no fragment at point, display all fragments in the
19165 current section.
19167 With prefix ARG, preview or clear image for all fragments in the
19168 current subtree or in the whole buffer when used before the first
19169 headline. With a prefix ARG `\\[universal-argument] \
19170 \\[universal-argument]' preview or clear images
19171 for all fragments in the buffer."
19172 (interactive "P")
19173 (when (display-graphic-p)
19174 (catch 'exit
19175 (save-excursion
19176 (let (beg end msg)
19177 (cond
19178 ((or (equal arg '(16))
19179 (and (equal arg '(4))
19180 (org-with-limited-levels (org-before-first-heading-p))))
19181 (if (org-remove-latex-fragment-image-overlays)
19182 (progn (message "LaTeX fragments images removed from buffer")
19183 (throw 'exit nil))
19184 (setq msg "Creating images for buffer...")))
19185 ((equal arg '(4))
19186 (org-with-limited-levels (org-back-to-heading t))
19187 (setq beg (point))
19188 (setq end (progn (org-end-of-subtree t) (point)))
19189 (if (org-remove-latex-fragment-image-overlays beg end)
19190 (progn
19191 (message "LaTeX fragment images removed from subtree")
19192 (throw 'exit nil))
19193 (setq msg "Creating images for subtree...")))
19194 ((let ((datum (org-element-context)))
19195 (when (memq (org-element-type datum)
19196 '(latex-environment latex-fragment))
19197 (setq beg (org-element-property :begin datum))
19198 (setq end (org-element-property :end datum))
19199 (if (org-remove-latex-fragment-image-overlays beg end)
19200 (progn (message "LaTeX fragment image removed")
19201 (throw 'exit nil))
19202 (setq msg "Creating image...")))))
19204 (org-with-limited-levels
19205 (setq beg (if (org-at-heading-p) (line-beginning-position)
19206 (outline-previous-heading)
19207 (point)))
19208 (setq end (progn (outline-next-heading) (point)))
19209 (if (org-remove-latex-fragment-image-overlays beg end)
19210 (progn
19211 (message "LaTeX fragment images removed from section")
19212 (throw 'exit nil))
19213 (setq msg "Creating images for section...")))))
19214 (let ((file (buffer-file-name (buffer-base-buffer))))
19215 (org-format-latex
19216 (concat org-preview-latex-image-directory "org-ltximg")
19217 beg end
19218 ;; Emacs cannot overlay images from remote hosts. Create
19219 ;; it in `temporary-file-directory' instead.
19220 (if (or (not file) (file-remote-p file))
19221 temporary-file-directory
19222 default-directory)
19223 'overlays msg 'forbuffer org-preview-latex-default-process))
19224 (message (concat msg "done")))))))
19226 (defun org-format-latex
19227 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19228 "Replace LaTeX fragments with links to an image.
19230 The function takes care of creating the replacement image.
19232 Only consider fragments between BEG and END when those are
19233 provided.
19235 When optional argument OVERLAYS is non-nil, display the image on
19236 top of the fragment instead of replacing it.
19238 PROCESSING-TYPE is the conversion method to use, as a symbol.
19240 Some of the options can be changed using the variable
19241 `org-format-latex-options', which see."
19242 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19243 (unless (eq processing-type 'verbatim)
19244 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19245 (cnt 0)
19246 checkdir-flag)
19247 (goto-char (or beg (point-min)))
19248 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19249 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19250 (overlay-recenter (or end (point-max))))
19251 (while (re-search-forward math-regexp end t)
19252 (unless (and overlays
19253 (eq (get-char-property (point) 'org-overlay-type)
19254 'org-latex-overlay))
19255 (let* ((context (org-element-context))
19256 (type (org-element-type context)))
19257 (when (memq type '(latex-environment latex-fragment))
19258 (let ((block-type (eq type 'latex-environment))
19259 (value (org-element-property :value context))
19260 (beg (org-element-property :begin context))
19261 (end (save-excursion
19262 (goto-char (org-element-property :end context))
19263 (skip-chars-backward " \r\t\n")
19264 (point))))
19265 (cond
19266 ((eq processing-type 'mathjax)
19267 ;; Prepare for MathJax processing.
19268 (if (not (string-match "\\`\\$\\$?" value))
19269 (goto-char end)
19270 (delete-region beg end)
19271 (if (string= (match-string 0 value) "$$")
19272 (insert "\\[" (substring value 2 -2) "\\]")
19273 (insert "\\(" (substring value 1 -1) "\\)"))))
19274 ((assq processing-type org-preview-latex-process-alist)
19275 ;; Process to an image.
19276 (cl-incf cnt)
19277 (goto-char beg)
19278 (let* ((processing-info
19279 (cdr (assq processing-type org-preview-latex-process-alist)))
19280 (face (face-at-point))
19281 ;; Get the colors from the face at point.
19283 (let ((color (plist-get org-format-latex-options
19284 :foreground)))
19285 (if (and forbuffer (eq color 'auto))
19286 (face-attribute face :foreground nil 'default)
19287 color)))
19289 (let ((color (plist-get org-format-latex-options
19290 :background)))
19291 (if (and forbuffer (eq color 'auto))
19292 (face-attribute face :background nil 'default)
19293 color)))
19294 (hash (sha1 (prin1-to-string
19295 (list org-format-latex-header
19296 org-latex-default-packages-alist
19297 org-latex-packages-alist
19298 org-format-latex-options
19299 forbuffer value fg bg))))
19300 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19301 (absprefix (expand-file-name prefix dir))
19302 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19303 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19304 (sep (and block-type "\n\n"))
19305 (link (concat sep "[[file:" linkfile "]]" sep))
19306 (options
19307 (org-combine-plists
19308 org-format-latex-options
19309 `(:foreground ,fg :background ,bg))))
19310 (when msg (message msg cnt))
19311 (unless checkdir-flag ; Ensure the directory exists.
19312 (setq checkdir-flag t)
19313 (let ((todir (file-name-directory absprefix)))
19314 (unless (file-directory-p todir)
19315 (make-directory todir t))))
19316 (unless (file-exists-p movefile)
19317 (org-create-formula-image
19318 value movefile options forbuffer processing-type))
19319 (if overlays
19320 (progn
19321 (dolist (o (overlays-in beg end))
19322 (when (eq (overlay-get o 'org-overlay-type)
19323 'org-latex-overlay)
19324 (delete-overlay o)))
19325 (org--format-latex-make-overlay beg end movefile imagetype)
19326 (goto-char end))
19327 (delete-region beg end)
19328 (insert
19329 (org-add-props link
19330 (list 'org-latex-src
19331 (replace-regexp-in-string "\"" "" value)
19332 'org-latex-src-embed-type
19333 (if block-type 'paragraph 'character)))))))
19334 ((eq processing-type 'mathml)
19335 ;; Process to MathML.
19336 (unless (org-format-latex-mathml-available-p)
19337 (user-error "LaTeX to MathML converter not configured"))
19338 (cl-incf cnt)
19339 (when msg (message msg cnt))
19340 (goto-char beg)
19341 (delete-region beg end)
19342 (insert (org-format-latex-as-mathml
19343 value block-type prefix dir)))
19345 (error "Unknown conversion process %s for LaTeX fragments"
19346 processing-type)))))))))))
19348 (defun org-create-math-formula (latex-frag &optional mathml-file)
19349 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19350 Use `org-latex-to-mathml-convert-command'. If the conversion is
19351 sucessful, return the portion between \"<math...> </math>\"
19352 elements otherwise return nil. When MATHML-FILE is specified,
19353 write the results in to that file. When invoked as an
19354 interactive command, prompt for LATEX-FRAG, with initial value
19355 set to the current active region and echo the results for user
19356 inspection."
19357 (interactive (list (let ((frag (when (org-region-active-p)
19358 (buffer-substring-no-properties
19359 (region-beginning) (region-end)))))
19360 (read-string "LaTeX Fragment: " frag nil frag))))
19361 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19362 (let* ((tmp-in-file
19363 (let ((file (file-relative-name
19364 (make-temp-name (expand-file-name "ltxmathml-in")))))
19365 (write-region latex-frag nil file)
19366 file))
19367 (tmp-out-file (file-relative-name
19368 (make-temp-name (expand-file-name "ltxmathml-out"))))
19369 (cmd (format-spec
19370 org-latex-to-mathml-convert-command
19371 `((?j . ,(and org-latex-to-mathml-jar-file
19372 (shell-quote-argument
19373 (expand-file-name
19374 org-latex-to-mathml-jar-file))))
19375 (?I . ,(shell-quote-argument tmp-in-file))
19376 (?i . ,latex-frag)
19377 (?o . ,(shell-quote-argument tmp-out-file)))))
19378 mathml shell-command-output)
19379 (when (called-interactively-p 'any)
19380 (unless (org-format-latex-mathml-available-p)
19381 (user-error "LaTeX to MathML converter not configured")))
19382 (message "Running %s" cmd)
19383 (setq shell-command-output (shell-command-to-string cmd))
19384 (setq mathml
19385 (when (file-readable-p tmp-out-file)
19386 (with-current-buffer (find-file-noselect tmp-out-file t)
19387 (goto-char (point-min))
19388 (when (re-search-forward
19389 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19390 (regexp-quote
19391 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19392 nil t)
19393 (prog1 (match-string 0) (kill-buffer))))))
19394 (cond
19395 (mathml
19396 (setq mathml
19397 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19398 (when mathml-file
19399 (write-region mathml nil mathml-file))
19400 (when (called-interactively-p 'any)
19401 (message mathml)))
19402 ((message "LaTeX to MathML conversion failed")
19403 (message shell-command-output)))
19404 (delete-file tmp-in-file)
19405 (when (file-exists-p tmp-out-file)
19406 (delete-file tmp-out-file))
19407 mathml))
19409 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19410 prefix &optional dir)
19411 "Use `org-create-math-formula' but check local cache first."
19412 (let* ((absprefix (expand-file-name prefix dir))
19413 (print-length nil) (print-level nil)
19414 (formula-id (concat
19415 "formula-"
19416 (sha1
19417 (prin1-to-string
19418 (list latex-frag
19419 org-latex-to-mathml-convert-command)))))
19420 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19421 (formula-cache-dir (file-name-directory formula-cache)))
19423 (unless (file-directory-p formula-cache-dir)
19424 (make-directory formula-cache-dir t))
19426 (unless (file-exists-p formula-cache)
19427 (org-create-math-formula latex-frag formula-cache))
19429 (if (file-exists-p formula-cache)
19430 ;; Successful conversion. Return the link to MathML file.
19431 (org-add-props
19432 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19433 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19434 'org-latex-src-embed-type (if latex-frag-type
19435 'paragraph 'character)))
19436 ;; Failed conversion. Return the LaTeX fragment verbatim
19437 latex-frag)))
19439 (declare-function org-export-get-backend "ox" (name))
19440 (declare-function org-export--get-global-options "ox" (&optional backend))
19441 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19442 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19443 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19444 (defun org-create-formula--latex-header ()
19445 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19446 (let ((info (org-combine-plists (org-export--get-global-options
19447 (org-export-get-backend 'latex))
19448 (org-export--get-inbuffer-options
19449 (org-export-get-backend 'latex)))))
19450 (org-latex-guess-babel-language
19451 (org-latex-guess-inputenc
19452 (org-splice-latex-header
19453 org-format-latex-header
19454 org-latex-default-packages-alist
19455 org-latex-packages-alist t
19456 (plist-get info :latex-header)))
19457 info)))
19459 (defun org--get-display-dpi ()
19460 "Get the DPI of the display.
19462 Assumes that the display has the same pixel width in the
19463 horizontal and vertical directions."
19464 (if (display-graphic-p)
19465 (round (/ (display-pixel-height)
19466 (/ (display-mm-height) 25.4)))
19467 (error "Attempt to calculate the dpi of a non-graphic display")))
19469 (defun org-create-formula-image
19470 (string tofile options buffer &optional processing-type)
19471 "Create an image from LaTeX source using external processes.
19473 The LaTeX STRING is saved to a temporary LaTeX file, then
19474 converted to an image file by process PROCESSING-TYPE defined in
19475 `org-preview-latex-process-alist'. A nil value defaults to
19476 `org-preview-latex-default-process'.
19478 The generated image file is eventually moved to TOFILE.
19480 The OPTIONS argument controls the size, foreground color and
19481 background color of the generated image.
19483 When BUFFER non-nil, this function is used for LaTeX previewing.
19484 Otherwise, it is used to deal with LaTeX snippets showed in
19485 a HTML file."
19486 (let* ((processing-type (or processing-type
19487 org-preview-latex-default-process))
19488 (processing-info
19489 (cdr (assq processing-type org-preview-latex-process-alist)))
19490 (programs (plist-get processing-info :programs))
19491 (error-message (or (plist-get processing-info :message) ""))
19492 (use-xcolor (plist-get processing-info :use-xcolor))
19493 (image-input-type (plist-get processing-info :image-input-type))
19494 (image-output-type (plist-get processing-info :image-output-type))
19495 (post-clean (or (plist-get processing-info :post-clean)
19496 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19497 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19498 (latex-header (or (plist-get processing-info :latex-header)
19499 (org-create-formula--latex-header)))
19500 (latex-compiler (plist-get processing-info :latex-compiler))
19501 (image-converter (plist-get processing-info :image-converter))
19502 (tmpdir temporary-file-directory)
19503 (texfilebase (make-temp-name
19504 (expand-file-name "orgtex" tmpdir)))
19505 (texfile (concat texfilebase ".tex"))
19506 (font-height (face-attribute 'default :height nil))
19507 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19508 '(1.0 . 1.0)))
19509 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19510 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19511 (dpi (* scale (floor (if buffer font-height 140.0))))
19512 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19513 "Black"))
19514 (bg (or (plist-get options (if buffer :background :html-background))
19515 "Transparent"))
19516 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19517 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19518 (dolist (program programs)
19519 (org-check-external-command program error-message))
19520 (if use-xcolor
19521 (progn (if (eq fg 'default)
19522 (setq fg (org-latex-color :foreground))
19523 (setq fg (org-latex-color-format fg)))
19524 (if (eq bg 'default)
19525 (setq bg (org-latex-color :background))
19526 (setq bg (org-latex-color-format
19527 (if (string= bg "Transparent") "white" bg))))
19528 (with-temp-file texfile
19529 (insert latex-header)
19530 (insert "\n\\begin{document}\n"
19531 "\\definecolor{fg}{rgb}{" fg "}\n"
19532 "\\definecolor{bg}{rgb}{" bg "}\n"
19533 "\n\\pagecolor{bg}\n"
19534 "\n{\\color{fg}\n"
19535 string
19536 "\n}\n"
19537 "\n\\end{document}\n")))
19538 (if (eq fg 'default)
19539 (setq fg (org-dvipng-color :foreground))
19540 (unless (string= fg "Transparent")
19541 (setq fg (org-dvipng-color-format fg))))
19542 (if (eq bg 'default)
19543 (setq bg (org-dvipng-color :background))
19544 (unless (string= bg "Transparent")
19545 (setq bg (org-dvipng-color-format bg))))
19546 (with-temp-file texfile
19547 (insert latex-header)
19548 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19550 (let* ((err-msg (format "Please adjust '%s' part of \
19551 `org-preview-latex-process-alist'."
19552 processing-type))
19553 (image-input-file
19554 (org-compile-file
19555 texfile latex-compiler image-input-type err-msg log-buf))
19556 (image-output-file
19557 (org-compile-file
19558 image-input-file image-converter image-output-type err-msg log-buf
19559 `((?F . ,(shell-quote-argument fg))
19560 (?B . ,(shell-quote-argument bg))
19561 (?D . ,(shell-quote-argument (format "%s" dpi)))
19562 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19563 (copy-file image-output-file tofile 'replace)
19564 (dolist (e post-clean)
19565 (when (file-exists-p (concat texfilebase e))
19566 (delete-file (concat texfilebase e))))
19567 image-output-file)))
19569 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19570 "Fill a LaTeX header template TPL.
19571 In the template, the following place holders will be recognized:
19573 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19574 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19575 [PACKAGES] \\usepackage statements for PKG
19576 [NO-PACKAGES] do not include PKG
19577 [EXTRA] the string EXTRA
19578 [NO-EXTRA] do not include EXTRA
19580 For backward compatibility, if both the positive and the negative place
19581 holder is missing, the positive one (without the \"NO-\") will be
19582 assumed to be present at the end of the template.
19583 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19584 EXTRA is a string.
19585 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19586 (let (rpl (end ""))
19587 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19588 (setq rpl (if (or (match-end 1) (not def-pkg))
19589 "" (org-latex-packages-to-string def-pkg snippets-p t))
19590 tpl (replace-match rpl t t tpl))
19591 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19593 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19594 (setq rpl (if (or (match-end 1) (not pkg))
19595 "" (org-latex-packages-to-string pkg snippets-p t))
19596 tpl (replace-match rpl t t tpl))
19597 (when pkg (setq end
19598 (concat end "\n"
19599 (org-latex-packages-to-string pkg snippets-p)))))
19601 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19602 (setq rpl (if (or (match-end 1) (not extra))
19603 "" (concat extra "\n"))
19604 tpl (replace-match rpl t t tpl))
19605 (when (and extra (string-match "\\S-" extra))
19606 (setq end (concat end "\n" extra))))
19608 (if (string-match "\\S-" end)
19609 (concat tpl "\n" end)
19610 tpl)))
19612 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19613 "Turn an alist of packages into a string with the \\usepackage macros."
19614 (setq pkg (mapconcat (lambda(p)
19615 (cond
19616 ((stringp p) p)
19617 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19618 (format "%% Package %s omitted" (cadr p)))
19619 ((equal "" (car p))
19620 (format "\\usepackage{%s}" (cadr p)))
19622 (format "\\usepackage[%s]{%s}"
19623 (car p) (cadr p)))))
19625 "\n"))
19626 (if newline (concat pkg "\n") pkg))
19628 (defun org-dvipng-color (attr)
19629 "Return a RGB color specification for dvipng."
19630 (org-dvipng-color-format (face-attribute 'default attr nil)))
19632 (defun org-dvipng-color-format (color-name)
19633 "Convert COLOR-NAME to a RGB color value for dvipng."
19634 (apply #'format "rgb %s %s %s"
19635 (mapcar 'org-normalize-color
19636 (color-values color-name))))
19638 (defun org-latex-color (attr)
19639 "Return a RGB color for the LaTeX color package."
19640 (org-latex-color-format (face-attribute 'default attr nil)))
19642 (defun org-latex-color-format (color-name)
19643 "Convert COLOR-NAME to a RGB color value."
19644 (apply #'format "%s,%s,%s"
19645 (mapcar 'org-normalize-color
19646 (color-values color-name))))
19648 (defun org-normalize-color (value)
19649 "Return string to be used as color value for an RGB component."
19650 (format "%g" (/ value 65535.0)))
19654 ;; Image display
19656 (defvar-local org-inline-image-overlays nil)
19658 (defun org-toggle-inline-images (&optional include-linked)
19659 "Toggle the display of inline images.
19660 INCLUDE-LINKED is passed to `org-display-inline-images'."
19661 (interactive "P")
19662 (if org-inline-image-overlays
19663 (progn
19664 (org-remove-inline-images)
19665 (when (called-interactively-p 'interactive)
19666 (message "Inline image display turned off")))
19667 (org-display-inline-images include-linked)
19668 (when (called-interactively-p 'interactive)
19669 (message (if org-inline-image-overlays
19670 (format "%d images displayed inline"
19671 (length org-inline-image-overlays))
19672 "No images to display inline")))))
19674 (defun org-redisplay-inline-images ()
19675 "Refresh the display of inline images."
19676 (interactive)
19677 (if (not org-inline-image-overlays)
19678 (org-toggle-inline-images)
19679 (org-toggle-inline-images)
19680 (org-toggle-inline-images)))
19682 (defun org-display-inline-images (&optional include-linked refresh beg end)
19683 "Display inline images.
19685 An inline image is a link which follows either of these
19686 conventions:
19688 1. Its path is a file with an extension matching return value
19689 from `image-file-name-regexp' and it has no contents.
19691 2. Its description consists in a single link of the previous
19692 type.
19694 When optional argument INCLUDE-LINKED is non-nil, also links with
19695 a text description part will be inlined. This can be nice for
19696 a quick look at those images, but it does not reflect what
19697 exported files will look like.
19699 When optional argument REFRESH is non-nil, refresh existing
19700 images between BEG and END. This will create new image displays
19701 only if necessary. BEG and END default to the buffer
19702 boundaries."
19703 (interactive "P")
19704 (when (display-graphic-p)
19705 (unless refresh
19706 (org-remove-inline-images)
19707 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19708 (org-with-wide-buffer
19709 (goto-char (or beg (point-min)))
19710 (let ((case-fold-search t)
19711 (file-extension-re (image-file-name-regexp)))
19712 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19713 (let ((link (save-match-data (org-element-context))))
19714 ;; Check if we're at an inline image.
19715 (when (and (equal (org-element-property :type link) "file")
19716 (or include-linked
19717 (not (org-element-property :contents-begin link)))
19718 (let ((parent (org-element-property :parent link)))
19719 (or (not (eq (org-element-type parent) 'link))
19720 (not (cdr (org-element-contents parent)))))
19721 (string-match-p file-extension-re
19722 (org-element-property :path link)))
19723 (let ((file (expand-file-name
19724 (org-link-unescape
19725 (org-element-property :path link)))))
19726 (when (file-exists-p file)
19727 (let ((width
19728 ;; Apply `org-image-actual-width' specifications.
19729 (cond
19730 ((not (image-type-available-p 'imagemagick)) nil)
19731 ((eq org-image-actual-width t) nil)
19732 ((listp org-image-actual-width)
19734 ;; First try to find a width among
19735 ;; attributes associated to the paragraph
19736 ;; containing link.
19737 (let ((paragraph
19738 (let ((e link))
19739 (while (and (setq e (org-element-property
19740 :parent e))
19741 (not (eq (org-element-type e)
19742 'paragraph))))
19743 e)))
19744 (when paragraph
19745 (save-excursion
19746 (goto-char (org-element-property :begin paragraph))
19747 (when
19748 (re-search-forward
19749 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19750 (org-element-property
19751 :post-affiliated paragraph)
19753 (string-to-number (match-string 1))))))
19754 ;; Otherwise, fall-back to provided number.
19755 (car org-image-actual-width)))
19756 ((numberp org-image-actual-width)
19757 org-image-actual-width)))
19758 (old (get-char-property-and-overlay
19759 (org-element-property :begin link)
19760 'org-image-overlay)))
19761 (if (and (car-safe old) refresh)
19762 (image-refresh (overlay-get (cdr old) 'display))
19763 (let ((image (create-image file
19764 (and width 'imagemagick)
19766 :width width)))
19767 (when image
19768 (let* ((link
19769 ;; If inline image is the description
19770 ;; of another link, be sure to
19771 ;; consider the latter as the one to
19772 ;; apply the overlay on.
19773 (let ((parent
19774 (org-element-property :parent link)))
19775 (if (eq (org-element-type parent) 'link)
19776 parent
19777 link)))
19778 (ov (make-overlay
19779 (org-element-property :begin link)
19780 (progn
19781 (goto-char
19782 (org-element-property :end link))
19783 (skip-chars-backward " \t")
19784 (point)))))
19785 (overlay-put ov 'display image)
19786 (overlay-put ov 'face 'default)
19787 (overlay-put ov 'org-image-overlay t)
19788 (overlay-put
19789 ov 'modification-hooks
19790 (list 'org-display-inline-remove-overlay))
19791 (push ov org-inline-image-overlays)))))))))))))))
19793 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19794 "Remove inline-display overlay if a corresponding region is modified."
19795 (let ((inhibit-modification-hooks t))
19796 (when (and ov after)
19797 (delete ov org-inline-image-overlays)
19798 (delete-overlay ov))))
19800 (defun org-remove-inline-images ()
19801 "Remove inline display of images."
19802 (interactive)
19803 (mapc #'delete-overlay org-inline-image-overlays)
19804 (setq org-inline-image-overlays nil))
19806 ;;;; Key bindings
19808 ;; Outline functions from `outline-mode-prefix-map'
19809 ;; that can be remapped in Org:
19810 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19811 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19812 (define-key org-mode-map [remap outline-forward-same-level]
19813 'org-forward-heading-same-level)
19814 (define-key org-mode-map [remap outline-backward-same-level]
19815 'org-backward-heading-same-level)
19816 (define-key org-mode-map [remap outline-show-branches]
19817 'org-kill-note-or-show-branches)
19818 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19819 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19820 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19821 (define-key org-mode-map [remap outline-next-visible-heading]
19822 'org-next-visible-heading)
19823 (define-key org-mode-map [remap outline-previous-visible-heading]
19824 'org-previous-visible-heading)
19825 (define-key org-mode-map [remap show-children] 'org-show-children)
19827 ;; Outline functions from `outline-mode-prefix-map' that can not
19828 ;; be remapped in Org:
19830 ;; - the column "key binding" shows whether the Outline function is still
19831 ;; available in Org mode on the same key that it has been bound to in
19832 ;; Outline mode:
19833 ;; - "overridden": key used for a different functionality in Org mode
19834 ;; - else: key still bound to the same Outline function in Org mode
19836 ;; | Outline function | key binding | Org replacement |
19837 ;; |------------------------------------+-------------+--------------------------|
19838 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19839 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19840 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19841 ;; | `show-entry' | overridden | no replacement |
19842 ;; | `show-branches' | `C-c C-k' | still same function |
19843 ;; | `show-subtree' | overridden | visibility cycling |
19844 ;; | `show-all' | overridden | no replacement |
19845 ;; | `hide-subtree' | overridden | visibility cycling |
19846 ;; | `hide-body' | overridden | no replacement |
19847 ;; | `hide-entry' | overridden | visibility cycling |
19848 ;; | `hide-leaves' | overridden | no replacement |
19849 ;; | `hide-sublevels' | overridden | no replacement |
19850 ;; | `hide-other' | overridden | no replacement |
19852 ;; Make `C-c C-x' a prefix key
19853 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19855 ;; TAB key with modifiers
19856 (org-defkey org-mode-map "\C-i" 'org-cycle)
19857 (org-defkey org-mode-map [(tab)] 'org-cycle)
19858 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19859 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19860 ;; The following line is necessary under Suse GNU/Linux
19861 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19862 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19863 (define-key org-mode-map [backtab] 'org-shifttab)
19865 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19866 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19867 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19869 ;; Cursor keys with modifiers
19870 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19871 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19872 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19873 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19875 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19876 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19877 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19878 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19879 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19880 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19882 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19883 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19884 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19885 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19887 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19888 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19889 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19890 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19892 ;; Babel keys
19893 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19894 (dolist (pair org-babel-key-bindings)
19895 (define-key org-babel-map (car pair) (cdr pair)))
19897 ;;; Extra keys for tty access.
19898 ;; We only set them when really needed because otherwise the
19899 ;; menus don't show the simple keys
19901 (when (or org-use-extra-keys (not window-system))
19902 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19903 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19904 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19905 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19906 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19907 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19908 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19909 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19910 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19911 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19912 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19913 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19914 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19915 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19916 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19917 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19918 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19919 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19920 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19921 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19922 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19923 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19924 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19925 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19926 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19927 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19928 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19929 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19931 ;; All the other keys
19933 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19934 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19935 (if (boundp 'narrow-map)
19936 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19937 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19938 (if (boundp 'narrow-map)
19939 (org-defkey narrow-map "b" 'org-narrow-to-block)
19940 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19941 (if (boundp 'narrow-map)
19942 (org-defkey narrow-map "e" 'org-narrow-to-element)
19943 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19944 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19945 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19946 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19947 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19948 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19949 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19950 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19951 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19952 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19953 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19954 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19955 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19956 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19957 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19958 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19959 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19960 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19961 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19962 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19963 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19964 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19965 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19966 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19967 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19968 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19969 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19970 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19971 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19972 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19973 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19974 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19975 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19976 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19977 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19978 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19979 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19980 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19981 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19982 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19983 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19984 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19985 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19986 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19987 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19988 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19989 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19990 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19991 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19992 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19993 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19994 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19995 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19996 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19997 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19998 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19999 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
20000 (org-defkey org-mode-map "\C-c^" 'org-sort)
20001 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
20002 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
20003 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
20004 (org-defkey org-mode-map [remap open-line] 'org-open-line)
20005 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
20006 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
20007 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
20008 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
20009 (org-defkey org-mode-map "\C-m" 'org-return)
20010 (org-defkey org-mode-map "\C-j" 'org-return-indent)
20011 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
20012 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
20013 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
20014 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
20015 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
20016 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
20017 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
20018 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
20019 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
20020 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
20021 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
20022 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
20023 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
20024 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
20025 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
20026 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
20027 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
20028 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
20029 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
20030 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
20031 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
20032 (org-defkey org-mode-map "\M-h" 'org-mark-element)
20033 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
20034 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
20036 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
20037 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
20038 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
20040 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
20041 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
20042 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
20043 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
20044 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
20045 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
20046 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
20047 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
20048 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
20049 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
20050 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
20051 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
20052 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
20053 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
20054 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
20055 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
20056 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
20057 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
20058 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
20059 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
20060 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
20061 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
20063 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
20064 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
20065 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
20066 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
20067 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
20069 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
20071 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
20073 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
20074 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
20076 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20079 (defconst org-speed-commands-default
20081 ("Outline Navigation")
20082 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20083 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20084 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20085 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20086 ("F" . org-next-block)
20087 ("B" . org-previous-block)
20088 ("u" . (org-speed-move-safe 'outline-up-heading))
20089 ("j" . org-goto)
20090 ("g" . (org-refile t))
20091 ("Outline Visibility")
20092 ("c" . org-cycle)
20093 ("C" . org-shifttab)
20094 (" " . org-display-outline-path)
20095 ("s" . org-narrow-to-subtree)
20096 ("=" . org-columns)
20097 ("Outline Structure Editing")
20098 ("U" . org-metaup)
20099 ("D" . org-metadown)
20100 ("r" . org-metaright)
20101 ("l" . org-metaleft)
20102 ("R" . org-shiftmetaright)
20103 ("L" . org-shiftmetaleft)
20104 ("i" . (progn (forward-char 1) (call-interactively
20105 'org-insert-heading-respect-content)))
20106 ("^" . org-sort)
20107 ("w" . org-refile)
20108 ("a" . org-archive-subtree-default-with-confirmation)
20109 ("@" . org-mark-subtree)
20110 ("#" . org-toggle-comment)
20111 ("Clock Commands")
20112 ("I" . org-clock-in)
20113 ("O" . org-clock-out)
20114 ("Meta Data Editing")
20115 ("t" . org-todo)
20116 ("," . (org-priority))
20117 ("0" . (org-priority ?\ ))
20118 ("1" . (org-priority ?A))
20119 ("2" . (org-priority ?B))
20120 ("3" . (org-priority ?C))
20121 (":" . org-set-tags-command)
20122 ("e" . org-set-effort)
20123 ("E" . org-inc-effort)
20124 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20125 (org-entry-put (point) "APPT_WARNTIME" m)))
20126 ("Agenda Views etc")
20127 ("v" . org-agenda)
20128 ("/" . org-sparse-tree)
20129 ("Misc")
20130 ("o" . org-open-at-point)
20131 ("?" . org-speed-command-help)
20132 ("<" . (org-agenda-set-restriction-lock 'subtree))
20133 (">" . (org-agenda-remove-restriction-lock))
20135 "The default speed commands.")
20137 (defun org-print-speed-command (e)
20138 (if (> (length (car e)) 1)
20139 (progn
20140 (princ "\n")
20141 (princ (car e))
20142 (princ "\n")
20143 (princ (make-string (length (car e)) ?-))
20144 (princ "\n"))
20145 (princ (car e))
20146 (princ " ")
20147 (if (symbolp (cdr e))
20148 (princ (symbol-name (cdr e)))
20149 (prin1 (cdr e)))
20150 (princ "\n")))
20152 (defun org-speed-command-help ()
20153 "Show the available speed commands."
20154 (interactive)
20155 (if (not org-use-speed-commands)
20156 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20157 (with-output-to-temp-buffer "*Help*"
20158 (princ "User-defined Speed commands\n===========================\n")
20159 (mapc #'org-print-speed-command org-speed-commands-user)
20160 (princ "\n")
20161 (princ "Built-in Speed commands\n=======================\n")
20162 (mapc #'org-print-speed-command org-speed-commands-default))
20163 (with-current-buffer "*Help*"
20164 (setq truncate-lines t))))
20166 (defun org-speed-move-safe (cmd)
20167 "Execute CMD, but make sure that the cursor always ends up in a headline.
20168 If not, return to the original position and throw an error."
20169 (interactive)
20170 (let ((pos (point)))
20171 (call-interactively cmd)
20172 (unless (and (bolp) (org-at-heading-p))
20173 (goto-char pos)
20174 (error "Boundary reached while executing %s" cmd))))
20176 (defvar org-self-insert-command-undo-counter 0)
20178 (defvar org-table-auto-blank-field) ; defined in org-table.el
20179 (defvar org-speed-command nil)
20181 (defun org-speed-command-activate (keys)
20182 "Hook for activating single-letter speed commands.
20183 `org-speed-commands-default' specifies a minimal command set.
20184 Use `org-speed-commands-user' for further customization."
20185 (when (or (and (bolp) (looking-at org-outline-regexp))
20186 (and (functionp org-use-speed-commands)
20187 (funcall org-use-speed-commands)))
20188 (cdr (assoc keys (append org-speed-commands-user
20189 org-speed-commands-default)))))
20191 (defun org-babel-speed-command-activate (keys)
20192 "Hook for activating single-letter code block commands."
20193 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20194 (cdr (assoc keys org-babel-key-bindings))))
20196 (defcustom org-speed-command-hook
20197 '(org-speed-command-default-hook org-babel-speed-command-hook)
20198 "Hook for activating speed commands at strategic locations.
20199 Hook functions are called in sequence until a valid handler is
20200 found.
20202 Each hook takes a single argument, a user-pressed command key
20203 which is also a `self-insert-command' from the global map.
20205 Within the hook, examine the cursor position and the command key
20206 and return nil or a valid handler as appropriate. Handler could
20207 be one of an interactive command, a function, or a form.
20209 Set `org-use-speed-commands' to non-nil value to enable this
20210 hook. The default setting is `org-speed-command-activate'."
20211 :group 'org-structure
20212 :version "24.1"
20213 :type 'hook)
20215 (defun org-self-insert-command (N)
20216 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20217 If the cursor is in a table looking at whitespace, the whitespace is
20218 overwritten, and the table is not marked as requiring realignment."
20219 (interactive "p")
20220 (org-check-before-invisible-edit 'insert)
20221 (cond
20222 ((and org-use-speed-commands
20223 (let ((kv (this-command-keys-vector)))
20224 (setq org-speed-command
20225 (run-hook-with-args-until-success
20226 'org-speed-command-hook
20227 (make-string 1 (aref kv (1- (length kv))))))))
20228 (cond
20229 ((commandp org-speed-command)
20230 (setq this-command org-speed-command)
20231 (call-interactively org-speed-command))
20232 ((functionp org-speed-command)
20233 (funcall org-speed-command))
20234 ((and org-speed-command (listp org-speed-command))
20235 (eval org-speed-command))
20236 (t (let (org-use-speed-commands)
20237 (call-interactively 'org-self-insert-command)))))
20238 ((and
20239 (org-at-table-p)
20240 (progn
20241 ;; Check if we blank the field, and if that triggers align.
20242 (and (featurep 'org-table) org-table-auto-blank-field
20243 (memq last-command
20244 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20245 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20246 ;; Got extra space, this field does not determine
20247 ;; column width.
20248 (let (org-table-may-need-update) (org-table-blank-field))
20249 ;; No extra space, this field may determine column
20250 ;; width.
20251 (org-table-blank-field)))
20253 (eq N 1)
20254 (looking-at "[^|\n]* \\( \\)|"))
20255 ;; There is room for insertion without re-aligning the table.
20256 (delete-region (match-beginning 1) (match-end 1))
20257 (self-insert-command N))
20259 (setq org-table-may-need-update t)
20260 (self-insert-command N)
20261 (org-fix-tags-on-the-fly)
20262 (when org-self-insert-cluster-for-undo
20263 (if (not (eq last-command 'org-self-insert-command))
20264 (setq org-self-insert-command-undo-counter 1)
20265 (if (>= org-self-insert-command-undo-counter 20)
20266 (setq org-self-insert-command-undo-counter 1)
20267 (and (> org-self-insert-command-undo-counter 0)
20268 buffer-undo-list (listp buffer-undo-list)
20269 (not (cadr buffer-undo-list)) ; remove nil entry
20270 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20271 (setq org-self-insert-command-undo-counter
20272 (1+ org-self-insert-command-undo-counter))))))))
20274 (defun org-check-before-invisible-edit (kind)
20275 "Check is editing if kind KIND would be dangerous with invisible text around.
20276 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20277 ;; First, try to get out of here as quickly as possible, to reduce overhead
20278 (when (and org-catch-invisible-edits
20279 (or (not (boundp 'visible-mode)) (not visible-mode))
20280 (or (get-char-property (point) 'invisible)
20281 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20282 ;; OK, we need to take a closer look
20283 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20284 (invisible-before-point (unless (bobp) (get-char-property
20285 (1- (point)) 'invisible)))
20286 (border-and-ok-direction
20288 ;; Check if we are acting predictably before invisible text
20289 (and invisible-at-point (not invisible-before-point)
20290 (memq kind '(insert delete-backward)))
20291 ;; Check if we are acting predictably after invisible text
20292 ;; This works not well, and I have turned it off. It seems
20293 ;; better to always show and stop after invisible text.
20294 ;; (and (not invisible-at-point) invisible-before-point
20295 ;; (memq kind '(insert delete)))
20297 (when (or (memq invisible-at-point '(outline org-hide-block t))
20298 (memq invisible-before-point '(outline org-hide-block t)))
20299 (when (eq org-catch-invisible-edits 'error)
20300 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20301 (if (and org-custom-properties-overlays
20302 (y-or-n-p "Display invisible properties in this buffer? "))
20303 (org-toggle-custom-properties-visibility)
20304 ;; Make the area visible
20305 (save-excursion
20306 (when invisible-before-point
20307 (goto-char (previous-single-char-property-change
20308 (point) 'invisible)))
20309 (outline-show-subtree))
20310 (cond
20311 ((eq org-catch-invisible-edits 'show)
20312 ;; That's it, we do the edit after showing
20313 (message
20314 "Unfolding invisible region around point before editing")
20315 (sit-for 1))
20316 ((and (eq org-catch-invisible-edits 'smart)
20317 border-and-ok-direction)
20318 (message "Unfolding invisible region around point before editing"))
20320 ;; Don't do the edit, make the user repeat it in full visibility
20321 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20323 (defun org-fix-tags-on-the-fly ()
20324 "Align tags in headline at point.
20325 Unlike to `org-set-tags', it ignores region and sorting."
20326 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
20327 (org-at-heading-p))
20328 (let ((org-ignore-region t)
20329 (org-tags-sort-function nil))
20330 (org-set-tags nil t))))
20332 (defun org-delete-backward-char (N)
20333 "Like `delete-backward-char', insert whitespace at field end in tables.
20334 When deleting backwards, in tables this function will insert whitespace in
20335 front of the next \"|\" separator, to keep the table aligned. The table will
20336 still be marked for re-alignment if the field did fill the entire column,
20337 because, in this case the deletion might narrow the column."
20338 (interactive "p")
20339 (save-match-data
20340 (org-check-before-invisible-edit 'delete-backward)
20341 (if (and (org-at-table-p)
20342 (eq N 1)
20343 (string-match "|" (buffer-substring (point-at-bol) (point)))
20344 (looking-at ".*?|"))
20345 (let ((pos (point))
20346 (noalign (looking-at "[^|\n\r]* |"))
20347 (c org-table-may-need-update))
20348 (backward-delete-char N)
20349 (unless overwrite-mode
20350 (skip-chars-forward "^|")
20351 (insert " ")
20352 (goto-char (1- pos)))
20353 ;; noalign: if there were two spaces at the end, this field
20354 ;; does not determine the width of the column.
20355 (when noalign (setq org-table-may-need-update c)))
20356 (backward-delete-char N)
20357 (org-fix-tags-on-the-fly))))
20359 (defun org-delete-char (N)
20360 "Like `delete-char', but insert whitespace at field end in tables.
20361 When deleting characters, in tables this function will insert whitespace in
20362 front of the next \"|\" separator, to keep the table aligned. The table will
20363 still be marked for re-alignment if the field did fill the entire column,
20364 because, in this case the deletion might narrow the column."
20365 (interactive "p")
20366 (save-match-data
20367 (org-check-before-invisible-edit 'delete)
20368 (if (and (org-at-table-p)
20369 (not (bolp))
20370 (not (= (char-after) ?|))
20371 (eq N 1))
20372 (if (looking-at ".*?|")
20373 (let ((pos (point))
20374 (noalign (looking-at "[^|\n\r]* |"))
20375 (c org-table-may-need-update))
20376 (replace-match
20377 (concat (substring (match-string 0) 1 -1) " |") nil t)
20378 (goto-char pos)
20379 ;; noalign: if there were two spaces at the end, this field
20380 ;; does not determine the width of the column.
20381 (when noalign (setq org-table-may-need-update c)))
20382 (delete-char N))
20383 (delete-char N)
20384 (org-fix-tags-on-the-fly))))
20386 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20387 (put 'org-self-insert-command 'delete-selection
20388 (lambda ()
20389 (not (run-hook-with-args-until-success
20390 'self-insert-uses-region-functions))))
20391 (put 'orgtbl-self-insert-command 'delete-selection
20392 (lambda ()
20393 (not (run-hook-with-args-until-success
20394 'self-insert-uses-region-functions))))
20395 (put 'org-delete-char 'delete-selection 'supersede)
20396 (put 'org-delete-backward-char 'delete-selection 'supersede)
20397 (put 'org-yank 'delete-selection 'yank)
20399 ;; Make `flyspell-mode' delay after some commands
20400 (put 'org-self-insert-command 'flyspell-delayed t)
20401 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20402 (put 'org-delete-char 'flyspell-delayed t)
20403 (put 'org-delete-backward-char 'flyspell-delayed t)
20405 ;; Make pabbrev-mode expand after Org mode commands
20406 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20407 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20409 (defun org-remap (map &rest commands)
20410 "In MAP, remap the functions given in COMMANDS.
20411 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20412 (let (new old)
20413 (while commands
20414 (setq old (pop commands) new (pop commands))
20415 (org-defkey map (vector 'remap old) new))))
20417 (defun org-transpose-words ()
20418 "Transpose words for Org.
20419 This uses the `org-mode-transpose-word-syntax-table' syntax
20420 table, which interprets characters in `org-emphasis-alist' as
20421 word constituents."
20422 (interactive)
20423 (with-syntax-table org-mode-transpose-word-syntax-table
20424 (call-interactively 'transpose-words)))
20425 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20427 (when (eq org-enable-table-editor 'optimized)
20428 ;; If the user wants maximum table support, we need to hijack
20429 ;; some standard editing functions
20430 (org-remap org-mode-map
20431 'self-insert-command 'org-self-insert-command
20432 'delete-char 'org-delete-char
20433 'delete-backward-char 'org-delete-backward-char)
20434 (org-defkey org-mode-map "|" 'org-force-self-insert))
20436 (defvar org-ctrl-c-ctrl-c-hook nil
20437 "Hook for functions attaching themselves to `C-c C-c'.
20439 This can be used to add additional functionality to the C-c C-c
20440 key which executes context-dependent commands. This hook is run
20441 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20442 run after the last test.
20444 Each function will be called with no arguments. The function
20445 must check if the context is appropriate for it to act. If yes,
20446 it should do its thing and then return a non-nil value. If the
20447 context is wrong, just do nothing and return nil.")
20449 (defvar org-ctrl-c-ctrl-c-final-hook nil
20450 "Hook for functions attaching themselves to `C-c C-c'.
20452 This can be used to add additional functionality to the C-c C-c
20453 key which executes context-dependent commands. This hook is run
20454 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20455 before the first test.
20457 Each function will be called with no arguments. The function
20458 must check if the context is appropriate for it to act. If yes,
20459 it should do its thing and then return a non-nil value. If the
20460 context is wrong, just do nothing and return nil.")
20462 (defvar org-tab-first-hook nil
20463 "Hook for functions to attach themselves to TAB.
20464 See `org-ctrl-c-ctrl-c-hook' for more information.
20465 This hook runs as the first action when TAB is pressed, even before
20466 `org-cycle' messes around with the `outline-regexp' to cater for
20467 inline tasks and plain list item folding.
20468 If any function in this hook returns t, any other actions that
20469 would have been caused by TAB (such as table field motion or visibility
20470 cycling) will not occur.")
20472 (defvar org-tab-after-check-for-table-hook nil
20473 "Hook for functions to attach themselves to TAB.
20474 See `org-ctrl-c-ctrl-c-hook' for more information.
20475 This hook runs after it has been established that the cursor is not in a
20476 table, but before checking if the cursor is in a headline or if global cycling
20477 should be done.
20478 If any function in this hook returns t, not other actions like visibility
20479 cycling will be done.")
20481 (defvar org-tab-after-check-for-cycling-hook nil
20482 "Hook for functions to attach themselves to TAB.
20483 See `org-ctrl-c-ctrl-c-hook' for more information.
20484 This hook runs after it has been established that not table field motion and
20485 not visibility should be done because of current context. This is probably
20486 the place where a package like yasnippets can hook in.")
20488 (defvar org-tab-before-tab-emulation-hook nil
20489 "Hook for functions to attach themselves to TAB.
20490 See `org-ctrl-c-ctrl-c-hook' for more information.
20491 This hook runs after every other options for TAB have been exhausted, but
20492 before indentation and \t insertion takes place.")
20494 (defvar org-metaleft-hook nil
20495 "Hook for functions attaching themselves to `M-left'.
20496 See `org-ctrl-c-ctrl-c-hook' for more information.")
20497 (defvar org-metaright-hook nil
20498 "Hook for functions attaching themselves to `M-right'.
20499 See `org-ctrl-c-ctrl-c-hook' for more information.")
20500 (defvar org-metaup-hook nil
20501 "Hook for functions attaching themselves to `M-up'.
20502 See `org-ctrl-c-ctrl-c-hook' for more information.")
20503 (defvar org-metadown-hook nil
20504 "Hook for functions attaching themselves to `M-down'.
20505 See `org-ctrl-c-ctrl-c-hook' for more information.")
20506 (defvar org-shiftmetaleft-hook nil
20507 "Hook for functions attaching themselves to `M-S-left'.
20508 See `org-ctrl-c-ctrl-c-hook' for more information.")
20509 (defvar org-shiftmetaright-hook nil
20510 "Hook for functions attaching themselves to `M-S-right'.
20511 See `org-ctrl-c-ctrl-c-hook' for more information.")
20512 (defvar org-shiftmetaup-hook nil
20513 "Hook for functions attaching themselves to `M-S-up'.
20514 See `org-ctrl-c-ctrl-c-hook' for more information.")
20515 (defvar org-shiftmetadown-hook nil
20516 "Hook for functions attaching themselves to `M-S-down'.
20517 See `org-ctrl-c-ctrl-c-hook' for more information.")
20518 (defvar org-metareturn-hook nil
20519 "Hook for functions attaching themselves to `M-RET'.
20520 See `org-ctrl-c-ctrl-c-hook' for more information.")
20521 (defvar org-shiftup-hook nil
20522 "Hook for functions attaching themselves to `S-up'.
20523 See `org-ctrl-c-ctrl-c-hook' for more information.")
20524 (defvar org-shiftup-final-hook nil
20525 "Hook for functions attaching themselves to `S-up'.
20526 This one runs after all other options except shift-select have been excluded.
20527 See `org-ctrl-c-ctrl-c-hook' for more information.")
20528 (defvar org-shiftdown-hook nil
20529 "Hook for functions attaching themselves to `S-down'.
20530 See `org-ctrl-c-ctrl-c-hook' for more information.")
20531 (defvar org-shiftdown-final-hook nil
20532 "Hook for functions attaching themselves to `S-down'.
20533 This one runs after all other options except shift-select have been excluded.
20534 See `org-ctrl-c-ctrl-c-hook' for more information.")
20535 (defvar org-shiftleft-hook nil
20536 "Hook for functions attaching themselves to `S-left'.
20537 See `org-ctrl-c-ctrl-c-hook' for more information.")
20538 (defvar org-shiftleft-final-hook nil
20539 "Hook for functions attaching themselves to `S-left'.
20540 This one runs after all other options except shift-select have been excluded.
20541 See `org-ctrl-c-ctrl-c-hook' for more information.")
20542 (defvar org-shiftright-hook nil
20543 "Hook for functions attaching themselves to `S-right'.
20544 See `org-ctrl-c-ctrl-c-hook' for more information.")
20545 (defvar org-shiftright-final-hook nil
20546 "Hook for functions attaching themselves to `S-right'.
20547 This one runs after all other options except shift-select have been excluded.
20548 See `org-ctrl-c-ctrl-c-hook' for more information.")
20550 (defun org-modifier-cursor-error ()
20551 "Throw an error, a modified cursor command was applied in wrong context."
20552 (user-error "This command is active in special context like tables, headlines or items"))
20554 (defun org-shiftselect-error ()
20555 "Throw an error because Shift-Cursor command was applied in wrong context."
20556 (if (and (boundp 'shift-select-mode) shift-select-mode)
20557 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20558 (user-error "This command works only in special context like headlines or timestamps")))
20560 (defun org-call-for-shift-select (cmd)
20561 (let ((this-command-keys-shift-translated t))
20562 (call-interactively cmd)))
20564 (defun org-shifttab (&optional arg)
20565 "Global visibility cycling or move to previous table field.
20566 Call `org-table-previous-field' within a table.
20567 When ARG is nil, cycle globally through visibility states.
20568 When ARG is a numeric prefix, show contents of this level."
20569 (interactive "P")
20570 (cond
20571 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20572 ((integerp arg)
20573 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20574 (message "Content view to level: %d" arg)
20575 (org-content (prefix-numeric-value arg2))
20576 (org-cycle-show-empty-lines t)
20577 (setq org-cycle-global-status 'overview)))
20578 (t (call-interactively 'org-global-cycle))))
20580 (defun org-shiftmetaleft ()
20581 "Promote subtree or delete table column.
20582 Calls `org-promote-subtree', `org-outdent-item-tree', or
20583 `org-table-delete-column', depending on context. See the
20584 individual commands for more information."
20585 (interactive)
20586 (cond
20587 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20588 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20589 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20590 ((if (not (org-region-active-p)) (org-at-item-p)
20591 (save-excursion (goto-char (region-beginning))
20592 (org-at-item-p)))
20593 (call-interactively 'org-outdent-item-tree))
20594 (t (org-modifier-cursor-error))))
20596 (defun org-shiftmetaright ()
20597 "Demote subtree or insert table column.
20598 Calls `org-demote-subtree', `org-indent-item-tree', or
20599 `org-table-insert-column', depending on context. See the
20600 individual commands for more information."
20601 (interactive)
20602 (cond
20603 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20604 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20605 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20606 ((if (not (org-region-active-p)) (org-at-item-p)
20607 (save-excursion (goto-char (region-beginning))
20608 (org-at-item-p)))
20609 (call-interactively 'org-indent-item-tree))
20610 (t (org-modifier-cursor-error))))
20612 (defun org-shiftmetaup (&optional _arg)
20613 "Drag the line at point up.
20614 In a table, kill the current row.
20615 On a clock timestamp, update the value of the timestamp like `S-<up>'
20616 but also adjust the previous clocked item in the clock history.
20617 Everywhere else, drag the line at point up."
20618 (interactive "P")
20619 (cond
20620 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20621 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20622 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20623 (call-interactively 'org-timestamp-up)))
20624 (t (call-interactively 'org-drag-line-backward))))
20626 (defun org-shiftmetadown (&optional _arg)
20627 "Drag the line at point down.
20628 In a table, insert an empty row at the current line.
20629 On a clock timestamp, update the value of the timestamp like `S-<down>'
20630 but also adjust the previous clocked item in the clock history.
20631 Everywhere else, drag the line at point down."
20632 (interactive "P")
20633 (cond
20634 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20635 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20636 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20637 (call-interactively 'org-timestamp-down)))
20638 (t (call-interactively 'org-drag-line-forward))))
20640 (defsubst org-hidden-tree-error ()
20641 (user-error
20642 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20644 (defun org-metaleft (&optional _arg)
20645 "Promote heading, list item at point or move table column left.
20647 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20648 depending on context. With no specific context, calls the Emacs
20649 default `backward-word'. See the individual commands for more
20650 information.
20652 This function runs the hook `org-metaleft-hook' as a first step,
20653 and returns at first non-nil value."
20654 (interactive "P")
20655 (cond
20656 ((run-hook-with-args-until-success 'org-metaleft-hook))
20657 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20658 ((org-with-limited-levels
20659 (or (org-at-heading-p)
20660 (and (org-region-active-p)
20661 (save-excursion
20662 (goto-char (region-beginning))
20663 (org-at-heading-p)))))
20664 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20665 (call-interactively 'org-do-promote))
20666 ;; At an inline task.
20667 ((org-at-heading-p)
20668 (call-interactively 'org-inlinetask-promote))
20669 ((or (org-at-item-p)
20670 (and (org-region-active-p)
20671 (save-excursion
20672 (goto-char (region-beginning))
20673 (org-at-item-p))))
20674 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20675 (call-interactively 'org-outdent-item))
20676 (t (call-interactively 'backward-word))))
20678 (defun org-metaright (&optional _arg)
20679 "Demote heading, list item at point or move table column right.
20681 In front of a drawer or a block keyword, indent it correctly.
20683 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20684 `org-indent-drawer' or `org-indent-block' depending on context.
20685 With no specific context, calls the Emacs default `forward-word'.
20686 See the individual commands for more information.
20688 This function runs the hook `org-metaright-hook' as a first step,
20689 and returns at first non-nil value."
20690 (interactive "P")
20691 (cond
20692 ((run-hook-with-args-until-success 'org-metaright-hook))
20693 ((org-at-table-p) (call-interactively 'org-table-move-column))
20694 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20695 ((org-at-block-p) (call-interactively 'org-indent-block))
20696 ((org-with-limited-levels
20697 (or (org-at-heading-p)
20698 (and (org-region-active-p)
20699 (save-excursion
20700 (goto-char (region-beginning))
20701 (org-at-heading-p)))))
20702 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20703 (call-interactively 'org-do-demote))
20704 ;; At an inline task.
20705 ((org-at-heading-p)
20706 (call-interactively 'org-inlinetask-demote))
20707 ((or (org-at-item-p)
20708 (and (org-region-active-p)
20709 (save-excursion
20710 (goto-char (region-beginning))
20711 (org-at-item-p))))
20712 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20713 (call-interactively 'org-indent-item))
20714 (t (call-interactively 'forward-word))))
20716 (defun org-check-for-hidden (what)
20717 "Check if there are hidden headlines/items in the current visual line.
20718 WHAT can be either `headlines' or `items'. If the current line is
20719 an outline or item heading and it has a folded subtree below it,
20720 this function returns t, nil otherwise."
20721 (let ((re (cond
20722 ((eq what 'headlines) org-outline-regexp-bol)
20723 ((eq what 'items) (org-item-beginning-re))
20724 (t (error "This should not happen"))))
20725 beg end)
20726 (save-excursion
20727 (catch 'exit
20728 (unless (org-region-active-p)
20729 (setq beg (point-at-bol))
20730 (beginning-of-line 2)
20731 (while (and (not (eobp)) ;; this is like `next-line'
20732 (get-char-property (1- (point)) 'invisible))
20733 (beginning-of-line 2))
20734 (setq end (point))
20735 (goto-char beg)
20736 (goto-char (point-at-eol))
20737 (setq end (max end (point)))
20738 (while (re-search-forward re end t)
20739 (when (get-char-property (match-beginning 0) 'invisible)
20740 (throw 'exit t))))
20741 nil))))
20743 (defun org-metaup (&optional _arg)
20744 "Move subtree up or move table row up.
20745 Calls `org-move-subtree-up' or `org-table-move-row' or
20746 `org-move-item-up', depending on context. See the individual commands
20747 for more information."
20748 (interactive "P")
20749 (cond
20750 ((run-hook-with-args-until-success 'org-metaup-hook))
20751 ((org-region-active-p)
20752 (let* ((a (min (region-beginning) (region-end)))
20753 (b (1- (max (region-beginning) (region-end))))
20754 (c (save-excursion (goto-char a)
20755 (move-beginning-of-line 0)))
20756 (d (save-excursion (goto-char a)
20757 (move-end-of-line 0) (point))))
20758 (transpose-regions a b c d)
20759 (goto-char c)))
20760 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20761 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20762 ((org-at-item-p) (call-interactively 'org-move-item-up))
20763 (t (org-drag-element-backward))))
20765 (defun org-metadown (&optional _arg)
20766 "Move subtree down or move table row down.
20767 Calls `org-move-subtree-down' or `org-table-move-row' or
20768 `org-move-item-down', depending on context. See the individual
20769 commands for more information."
20770 (interactive "P")
20771 (cond
20772 ((run-hook-with-args-until-success 'org-metadown-hook))
20773 ((org-region-active-p)
20774 (let* ((a (min (region-beginning) (region-end)))
20775 (b (max (region-beginning) (region-end)))
20776 (c (save-excursion (goto-char b)
20777 (move-beginning-of-line 1)))
20778 (d (save-excursion (goto-char b)
20779 (move-end-of-line 1) (1+ (point)))))
20780 (transpose-regions a b c d)
20781 (goto-char d)))
20782 ((org-at-table-p) (call-interactively 'org-table-move-row))
20783 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20784 ((org-at-item-p) (call-interactively 'org-move-item-down))
20785 (t (org-drag-element-forward))))
20787 (defun org-shiftup (&optional arg)
20788 "Increase item in timestamp or increase priority of current headline.
20789 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20790 depending on context. See the individual commands for more information."
20791 (interactive "P")
20792 (cond
20793 ((run-hook-with-args-until-success 'org-shiftup-hook))
20794 ((and org-support-shift-select (org-region-active-p))
20795 (org-call-for-shift-select 'previous-line))
20796 ((org-at-timestamp-p t)
20797 (call-interactively (if org-edit-timestamp-down-means-later
20798 'org-timestamp-down 'org-timestamp-up)))
20799 ((and (not (eq org-support-shift-select 'always))
20800 org-enable-priority-commands
20801 (org-at-heading-p))
20802 (call-interactively 'org-priority-up))
20803 ((and (not org-support-shift-select) (org-at-item-p))
20804 (call-interactively 'org-previous-item))
20805 ((org-clocktable-try-shift 'up arg))
20806 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20807 (org-support-shift-select
20808 (org-call-for-shift-select 'previous-line))
20809 (t (org-shiftselect-error))))
20811 (defun org-shiftdown (&optional arg)
20812 "Decrease item in timestamp or decrease priority of current headline.
20813 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20814 depending on context. See the individual commands for more information."
20815 (interactive "P")
20816 (cond
20817 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20818 ((and org-support-shift-select (org-region-active-p))
20819 (org-call-for-shift-select 'next-line))
20820 ((org-at-timestamp-p t)
20821 (call-interactively (if org-edit-timestamp-down-means-later
20822 'org-timestamp-up 'org-timestamp-down)))
20823 ((and (not (eq org-support-shift-select 'always))
20824 org-enable-priority-commands
20825 (org-at-heading-p))
20826 (call-interactively 'org-priority-down))
20827 ((and (not org-support-shift-select) (org-at-item-p))
20828 (call-interactively 'org-next-item))
20829 ((org-clocktable-try-shift 'down arg))
20830 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20831 (org-support-shift-select
20832 (org-call-for-shift-select 'next-line))
20833 (t (org-shiftselect-error))))
20835 (defun org-shiftright (&optional arg)
20836 "Cycle the thing at point or in the current line, depending on context.
20837 Depending on context, this does one of the following:
20839 - switch a timestamp at point one day into the future
20840 - on a headline, switch to the next TODO keyword.
20841 - on an item, switch entire list to the next bullet type
20842 - on a property line, switch to the next allowed value
20843 - on a clocktable definition line, move time block into the future"
20844 (interactive "P")
20845 (cond
20846 ((run-hook-with-args-until-success 'org-shiftright-hook))
20847 ((and org-support-shift-select (org-region-active-p))
20848 (org-call-for-shift-select 'forward-char))
20849 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20850 ((and (not (eq org-support-shift-select 'always))
20851 (org-at-heading-p))
20852 (let ((org-inhibit-logging
20853 (not org-treat-S-cursor-todo-selection-as-state-change))
20854 (org-inhibit-blocking
20855 (not org-treat-S-cursor-todo-selection-as-state-change)))
20856 (org-call-with-arg 'org-todo 'right)))
20857 ((or (and org-support-shift-select
20858 (not (eq org-support-shift-select 'always))
20859 (org-at-item-bullet-p))
20860 (and (not org-support-shift-select) (org-at-item-p)))
20861 (org-call-with-arg 'org-cycle-list-bullet nil))
20862 ((and (not (eq org-support-shift-select 'always))
20863 (org-at-property-p))
20864 (call-interactively 'org-property-next-allowed-value))
20865 ((org-clocktable-try-shift 'right arg))
20866 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20867 (org-support-shift-select
20868 (org-call-for-shift-select 'forward-char))
20869 (t (org-shiftselect-error))))
20871 (defun org-shiftleft (&optional arg)
20872 "Cycle the thing at point or in the current line, depending on context.
20873 Depending on context, this does one of the following:
20875 - switch a timestamp at point one day into the past
20876 - on a headline, switch to the previous TODO keyword.
20877 - on an item, switch entire list to the previous bullet type
20878 - on a property line, switch to the previous allowed value
20879 - on a clocktable definition line, move time block into the past"
20880 (interactive "P")
20881 (cond
20882 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20883 ((and org-support-shift-select (org-region-active-p))
20884 (org-call-for-shift-select 'backward-char))
20885 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20886 ((and (not (eq org-support-shift-select 'always))
20887 (org-at-heading-p))
20888 (let ((org-inhibit-logging
20889 (not org-treat-S-cursor-todo-selection-as-state-change))
20890 (org-inhibit-blocking
20891 (not org-treat-S-cursor-todo-selection-as-state-change)))
20892 (org-call-with-arg 'org-todo 'left)))
20893 ((or (and org-support-shift-select
20894 (not (eq org-support-shift-select 'always))
20895 (org-at-item-bullet-p))
20896 (and (not org-support-shift-select) (org-at-item-p)))
20897 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20898 ((and (not (eq org-support-shift-select 'always))
20899 (org-at-property-p))
20900 (call-interactively 'org-property-previous-allowed-value))
20901 ((org-clocktable-try-shift 'left arg))
20902 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20903 (org-support-shift-select
20904 (org-call-for-shift-select 'backward-char))
20905 (t (org-shiftselect-error))))
20907 (defun org-shiftcontrolright ()
20908 "Switch to next TODO set."
20909 (interactive)
20910 (cond
20911 ((and org-support-shift-select (org-region-active-p))
20912 (org-call-for-shift-select 'forward-word))
20913 ((and (not (eq org-support-shift-select 'always))
20914 (org-at-heading-p))
20915 (org-call-with-arg 'org-todo 'nextset))
20916 (org-support-shift-select
20917 (org-call-for-shift-select 'forward-word))
20918 (t (org-shiftselect-error))))
20920 (defun org-shiftcontrolleft ()
20921 "Switch to previous TODO set."
20922 (interactive)
20923 (cond
20924 ((and org-support-shift-select (org-region-active-p))
20925 (org-call-for-shift-select 'backward-word))
20926 ((and (not (eq org-support-shift-select 'always))
20927 (org-at-heading-p))
20928 (org-call-with-arg 'org-todo 'previousset))
20929 (org-support-shift-select
20930 (org-call-for-shift-select 'backward-word))
20931 (t (org-shiftselect-error))))
20933 (defun org-shiftcontrolup (&optional n)
20934 "Change timestamps synchronously up in CLOCK log lines.
20935 Optional argument N tells to change by that many units."
20936 (interactive "P")
20937 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20938 (let (org-support-shift-select)
20939 (org-clock-timestamps-up n))
20940 (user-error "Not at a clock log")))
20942 (defun org-shiftcontroldown (&optional n)
20943 "Change timestamps synchronously down in CLOCK log lines.
20944 Optional argument N tells to change by that many units."
20945 (interactive "P")
20946 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20947 (let (org-support-shift-select)
20948 (org-clock-timestamps-down n))
20949 (user-error "Not at a clock log")))
20951 (defun org-increase-number-at-point (&optional inc)
20952 "Increment the number at point.
20953 With an optional prefix numeric argument INC, increment using
20954 this numeric value."
20955 (interactive "p")
20956 (if (not (number-at-point))
20957 (user-error "Not on a number")
20958 (unless inc (setq inc 1))
20959 (let ((pos (point))
20960 (beg (skip-chars-backward "-+^/*0-9eE."))
20961 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20962 (setq nap (buffer-substring-no-properties
20963 (+ pos beg) (+ pos beg end)))
20964 (delete-region (+ pos beg) (+ pos beg end))
20965 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20966 (when (org-at-table-p)
20967 (org-table-align)
20968 (org-table-end-of-field 1))))
20970 (defun org-decrease-number-at-point (&optional inc)
20971 "Decrement the number at point.
20972 With an optional prefix numeric argument INC, decrement using
20973 this numeric value."
20974 (interactive "p")
20975 (org-increase-number-at-point (- (or inc 1))))
20977 (defun org-ctrl-c-ret ()
20978 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20979 (interactive)
20980 (cond
20981 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20982 (t (call-interactively 'org-insert-heading))))
20984 (defun org-find-visible ()
20985 (let ((s (point)))
20986 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20987 (get-char-property s 'invisible)))
20989 (defun org-find-invisible ()
20990 (let ((s (point)))
20991 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20992 (not (get-char-property s 'invisible))))
20995 (defun org-copy-visible (beg end)
20996 "Copy the visible parts of the region."
20997 (interactive "r")
20998 (let (snippets s)
20999 (save-excursion
21000 (save-restriction
21001 (narrow-to-region beg end)
21002 (setq s (goto-char (point-min)))
21003 (while (not (= (point) (point-max)))
21004 (goto-char (org-find-invisible))
21005 (push (buffer-substring s (point)) snippets)
21006 (setq s (goto-char (org-find-visible))))))
21007 (kill-new (apply 'concat (nreverse snippets)))))
21009 (defun org-copy-special ()
21010 "Copy region in table or copy current subtree.
21011 Calls `org-table-copy-region' or `org-copy-subtree', depending on
21012 context. See the individual commands for more information."
21013 (interactive)
21014 (call-interactively
21015 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
21017 (defun org-cut-special ()
21018 "Cut region in table or cut current subtree.
21019 Calls `org-table-cut-region' or `org-cut-subtree', depending on
21020 context. See the individual commands for more information."
21021 (interactive)
21022 (call-interactively
21023 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
21025 (defun org-paste-special (arg)
21026 "Paste rectangular region into table, or past subtree relative to level.
21027 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
21028 See the individual commands for more information."
21029 (interactive "P")
21030 (if (org-at-table-p)
21031 (org-table-paste-rectangle)
21032 (org-paste-subtree arg)))
21034 (defun org-edit-special (&optional arg)
21035 "Call a special editor for the element at point.
21036 When at a table, call the formula editor with `org-table-edit-formulas'.
21037 When in a source code block, call `org-edit-src-code'.
21038 When in a fixed-width region, call `org-edit-fixed-width-region'.
21039 When in an export block, call `org-edit-export-block'.
21040 When at an #+INCLUDE keyword, visit the included file.
21041 When at a footnote reference, call `org-edit-footnote-reference'
21042 On a link, call `ffap' to visit the link at point.
21043 Otherwise, return a user error."
21044 (interactive "P")
21045 (let ((element (org-element-at-point)))
21046 (barf-if-buffer-read-only)
21047 (pcase (org-element-type element)
21048 (`src-block
21049 (if (not arg) (org-edit-src-code)
21050 (let* ((info (org-babel-get-src-block-info))
21051 (lang (nth 0 info))
21052 (params (nth 2 info))
21053 (session (cdr (assq :session params))))
21054 (if (not session) (org-edit-src-code)
21055 ;; At a src-block with a session and function called with
21056 ;; an ARG: switch to the buffer related to the inferior
21057 ;; process.
21058 (switch-to-buffer
21059 (funcall (intern (concat "org-babel-prep-session:" lang))
21060 session params))))))
21061 (`keyword
21062 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
21063 (org-open-link-from-string
21064 (format "[[%s]]"
21065 (expand-file-name
21066 (let ((value (org-element-property :value element)))
21067 (cond ((not (org-string-nw-p value))
21068 (user-error "No file to edit"))
21069 ((string-match "\\`\"\\(.*?\\)\"" value)
21070 (match-string 1 value))
21071 ((string-match "\\`[^ \t\"]\\S-*" value)
21072 (match-string 0 value))
21073 (t (user-error "No valid file specified")))))))
21074 (user-error "No special environment to edit here")))
21075 (`table
21076 (if (eq (org-element-property :type element) 'table.el)
21077 (org-edit-table.el)
21078 (call-interactively 'org-table-edit-formulas)))
21079 ;; Only Org tables contain `table-row' type elements.
21080 (`table-row (call-interactively 'org-table-edit-formulas))
21081 (`example-block (org-edit-src-code))
21082 (`export-block (org-edit-export-block))
21083 (`fixed-width (org-edit-fixed-width-region))
21085 ;; No notable element at point. Though, we may be at a link or
21086 ;; a footnote reference, which are objects. Thus, scan deeper.
21087 (let ((context (org-element-context element)))
21088 (pcase (org-element-type context)
21089 (`footnote-reference (org-edit-footnote-reference))
21090 (`inline-src-block (org-edit-inline-src-code))
21091 (`link (call-interactively #'ffap))
21092 (_ (user-error "No special environment to edit here"))))))))
21094 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21095 (defun org-ctrl-c-ctrl-c (&optional arg)
21096 "Set tags in headline, or update according to changed information at point.
21098 This command does many different things, depending on context:
21100 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21101 this is what we do.
21103 - If the cursor is on a statistics cookie, update it.
21105 - If the cursor is in a headline, prompt for tags and insert them
21106 into the current line, aligned to `org-tags-column'. When called
21107 with prefix arg, realign all tags in the current buffer.
21109 - If the cursor is in one of the special #+KEYWORD lines, this
21110 triggers scanning the buffer for these lines and updating the
21111 information.
21113 - If the cursor is inside a table, realign the table. This command
21114 works even if the automatic table editor has been turned off.
21116 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21117 the entire table.
21119 - If the cursor is at a footnote reference or definition, jump to
21120 the corresponding definition or references, respectively.
21122 - If the cursor is a the beginning of a dynamic block, update it.
21124 - If the current buffer is a capture buffer, close note and file it.
21126 - If the cursor is on a <<<target>>>, update radio targets and
21127 corresponding links in this buffer.
21129 - If the cursor is on a numbered item in a plain list, renumber the
21130 ordered list.
21132 - If the cursor is on a checkbox, toggle it.
21134 - If the cursor is on a code block, evaluate it. The variable
21135 `org-confirm-babel-evaluate' can be used to control prompting
21136 before code block evaluation, by default every code block
21137 evaluation requires confirmation. Code block evaluation can be
21138 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21139 (interactive "P")
21140 (cond
21141 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
21142 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21143 (org-remove-occur-highlights)
21144 (message "Temporary highlights/overlays removed from current buffer"))
21145 ((and (local-variable-p 'org-finish-function)
21146 (fboundp org-finish-function))
21147 (funcall org-finish-function))
21148 ((org-babel-hash-at-point))
21149 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21150 ((save-excursion (beginning-of-line) (looking-at-p "[ \t]*$"))
21151 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21152 (user-error
21153 (substitute-command-keys
21154 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
21156 (let* ((context
21157 (org-element-lineage
21158 (org-element-context)
21159 ;; Limit to supported contexts.
21160 '(babel-call clock dynamic-block footnote-definition
21161 footnote-reference inline-babel-call inline-src-block
21162 item keyword node-property paragraph plain-list
21163 property-drawer radio-target src-block
21164 statistics-cookie table table-cell table-row
21165 timestamp)
21167 (type (org-element-type context)))
21168 ;; For convenience: at the first line of a paragraph on the same
21169 ;; line as an item, apply function on that item instead.
21170 (when (eq type 'paragraph)
21171 (let ((parent (org-element-property :parent context)))
21172 (when (and (eq (org-element-type parent) 'item)
21173 (= (line-beginning-position)
21174 (org-element-property :begin parent)))
21175 (setq context parent)
21176 (setq type 'item))))
21177 ;; Act according to type of element or object at point.
21178 (pcase type
21179 ((or `babel-call `inline-babel-call)
21180 (let ((info (org-babel-lob-get-info context)))
21181 (when info (org-babel-execute-src-block nil info))))
21182 (`clock (org-clock-update-time-maybe))
21183 (`dynamic-block
21184 (save-excursion
21185 (goto-char (org-element-property :post-affiliated context))
21186 (org-update-dblock)))
21187 (`footnote-definition
21188 (goto-char (org-element-property :post-affiliated context))
21189 (call-interactively 'org-footnote-action))
21190 (`footnote-reference (call-interactively #'org-footnote-action))
21191 ((or `headline `inlinetask)
21192 (save-excursion (goto-char (org-element-property :begin context))
21193 (call-interactively #'org-set-tags)))
21194 ((or `inline-src-block `src-block)
21195 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
21196 (org-babel-eval-wipe-error-buffer)
21197 (org-babel-execute-src-block
21198 current-prefix-arg (org-babel-get-src-block-info nil context))))
21199 (`item
21200 ;; At an item: `C-u C-u' sets checkbox to "[-]"
21201 ;; unconditionally, whereas `C-u' will toggle its presence.
21202 ;; Without a universal argument, if the item has a checkbox,
21203 ;; toggle it. Otherwise repair the list.
21204 (let* ((box (org-element-property :checkbox context))
21205 (struct (org-element-property :structure context))
21206 (old-struct (copy-tree struct))
21207 (parents (org-list-parents-alist struct))
21208 (prevs (org-list-prevs-alist struct))
21209 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21210 (org-list-set-checkbox
21211 (org-element-property :begin context) struct
21212 (cond ((equal arg '(16)) "[-]")
21213 ((and (not box) (equal arg '(4))) "[ ]")
21214 ((or (not box) (equal arg '(4))) nil)
21215 ((eq box 'on) "[ ]")
21216 (t "[X]")))
21217 ;; Mimic `org-list-write-struct' but with grabbing a return
21218 ;; value from `org-list-struct-fix-box'.
21219 (org-list-struct-fix-ind struct parents 2)
21220 (org-list-struct-fix-item-end struct)
21221 (org-list-struct-fix-bul struct prevs)
21222 (org-list-struct-fix-ind struct parents)
21223 (let ((block-item
21224 (org-list-struct-fix-box struct parents prevs orderedp)))
21225 (if (and box (equal struct old-struct))
21226 (if (equal arg '(16))
21227 (message "Checkboxes already reset")
21228 (user-error "Cannot toggle this checkbox: %s"
21229 (if (eq box 'on)
21230 "all subitems checked"
21231 "unchecked subitems")))
21232 (org-list-struct-apply-struct struct old-struct)
21233 (org-update-checkbox-count-maybe))
21234 (when block-item
21235 (message "Checkboxes were removed due to empty box at line %d"
21236 (org-current-line block-item))))))
21237 (`keyword
21238 (let ((org-inhibit-startup-visibility-stuff t)
21239 (org-startup-align-all-tables nil))
21240 (when (boundp 'org-table-coordinate-overlays)
21241 (mapc #'delete-overlay org-table-coordinate-overlays)
21242 (setq org-table-coordinate-overlays nil))
21243 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21244 (message "Local setup has been refreshed"))
21245 (`plain-list
21246 ;; At a plain list, with a double C-u argument, set
21247 ;; checkboxes of each item to "[-]", whereas a single one
21248 ;; will toggle their presence according to the state of the
21249 ;; first item in the list. Without an argument, repair the
21250 ;; list.
21251 (let* ((begin (org-element-property :contents-begin context))
21252 (beginm (move-marker (make-marker) begin))
21253 (struct (org-element-property :structure context))
21254 (old-struct (copy-tree struct))
21255 (first-box (save-excursion
21256 (goto-char begin)
21257 (looking-at org-list-full-item-re)
21258 (match-string-no-properties 3)))
21259 (new-box (cond ((equal arg '(16)) "[-]")
21260 ((equal arg '(4)) (unless first-box "[ ]"))
21261 ((equal first-box "[X]") "[ ]")
21262 (t "[X]"))))
21263 (cond
21264 (arg
21265 (dolist (pos
21266 (org-list-get-all-items
21267 begin struct (org-list-prevs-alist struct)))
21268 (org-list-set-checkbox pos struct new-box)))
21269 ((and first-box (eq (point) begin))
21270 ;; For convenience, when point is at bol on the first
21271 ;; item of the list and no argument is provided, simply
21272 ;; toggle checkbox of that item, if any.
21273 (org-list-set-checkbox begin struct new-box)))
21274 (org-list-write-struct
21275 struct (org-list-parents-alist struct) old-struct)
21276 (org-update-checkbox-count-maybe)
21277 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21278 ((or `property-drawer `node-property)
21279 (call-interactively #'org-property-action))
21280 (`radio-target
21281 (call-interactively #'org-update-radio-target-regexp))
21282 (`statistics-cookie
21283 (call-interactively #'org-update-statistics-cookies))
21284 ((or `table `table-cell `table-row)
21285 ;; At a table, recalculate every field and align it. Also
21286 ;; send the table if necessary. If the table has
21287 ;; a `table.el' type, just give up. At a table row or cell,
21288 ;; maybe recalculate line but always align table.
21289 (if (eq (org-element-property :type context) 'table.el)
21290 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21291 Use `\\[org-edit-special]' to edit table.el tables"))
21292 (let ((org-enable-table-editor t))
21293 (if (or (eq type 'table)
21294 ;; Check if point is at a TBLFM line.
21295 (and (eq type 'table-row)
21296 (= (point) (org-element-property :end context))))
21297 (save-excursion
21298 (if (org-at-TBLFM-p)
21299 (progn (require 'org-table)
21300 (org-table-calc-current-TBLFM))
21301 (goto-char (org-element-property :contents-begin context))
21302 (org-call-with-arg 'org-table-recalculate (or arg t))
21303 (orgtbl-send-table 'maybe)))
21304 (org-table-maybe-eval-formula)
21305 (cond (arg (call-interactively #'org-table-recalculate))
21306 ((org-table-maybe-recalculate-line))
21307 (t (org-table-align)))))))
21308 (`timestamp (org-timestamp-change 0 'day))
21309 ((and `nil (guard (org-at-heading-p)))
21310 ;; When point is on an unsupported object type, we can miss
21311 ;; the fact that it also is at a heading. Handle it here.
21312 (call-interactively #'org-set-tags))
21313 ((guard
21314 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
21316 (user-error
21317 (substitute-command-keys
21318 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
21320 (defun org-mode-restart ()
21321 (interactive)
21322 (let ((indent-status (bound-and-true-p org-indent-mode)))
21323 (funcall major-mode)
21324 (hack-local-variables)
21325 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21326 (org-indent-mode -1)))
21327 (message "%s restarted" major-mode))
21329 (defun org-kill-note-or-show-branches ()
21330 "Abort storing current note, or call `outline-show-branches'."
21331 (interactive)
21332 (if (not org-finish-function)
21333 (progn
21334 (outline-hide-subtree)
21335 (call-interactively 'outline-show-branches))
21336 (let ((org-note-abort t))
21337 (funcall org-finish-function))))
21339 (defun org-delete-indentation (&optional arg)
21340 "Join current line to previous and fix whitespace at join.
21342 If previous line is a headline add to headline title. Otherwise
21343 the function calls `delete-indentation'.
21345 With a non-nil optional argument, join it to the following one."
21346 (interactive "*P")
21347 (if (save-excursion
21348 (beginning-of-line (if arg 1 0))
21349 (let ((case-fold-search nil))
21350 (looking-at org-complex-heading-regexp)))
21351 ;; At headline.
21352 (let ((tags-column (when (match-beginning 5)
21353 (save-excursion (goto-char (match-beginning 5))
21354 (current-column))))
21355 (string (concat " " (progn (when arg (forward-line 1))
21356 (org-trim (delete-and-extract-region
21357 (line-beginning-position)
21358 (line-end-position)))))))
21359 (unless (bobp) (delete-region (point) (1- (point))))
21360 (goto-char (or (match-end 4)
21361 (match-beginning 5)
21362 (match-end 0)))
21363 (skip-chars-backward " \t")
21364 (save-excursion (insert string))
21365 ;; Adjust alignment of tags.
21366 (cond
21367 ((not tags-column)) ;no tags
21368 (org-auto-align-tags (org-set-tags nil t))
21369 (t (org--align-tags-here tags-column)))) ;preserve tags column
21370 (delete-indentation arg)))
21372 (defun org-open-line (n)
21373 "Insert a new row in tables, call `open-line' elsewhere.
21374 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21375 As a special case, when a document starts with a table, allow to
21376 call `open-line' on the very first character."
21377 (interactive "*p")
21378 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21379 (org-table-insert-row)
21380 (open-line n)))
21382 (defun org-return (&optional indent)
21383 "Goto next table row or insert a newline.
21385 Calls `org-table-next-row' or `newline', depending on context.
21387 When optional INDENT argument is non-nil, call
21388 `newline-and-indent' instead of `newline'.
21390 When `org-return-follows-link' is non-nil and point is on
21391 a timestamp or a link, call `org-open-at-point'. However, it
21392 will not happen if point is in a table or on a \"dead\"
21393 object (e.g., within a comment). In these case, you need to use
21394 `org-open-at-point' directly."
21395 (interactive)
21396 (let ((context (if org-return-follows-link (org-element-context)
21397 (org-element-at-point))))
21398 (cond
21399 ;; In a table, call `org-table-next-row'.
21400 ((or (and (eq (org-element-type context) 'table)
21401 (>= (point) (org-element-property :contents-begin context))
21402 (< (point) (org-element-property :contents-end context)))
21403 (org-element-lineage context '(table-row table-cell) t))
21404 (org-table-justify-field-maybe)
21405 (call-interactively #'org-table-next-row))
21406 ;; On a link or a timestamp, call `org-open-at-point' if
21407 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21408 ;; locations, e.g., in a comment, as `org-open-at-point'.
21409 ((and org-return-follows-link
21410 (or (org-in-regexp org-ts-regexp-both nil t)
21411 (org-in-regexp org-tsr-regexp-both nil t)
21412 (org-in-regexp org-any-link-re nil t)))
21413 (call-interactively #'org-open-at-point))
21414 ;; Insert newline in heading, but preserve tags.
21415 ((and (not (bolp))
21416 (save-excursion (beginning-of-line)
21417 (let ((case-fold-search nil))
21418 (looking-at org-complex-heading-regexp))))
21419 ;; At headline. Split line. However, if point is on keyword,
21420 ;; priority cookie or tags, do not break any of them: add
21421 ;; a newline after the headline instead.
21422 (let ((tags-column (and (match-beginning 5)
21423 (save-excursion (goto-char (match-beginning 5))
21424 (current-column))))
21425 (string
21426 (when (and (match-end 4) (org-point-in-group (point) 4))
21427 (delete-and-extract-region (point) (match-end 4)))))
21428 ;; Adjust tag alignment.
21429 (cond
21430 ((not (and tags-column string)))
21431 (org-auto-align-tags (org-set-tags nil t))
21432 (t (org--align-tags-here tags-column))) ;preserve tags column
21433 (end-of-line)
21434 (org-show-entry)
21435 (if indent (newline-and-indent) (newline))
21436 (when string (save-excursion (insert (org-trim string))))))
21437 ;; In a list, make sure indenting keeps trailing text within.
21438 ((and indent
21439 (not (eolp))
21440 (org-element-lineage context '(item)))
21441 (let ((trailing-data
21442 (delete-and-extract-region (point) (line-end-position))))
21443 (newline-and-indent)
21444 (save-excursion (insert trailing-data))))
21445 (t (if indent (newline-and-indent) (newline))))))
21447 (defun org-return-indent ()
21448 "Goto next table row or insert a newline and indent.
21449 Calls `org-table-next-row' or `newline-and-indent', depending on
21450 context. See the individual commands for more information."
21451 (interactive)
21452 (org-return t))
21454 (defun org-ctrl-c-star ()
21455 "Compute table, or change heading status of lines.
21456 Calls `org-table-recalculate' or `org-toggle-heading',
21457 depending on context."
21458 (interactive)
21459 (cond
21460 ((org-at-table-p)
21461 (call-interactively 'org-table-recalculate))
21463 ;; Convert all lines in region to list items
21464 (call-interactively 'org-toggle-heading))))
21466 (defun org-ctrl-c-minus ()
21467 "Insert separator line in table or modify bullet status of line.
21468 Also turns a plain line or a region of lines into list items.
21469 Calls `org-table-insert-hline', `org-toggle-item', or
21470 `org-cycle-list-bullet', depending on context."
21471 (interactive)
21472 (cond
21473 ((org-at-table-p)
21474 (call-interactively 'org-table-insert-hline))
21475 ((org-region-active-p)
21476 (call-interactively 'org-toggle-item))
21477 ((org-in-item-p)
21478 (call-interactively 'org-cycle-list-bullet))
21480 (call-interactively 'org-toggle-item))))
21482 (defun org-toggle-heading (&optional nstars)
21483 "Convert headings to normal text, or items or text to headings.
21484 If there is no active region, only convert the current line.
21486 With a `\\[universal-argument]' prefix, convert the whole list at
21487 point into heading.
21489 In a region:
21491 - If the first non blank line is a headline, remove the stars
21492 from all headlines in the region.
21494 - If it is a normal line, turn each and every normal line (i.e.,
21495 not an heading or an item) in the region into headings. If you
21496 want to convert only the first line of this region, use one
21497 universal prefix argument.
21499 - If it is a plain list item, turn all plain list items into headings.
21501 When converting a line into a heading, the number of stars is chosen
21502 such that the lines become children of the current entry. However,
21503 when a numeric prefix argument is given, its value determines the
21504 number of stars to add."
21505 (interactive "P")
21506 (let ((skip-blanks
21507 (function
21508 ;; Return beginning of first non-blank line, starting from
21509 ;; line at POS.
21510 (lambda (pos)
21511 (save-excursion
21512 (goto-char pos)
21513 (while (org-at-comment-p) (forward-line))
21514 (skip-chars-forward " \r\t\n")
21515 (point-at-bol)))))
21516 beg end toggled)
21517 ;; Determine boundaries of changes. If a universal prefix has
21518 ;; been given, put the list in a region. If region ends at a bol,
21519 ;; do not consider the last line to be in the region.
21521 (when (and current-prefix-arg (org-at-item-p))
21522 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21523 (org-mark-element))
21525 (if (org-region-active-p)
21526 (setq beg (funcall skip-blanks (region-beginning))
21527 end (copy-marker (save-excursion
21528 (goto-char (region-end))
21529 (if (bolp) (point) (point-at-eol)))))
21530 (setq beg (funcall skip-blanks (point-at-bol))
21531 end (copy-marker (point-at-eol))))
21532 ;; Ensure inline tasks don't count as headings.
21533 (org-with-limited-levels
21534 (save-excursion
21535 (goto-char beg)
21536 (cond
21537 ;; Case 1. Started at an heading: de-star headings.
21538 ((org-at-heading-p)
21539 (while (< (point) end)
21540 (when (org-at-heading-p t)
21541 (looking-at org-outline-regexp) (replace-match "")
21542 (setq toggled t))
21543 (forward-line)))
21544 ;; Case 2. Started at an item: change items into headlines.
21545 ;; One star will be added by `org-list-to-subtree'.
21546 ((org-at-item-p)
21547 (while (< (point) end)
21548 (when (org-at-item-p)
21549 ;; Pay attention to cases when region ends before list.
21550 (let* ((struct (org-list-struct))
21551 (list-end
21552 (min (org-list-get-bottom-point struct) (1+ end))))
21553 (save-restriction
21554 (narrow-to-region (point) list-end)
21555 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21556 (setq toggled t))
21557 (forward-line)))
21558 ;; Case 3. Started at normal text: make every line an heading,
21559 ;; skipping headlines and items.
21560 (t (let* ((stars
21561 (make-string
21562 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21563 (add-stars
21564 (cond (nstars "") ; stars from prefix only
21565 ((equal stars "") "*") ; before first heading
21566 (org-odd-levels-only "**") ; inside heading, odd
21567 (t "*"))) ; inside heading, oddeven
21568 (rpl (concat stars add-stars " "))
21569 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21570 (while (< (point) (if (equal nstars '(4)) lend end))
21571 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21572 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21573 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21574 (forward-line)))))))
21575 (unless toggled (message "Cannot toggle heading from here"))))
21577 (defun org-meta-return (&optional _arg)
21578 "Insert a new heading or wrap a region in a table.
21579 Calls `org-insert-heading' or `org-table-wrap-region', depending
21580 on context. See the individual commands for more information."
21581 (interactive)
21582 (org-check-before-invisible-edit 'insert)
21583 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21584 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21585 #'org-insert-heading))))
21587 ;;; Menu entries
21589 (defsubst org-in-subtree-not-table-p ()
21590 "Are we in a subtree and not in a table?"
21591 (and (not (org-before-first-heading-p))
21592 (not (org-at-table-p))))
21594 ;; Define the Org mode menus
21595 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21596 '("Tbl"
21597 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21598 ["Next Field" org-cycle (org-at-table-p)]
21599 ["Previous Field" org-shifttab (org-at-table-p)]
21600 ["Next Row" org-return (org-at-table-p)]
21601 "--"
21602 ["Blank Field" org-table-blank-field (org-at-table-p)]
21603 ["Edit Field" org-table-edit-field (org-at-table-p)]
21604 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21605 "--"
21606 ("Column"
21607 ["Move Column Left" org-metaleft (org-at-table-p)]
21608 ["Move Column Right" org-metaright (org-at-table-p)]
21609 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21610 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21611 ("Row"
21612 ["Move Row Up" org-metaup (org-at-table-p)]
21613 ["Move Row Down" org-metadown (org-at-table-p)]
21614 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21615 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21616 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21617 "--"
21618 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21619 ("Rectangle"
21620 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21621 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21622 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21623 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21624 "--"
21625 ("Calculate"
21626 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21627 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21628 ["Edit Formulas" org-edit-special (org-at-table-p)]
21629 "--"
21630 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21631 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21632 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21633 "--"
21634 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21635 "--"
21636 ["Sum Column/Rectangle" org-table-sum
21637 (or (org-at-table-p) (org-region-active-p))]
21638 ["Which Column?" org-table-current-column (org-at-table-p)])
21639 ["Debug Formulas"
21640 org-table-toggle-formula-debugger
21641 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21642 ["Show Col/Row Numbers"
21643 org-table-toggle-coordinate-overlays
21644 :style toggle
21645 :selected (bound-and-true-p org-table-overlay-coordinates)]
21646 "--"
21647 ["Create" org-table-create (and (not (org-at-table-p))
21648 org-enable-table-editor)]
21649 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21650 ["Import from File" org-table-import (not (org-at-table-p))]
21651 ["Export to File" org-table-export (org-at-table-p)]
21652 "--"
21653 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21654 "--"
21655 ("Plot"
21656 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21657 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21659 (easy-menu-define org-org-menu org-mode-map "Org menu"
21660 '("Org"
21661 ("Show/Hide"
21662 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21663 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21664 ["Sparse Tree..." org-sparse-tree t]
21665 ["Reveal Context" org-reveal t]
21666 ["Show All" outline-show-all t]
21667 "--"
21668 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21669 "--"
21670 ["New Heading" org-insert-heading t]
21671 ("Navigate Headings"
21672 ["Up" outline-up-heading t]
21673 ["Next" outline-next-visible-heading t]
21674 ["Previous" outline-previous-visible-heading t]
21675 ["Next Same Level" outline-forward-same-level t]
21676 ["Previous Same Level" outline-backward-same-level t]
21677 "--"
21678 ["Jump" org-goto t])
21679 ("Edit Structure"
21680 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21681 "--"
21682 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21683 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21684 "--"
21685 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21686 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21687 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21688 "--"
21689 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21690 "--"
21691 ["Copy visible text" org-copy-visible t]
21692 "--"
21693 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21694 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21695 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21696 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21697 "--"
21698 ["Sort Region/Children" org-sort t]
21699 "--"
21700 ["Convert to odd levels" org-convert-to-odd-levels t]
21701 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21702 ("Editing"
21703 ["Emphasis..." org-emphasize t]
21704 ["Edit Source Example" org-edit-special t]
21705 "--"
21706 ["Footnote new/jump" org-footnote-action t]
21707 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21708 ("Archive"
21709 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21710 "--"
21711 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21712 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21713 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21715 "--"
21716 ("Hyperlinks"
21717 ["Store Link (Global)" org-store-link t]
21718 ["Find existing link to here" org-occur-link-in-agenda-files t]
21719 ["Insert Link" org-insert-link t]
21720 ["Follow Link" org-open-at-point t]
21721 "--"
21722 ["Next link" org-next-link t]
21723 ["Previous link" org-previous-link t]
21724 "--"
21725 ["Descriptive Links"
21726 org-toggle-link-display
21727 :style radio
21728 :selected org-descriptive-links
21730 ["Literal Links"
21731 org-toggle-link-display
21732 :style radio
21733 :selected (not org-descriptive-links)])
21734 "--"
21735 ("TODO Lists"
21736 ["TODO/DONE/-" org-todo t]
21737 ("Select keyword"
21738 ["Next keyword" org-shiftright (org-at-heading-p)]
21739 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21740 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21741 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21742 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21743 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21744 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21745 "--"
21746 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21747 :selected org-enforce-todo-dependencies :style toggle :active t]
21748 "Settings for tree at point"
21749 ["Do Children sequentially" org-toggle-ordered-property :style radio
21750 :selected (org-entry-get nil "ORDERED")
21751 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21752 ["Do Children parallel" org-toggle-ordered-property :style radio
21753 :selected (not (org-entry-get nil "ORDERED"))
21754 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21755 "--"
21756 ["Set Priority" org-priority t]
21757 ["Priority Up" org-shiftup t]
21758 ["Priority Down" org-shiftdown t]
21759 "--"
21760 ["Get news from all feeds" org-feed-update-all t]
21761 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21762 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21763 ("TAGS and Properties"
21764 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21765 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21766 "--"
21767 ["Set property" org-set-property (not (org-before-first-heading-p))]
21768 ["Column view of properties" org-columns t]
21769 ["Insert Column View DBlock" org-columns-insert-dblock t])
21770 ("Dates and Scheduling"
21771 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21772 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21773 ("Change Date"
21774 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21775 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21776 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21777 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21778 ["Compute Time Range" org-evaluate-time-range t]
21779 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21780 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21781 "--"
21782 ["Custom time format" org-toggle-time-stamp-overlays
21783 :style radio :selected org-display-custom-times]
21784 "--"
21785 ["Goto Calendar" org-goto-calendar t]
21786 ["Date from Calendar" org-date-from-calendar t]
21787 "--"
21788 ["Start/Restart Timer" org-timer-start t]
21789 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21790 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21791 ["Insert Timer String" org-timer t]
21792 ["Insert Timer Item" org-timer-item t])
21793 ("Logging work"
21794 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21795 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21796 ["Clock out" org-clock-out t]
21797 ["Clock cancel" org-clock-cancel t]
21798 "--"
21799 ["Mark as default task" org-clock-mark-default-task t]
21800 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21801 ["Goto running clock" org-clock-goto t]
21802 "--"
21803 ["Display times" org-clock-display t]
21804 ["Create clock table" org-clock-report t]
21805 "--"
21806 ["Record DONE time"
21807 (progn (setq org-log-done (not org-log-done))
21808 (message "Switching to %s will %s record a timestamp"
21809 (car org-done-keywords)
21810 (if org-log-done "automatically" "not")))
21811 :style toggle :selected org-log-done])
21812 "--"
21813 ["Agenda Command..." org-agenda t]
21814 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21815 ("File List for Agenda")
21816 ("Special views current file"
21817 ["TODO Tree" org-show-todo-tree t]
21818 ["Check Deadlines" org-check-deadlines t]
21819 ["Timeline" org-timeline t]
21820 ["Tags/Property tree" org-match-sparse-tree t])
21821 "--"
21822 ["Export/Publish..." org-export-dispatch t]
21823 ("LaTeX"
21824 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21825 :selected org-cdlatex-mode]
21826 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21827 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21828 ["Modify math symbol" org-cdlatex-math-modify
21829 (org-inside-LaTeX-fragment-p)]
21830 ["Insert citation" org-reftex-citation t])
21831 "--"
21832 ("MobileOrg"
21833 ["Push Files and Views" org-mobile-push t]
21834 ["Get Captured and Flagged" org-mobile-pull t]
21835 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21836 "--"
21837 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21838 "--"
21839 ("Documentation"
21840 ["Show Version" org-version t]
21841 ["Info Documentation" org-info t])
21842 ("Customize"
21843 ["Browse Org Group" org-customize t]
21844 "--"
21845 ["Expand This Menu" org-create-customize-menu
21846 (fboundp 'customize-menu-create)])
21847 ["Send bug report" org-submit-bug-report t]
21848 "--"
21849 ("Refresh/Reload"
21850 ["Refresh setup current buffer" org-mode-restart t]
21851 ["Reload Org (after update)" org-reload t]
21852 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21855 (defun org-info (&optional node)
21856 "Read documentation for Org in the info system.
21857 With optional NODE, go directly to that node."
21858 (interactive)
21859 (info (format "(org)%s" (or node ""))))
21861 ;;;###autoload
21862 (defun org-submit-bug-report ()
21863 "Submit a bug report on Org via mail.
21865 Don't hesitate to report any problems or inaccurate documentation.
21867 If you don't have setup sending mail from (X)Emacs, please copy the
21868 output buffer into your mail program, as it gives us important
21869 information about your Org version and configuration."
21870 (interactive)
21871 (require 'reporter)
21872 (defvar reporter-prompt-for-summary-p)
21873 (org-load-modules-maybe)
21874 (org-require-autoloaded-modules)
21875 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21876 (reporter-submit-bug-report
21877 "emacs-orgmode@gnu.org"
21878 (org-version nil 'full)
21879 (let (list)
21880 (save-window-excursion
21881 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21882 (delete-other-windows)
21883 (erase-buffer)
21884 (insert "You are about to submit a bug report to the Org mailing list.
21886 We would like to add your full Org and Outline configuration to the
21887 bug report. This greatly simplifies the work of the maintainer and
21888 other experts on the mailing list.
21890 HOWEVER, some variables you have customized may contain private
21891 information. The names of customers, colleagues, or friends, might
21892 appear in the form of file names, tags, todo states, or search strings.
21893 If you answer yes to the prompt, you might want to check and remove
21894 such private information before sending the email.")
21895 (add-text-properties (point-min) (point-max) '(face org-warning))
21896 (when (yes-or-no-p "Include your Org configuration ")
21897 (mapatoms
21898 (lambda (v)
21899 (and (boundp v)
21900 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21901 (or (and (symbol-value v)
21902 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21903 (and
21904 (get v 'custom-type) (get v 'standard-value)
21905 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21906 (push v list)))))
21907 (kill-buffer (get-buffer "*Warn about privacy*"))
21908 list))
21909 nil nil
21910 "Remember to cover the basics, that is, what you expected to happen and
21911 what in fact did happen. You don't know how to make a good report? See
21913 http://orgmode.org/manual/Feedback.html#Feedback
21915 Your bug report will be posted to the Org mailing list.
21916 ------------------------------------------------------------------------")
21917 (save-excursion
21918 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21919 (replace-match "\\1Bug: \\3 [\\2]")))))
21922 (defun org-install-agenda-files-menu ()
21923 (let ((bl (buffer-list)))
21924 (save-excursion
21925 (while bl
21926 (set-buffer (pop bl))
21927 (when (derived-mode-p 'org-mode) (setq bl nil)))
21928 (when (derived-mode-p 'org-mode)
21929 (easy-menu-change
21930 '("Org") "File List for Agenda"
21931 (append
21932 (list
21933 ["Edit File List" (org-edit-agenda-file-list) t]
21934 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21935 ["Remove Current File from List" org-remove-file t]
21936 ["Cycle through agenda files" org-cycle-agenda-files t]
21937 ["Occur in all agenda files" org-occur-in-agenda-files t]
21938 "--")
21939 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21941 ;;;; Documentation
21943 (defun org-require-autoloaded-modules ()
21944 (interactive)
21945 (mapc #'require
21946 '(org-agenda org-archive org-attach org-clock org-colview org-id
21947 org-table org-timer)))
21949 ;;;###autoload
21950 (defun org-reload (&optional uncompiled)
21951 "Reload all org lisp files.
21952 With prefix arg UNCOMPILED, load the uncompiled versions."
21953 (interactive "P")
21954 (require 'loadhist)
21955 (let* ((org-dir (org-find-library-dir "org"))
21956 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21957 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21958 (remove-re (format "\\`%s\\'"
21959 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21960 (feats (delete-dups
21961 (mapcar 'file-name-sans-extension
21962 (mapcar 'file-name-nondirectory
21963 (delq nil
21964 (mapcar 'feature-file
21965 features))))))
21966 (lfeat (append
21967 (sort
21968 (setq feats
21969 (delq nil (mapcar
21970 (lambda (f)
21971 (if (and (string-match feature-re f)
21972 (not (string-match remove-re f)))
21973 f nil))
21974 feats)))
21975 'string-lessp)
21976 (list "org-version" "org")))
21977 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21978 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21979 load-uncore load-misses)
21980 (setq load-misses
21981 (delq 't
21982 (mapcar (lambda (f)
21983 (or (org-load-noerror-mustsuffix (concat org-dir f))
21984 (and (string= org-dir contrib-dir)
21985 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21986 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21987 (add-to-list 'load-uncore f 'append)
21990 lfeat)))
21991 (when load-uncore
21992 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21993 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21994 (if load-misses
21995 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21996 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21997 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21999 ;;;###autoload
22000 (defun org-customize ()
22001 "Call the customize function with org as argument."
22002 (interactive)
22003 (org-load-modules-maybe)
22004 (org-require-autoloaded-modules)
22005 (customize-browse 'org))
22007 (defun org-create-customize-menu ()
22008 "Create a full customization menu for Org mode, insert it into the menu."
22009 (interactive)
22010 (org-load-modules-maybe)
22011 (org-require-autoloaded-modules)
22012 (if (fboundp 'customize-menu-create)
22013 (progn
22014 (easy-menu-change
22015 '("Org") "Customize"
22016 `(["Browse Org group" org-customize t]
22017 "--"
22018 ,(customize-menu-create 'org)
22019 ["Set" Custom-set t]
22020 ["Save" Custom-save t]
22021 ["Reset to Current" Custom-reset-current t]
22022 ["Reset to Saved" Custom-reset-saved t]
22023 ["Reset to Standard Settings" Custom-reset-standard t]))
22024 (message "\"Org\"-menu now contains full customization menu"))
22025 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22027 ;;;; Miscellaneous stuff
22029 ;;; Generally useful functions
22031 (defun org-get-at-eol (property n)
22032 "Get text property PROPERTY at the end of line less N characters."
22033 (get-text-property (- (point-at-eol) n) property))
22035 (defun org-find-text-property-in-string (prop s)
22036 "Return the first non-nil value of property PROP in string S."
22037 (or (get-text-property 0 prop s)
22038 (get-text-property (or (next-single-property-change 0 prop s) 0)
22039 prop s)))
22041 (defun org-display-warning (message)
22042 "Display the given MESSAGE as a warning."
22043 (display-warning 'org message :warning))
22045 (defun org-eval (form)
22046 "Eval FORM and return result."
22047 (condition-case error
22048 (eval form)
22049 (error (format "%%![Error: %s]" error))))
22051 (defun org-in-clocktable-p ()
22052 "Check if the cursor is in a clocktable."
22053 (let ((pos (point)) start)
22054 (save-excursion
22055 (end-of-line 1)
22056 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22057 (setq start (match-beginning 0))
22058 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22059 (>= (match-end 0) pos)
22060 start))))
22062 (defun org-in-verbatim-emphasis ()
22063 (save-match-data
22064 (and (org-in-regexp org-emph-re 2)
22065 (>= (point) (match-beginning 3))
22066 (<= (point) (match-end 4))
22067 (member (match-string 3) '("=" "~")))))
22069 (defun org-overlay-display (ovl text &optional face evap)
22070 "Make overlay OVL display TEXT with face FACE."
22071 (overlay-put ovl 'display text)
22072 (if face (overlay-put ovl 'face face))
22073 (if evap (overlay-put ovl 'evaporate t)))
22075 (defun org-overlay-before-string (ovl text &optional face evap)
22076 "Make overlay OVL display TEXT with face FACE."
22077 (if face (org-add-props text nil 'face face))
22078 (overlay-put ovl 'before-string text)
22079 (if evap (overlay-put ovl 'evaporate t)))
22081 (defun org-find-overlays (prop &optional pos delete)
22082 "Find all overlays specifying PROP at POS or point.
22083 If DELETE is non-nil, delete all those overlays."
22084 (let (found)
22085 (dolist (ov (overlays-at (or pos (point))) found)
22086 (cond ((not (overlay-get ov prop)))
22087 (delete (delete-overlay ov))
22088 (t (push ov found))))))
22090 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22091 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22092 (if (and marker (marker-buffer marker)
22093 (buffer-live-p (marker-buffer marker)))
22094 (progn
22095 (pop-to-buffer-same-window (marker-buffer marker))
22096 (when (or (> marker (point-max)) (< marker (point-min)))
22097 (widen))
22098 (goto-char marker)
22099 (org-show-context 'org-goto))
22100 (if bookmark
22101 (bookmark-jump bookmark)
22102 (error "Cannot find location"))))
22104 (defun org-quote-csv-field (s)
22105 "Quote field for inclusion in CSV material."
22106 (if (string-match "[\",]" s)
22107 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22110 (defun org-force-self-insert (N)
22111 "Needed to enforce self-insert under remapping."
22112 (interactive "p")
22113 (self-insert-command N))
22115 (defun org-string-width (s)
22116 "Compute width of string, ignoring invisible characters.
22117 This ignores character with invisibility property `org-link', and also
22118 characters with property `org-cwidth', because these will become invisible
22119 upon the next fontification round."
22120 (let (b l)
22121 (when (or (eq t buffer-invisibility-spec)
22122 (assq 'org-link buffer-invisibility-spec))
22123 (while (setq b (text-property-any 0 (length s)
22124 'invisible 'org-link s))
22125 (setq s (concat (substring s 0 b)
22126 (substring s (or (next-single-property-change
22127 b 'invisible s)
22128 (length s)))))))
22129 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22130 (setq s (concat (substring s 0 b)
22131 (substring s (or (next-single-property-change
22132 b 'org-cwidth s)
22133 (length s))))))
22134 (setq l (string-width s) b -1)
22135 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22136 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22139 (defun org-shorten-string (s maxlength)
22140 "Shorten string S so that it is no longer than MAXLENGTH characters.
22141 If the string is shorter or has length MAXLENGTH, just return the
22142 original string. If it is longer, the functions finds a space in the
22143 string, breaks this string off at that locations and adds three dots
22144 as ellipsis. Including the ellipsis, the string will not be longer
22145 than MAXLENGTH. If finding a good breaking point in the string does
22146 not work, the string is just chopped off in the middle of a word
22147 if necessary."
22148 (if (<= (length s) maxlength)
22150 (let* ((n (max (- maxlength 4) 1))
22151 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22152 (if (string-match re s)
22153 (concat (match-string 1 s) "...")
22154 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22156 (defun org-get-indentation (&optional line)
22157 "Get the indentation of the current line, interpreting tabs.
22158 When LINE is given, assume it represents a line and compute its indentation."
22159 (if line
22160 (when (string-match "^ *" (org-remove-tabs line))
22161 (match-end 0))
22162 (save-excursion
22163 (beginning-of-line 1)
22164 (skip-chars-forward " \t")
22165 (current-column))))
22167 (defun org-get-string-indentation (s)
22168 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22169 (let ((n -1) (i 0) (w tab-width) c)
22170 (catch 'exit
22171 (while (< (setq n (1+ n)) (length s))
22172 (setq c (aref s n))
22173 (cond ((= c ?\ ) (setq i (1+ i)))
22174 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22175 (t (throw 'exit t)))))
22178 (defun org-remove-tabs (s &optional width)
22179 "Replace tabulators in S with spaces.
22180 Assumes that s is a single line, starting in column 0."
22181 (setq width (or width tab-width))
22182 (while (string-match "\t" s)
22183 (setq s (replace-match
22184 (make-string
22185 (- (* width (/ (+ (match-beginning 0) width) width))
22186 (match-beginning 0)) ?\ )
22187 t t s)))
22190 (defun org-fix-indentation (line ind)
22191 "Fix indentation in LINE.
22192 IND is a cons cell with target and minimum indentation.
22193 If the current indentation in LINE is smaller than the minimum,
22194 leave it alone. If it is larger than ind, set it to the target."
22195 (let* ((l (org-remove-tabs line))
22196 (i (org-get-indentation l))
22197 (i1 (car ind)) (i2 (cdr ind)))
22198 (when (>= i i2) (setq l (substring line i2)))
22199 (if (> i1 0)
22200 (concat (make-string i1 ?\ ) l)
22201 l)))
22203 (defun org-remove-indentation (code &optional n)
22204 "Remove maximum common indentation in string CODE and return it.
22205 N may optionally be the number of columns to remove. Return CODE
22206 as-is if removal failed."
22207 (with-temp-buffer
22208 (insert code)
22209 (if (org-do-remove-indentation n) (buffer-string) code)))
22211 (defun org-do-remove-indentation (&optional n)
22212 "Remove the maximum common indentation from the buffer.
22213 When optional argument N is a positive integer, remove exactly
22214 that much characters from indentation, if possible. Return nil
22215 if it fails."
22216 (catch :exit
22217 (goto-char (point-min))
22218 ;; Find maximum common indentation, if not specified.
22219 (let ((n (or n
22220 (let ((min-ind (point-max)))
22221 (save-excursion
22222 (while (re-search-forward "^[ \t]*\\S-" nil t)
22223 (let ((ind (1- (current-column))))
22224 (if (zerop ind) (throw :exit nil)
22225 (setq min-ind (min min-ind ind))))))
22226 min-ind))))
22227 (if (zerop n) (throw :exit nil)
22228 ;; Remove exactly N indentation, but give up if not possible.
22229 (while (not (eobp))
22230 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22231 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22232 ((< ind n) (throw :exit nil))
22233 (t (indent-line-to (- ind n))))
22234 (forward-line)))
22235 ;; Signal success.
22236 t))))
22238 (defun org-fill-template (template alist)
22239 "Find each %key of ALIST in TEMPLATE and replace it."
22240 (let ((case-fold-search nil))
22241 (dolist (entry (sort (copy-sequence alist)
22242 (lambda (a b) (< (length (car a)) (length (car b))))))
22243 (setq template
22244 (replace-regexp-in-string
22245 (concat "%" (regexp-quote (car entry)))
22246 (or (cdr entry) "") template t t)))
22247 template))
22249 (defun org-base-buffer (buffer)
22250 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22251 (if (not buffer)
22252 buffer
22253 (or (buffer-base-buffer buffer)
22254 buffer)))
22256 (defun org-wrap (string &optional width lines)
22257 "Wrap string to either a number of lines, or a width in characters.
22258 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22259 that costs. If there is a word longer than WIDTH, the text is actually
22260 wrapped to the length of that word.
22261 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22262 many lines, whatever width that takes.
22263 The return value is a list of lines, without newlines at the end."
22264 (let* ((words (org-split-string string "[ \t\n]+"))
22265 (maxword (apply 'max (mapcar 'org-string-width words)))
22266 w ll)
22267 (cond (width
22268 (org-do-wrap words (max maxword width)))
22269 (lines
22270 (setq w maxword)
22271 (setq ll (org-do-wrap words maxword))
22272 (if (<= (length ll) lines)
22274 (setq ll words)
22275 (while (> (length ll) lines)
22276 (setq w (1+ w))
22277 (setq ll (org-do-wrap words w)))
22278 ll))
22279 (t (error "Cannot wrap this")))))
22281 (defun org-do-wrap (words width)
22282 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22283 (let (lines line)
22284 (while words
22285 (setq line (pop words))
22286 (while (and words (< (+ (length line) (length (car words))) width))
22287 (setq line (concat line " " (pop words))))
22288 (setq lines (push line lines)))
22289 (nreverse lines)))
22291 (defun org-split-string (string &optional separators)
22292 "Splits STRING into substrings at SEPARATORS.
22293 SEPARATORS is a regular expression.
22294 No empty strings are returned if there are matches at the beginning
22295 and end of string."
22296 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22297 (let ((start 0) notfirst list)
22298 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22299 (if (and notfirst
22300 (= start (match-beginning 0))
22301 (< start (length string)))
22302 (1+ start) start))
22303 (< (match-beginning 0) (length string)))
22304 (setq notfirst t)
22305 (or (eq (match-beginning 0) 0)
22306 (and (eq (match-beginning 0) (match-end 0))
22307 (eq (match-beginning 0) start))
22308 (push (substring string start (match-beginning 0)) list))
22309 (setq start (match-end 0)))
22310 (or (eq start (length string))
22311 (push (substring string start) list))
22312 (nreverse list)))
22314 (defun org-quote-vert (s)
22315 "Replace \"|\" with \"\\vert\"."
22316 (while (string-match "|" s)
22317 (setq s (replace-match "\\vert" t t s)))
22320 (defun org-uuidgen-p (s)
22321 "Is S an ID created by UUIDGEN?"
22322 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22324 (defun org-in-src-block-p (&optional inside)
22325 "Whether point is in a code source block.
22326 When INSIDE is non-nil, don't consider we are within a src block
22327 when point is at #+BEGIN_SRC or #+END_SRC."
22328 (let ((case-fold-search t))
22329 (or (and (eq (get-char-property (point) 'src-block) t))
22330 (and (not inside)
22331 (save-match-data
22332 (save-excursion
22333 (beginning-of-line)
22334 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22336 (defun org-context ()
22337 "Return a list of contexts of the current cursor position.
22338 If several contexts apply, all are returned.
22339 Each context entry is a list with a symbol naming the context, and
22340 two positions indicating start and end of the context. Possible
22341 contexts are:
22343 :headline anywhere in a headline
22344 :headline-stars on the leading stars in a headline
22345 :todo-keyword on a TODO keyword (including DONE) in a headline
22346 :tags on the TAGS in a headline
22347 :priority on the priority cookie in a headline
22348 :item on the first line of a plain list item
22349 :item-bullet on the bullet/number of a plain list item
22350 :checkbox on the checkbox in a plain list item
22351 :table in an Org table
22352 :table-special on a special filed in a table
22353 :table-table in a table.el table
22354 :clocktable in a clocktable
22355 :src-block in a source block
22356 :link on a hyperlink
22357 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22358 :target on a <<target>>
22359 :radio-target on a <<<radio-target>>>
22360 :latex-fragment on a LaTeX fragment
22361 :latex-preview on a LaTeX fragment with overlaid preview image
22363 This function expects the position to be visible because it uses font-lock
22364 faces as a help to recognize the following contexts: :table-special, :link,
22365 and :keyword."
22366 (let* ((f (get-text-property (point) 'face))
22367 (faces (if (listp f) f (list f)))
22368 (case-fold-search t)
22369 (p (point)) clist o)
22370 ;; First the large context
22371 (cond
22372 ((org-at-heading-p t)
22373 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22374 (when (progn
22375 (beginning-of-line 1)
22376 (looking-at org-todo-line-tags-regexp))
22377 (push (org-point-in-group p 1 :headline-stars) clist)
22378 (push (org-point-in-group p 2 :todo-keyword) clist)
22379 (push (org-point-in-group p 4 :tags) clist))
22380 (goto-char p)
22381 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22382 (when (looking-at "\\[#[A-Z0-9]\\]")
22383 (push (org-point-in-group p 0 :priority) clist)))
22385 ((org-at-item-p)
22386 (push (org-point-in-group p 2 :item-bullet) clist)
22387 (push (list :item (point-at-bol)
22388 (save-excursion (org-end-of-item) (point)))
22389 clist)
22390 (and (org-at-item-checkbox-p)
22391 (push (org-point-in-group p 0 :checkbox) clist)))
22393 ((org-at-table-p)
22394 (push (list :table (org-table-begin) (org-table-end)) clist)
22395 (when (memq 'org-formula faces)
22396 (push (list :table-special
22397 (previous-single-property-change p 'face)
22398 (next-single-property-change p 'face)) clist)))
22399 ((org-at-table-p 'any)
22400 (push (list :table-table) clist)))
22401 (goto-char p)
22403 (let ((case-fold-search t))
22404 ;; New the "medium" contexts: clocktables, source blocks
22405 (cond ((org-in-clocktable-p)
22406 (push (list :clocktable
22407 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22408 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22409 (match-beginning 1))
22410 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22411 (match-end 0))) clist))
22412 ((org-in-src-block-p)
22413 (push (list :src-block
22414 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22415 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22416 (match-beginning 1))
22417 (and (search-forward "#+END_SRC" nil t)
22418 (match-beginning 0))) clist))))
22419 (goto-char p)
22421 ;; Now the small context
22422 (cond
22423 ((org-at-timestamp-p)
22424 (push (org-point-in-group p 0 :timestamp) clist))
22425 ((memq 'org-link faces)
22426 (push (list :link
22427 (previous-single-property-change p 'face)
22428 (next-single-property-change p 'face)) clist))
22429 ((memq 'org-special-keyword faces)
22430 (push (list :keyword
22431 (previous-single-property-change p 'face)
22432 (next-single-property-change p 'face)) clist))
22433 ((org-at-target-p)
22434 (push (org-point-in-group p 0 :target) clist)
22435 (goto-char (1- (match-beginning 0)))
22436 (when (looking-at org-radio-target-regexp)
22437 (push (org-point-in-group p 0 :radio-target) clist))
22438 (goto-char p))
22439 ((setq o (cl-some
22440 (lambda (o)
22441 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22443 (overlays-at (point))))
22444 (push (list :latex-fragment
22445 (overlay-start o) (overlay-end o)) clist)
22446 (push (list :latex-preview
22447 (overlay-start o) (overlay-end o)) clist))
22448 ((org-inside-LaTeX-fragment-p)
22449 ;; FIXME: positions wrong.
22450 (push (list :latex-fragment (point) (point)) clist)))
22452 (setq clist (nreverse (delq nil clist)))
22453 clist))
22455 (defun org-in-regexp (regexp &optional nlines visually)
22456 "Check if point is inside a match of REGEXP.
22458 Normally only the current line is checked, but you can include
22459 NLINES extra lines around point into the search. If VISUALLY is
22460 set, require that the cursor is not after the match but really
22461 on, so that the block visually is on the match.
22463 Return nil or a cons cell (BEG . END) where BEG and END are,
22464 respectively, the positions at the beginning and the end of the
22465 match."
22466 (catch :exit
22467 (let ((pos (point))
22468 (eol (line-end-position (if nlines (1+ nlines) 1))))
22469 (save-excursion
22470 (beginning-of-line (- 1 (or nlines 0)))
22471 (while (and (re-search-forward regexp eol t)
22472 (<= (match-beginning 0) pos))
22473 (let ((end (match-end 0)))
22474 (when (or (> end pos) (and (= end pos) (not visually)))
22475 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22477 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22478 "Non-nil when point is between matches of START-RE and END-RE.
22480 Also return a non-nil value when point is on one of the matches.
22482 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22483 buffer positions. Default values are the positions of headlines
22484 surrounding the point.
22486 The functions returns a cons cell whose car (resp. cdr) is the
22487 position before START-RE (resp. after END-RE)."
22488 (save-match-data
22489 (let ((pos (point))
22490 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22491 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22492 beg end)
22493 (save-excursion
22494 ;; Point is on a block when on START-RE or if START-RE can be
22495 ;; found before it...
22496 (and (or (org-in-regexp start-re)
22497 (re-search-backward start-re limit-up t))
22498 (setq beg (match-beginning 0))
22499 ;; ... and END-RE after it...
22500 (goto-char (match-end 0))
22501 (re-search-forward end-re limit-down t)
22502 (> (setq end (match-end 0)) pos)
22503 ;; ... without another START-RE in-between.
22504 (goto-char (match-beginning 0))
22505 (not (re-search-backward start-re (1+ beg) t))
22506 ;; Return value.
22507 (cons beg end))))))
22509 (defun org-in-block-p (names)
22510 "Non-nil when point belongs to a block whose name belongs to NAMES.
22512 NAMES is a list of strings containing names of blocks.
22514 Return first block name matched, or nil. Beware that in case of
22515 nested blocks, the returned name may not belong to the closest
22516 block from point."
22517 (save-match-data
22518 (catch 'exit
22519 (let ((case-fold-search t)
22520 (lim-up (save-excursion (outline-previous-heading)))
22521 (lim-down (save-excursion (outline-next-heading))))
22522 (dolist (name names)
22523 (let ((n (regexp-quote name)))
22524 (when (org-between-regexps-p
22525 (concat "^[ \t]*#\\+begin_" n)
22526 (concat "^[ \t]*#\\+end_" n)
22527 lim-up lim-down)
22528 (throw 'exit n)))))
22529 nil)))
22531 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22532 "Call `multi-occur' with buffers for all agenda files."
22533 (interactive "sOrg-files matching: ")
22534 (let* ((files (org-agenda-files))
22535 (tnames (mapcar #'file-truename files))
22536 (extra org-agenda-text-search-extra-files))
22537 (when (eq (car extra) 'agenda-archives)
22538 (setq extra (cdr extra))
22539 (setq files (org-add-archive-files files)))
22540 (dolist (f extra)
22541 (unless (member (file-truename f) tnames)
22542 (unless (member f files) (setq files (append files (list f))))
22543 (setq tnames (append tnames (list (file-truename f))))))
22544 (multi-occur
22545 (mapcar (lambda (x)
22546 (with-current-buffer
22547 ;; FIXME: Why not just (find-file-noselect x)?
22548 ;; Is it to avoid the "revert buffer" prompt?
22549 (or (get-file-buffer x) (find-file-noselect x))
22550 (widen)
22551 (current-buffer)))
22552 files)
22553 regexp)))
22555 (add-hook 'occur-mode-find-occurrence-hook
22556 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22558 (defun org-occur-link-in-agenda-files ()
22559 "Create a link and search for it in the agendas.
22560 The link is not stored in `org-stored-links', it is just created
22561 for the search purpose."
22562 (interactive)
22563 (let ((link (condition-case nil
22564 (org-store-link nil)
22565 (error "Unable to create a link to here"))))
22566 (org-occur-in-agenda-files (regexp-quote link))))
22568 (defun org-reverse-string (string)
22569 "Return the reverse of STRING."
22570 (apply 'string (reverse (string-to-list string))))
22572 ;; defsubst org-uniquify must be defined before first use
22574 (defun org-uniquify-alist (alist)
22575 "Merge elements of ALIST with the same key.
22577 For example, in this alist:
22579 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22580 => \\='((a 1 3) (b 2))
22582 merge (a 1) and (a 3) into (a 1 3).
22584 The function returns the new ALIST."
22585 (let (rtn)
22586 (dolist (e alist rtn)
22587 (let (n)
22588 (if (not (assoc (car e) rtn))
22589 (push e rtn)
22590 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22591 (setq rtn (assq-delete-all (car e) rtn))
22592 (push n rtn))))))
22594 (defun org-delete-all (elts list)
22595 "Remove all elements in ELTS from LIST.
22596 Comparison is done with `equal'. It is a destructive operation
22597 that may remove elements by altering the list structure."
22598 (while elts
22599 (setq list (delete (pop elts) list)))
22600 list)
22602 (defun org-back-over-empty-lines ()
22603 "Move backwards over whitespace, to the beginning of the first empty line.
22604 Returns the number of empty lines passed."
22605 (let ((pos (point)))
22606 (if (cdr (assq 'heading org-blank-before-new-entry))
22607 (skip-chars-backward " \t\n\r")
22608 (unless (eobp)
22609 (forward-line -1)))
22610 (beginning-of-line 2)
22611 (goto-char (min (point) pos))
22612 (count-lines (point) pos)))
22614 (defun org-skip-whitespace ()
22615 (skip-chars-forward " \t\n\r"))
22617 (defun org-point-in-group (point group &optional context)
22618 "Check if POINT is in match-group GROUP.
22619 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22620 match. If the match group does not exist or point is not inside it,
22621 return nil."
22622 (and (match-beginning group)
22623 (>= point (match-beginning group))
22624 (<= point (match-end group))
22625 (if context
22626 (list context (match-beginning group) (match-end group))
22627 t)))
22629 (defun org-switch-to-buffer-other-window (&rest args)
22630 "Switch to buffer in a second window on the current frame.
22631 In particular, do not allow pop-up frames.
22632 Returns the newly created buffer."
22633 (org-no-popups
22634 (apply 'switch-to-buffer-other-window args)))
22636 (defun org-combine-plists (&rest plists)
22637 "Create a single property list from all plists in PLISTS.
22638 The process starts by copying the first list, and then setting properties
22639 from the other lists. Settings in the last list are the most significant
22640 ones and overrule settings in the other lists."
22641 (let ((rtn (copy-sequence (pop plists)))
22642 p v ls)
22643 (while plists
22644 (setq ls (pop plists))
22645 (while ls
22646 (setq p (pop ls) v (pop ls))
22647 (setq rtn (plist-put rtn p v))))
22648 rtn))
22650 (defun org-replace-escapes (string table)
22651 "Replace %-escapes in STRING with values in TABLE.
22652 TABLE is an association list with keys like \"%a\" and string values.
22653 The sequences in STRING may contain normal field width and padding information,
22654 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22655 so values can contain further %-escapes if they are define later in TABLE."
22656 (let ((tbl (copy-alist table))
22657 (case-fold-search nil)
22658 (pchg 0)
22659 re rpl)
22660 (dolist (e tbl)
22661 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22662 (when (and (cdr e) (string-match re (cdr e)))
22663 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22664 (safe "SREF"))
22665 (add-text-properties 0 3 (list 'sref sref) safe)
22666 (setcdr e (replace-match safe t t (cdr e)))))
22667 (while (string-match re string)
22668 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22669 (cdr e)))
22670 (setq string (replace-match rpl t t string))))
22671 (while (setq pchg (next-property-change pchg string))
22672 (let ((sref (get-text-property pchg 'sref string)))
22673 (when (and sref (string-match "SREF" string pchg))
22674 (setq string (replace-match sref t t string)))))
22675 string))
22677 (defun org-find-base-buffer-visiting (file)
22678 "Like `find-buffer-visiting' but always return the base buffer and
22679 not an indirect buffer."
22680 (let ((buf (or (get-file-buffer file)
22681 (find-buffer-visiting file))))
22682 (if buf
22683 (or (buffer-base-buffer buf) buf)
22684 nil)))
22686 ;;; TODO: Only called once, from ox-odt which should probably use
22687 ;;; org-export-inline-image-p or something.
22688 (defun org-file-image-p (file)
22689 "Return non-nil if FILE is an image."
22690 (save-match-data
22691 (string-match (image-file-name-regexp) file)))
22693 (defun org-get-cursor-date (&optional with-time)
22694 "Return the date at cursor in as a time.
22695 This works in the calendar and in the agenda, anywhere else it just
22696 returns the current time.
22697 If WITH-TIME is non-nil, returns the time of the event at point (in
22698 the agenda) or the current time of the day."
22699 (let (date day defd tp hod mod)
22700 (when with-time
22701 (setq tp (get-text-property (point) 'time))
22702 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22703 (setq hod (string-to-number (match-string 1 tp))
22704 mod (string-to-number (match-string 2 tp))))
22705 (or tp (let ((now (decode-time)))
22706 (setq hod (nth 2 now)
22707 mod (nth 1 now)))))
22708 (cond
22709 ((eq major-mode 'calendar-mode)
22710 (setq date (calendar-cursor-to-date)
22711 defd (encode-time 0 (or mod 0) (or hod 0)
22712 (nth 1 date) (nth 0 date) (nth 2 date))))
22713 ((eq major-mode 'org-agenda-mode)
22714 (setq day (get-text-property (point) 'day))
22715 (when day
22716 (setq date (calendar-gregorian-from-absolute day)
22717 defd (encode-time 0 (or mod 0) (or hod 0)
22718 (nth 1 date) (nth 0 date) (nth 2 date))))))
22719 (or defd (current-time))))
22721 (defun org-mark-subtree (&optional up)
22722 "Mark the current subtree.
22723 This puts point at the start of the current subtree, and mark at
22724 the end. If a numeric prefix UP is given, move up into the
22725 hierarchy of headlines by UP levels before marking the subtree."
22726 (interactive "P")
22727 (org-with-limited-levels
22728 (cond ((org-at-heading-p) (beginning-of-line))
22729 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22730 (t (outline-previous-visible-heading 1))))
22731 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22732 (if (called-interactively-p 'any)
22733 (call-interactively 'org-mark-element)
22734 (org-mark-element)))
22736 (defun org-file-newer-than-p (file time)
22737 "Non-nil if FILE is newer than TIME.
22738 FILE is a filename, as a string, TIME is a list of integers, as
22739 returned by, e.g., `current-time'."
22740 (and (file-exists-p file)
22741 ;; Only compare times up to whole seconds as some file-systems
22742 ;; (e.g. HFS+) do not retain any finer granularity. As
22743 ;; a consequence, make sure we return non-nil when the two
22744 ;; times are equal.
22745 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22746 (cl-subseq time 0 2)))))
22748 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22749 "Compile a SOURCE file using PROCESS.
22751 PROCESS is either a function or a list of shell commands, as
22752 strings. EXT is a file extension, without the leading dot, as
22753 a string. It is used to check if the process actually succeeded.
22755 PROCESS must create a file with the same base name and directory
22756 as SOURCE, but ending with EXT. The function then returns its
22757 filename. Otherwise, it raises an error. The error message can
22758 then be refined by providing string ERR-MSG, which is appended to
22759 the standard message.
22761 If PROCESS is a function, it is called with a single argument:
22762 the SOURCE file.
22764 If it is a list of commands, each of them is called using
22765 `shell-command'. By default, in each command, %b, %f, %F, %o and
22766 %O are replaced with, respectively, SOURCE base name, name, full
22767 name, directory and absolute output file name. It is possible,
22768 however, to use more place-holders by specifying them in optional
22769 argument SPEC, as an alist following the pattern
22771 (CHARACTER . REPLACEMENT-STRING).
22773 When PROCESS is a list of commands, optional argument LOG-BUF can
22774 be set to a buffer or a buffer name. `shell-command' then uses
22775 it for output."
22776 (let* ((base-name (file-name-base source))
22777 (full-name (file-truename source))
22778 (out-dir (file-name-directory source))
22779 (output (expand-file-name (concat base-name "." ext) out-dir))
22780 (time (current-time))
22781 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22782 (save-window-excursion
22783 (pcase process
22784 ((pred functionp) (funcall process (shell-quote-argument source)))
22785 ((pred consp)
22786 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22787 (spec (append spec
22788 `((?b . ,(shell-quote-argument base-name))
22789 (?f . ,(shell-quote-argument source))
22790 (?F . ,(shell-quote-argument full-name))
22791 (?o . ,(shell-quote-argument out-dir))
22792 (?O . ,(shell-quote-argument output))))))
22793 (dolist (command process)
22794 (shell-command (format-spec command spec) log-buf))))
22795 (_ (error "No valid command to process %S%s" source err-msg))))
22796 ;; Check for process failure. Output file is expected to be
22797 ;; located in the same directory as SOURCE.
22798 (unless (org-file-newer-than-p output time)
22799 (error (format "File %S wasn't produced%s" output err-msg)))
22800 output))
22802 ;;; Indentation
22804 (defun org--get-expected-indentation (element contentsp)
22805 "Expected indentation column for current line, according to ELEMENT.
22806 ELEMENT is an element containing point. CONTENTSP is non-nil
22807 when indentation is to be computed according to contents of
22808 ELEMENT."
22809 (let ((type (org-element-type element))
22810 (start (org-element-property :begin element))
22811 (post-affiliated (org-element-property :post-affiliated element)))
22812 (org-with-wide-buffer
22813 (cond
22814 (contentsp
22815 (cl-case type
22816 ((diary-sexp footnote-definition) 0)
22817 ((headline inlinetask nil)
22818 (if (not org-adapt-indentation) 0
22819 (let ((level (org-current-level)))
22820 (if level (1+ level) 0))))
22821 ((item plain-list) (org-list-item-body-column post-affiliated))
22823 (goto-char start)
22824 (org-get-indentation))))
22825 ((memq type '(headline inlinetask nil))
22826 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22827 (org--get-expected-indentation element t)
22829 ((memq type '(diary-sexp footnote-definition)) 0)
22830 ;; First paragraph of a footnote definition or an item.
22831 ;; Indent like parent.
22832 ((< (line-beginning-position) start)
22833 (org--get-expected-indentation
22834 (org-element-property :parent element) t))
22835 ;; At first line: indent according to previous sibling, if any,
22836 ;; ignoring footnote definitions and inline tasks, or parent's
22837 ;; contents.
22838 ((= (line-beginning-position) start)
22839 (catch 'exit
22840 (while t
22841 (if (= (point-min) start) (throw 'exit 0)
22842 (goto-char (1- start))
22843 (let* ((previous (org-element-at-point))
22844 (parent previous))
22845 (while (and parent (<= (org-element-property :end parent) start))
22846 (setq previous parent
22847 parent (org-element-property :parent parent)))
22848 (cond
22849 ((not previous) (throw 'exit 0))
22850 ((> (org-element-property :end previous) start)
22851 (throw 'exit (org--get-expected-indentation previous t)))
22852 ((memq (org-element-type previous)
22853 '(footnote-definition inlinetask))
22854 (setq start (org-element-property :begin previous)))
22855 (t (goto-char (org-element-property :begin previous))
22856 (throw 'exit
22857 (if (bolp) (org-get-indentation)
22858 ;; At first paragraph in an item or
22859 ;; a footnote definition.
22860 (org--get-expected-indentation
22861 (org-element-property :parent previous) t))))))))))
22862 ;; Otherwise, move to the first non-blank line above.
22864 (beginning-of-line)
22865 (let ((pos (point)))
22866 (skip-chars-backward " \r\t\n")
22867 (cond
22868 ;; Two blank lines end a footnote definition or a plain
22869 ;; list. When we indent an empty line after them, the
22870 ;; containing list or footnote definition is over, so it
22871 ;; qualifies as a previous sibling. Therefore, we indent
22872 ;; like its first line.
22873 ((and (memq type '(footnote-definition plain-list))
22874 (> (count-lines (point) pos) 2))
22875 (goto-char start)
22876 (org-get-indentation))
22877 ;; Line above is the first one of a paragraph at the
22878 ;; beginning of an item or a footnote definition. Indent
22879 ;; like parent.
22880 ((< (line-beginning-position) start)
22881 (org--get-expected-indentation
22882 (org-element-property :parent element) t))
22883 ;; Line above is the beginning of an element, i.e., point
22884 ;; was originally on the blank lines between element's start
22885 ;; and contents.
22886 ((= (line-beginning-position) post-affiliated)
22887 (org--get-expected-indentation element t))
22888 ;; POS is after contents in a greater element. Indent like
22889 ;; the beginning of the element.
22891 ;; As a special case, if point is at the end of a footnote
22892 ;; definition or an item, indent like the very last element
22893 ;; within. If that last element is an item, indent like its
22894 ;; contents.
22895 ((and (not (eq type 'paragraph))
22896 (let ((cend (org-element-property :contents-end element)))
22897 (and cend (<= cend pos))))
22898 (if (memq type '(footnote-definition item plain-list))
22899 (let ((last (org-element-at-point)))
22900 (org--get-expected-indentation
22901 last (eq (org-element-type last) 'item)))
22902 (goto-char start)
22903 (org-get-indentation)))
22904 ;; In any other case, indent like the current line.
22905 (t (org-get-indentation)))))))))
22907 (defun org--align-node-property ()
22908 "Align node property at point.
22909 Alignment is done according to `org-property-format', which see."
22910 (when (save-excursion
22911 (beginning-of-line)
22912 (looking-at org-property-re))
22913 (replace-match
22914 (concat (match-string 4)
22915 (org-trim
22916 (format org-property-format (match-string 1) (match-string 3))))
22917 t t)))
22919 (defun org-indent-line ()
22920 "Indent line depending on context.
22922 Indentation is done according to the following rules:
22924 - Footnote definitions, diary sexps, headlines and inline tasks
22925 have to start at column 0.
22927 - On the very first line of an element, consider, in order, the
22928 next rules until one matches:
22930 1. If there's a sibling element before, ignoring footnote
22931 definitions and inline tasks, indent like its first line.
22933 2. If element has a parent, indent like its contents. More
22934 precisely, if parent is an item, indent after the
22935 description part, if any, or the bullet (see
22936 `org-list-description-max-indent'). Else, indent like
22937 parent's first line.
22939 3. Otherwise, indent relatively to current level, if
22940 `org-adapt-indentation' is non-nil, or to left margin.
22942 - On a blank line at the end of an element, indent according to
22943 the type of the element. More precisely
22945 1. If element is a plain list, an item, or a footnote
22946 definition, indent like the very last element within.
22948 2. If element is a paragraph, indent like its last non blank
22949 line.
22951 3. Otherwise, indent like its very first line.
22953 - In the code part of a source block, use language major mode
22954 to indent current line if `org-src-tab-acts-natively' is
22955 non-nil. If it is nil, do nothing.
22957 - Otherwise, indent like the first non-blank line above.
22959 The function doesn't indent an item as it could break the whole
22960 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22961 `\\[org-shiftmetaright]'.
22963 Also align node properties according to `org-property-format'."
22964 (interactive)
22965 (cond
22966 (orgstruct-is-++
22967 (let ((indent-line-function
22968 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22969 (indent-according-to-mode)))
22970 ((org-at-heading-p) 'noindent)
22972 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22973 (type (org-element-type element)))
22974 (cond ((and (memq type '(plain-list item))
22975 (= (line-beginning-position)
22976 (org-element-property :post-affiliated element)))
22977 'noindent)
22978 ((and (eq type 'src-block)
22979 org-src-tab-acts-natively
22980 (> (line-beginning-position)
22981 (org-element-property :post-affiliated element))
22982 (< (line-beginning-position)
22983 (org-with-wide-buffer
22984 (goto-char (org-element-property :end element))
22985 (skip-chars-backward " \r\t\n")
22986 (line-beginning-position))))
22987 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22989 (let ((column (org--get-expected-indentation element nil)))
22990 ;; Preserve current column.
22991 (if (<= (current-column) (current-indentation))
22992 (indent-line-to column)
22993 (save-excursion (indent-line-to column))))
22994 ;; Align node property. Also preserve current column.
22995 (when (eq type 'node-property)
22996 (let ((column (current-column)))
22997 (org--align-node-property)
22998 (org-move-to-column column)))))))))
23000 (defun org-indent-region (start end)
23001 "Indent each non-blank line in the region.
23002 Called from a program, START and END specify the region to
23003 indent. The function will not indent contents of example blocks,
23004 verse blocks and export blocks as leading white spaces are
23005 assumed to be significant there."
23006 (interactive "r")
23007 (save-excursion
23008 (goto-char start)
23009 (skip-chars-forward " \r\t\n")
23010 (unless (eobp) (beginning-of-line))
23011 (let ((indent-to
23012 (lambda (ind pos)
23013 ;; Set IND as indentation for all lines between point and
23014 ;; POS. Blank lines are ignored. Leave point after POS
23015 ;; once done.
23016 (let ((limit (copy-marker pos)))
23017 (while (< (point) limit)
23018 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
23019 (forward-line))
23020 (set-marker limit nil))))
23021 (end (copy-marker end)))
23022 (while (< (point) end)
23023 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23024 (let* ((element (org-element-at-point))
23025 (type (org-element-type element))
23026 (element-end (copy-marker (org-element-property :end element)))
23027 (ind (org--get-expected-indentation element nil)))
23028 (cond
23029 ((or (memq type '(paragraph table table-row))
23030 (not (or (org-element-property :contents-begin element)
23031 (memq type
23032 '(example-block export-block src-block)))))
23033 ;; Elements here are indented as a single block. Also
23034 ;; align node properties.
23035 (when (eq type 'node-property)
23036 (org--align-node-property)
23037 (beginning-of-line))
23038 (funcall indent-to ind (min element-end end)))
23040 ;; Elements in this category consist of three parts:
23041 ;; before the contents, the contents, and after the
23042 ;; contents. The contents are treated specially,
23043 ;; according to the element type, or not indented at
23044 ;; all. Other parts are indented as a single block.
23045 (let* ((post (copy-marker
23046 (org-element-property :post-affiliated element)))
23047 (cbeg
23048 (copy-marker
23049 (cond
23050 ((not (org-element-property :contents-begin element))
23051 ;; Fake contents for source blocks.
23052 (org-with-wide-buffer
23053 (goto-char post)
23054 (forward-line)
23055 (point)))
23056 ((memq type '(footnote-definition item plain-list))
23057 ;; Contents in these elements could start on
23058 ;; the same line as the beginning of the
23059 ;; element. Make sure we start indenting
23060 ;; from the second line.
23061 (org-with-wide-buffer
23062 (goto-char post)
23063 (end-of-line)
23064 (skip-chars-forward " \r\t\n")
23065 (if (eobp) (point) (line-beginning-position))))
23066 (t (org-element-property :contents-begin element)))))
23067 (cend (copy-marker
23068 (or (org-element-property :contents-end element)
23069 ;; Fake contents for source blocks.
23070 (org-with-wide-buffer
23071 (goto-char element-end)
23072 (skip-chars-backward " \r\t\n")
23073 (line-beginning-position)))
23074 t)))
23075 ;; Do not change items indentation individually as it
23076 ;; might break the list as a whole. On the other
23077 ;; hand, when at a plain list, indent it as a whole.
23078 (cond ((eq type 'plain-list)
23079 (let ((offset (- ind (org-get-indentation))))
23080 (unless (zerop offset)
23081 (indent-rigidly (org-element-property :begin element)
23082 (org-element-property :end element)
23083 offset))
23084 (goto-char cbeg)))
23085 ((eq type 'item) (goto-char cbeg))
23086 (t (funcall indent-to ind (min cbeg end))))
23087 (when (< (point) end)
23088 (cl-case type
23089 ((example-block export-block verse-block))
23090 (src-block
23091 ;; In a source block, indent source code
23092 ;; according to language major mode, but only if
23093 ;; `org-src-tab-acts-natively' is non-nil.
23094 (when (and (< (point) end) org-src-tab-acts-natively)
23095 (ignore-errors
23096 (org-babel-do-in-edit-buffer
23097 (indent-region (point-min) (point-max))))))
23098 (t (org-indent-region (point) (min cend end))))
23099 (goto-char (min cend end))
23100 (when (< (point) end)
23101 (funcall indent-to ind (min element-end end))))
23102 (set-marker post nil)
23103 (set-marker cbeg nil)
23104 (set-marker cend nil))))
23105 (set-marker element-end nil))))
23106 (set-marker end nil))))
23108 (defun org-indent-drawer ()
23109 "Indent the drawer at point."
23110 (interactive)
23111 (unless (save-excursion
23112 (beginning-of-line)
23113 (looking-at-p org-drawer-regexp))
23114 (user-error "Not at a drawer"))
23115 (let ((element (org-element-at-point)))
23116 (unless (memq (org-element-type element) '(drawer property-drawer))
23117 (user-error "Not at a drawer"))
23118 (org-with-wide-buffer
23119 (org-indent-region (org-element-property :begin element)
23120 (org-element-property :end element))))
23121 (message "Drawer at point indented"))
23123 (defun org-indent-block ()
23124 "Indent the block at point."
23125 (interactive)
23126 (unless (save-excursion
23127 (beginning-of-line)
23128 (let ((case-fold-search t))
23129 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23130 (user-error "Not at a block"))
23131 (let ((element (org-element-at-point)))
23132 (unless (memq (org-element-type element)
23133 '(comment-block center-block dynamic-block example-block
23134 export-block quote-block special-block
23135 src-block verse-block))
23136 (user-error "Not at a block"))
23137 (org-with-wide-buffer
23138 (org-indent-region (org-element-property :begin element)
23139 (org-element-property :end element))))
23140 (message "Block at point indented"))
23143 ;;; Filling
23145 ;; We use our own fill-paragraph and auto-fill functions.
23147 ;; `org-fill-paragraph' relies on adaptive filling and context
23148 ;; checking. Appropriate `fill-prefix' is computed with
23149 ;; `org-adaptive-fill-function'.
23151 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23152 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23153 ;; `org-adaptive-fill-function' value. Internally,
23154 ;; `org-comment-line-break-function' breaks the line.
23156 ;; `org-setup-filling' installs filling and auto-filling related
23157 ;; variables during `org-mode' initialization.
23159 (defvar org-element-paragraph-separate) ; org-element.el
23160 (defun org-setup-filling ()
23161 (require 'org-element)
23162 ;; Prevent auto-fill from inserting unwanted new items.
23163 (when (boundp 'fill-nobreak-predicate)
23164 (setq-local
23165 fill-nobreak-predicate
23166 (org-uniquify
23167 (append fill-nobreak-predicate
23168 '(org-fill-line-break-nobreak-p
23169 org-fill-paragraph-with-timestamp-nobreak-p)))))
23170 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23171 (setq-local paragraph-start paragraph-ending)
23172 (setq-local paragraph-separate paragraph-ending))
23173 (setq-local fill-paragraph-function 'org-fill-paragraph)
23174 (setq-local auto-fill-inhibit-regexp nil)
23175 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23176 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23177 (setq-local comment-line-break-function 'org-comment-line-break-function))
23179 (defun org-fill-line-break-nobreak-p ()
23180 "Non-nil when a new line at point would create an Org line break."
23181 (save-excursion
23182 (skip-chars-backward "[ \t]")
23183 (skip-chars-backward "\\\\")
23184 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23186 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23187 "Non-nil when a new line at point would split a timestamp."
23188 (and (org-at-timestamp-p t)
23189 (not (looking-at org-ts-regexp-both))))
23191 (declare-function message-in-body-p "message" ())
23192 (defvar orgtbl-line-start-regexp) ; From org-table.el
23193 (defun org-adaptive-fill-function ()
23194 "Compute a fill prefix for the current line.
23195 Return fill prefix, as a string, or nil if current line isn't
23196 meant to be filled. For convenience, if `adaptive-fill-regexp'
23197 matches in paragraphs or comments, use it."
23198 (catch 'exit
23199 (when (derived-mode-p 'message-mode)
23200 (save-excursion
23201 (beginning-of-line)
23202 (cond ((not (message-in-body-p)) (throw 'exit nil))
23203 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23204 ((looking-at message-cite-prefix-regexp)
23205 (throw 'exit (match-string-no-properties 0)))
23206 ((looking-at org-outline-regexp)
23207 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23208 (org-with-wide-buffer
23209 (unless (org-at-heading-p)
23210 (let* ((p (line-beginning-position))
23211 (element (save-excursion
23212 (beginning-of-line)
23213 (org-element-at-point)))
23214 (type (org-element-type element))
23215 (post-affiliated (org-element-property :post-affiliated element)))
23216 (unless (< p post-affiliated)
23217 (cl-case type
23218 (comment
23219 (save-excursion
23220 (beginning-of-line)
23221 (looking-at "[ \t]*")
23222 (concat (match-string 0) "# ")))
23223 (footnote-definition "")
23224 ((item plain-list)
23225 (make-string (org-list-item-body-column post-affiliated) ?\s))
23226 (paragraph
23227 ;; Fill prefix is usually the same as the current line,
23228 ;; unless the paragraph is at the beginning of an item.
23229 (let ((parent (org-element-property :parent element)))
23230 (save-excursion
23231 (beginning-of-line)
23232 (cond ((eq (org-element-type parent) 'item)
23233 (make-string (org-list-item-body-column
23234 (org-element-property :begin parent))
23235 ?\s))
23236 ((and adaptive-fill-regexp
23237 ;; Locally disable
23238 ;; `adaptive-fill-function' to let
23239 ;; `fill-context-prefix' handle
23240 ;; `adaptive-fill-regexp' variable.
23241 (let (adaptive-fill-function)
23242 (fill-context-prefix
23243 post-affiliated
23244 (org-element-property :end element)))))
23245 ((looking-at "[ \t]+") (match-string 0))
23246 (t "")))))
23247 (comment-block
23248 ;; Only fill contents if P is within block boundaries.
23249 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23250 (forward-line)
23251 (point)))
23252 (cend (save-excursion
23253 (goto-char (org-element-property :end element))
23254 (skip-chars-backward " \r\t\n")
23255 (line-beginning-position))))
23256 (when (and (>= p cbeg) (< p cend))
23257 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23258 (match-string 0)
23259 "")))))))))))
23261 (declare-function message-goto-body "message" ())
23262 (defvar message-cite-prefix-regexp) ; From message.el
23263 (defun org-fill-paragraph (&optional justify)
23264 "Fill element at point, when applicable.
23266 This function only applies to comment blocks, comments, example
23267 blocks and paragraphs. Also, as a special case, re-align table
23268 when point is at one.
23270 If JUSTIFY is non-nil (interactively, with prefix argument),
23271 justify as well. If `sentence-end-double-space' is non-nil, then
23272 period followed by one space does not end a sentence, so don't
23273 break a line there. The variable `fill-column' controls the
23274 width for filling.
23276 For convenience, when point is at a plain list, an item or
23277 a footnote definition, try to fill the first paragraph within."
23278 (interactive)
23279 (if (and (derived-mode-p 'message-mode)
23280 (or (not (message-in-body-p))
23281 (save-excursion (move-beginning-of-line 1)
23282 (looking-at message-cite-prefix-regexp))))
23283 ;; First ensure filling is correct in message-mode.
23284 (let ((fill-paragraph-function
23285 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23286 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23287 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23288 (paragraph-separate
23289 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23290 (fill-paragraph nil))
23291 (with-syntax-table org-mode-transpose-word-syntax-table
23292 ;; Move to end of line in order to get the first paragraph
23293 ;; within a plain list or a footnote definition.
23294 (let ((element (save-excursion
23295 (end-of-line)
23296 (or (ignore-errors (org-element-at-point))
23297 (user-error "An element cannot be parsed line %d"
23298 (line-number-at-pos (point)))))))
23299 ;; First check if point is in a blank line at the beginning of
23300 ;; the buffer. In that case, ignore filling.
23301 (cl-case (org-element-type element)
23302 ;; Use major mode filling function is src blocks.
23303 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23304 ;; Align Org tables, leave table.el tables as-is.
23305 (table-row (org-table-align) t)
23306 (table
23307 (when (eq (org-element-property :type element) 'org)
23308 (save-excursion
23309 (goto-char (org-element-property :post-affiliated element))
23310 (org-table-align)))
23312 (paragraph
23313 ;; Paragraphs may contain `line-break' type objects.
23314 (let ((beg (max (point-min)
23315 (org-element-property :contents-begin element)))
23316 (end (min (point-max)
23317 (org-element-property :contents-end element))))
23318 ;; Do nothing if point is at an affiliated keyword.
23319 (if (< (line-end-position) beg) t
23320 (when (derived-mode-p 'message-mode)
23321 ;; In `message-mode', do not fill following citation
23322 ;; in current paragraph nor text before message body.
23323 (let ((body-start (save-excursion (message-goto-body))))
23324 (when body-start (setq beg (max body-start beg))))
23325 (when (save-excursion
23326 (re-search-forward
23327 (concat "^" message-cite-prefix-regexp) end t))
23328 (setq end (match-beginning 0))))
23329 ;; Fill paragraph, taking line breaks into account.
23330 (save-excursion
23331 (goto-char beg)
23332 (let ((cuts (list beg)))
23333 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23334 (when (eq 'line-break
23335 (org-element-type
23336 (save-excursion (backward-char)
23337 (org-element-context))))
23338 (push (point) cuts)))
23339 (dolist (c (delq end cuts))
23340 (fill-region-as-paragraph c end justify)
23341 (setq end c))))
23342 t)))
23343 ;; Contents of `comment-block' type elements should be
23344 ;; filled as plain text, but only if point is within block
23345 ;; markers.
23346 (comment-block
23347 (let* ((case-fold-search t)
23348 (beg (save-excursion
23349 (goto-char (org-element-property :begin element))
23350 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23351 (forward-line)
23352 (point)))
23353 (end (save-excursion
23354 (goto-char (org-element-property :end element))
23355 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23356 (line-beginning-position))))
23357 (if (or (< (point) beg) (> (point) end)) t
23358 (fill-region-as-paragraph
23359 (save-excursion (end-of-line)
23360 (re-search-backward "^[ \t]*$" beg 'move)
23361 (line-beginning-position))
23362 (save-excursion (beginning-of-line)
23363 (re-search-forward "^[ \t]*$" end 'move)
23364 (line-beginning-position))
23365 justify))))
23366 ;; Fill comments.
23367 (comment
23368 (let ((begin (org-element-property :post-affiliated element))
23369 (end (org-element-property :end element)))
23370 (when (and (>= (point) begin) (<= (point) end))
23371 (let ((begin (save-excursion
23372 (end-of-line)
23373 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23374 (progn (forward-line) (point))
23375 begin)))
23376 (end (save-excursion
23377 (end-of-line)
23378 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23379 (1- (line-beginning-position))
23380 (skip-chars-backward " \r\t\n")
23381 (line-end-position)))))
23382 ;; Do not fill comments when at a blank line.
23383 (when (> end begin)
23384 (let ((fill-prefix
23385 (save-excursion
23386 (beginning-of-line)
23387 (looking-at "[ \t]*#")
23388 (let ((comment-prefix (match-string 0)))
23389 (goto-char (match-end 0))
23390 (if (looking-at adaptive-fill-regexp)
23391 (concat comment-prefix (match-string 0))
23392 (concat comment-prefix " "))))))
23393 (save-excursion
23394 (fill-region-as-paragraph begin end justify))))))
23396 ;; Ignore every other element.
23397 (otherwise t))))))
23399 (defun org-auto-fill-function ()
23400 "Auto-fill function."
23401 ;; Check if auto-filling is meaningful.
23402 (let ((fc (current-fill-column)))
23403 (when (and fc (> (current-column) fc))
23404 (let* ((fill-prefix (org-adaptive-fill-function))
23405 ;; Enforce empty fill prefix, if required. Otherwise, it
23406 ;; will be computed again.
23407 (adaptive-fill-mode (not (equal fill-prefix ""))))
23408 (when fill-prefix (do-auto-fill))))))
23410 (defun org-comment-line-break-function (&optional soft)
23411 "Break line at point and indent, continuing comment if within one.
23412 The inserted newline is marked hard if variable
23413 `use-hard-newlines' is true, unless optional argument SOFT is
23414 non-nil."
23415 (if soft (insert-and-inherit ?\n) (newline 1))
23416 (save-excursion (forward-char -1) (delete-horizontal-space))
23417 (delete-horizontal-space)
23418 (indent-to-left-margin)
23419 (insert-before-markers-and-inherit fill-prefix))
23422 ;;; Fixed Width Areas
23424 (defun org-toggle-fixed-width ()
23425 "Toggle fixed-width markup.
23427 Add or remove fixed-width markup on current line, whenever it
23428 makes sense. Return an error otherwise.
23430 If a region is active and if it contains only fixed-width areas
23431 or blank lines, remove all fixed-width markup in it. If the
23432 region contains anything else, convert all non-fixed-width lines
23433 to fixed-width ones.
23435 Blank lines at the end of the region are ignored unless the
23436 region only contains such lines."
23437 (interactive)
23438 (if (not (org-region-active-p))
23439 ;; No region:
23441 ;; Remove fixed width marker only in a fixed-with element.
23443 ;; Add fixed width maker in paragraphs, in blank lines after
23444 ;; elements or at the beginning of a headline or an inlinetask,
23445 ;; and before any one-line elements (e.g., a clock).
23446 (progn
23447 (beginning-of-line)
23448 (let* ((element (org-element-at-point))
23449 (type (org-element-type element)))
23450 (cond
23451 ((and (eq type 'fixed-width)
23452 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23453 (replace-match
23454 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23455 ((and (memq type '(babel-call clock comment diary-sexp headline
23456 horizontal-rule keyword paragraph
23457 planning))
23458 (<= (org-element-property :post-affiliated element) (point)))
23459 (skip-chars-forward " \t")
23460 (insert ": "))
23461 ((and (looking-at-p "[ \t]*$")
23462 (or (eq type 'inlinetask)
23463 (save-excursion
23464 (skip-chars-forward " \r\t\n")
23465 (<= (org-element-property :end element) (point)))))
23466 (delete-region (point) (line-end-position))
23467 (org-indent-line)
23468 (insert ": "))
23469 (t (user-error "Cannot insert a fixed-width line here")))))
23470 ;; Region active.
23471 (let* ((begin (save-excursion
23472 (goto-char (region-beginning))
23473 (line-beginning-position)))
23474 (end (copy-marker
23475 (save-excursion
23476 (goto-char (region-end))
23477 (unless (eolp) (beginning-of-line))
23478 (if (save-excursion (re-search-backward "\\S-" begin t))
23479 (progn (skip-chars-backward " \r\t\n") (point))
23480 (point)))))
23481 (all-fixed-width-p
23482 (catch 'not-all-p
23483 (save-excursion
23484 (goto-char begin)
23485 (skip-chars-forward " \r\t\n")
23486 (when (eobp) (throw 'not-all-p nil))
23487 (while (< (point) end)
23488 (let ((element (org-element-at-point)))
23489 (if (eq (org-element-type element) 'fixed-width)
23490 (goto-char (org-element-property :end element))
23491 (throw 'not-all-p nil))))
23492 t))))
23493 (if all-fixed-width-p
23494 (save-excursion
23495 (goto-char begin)
23496 (while (< (point) end)
23497 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23498 (replace-match
23499 "" nil nil nil
23500 (if (= (line-end-position) (match-end 0)) 0 1)))
23501 (forward-line)))
23502 (let ((min-ind (point-max)))
23503 ;; Find minimum indentation across all lines.
23504 (save-excursion
23505 (goto-char begin)
23506 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23507 (setq min-ind 0)
23508 (catch 'zerop
23509 (while (< (point) end)
23510 (unless (looking-at-p "[ \t]*$")
23511 (let ((ind (org-get-indentation)))
23512 (setq min-ind (min min-ind ind))
23513 (when (zerop ind) (throw 'zerop t))))
23514 (forward-line)))))
23515 ;; Loop over all lines and add fixed-width markup everywhere
23516 ;; but in fixed-width lines.
23517 (save-excursion
23518 (goto-char begin)
23519 (while (< (point) end)
23520 (cond
23521 ((org-at-heading-p)
23522 (insert ": ")
23523 (forward-line)
23524 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23525 (insert ":")
23526 (forward-line)))
23527 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23528 (let* ((element (org-element-at-point))
23529 (element-end (org-element-property :end element)))
23530 (if (eq (org-element-type element) 'fixed-width)
23531 (progn (goto-char element-end)
23532 (skip-chars-backward " \r\t\n")
23533 (forward-line))
23534 (let ((limit (min end element-end)))
23535 (while (< (point) limit)
23536 (org-move-to-column min-ind t)
23537 (insert ": ")
23538 (forward-line))))))
23540 (org-move-to-column min-ind t)
23541 (insert ": ")
23542 (forward-line)))))))
23543 (set-marker end nil))))
23546 ;;; Comments
23548 ;; Org comments syntax is quite complex. It requires the entire line
23549 ;; to be just a comment. Also, even with the right syntax at the
23550 ;; beginning of line, some some elements (i.e. verse-block or
23551 ;; example-block) don't accept comments. Usual Emacs comment commands
23552 ;; cannot cope with those requirements. Therefore, Org replaces them.
23554 ;; Org still relies on `comment-dwim', but cannot trust
23555 ;; `comment-only-p'. So, `comment-region-function' and
23556 ;; `uncomment-region-function' both point
23557 ;; to`org-comment-or-uncomment-region'. Eventually,
23558 ;; `org-insert-comment' takes care of insertion of comments at the
23559 ;; beginning of line.
23561 ;; `org-setup-comments-handling' install comments related variables
23562 ;; during `org-mode' initialization.
23564 (defun org-setup-comments-handling ()
23565 (interactive)
23566 (setq-local comment-use-syntax nil)
23567 (setq-local comment-start "# ")
23568 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23569 (setq-local comment-insert-comment-function 'org-insert-comment)
23570 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23571 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23573 (defun org-insert-comment ()
23574 "Insert an empty comment above current line.
23575 If the line is empty, insert comment at its beginning. When
23576 point is within a source block, comment according to the related
23577 major mode."
23578 (if (let ((element (org-element-at-point)))
23579 (and (eq (org-element-type element) 'src-block)
23580 (< (save-excursion
23581 (goto-char (org-element-property :post-affiliated element))
23582 (line-end-position))
23583 (point))
23584 (> (save-excursion
23585 (goto-char (org-element-property :end element))
23586 (skip-chars-backward " \r\t\n")
23587 (line-beginning-position))
23588 (point))))
23589 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23590 (beginning-of-line)
23591 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23592 (open-line 1))
23593 (org-indent-line)
23594 (insert "# ")))
23596 (defvar comment-empty-lines) ; From newcomment.el.
23597 (defun org-comment-or-uncomment-region (beg end &rest _)
23598 "Comment or uncomment each non-blank line in the region.
23599 Uncomment each non-blank line between BEG and END if it only
23600 contains commented lines. Otherwise, comment them. If region is
23601 strictly within a source block, use appropriate comment syntax."
23602 (if (let ((element (org-element-at-point)))
23603 (and (eq (org-element-type element) 'src-block)
23604 (< (save-excursion
23605 (goto-char (org-element-property :post-affiliated element))
23606 (line-end-position))
23607 beg)
23608 (>= (save-excursion
23609 (goto-char (org-element-property :end element))
23610 (skip-chars-backward " \r\t\n")
23611 (line-beginning-position))
23612 end)))
23613 ;; Translate region boundaries for the Org buffer to the source
23614 ;; buffer.
23615 (let ((offset (- end beg)))
23616 (save-excursion
23617 (goto-char beg)
23618 (org-babel-do-in-edit-buffer
23619 (comment-or-uncomment-region (point) (+ offset (point))))))
23620 (save-restriction
23621 ;; Restrict region
23622 (narrow-to-region (save-excursion (goto-char beg)
23623 (skip-chars-forward " \r\t\n" end)
23624 (line-beginning-position))
23625 (save-excursion (goto-char end)
23626 (skip-chars-backward " \r\t\n" beg)
23627 (line-end-position)))
23628 (let ((uncommentp
23629 ;; UNCOMMENTP is non-nil when every non blank line between
23630 ;; BEG and END is a comment.
23631 (save-excursion
23632 (goto-char (point-min))
23633 (while (and (not (eobp))
23634 (let ((element (org-element-at-point)))
23635 (and (eq (org-element-type element) 'comment)
23636 (goto-char (min (point-max)
23637 (org-element-property
23638 :end element)))))))
23639 (eobp))))
23640 (if uncommentp
23641 ;; Only blank lines and comments in region: uncomment it.
23642 (save-excursion
23643 (goto-char (point-min))
23644 (while (not (eobp))
23645 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23646 (replace-match "" nil nil nil 1))
23647 (forward-line)))
23648 ;; Comment each line in region.
23649 (let ((min-indent (point-max)))
23650 ;; First find the minimum indentation across all lines.
23651 (save-excursion
23652 (goto-char (point-min))
23653 (while (and (not (eobp)) (not (zerop min-indent)))
23654 (unless (looking-at "[ \t]*$")
23655 (setq min-indent (min min-indent (current-indentation))))
23656 (forward-line)))
23657 ;; Then loop over all lines.
23658 (save-excursion
23659 (goto-char (point-min))
23660 (while (not (eobp))
23661 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23662 ;; Don't get fooled by invisible text (e.g. link path)
23663 ;; when moving to column MIN-INDENT.
23664 (let ((buffer-invisibility-spec nil))
23665 (org-move-to-column min-indent t))
23666 (insert comment-start))
23667 (forward-line)))))))))
23669 (defun org-comment-dwim (_arg)
23670 "Call `comment-dwim' within a source edit buffer if needed."
23671 (interactive "*P")
23672 (if (org-in-src-block-p)
23673 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23674 (call-interactively 'comment-dwim)))
23677 ;;; Timestamps API
23679 ;; This section contains tools to operate on timestamp objects, as
23680 ;; returned by, e.g. `org-element-context'.
23682 (defun org-timestamp--to-internal-time (timestamp &optional end)
23683 "Encode TIMESTAMP object into Emacs internal time.
23684 Use end of date range or time range when END is non-nil."
23685 (apply #'encode-time
23686 (cons 0
23687 (mapcar
23688 (lambda (prop) (or (org-element-property prop timestamp) 0))
23689 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23690 '(:minute-start :hour-start :day-start :month-start
23691 :year-start))))))
23693 (defun org-timestamp-has-time-p (timestamp)
23694 "Non-nil when TIMESTAMP has a time specified."
23695 (org-element-property :hour-start timestamp))
23697 (defun org-timestamp-format (timestamp format &optional end utc)
23698 "Format a TIMESTAMP object into a string.
23700 FORMAT is a format specifier to be passed to
23701 `format-time-string'.
23703 When optional argument END is non-nil, use end of date-range or
23704 time-range, if possible.
23706 When optional argument UTC is non-nil, time will be expressed as
23707 Universal Time."
23708 (format-time-string
23709 format (org-timestamp--to-internal-time timestamp end)
23710 (and utc t)))
23712 (defun org-timestamp-split-range (timestamp &optional end)
23713 "Extract a TIMESTAMP object from a date or time range.
23715 END, when non-nil, means extract the end of the range.
23716 Otherwise, extract its start.
23718 Return a new timestamp object."
23719 (let ((type (org-element-property :type timestamp)))
23720 (if (memq type '(active inactive diary)) timestamp
23721 (let ((split-ts (org-element-copy timestamp)))
23722 ;; Set new type.
23723 (org-element-put-property
23724 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23725 ;; Copy start properties over end properties if END is
23726 ;; non-nil. Otherwise, copy end properties over `start' ones.
23727 (let ((p-alist '((:minute-start . :minute-end)
23728 (:hour-start . :hour-end)
23729 (:day-start . :day-end)
23730 (:month-start . :month-end)
23731 (:year-start . :year-end))))
23732 (dolist (p-cell p-alist)
23733 (org-element-put-property
23734 split-ts
23735 (funcall (if end #'car #'cdr) p-cell)
23736 (org-element-property
23737 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23738 ;; Eventually refresh `:raw-value'.
23739 (org-element-put-property split-ts :raw-value nil)
23740 (org-element-put-property
23741 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23743 (defun org-timestamp-translate (timestamp &optional boundary)
23744 "Translate TIMESTAMP object to custom format.
23746 Format string is defined in `org-time-stamp-custom-formats',
23747 which see.
23749 When optional argument BOUNDARY is non-nil, it is either the
23750 symbol `start' or `end'. In this case, only translate the
23751 starting or ending part of TIMESTAMP if it is a date or time
23752 range. Otherwise, translate both parts.
23754 Return timestamp as-is if `org-display-custom-times' is nil or if
23755 it has a `diary' type."
23756 (let ((type (org-element-property :type timestamp)))
23757 (if (or (not org-display-custom-times) (eq type 'diary))
23758 (org-element-interpret-data timestamp)
23759 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23760 org-time-stamp-custom-formats)))
23761 (if (and (not boundary) (memq type '(active-range inactive-range)))
23762 (concat (org-timestamp-format timestamp fmt)
23763 "--"
23764 (org-timestamp-format timestamp fmt t))
23765 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23769 ;;; Other stuff.
23771 (defvar reftex-docstruct-symbol)
23772 (defvar org--rds)
23774 (defun org-reftex-citation ()
23775 "Use reftex-citation to insert a citation into the buffer.
23776 This looks for a line like
23778 #+BIBLIOGRAPHY: foo plain option:-d
23780 and derives from it that foo.bib is the bibliography file relevant
23781 for this document. It then installs the necessary environment for RefTeX
23782 to work in this buffer and calls `reftex-citation' to insert a citation
23783 into the buffer.
23785 Export of such citations to both LaTeX and HTML is handled by the contributed
23786 package ox-bibtex by Taru Karttunen."
23787 (interactive)
23788 (let ((reftex-docstruct-symbol 'org--rds)
23789 org--rds bib)
23790 (org-with-wide-buffer
23791 (let ((case-fold-search t)
23792 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23793 (if (not (save-excursion
23794 (or (re-search-forward re nil t)
23795 (re-search-backward re nil t))))
23796 (user-error "No bibliography defined in file")
23797 (setq bib (concat (match-string 1) ".bib")
23798 org--rds (list (list 'bib bib))))))
23799 (call-interactively 'reftex-citation)))
23801 ;;;; Functions extending outline functionality
23803 (defun org-beginning-of-line (&optional n)
23804 "Go to the beginning of the current visible line.
23806 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23807 tags on the first attempt, and only move to after the tags when
23808 the cursor is already beyond the end of the headline.
23810 With argument N not nil or 1, move forward N - 1 lines first."
23811 (interactive "^p")
23812 (let ((origin (point))
23813 (special (pcase org-special-ctrl-a/e
23814 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23815 deactivate-mark)
23816 ;; First move to a visible line.
23817 (if (bound-and-true-p visual-line-mode)
23818 (beginning-of-visual-line n)
23819 (move-beginning-of-line n)
23820 ;; `move-beginning-of-line' may leave point after invisible
23821 ;; characters if line starts with such of these (e.g., with
23822 ;; a link at column 0). Really move to the beginning of the
23823 ;; current visible line.
23824 (beginning-of-line))
23825 (cond
23826 ;; No special behavior. Point is already at the beginning of
23827 ;; a line, logical or visual.
23828 ((not special))
23829 ;; `beginning-of-visual-line' left point before logical beginning
23830 ;; of line: point is at the beginning of a visual line. Bail
23831 ;; out.
23832 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23833 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23834 ;; At a headline, special position is before the title, but
23835 ;; after any TODO keyword or priority cookie.
23836 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23837 (line-end-position)))
23838 (bol (point)))
23839 (if (eq special 'reversed)
23840 (when (and (= origin bol) (eq last-command this-command))
23841 (goto-char refpos))
23842 (when (or (> origin refpos) (= origin bol))
23843 (goto-char refpos)))))
23844 ((and (looking-at org-list-full-item-re)
23845 (memq (org-element-type (save-match-data (org-element-at-point)))
23846 '(item plain-list)))
23847 ;; Set special position at first white space character after
23848 ;; bullet, and check-box, if any.
23849 (let ((after-bullet
23850 (let ((box (match-end 3)))
23851 (cond ((not box) (match-end 1))
23852 ((eq (char-after box) ?\s) (1+ box))
23853 (t box)))))
23854 (if (eq special 'reversed)
23855 (when (and (= (point) origin) (eq last-command this-command))
23856 (goto-char after-bullet))
23857 (when (or (> origin after-bullet) (= (point) origin))
23858 (goto-char after-bullet)))))
23859 ;; No special context. Point is already at beginning of line.
23860 (t nil))))
23862 (defun org-end-of-line (&optional n)
23863 "Go to the end of the line, but before ellipsis, if any.
23865 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23866 tags on the first attempt, and only move to after the tags when
23867 the cursor is already beyond the end of the headline.
23869 With argument N not nil or 1, move forward N - 1 lines first."
23870 (interactive "^p")
23871 (let ((origin (point))
23872 (special (pcase org-special-ctrl-a/e
23873 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23874 deactivate-mark)
23875 ;; First move to a visible line.
23876 (if (bound-and-true-p visual-line-mode)
23877 (beginning-of-visual-line n)
23878 (move-beginning-of-line n))
23879 (cond
23880 ;; At a headline, with tags.
23881 ((and special
23882 (save-excursion
23883 (beginning-of-line)
23884 (let ((case-fold-search nil))
23885 (looking-at org-complex-heading-regexp)))
23886 (match-end 5))
23887 (let ((tags (save-excursion
23888 (goto-char (match-beginning 5))
23889 (skip-chars-backward " \t")
23890 (point)))
23891 (visual-end (and (bound-and-true-p visual-line-mode)
23892 (save-excursion
23893 (end-of-visual-line)
23894 (point)))))
23895 ;; If `end-of-visual-line' brings us before end of line or
23896 ;; even tags, i.e., the headline spans over multiple visual
23897 ;; lines, move there.
23898 (cond ((and visual-end
23899 (< visual-end tags)
23900 (<= origin visual-end))
23901 (goto-char visual-end))
23902 ((eq special 'reversed)
23903 (if (and (= origin (line-end-position))
23904 (eq this-command last-command))
23905 (goto-char tags)
23906 (end-of-line)))
23908 (if (or (< origin tags) (= origin (line-end-position)))
23909 (goto-char tags)
23910 (end-of-line))))))
23911 ((bound-and-true-p visual-line-mode)
23912 (let ((bol (line-beginning-position)))
23913 (end-of-visual-line)
23914 ;; If `end-of-visual-line' gets us past the ellipsis at the
23915 ;; end of a line, backtrack and use `end-of-line' instead.
23916 (when (/= bol (line-beginning-position))
23917 (goto-char bol)
23918 (end-of-line))))
23919 (t (end-of-line)))))
23921 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23922 (define-key org-mode-map "\C-e" 'org-end-of-line)
23924 (defun org-backward-sentence (&optional _arg)
23925 "Go to beginning of sentence, or beginning of table field.
23926 This will call `backward-sentence' or `org-table-beginning-of-field',
23927 depending on context."
23928 (interactive)
23929 (let* ((element (org-element-at-point))
23930 (contents-begin (org-element-property :contents-begin element))
23931 (table (org-element-lineage element '(table) t)))
23932 (if (and table
23933 (> (point) contents-begin)
23934 (<= (point) (org-element-property :contents-end table)))
23935 (call-interactively #'org-table-beginning-of-field)
23936 (save-restriction
23937 (when (and contents-begin
23938 (< (point-min) contents-begin)
23939 (> (point) contents-begin))
23940 (narrow-to-region contents-begin
23941 (org-element-property :contents-end element)))
23942 (call-interactively #'backward-sentence)))))
23944 (defun org-forward-sentence (&optional _arg)
23945 "Go to end of sentence, or end of table field.
23946 This will call `forward-sentence' or `org-table-end-of-field',
23947 depending on context."
23948 (interactive)
23949 (let* ((element (org-element-at-point))
23950 (contents-end (org-element-property :contents-end element))
23951 (table (org-element-lineage element '(table) t)))
23952 (if (and table
23953 (>= (point) (org-element-property :contents-begin table))
23954 (< (point) contents-end))
23955 (call-interactively #'org-table-end-of-field)
23956 (save-restriction
23957 (when (and contents-end
23958 (> (point-max) contents-end)
23959 ;; Skip blank lines between elements.
23960 (< (org-element-property :end element)
23961 (save-excursion (goto-char contents-end)
23962 (skip-chars-forward " \r\t\n"))))
23963 (narrow-to-region (org-element-property :contents-begin element)
23964 contents-end))
23965 (call-interactively #'forward-sentence)))))
23967 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23968 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23970 (defun org-kill-line (&optional _arg)
23971 "Kill line, to tags or end of line."
23972 (interactive)
23973 (cond
23974 ((or (not org-special-ctrl-k)
23975 (bolp)
23976 (not (org-at-heading-p)))
23977 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23978 org-ctrl-k-protect-subtree
23979 (or (eq org-ctrl-k-protect-subtree 'error)
23980 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23981 (user-error "C-k aborted as it would kill a hidden subtree"))
23982 (call-interactively
23983 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23984 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23985 (kill-region (point) (match-beginning 1))
23986 (org-set-tags nil t))
23987 (t (kill-region (point) (point-at-eol)))))
23989 (define-key org-mode-map "\C-k" 'org-kill-line)
23991 (defun org-yank (&optional arg)
23992 "Yank. If the kill is a subtree, treat it specially.
23993 This command will look at the current kill and check if is a single
23994 subtree, or a series of subtrees[1]. If it passes the test, and if the
23995 cursor is at the beginning of a line or after the stars of a currently
23996 empty headline, then the yank is handled specially. How exactly depends
23997 on the value of the following variables.
23999 `org-yank-folded-subtrees'
24000 By default, this variable is non-nil, which results in
24001 subtree(s) being folded after insertion, except if doing so
24002 would swallow text after the yanked text.
24004 `org-yank-adjusted-subtrees'
24005 When non-nil (the default value is nil), the subtree will be
24006 promoted or demoted in order to fit into the local outline tree
24007 structure, which means that the level will be adjusted so that it
24008 becomes the smaller one of the two *visible* surrounding headings.
24010 Any prefix to this command will cause `yank' to be called directly with
24011 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
24012 will just
24013 plainly yank the text as it is.
24015 \[1] The test checks if the first non-white line is a heading
24016 and if there are no other headings with fewer stars."
24017 (interactive "P")
24018 (org-yank-generic 'yank arg))
24020 (defun org-yank-generic (command arg)
24021 "Perform some yank-like command.
24023 This function implements the behavior described in the `org-yank'
24024 documentation. However, it has been generalized to work for any
24025 interactive command with similar behavior."
24027 ;; pretend to be command COMMAND
24028 (setq this-command command)
24030 (if arg
24031 (call-interactively command)
24033 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24034 (and (org-kill-is-subtree-p)
24035 (or (bolp)
24036 (and (looking-at "[ \t]*$")
24037 (string-match
24038 "\\`\\*+\\'"
24039 (buffer-substring (point-at-bol) (point)))))))
24040 swallowp)
24041 (cond
24042 ((and subtreep org-yank-folded-subtrees)
24043 (let ((beg (point))
24044 end)
24045 (if (and subtreep org-yank-adjusted-subtrees)
24046 (org-paste-subtree nil nil 'for-yank)
24047 (call-interactively command))
24049 (setq end (point))
24050 (goto-char beg)
24051 (when (and (bolp) subtreep
24052 (not (setq swallowp
24053 (org-yank-folding-would-swallow-text beg end))))
24054 (org-with-limited-levels
24055 (or (looking-at org-outline-regexp)
24056 (re-search-forward org-outline-regexp-bol end t))
24057 (while (and (< (point) end) (looking-at org-outline-regexp))
24058 (outline-hide-subtree)
24059 (org-cycle-show-empty-lines 'folded)
24060 (condition-case nil
24061 (outline-forward-same-level 1)
24062 (error (goto-char end))))))
24063 (when swallowp
24064 (message
24065 "Inserted text not folded because that would swallow text"))
24067 (goto-char end)
24068 (skip-chars-forward " \t\n\r")
24069 (beginning-of-line 1)
24070 (push-mark beg 'nomsg)))
24071 ((and subtreep org-yank-adjusted-subtrees)
24072 (let ((beg (point-at-bol)))
24073 (org-paste-subtree nil nil 'for-yank)
24074 (push-mark beg 'nomsg)))
24076 (call-interactively command))))))
24078 (defun org-yank-folding-would-swallow-text (beg end)
24079 "Would hide-subtree at BEG swallow any text after END?"
24080 (let (level)
24081 (org-with-limited-levels
24082 (save-excursion
24083 (goto-char beg)
24084 (when (or (looking-at org-outline-regexp)
24085 (re-search-forward org-outline-regexp-bol end t))
24086 (setq level (org-outline-level)))
24087 (goto-char end)
24088 (skip-chars-forward " \t\r\n\v\f")
24089 (not (or (eobp)
24090 (and (bolp) (looking-at-p org-outline-regexp)
24091 (<= (org-outline-level) level))))))))
24093 (define-key org-mode-map "\C-y" 'org-yank)
24095 (defun org-truely-invisible-p ()
24096 "Check if point is at a character currently not visible.
24097 This version does not only check the character property, but also
24098 `visible-mode'."
24099 ;; Early versions of noutline don't have `outline-invisible-p'.
24100 (unless (bound-and-true-p visible-mode)
24101 (outline-invisible-p)))
24103 (defun org-invisible-p2 ()
24104 "Check if point is at a character currently not visible."
24105 (save-excursion
24106 (when (and (eolp) (not (bobp))) (backward-char 1))
24107 ;; Early versions of noutline don't have `outline-invisible-p'.
24108 (outline-invisible-p)))
24110 (defun org-back-to-heading (&optional invisible-ok)
24111 "Call `outline-back-to-heading', but provide a better error message."
24112 (condition-case nil
24113 (outline-back-to-heading invisible-ok)
24114 (error (error "Before first headline at position %d in buffer %s"
24115 (point) (current-buffer)))))
24117 (defun org-before-first-heading-p ()
24118 "Before first heading?"
24119 (save-excursion
24120 (end-of-line)
24121 (null (re-search-backward org-outline-regexp-bol nil t))))
24123 (defun org-at-heading-p (&optional ignored)
24124 (outline-on-heading-p t))
24126 (defun org-in-commented-heading-p (&optional no-inheritance)
24127 "Non-nil if point is under a commented heading.
24128 This function also checks ancestors of the current headline,
24129 unless optional argument NO-INHERITANCE is non-nil."
24130 (cond
24131 ((org-before-first-heading-p) nil)
24132 ((let ((headline (nth 4 (org-heading-components))))
24133 (and headline
24134 (let ((case-fold-search nil))
24135 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24136 headline)))))
24137 (no-inheritance nil)
24139 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24141 (defun org-at-comment-p nil
24142 "Is cursor in a commented line?"
24143 (save-excursion
24144 (save-match-data
24145 (beginning-of-line)
24146 (looking-at "^[ \t]*# "))))
24148 (defun org-at-drawer-p nil
24149 "Is cursor at a drawer keyword?"
24150 (save-excursion
24151 (move-beginning-of-line 1)
24152 (looking-at org-drawer-regexp)))
24154 (defun org-at-block-p nil
24155 "Is cursor at a block keyword?"
24156 (save-excursion
24157 (move-beginning-of-line 1)
24158 (looking-at org-block-regexp)))
24160 (defun org-point-at-end-of-empty-headline ()
24161 "If point is at the end of an empty headline, return t, else nil.
24162 If the heading only contains a TODO keyword, it is still still considered
24163 empty."
24164 (let ((case-fold-search nil))
24165 (and (looking-at "[ \t]*$")
24166 org-todo-line-regexp
24167 (save-excursion
24168 (beginning-of-line)
24169 (looking-at org-todo-line-regexp)
24170 (string= (match-string 3) "")))))
24172 (defun org-at-heading-or-item-p ()
24173 (or (org-at-heading-p) (org-at-item-p)))
24175 (defun org-at-target-p ()
24176 (or (org-in-regexp org-radio-target-regexp)
24177 (org-in-regexp org-target-regexp)))
24178 ;; Compatibility alias with Org versions < 7.8.03
24179 (defalias 'org-on-target-p 'org-at-target-p)
24181 (defun org-up-heading-all (arg)
24182 "Move to the heading line of which the present line is a subheading.
24183 This function considers both visible and invisible heading lines.
24184 With argument, move up ARG levels."
24185 (outline-up-heading arg t))
24187 (defun org-up-heading-safe ()
24188 "Move to the heading line of which the present line is a subheading.
24189 This version will not throw an error. It will return the level of the
24190 headline found, or nil if no higher level is found.
24192 Also, this function will be a lot faster than `outline-up-heading',
24193 because it relies on stars being the outline starters. This can really
24194 make a significant difference in outlines with very many siblings."
24195 (when (ignore-errors (org-back-to-heading t))
24196 (let ((level-up (1- (funcall outline-level))))
24197 (and (> level-up 0)
24198 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24199 (funcall outline-level)))))
24201 (defun org-first-sibling-p ()
24202 "Is this heading the first child of its parents?"
24203 (interactive)
24204 (let ((re org-outline-regexp-bol)
24205 level l)
24206 (unless (org-at-heading-p t)
24207 (user-error "Not at a heading"))
24208 (setq level (funcall outline-level))
24209 (save-excursion
24210 (if (not (re-search-backward re nil t))
24212 (setq l (funcall outline-level))
24213 (< l level)))))
24215 (defun org-goto-sibling (&optional previous)
24216 "Goto the next sibling, even if it is invisible.
24217 When PREVIOUS is set, go to the previous sibling instead. Returns t
24218 when a sibling was found. When none is found, return nil and don't
24219 move point."
24220 (let ((fun (if previous 're-search-backward 're-search-forward))
24221 (pos (point))
24222 (re org-outline-regexp-bol)
24223 level l)
24224 (when (ignore-errors (org-back-to-heading t))
24225 (setq level (funcall outline-level))
24226 (catch 'exit
24227 (or previous (forward-char 1))
24228 (while (funcall fun re nil t)
24229 (setq l (funcall outline-level))
24230 (when (< l level) (goto-char pos) (throw 'exit nil))
24231 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24232 (goto-char pos)
24233 nil))))
24235 (defun org-show-siblings ()
24236 "Show all siblings of the current headline."
24237 (save-excursion
24238 (while (org-goto-sibling) (org-flag-heading nil)))
24239 (save-excursion
24240 (while (org-goto-sibling 'previous)
24241 (org-flag-heading nil))))
24243 (defun org-goto-first-child ()
24244 "Goto the first child, even if it is invisible.
24245 Return t when a child was found. Otherwise don't move point and
24246 return nil."
24247 (let (level (pos (point)) (re org-outline-regexp-bol))
24248 (when (ignore-errors (org-back-to-heading t))
24249 (setq level (outline-level))
24250 (forward-char 1)
24251 (if (and (re-search-forward re nil t) (> (outline-level) level))
24252 (progn (goto-char (match-beginning 0)) t)
24253 (goto-char pos) nil))))
24255 (defun org-show-hidden-entry ()
24256 "Show an entry where even the heading is hidden."
24257 (save-excursion
24258 (org-show-entry)))
24260 (defun org-flag-heading (flag &optional entry)
24261 "Flag the current heading. FLAG non-nil means make invisible.
24262 When ENTRY is non-nil, show the entire entry."
24263 (save-excursion
24264 (org-back-to-heading t)
24265 ;; Check if we should show the entire entry
24266 (if entry
24267 (progn
24268 (org-show-entry)
24269 (save-excursion
24270 (and (outline-next-heading)
24271 (org-flag-heading nil))))
24272 (outline-flag-region (max (point-min) (1- (point)))
24273 (save-excursion (outline-end-of-heading) (point))
24274 flag))))
24276 (defun org-get-next-sibling ()
24277 "Move to next heading of the same level, and return point.
24278 If there is no such heading, return nil.
24279 This is like outline-next-sibling, but invisible headings are ok."
24280 (let ((level (funcall outline-level)))
24281 (outline-next-heading)
24282 (while (and (not (eobp)) (> (funcall outline-level) level))
24283 (outline-next-heading))
24284 (unless (or (eobp) (< (funcall outline-level) level))
24285 (point))))
24287 (defun org-get-last-sibling ()
24288 "Move to previous heading of the same level, and return point.
24289 If there is no such heading, return nil."
24290 (let ((opoint (point))
24291 (level (funcall outline-level)))
24292 (outline-previous-heading)
24293 (when (and (/= (point) opoint) (outline-on-heading-p t))
24294 (while (and (> (funcall outline-level) level)
24295 (not (bobp)))
24296 (outline-previous-heading))
24297 (unless (< (funcall outline-level) level)
24298 (point)))))
24300 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24301 "Goto to the end of a subtree."
24302 ;; This contains an exact copy of the original function, but it uses
24303 ;; `org-back-to-heading', to make it work also in invisible
24304 ;; trees. And is uses an invisible-ok argument.
24305 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24306 ;; Furthermore, when used inside Org, finding the end of a large subtree
24307 ;; with many children and grandchildren etc, this can be much faster
24308 ;; than the outline version.
24309 (org-back-to-heading invisible-ok)
24310 (let ((first t)
24311 (level (funcall outline-level)))
24312 (if (and (derived-mode-p 'org-mode) (< level 1000))
24313 ;; A true heading (not a plain list item), in Org
24314 ;; This means we can easily find the end by looking
24315 ;; only for the right number of stars. Using a regexp to do
24316 ;; this is so much faster than using a Lisp loop.
24317 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24318 (forward-char 1)
24319 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24320 ;; something else, do it the slow way
24321 (while (and (not (eobp))
24322 (or first (> (funcall outline-level) level)))
24323 (setq first nil)
24324 (outline-next-heading)))
24325 (unless to-heading
24326 (when (memq (preceding-char) '(?\n ?\^M))
24327 ;; Go to end of line before heading
24328 (forward-char -1)
24329 (when (memq (preceding-char) '(?\n ?\^M))
24330 ;; leave blank line before heading
24331 (forward-char -1)))))
24332 (point))
24334 (defun org-end-of-meta-data (&optional full)
24335 "Skip planning line and properties drawer in current entry.
24336 When optional argument FULL is non-nil, also skip empty lines,
24337 clocking lines and regular drawers at the beginning of the
24338 entry."
24339 (org-back-to-heading t)
24340 (forward-line)
24341 (when (looking-at-p org-planning-line-re) (forward-line))
24342 (when (looking-at org-property-drawer-re)
24343 (goto-char (match-end 0))
24344 (forward-line))
24345 (when (and full (not (org-at-heading-p)))
24346 (catch 'exit
24347 (let ((end (save-excursion (outline-next-heading) (point)))
24348 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24349 (while (not (eobp))
24350 (cond ((looking-at-p org-drawer-regexp)
24351 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24352 (forward-line)
24353 (throw 'exit t)))
24354 ((looking-at-p re) (forward-line))
24355 (t (throw 'exit t))))))))
24357 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24358 "Move forward to the ARG'th subheading at same level as this one.
24359 Stop at the first and last subheadings of a superior heading.
24360 Normally this only looks at visible headings, but when INVISIBLE-OK is
24361 non-nil it will also look at invisible ones."
24362 (interactive "p")
24363 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24364 (if (and arg (< arg 0))
24365 (goto-char (point-min))
24366 (outline-next-heading))
24367 (org-at-heading-p)
24368 (let ((level (- (match-end 0) (match-beginning 0) 1))
24369 (f (if (and arg (< arg 0))
24370 're-search-backward
24371 're-search-forward))
24372 (count (if arg (abs arg) 1))
24373 (result (point)))
24374 (while (and (prog1 (> count 0)
24375 (forward-char (if (and arg (< arg 0)) -1 1)))
24376 (funcall f org-outline-regexp-bol nil 'move))
24377 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24378 (cond ((< l level) (setq count 0))
24379 ((and (= l level)
24380 (or invisible-ok
24381 (progn
24382 (goto-char (line-beginning-position))
24383 (not (outline-invisible-p)))))
24384 (setq count (1- count))
24385 (when (eq l level)
24386 (setq result (point)))))))
24387 (goto-char result))
24388 (beginning-of-line 1)))
24390 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24391 "Move backward to the ARG'th subheading at same level as this one.
24392 Stop at the first and last subheadings of a superior heading."
24393 (interactive "p")
24394 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24396 (defun org-next-visible-heading (arg)
24397 "Move to the next visible heading.
24399 This function wraps `outline-next-visible-heading' with
24400 `org-with-limited-levels' in order to skip over inline tasks and
24401 respect customization of `org-odd-levels-only'."
24402 (interactive "p")
24403 (org-with-limited-levels
24404 (outline-next-visible-heading arg)))
24406 (defun org-previous-visible-heading (arg)
24407 "Move to the previous visible heading.
24409 This function wraps `outline-previous-visible-heading' with
24410 `org-with-limited-levels' in order to skip over inline tasks and
24411 respect customization of `org-odd-levels-only'."
24412 (interactive "p")
24413 (org-with-limited-levels
24414 (outline-previous-visible-heading arg)))
24416 (defun org-next-block (arg &optional backward block-regexp)
24417 "Jump to the next block.
24419 With a prefix argument ARG, jump forward ARG many blocks.
24421 When BACKWARD is non-nil, jump to the previous block.
24423 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24424 Match data is set according to this regexp when the function
24425 returns.
24427 Return point at beginning of the opening line of found block.
24428 Throw an error if no block is found."
24429 (interactive "p")
24430 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24431 (case-fold-search t)
24432 (search-fn (if backward #'re-search-backward #'re-search-forward))
24433 (count (or arg 1))
24434 (origin (point))
24435 last-element)
24436 (if backward (beginning-of-line) (end-of-line))
24437 (while (and (> count 0) (funcall search-fn re nil t))
24438 (let ((element (save-excursion
24439 (goto-char (match-beginning 0))
24440 (save-match-data (org-element-at-point)))))
24441 (when (and (memq (org-element-type element)
24442 '(center-block comment-block dynamic-block
24443 example-block export-block quote-block
24444 special-block src-block verse-block))
24445 (<= (match-beginning 0)
24446 (org-element-property :post-affiliated element)))
24447 (setq last-element element)
24448 (cl-decf count))))
24449 (if (= count 0)
24450 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24451 (save-match-data (org-show-context)))
24452 (goto-char origin)
24453 (user-error "No %s code blocks" (if backward "previous" "further")))))
24455 (defun org-previous-block (arg &optional block-regexp)
24456 "Jump to the previous block.
24457 With a prefix argument ARG, jump backward ARG many source blocks.
24458 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24459 (interactive "p")
24460 (org-next-block arg t block-regexp))
24462 (defun org-forward-paragraph ()
24463 "Move forward to beginning of next paragraph or equivalent.
24465 The function moves point to the beginning of the next visible
24466 structural element, which can be a paragraph, a table, a list
24467 item, etc. It also provides some special moves for convenience:
24469 - On an affiliated keyword, jump to the beginning of the
24470 relative element.
24471 - On an item or a footnote definition, move to the second
24472 element inside, if any.
24473 - On a table or a property drawer, jump after it.
24474 - On a verse or source block, stop after blank lines."
24475 (interactive)
24476 (when (eobp) (user-error "Cannot move further down"))
24477 (let* ((deactivate-mark nil)
24478 (element (org-element-at-point))
24479 (type (org-element-type element))
24480 (post-affiliated (org-element-property :post-affiliated element))
24481 (contents-begin (org-element-property :contents-begin element))
24482 (contents-end (org-element-property :contents-end element))
24483 (end (let ((end (org-element-property :end element)) (parent element))
24484 (while (and (setq parent (org-element-property :parent parent))
24485 (= (org-element-property :contents-end parent) end))
24486 (setq end (org-element-property :end parent)))
24487 end)))
24488 (cond ((not element)
24489 (skip-chars-forward " \r\t\n")
24490 (or (eobp) (beginning-of-line)))
24491 ;; On affiliated keywords, move to element's beginning.
24492 ((< (point) post-affiliated)
24493 (goto-char post-affiliated))
24494 ;; At a table row, move to the end of the table. Similarly,
24495 ;; at a node property, move to the end of the property
24496 ;; drawer.
24497 ((memq type '(node-property table-row))
24498 (goto-char (org-element-property
24499 :end (org-element-property :parent element))))
24500 ((memq type '(property-drawer table)) (goto-char end))
24501 ;; Consider blank lines as separators in verse and source
24502 ;; blocks to ease editing.
24503 ((memq type '(src-block verse-block))
24504 (when (eq type 'src-block)
24505 (setq contents-end
24506 (save-excursion (goto-char end)
24507 (skip-chars-backward " \r\t\n")
24508 (line-beginning-position))))
24509 (beginning-of-line)
24510 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24511 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24512 (goto-char end)
24513 (skip-chars-forward " \r\t\n")
24514 (if (= (point) contents-end) (goto-char end)
24515 (beginning-of-line))))
24516 ;; With no contents, just skip element.
24517 ((not contents-begin) (goto-char end))
24518 ;; If contents are invisible, skip the element altogether.
24519 ((outline-invisible-p (line-end-position))
24520 (cl-case type
24521 (headline
24522 (org-with-limited-levels (outline-next-visible-heading 1)))
24523 ;; At a plain list, make sure we move to the next item
24524 ;; instead of skipping the whole list.
24525 (plain-list (forward-char)
24526 (org-forward-paragraph))
24527 (otherwise (goto-char end))))
24528 ((>= (point) contents-end) (goto-char end))
24529 ((>= (point) contents-begin)
24530 ;; This can only happen on paragraphs and plain lists.
24531 (cl-case type
24532 (paragraph (goto-char end))
24533 ;; At a plain list, try to move to second element in
24534 ;; first item, if possible.
24535 (plain-list (end-of-line)
24536 (org-forward-paragraph))))
24537 ;; When contents start on the middle of a line (e.g. in
24538 ;; items and footnote definitions), try to reach first
24539 ;; element starting after current line.
24540 ((> (line-end-position) contents-begin)
24541 (end-of-line)
24542 (org-forward-paragraph))
24543 (t (goto-char contents-begin)))))
24545 (defun org-backward-paragraph ()
24546 "Move backward to start of previous paragraph or equivalent.
24548 The function moves point to the beginning of the current
24549 structural element, which can be a paragraph, a table, a list
24550 item, etc., or to the beginning of the previous visible one if
24551 point is already there. It also provides some special moves for
24552 convenience:
24554 - On an affiliated keyword, jump to the first one.
24555 - On a table or a property drawer, move to its beginning.
24556 - On a verse or source block, stop before blank lines."
24557 (interactive)
24558 (when (bobp) (user-error "Cannot move further up"))
24559 (let* ((deactivate-mark nil)
24560 (element (org-element-at-point))
24561 (type (org-element-type element))
24562 (contents-begin (org-element-property :contents-begin element))
24563 (contents-end (org-element-property :contents-end element))
24564 (post-affiliated (org-element-property :post-affiliated element))
24565 (begin (org-element-property :begin element)))
24566 (cond
24567 ((not element) (goto-char (point-min)))
24568 ((= (point) begin)
24569 (backward-char)
24570 (org-backward-paragraph))
24571 ((<= (point) post-affiliated) (goto-char begin))
24572 ((memq type '(node-property table-row))
24573 (goto-char (org-element-property
24574 :post-affiliated (org-element-property :parent element))))
24575 ((memq type '(property-drawer table)) (goto-char begin))
24576 ((memq type '(src-block verse-block))
24577 (when (eq type 'src-block)
24578 (setq contents-begin
24579 (save-excursion (goto-char begin) (forward-line) (point))))
24580 (if (= (point) contents-begin) (goto-char post-affiliated)
24581 ;; Inside a verse block, see blank lines as paragraph
24582 ;; separators.
24583 (let ((origin (point)))
24584 (skip-chars-backward " \r\t\n" contents-begin)
24585 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24586 (skip-chars-forward " \r\t\n" origin)
24587 (if (= (point) origin) (goto-char contents-begin)
24588 (beginning-of-line))))))
24589 ((not contents-begin) (goto-char (or post-affiliated begin)))
24590 ((eq type 'paragraph)
24591 (goto-char contents-begin)
24592 ;; When at first paragraph in an item or a footnote definition,
24593 ;; move directly to beginning of line.
24594 (let ((parent-contents
24595 (org-element-property
24596 :contents-begin (org-element-property :parent element))))
24597 (when (and parent-contents (= parent-contents contents-begin))
24598 (beginning-of-line))))
24599 ;; At the end of a greater element, move to the beginning of the
24600 ;; last element within.
24601 ((>= (point) contents-end)
24602 (goto-char (1- contents-end))
24603 (org-backward-paragraph))
24604 (t (goto-char (or post-affiliated begin))))
24605 ;; Ensure we never leave point invisible.
24606 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24608 (defun org-forward-element ()
24609 "Move forward by one element.
24610 Move to the next element at the same level, when possible."
24611 (interactive)
24612 (cond ((eobp) (user-error "Cannot move further down"))
24613 ((org-with-limited-levels (org-at-heading-p))
24614 (let ((origin (point)))
24615 (goto-char (org-end-of-subtree nil t))
24616 (unless (org-with-limited-levels (org-at-heading-p))
24617 (goto-char origin)
24618 (user-error "Cannot move further down"))))
24620 (let* ((elem (org-element-at-point))
24621 (end (org-element-property :end elem))
24622 (parent (org-element-property :parent elem)))
24623 (cond ((and parent (= (org-element-property :contents-end parent) end))
24624 (goto-char (org-element-property :end parent)))
24625 ((integer-or-marker-p end) (goto-char end))
24626 (t (message "No element at point")))))))
24628 (defun org-backward-element ()
24629 "Move backward by one element.
24630 Move to the previous element at the same level, when possible."
24631 (interactive)
24632 (cond ((bobp) (user-error "Cannot move further up"))
24633 ((org-with-limited-levels (org-at-heading-p))
24634 ;; At a headline, move to the previous one, if any, or stay
24635 ;; here.
24636 (let ((origin (point)))
24637 (org-with-limited-levels (org-backward-heading-same-level 1))
24638 ;; When current headline has no sibling above, move to its
24639 ;; parent.
24640 (when (= (point) origin)
24641 (or (org-with-limited-levels (org-up-heading-safe))
24642 (progn (goto-char origin)
24643 (user-error "Cannot move further up"))))))
24645 (let* ((elem (org-element-at-point))
24646 (beg (org-element-property :begin elem)))
24647 (cond
24648 ;; Move to beginning of current element if point isn't
24649 ;; there already.
24650 ((null beg) (message "No element at point"))
24651 ((/= (point) beg) (goto-char beg))
24652 (t (goto-char beg)
24653 (skip-chars-backward " \r\t\n")
24654 (unless (bobp)
24655 (let ((prev (org-element-at-point)))
24656 (goto-char (org-element-property :begin prev))
24657 (while (and (setq prev (org-element-property :parent prev))
24658 (<= (org-element-property :end prev) beg))
24659 (goto-char (org-element-property :begin prev)))))))))))
24661 (defun org-up-element ()
24662 "Move to upper element."
24663 (interactive)
24664 (if (org-with-limited-levels (org-at-heading-p))
24665 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24666 (let* ((elem (org-element-at-point))
24667 (parent (org-element-property :parent elem)))
24668 (if parent (goto-char (org-element-property :begin parent))
24669 (if (org-with-limited-levels (org-before-first-heading-p))
24670 (user-error "No surrounding element")
24671 (org-with-limited-levels (org-back-to-heading)))))))
24673 (defvar org-element-greater-elements)
24674 (defun org-down-element ()
24675 "Move to inner element."
24676 (interactive)
24677 (let ((element (org-element-at-point)))
24678 (cond
24679 ((memq (org-element-type element) '(plain-list table))
24680 (goto-char (org-element-property :contents-begin element))
24681 (forward-char))
24682 ((memq (org-element-type element) org-element-greater-elements)
24683 ;; If contents are hidden, first disclose them.
24684 (when (outline-invisible-p (line-end-position)) (org-cycle))
24685 (goto-char (or (org-element-property :contents-begin element)
24686 (user-error "No content for this element"))))
24687 (t (user-error "No inner element")))))
24689 (defun org-drag-element-backward ()
24690 "Move backward element at point."
24691 (interactive)
24692 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24693 (let* ((elem (or (org-element-at-point)
24694 (user-error "No element at point")))
24695 (prev-elem
24696 (save-excursion
24697 (goto-char (org-element-property :begin elem))
24698 (skip-chars-backward " \r\t\n")
24699 (unless (bobp)
24700 (let* ((beg (org-element-property :begin elem))
24701 (prev (org-element-at-point))
24702 (up prev))
24703 (while (and (setq up (org-element-property :parent up))
24704 (<= (org-element-property :end up) beg))
24705 (setq prev up))
24706 prev)))))
24707 ;; Error out if no previous element or previous element is
24708 ;; a parent of the current one.
24709 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24710 (user-error "Cannot drag element backward")
24711 (let ((pos (point)))
24712 (org-element-swap-A-B prev-elem elem)
24713 (goto-char (+ (org-element-property :begin prev-elem)
24714 (- pos (org-element-property :begin elem)))))))))
24716 (defun org-drag-element-forward ()
24717 "Move forward element at point."
24718 (interactive)
24719 (let* ((pos (point))
24720 (elem (or (org-element-at-point)
24721 (user-error "No element at point"))))
24722 (when (= (point-max) (org-element-property :end elem))
24723 (user-error "Cannot drag element forward"))
24724 (goto-char (org-element-property :end elem))
24725 (let ((next-elem (org-element-at-point)))
24726 (when (or (org-element-nested-p elem next-elem)
24727 (and (eq (org-element-type next-elem) 'headline)
24728 (not (eq (org-element-type elem) 'headline))))
24729 (goto-char pos)
24730 (user-error "Cannot drag element forward"))
24731 ;; Compute new position of point: it's shifted by NEXT-ELEM
24732 ;; body's length (without final blanks) and by the length of
24733 ;; blanks between ELEM and NEXT-ELEM.
24734 (let ((size-next (- (save-excursion
24735 (goto-char (org-element-property :end next-elem))
24736 (skip-chars-backward " \r\t\n")
24737 (forward-line)
24738 ;; Small correction if buffer doesn't end
24739 ;; with a newline character.
24740 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24741 (org-element-property :begin next-elem)))
24742 (size-blank (- (org-element-property :end elem)
24743 (save-excursion
24744 (goto-char (org-element-property :end elem))
24745 (skip-chars-backward " \r\t\n")
24746 (forward-line)
24747 (point)))))
24748 (org-element-swap-A-B elem next-elem)
24749 (goto-char (+ pos size-next size-blank))))))
24751 (defun org-drag-line-forward (arg)
24752 "Drag the line at point ARG lines forward."
24753 (interactive "p")
24754 (dotimes (_ (abs arg))
24755 (let ((c (current-column)))
24756 (if (< 0 arg)
24757 (progn
24758 (beginning-of-line 2)
24759 (transpose-lines 1)
24760 (beginning-of-line 0))
24761 (transpose-lines 1)
24762 (beginning-of-line -1))
24763 (org-move-to-column c))))
24765 (defun org-drag-line-backward (arg)
24766 "Drag the line at point ARG lines backward."
24767 (interactive "p")
24768 (org-drag-line-forward (- arg)))
24770 (defun org-mark-element ()
24771 "Put point at beginning of this element, mark at end.
24773 Interactively, if this command is repeated or (in Transient Mark
24774 mode) if the mark is active, it marks the next element after the
24775 ones already marked."
24776 (interactive)
24777 (let (deactivate-mark)
24778 (if (and (called-interactively-p 'any)
24779 (or (and (eq last-command this-command) (mark t))
24780 (and transient-mark-mode mark-active)))
24781 (set-mark
24782 (save-excursion
24783 (goto-char (mark))
24784 (goto-char (org-element-property :end (org-element-at-point)))))
24785 (let ((element (org-element-at-point)))
24786 (end-of-line)
24787 (push-mark (org-element-property :end element) t t)
24788 (goto-char (org-element-property :begin element))))))
24790 (defun org-narrow-to-element ()
24791 "Narrow buffer to current element."
24792 (interactive)
24793 (let ((elem (org-element-at-point)))
24794 (cond
24795 ((eq (car elem) 'headline)
24796 (narrow-to-region
24797 (org-element-property :begin elem)
24798 (org-element-property :end elem)))
24799 ((memq (car elem) org-element-greater-elements)
24800 (narrow-to-region
24801 (org-element-property :contents-begin elem)
24802 (org-element-property :contents-end elem)))
24804 (narrow-to-region
24805 (org-element-property :begin elem)
24806 (org-element-property :end elem))))))
24808 (defun org-transpose-element ()
24809 "Transpose current and previous elements, keeping blank lines between.
24810 Point is moved after both elements."
24811 (interactive)
24812 (org-skip-whitespace)
24813 (let ((end (org-element-property :end (org-element-at-point))))
24814 (org-drag-element-backward)
24815 (goto-char end)))
24817 (defun org-unindent-buffer ()
24818 "Un-indent the visible part of the buffer.
24819 Relative indentation (between items, inside blocks, etc.) isn't
24820 modified."
24821 (interactive)
24822 (unless (eq major-mode 'org-mode)
24823 (user-error "Cannot un-indent a buffer not in Org mode"))
24824 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24825 (unindent-tree
24826 (lambda (contents)
24827 (dolist (element (reverse contents))
24828 (if (memq (org-element-type element) '(headline section))
24829 (funcall unindent-tree (org-element-contents element))
24830 (save-excursion
24831 (save-restriction
24832 (narrow-to-region
24833 (org-element-property :begin element)
24834 (org-element-property :end element))
24835 (org-do-remove-indentation))))))))
24836 (funcall unindent-tree (org-element-contents parse-tree))))
24838 (defun org-show-children (&optional level)
24839 "Show all direct subheadings of this heading.
24840 Prefix arg LEVEL is how many levels below the current level
24841 should be shown. Default is enough to cause the following
24842 heading to appear."
24843 (interactive "p")
24844 ;; If `orgstruct-mode' is active, use the slower version.
24845 (if orgstruct-mode (call-interactively #'outline-show-children)
24846 (save-excursion
24847 (org-back-to-heading t)
24848 (let* ((current-level (funcall outline-level))
24849 (max-level (org-get-valid-level
24850 current-level
24851 (if level (prefix-numeric-value level) 1)))
24852 (end (save-excursion (org-end-of-subtree t t)))
24853 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24854 (past-first-child nil)
24855 ;; Make sure to skip inlinetasks.
24856 (re (format regexp-fmt
24857 current-level
24858 (cond
24859 ((not (featurep 'org-inlinetask)) "")
24860 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24862 (t (1- org-inlinetask-min-level))))))
24863 ;; Display parent heading.
24864 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24865 (forward-line)
24866 ;; Display children. First child may be deeper than expected
24867 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24868 ;; MAX-LEVEL accordingly.
24869 (while (re-search-forward re end t)
24870 (unless past-first-child
24871 (setq re (format regexp-fmt
24872 current-level
24873 (max (funcall outline-level) max-level)))
24874 (setq past-first-child t))
24875 (outline-flag-region
24876 (line-end-position 0) (line-end-position) nil))))))
24878 (defun org-show-subtree ()
24879 "Show everything after this heading at deeper levels."
24880 (interactive)
24881 (outline-flag-region
24882 (point)
24883 (save-excursion
24884 (org-end-of-subtree t t))
24885 nil))
24887 (defun org-show-entry ()
24888 "Show the body directly following this heading.
24889 Show the heading too, if it is currently invisible."
24890 (interactive)
24891 (save-excursion
24892 (ignore-errors
24893 (org-back-to-heading t)
24894 (outline-flag-region
24895 (max (point-min) (1- (point)))
24896 (save-excursion
24897 (if (re-search-forward
24898 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24899 (match-beginning 1)
24900 (point-max)))
24901 nil)
24902 (org-cycle-hide-drawers 'children))))
24904 (defun org-make-options-regexp (kwds &optional extra)
24905 "Make a regular expression for keyword lines.
24906 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24907 when non-nil, is a regexp matching keywords names."
24908 (concat "^[ \t]*#\\+\\("
24909 (regexp-opt kwds)
24910 (and extra (concat (and kwds "\\|") extra))
24911 "\\):[ \t]*\\(.*\\)"))
24913 ;;;; Integration with and fixes for other packages
24915 ;;; Imenu support
24917 (defvar-local org-imenu-markers nil
24918 "All markers currently used by Imenu.")
24920 (defun org-imenu-new-marker (&optional pos)
24921 "Return a new marker for use by Imenu, and remember the marker."
24922 (let ((m (make-marker)))
24923 (move-marker m (or pos (point)))
24924 (push m org-imenu-markers)
24927 (defun org-imenu-get-tree ()
24928 "Produce the index for Imenu."
24929 (dolist (x org-imenu-markers) (move-marker x nil))
24930 (setq org-imenu-markers nil)
24931 (let* ((case-fold-search nil)
24932 (n org-imenu-depth)
24933 (re (concat "^" (org-get-limited-outline-regexp)))
24934 (subs (make-vector (1+ n) nil))
24935 (last-level 0)
24936 m level head0 head)
24937 (org-with-wide-buffer
24938 (goto-char (point-max))
24939 (while (re-search-backward re nil t)
24940 (setq level (org-reduced-level (funcall outline-level)))
24941 (when (and (<= level n)
24942 (looking-at org-complex-heading-regexp)
24943 (setq head0 (match-string-no-properties 4)))
24944 (setq head (org-link-display-format head0)
24945 m (org-imenu-new-marker))
24946 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24947 (if (>= level last-level)
24948 (push (cons head m) (aref subs level))
24949 (push (cons head (aref subs (1+ level))) (aref subs level))
24950 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24951 (setq last-level level))))
24952 (aref subs 1)))
24954 (eval-after-load "imenu"
24955 '(progn
24956 (add-hook 'imenu-after-jump-hook
24957 (lambda ()
24958 (when (derived-mode-p 'org-mode)
24959 (org-show-context 'org-goto))))))
24961 (defun org-link-display-format (s)
24962 "Replace links in string S with their description.
24963 If there is no description, use the link target."
24964 (save-match-data
24965 (replace-regexp-in-string
24966 org-bracket-link-analytic-regexp
24967 (lambda (m)
24968 (if (match-end 5) (match-string 5 m)
24969 (concat (match-string 1 m) (match-string 3 m))))
24970 s nil t)))
24972 (defun org-toggle-link-display ()
24973 "Toggle the literal or descriptive display of links."
24974 (interactive)
24975 (if org-descriptive-links
24976 (progn (org-remove-from-invisibility-spec '(org-link))
24977 (org-restart-font-lock)
24978 (setq org-descriptive-links nil))
24979 (progn (add-to-invisibility-spec '(org-link))
24980 (org-restart-font-lock)
24981 (setq org-descriptive-links t))))
24983 ;; Speedbar support
24985 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24986 "Overlay marking the agenda restriction line in speedbar.")
24987 (overlay-put org-speedbar-restriction-lock-overlay
24988 'face 'org-agenda-restriction-lock)
24989 (overlay-put org-speedbar-restriction-lock-overlay
24990 'help-echo "Agendas are currently limited to this item.")
24991 (delete-overlay org-speedbar-restriction-lock-overlay)
24993 (defun org-speedbar-set-agenda-restriction ()
24994 "Restrict future agenda commands to the location at point in speedbar.
24995 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24996 (interactive)
24997 (require 'org-agenda)
24998 (let (p m tp np dir txt)
24999 (cond
25000 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25001 'org-imenu t))
25002 (setq m (get-text-property p 'org-imenu-marker))
25003 (with-current-buffer (marker-buffer m)
25004 (goto-char m)
25005 (org-agenda-set-restriction-lock 'subtree)))
25006 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25007 'speedbar-function 'speedbar-find-file))
25008 (setq tp (previous-single-property-change
25009 (1+ p) 'speedbar-function)
25010 np (next-single-property-change
25011 tp 'speedbar-function)
25012 dir (speedbar-line-directory)
25013 txt (buffer-substring-no-properties (or tp (point-min))
25014 (or np (point-max))))
25015 (with-current-buffer (find-file-noselect
25016 (let ((default-directory dir))
25017 (expand-file-name txt)))
25018 (unless (derived-mode-p 'org-mode)
25019 (user-error "Cannot restrict to non-Org mode file"))
25020 (org-agenda-set-restriction-lock 'file)))
25021 (t (user-error "Don't know how to restrict Org mode agenda")))
25022 (move-overlay org-speedbar-restriction-lock-overlay
25023 (point-at-bol) (point-at-eol))
25024 (setq current-prefix-arg nil)
25025 (org-agenda-maybe-redo)))
25027 (defvar speedbar-file-key-map)
25028 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25029 (eval-after-load "speedbar"
25030 '(progn
25031 (speedbar-add-supported-extension ".org")
25032 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25033 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25034 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25035 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25036 (add-hook 'speedbar-visiting-tag-hook
25037 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25039 ;;; Fixes and Hacks for problems with other packages
25041 (defun org--flyspell-object-check-p (element)
25042 "Non-nil when Flyspell can check object at point.
25043 ELEMENT is the element at point."
25044 (let ((object (save-excursion
25045 (when (looking-at-p "\\>") (backward-char))
25046 (org-element-context element))))
25047 (cl-case (org-element-type object)
25048 ;; Prevent checks in links due to keybinding conflict with
25049 ;; Flyspell.
25050 ((code entity export-snippet inline-babel-call
25051 inline-src-block line-break latex-fragment link macro
25052 statistics-cookie target timestamp verbatim)
25053 nil)
25054 (footnote-reference
25055 ;; Only in inline footnotes, within the definition.
25056 (and (eq (org-element-property :type object) 'inline)
25057 (< (save-excursion
25058 (goto-char (org-element-property :begin object))
25059 (search-forward ":" nil t 2))
25060 (point))))
25061 (otherwise t))))
25063 (defun org-mode-flyspell-verify ()
25064 "Function used for `flyspell-generic-check-word-predicate'."
25065 (if (org-at-heading-p)
25066 ;; At a headline or an inlinetask, check title only. This is
25067 ;; faster than relying on `org-element-at-point'.
25068 (and (save-excursion (beginning-of-line)
25069 (and (let ((case-fold-search t))
25070 (not (looking-at-p "\\*+ END[ \t]*$")))
25071 (let ((case-fold-search nil))
25072 (looking-at org-complex-heading-regexp))))
25073 (match-beginning 4)
25074 (>= (point) (match-beginning 4))
25075 (or (not (match-beginning 5))
25076 (< (point) (match-beginning 5))))
25077 (let* ((element (org-element-at-point))
25078 (post-affiliated (org-element-property :post-affiliated element)))
25079 (cond
25080 ;; Ignore checks in all affiliated keywords but captions.
25081 ((< (point) post-affiliated)
25082 (and (save-excursion
25083 (beginning-of-line)
25084 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25085 (> (point) (match-end 0))
25086 (org--flyspell-object-check-p element)))
25087 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25088 ((let ((log (org-log-into-drawer)))
25089 (and log
25090 (let ((drawer (org-element-lineage element '(drawer))))
25091 (and drawer
25092 (eq (compare-strings
25093 log nil nil
25094 (org-element-property :drawer-name drawer) nil nil t)
25095 t)))))
25096 nil)
25098 (cl-case (org-element-type element)
25099 ((comment quote-section) t)
25100 (comment-block
25101 ;; Allow checks between block markers, not on them.
25102 (and (> (line-beginning-position) post-affiliated)
25103 (save-excursion
25104 (end-of-line)
25105 (skip-chars-forward " \r\t\n")
25106 (< (point) (org-element-property :end element)))))
25107 ;; Arbitrary list of keywords where checks are meaningful.
25108 ;; Make sure point is on the value part of the element.
25109 (keyword
25110 (and (member (org-element-property :key element)
25111 '("DESCRIPTION" "TITLE"))
25112 (save-excursion
25113 (search-backward ":" (line-beginning-position) t))))
25114 ;; Check is globally allowed in paragraphs verse blocks and
25115 ;; table rows (after affiliated keywords) but some objects
25116 ;; must not be affected.
25117 ((paragraph table-row verse-block)
25118 (let ((cbeg (org-element-property :contents-begin element))
25119 (cend (org-element-property :contents-end element)))
25120 (and cbeg (>= (point) cbeg) (< (point) cend)
25121 (org--flyspell-object-check-p element))))))))))
25122 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25124 (defun org-remove-flyspell-overlays-in (beg end)
25125 "Remove flyspell overlays in region."
25126 (and (bound-and-true-p flyspell-mode)
25127 (fboundp 'flyspell-delete-region-overlays)
25128 (flyspell-delete-region-overlays beg end)))
25130 (defvar flyspell-delayed-commands)
25131 (eval-after-load "flyspell"
25132 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25134 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25135 (eval-after-load "bookmark"
25136 '(if (boundp 'bookmark-after-jump-hook)
25137 ;; We can use the hook
25138 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25139 ;; Hook not available, use advice
25140 (defadvice bookmark-jump (after org-make-visible activate)
25141 "Make the position visible."
25142 (org-bookmark-jump-unhide))))
25144 ;; Make sure saveplace shows the location if it was hidden
25145 (eval-after-load "saveplace"
25146 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25147 "Make the position visible."
25148 (org-bookmark-jump-unhide)))
25150 ;; Make sure ecb shows the location if it was hidden
25151 (eval-after-load "ecb"
25152 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25153 "Make hierarchy visible when jumping into location from ECB tree buffer."
25154 (when (derived-mode-p 'org-mode)
25155 (org-show-context))))
25157 (defun org-bookmark-jump-unhide ()
25158 "Unhide the current position, to show the bookmark location."
25159 (and (derived-mode-p 'org-mode)
25160 (or (outline-invisible-p)
25161 (save-excursion (goto-char (max (point-min) (1- (point))))
25162 (outline-invisible-p)))
25163 (org-show-context 'bookmark-jump)))
25165 (defun org-mark-jump-unhide ()
25166 "Make the point visible with `org-show-context' after jumping to the mark."
25167 (when (and (derived-mode-p 'org-mode)
25168 (outline-invisible-p))
25169 (org-show-context 'mark-goto)))
25171 (eval-after-load "simple"
25172 '(defadvice pop-to-mark-command (after org-make-visible activate)
25173 "Make the point visible with `org-show-context'."
25174 (org-mark-jump-unhide)))
25176 (eval-after-load "simple"
25177 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25178 "Make the point visible with `org-show-context'."
25179 (org-mark-jump-unhide)))
25181 (eval-after-load "simple"
25182 '(defadvice pop-global-mark (after org-make-visible activate)
25183 "Make the point visible with `org-show-context'."
25184 (org-mark-jump-unhide)))
25186 ;; Make session.el ignore our circular variable
25187 (defvar session-globals-exclude)
25188 (eval-after-load "session"
25189 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25191 ;;;; Finish up
25193 (provide 'org)
25195 (run-hooks 'org-load-hook)
25197 ;;; org.el ends here