Fix docstrings
[org-mode/org-tableheadings.git] / lisp / org.el
blob3c72a4a903dbc596111a26297fa4920c0cf296c5
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.
926 This can also be configured on a per-file basis by adding one of
927 the following lines anywhere in the buffer:
929 #+STARTUP: fold (or `overview', this is equivalent)
930 #+STARTUP: nofold (or `showall', this is equivalent)
931 #+STARTUP: content
932 #+STARTUP: showeverything
934 By default, this option is ignored when Org opens agenda files
935 for the first time. If you want the agenda to honor the startup
936 option, set `org-agenda-inhibit-startup' to nil."
937 :group 'org-startup
938 :type '(choice
939 (const :tag "nofold: show all" nil)
940 (const :tag "fold: overview" t)
941 (const :tag "content: all headlines" content)
942 (const :tag "show everything, even drawers" showeverything)))
944 (defcustom org-startup-truncated t
945 "Non-nil means entering Org mode will set `truncate-lines'.
946 This is useful since some lines containing links can be very long and
947 uninteresting. Also tables look terrible when wrapped.
949 The variable `org-startup-truncated' allows to configure
950 truncation for Org mode different to the other modes that use the
951 variable `truncate-lines' and as a shortcut instead of putting
952 the variable `truncate-lines' into the `org-mode-hook'. If one
953 wants to configure truncation for Org mode not statically but
954 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
955 the variable `truncate-lines' has to be used because in such a
956 case it is too late to set the variable `org-startup-truncated'."
957 :group 'org-startup
958 :type 'boolean)
960 (defcustom org-startup-indented nil
961 "Non-nil means turn on `org-indent-mode' on startup.
962 This can also be configured on a per-file basis by adding one of
963 the following lines anywhere in the buffer:
965 #+STARTUP: indent
966 #+STARTUP: noindent"
967 :group 'org-structure
968 :type '(choice
969 (const :tag "Not" nil)
970 (const :tag "Globally (slow on startup in large files)" t)))
972 (defcustom org-use-sub-superscripts t
973 "Non-nil means interpret \"_\" and \"^\" for display.
975 If you want to control how Org exports those characters, see
976 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
977 used to be an alias for `org-export-with-sub-superscripts' in
978 Org <8.0, it is not anymore.
980 When this option is turned on, you can use TeX-like syntax for
981 sub- and superscripts within the buffer. Several characters after
982 \"_\" or \"^\" will be considered as a single item - so grouping
983 with {} is normally not needed. For example, the following things
984 will be parsed as single sub- or superscripts:
986 10^24 or 10^tau several digits will be considered 1 item.
987 10^-12 or 10^-tau a leading sign with digits or a word
988 x^2-y^3 will be read as x^2 - y^3, because items are
989 terminated by almost any nonword/nondigit char.
990 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
992 Still, ambiguity is possible. So when in doubt, use {} to enclose
993 the sub/superscript. If you set this variable to the symbol `{}',
994 the braces are *required* in order to trigger interpretations as
995 sub/superscript. This can be helpful in documents that need \"_\"
996 frequently in plain text."
997 :group 'org-startup
998 :version "24.4"
999 :package-version '(Org . "8.0")
1000 :type '(choice
1001 (const :tag "Always interpret" t)
1002 (const :tag "Only with braces" {})
1003 (const :tag "Never interpret" nil)))
1005 (defcustom org-startup-with-beamer-mode nil
1006 "Non-nil means turn on `org-beamer-mode' on startup.
1007 This can also be configured on a per-file basis by adding one of
1008 the following lines anywhere in the buffer:
1010 #+STARTUP: beamer"
1011 :group 'org-startup
1012 :version "24.1"
1013 :type 'boolean)
1015 (defcustom org-startup-align-all-tables nil
1016 "Non-nil means align all tables when visiting a file.
1017 This is useful when the column width in tables is forced with <N> cookies
1018 in table fields. Such tables will look correct only after the first re-align.
1019 This can also be configured on a per-file basis by adding one of
1020 the following lines anywhere in the buffer:
1021 #+STARTUP: align
1022 #+STARTUP: noalign"
1023 :group 'org-startup
1024 :type 'boolean)
1026 (defcustom org-startup-with-inline-images nil
1027 "Non-nil means show inline images when loading a new Org file.
1028 This can also be configured on a per-file basis by adding one of
1029 the following lines anywhere in the buffer:
1030 #+STARTUP: inlineimages
1031 #+STARTUP: noinlineimages"
1032 :group 'org-startup
1033 :version "24.1"
1034 :type 'boolean)
1036 (defcustom org-startup-with-latex-preview nil
1037 "Non-nil means preview LaTeX fragments when loading a new Org file.
1039 This can also be configured on a per-file basis by adding one of
1040 the following lines anywhere in the buffer:
1041 #+STARTUP: latexpreview
1042 #+STARTUP: nolatexpreview"
1043 :group 'org-startup
1044 :version "24.4"
1045 :package-version '(Org . "8.0")
1046 :type 'boolean)
1048 (defcustom org-insert-mode-line-in-empty-file nil
1049 "Non-nil means insert the first line setting Org mode in empty files.
1050 When the function `org-mode' is called interactively in an empty file, this
1051 normally means that the file name does not automatically trigger Org mode.
1052 To ensure that the file will always be in Org mode in the future, a
1053 line enforcing Org mode will be inserted into the buffer, if this option
1054 has been set."
1055 :group 'org-startup
1056 :type 'boolean)
1058 (defcustom org-replace-disputed-keys nil
1059 "Non-nil means use alternative key bindings for some keys.
1060 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1061 These keys are also used by other packages like shift-selection-mode'
1062 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1063 If you want to use Org mode together with one of these other modes,
1064 or more generally if you would like to move some Org mode commands to
1065 other keys, set this variable and configure the keys with the variable
1066 `org-disputed-keys'.
1068 This option is only relevant at load-time of Org mode, and must be set
1069 *before* org.el is loaded. Changing it requires a restart of Emacs to
1070 become effective."
1071 :group 'org-startup
1072 :type 'boolean)
1074 (defcustom org-use-extra-keys nil
1075 "Non-nil means use extra key sequence definitions for certain commands.
1076 This happens automatically if `window-system' is nil. This
1077 variable lets you do the same manually. You must set it before
1078 loading Org."
1079 :group 'org-startup
1080 :type 'boolean)
1082 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1084 (defcustom org-disputed-keys
1085 '(([(shift up)] . [(meta p)])
1086 ([(shift down)] . [(meta n)])
1087 ([(shift left)] . [(meta -)])
1088 ([(shift right)] . [(meta +)])
1089 ([(control shift right)] . [(meta shift +)])
1090 ([(control shift left)] . [(meta shift -)]))
1091 "Keys for which Org mode and other modes compete.
1092 This is an alist, cars are the default keys, second element specifies
1093 the alternative to use when `org-replace-disputed-keys' is t.
1095 Keys can be specified in any syntax supported by `define-key'.
1096 The value of this option takes effect only at Org mode startup,
1097 therefore you'll have to restart Emacs to apply it after changing."
1098 :group 'org-startup
1099 :type 'alist)
1101 (defun org-key (key)
1102 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1103 Or return the original if not disputed."
1104 (when org-replace-disputed-keys
1105 (let* ((nkey (key-description key))
1106 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1107 org-disputed-keys)))
1108 (setq key (if x (cdr x) key))))
1109 key)
1111 (defun org-defkey (keymap key def)
1112 "Define a key, possibly translated, as returned by `org-key'."
1113 (define-key keymap (org-key key) def))
1115 (defcustom org-ellipsis nil
1116 "The ellipsis to use in the Org mode outline.
1118 When nil, just use the standard three dots.
1119 When a string, use that string instead.
1121 The change affects only Org mode (which will then use its own display table).
1122 Changing this requires executing `\\[org-mode]' in a buffer to become
1123 effective."
1124 :group 'org-startup
1125 :type '(choice (const :tag "Default" nil)
1126 (string :tag "String" :value "...#"))
1127 :safe #'string-or-null-p)
1129 (defvar org-display-table nil
1130 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1132 (defgroup org-keywords nil
1133 "Keywords in Org mode."
1134 :tag "Org Keywords"
1135 :group 'org)
1137 (defcustom org-closed-keep-when-no-todo nil
1138 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1139 :group 'org-todo
1140 :group 'org-keywords
1141 :version "24.4"
1142 :package-version '(Org . "8.0")
1143 :type 'boolean)
1145 (defgroup org-structure nil
1146 "Options concerning the general structure of Org files."
1147 :tag "Org Structure"
1148 :group 'org)
1150 (defgroup org-reveal-location nil
1151 "Options about how to make context of a location visible."
1152 :tag "Org Reveal Location"
1153 :group 'org-structure)
1155 (defcustom org-show-context-detail '((agenda . local)
1156 (bookmark-jump . lineage)
1157 (isearch . lineage)
1158 (default . ancestors))
1159 "Alist between context and visibility span when revealing a location.
1161 \\<org-mode-map>Some actions may move point into invisible
1162 locations. As a consequence, Org always expose a neighborhood
1163 around point. How much is shown depends on the initial action,
1164 or context. Valid contexts are
1166 agenda when exposing an entry from the agenda
1167 org-goto when using the command `org-goto' (`\\[org-goto]')
1168 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1169 tags-tree when constructing a sparse tree based on tags matches
1170 link-search when exposing search matches associated with a link
1171 mark-goto when exposing the jump goal of a mark
1172 bookmark-jump when exposing a bookmark location
1173 isearch when exiting from an incremental search
1174 default default for all contexts not set explicitly
1176 Allowed visibility spans are
1178 minimal show current headline; if point is not on headline,
1179 also show entry
1181 local show current headline, entry and next headline
1183 ancestors show current headline and its direct ancestors; if
1184 point is not on headline, also show entry
1186 lineage show current headline, its direct ancestors and all
1187 their children; if point is not on headline, also show
1188 entry and first child
1190 tree show current headline, its direct ancestors and all
1191 their children; if point is not on headline, also show
1192 entry and all children
1194 canonical show current headline, its direct ancestors along with
1195 their entries and children; if point is not located on
1196 the headline, also show current entry and all children
1198 As special cases, a nil or t value means show all contexts in
1199 `minimal' or `canonical' view, respectively.
1201 Some views can make displayed information very compact, but also
1202 make it harder to edit the location of the match. In such
1203 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1204 more context."
1205 :group 'org-reveal-location
1206 :version "25.2"
1207 :package-version '(Org . "9.0")
1208 :type '(choice
1209 (const :tag "Canonical" t)
1210 (const :tag "Minimal" nil)
1211 (repeat :greedy t :tag "Individual contexts"
1212 (cons
1213 (choice :tag "Context"
1214 (const agenda)
1215 (const org-goto)
1216 (const occur-tree)
1217 (const tags-tree)
1218 (const link-search)
1219 (const mark-goto)
1220 (const bookmark-jump)
1221 (const isearch)
1222 (const default))
1223 (choice :tag "Detail level"
1224 (const minimal)
1225 (const local)
1226 (const ancestors)
1227 (const lineage)
1228 (const tree)
1229 (const canonical))))))
1231 (defcustom org-indirect-buffer-display 'other-window
1232 "How should indirect tree buffers be displayed?
1234 This applies to indirect buffers created with the commands
1235 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1237 Valid values are:
1238 current-window Display in the current window
1239 other-window Just display in another window.
1240 dedicated-frame Create one new frame, and re-use it each time.
1241 new-frame Make a new frame each time. Note that in this case
1242 previously-made indirect buffers are kept, and you need to
1243 kill these buffers yourself."
1244 :group 'org-structure
1245 :group 'org-agenda-windows
1246 :type '(choice
1247 (const :tag "In current window" current-window)
1248 (const :tag "In current frame, other window" other-window)
1249 (const :tag "Each time a new frame" new-frame)
1250 (const :tag "One dedicated frame" dedicated-frame)))
1252 (defcustom org-use-speed-commands nil
1253 "Non-nil means activate single letter commands at beginning of a headline.
1254 This may also be a function to test for appropriate locations where speed
1255 commands should be active.
1257 For example, to activate speed commands when the point is on any
1258 star at the beginning of the headline, you can do this:
1260 (setq org-use-speed-commands
1261 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1262 :group 'org-structure
1263 :type '(choice
1264 (const :tag "Never" nil)
1265 (const :tag "At beginning of headline stars" t)
1266 (function)))
1268 (defcustom org-speed-commands-user nil
1269 "Alist of additional speed commands.
1270 This list will be checked before `org-speed-commands-default'
1271 when the variable `org-use-speed-commands' is non-nil
1272 and when the cursor is at the beginning of a headline.
1273 The car if each entry is a string with a single letter, which must
1274 be assigned to `self-insert-command' in the global map.
1275 The cdr is either a command to be called interactively, a function
1276 to be called, or a form to be evaluated.
1277 An entry that is just a list with a single string will be interpreted
1278 as a descriptive headline that will be added when listing the speed
1279 commands in the Help buffer using the `?' speed command."
1280 :group 'org-structure
1281 :type '(repeat :value ("k" . ignore)
1282 (choice :value ("k" . ignore)
1283 (list :tag "Descriptive Headline" (string :tag "Headline"))
1284 (cons :tag "Letter and Command"
1285 (string :tag "Command letter")
1286 (choice
1287 (function)
1288 (sexp))))))
1290 (defcustom org-bookmark-names-plist
1291 '(:last-capture "org-capture-last-stored"
1292 :last-refile "org-refile-last-stored"
1293 :last-capture-marker "org-capture-last-stored-marker")
1294 "Names for bookmarks automatically set by some Org commands.
1295 This can provide strings as names for a number of bookmarks Org sets
1296 automatically. The following keys are currently implemented:
1297 :last-capture
1298 :last-capture-marker
1299 :last-refile
1300 When a key does not show up in the property list, the corresponding bookmark
1301 is not set."
1302 :group 'org-structure
1303 :type 'plist)
1305 (defgroup org-cycle nil
1306 "Options concerning visibility cycling in Org mode."
1307 :tag "Org Cycle"
1308 :group 'org-structure)
1310 (defcustom org-cycle-skip-children-state-if-no-children t
1311 "Non-nil means skip CHILDREN state in entries that don't have any."
1312 :group 'org-cycle
1313 :type 'boolean)
1315 (defcustom org-cycle-max-level nil
1316 "Maximum level which should still be subject to visibility cycling.
1317 Levels higher than this will, for cycling, be treated as text, not a headline.
1318 When `org-odd-levels-only' is set, a value of N in this variable actually
1319 means 2N-1 stars as the limiting headline.
1320 When nil, cycle all levels.
1321 Note that the limiting level of cycling is also influenced by
1322 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1323 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1324 than its value."
1325 :group 'org-cycle
1326 :type '(choice
1327 (const :tag "No limit" nil)
1328 (integer :tag "Maximum level")))
1330 (defcustom org-hide-block-startup nil
1331 "Non-nil means entering Org mode will fold all blocks.
1332 This can also be set in on a per-file basis with
1334 #+STARTUP: hideblocks
1335 #+STARTUP: showblocks"
1336 :group 'org-startup
1337 :group 'org-cycle
1338 :type 'boolean)
1340 (defcustom org-cycle-global-at-bob nil
1341 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1343 This makes it possible to do global cycling without having to use `S-TAB'
1344 or `\\[universal-argument] TAB'. For this special case to work, the first \
1345 line of the buffer
1346 must not be a headline -- it may be empty or some other text.
1348 When used in this way, `org-cycle-hook' is disabled temporarily to make
1349 sure the cursor stays at the beginning of the buffer.
1351 When this option is nil, don't do anything special at the beginning of
1352 the buffer."
1353 :group 'org-cycle
1354 :type 'boolean)
1356 (defcustom org-cycle-level-after-item/entry-creation t
1357 "Non-nil means cycle entry level or item indentation in new empty entries.
1359 When the cursor is at the end of an empty headline, i.e., with only stars
1360 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1361 and then all possible ancestor states, before returning to the original state.
1362 This makes data entry extremely fast: M-RET to create a new headline,
1363 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1365 When the cursor is at the end of an empty plain list item, one TAB will
1366 make it a subitem, two or more tabs will back up to make this an item
1367 higher up in the item hierarchy."
1368 :group 'org-cycle
1369 :type 'boolean)
1371 (defcustom org-cycle-emulate-tab t
1372 "Where should `org-cycle' emulate TAB.
1373 nil Never
1374 white Only in completely white lines
1375 whitestart Only at the beginning of lines, before the first non-white char
1376 t Everywhere except in headlines
1377 exc-hl-bol Everywhere except at the start of a headline
1378 If TAB is used in a place where it does not emulate TAB, the current subtree
1379 visibility is cycled."
1380 :group 'org-cycle
1381 :type '(choice (const :tag "Never" nil)
1382 (const :tag "Only in completely white lines" white)
1383 (const :tag "Before first char in a line" whitestart)
1384 (const :tag "Everywhere except in headlines" t)
1385 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1387 (defcustom org-cycle-separator-lines 2
1388 "Number of empty lines needed to keep an empty line between collapsed trees.
1389 If you leave an empty line between the end of a subtree and the following
1390 headline, this empty line is hidden when the subtree is folded.
1391 Org mode will leave (exactly) one empty line visible if the number of
1392 empty lines is equal or larger to the number given in this variable.
1393 So the default 2 means at least 2 empty lines after the end of a subtree
1394 are needed to produce free space between a collapsed subtree and the
1395 following headline.
1397 If the number is negative, and the number of empty lines is at least -N,
1398 all empty lines are shown.
1400 Special case: when 0, never leave empty lines in collapsed view."
1401 :group 'org-cycle
1402 :type 'integer)
1403 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1405 (defcustom org-pre-cycle-hook nil
1406 "Hook that is run before visibility cycling is happening.
1407 The function(s) in this hook must accept a single argument which indicates
1408 the new state that will be set right after running this hook. The
1409 argument is a symbol. Before a global state change, it can have the values
1410 `overview', `content', or `all'. Before a local state change, it can have
1411 the values `folded', `children', or `subtree'."
1412 :group 'org-cycle
1413 :type 'hook)
1415 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1416 org-cycle-hide-drawers
1417 org-cycle-show-empty-lines
1418 org-optimize-window-after-visibility-change)
1419 "Hook that is run after `org-cycle' has changed the buffer visibility.
1420 The function(s) in this hook must accept a single argument which indicates
1421 the new state that was set by the most recent `org-cycle' command. The
1422 argument is a symbol. After a global state change, it can have the values
1423 `overview', `contents', or `all'. After a local state change, it can have
1424 the values `folded', `children', or `subtree'."
1425 :group 'org-cycle
1426 :type 'hook
1427 :version "25.2"
1428 :package-version '(Org . "8.3"))
1430 (defgroup org-edit-structure nil
1431 "Options concerning structure editing in Org mode."
1432 :tag "Org Edit Structure"
1433 :group 'org-structure)
1435 (defcustom org-odd-levels-only nil
1436 "Non-nil means skip even levels and only use odd levels for the outline.
1437 This has the effect that two stars are being added/taken away in
1438 promotion/demotion commands. It also influences how levels are
1439 handled by the exporters.
1440 Changing it requires restart of `font-lock-mode' to become effective
1441 for fontification also in regions already fontified.
1442 You may also set this on a per-file basis by adding one of the following
1443 lines to the buffer:
1445 #+STARTUP: odd
1446 #+STARTUP: oddeven"
1447 :group 'org-edit-structure
1448 :group 'org-appearance
1449 :type 'boolean)
1451 (defcustom org-adapt-indentation t
1452 "Non-nil means adapt indentation to outline node level.
1454 When this variable is set, Org assumes that you write outlines by
1455 indenting text in each node to align with the headline (after the
1456 stars). The following issues are influenced by this variable:
1458 - The indentation is increased by one space in a demotion
1459 command, and decreased by one in a promotion command. However,
1460 in the latter case, if shifting some line in the entry body
1461 would alter document structure (e.g., insert a new headline),
1462 indentation is not changed at all.
1464 - Property drawers and planning information is inserted indented
1465 when this variable is set. When nil, they will not be indented.
1467 - TAB indents a line relative to current level. The lines below
1468 a headline will be indented when this variable is set.
1470 Note that this is all about true indentation, by adding and
1471 removing space characters. See also `org-indent.el' which does
1472 level-dependent indentation in a virtual way, i.e. at display
1473 time in Emacs."
1474 :group 'org-edit-structure
1475 :type 'boolean)
1477 (defcustom org-special-ctrl-a/e nil
1478 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1480 When t, `C-a' will bring back the cursor to the beginning of the
1481 headline text, i.e. after the stars and after a possible TODO
1482 keyword. In an item, this will be the position after bullet and
1483 check-box, if any. When the cursor is already at that position,
1484 another `C-a' will bring it to the beginning of the line.
1486 `C-e' will jump to the end of the headline, ignoring the presence
1487 of tags in the headline. A second `C-e' will then jump to the
1488 true end of the line, after any tags. This also means that, when
1489 this variable is non-nil, `C-e' also will never jump beyond the
1490 end of the heading of a folded section, i.e. not after the
1491 ellipses.
1493 When set to the symbol `reversed', the first `C-a' or `C-e' works
1494 normally, going to the true line boundary first. Only a directly
1495 following, identical keypress will bring the cursor to the
1496 special positions.
1498 This may also be a cons cell where the behavior for `C-a' and
1499 `C-e' is set separately."
1500 :group 'org-edit-structure
1501 :type '(choice
1502 (const :tag "off" nil)
1503 (const :tag "on: after stars/bullet and before tags first" t)
1504 (const :tag "reversed: true line boundary first" reversed)
1505 (cons :tag "Set C-a and C-e separately"
1506 (choice :tag "Special C-a"
1507 (const :tag "off" nil)
1508 (const :tag "on: after stars/bullet first" t)
1509 (const :tag "reversed: before stars/bullet first" reversed))
1510 (choice :tag "Special C-e"
1511 (const :tag "off" nil)
1512 (const :tag "on: before tags first" t)
1513 (const :tag "reversed: after tags first" reversed)))))
1514 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1516 (defcustom org-special-ctrl-k nil
1517 "Non-nil means `C-k' will behave specially in headlines.
1518 When nil, `C-k' will call the default `kill-line' command.
1519 When t, the following will happen while the cursor is in the headline:
1521 - When the cursor is at the beginning of a headline, kill the entire
1522 line and possible the folded subtree below the line.
1523 - When in the middle of the headline text, kill the headline up to the tags.
1524 - When after the headline text, kill the tags."
1525 :group 'org-edit-structure
1526 :type 'boolean)
1528 (defcustom org-ctrl-k-protect-subtree nil
1529 "Non-nil means, do not delete a hidden subtree with C-k.
1530 When set to the symbol `error', simply throw an error when C-k is
1531 used to kill (part-of) a headline that has hidden text behind it.
1532 Any other non-nil value will result in a query to the user, if it is
1533 OK to kill that hidden subtree. When nil, kill without remorse."
1534 :group 'org-edit-structure
1535 :version "24.1"
1536 :type '(choice
1537 (const :tag "Do not protect hidden subtrees" nil)
1538 (const :tag "Protect hidden subtrees with a security query" t)
1539 (const :tag "Never kill a hidden subtree with C-k" error)))
1541 (defcustom org-special-ctrl-o t
1542 "Non-nil means, make `C-o' insert a row in tables."
1543 :group 'org-edit-structure
1544 :type 'boolean)
1546 (defcustom org-catch-invisible-edits nil
1547 "Check if in invisible region before inserting or deleting a character.
1548 Valid values are:
1550 nil Do not check, so just do invisible edits.
1551 error Throw an error and do nothing.
1552 show Make point visible, and do the requested edit.
1553 show-and-error Make point visible, then throw an error and abort the edit.
1554 smart Make point visible, and do insertion/deletion if it is
1555 adjacent to visible text and the change feels predictable.
1556 Never delete a previously invisible character or add in the
1557 middle or right after an invisible region. Basically, this
1558 allows insertion and backward-delete right before ellipses.
1559 FIXME: maybe in this case we should not even show?"
1560 :group 'org-edit-structure
1561 :version "24.1"
1562 :type '(choice
1563 (const :tag "Do not check" nil)
1564 (const :tag "Throw error when trying to edit" error)
1565 (const :tag "Unhide, but do not do the edit" show-and-error)
1566 (const :tag "Show invisible part and do the edit" show)
1567 (const :tag "Be smart and do the right thing" smart)))
1569 (defcustom org-yank-folded-subtrees t
1570 "Non-nil means when yanking subtrees, fold them.
1571 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1572 it starts with a heading and all other headings in it are either children
1573 or siblings, then fold all the subtrees. However, do this only if no
1574 text after the yank would be swallowed into a folded tree by this action."
1575 :group 'org-edit-structure
1576 :type 'boolean)
1578 (defcustom org-yank-adjusted-subtrees nil
1579 "Non-nil means when yanking subtrees, adjust the level.
1580 With this setting, `org-paste-subtree' is used to insert the subtree, see
1581 this function for details."
1582 :group 'org-edit-structure
1583 :type 'boolean)
1585 (defcustom org-M-RET-may-split-line '((default . t))
1586 "Non-nil means M-RET will split the line at the cursor position.
1587 When nil, it will go to the end of the line before making a
1588 new line.
1589 You may also set this option in a different way for different
1590 contexts. Valid contexts are:
1592 headline when creating a new headline
1593 item when creating a new item
1594 table in a table field
1595 default the value to be used for all contexts not explicitly
1596 customized"
1597 :group 'org-structure
1598 :group 'org-table
1599 :type '(choice
1600 (const :tag "Always" t)
1601 (const :tag "Never" nil)
1602 (repeat :greedy t :tag "Individual contexts"
1603 (cons
1604 (choice :tag "Context"
1605 (const headline)
1606 (const item)
1607 (const table)
1608 (const default))
1609 (boolean)))))
1612 (defcustom org-insert-heading-respect-content nil
1613 "Non-nil means insert new headings after the current subtree.
1614 \\<org-mode-map>
1615 When nil, the new heading is created directly after the current line.
1616 The commands `\\[org-insert-heading-respect-content]' and \
1617 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1618 for the duration of the command."
1619 :group 'org-structure
1620 :type 'boolean)
1622 (defcustom org-blank-before-new-entry '((heading . auto)
1623 (plain-list-item . auto))
1624 "Should `org-insert-heading' leave a blank line before new heading/item?
1625 The value is an alist, with `heading' and `plain-list-item' as CAR,
1626 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1627 which case Org will look at the surrounding headings/items and try to
1628 make an intelligent decision whether to insert a blank line or not."
1629 :group 'org-edit-structure
1630 :type '(list
1631 (cons (const heading)
1632 (choice (const :tag "Never" nil)
1633 (const :tag "Always" t)
1634 (const :tag "Auto" auto)))
1635 (cons (const plain-list-item)
1636 (choice (const :tag "Never" nil)
1637 (const :tag "Always" t)
1638 (const :tag "Auto" auto)))))
1640 (defcustom org-insert-heading-hook nil
1641 "Hook being run after inserting a new heading."
1642 :group 'org-edit-structure
1643 :type 'hook)
1645 (defcustom org-enable-fixed-width-editor t
1646 "Non-nil means lines starting with \":\" are treated as fixed-width.
1647 This currently only means they are never auto-wrapped.
1648 When nil, such lines will be treated like ordinary lines."
1649 :group 'org-edit-structure
1650 :type 'boolean)
1652 (defcustom org-goto-auto-isearch t
1653 "Non-nil means typing characters in `org-goto' starts incremental search.
1654 When nil, you can use these keybindings to navigate the buffer:
1656 q Quit the org-goto interface
1657 n Go to the next visible heading
1658 p Go to the previous visible heading
1659 f Go one heading forward on same level
1660 b Go one heading backward on same level
1661 u Go one heading up"
1662 :group 'org-edit-structure
1663 :type 'boolean)
1665 (defgroup org-sparse-trees nil
1666 "Options concerning sparse trees in Org mode."
1667 :tag "Org Sparse Trees"
1668 :group 'org-structure)
1670 (defcustom org-highlight-sparse-tree-matches t
1671 "Non-nil means highlight all matches that define a sparse tree.
1672 The highlights will automatically disappear the next time the buffer is
1673 changed by an edit command."
1674 :group 'org-sparse-trees
1675 :type 'boolean)
1677 (defcustom org-remove-highlights-with-change t
1678 "Non-nil means any change to the buffer will remove temporary highlights.
1679 \\<org-mode-map>\
1680 Such highlights are created by `org-occur' and `org-clock-display'.
1681 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1682 to get rid of the highlights.
1683 The highlights created by `org-toggle-latex-fragment' always need
1684 `\\[org-toggle-latex-fragment]' to be removed."
1685 :group 'org-sparse-trees
1686 :group 'org-time
1687 :type 'boolean)
1689 (defcustom org-occur-case-fold-search t
1690 "Non-nil means `org-occur' should be case-insensitive.
1691 If set to `smart' the search will be case-insensitive only if it
1692 doesn't specify any upper case character."
1693 :group 'org-sparse-trees
1694 :version "25.2"
1695 :type '(choice
1696 (const :tag "Case-sensitive" nil)
1697 (const :tag "Case-insensitive" t)
1698 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1700 (defcustom org-occur-hook '(org-first-headline-recenter)
1701 "Hook that is run after `org-occur' has constructed a sparse tree.
1702 This can be used to recenter the window to show as much of the structure
1703 as possible."
1704 :group 'org-sparse-trees
1705 :type 'hook)
1707 (defgroup org-imenu-and-speedbar nil
1708 "Options concerning imenu and speedbar in Org mode."
1709 :tag "Org Imenu and Speedbar"
1710 :group 'org-structure)
1712 (defcustom org-imenu-depth 2
1713 "The maximum level for Imenu access to Org headlines.
1714 This also applied for speedbar access."
1715 :group 'org-imenu-and-speedbar
1716 :type 'integer)
1718 (defgroup org-table nil
1719 "Options concerning tables in Org mode."
1720 :tag "Org Table"
1721 :group 'org)
1723 (defcustom org-enable-table-editor 'optimized
1724 "Non-nil means lines starting with \"|\" are handled by the table editor.
1725 When nil, such lines will be treated like ordinary lines.
1727 When equal to the symbol `optimized', the table editor will be optimized to
1728 do the following:
1729 - Automatic overwrite mode in front of whitespace in table fields.
1730 This makes the structure of the table stay in tact as long as the edited
1731 field does not exceed the column width.
1732 - Minimize the number of realigns. Normally, the table is aligned each time
1733 TAB or RET are pressed to move to another field. With optimization this
1734 happens only if changes to a field might have changed the column width.
1735 Optimization requires replacing the functions `self-insert-command',
1736 `delete-char', and `backward-delete-char' in Org buffers, with a
1737 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1738 good at guessing when a re-align will be necessary, but you can always
1739 force one with `\\[org-ctrl-c-ctrl-c]'.
1741 If you would like to use the optimized version in Org mode, but the
1742 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1744 This variable can be used to turn on and off the table editor during a session,
1745 but in order to toggle optimization, a restart is required.
1747 See also the variable `org-table-auto-blank-field'."
1748 :group 'org-table
1749 :type '(choice
1750 (const :tag "off" nil)
1751 (const :tag "on" t)
1752 (const :tag "on, optimized" optimized)))
1754 (defcustom org-self-insert-cluster-for-undo nil
1755 "Non-nil means cluster self-insert commands for undo when possible.
1756 If this is set, then, like in the Emacs command loop, 20 consecutive
1757 characters will be undone together.
1758 This is configurable, because there is some impact on typing performance."
1759 :group 'org-table
1760 :type 'boolean)
1762 (defcustom org-table-tab-recognizes-table.el t
1763 "Non-nil means TAB will automatically notice a table.el table.
1764 When it sees such a table, it moves point into it and - if necessary -
1765 calls `table-recognize-table'."
1766 :group 'org-table-editing
1767 :type 'boolean)
1769 (defgroup org-link nil
1770 "Options concerning links in Org mode."
1771 :tag "Org Link"
1772 :group 'org)
1774 (defvar-local org-link-abbrev-alist-local nil
1775 "Buffer-local version of `org-link-abbrev-alist', which see.
1776 The value of this is taken from the #+LINK lines.")
1778 (defcustom org-link-parameters
1779 '(("doi" :follow org--open-doi-link)
1780 ("elisp" :follow org--open-elisp-link)
1781 ("file" :complete org-file-complete-link)
1782 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1783 ("help" :follow org--open-help-link)
1784 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1785 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1786 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1787 ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
1788 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1789 ("shell" :follow org--open-shell-link))
1790 "An alist of properties that defines all the links in Org mode.
1791 The key in each association is a string of the link type.
1792 Subsequent optional elements make up a p-list of link properties.
1794 :follow - A function that takes the link path as an argument.
1796 :export - A function that takes the link path, description and
1797 export-backend as arguments.
1799 :store - A function responsible for storing the link. See the
1800 function `org-store-link-functions'.
1802 :complete - A function that inserts a link with completion. The
1803 function takes one optional prefix arg.
1805 :face - A face for the link, or a function that returns a face.
1806 The function takes one argument which is the link path. The
1807 default face is `org-link'.
1809 :mouse-face - The mouse-face. The default is `highlight'.
1811 :display - `full' will not fold the link in descriptive
1812 display. Default is `org-link'.
1814 :help-echo - A string or function that takes (window object position)
1815 as arguments and returns a string.
1817 :keymap - A keymap that is active on the link. The default is
1818 `org-mouse-map'.
1820 :htmlize-link - A function for the htmlize-link. Defaults
1821 to (list :uri \"type:path\")
1823 :activate-func - A function to run at the end of font-lock
1824 activation. The function must accept (link-start link-end path bracketp)
1825 as arguments."
1826 :group 'org-link
1827 :type '(alist :tag "Link display parameters"
1828 :value-type plist))
1830 (defun org-link-get-parameter (type key)
1831 "Get TYPE link property for KEY.
1832 TYPE is a string and KEY is a plist keyword."
1833 (plist-get
1834 (cdr (assoc type org-link-parameters))
1835 key))
1837 (defun org-link-set-parameters (type &rest parameters)
1838 "Set link TYPE properties to PARAMETERS.
1839 PARAMETERS should be :key val pairs."
1840 (let ((data (assoc type org-link-parameters)))
1841 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1842 (push (cons type parameters) org-link-parameters)
1843 (org-make-link-regexps)
1844 (org-element-update-syntax))))
1846 (defun org-link-types ()
1847 "Return a list of known link types."
1848 (mapcar #'car org-link-parameters))
1850 (defcustom org-link-abbrev-alist nil
1851 "Alist of link abbreviations.
1852 The car of each element is a string, to be replaced at the start of a link.
1853 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1854 links in Org buffers can have an optional tag after a double colon, e.g.,
1856 [[linkkey:tag][description]]
1858 The `linkkey' must be a single word, starting with a letter, followed
1859 by letters, numbers, `-' or `_'.
1861 If REPLACE is a string, the tag will simply be appended to create the link.
1862 If the string contains \"%s\", the tag will be inserted there. If the string
1863 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1864 at that point (see the function `url-hexify-string'). If the string contains
1865 the specifier \"%(my-function)\", then the custom function `my-function' will
1866 be invoked: this function takes the tag as its only argument and must return
1867 a string.
1869 REPLACE may also be a function that will be called with the tag as the
1870 only argument to create the link, which should be returned as a string.
1872 See the manual for examples."
1873 :group 'org-link
1874 :type '(repeat
1875 (cons
1876 (string :tag "Protocol")
1877 (choice
1878 (string :tag "Format")
1879 (function)))))
1881 (defcustom org-descriptive-links t
1882 "Non-nil means Org will display descriptive links.
1883 E.g. [[http://orgmode.org][Org website]] will be displayed as
1884 \"Org Website\", hiding the link itself and just displaying its
1885 description. When set to nil, Org will display the full links
1886 literally.
1888 You can interactively set the value of this variable by calling
1889 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1890 :group 'org-link
1891 :type 'boolean)
1893 (defcustom org-link-file-path-type 'adaptive
1894 "How the path name in file links should be stored.
1895 Valid values are:
1897 relative Relative to the current directory, i.e. the directory of the file
1898 into which the link is being inserted.
1899 absolute Absolute path, if possible with ~ for home directory.
1900 noabbrev Absolute path, no abbreviation of home directory.
1901 adaptive Use relative path for files in the current directory and sub-
1902 directories of it. For other files, use an absolute path."
1903 :group 'org-link
1904 :type '(choice
1905 (const relative)
1906 (const absolute)
1907 (const noabbrev)
1908 (const adaptive)))
1910 (defvaralias 'org-activate-links 'org-highlight-links)
1911 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1912 "Types of links that should be highlighted in Org files.
1914 This is a list of symbols, each one of them leading to the
1915 highlighting of a certain link type.
1917 You can still open links that are not highlighted.
1919 In principle, it does not hurt to turn on highlighting for all
1920 link types. There may be a small gain when turning off unused
1921 link types. The types are:
1923 bracket The recommended [[link][description]] or [[link]] links with hiding.
1924 angle Links in angular brackets that may contain whitespace like
1925 <bbdb:Carsten Dominik>.
1926 plain Plain links in normal text, no whitespace, like http://google.com.
1927 radio Text that is matched by a radio target, see manual for details.
1928 tag Tag settings in a headline (link to tag search).
1929 date Time stamps (link to calendar).
1930 footnote Footnote labels.
1932 If you set this variable during an Emacs session, use `org-mode-restart'
1933 in the Org buffer so that the change takes effect."
1934 :group 'org-link
1935 :group 'org-appearance
1936 :type '(set :greedy t
1937 (const :tag "Double bracket links" bracket)
1938 (const :tag "Angular bracket links" angle)
1939 (const :tag "Plain text links" plain)
1940 (const :tag "Radio target matches" radio)
1941 (const :tag "Tags" tag)
1942 (const :tag "Timestamps" date)
1943 (const :tag "Footnotes" footnote)))
1945 (defcustom org-make-link-description-function nil
1946 "Function to use for generating link descriptions from links.
1947 When nil, the link location will be used. This function must take
1948 two parameters: the first one is the link, the second one is the
1949 description generated by `org-insert-link'. The function should
1950 return the description to use."
1951 :group 'org-link
1952 :type '(choice (const nil) (function)))
1954 (defgroup org-link-store nil
1955 "Options concerning storing links in Org mode."
1956 :tag "Org Store Link"
1957 :group 'org-link)
1959 (defcustom org-url-hexify-p t
1960 "When non-nil, hexify URL when creating a link."
1961 :type 'boolean
1962 :version "24.3"
1963 :group 'org-link-store)
1965 (defcustom org-email-link-description-format "Email %c: %.30s"
1966 "Format of the description part of a link to an email or usenet message.
1967 The following %-escapes will be replaced by corresponding information:
1969 %F full \"From\" field
1970 %f name, taken from \"From\" field, address if no name
1971 %T full \"To\" field
1972 %t first name in \"To\" field, address if no name
1973 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1974 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1975 %s subject
1976 %d date
1977 %m message-id.
1979 You may use normal field width specification between the % and the letter.
1980 This is for example useful to limit the length of the subject.
1982 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1983 :group 'org-link-store
1984 :type 'string)
1986 (defcustom org-from-is-user-regexp
1987 (let (r1 r2)
1988 (when (and user-mail-address (not (string= user-mail-address "")))
1989 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1990 (when (and user-full-name (not (string= user-full-name "")))
1991 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1992 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1993 "Regexp matched against the \"From:\" header of an email or usenet message.
1994 It should match if the message is from the user him/herself."
1995 :group 'org-link-store
1996 :type 'regexp)
1998 (defcustom org-context-in-file-links t
1999 "Non-nil means file links from `org-store-link' contain context.
2000 \\<org-mode-map>
2001 A search string will be added to the file name with :: as separator
2002 and used to find the context when the link is activated by the command
2003 `org-open-at-point'. When this option is t, the entire active region
2004 will be placed in the search string of the file link. If set to a
2005 positive integer, only the first n lines of context will be stored.
2007 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2008 \\[org-store-link]')
2009 negates this setting for the duration of the command."
2010 :group 'org-link-store
2011 :type '(choice boolean integer))
2013 (defcustom org-keep-stored-link-after-insertion nil
2014 "Non-nil means keep link in list for entire session.
2015 \\<org-mode-map>
2016 The command `org-store-link' adds a link pointing to the current
2017 location to an internal list. These links accumulate during a session.
2018 The command `org-insert-link' can be used to insert links into any
2019 Org file (offering completion for all stored links).
2021 When this option is nil, every link which has been inserted once using
2022 `\\[org-insert-link]' will be removed from the list, to make completing the \
2023 unused
2024 links more efficient."
2025 :group 'org-link-store
2026 :type 'boolean)
2028 (defgroup org-link-follow nil
2029 "Options concerning following links in Org mode."
2030 :tag "Org Follow Link"
2031 :group 'org-link)
2033 (defcustom org-link-translation-function nil
2034 "Function to translate links with different syntax to Org syntax.
2035 This can be used to translate links created for example by the Planner
2036 or emacs-wiki packages to Org syntax.
2037 The function must accept two parameters, a TYPE containing the link
2038 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2039 which is everything after the link protocol. It should return a cons
2040 with possibly modified values of type and path.
2041 Org contains a function for this, so if you set this variable to
2042 `org-translate-link-from-planner', you should be able follow many
2043 links created by planner."
2044 :group 'org-link-follow
2045 :type '(choice (const nil) (function)))
2047 (defcustom org-follow-link-hook nil
2048 "Hook that is run after a link has been followed."
2049 :group 'org-link-follow
2050 :type 'hook)
2052 (defcustom org-tab-follows-link nil
2053 "Non-nil means on links TAB will follow the link.
2054 Needs to be set before org.el is loaded.
2055 This really should not be used, it does not make sense, and the
2056 implementation is bad."
2057 :group 'org-link-follow
2058 :type 'boolean)
2060 (defcustom org-return-follows-link nil
2061 "Non-nil means on links RET will follow the link.
2062 In tables, the special behavior of RET has precedence."
2063 :group 'org-link-follow
2064 :type 'boolean)
2066 (defcustom org-mouse-1-follows-link
2067 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2068 "Non-nil means mouse-1 on a link will follow the link.
2069 A longer mouse click will still set point. Needs to be set
2070 before org.el is loaded."
2071 :group 'org-link-follow
2072 :version "24.4"
2073 :package-version '(Org . "8.3")
2074 :type '(choice
2075 (const :tag "A double click follows the link" double)
2076 (const :tag "Unconditionally follow the link with mouse-1" t)
2077 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2079 (defcustom org-mark-ring-length 4
2080 "Number of different positions to be recorded in the ring.
2081 Changing this requires a restart of Emacs to work correctly."
2082 :group 'org-link-follow
2083 :type 'integer)
2085 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2086 "Non-nil means internal links in Org files must exactly match a headline.
2087 When nil, the link search tries to match a phrase with all words
2088 in the search text."
2089 :group 'org-link-follow
2090 :version "24.1"
2091 :type '(choice
2092 (const :tag "Use fuzzy text search" nil)
2093 (const :tag "Match only exact headline" t)
2094 (const :tag "Match exact headline or query to create it"
2095 query-to-create)))
2097 (defcustom org-link-frame-setup
2098 '((vm . vm-visit-folder-other-frame)
2099 (vm-imap . vm-visit-imap-folder-other-frame)
2100 (gnus . org-gnus-no-new-news)
2101 (file . find-file-other-window)
2102 (wl . wl-other-frame))
2103 "Setup the frame configuration for following links.
2104 When following a link with Emacs, it may often be useful to display
2105 this link in another window or frame. This variable can be used to
2106 set this up for the different types of links.
2107 For VM, use any of
2108 `vm-visit-folder'
2109 `vm-visit-folder-other-window'
2110 `vm-visit-folder-other-frame'
2111 For Gnus, use any of
2112 `gnus'
2113 `gnus-other-frame'
2114 `org-gnus-no-new-news'
2115 For FILE, use any of
2116 `find-file'
2117 `find-file-other-window'
2118 `find-file-other-frame'
2119 For Wanderlust use any of
2120 `wl'
2121 `wl-other-frame'
2122 For the calendar, use the variable `calendar-setup'.
2123 For BBDB, it is currently only possible to display the matches in
2124 another window."
2125 :group 'org-link-follow
2126 :type '(list
2127 (cons (const vm)
2128 (choice
2129 (const vm-visit-folder)
2130 (const vm-visit-folder-other-window)
2131 (const vm-visit-folder-other-frame)))
2132 (cons (const vm-imap)
2133 (choice
2134 (const vm-visit-imap-folder)
2135 (const vm-visit-imap-folder-other-window)
2136 (const vm-visit-imap-folder-other-frame)))
2137 (cons (const gnus)
2138 (choice
2139 (const gnus)
2140 (const gnus-other-frame)
2141 (const org-gnus-no-new-news)))
2142 (cons (const file)
2143 (choice
2144 (const find-file)
2145 (const find-file-other-window)
2146 (const find-file-other-frame)))
2147 (cons (const wl)
2148 (choice
2149 (const wl)
2150 (const wl-other-frame)))))
2152 (defcustom org-display-internal-link-with-indirect-buffer nil
2153 "Non-nil means use indirect buffer to display infile links.
2154 Activating internal links (from one location in a file to another location
2155 in the same file) normally just jumps to the location. When the link is
2156 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2157 is displayed in
2158 another window. When this option is set, the other window actually displays
2159 an indirect buffer clone of the current buffer, to avoid any visibility
2160 changes to the current buffer."
2161 :group 'org-link-follow
2162 :type 'boolean)
2164 (defcustom org-open-non-existing-files nil
2165 "Non-nil means `org-open-file' will open non-existing files.
2166 When nil, an error will be generated.
2167 This variable applies only to external applications because they
2168 might choke on non-existing files. If the link is to a file that
2169 will be opened in Emacs, the variable is ignored."
2170 :group 'org-link-follow
2171 :type 'boolean)
2173 (defcustom org-open-directory-means-index-dot-org nil
2174 "Non-nil means a link to a directory really means to index.org.
2175 When nil, following a directory link will run dired or open a finder/explorer
2176 window on that directory."
2177 :group 'org-link-follow
2178 :type 'boolean)
2180 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2181 "Non-nil means ask for confirmation before executing shell links.
2182 Shell links can be dangerous: just think about a link
2184 [[shell:rm -rf ~/*][Google Search]]
2186 This link would show up in your Org document as \"Google Search\",
2187 but really it would remove your entire home directory.
2188 Therefore we advise against setting this variable to nil.
2189 Just change it to `y-or-n-p' if you want to confirm with a
2190 single keystroke rather than having to type \"yes\"."
2191 :group 'org-link-follow
2192 :type '(choice
2193 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2194 (const :tag "with y-or-n (faster)" y-or-n-p)
2195 (const :tag "no confirmation (dangerous)" nil)))
2196 (put 'org-confirm-shell-link-function
2197 'safe-local-variable
2198 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2200 (defcustom org-confirm-shell-link-not-regexp ""
2201 "A regexp to skip confirmation for shell links."
2202 :group 'org-link-follow
2203 :version "24.1"
2204 :type 'regexp)
2206 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2207 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2208 Elisp links can be dangerous: just think about a link
2210 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2212 This link would show up in your Org document as \"Google Search\",
2213 but really it would remove your entire home directory.
2214 Therefore we advise against setting this variable to nil.
2215 Just change it to `y-or-n-p' if you want to confirm with a
2216 single keystroke rather than having to type \"yes\"."
2217 :group 'org-link-follow
2218 :type '(choice
2219 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2220 (const :tag "with y-or-n (faster)" y-or-n-p)
2221 (const :tag "no confirmation (dangerous)" nil)))
2222 (put 'org-confirm-shell-link-function
2223 'safe-local-variable
2224 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2226 (defcustom org-confirm-elisp-link-not-regexp ""
2227 "A regexp to skip confirmation for Elisp links."
2228 :group 'org-link-follow
2229 :version "24.1"
2230 :type 'regexp)
2232 (defconst org-file-apps-defaults-gnu
2233 '((remote . emacs)
2234 (system . mailcap)
2235 (t . mailcap))
2236 "Default file applications on a UNIX or GNU/Linux system.
2237 See `org-file-apps'.")
2239 (defconst org-file-apps-defaults-macosx
2240 '((remote . emacs)
2241 (system . "open %s")
2242 ("ps.gz" . "gv %s")
2243 ("eps.gz" . "gv %s")
2244 ("dvi" . "xdvi %s")
2245 ("fig" . "xfig %s")
2246 (t . "open %s"))
2247 "Default file applications on a MacOS X system.
2248 The system \"open\" is known as a default, but we use X11 applications
2249 for some files for which the OS does not have a good default.
2250 See `org-file-apps'.")
2252 (defconst org-file-apps-defaults-windowsnt
2253 (list '(remote . emacs)
2254 (cons 'system (lambda (file _path)
2255 (with-no-warnings (w32-shell-execute "open" file))))
2256 (cons t (lambda (file _path)
2257 (with-no-warnings (w32-shell-execute "open" file)))))
2258 "Default file applications on a Windows NT system.
2259 The system \"open\" is used for most files.
2260 See `org-file-apps'.")
2262 (defcustom org-file-apps
2263 '((auto-mode . emacs)
2264 ("\\.mm\\'" . default)
2265 ("\\.x?html?\\'" . default)
2266 ("\\.pdf\\'" . default))
2267 "External applications for opening `file:path' items in a document.
2268 \\<org-mode-map>\
2270 Org mode uses system defaults for different file types, but
2271 you can use this variable to set the application for a given file
2272 extension. The entries in this list are cons cells where the car identifies
2273 files and the cdr the corresponding command.
2275 Possible values for the file identifier are:
2277 \"string\" A string as a file identifier can be interpreted in different
2278 ways, depending on its contents:
2280 - Alphanumeric characters only:
2281 Match links with this file extension.
2282 Example: (\"pdf\" . \"evince %s\")
2283 to open PDFs with evince.
2285 - Regular expression: Match links where the
2286 filename matches the regexp. If you want to
2287 use groups here, use shy groups.
2289 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2290 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2291 to open *.html and *.xhtml with firefox.
2293 - Regular expression which contains (non-shy) groups:
2294 Match links where the whole link, including \"::\", and
2295 anything after that, matches the regexp.
2296 In a custom command string, %1, %2, etc. are replaced with
2297 the parts of the link that were matched by the groups.
2298 For backwards compatibility, if a command string is given
2299 that does not use any of the group matches, this case is
2300 handled identically to the second one (i.e. match against
2301 file name only).
2302 In a custom function, you can access the group matches with
2303 (match-string n link).
2305 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2306 \"evince -p %1 %s\")
2307 to open [[file:document.pdf::5]] with evince at page 5.
2309 `directory' Matches a directory
2310 `remote' Matches a remote file, accessible through tramp or efs.
2311 Remote files most likely should be visited through Emacs
2312 because external applications cannot handle such paths.
2313 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2314 so all files Emacs knows how to handle. Using this with
2315 command `emacs' will open most files in Emacs. Beware that this
2316 will also open html files inside Emacs, unless you add
2317 (\"html\" . default) to the list as well.
2318 `system' The system command to open files, like `open' on Windows
2319 and Mac OS X, and mailcap under GNU/Linux. This is the command
2320 that will be selected if you call `org-open-at-point' with a
2321 double prefix argument (`\\[universal-argument] \
2322 \\[universal-argument] \\[org-open-at-point]').
2323 t Default for files not matched by any of the other options.
2325 Possible values for the command are:
2327 `emacs' The file will be visited by the current Emacs process.
2328 `default' Use the default application for this file type, which is the
2329 association for t in the list, most likely in the system-specific
2330 part. This can be used to overrule an unwanted setting in the
2331 system-specific variable.
2332 `system' Use the system command for opening files, like \"open\".
2333 This command is specified by the entry whose car is `system'.
2334 Most likely, the system-specific version of this variable
2335 does define this command, but you can overrule/replace it
2336 here.
2337 `mailcap' Use command specified in the mailcaps.
2338 string A command to be executed by a shell; %s will be replaced
2339 by the path to the file.
2340 function A Lisp function, which will be called with two arguments:
2341 the file path and the original link string, without the
2342 \"file:\" prefix.
2344 For more examples, see the system specific constants
2345 `org-file-apps-defaults-macosx'
2346 `org-file-apps-defaults-windowsnt'
2347 `org-file-apps-defaults-gnu'."
2348 :group 'org-link-follow
2349 :type '(repeat
2350 (cons (choice :value ""
2351 (string :tag "Extension")
2352 (const :tag "System command to open files" system)
2353 (const :tag "Default for unrecognized files" t)
2354 (const :tag "Remote file" remote)
2355 (const :tag "Links to a directory" directory)
2356 (const :tag "Any files that have Emacs modes"
2357 auto-mode))
2358 (choice :value ""
2359 (const :tag "Visit with Emacs" emacs)
2360 (const :tag "Use default" default)
2361 (const :tag "Use the system command" system)
2362 (string :tag "Command")
2363 (function :tag "Function")))))
2365 (defcustom org-doi-server-url "http://dx.doi.org/"
2366 "The URL of the DOI server."
2367 :type 'string
2368 :version "24.3"
2369 :group 'org-link-follow)
2371 (defgroup org-refile nil
2372 "Options concerning refiling entries in Org mode."
2373 :tag "Org Refile"
2374 :group 'org)
2376 (defcustom org-directory "~/org"
2377 "Directory with Org files.
2378 This is just a default location to look for Org files. There is no need
2379 at all to put your files into this directory. It is used in the
2380 following situations:
2382 1. When a capture template specifies a target file that is not an
2383 absolute path. The path will then be interpreted relative to
2384 `org-directory'
2385 2. When the value of variable `org-agenda-files' is a single file, any
2386 relative paths in this file will be taken as relative to
2387 `org-directory'."
2388 :group 'org-refile
2389 :group 'org-capture
2390 :type 'directory)
2392 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2393 "Default target for storing notes.
2394 Used as a fall back file for org-capture.el, for templates that
2395 do not specify a target file."
2396 :group 'org-refile
2397 :group 'org-capture
2398 :type 'file)
2400 (defcustom org-goto-interface 'outline
2401 "The default interface to be used for `org-goto'.
2402 Allowed values are:
2403 outline The interface shows an outline of the relevant file
2404 and the correct heading is found by moving through
2405 the outline or by searching with incremental search.
2406 outline-path-completion Headlines in the current buffer are offered via
2407 completion. This is the interface also used by
2408 the refile command."
2409 :group 'org-refile
2410 :type '(choice
2411 (const :tag "Outline" outline)
2412 (const :tag "Outline-path-completion" outline-path-completion)))
2414 (defcustom org-goto-max-level 5
2415 "Maximum target level when running `org-goto' with refile interface."
2416 :group 'org-refile
2417 :type 'integer)
2419 (defcustom org-reverse-note-order nil
2420 "Non-nil means store new notes at the beginning of a file or entry.
2421 When nil, new notes will be filed to the end of a file or entry.
2422 This can also be a list with cons cells of regular expressions that
2423 are matched against file names, and values."
2424 :group 'org-capture
2425 :group 'org-refile
2426 :type '(choice
2427 (const :tag "Reverse always" t)
2428 (const :tag "Reverse never" nil)
2429 (repeat :tag "By file name regexp"
2430 (cons regexp boolean))))
2432 (defcustom org-log-refile nil
2433 "Information to record when a task is refiled.
2435 Possible values are:
2437 nil Don't add anything
2438 time Add a time stamp to the task
2439 note Prompt for a note and add it with template `org-log-note-headings'
2441 This option can also be set with on a per-file-basis with
2443 #+STARTUP: nologrefile
2444 #+STARTUP: logrefile
2445 #+STARTUP: lognoterefile
2447 You can have local logging settings for a subtree by setting the LOGGING
2448 property to one or more of these keywords.
2450 When bulk-refiling from the agenda, the value `note' is forbidden and
2451 will temporarily be changed to `time'."
2452 :group 'org-refile
2453 :group 'org-progress
2454 :version "24.1"
2455 :type '(choice
2456 (const :tag "No logging" nil)
2457 (const :tag "Record timestamp" time)
2458 (const :tag "Record timestamp with note." note)))
2460 (defcustom org-refile-targets nil
2461 "Targets for refiling entries with `\\[org-refile]'.
2462 This is a list of cons cells. Each cell contains:
2463 - a specification of the files to be considered, either a list of files,
2464 or a symbol whose function or variable value will be used to retrieve
2465 a file name or a list of file names. If you use `org-agenda-files' for
2466 that, all agenda files will be scanned for targets. Nil means consider
2467 headings in the current buffer.
2468 - A specification of how to find candidate refile targets. This may be
2469 any of:
2470 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2471 This tag has to be present in all target headlines, inheritance will
2472 not be considered.
2473 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2474 todo keyword.
2475 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2476 headlines that are refiling targets.
2477 - a cons cell (:level . N). Any headline of level N is considered a target.
2478 Note that, when `org-odd-levels-only' is set, level corresponds to
2479 order in hierarchy, not to the number of stars.
2480 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2481 Note that, when `org-odd-levels-only' is set, level corresponds to
2482 order in hierarchy, not to the number of stars.
2484 Each element of this list generates a set of possible targets.
2485 The union of these sets is presented (with completion) to
2486 the user by `org-refile'.
2488 You can set the variable `org-refile-target-verify-function' to a function
2489 to verify each headline found by the simple criteria above.
2491 When this variable is nil, all top-level headlines in the current buffer
2492 are used, equivalent to the value `((nil . (:level . 1))'."
2493 :group 'org-refile
2494 :type '(repeat
2495 (cons
2496 (choice :value org-agenda-files
2497 (const :tag "All agenda files" org-agenda-files)
2498 (const :tag "Current buffer" nil)
2499 (function) (variable) (file))
2500 (choice :tag "Identify target headline by"
2501 (cons :tag "Specific tag" (const :value :tag) (string))
2502 (cons :tag "TODO keyword" (const :value :todo) (string))
2503 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2504 (cons :tag "Level number" (const :value :level) (integer))
2505 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2507 (defcustom org-refile-target-verify-function nil
2508 "Function to verify if the headline at point should be a refile target.
2509 The function will be called without arguments, with point at the
2510 beginning of the headline. It should return t and leave point
2511 where it is if the headline is a valid target for refiling.
2513 If the target should not be selected, the function must return nil.
2514 In addition to this, it may move point to a place from where the search
2515 should be continued. For example, the function may decide that the entire
2516 subtree of the current entry should be excluded and move point to the end
2517 of the subtree."
2518 :group 'org-refile
2519 :type '(choice
2520 (const nil)
2521 (function)))
2523 (defcustom org-refile-use-cache nil
2524 "Non-nil means cache refile targets to speed up the process.
2525 \\<org-mode-map>\
2526 The cache for a particular file will be updated automatically when
2527 the buffer has been killed, or when any of the marker used for flagging
2528 refile targets no longer points at a live buffer.
2529 If you have added new entries to a buffer that might themselves be targets,
2530 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2531 if you find that easier, \
2532 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2533 \\[org-refile]'."
2534 :group 'org-refile
2535 :version "24.1"
2536 :type 'boolean)
2538 (defcustom org-refile-use-outline-path nil
2539 "Non-nil means provide refile targets as paths.
2540 So a level 3 headline will be available as level1/level2/level3.
2542 When the value is `file', also include the file name (without directory)
2543 into the path. In this case, you can also stop the completion after
2544 the file name, to get entries inserted as top level in the file.
2546 When `full-file-path', include the full file path."
2547 :group 'org-refile
2548 :type '(choice
2549 (const :tag "Not" nil)
2550 (const :tag "Yes" t)
2551 (const :tag "Start with file name" file)
2552 (const :tag "Start with full file path" full-file-path)))
2554 (defcustom org-outline-path-complete-in-steps t
2555 "Non-nil means complete the outline path in hierarchical steps.
2556 When Org uses the refile interface to select an outline path (see
2557 `org-refile-use-outline-path'), the completion of the path can be
2558 done in a single go, or it can be done in steps down the headline
2559 hierarchy. Going in steps is probably the best if you do not use
2560 a special completion package like `ido' or `icicles'. However,
2561 when using these packages, going in one step can be very fast,
2562 while still showing the whole path to the entry."
2563 :group 'org-refile
2564 :type 'boolean)
2566 (defcustom org-refile-allow-creating-parent-nodes nil
2567 "Non-nil means allow the creation of new nodes as refile targets.
2568 New nodes are then created by adding \"/new node name\" to the completion
2569 of an existing node. When the value of this variable is `confirm',
2570 new node creation must be confirmed by the user (recommended).
2571 When nil, the completion must match an existing entry.
2573 Note that, if the new heading is not seen by the criteria
2574 listed in `org-refile-targets', multiple instances of the same
2575 heading would be created by trying again to file under the new
2576 heading."
2577 :group 'org-refile
2578 :type '(choice
2579 (const :tag "Never" nil)
2580 (const :tag "Always" t)
2581 (const :tag "Prompt for confirmation" confirm)))
2583 (defcustom org-refile-active-region-within-subtree nil
2584 "Non-nil means also refile active region within a subtree.
2586 By default `org-refile' doesn't allow refiling regions if they
2587 don't contain a set of subtrees, but it might be convenient to
2588 do so sometimes: in that case, the first line of the region is
2589 converted to a headline before refiling."
2590 :group 'org-refile
2591 :version "24.1"
2592 :type 'boolean)
2594 (defgroup org-todo nil
2595 "Options concerning TODO items in Org mode."
2596 :tag "Org TODO"
2597 :group 'org)
2599 (defgroup org-progress nil
2600 "Options concerning Progress logging in Org mode."
2601 :tag "Org Progress"
2602 :group 'org-time)
2604 (defvar org-todo-interpretation-widgets
2605 '((:tag "Sequence (cycling hits every state)" sequence)
2606 (:tag "Type (cycling directly to DONE)" type))
2607 "The available interpretation symbols for customizing `org-todo-keywords'.
2608 Interested libraries should add to this list.")
2610 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2611 "List of TODO entry keyword sequences and their interpretation.
2612 \\<org-mode-map>This is a list of sequences.
2614 Each sequence starts with a symbol, either `sequence' or `type',
2615 indicating if the keywords should be interpreted as a sequence of
2616 action steps, or as different types of TODO items. The first
2617 keywords are states requiring action - these states will select a headline
2618 for inclusion into the global TODO list Org produces. If one of the
2619 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2620 signify that no further action is necessary. If \"|\" is not found,
2621 the last keyword is treated as the only DONE state of the sequence.
2623 The command `\\[org-todo]' cycles an entry through these states, and one
2624 additional state where no keyword is present. For details about this
2625 cycling, see the manual.
2627 TODO keywords and interpretation can also be set on a per-file basis with
2628 the special #+SEQ_TODO and #+TYP_TODO lines.
2630 Each keyword can optionally specify a character for fast state selection
2631 \(in combination with the variable `org-use-fast-todo-selection')
2632 and specifiers for state change logging, using the same syntax that
2633 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2634 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2635 indicates to record a time stamp each time this state is selected.
2637 Each keyword may also specify if a timestamp or a note should be
2638 recorded when entering or leaving the state, by adding additional
2639 characters in the parenthesis after the keyword. This looks like this:
2640 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2641 record only the time of the state change. With X and Y being either
2642 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2643 Y when leaving the state if and only if the *target* state does not
2644 define X. You may omit any of the fast-selection key or X or /Y,
2645 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2647 For backward compatibility, this variable may also be just a list
2648 of keywords. In this case the interpretation (sequence or type) will be
2649 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2650 :group 'org-todo
2651 :group 'org-keywords
2652 :type '(choice
2653 (repeat :tag "Old syntax, just keywords"
2654 (string :tag "Keyword"))
2655 (repeat :tag "New syntax"
2656 (cons
2657 (choice
2658 :tag "Interpretation"
2659 ;;Quick and dirty way to see
2660 ;;`org-todo-interpretations'. This takes the
2661 ;;place of item arguments
2662 :convert-widget
2663 (lambda (widget)
2664 (widget-put widget
2665 :args (mapcar
2666 (lambda (x)
2667 (widget-convert
2668 (cons 'const x)))
2669 org-todo-interpretation-widgets))
2670 widget))
2671 (repeat
2672 (string :tag "Keyword"))))))
2674 (defvar-local org-todo-keywords-1 nil
2675 "All TODO and DONE keywords active in a buffer.")
2676 (defvar org-todo-keywords-for-agenda nil)
2677 (defvar org-done-keywords-for-agenda nil)
2678 (defvar org-todo-keyword-alist-for-agenda nil)
2679 (defvar org-tag-alist-for-agenda nil
2680 "Alist of all tags from all agenda files.")
2681 (defvar org-tag-groups-alist-for-agenda nil
2682 "Alist of all groups tags from all current agenda files.")
2683 (defvar-local org-tag-groups-alist nil)
2684 (defvar org-agenda-contributing-files nil)
2685 (defvar-local org-current-tag-alist nil
2686 "Alist of all tag groups in current buffer.
2687 This variable takes into consideration `org-tag-alist',
2688 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2689 (defvar-local org-not-done-keywords nil)
2690 (defvar-local org-done-keywords nil)
2691 (defvar-local org-todo-heads nil)
2692 (defvar-local org-todo-sets nil)
2693 (defvar-local org-todo-log-states nil)
2694 (defvar-local org-todo-kwd-alist nil)
2695 (defvar-local org-todo-key-alist nil)
2696 (defvar-local org-todo-key-trigger nil)
2698 (defcustom org-todo-interpretation 'sequence
2699 "Controls how TODO keywords are interpreted.
2700 This variable is in principle obsolete and is only used for
2701 backward compatibility, if the interpretation of todo keywords is
2702 not given already in `org-todo-keywords'. See that variable for
2703 more information."
2704 :group 'org-todo
2705 :group 'org-keywords
2706 :type '(choice (const sequence)
2707 (const type)))
2709 (defcustom org-use-fast-todo-selection t
2710 "\\<org-mode-map>\
2711 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2712 This variable describes if and under what circumstances the cycling
2713 mechanism for TODO keywords will be replaced by a single-key, direct
2714 selection scheme.
2716 When nil, fast selection is never used.
2718 When the symbol `prefix', it will be used when `org-todo' is called
2719 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2720 in an Org buffer, and
2721 `\\[universal-argument] t' in an agenda buffer.
2723 When t, fast selection is used by default. In this case, the prefix
2724 argument forces cycling instead.
2726 In all cases, the special interface is only used if access keys have
2727 actually been assigned by the user, i.e. if keywords in the configuration
2728 are followed by a letter in parenthesis, like TODO(t)."
2729 :group 'org-todo
2730 :type '(choice
2731 (const :tag "Never" nil)
2732 (const :tag "By default" t)
2733 (const :tag "Only with C-u C-c C-t" prefix)))
2735 (defcustom org-provide-todo-statistics t
2736 "Non-nil means update todo statistics after insert and toggle.
2737 ALL-HEADLINES means update todo statistics by including headlines
2738 with no TODO keyword as well, counting them as not done.
2739 A list of TODO keywords means the same, but skip keywords that are
2740 not in this list.
2741 When set to a list of two lists, the first list contains keywords
2742 to consider as TODO keywords, the second list contains keywords
2743 to consider as DONE keywords.
2745 When this is set, todo statistics is updated in the parent of the
2746 current entry each time a todo state is changed."
2747 :group 'org-todo
2748 :type '(choice
2749 (const :tag "Yes, only for TODO entries" t)
2750 (const :tag "Yes, including all entries" all-headlines)
2751 (repeat :tag "Yes, for TODOs in this list"
2752 (string :tag "TODO keyword"))
2753 (list :tag "Yes, for TODOs and DONEs in these lists"
2754 (repeat (string :tag "TODO keyword"))
2755 (repeat (string :tag "DONE keyword")))
2756 (other :tag "No TODO statistics" nil)))
2758 (defcustom org-hierarchical-todo-statistics t
2759 "Non-nil means TODO statistics covers just direct children.
2760 When nil, all entries in the subtree are considered.
2761 This has only an effect if `org-provide-todo-statistics' is set.
2762 To set this to nil for only a single subtree, use a COOKIE_DATA
2763 property and include the word \"recursive\" into the value."
2764 :group 'org-todo
2765 :type 'boolean)
2767 (defcustom org-after-todo-state-change-hook nil
2768 "Hook which is run after the state of a TODO item was changed.
2769 The new state (a string with a TODO keyword, or nil) is available in the
2770 Lisp variable `org-state'."
2771 :group 'org-todo
2772 :type 'hook)
2774 (defvar org-blocker-hook nil
2775 "Hook for functions that are allowed to block a state change.
2777 Functions in this hook should not modify the buffer.
2778 Each function gets as its single argument a property list,
2779 see `org-trigger-hook' for more information about this list.
2781 If any of the functions in this hook returns nil, the state change
2782 is blocked.")
2784 (defvar org-trigger-hook nil
2785 "Hook for functions that are triggered by a state change.
2787 Each function gets as its single argument a property list with at
2788 least the following elements:
2790 (:type type-of-change :position pos-at-entry-start
2791 :from old-state :to new-state)
2793 Depending on the type, more properties may be present.
2795 This mechanism is currently implemented for:
2797 TODO state changes
2798 ------------------
2799 :type todo-state-change
2800 :from previous state (keyword as a string), or nil, or a symbol
2801 `todo' or `done', to indicate the general type of state.
2802 :to new state, like in :from")
2804 (defcustom org-enforce-todo-dependencies nil
2805 "Non-nil means undone TODO entries will block switching the parent to DONE.
2806 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2807 be blocked if any prior sibling is not yet done.
2808 Finally, if the parent is blocked because of ordered siblings of its own,
2809 the child will also be blocked."
2810 :set (lambda (var val)
2811 (set var val)
2812 (if val
2813 (add-hook 'org-blocker-hook
2814 'org-block-todo-from-children-or-siblings-or-parent)
2815 (remove-hook 'org-blocker-hook
2816 'org-block-todo-from-children-or-siblings-or-parent)))
2817 :group 'org-todo
2818 :type 'boolean)
2820 (defcustom org-enforce-todo-checkbox-dependencies nil
2821 "Non-nil means unchecked boxes will block switching the parent to DONE.
2822 When this is nil, checkboxes have no influence on switching TODO states.
2823 When non-nil, you first need to check off all check boxes before the TODO
2824 entry can be switched to DONE.
2825 This variable needs to be set before org.el is loaded, and you need to
2826 restart Emacs after a change to make the change effective. The only way
2827 to change is while Emacs is running is through the customize interface."
2828 :set (lambda (var val)
2829 (set var val)
2830 (if val
2831 (add-hook 'org-blocker-hook
2832 'org-block-todo-from-checkboxes)
2833 (remove-hook 'org-blocker-hook
2834 'org-block-todo-from-checkboxes)))
2835 :group 'org-todo
2836 :type 'boolean)
2838 (defcustom org-treat-insert-todo-heading-as-state-change nil
2839 "Non-nil means inserting a TODO heading is treated as state change.
2840 So when the command `\\[org-insert-todo-heading]' is used, state change
2841 logging will apply if appropriate. When nil, the new TODO item will
2842 be inserted directly, and no logging will take place."
2843 :group 'org-todo
2844 :type 'boolean)
2846 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2847 "Non-nil means switching TODO states with S-cursor counts as state change.
2848 This is the default behavior. However, setting this to nil allows a
2849 convenient way to select a TODO state and bypass any logging associated
2850 with that."
2851 :group 'org-todo
2852 :type 'boolean)
2854 (defcustom org-todo-state-tags-triggers nil
2855 "Tag changes that should be triggered by TODO state changes.
2856 This is a list. Each entry is
2858 (state-change (tag . flag) .......)
2860 State-change can be a string with a state, and empty string to indicate the
2861 state that has no TODO keyword, or it can be one of the symbols `todo'
2862 or `done', meaning any not-done or done state, respectively."
2863 :group 'org-todo
2864 :group 'org-tags
2865 :type '(repeat
2866 (cons (choice :tag "When changing to"
2867 (const :tag "Not-done state" todo)
2868 (const :tag "Done state" done)
2869 (string :tag "State"))
2870 (repeat
2871 (cons :tag "Tag action"
2872 (string :tag "Tag")
2873 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2875 (defcustom org-log-done nil
2876 "Information to record when a task moves to the DONE state.
2878 Possible values are:
2880 nil Don't add anything, just change the keyword
2881 time Add a time stamp to the task
2882 note Prompt for a note and add it with template `org-log-note-headings'
2884 This option can also be set with on a per-file-basis with
2886 #+STARTUP: nologdone
2887 #+STARTUP: logdone
2888 #+STARTUP: lognotedone
2890 You can have local logging settings for a subtree by setting the LOGGING
2891 property to one or more of these keywords."
2892 :group 'org-todo
2893 :group 'org-progress
2894 :type '(choice
2895 (const :tag "No logging" nil)
2896 (const :tag "Record CLOSED timestamp" time)
2897 (const :tag "Record CLOSED timestamp with note." note)))
2899 ;; Normalize old uses of org-log-done.
2900 (cond
2901 ((eq org-log-done t) (setq org-log-done 'time))
2902 ((and (listp org-log-done) (memq 'done org-log-done))
2903 (setq org-log-done 'note)))
2905 (defcustom org-log-reschedule nil
2906 "Information to record when the scheduling date of a tasks is modified.
2908 Possible values are:
2910 nil Don't add anything, just change the date
2911 time Add a time stamp to the task
2912 note Prompt for a note and add it with template `org-log-note-headings'
2914 This option can also be set with on a per-file-basis with
2916 #+STARTUP: nologreschedule
2917 #+STARTUP: logreschedule
2918 #+STARTUP: lognotereschedule"
2919 :group 'org-todo
2920 :group 'org-progress
2921 :type '(choice
2922 (const :tag "No logging" nil)
2923 (const :tag "Record timestamp" time)
2924 (const :tag "Record timestamp with note." note)))
2926 (defcustom org-log-redeadline nil
2927 "Information to record when the deadline date of a tasks is modified.
2929 Possible values are:
2931 nil Don't add anything, just change the date
2932 time Add a time stamp to the task
2933 note Prompt for a note and add it with template `org-log-note-headings'
2935 This option can also be set with on a per-file-basis with
2937 #+STARTUP: nologredeadline
2938 #+STARTUP: logredeadline
2939 #+STARTUP: lognoteredeadline
2941 You can have local logging settings for a subtree by setting the LOGGING
2942 property to one or more of these keywords."
2943 :group 'org-todo
2944 :group 'org-progress
2945 :type '(choice
2946 (const :tag "No logging" nil)
2947 (const :tag "Record timestamp" time)
2948 (const :tag "Record timestamp with note." note)))
2950 (defcustom org-log-note-clock-out nil
2951 "Non-nil means record a note when clocking out of an item.
2952 This can also be configured on a per-file basis by adding one of
2953 the following lines anywhere in the buffer:
2955 #+STARTUP: lognoteclock-out
2956 #+STARTUP: nolognoteclock-out"
2957 :group 'org-todo
2958 :group 'org-progress
2959 :type 'boolean)
2961 (defcustom org-log-done-with-time t
2962 "Non-nil means the CLOSED time stamp will contain date and time.
2963 When nil, only the date will be recorded."
2964 :group 'org-progress
2965 :type 'boolean)
2967 (defcustom org-log-note-headings
2968 '((done . "CLOSING NOTE %t")
2969 (state . "State %-12s from %-12S %t")
2970 (note . "Note taken on %t")
2971 (reschedule . "Rescheduled from %S on %t")
2972 (delschedule . "Not scheduled, was %S on %t")
2973 (redeadline . "New deadline from %S on %t")
2974 (deldeadline . "Removed deadline, was %S on %t")
2975 (refile . "Refiled on %t")
2976 (clock-out . ""))
2977 "Headings for notes added to entries.
2979 The value is an alist, with the car being a symbol indicating the
2980 note context, and the cdr is the heading to be used. The heading
2981 may also be the empty string. The following placeholders can be
2982 used:
2984 %t a time stamp.
2985 %T an active time stamp instead the default inactive one
2986 %d a short-format time stamp.
2987 %D an active short-format time stamp.
2988 %s the new TODO state or time stamp (inactive), in double quotes.
2989 %S the old TODO state or time stamp (inactive), in double quotes.
2990 %u the user name.
2991 %U full user name.
2993 In fact, it is not a good idea to change the `state' entry,
2994 because Agenda Log mode depends on the format of these entries."
2995 :group 'org-todo
2996 :group 'org-progress
2997 :type '(list :greedy t
2998 (cons (const :tag "Heading when closing an item" done) string)
2999 (cons (const :tag
3000 "Heading when changing todo state (todo sequence only)"
3001 state) string)
3002 (cons (const :tag "Heading when just taking a note" note) string)
3003 (cons (const :tag "Heading when rescheduling" reschedule) string)
3004 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3005 (cons (const :tag "Heading when changing deadline" redeadline) string)
3006 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3007 (cons (const :tag "Heading when refiling" refile) string)
3008 (cons (const :tag "Heading when clocking out" clock-out) string)))
3010 (unless (assq 'note org-log-note-headings)
3011 (push '(note . "%t") org-log-note-headings))
3013 (defcustom org-log-into-drawer nil
3014 "Non-nil means insert state change notes and time stamps into a drawer.
3015 When nil, state changes notes will be inserted after the headline and
3016 any scheduling and clock lines, but not inside a drawer.
3018 The value of this variable should be the name of the drawer to use.
3019 LOGBOOK is proposed as the default drawer for this purpose, you can
3020 also set this to a string to define the drawer of your choice.
3022 A value of t is also allowed, representing \"LOGBOOK\".
3024 A value of t or nil can also be set with on a per-file-basis with
3026 #+STARTUP: logdrawer
3027 #+STARTUP: nologdrawer
3029 If this variable is set, `org-log-state-notes-insert-after-drawers'
3030 will be ignored.
3032 You can set the property LOG_INTO_DRAWER to overrule this setting for
3033 a subtree.
3035 Do not check directly this variable in a Lisp program. Call
3036 function `org-log-into-drawer' instead."
3037 :group 'org-todo
3038 :group 'org-progress
3039 :type '(choice
3040 (const :tag "Not into a drawer" nil)
3041 (const :tag "LOGBOOK" t)
3042 (string :tag "Other")))
3044 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3046 (defun org-log-into-drawer ()
3047 "Name of the log drawer, as a string, or nil.
3048 This is the value of `org-log-into-drawer'. However, if the
3049 current entry has or inherits a LOG_INTO_DRAWER property, it will
3050 be used instead of the default value."
3051 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3052 (cond ((equal p "nil") nil)
3053 ((equal p "t") "LOGBOOK")
3054 ((stringp p) p)
3055 (p "LOGBOOK")
3056 ((stringp org-log-into-drawer) org-log-into-drawer)
3057 (org-log-into-drawer "LOGBOOK"))))
3059 (defcustom org-log-state-notes-insert-after-drawers nil
3060 "Non-nil means insert state change notes after any drawers in entry.
3061 Only the drawers that *immediately* follow the headline and the
3062 deadline/scheduled line are skipped.
3063 When nil, insert notes right after the heading and perhaps the line
3064 with deadline/scheduling if present.
3066 This variable will have no effect if `org-log-into-drawer' is
3067 set."
3068 :group 'org-todo
3069 :group 'org-progress
3070 :type 'boolean)
3072 (defcustom org-log-states-order-reversed t
3073 "Non-nil means the latest state note will be directly after heading.
3074 When nil, the state change notes will be ordered according to time.
3076 This option can also be set with on a per-file-basis with
3078 #+STARTUP: logstatesreversed
3079 #+STARTUP: nologstatesreversed"
3080 :group 'org-todo
3081 :group 'org-progress
3082 :type 'boolean)
3084 (defcustom org-todo-repeat-to-state nil
3085 "The TODO state to which a repeater should return the repeating task.
3086 By default this is the first task in a TODO sequence, or the previous state
3087 in a TODO_TYP set. But you can specify another task here.
3088 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3089 :group 'org-todo
3090 :version "24.1"
3091 :type '(choice (const :tag "Head of sequence" nil)
3092 (string :tag "Specific state")))
3094 (defcustom org-log-repeat 'time
3095 "Non-nil means record moving through the DONE state when triggering repeat.
3096 An auto-repeating task is immediately switched back to TODO when
3097 marked DONE. If you are not logging state changes (by adding \"@\"
3098 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3099 record a closing note, there will be no record of the task moving
3100 through DONE. This variable forces taking a note anyway.
3102 nil Don't force a record
3103 time Record a time stamp
3104 note Prompt for a note and add it with template `org-log-note-headings'
3106 This option can also be set with on a per-file-basis with
3108 #+STARTUP: nologrepeat
3109 #+STARTUP: logrepeat
3110 #+STARTUP: lognoterepeat
3112 You can have local logging settings for a subtree by setting the LOGGING
3113 property to one or more of these keywords."
3114 :group 'org-todo
3115 :group 'org-progress
3116 :type '(choice
3117 (const :tag "Don't force a record" nil)
3118 (const :tag "Force recording the DONE state" time)
3119 (const :tag "Force recording a note with the DONE state" note)))
3122 (defgroup org-priorities nil
3123 "Priorities in Org mode."
3124 :tag "Org Priorities"
3125 :group 'org-todo)
3127 (defcustom org-enable-priority-commands t
3128 "Non-nil means priority commands are active.
3129 When nil, these commands will be disabled, so that you never accidentally
3130 set a priority."
3131 :group 'org-priorities
3132 :type 'boolean)
3134 (defcustom org-highest-priority ?A
3135 "The highest priority of TODO items. A character like ?A, ?B etc.
3136 Must have a smaller ASCII number than `org-lowest-priority'."
3137 :group 'org-priorities
3138 :type 'character)
3140 (defcustom org-lowest-priority ?C
3141 "The lowest priority of TODO items. A character like ?A, ?B etc.
3142 Must have a larger ASCII number than `org-highest-priority'."
3143 :group 'org-priorities
3144 :type 'character)
3146 (defcustom org-default-priority ?B
3147 "The default priority of TODO items.
3148 This is the priority an item gets if no explicit priority is given.
3149 When starting to cycle on an empty priority the first step in the cycle
3150 depends on `org-priority-start-cycle-with-default'. The resulting first
3151 step priority must not exceed the range from `org-highest-priority' to
3152 `org-lowest-priority' which means that `org-default-priority' has to be
3153 in this range exclusive or inclusive the range boundaries. Else the
3154 first step refuses to set the default and the second will fall back
3155 to (depending on the command used) the highest or lowest priority."
3156 :group 'org-priorities
3157 :type 'character)
3159 (defcustom org-priority-start-cycle-with-default t
3160 "Non-nil means start with default priority when starting to cycle.
3161 When this is nil, the first step in the cycle will be (depending on the
3162 command used) one higher or lower than the default priority.
3163 See also `org-default-priority'."
3164 :group 'org-priorities
3165 :type 'boolean)
3167 (defcustom org-get-priority-function nil
3168 "Function to extract the priority from a string.
3169 The string is normally the headline. If this is nil Org computes the
3170 priority from the priority cookie like [#A] in the headline. It returns
3171 an integer, increasing by 1000 for each priority level.
3172 The user can set a different function here, which should take a string
3173 as an argument and return the numeric priority."
3174 :group 'org-priorities
3175 :version "24.1"
3176 :type '(choice
3177 (const nil)
3178 (function)))
3180 (defgroup org-time nil
3181 "Options concerning time stamps and deadlines in Org mode."
3182 :tag "Org Time"
3183 :group 'org)
3185 (defcustom org-time-stamp-rounding-minutes '(0 5)
3186 "Number of minutes to round time stamps to.
3187 \\<org-mode-map>\
3188 These are two values, the first applies when first creating a time stamp.
3189 The second applies when changing it with the commands `S-up' and `S-down'.
3190 When changing the time stamp, this means that it will change in steps
3191 of N minutes, as given by the second value.
3193 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3194 numbers should be factors of 60, so for example 5, 10, 15.
3196 When this is larger than 1, you can still force an exact time stamp by using
3197 a double prefix argument to a time stamp command like \
3198 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3199 and by using a prefix arg to `S-up/down' to specify the exact number
3200 of minutes to shift."
3201 :group 'org-time
3202 :get (lambda (var) ; Make sure both elements are there
3203 (if (integerp (default-value var))
3204 (list (default-value var) 5)
3205 (default-value var)))
3206 :type '(list
3207 (integer :tag "when inserting times")
3208 (integer :tag "when modifying times")))
3210 ;; Normalize old customizations of this variable.
3211 (when (integerp org-time-stamp-rounding-minutes)
3212 (setq org-time-stamp-rounding-minutes
3213 (list org-time-stamp-rounding-minutes
3214 org-time-stamp-rounding-minutes)))
3216 (defcustom org-display-custom-times nil
3217 "Non-nil means overlay custom formats over all time stamps.
3218 The formats are defined through the variable `org-time-stamp-custom-formats'.
3219 To turn this on on a per-file basis, insert anywhere in the file:
3220 #+STARTUP: customtime"
3221 :group 'org-time
3222 :set 'set-default
3223 :type 'sexp)
3224 (make-variable-buffer-local 'org-display-custom-times)
3226 (defcustom org-time-stamp-custom-formats
3227 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3228 "Custom formats for time stamps. See `format-time-string' for the syntax.
3229 These are overlaid over the default ISO format if the variable
3230 `org-display-custom-times' is set. Time like %H:%M should be at the
3231 end of the second format. The custom formats are also honored by export
3232 commands, if custom time display is turned on at the time of export."
3233 :group 'org-time
3234 :type 'sexp)
3236 (defun org-time-stamp-format (&optional long inactive)
3237 "Get the right format for a time string."
3238 (let ((f (if long (cdr org-time-stamp-formats)
3239 (car org-time-stamp-formats))))
3240 (if inactive
3241 (concat "[" (substring f 1 -1) "]")
3242 f)))
3244 (defcustom org-time-clocksum-format
3245 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3246 "The format string used when creating CLOCKSUM lines.
3247 This is also used when Org mode generates a time duration.
3249 The value can be a single format string containing two
3250 %-sequences, which will be filled with the number of hours and
3251 minutes in that order.
3253 Alternatively, the value can be a plist associating any of the
3254 keys :years, :months, :weeks, :days, :hours or :minutes with
3255 format strings. The time duration is formatted using only the
3256 time components that are needed and concatenating the results.
3257 If a time unit in absent, it falls back to the next smallest
3258 unit.
3260 The keys :require-years, :require-months, :require-days,
3261 :require-weeks, :require-hours, :require-minutes are also
3262 meaningful. A non-nil value for these keys indicates that the
3263 corresponding time component should always be included, even if
3264 its value is 0.
3267 For example,
3269 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3270 :require-minutes t)
3272 means durations longer than a day will be expressed in days,
3273 hours and minutes, and durations less than a day will always be
3274 expressed in hours and minutes (even for durations less than an
3275 hour).
3277 The value
3279 (:days \"%dd\" :minutes \"%dm\")
3281 means durations longer than a day will be expressed in days and
3282 minutes, and durations less than a day will be expressed entirely
3283 in minutes (even for durations longer than an hour)."
3284 :group 'org-time
3285 :group 'org-clock
3286 :version "24.4"
3287 :package-version '(Org . "8.0")
3288 :type '(choice (string :tag "Format string")
3289 (set :tag "Plist"
3290 (group :inline t (const :tag "Years" :years)
3291 (string :tag "Format string"))
3292 (group :inline t
3293 (const :tag "Always show years" :require-years)
3294 (const t))
3295 (group :inline t (const :tag "Months" :months)
3296 (string :tag "Format string"))
3297 (group :inline t
3298 (const :tag "Always show months" :require-months)
3299 (const t))
3300 (group :inline t (const :tag "Weeks" :weeks)
3301 (string :tag "Format string"))
3302 (group :inline t
3303 (const :tag "Always show weeks" :require-weeks)
3304 (const t))
3305 (group :inline t (const :tag "Days" :days)
3306 (string :tag "Format string"))
3307 (group :inline t
3308 (const :tag "Always show days" :require-days)
3309 (const t))
3310 (group :inline t (const :tag "Hours" :hours)
3311 (string :tag "Format string"))
3312 (group :inline t
3313 (const :tag "Always show hours" :require-hours)
3314 (const t))
3315 (group :inline t (const :tag "Minutes" :minutes)
3316 (string :tag "Format string"))
3317 (group :inline t
3318 (const :tag "Always show minutes" :require-minutes)
3319 (const t)))))
3321 (defcustom org-time-clocksum-use-fractional nil
3322 "When non-nil, `\\[org-clock-display]' uses fractional times.
3323 See `org-time-clocksum-format' for more on time clock formats."
3324 :group 'org-time
3325 :group 'org-clock
3326 :version "24.3"
3327 :type 'boolean)
3329 (defcustom org-time-clocksum-use-effort-durations nil
3330 "When non-nil, `\\[org-clock-display]' uses effort durations.
3331 E.g. by default, one day is considered to be a 8 hours effort,
3332 so a task that has been clocked for 16 hours will be displayed
3333 as during 2 days in the clock display or in the clocktable.
3335 See `org-effort-durations' on how to set effort durations
3336 and `org-time-clocksum-format' for more on time clock formats."
3337 :group 'org-time
3338 :group 'org-clock
3339 :version "24.4"
3340 :package-version '(Org . "8.0")
3341 :type 'boolean)
3343 (defcustom org-time-clocksum-fractional-format "%.2f"
3344 "The format string used when creating CLOCKSUM lines,
3345 or when Org mode generates a time duration, if
3346 `org-time-clocksum-use-fractional' is enabled.
3348 The value can be a single format string containing one
3349 %-sequence, which will be filled with the number of hours as
3350 a float.
3352 Alternatively, the value can be a plist associating any of the
3353 keys :years, :months, :weeks, :days, :hours or :minutes with
3354 a format string. The time duration is formatted using the
3355 largest time unit which gives a non-zero integer part. If all
3356 specified formats have zero integer part, the smallest time unit
3357 is used."
3358 :group 'org-time
3359 :type '(choice (string :tag "Format string")
3360 (set (group :inline t (const :tag "Years" :years)
3361 (string :tag "Format string"))
3362 (group :inline t (const :tag "Months" :months)
3363 (string :tag "Format string"))
3364 (group :inline t (const :tag "Weeks" :weeks)
3365 (string :tag "Format string"))
3366 (group :inline t (const :tag "Days" :days)
3367 (string :tag "Format string"))
3368 (group :inline t (const :tag "Hours" :hours)
3369 (string :tag "Format string"))
3370 (group :inline t (const :tag "Minutes" :minutes)
3371 (string :tag "Format string")))))
3373 (defcustom org-deadline-warning-days 14
3374 "Number of days before expiration during which a deadline becomes active.
3375 This variable governs the display in sparse trees and in the agenda.
3376 When 0 or negative, it means use this number (the absolute value of it)
3377 even if a deadline has a different individual lead time specified.
3379 Custom commands can set this variable in the options section."
3380 :group 'org-time
3381 :group 'org-agenda-daily/weekly
3382 :type 'integer)
3384 (defcustom org-scheduled-delay-days 0
3385 "Number of days before a scheduled item becomes active.
3386 This variable governs the display in sparse trees and in the agenda.
3387 The default value (i.e. 0) means: don't delay scheduled item.
3388 When negative, it means use this number (the absolute value of it)
3389 even if a scheduled item has a different individual delay time
3390 specified.
3392 Custom commands can set this variable in the options section."
3393 :group 'org-time
3394 :group 'org-agenda-daily/weekly
3395 :version "24.4"
3396 :package-version '(Org . "8.0")
3397 :type 'integer)
3399 (defcustom org-read-date-prefer-future t
3400 "Non-nil means assume future for incomplete date input from user.
3401 This affects the following situations:
3402 1. The user gives a month but not a year.
3403 For example, if it is April and you enter \"feb 2\", this will be read
3404 as Feb 2, *next* year. \"May 5\", however, will be this year.
3405 2. The user gives a day, but no month.
3406 For example, if today is the 15th, and you enter \"3\", Org will read
3407 this as the third of *next* month. However, if you enter \"17\",
3408 it will be considered as *this* month.
3410 If you set this variable to the symbol `time', then also the following
3411 will work:
3413 3. If the user gives a time.
3414 If the time is before now, it will be interpreted as tomorrow.
3416 Currently none of this works for ISO week specifications.
3418 When this option is nil, the current day, month and year will always be
3419 used as defaults.
3421 See also `org-agenda-jump-prefer-future'."
3422 :group 'org-time
3423 :type '(choice
3424 (const :tag "Never" nil)
3425 (const :tag "Check month and day" t)
3426 (const :tag "Check month, day, and time" time)))
3428 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3429 "Should the agenda jump command prefer the future for incomplete dates?
3430 The default is to do the same as configured in `org-read-date-prefer-future'.
3431 But you can also set a deviating value here.
3432 This may t or nil, or the symbol `org-read-date-prefer-future'."
3433 :group 'org-agenda
3434 :group 'org-time
3435 :version "24.1"
3436 :type '(choice
3437 (const :tag "Use org-read-date-prefer-future"
3438 org-read-date-prefer-future)
3439 (const :tag "Never" nil)
3440 (const :tag "Always" t)))
3442 (defcustom org-read-date-force-compatible-dates t
3443 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3445 Depending on the system Emacs is running on, certain dates cannot
3446 be represented with the type used internally to represent time.
3447 Dates between 1970-1-1 and 2038-1-1 can always be represented
3448 correctly. Some systems allow for earlier dates, some for later,
3449 some for both. One way to find out it to insert any date into an
3450 Org buffer, putting the cursor on the year and hitting S-up and
3451 S-down to test the range.
3453 When this variable is set to t, the date/time prompt will not let
3454 you specify dates outside the 1970-2037 range, so it is certain that
3455 these dates will work in whatever version of Emacs you are
3456 running, and also that you can move a file from one Emacs implementation
3457 to another. WHenever Org is forcing the year for you, it will display
3458 a message and beep.
3460 When this variable is nil, Org will check if the date is
3461 representable in the specific Emacs implementation you are using.
3462 If not, it will force a year, usually the current year, and beep
3463 to remind you. Currently this setting is not recommended because
3464 the likelihood that you will open your Org files in an Emacs that
3465 has limited date range is not negligible.
3467 A workaround for this problem is to use diary sexp dates for time
3468 stamps outside of this range."
3469 :group 'org-time
3470 :version "24.1"
3471 :type 'boolean)
3473 (defcustom org-read-date-display-live t
3474 "Non-nil means display current interpretation of date prompt live.
3475 This display will be in an overlay, in the minibuffer."
3476 :group 'org-time
3477 :type 'boolean)
3479 (defcustom org-read-date-popup-calendar t
3480 "Non-nil means pop up a calendar when prompting for a date.
3481 In the calendar, the date can be selected with mouse-1. However, the
3482 minibuffer will also be active, and you can simply enter the date as well.
3483 When nil, only the minibuffer will be available."
3484 :group 'org-time
3485 :type 'boolean)
3486 (defvaralias 'org-popup-calendar-for-date-prompt
3487 'org-read-date-popup-calendar)
3489 (defcustom org-extend-today-until 0
3490 "The hour when your day really ends. Must be an integer.
3491 This has influence for the following applications:
3492 - When switching the agenda to \"today\". It it is still earlier than
3493 the time given here, the day recognized as TODAY is actually yesterday.
3494 - When a date is read from the user and it is still before the time given
3495 here, the current date and time will be assumed to be yesterday, 23:59.
3496 Also, timestamps inserted in capture templates follow this rule.
3498 IMPORTANT: This is a feature whose implementation is and likely will
3499 remain incomplete. Really, it is only here because past midnight seems to
3500 be the favorite working time of John Wiegley :-)"
3501 :group 'org-time
3502 :type 'integer)
3504 (defcustom org-use-effective-time nil
3505 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3506 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3507 \"effective time\" of any timestamps between midnight and 8am will be
3508 23:59 of the previous day."
3509 :group 'org-time
3510 :version "24.1"
3511 :type 'boolean)
3513 (defcustom org-use-last-clock-out-time-as-effective-time nil
3514 "When non-nil, use the last clock out time for `org-todo'.
3515 Note that this option has precedence over the combined use of
3516 `org-use-effective-time' and `org-extend-today-until'."
3517 :group 'org-time
3518 :version "24.4"
3519 :package-version '(Org . "8.0")
3520 :type 'boolean)
3522 (defcustom org-edit-timestamp-down-means-later nil
3523 "Non-nil means S-down will increase the time in a time stamp.
3524 When nil, S-up will increase."
3525 :group 'org-time
3526 :type 'boolean)
3528 (defcustom org-calendar-follow-timestamp-change t
3529 "Non-nil means make the calendar window follow timestamp changes.
3530 When a timestamp is modified and the calendar window is visible, it will be
3531 moved to the new date."
3532 :group 'org-time
3533 :type 'boolean)
3535 (defgroup org-tags nil
3536 "Options concerning tags in Org mode."
3537 :tag "Org Tags"
3538 :group 'org)
3540 (defcustom org-tag-alist nil
3541 "Default tags available in Org files.
3543 The value of this variable is an alist. Associations either:
3545 (TAG)
3546 (TAG . SELECT)
3547 (SPECIAL)
3549 where TAG is a tag as a string, SELECT is a character, used to
3550 select that tag through the fast tag selection interface, and
3551 SPECIAL is one of the following keywords: `:startgroup',
3552 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3553 `:newline'. These keywords are used to define a hierarchy of
3554 tags. See manual for details.
3556 When this variable is nil, Org mode bases tag input on what is
3557 already in the buffer. The value can be overridden locally by
3558 using a TAGS keyword, e.g.,
3560 #+TAGS: tag1 tag2
3562 See also `org-tag-persistent-alist' to sidestep this behavior."
3563 :group 'org-tags
3564 :type '(repeat
3565 (choice
3566 (cons (string :tag "Tag name")
3567 (character :tag "Access char"))
3568 (const :tag "Start radio group" (:startgroup))
3569 (const :tag "Start tag group, non distinct" (:startgrouptag))
3570 (const :tag "Group tags delimiter" (:grouptags))
3571 (const :tag "End radio group" (:endgroup))
3572 (const :tag "End tag group, non distinct" (:endgrouptag))
3573 (const :tag "New line" (:newline)))))
3575 (defcustom org-tag-persistent-alist nil
3576 "Tags always available in Org files.
3578 The value of this variable is an alist. Associations either:
3580 (TAG)
3581 (TAG . SELECT)
3582 (SPECIAL)
3584 where TAG is a tag as a string, SELECT is a character, used to
3585 select that tag through the fast tag selection interface, and
3586 SPECIAL is one of the following keywords: `:startgroup',
3587 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3588 `:newline'. These keywords are used to define a hierarchy of
3589 tags. See manual for details.
3591 Unlike to `org-tag-alist', tags defined in this variable do not
3592 depend on a local TAGS keyword. Instead, to disable these tags
3593 on a per-file basis, insert anywhere in the file:
3595 #+STARTUP: noptag"
3596 :group 'org-tags
3597 :type '(repeat
3598 (choice
3599 (cons (string :tag "Tag name")
3600 (character :tag "Access char"))
3601 (const :tag "Start radio group" (:startgroup))
3602 (const :tag "Start tag group, non distinct" (:startgrouptag))
3603 (const :tag "Group tags delimiter" (:grouptags))
3604 (const :tag "End radio group" (:endgroup))
3605 (const :tag "End tag group, non distinct" (:endgrouptag))
3606 (const :tag "New line" (:newline)))))
3608 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3609 "If non-nil, always offer completion for all tags of all agenda files.
3610 Instead of customizing this variable directly, you might want to
3611 set it locally for capture buffers, because there no list of
3612 tags in that file can be created dynamically (there are none).
3614 (add-hook \\='org-capture-mode-hook
3615 (lambda ()
3616 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3617 :group 'org-tags
3618 :version "24.1"
3619 :type 'boolean)
3621 (defvar org-file-tags nil
3622 "List of tags that can be inherited by all entries in the file.
3623 The tags will be inherited if the variable `org-use-tag-inheritance'
3624 says they should be.
3625 This variable is populated from #+FILETAGS lines.")
3627 (defcustom org-use-fast-tag-selection 'auto
3628 "Non-nil means use fast tag selection scheme.
3629 This is a special interface to select and deselect tags with single keys.
3630 When nil, fast selection is never used.
3631 When the symbol `auto', fast selection is used if and only if selection
3632 characters for tags have been configured, either through the variable
3633 `org-tag-alist' or through a #+TAGS line in the buffer.
3634 When t, fast selection is always used and selection keys are assigned
3635 automatically if necessary."
3636 :group 'org-tags
3637 :type '(choice
3638 (const :tag "Always" t)
3639 (const :tag "Never" nil)
3640 (const :tag "When selection characters are configured" auto)))
3642 (defcustom org-fast-tag-selection-single-key nil
3643 "Non-nil means fast tag selection exits after first change.
3644 When nil, you have to press RET to exit it.
3645 During fast tag selection, you can toggle this flag with `C-c'.
3646 This variable can also have the value `expert'. In this case, the window
3647 displaying the tags menu is not even shown, until you press C-c again."
3648 :group 'org-tags
3649 :type '(choice
3650 (const :tag "No" nil)
3651 (const :tag "Yes" t)
3652 (const :tag "Expert" expert)))
3654 (defvar org-fast-tag-selection-include-todo nil
3655 "Non-nil means fast tags selection interface will also offer TODO states.
3656 This is an undocumented feature, you should not rely on it.")
3658 (defcustom org-tags-column -77
3659 "The column to which tags should be indented in a headline.
3660 If this number is positive, it specifies the column. If it is negative,
3661 it means that the tags should be flushright to that column. For example,
3662 -80 works well for a normal 80 character screen.
3663 When 0, place tags directly after headline text, with only one space in
3664 between."
3665 :group 'org-tags
3666 :type 'integer)
3668 (defcustom org-auto-align-tags t
3669 "Non-nil keeps tags aligned when modifying headlines.
3670 Some operations (i.e. demoting) change the length of a headline and
3671 therefore shift the tags around. With this option turned on, after
3672 each such operation the tags are again aligned to `org-tags-column'."
3673 :group 'org-tags
3674 :type 'boolean)
3676 (defcustom org-use-tag-inheritance t
3677 "Non-nil means tags in levels apply also for sublevels.
3678 When nil, only the tags directly given in a specific line apply there.
3679 This may also be a list of tags that should be inherited, or a regexp that
3680 matches tags that should be inherited. Additional control is possible
3681 with the variable `org-tags-exclude-from-inheritance' which gives an
3682 explicit list of tags to be excluded from inheritance, even if the value of
3683 `org-use-tag-inheritance' would select it for inheritance.
3685 If this option is t, a match early-on in a tree can lead to a large
3686 number of matches in the subtree when constructing the agenda or creating
3687 a sparse tree. If you only want to see the first match in a tree during
3688 a search, check out the variable `org-tags-match-list-sublevels'."
3689 :group 'org-tags
3690 :type '(choice
3691 (const :tag "Not" nil)
3692 (const :tag "Always" t)
3693 (repeat :tag "Specific tags" (string :tag "Tag"))
3694 (regexp :tag "Tags matched by regexp")))
3696 (defcustom org-tags-exclude-from-inheritance nil
3697 "List of tags that should never be inherited.
3698 This is a way to exclude a few tags from inheritance. For way to do
3699 the opposite, to actively allow inheritance for selected tags,
3700 see the variable `org-use-tag-inheritance'."
3701 :group 'org-tags
3702 :type '(repeat (string :tag "Tag")))
3704 (defun org-tag-inherit-p (tag)
3705 "Check if TAG is one that should be inherited."
3706 (cond
3707 ((member tag org-tags-exclude-from-inheritance) nil)
3708 ((eq org-use-tag-inheritance t) t)
3709 ((not org-use-tag-inheritance) nil)
3710 ((stringp org-use-tag-inheritance)
3711 (string-match org-use-tag-inheritance tag))
3712 ((listp org-use-tag-inheritance)
3713 (member tag org-use-tag-inheritance))
3714 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3716 (defcustom org-tags-match-list-sublevels t
3717 "Non-nil means list also sublevels of headlines matching a search.
3718 This variable applies to tags/property searches, and also to stuck
3719 projects because this search is based on a tags match as well.
3721 When set to the symbol `indented', sublevels are indented with
3722 leading dots.
3724 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3725 the sublevels of a headline matching a tag search often also match
3726 the same search. Listing all of them can create very long lists.
3727 Setting this variable to nil causes subtrees of a match to be skipped.
3729 This variable is semi-obsolete and probably should always be true. It
3730 is better to limit inheritance to certain tags using the variables
3731 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3732 :group 'org-tags
3733 :type '(choice
3734 (const :tag "No, don't list them" nil)
3735 (const :tag "Yes, do list them" t)
3736 (const :tag "List them, indented with leading dots" indented)))
3738 (defcustom org-tags-sort-function nil
3739 "When set, tags are sorted using this function as a comparator."
3740 :group 'org-tags
3741 :type '(choice
3742 (const :tag "No sorting" nil)
3743 (const :tag "Alphabetical" string<)
3744 (const :tag "Reverse alphabetical" string>)
3745 (function :tag "Custom function" nil)))
3747 (defvar org-tags-history nil
3748 "History of minibuffer reads for tags.")
3749 (defvar org-last-tags-completion-table nil
3750 "The last used completion table for tags.")
3751 (defvar org-after-tags-change-hook nil
3752 "Hook that is run after the tags in a line have changed.")
3754 (defgroup org-properties nil
3755 "Options concerning properties in Org mode."
3756 :tag "Org Properties"
3757 :group 'org)
3759 (defcustom org-property-format "%-10s %s"
3760 "How property key/value pairs should be formatted by `indent-line'.
3761 When `indent-line' hits a property definition, it will format the line
3762 according to this format, mainly to make sure that the values are
3763 lined-up with respect to each other."
3764 :group 'org-properties
3765 :type 'string)
3767 (defcustom org-properties-postprocess-alist nil
3768 "Alist of properties and functions to adjust inserted values.
3769 Elements of this alist must be of the form
3771 ([string] [function])
3773 where [string] must be a property name and [function] must be a
3774 lambda expression: this lambda expression must take one argument,
3775 the value to adjust, and return the new value as a string.
3777 For example, this element will allow the property \"Remaining\"
3778 to be updated wrt the relation between the \"Effort\" property
3779 and the clock summary:
3781 ((\"Remaining\" (lambda(value)
3782 (let ((clocksum (org-clock-sum-current-item))
3783 (effort (org-duration-string-to-minutes
3784 (org-entry-get (point) \"Effort\"))))
3785 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3786 :group 'org-properties
3787 :version "24.1"
3788 :type '(alist :key-type (string :tag "Property")
3789 :value-type (function :tag "Function")))
3791 (defcustom org-use-property-inheritance nil
3792 "Non-nil means properties apply also for sublevels.
3794 This setting is chiefly used during property searches. Turning it on can
3795 cause significant overhead when doing a search, which is why it is not
3796 on by default.
3798 When nil, only the properties directly given in the current entry count.
3799 When t, every property is inherited. The value may also be a list of
3800 properties that should have inheritance, or a regular expression matching
3801 properties that should be inherited.
3803 However, note that some special properties use inheritance under special
3804 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3805 and the properties ending in \"_ALL\" when they are used as descriptor
3806 for valid values of a property.
3808 Note for programmers:
3809 When querying an entry with `org-entry-get', you can control if inheritance
3810 should be used. By default, `org-entry-get' looks only at the local
3811 properties. You can request inheritance by setting the inherit argument
3812 to t (to force inheritance) or to `selective' (to respect the setting
3813 in this variable)."
3814 :group 'org-properties
3815 :type '(choice
3816 (const :tag "Not" nil)
3817 (const :tag "Always" t)
3818 (repeat :tag "Specific properties" (string :tag "Property"))
3819 (regexp :tag "Properties matched by regexp")))
3821 (defun org-property-inherit-p (property)
3822 "Check if PROPERTY is one that should be inherited."
3823 (cond
3824 ((eq org-use-property-inheritance t) t)
3825 ((not org-use-property-inheritance) nil)
3826 ((stringp org-use-property-inheritance)
3827 (string-match org-use-property-inheritance property))
3828 ((listp org-use-property-inheritance)
3829 (member property org-use-property-inheritance))
3830 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3832 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3833 "The default column format, if no other format has been defined.
3834 This variable can be set on the per-file basis by inserting a line
3836 #+COLUMNS: %25ITEM ....."
3837 :group 'org-properties
3838 :type 'string)
3840 (defcustom org-columns-ellipses ".."
3841 "The ellipses to be used when a field in column view is truncated.
3842 When this is the empty string, as many characters as possible are shown,
3843 but then there will be no visual indication that the field has been truncated.
3844 When this is a string of length N, the last N characters of a truncated
3845 field are replaced by this string. If the column is narrower than the
3846 ellipses string, only part of the ellipses string will be shown."
3847 :group 'org-properties
3848 :type 'string)
3850 (defconst org-global-properties-fixed
3851 '(("VISIBILITY_ALL" . "folded children content all")
3852 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3853 "List of property/value pairs that can be inherited by any entry.
3855 These are fixed values, for the preset properties. The user variable
3856 that can be used to add to this list is `org-global-properties'.
3858 The entries in this list are cons cells where the car is a property
3859 name and cdr is a string with the value. If the value represents
3860 multiple items like an \"_ALL\" property, separate the items by
3861 spaces.")
3863 (defcustom org-global-properties nil
3864 "List of property/value pairs that can be inherited by any entry.
3866 This list will be combined with the constant `org-global-properties-fixed'.
3868 The entries in this list are cons cells where the car is a property
3869 name and cdr is a string with the value.
3871 You can set buffer-local values for the same purpose in the variable
3872 `org-file-properties' this by adding lines like
3874 #+PROPERTY: NAME VALUE"
3875 :group 'org-properties
3876 :type '(repeat
3877 (cons (string :tag "Property")
3878 (string :tag "Value"))))
3880 (defvar-local org-file-properties nil
3881 "List of property/value pairs that can be inherited by any entry.
3882 Valid for the current buffer.
3883 This variable is populated from #+PROPERTY lines.")
3885 (defgroup org-agenda nil
3886 "Options concerning agenda views in Org mode."
3887 :tag "Org Agenda"
3888 :group 'org)
3890 (defvar-local org-category nil
3891 "Variable used by org files to set a category for agenda display.
3892 Such files should use a file variable to set it, for example
3894 # -*- mode: org; org-category: \"ELisp\"
3896 or contain a special line
3898 #+CATEGORY: ELisp
3900 If the file does not specify a category, then file's base name
3901 is used instead.")
3902 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3904 (defcustom org-agenda-files nil
3905 "The files to be used for agenda display.
3907 If an entry is a directory, all files in that directory that are matched
3908 by `org-agenda-file-regexp' will be part of the file list.
3910 If the value of the variable is not a list but a single file name, then
3911 the list of agenda files is actually stored and maintained in that file,
3912 one agenda file per line. In this file paths can be given relative to
3913 `org-directory'. Tilde expansion and environment variable substitution
3914 are also made.
3916 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3917 and removed with `\\[org-remove-file]'."
3918 :group 'org-agenda
3919 :type '(choice
3920 (repeat :tag "List of files and directories" file)
3921 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3923 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3924 "Regular expression to match files for `org-agenda-files'.
3925 If any element in the list in that variable contains a directory instead
3926 of a normal file, all files in that directory that are matched by this
3927 regular expression will be included."
3928 :group 'org-agenda
3929 :type 'regexp)
3931 (defcustom org-agenda-text-search-extra-files nil
3932 "List of extra files to be searched by text search commands.
3933 These files will be searched in addition to the agenda files by the
3934 commands `org-search-view' (`\\[org-agenda] s') \
3935 and `org-occur-in-agenda-files'.
3936 Note that these files will only be searched for text search commands,
3937 not for the other agenda views like todo lists, tag searches or the weekly
3938 agenda. This variable is intended to list notes and possibly archive files
3939 that should also be searched by these two commands.
3940 In fact, if the first element in the list is the symbol `agenda-archives',
3941 then all archive files of all agenda files will be added to the search
3942 scope."
3943 :group 'org-agenda
3944 :type '(set :greedy t
3945 (const :tag "Agenda Archives" agenda-archives)
3946 (repeat :inline t (file))))
3948 (defvaralias 'org-agenda-multi-occur-extra-files
3949 'org-agenda-text-search-extra-files)
3951 (defcustom org-agenda-skip-unavailable-files nil
3952 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3953 A nil value means to remove them, after a query, from the list."
3954 :group 'org-agenda
3955 :type 'boolean)
3957 (defcustom org-calendar-to-agenda-key [?c]
3958 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3959 The command `org-calendar-goto-agenda' will be bound to this key. The
3960 default is the character `c' because then `c' can be used to switch back and
3961 forth between agenda and calendar."
3962 :group 'org-agenda
3963 :type 'sexp)
3965 (defcustom org-calendar-insert-diary-entry-key [?i]
3966 "The key to be installed in `calendar-mode-map' for adding diary entries.
3967 This option is irrelevant until `org-agenda-diary-file' has been configured
3968 to point to an Org file. When that is the case, the command
3969 `org-agenda-diary-entry' will be bound to the key given here, by default
3970 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3971 if you want to continue doing this, you need to change this to a different
3972 key."
3973 :group 'org-agenda
3974 :type 'sexp)
3976 (defcustom org-agenda-diary-file 'diary-file
3977 "File to which to add new entries with the `i' key in agenda and calendar.
3978 When this is the symbol `diary-file', the functionality in the Emacs
3979 calendar will be used to add entries to the `diary-file'. But when this
3980 points to a file, `org-agenda-diary-entry' will be used instead."
3981 :group 'org-agenda
3982 :type '(choice
3983 (const :tag "The standard Emacs diary file" diary-file)
3984 (file :tag "Special Org file diary entries")))
3986 (eval-after-load "calendar"
3987 '(progn
3988 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3989 'org-calendar-goto-agenda)
3990 (add-hook 'calendar-mode-hook
3991 (lambda ()
3992 (unless (eq org-agenda-diary-file 'diary-file)
3993 (define-key calendar-mode-map
3994 org-calendar-insert-diary-entry-key
3995 'org-agenda-diary-entry))))))
3997 (defgroup org-latex nil
3998 "Options for embedding LaTeX code into Org mode."
3999 :tag "Org LaTeX"
4000 :group 'org)
4002 (defcustom org-format-latex-options
4003 '(:foreground default :background default :scale 1.0
4004 :html-foreground "Black" :html-background "Transparent"
4005 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
4006 "Options for creating images from LaTeX fragments.
4007 This is a property list with the following properties:
4008 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
4009 `default' means use the foreground of the default face.
4010 `auto' means use the foreground from the text face.
4011 :background the background color, or \"Transparent\".
4012 `default' means use the background of the default face.
4013 `auto' means use the background from the text face.
4014 :scale a scaling factor for the size of the images, to get more pixels
4015 :html-foreground, :html-background, :html-scale
4016 the same numbers for HTML export.
4017 :matchers a list indicating which matchers should be used to
4018 find LaTeX fragments. Valid members of this list are:
4019 \"begin\" find environments
4020 \"$1\" find single characters surrounded by $.$
4021 \"$\" find math expressions surrounded by $...$
4022 \"$$\" find math expressions surrounded by $$....$$
4023 \"\\(\" find math expressions surrounded by \\(...\\)
4024 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
4025 :group 'org-latex
4026 :type 'plist)
4028 (defcustom org-format-latex-signal-error t
4029 "Non-nil means signal an error when image creation of LaTeX snippets fails.
4030 When nil, just push out a message."
4031 :group 'org-latex
4032 :version "24.1"
4033 :type 'boolean)
4035 (defcustom org-latex-to-mathml-jar-file nil
4036 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
4037 Use this to specify additional executable file say a jar file.
4039 When using MathToWeb as the converter, specify the full-path to
4040 your mathtoweb.jar file."
4041 :group 'org-latex
4042 :version "24.1"
4043 :type '(choice
4044 (const :tag "None" nil)
4045 (file :tag "JAR file" :must-match t)))
4047 (defcustom org-latex-to-mathml-convert-command nil
4048 "Command to convert LaTeX fragments to MathML.
4049 Replace format-specifiers in the command as noted below and use
4050 `shell-command' to convert LaTeX to MathML.
4051 %j: Executable file in fully expanded form as specified by
4052 `org-latex-to-mathml-jar-file'.
4053 %I: Input LaTeX file in fully expanded form.
4054 %i: The latex fragment to be converted.
4055 %o: Output MathML file.
4057 This command is used by `org-create-math-formula'.
4059 When using MathToWeb as the converter, set this option to
4060 \"java -jar %j -unicode -force -df %o %I\".
4062 When using LaTeXML set this option to
4063 \"latexmlmath \"%i\" --presentationmathml=%o\"."
4064 :group 'org-latex
4065 :version "24.1"
4066 :type '(choice
4067 (const :tag "None" nil)
4068 (string :tag "\nShell command")))
4070 (defcustom org-preview-latex-default-process 'dvipng
4071 "The default process to convert LaTeX fragments to image files.
4072 All available processes and theirs documents can be found in
4073 `org-preview-latex-process-alist', which see."
4074 :group 'org-latex
4075 :version "25.2"
4076 :package-version '(Org . "9.0")
4077 :type 'symbol)
4079 (defcustom org-preview-latex-process-alist
4080 '((dvipng
4081 :programs ("latex" "dvipng" "gs")
4082 :description "dvi > png"
4083 :message "you need to install the programs: latex, dvipng and ghostscript."
4084 :image-input-type "dvi"
4085 :image-output-type "png"
4086 :image-size-adjust (1.0 . 1.0)
4087 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4088 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %b.png %f"))
4089 (dvisvgm
4090 :programs ("latex" "dvisvgm" "gs")
4091 :description "dvi > svg"
4092 :message "you need to install the programs: latex, dvisvgm and ghostscript."
4093 :use-xcolor t
4094 :image-input-type "dvi"
4095 :image-output-type "svg"
4096 :image-size-adjust (1.7 . 1.5)
4097 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4098 :image-converter ("dvisvgm %f -n -b min -c %S -o %b.svg"))
4099 (imagemagick
4100 :programs ("latex" "convert" "gs")
4101 :description "pdf > png"
4102 :message
4103 "you need to install the programs: latex, imagemagick and ghostscript."
4104 :use-xcolor t
4105 :image-input-type "pdf"
4106 :image-output-type "png"
4107 :image-size-adjust (1.0 . 1.0)
4108 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4109 :image-converter
4110 ("convert -density %D -trim -antialias %f -quality 100 %b.png")))
4111 "Definitions of external processes for LaTeX previewing.
4112 Org mode can use some external commands to generate TeX snippet's images for
4113 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4114 `org-create-formula-image' how to call them.
4116 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4117 PROPERTIES accepts the following attributes:
4119 :programs list of strings, required programs.
4120 :description string, describe the process.
4121 :message string, message it when required programs cannot be found.
4122 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4123 :image-output-type string, output file type of image converter (e.g., \"png\").
4124 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4125 deal with background and foreground color of image.
4126 Otherwise, dvipng style background and foregroud color
4127 format are generated. You may then refer to them in
4128 command options with \"%F\" and \"%B\".
4129 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4130 image size showed in buffer and the cdr element is for
4131 HTML file. This option is only useful for process
4132 developers, users should use variable
4133 `org-format-latex-options' instead.
4134 :post-clean list of strings, files matched are to be cleaned up once
4135 the image is generated. When nil, the files with \".dvi\",
4136 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4137 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4138 be cleaned up.
4139 :latex-header list of strings, the LaTeX header of the snippet file.
4140 When nil, the fallback value is used instead, which is
4141 controlled by `org-format-latex-header',
4142 `org-latex-default-packages-alist' and
4143 `org-latex-packages-alist', which see.
4144 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4145 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4146 replaced with values defined below.
4147 :image-converter list of image converter commands strings. Each of them is
4148 given to the shell and supports any of the following
4149 place-holders defined below.
4151 Place-holders used by `:image-converter' and `:latex-compiler':
4153 %f input file name.
4154 %b base name of input file.
4155 %o base directory of input file.
4157 Place-holders only used by `:image-converter':
4159 %F foreground of image
4160 %B background of image
4161 %D dpi, which is used to adjust image size by some processing commands.
4162 %S the image size scale ratio, which is used to adjust image size by some
4163 processing commands."
4164 :group 'org-latex
4165 :version "25.2"
4166 :package-version '(Org . "9.0")
4167 :type '(alist :tag "LaTeX to image backends"
4168 :value-type (plist)))
4170 (defcustom org-preview-latex-image-directory "ltximg/"
4171 "Path to store latex preview images.
4172 A relative path here creates many directories relative to the
4173 processed org files paths. An absolute path puts all preview
4174 images at the same place."
4175 :group 'org-latex
4176 :version "25.2"
4177 :package-version '(Org . "9.0")
4178 :type 'string)
4180 (defun org-format-latex-mathml-available-p ()
4181 "Return t if `org-latex-to-mathml-convert-command' is usable."
4182 (save-match-data
4183 (when (and (boundp 'org-latex-to-mathml-convert-command)
4184 org-latex-to-mathml-convert-command)
4185 (let ((executable (car (split-string
4186 org-latex-to-mathml-convert-command))))
4187 (when (executable-find executable)
4188 (if (string-match
4189 "%j" org-latex-to-mathml-convert-command)
4190 (file-readable-p org-latex-to-mathml-jar-file)
4191 t))))))
4193 (defcustom org-format-latex-header "\\documentclass{article}
4194 \\usepackage[usenames]{color}
4195 \[PACKAGES]
4196 \[DEFAULT-PACKAGES]
4197 \\pagestyle{empty} % do not remove
4198 % The settings below are copied from fullpage.sty
4199 \\setlength{\\textwidth}{\\paperwidth}
4200 \\addtolength{\\textwidth}{-3cm}
4201 \\setlength{\\oddsidemargin}{1.5cm}
4202 \\addtolength{\\oddsidemargin}{-2.54cm}
4203 \\setlength{\\evensidemargin}{\\oddsidemargin}
4204 \\setlength{\\textheight}{\\paperheight}
4205 \\addtolength{\\textheight}{-\\headheight}
4206 \\addtolength{\\textheight}{-\\headsep}
4207 \\addtolength{\\textheight}{-\\footskip}
4208 \\addtolength{\\textheight}{-3cm}
4209 \\setlength{\\topmargin}{1.5cm}
4210 \\addtolength{\\topmargin}{-2.54cm}"
4211 "The document header used for processing LaTeX fragments.
4212 It is imperative that this header make sure that no page number
4213 appears on the page. The package defined in the variables
4214 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4215 will either replace the placeholder \"[PACKAGES]\" in this
4216 header, or they will be appended."
4217 :group 'org-latex
4218 :type 'string)
4220 (defun org-set-packages-alist (var val)
4221 "Set the packages alist and make sure it has 3 elements per entry."
4222 (set var (mapcar (lambda (x)
4223 (if (and (consp x) (= (length x) 2))
4224 (list (car x) (nth 1 x) t)
4226 val)))
4228 (defun org-get-packages-alist (var)
4229 "Get the packages alist and make sure it has 3 elements per entry."
4230 (mapcar (lambda (x)
4231 (if (and (consp x) (= (length x) 2))
4232 (list (car x) (nth 1 x) t)
4234 (default-value var)))
4236 (defcustom org-latex-default-packages-alist
4237 '(("AUTO" "inputenc" t ("pdflatex"))
4238 ("T1" "fontenc" t ("pdflatex"))
4239 ("" "graphicx" t)
4240 ("" "grffile" t)
4241 ("" "longtable" nil)
4242 ("" "wrapfig" nil)
4243 ("" "rotating" nil)
4244 ("normalem" "ulem" t)
4245 ("" "amsmath" t)
4246 ("" "textcomp" t)
4247 ("" "amssymb" t)
4248 ("" "capt-of" nil)
4249 ("" "hyperref" nil))
4250 "Alist of default packages to be inserted in the header.
4252 Change this only if one of the packages here causes an
4253 incompatibility with another package you are using.
4255 The packages in this list are needed by one part or another of
4256 Org mode to function properly:
4258 - inputenc, fontenc: for basic font and character selection
4259 - graphicx: for including images
4260 - grffile: allow periods and spaces in graphics file names
4261 - longtable: For multipage tables
4262 - wrapfig: for figure placement
4263 - rotating: for sideways figures and tables
4264 - ulem: for underline and strike-through
4265 - amsmath: for subscript and superscript and math environments
4266 - textcomp, amssymb: for various symbols used
4267 for interpreting the entities in `org-entities'. You can skip
4268 some of these packages if you don't use any of their symbols.
4269 - capt-of: for captions outside of floats
4270 - hyperref: for cross references
4272 Therefore you should not modify this variable unless you know
4273 what you are doing. The one reason to change it anyway is that
4274 you might be loading some other package that conflicts with one
4275 of the default packages. Each element is either a cell or
4276 a string.
4278 A cell is of the format
4280 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4282 If SNIPPET-FLAG is non-nil, the package also needs to be included
4283 when compiling LaTeX snippets into images for inclusion into
4284 non-LaTeX output. COMPILERS is a list of compilers that should
4285 include the package, see `org-latex-compiler'. If the document
4286 compiler is not in the list, and the list is non-nil, the package
4287 will not be inserted in the final document.
4289 A string will be inserted as-is in the header of the document."
4290 :group 'org-latex
4291 :group 'org-export-latex
4292 :set 'org-set-packages-alist
4293 :get 'org-get-packages-alist
4294 :version "25.2"
4295 :package-version '(Org . "8.3")
4296 :type '(repeat
4297 (choice
4298 (list :tag "options/package pair"
4299 (string :tag "options")
4300 (string :tag "package")
4301 (boolean :tag "Snippet"))
4302 (string :tag "A line of LaTeX"))))
4304 (defcustom org-latex-packages-alist nil
4305 "Alist of packages to be inserted in every LaTeX header.
4307 These will be inserted after `org-latex-default-packages-alist'.
4308 Each element is either a cell or a string.
4310 A cell is of the format:
4312 (\"options\" \"package\" SNIPPET-FLAG)
4314 SNIPPET-FLAG, when non-nil, indicates that this package is also
4315 needed when turning LaTeX snippets into images for inclusion into
4316 non-LaTeX output.
4318 A string will be inserted as-is in the header of the document.
4320 Make sure that you only list packages here which:
4322 - you want in every file;
4323 - do not conflict with the setup in `org-format-latex-header';
4324 - do not conflict with the default packages in
4325 `org-latex-default-packages-alist'."
4326 :group 'org-latex
4327 :group 'org-export-latex
4328 :set 'org-set-packages-alist
4329 :get 'org-get-packages-alist
4330 :type '(repeat
4331 (choice
4332 (list :tag "options/package pair"
4333 (string :tag "options")
4334 (string :tag "package")
4335 (boolean :tag "Snippet"))
4336 (string :tag "A line of LaTeX"))))
4338 (defgroup org-appearance nil
4339 "Settings for Org mode appearance."
4340 :tag "Org Appearance"
4341 :group 'org)
4343 (defcustom org-level-color-stars-only nil
4344 "Non-nil means fontify only the stars in each headline.
4345 When nil, the entire headline is fontified.
4346 Changing it requires restart of `font-lock-mode' to become effective
4347 also in regions already fontified."
4348 :group 'org-appearance
4349 :type 'boolean)
4351 (defcustom org-hide-leading-stars nil
4352 "Non-nil means hide the first N-1 stars in a headline.
4353 This works by using the face `org-hide' for these stars. This
4354 face is white for a light background, and black for a dark
4355 background. You may have to customize the face `org-hide' to
4356 make this work.
4357 Changing it requires restart of `font-lock-mode' to become effective
4358 also in regions already fontified.
4359 You may also set this on a per-file basis by adding one of the following
4360 lines to the buffer:
4362 #+STARTUP: hidestars
4363 #+STARTUP: showstars"
4364 :group 'org-appearance
4365 :type 'boolean)
4367 (defcustom org-hidden-keywords nil
4368 "List of symbols corresponding to keywords to be hidden the org buffer.
4369 For example, a value \\='(title) for this list will make the document's title
4370 appear in the buffer without the initial #+TITLE: keyword."
4371 :group 'org-appearance
4372 :version "24.1"
4373 :type '(set (const :tag "#+AUTHOR" author)
4374 (const :tag "#+DATE" date)
4375 (const :tag "#+EMAIL" email)
4376 (const :tag "#+TITLE" title)))
4378 (defcustom org-custom-properties nil
4379 "List of properties (as strings) with a special meaning.
4380 The default use of these custom properties is to let the user
4381 hide them with `org-toggle-custom-properties-visibility'."
4382 :group 'org-properties
4383 :group 'org-appearance
4384 :version "24.3"
4385 :type '(repeat (string :tag "Property Name")))
4387 (defcustom org-fontify-done-headline nil
4388 "Non-nil means change the face of a headline if it is marked DONE.
4389 Normally, only the TODO/DONE keyword indicates the state of a headline.
4390 When this is non-nil, the headline after the keyword is set to the
4391 `org-headline-done' as an additional indication."
4392 :group 'org-appearance
4393 :type 'boolean)
4395 (defcustom org-fontify-emphasized-text t
4396 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4397 Changing this variable requires a restart of Emacs to take effect."
4398 :group 'org-appearance
4399 :type 'boolean)
4401 (defcustom org-fontify-whole-heading-line nil
4402 "Non-nil means fontify the whole line for headings.
4403 This is useful when setting a background color for the
4404 org-level-* faces."
4405 :group 'org-appearance
4406 :type 'boolean)
4408 (defcustom org-highlight-latex-and-related nil
4409 "Non-nil means highlight LaTeX related syntax in the buffer.
4410 When non nil, the value should be a list containing any of the
4411 following symbols:
4412 `latex' Highlight LaTeX snippets and environments.
4413 `script' Highlight subscript and superscript.
4414 `entities' Highlight entities."
4415 :group 'org-appearance
4416 :version "24.4"
4417 :package-version '(Org . "8.0")
4418 :type '(choice
4419 (const :tag "No highlighting" nil)
4420 (set :greedy t :tag "Highlight"
4421 (const :tag "LaTeX snippets and environments" latex)
4422 (const :tag "Subscript and superscript" script)
4423 (const :tag "Entities" entities))))
4425 (defcustom org-hide-emphasis-markers nil
4426 "Non-nil mean font-lock should hide the emphasis marker characters."
4427 :group 'org-appearance
4428 :type 'boolean)
4430 (defcustom org-hide-macro-markers nil
4431 "Non-nil mean font-lock should hide the brackets marking macro calls."
4432 :group 'org-appearance
4433 :type 'boolean)
4435 (defcustom org-pretty-entities nil
4436 "Non-nil means show entities as UTF8 characters.
4437 When nil, the \\name form remains in the buffer."
4438 :group 'org-appearance
4439 :version "24.1"
4440 :type 'boolean)
4442 (defcustom org-pretty-entities-include-sub-superscripts t
4443 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4444 :group 'org-appearance
4445 :version "24.1"
4446 :type 'boolean)
4448 (defvar org-emph-re nil
4449 "Regular expression for matching emphasis.
4450 After a match, the match groups contain these elements:
4451 0 The match of the full regular expression, including the characters
4452 before and after the proper match
4453 1 The character before the proper match, or empty at beginning of line
4454 2 The proper match, including the leading and trailing markers
4455 3 The leading marker like * or /, indicating the type of highlighting
4456 4 The text between the emphasis markers, not including the markers
4457 5 The character after the match, empty at the end of a line")
4458 (defvar org-verbatim-re nil
4459 "Regular expression for matching verbatim text.")
4460 (defvar org-emphasis-regexp-components) ; defined just below
4461 (defvar org-emphasis-alist) ; defined just below
4462 (defun org-set-emph-re (var val)
4463 "Set variable and compute the emphasis regular expression."
4464 (set var val)
4465 (when (and (boundp 'org-emphasis-alist)
4466 (boundp 'org-emphasis-regexp-components)
4467 org-emphasis-alist org-emphasis-regexp-components)
4468 (let* ((e org-emphasis-regexp-components)
4469 (pre (car e))
4470 (post (nth 1 e))
4471 (border (nth 2 e))
4472 (body (nth 3 e))
4473 (nl (nth 4 e))
4474 (body1 (concat body "*?"))
4475 (markers (mapconcat 'car org-emphasis-alist ""))
4476 (vmarkers (mapconcat
4477 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4478 org-emphasis-alist "")))
4479 ;; make sure special characters appear at the right position in the class
4480 (if (string-match "\\^" markers)
4481 (setq markers (concat (replace-match "" t t markers) "^")))
4482 (if (string-match "-" markers)
4483 (setq markers (concat (replace-match "" t t markers) "-")))
4484 (if (string-match "\\^" vmarkers)
4485 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4486 (if (string-match "-" vmarkers)
4487 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4488 (if (> nl 0)
4489 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4490 (int-to-string nl) "\\}")))
4491 ;; Make the regexp
4492 (setq org-emph-re
4493 (concat "\\([" pre "]\\|^\\)"
4494 "\\("
4495 "\\([" markers "]\\)"
4496 "\\("
4497 "[^" border "]\\|"
4498 "[^" border "]"
4499 body1
4500 "[^" border "]"
4501 "\\)"
4502 "\\3\\)"
4503 "\\([" post "]\\|$\\)"))
4504 (setq org-verbatim-re
4505 (concat "\\([" pre "]\\|^\\)"
4506 "\\("
4507 "\\([" vmarkers "]\\)"
4508 "\\("
4509 "[^" border "]\\|"
4510 "[^" border "]"
4511 body1
4512 "[^" border "]"
4513 "\\)"
4514 "\\3\\)"
4515 "\\([" post "]\\|$\\)")))))
4517 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4518 ;; set this option proved cumbersome. See this message/thread:
4519 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4520 (defvar org-emphasis-regexp-components
4521 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4522 "Components used to build the regular expression for emphasis.
4523 This is a list with five entries. Terminology: In an emphasis string
4524 like \" *strong word* \", we call the initial space PREMATCH, the final
4525 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4526 and \"trong wor\" is the body. The different components in this variable
4527 specify what is allowed/forbidden in each part:
4529 pre Chars allowed as prematch. Beginning of line will be allowed too.
4530 post Chars allowed as postmatch. End of line will be allowed too.
4531 border The chars *forbidden* as border characters.
4532 body-regexp A regexp like \".\" to match a body character. Don't use
4533 non-shy groups here, and don't allow newline here.
4534 newline The maximum number of newlines allowed in an emphasis exp.
4536 You need to reload Org or to restart Emacs after customizing this.")
4538 (defcustom org-emphasis-alist
4539 '(("*" bold)
4540 ("/" italic)
4541 ("_" underline)
4542 ("=" org-verbatim verbatim)
4543 ("~" org-code verbatim)
4544 ("+" (:strike-through t)))
4545 "Alist of characters and faces to emphasize text.
4546 Text starting and ending with a special character will be emphasized,
4547 for example *bold*, _underlined_ and /italic/. This variable sets the
4548 marker characters and the face to be used by font-lock for highlighting
4549 in Org buffers.
4551 You need to reload Org or to restart Emacs after customizing this."
4552 :group 'org-appearance
4553 :set 'org-set-emph-re
4554 :version "24.4"
4555 :package-version '(Org . "8.0")
4556 :type '(repeat
4557 (list
4558 (string :tag "Marker character")
4559 (choice
4560 (face :tag "Font-lock-face")
4561 (plist :tag "Face property list"))
4562 (option (const verbatim)))))
4564 (defvar org-protecting-blocks '("src" "example" "export")
4565 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4566 This is needed for font-lock setup.")
4568 ;;; Functions and variables from their packages
4569 ;; Declared here to avoid compiler warnings
4570 (defvar mark-active)
4572 ;; Various packages
4573 (declare-function calc-eval "calc" (str &optional separator &rest args))
4574 (declare-function calendar-forward-day "cal-move" (arg))
4575 (declare-function calendar-goto-date "cal-move" (date))
4576 (declare-function calendar-goto-today "cal-move" ())
4577 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4578 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4579 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4580 (declare-function cdlatex-tab "ext:cdlatex" ())
4581 (declare-function dired-get-filename
4582 "dired"
4583 (&optional localp no-error-if-not-filep))
4584 (declare-function iswitchb-read-buffer
4585 "iswitchb"
4586 (prompt &optional
4587 default require-match _predicate start matches-set))
4588 (declare-function org-agenda-change-all-lines
4589 "org-agenda"
4590 (newhead hdmarker &optional fixface just-this))
4591 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4592 "org-agenda"
4593 (&optional end))
4594 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4595 (declare-function org-agenda-format-item
4596 "org-agenda"
4597 (extra txt &optional level category tags dotime
4598 remove-re habitp))
4599 (declare-function org-agenda-maybe-redo "org-agenda" ())
4600 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4601 (declare-function org-agenda-save-markers-for-cut-and-paste
4602 "org-agenda"
4603 (beg end))
4604 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4605 (declare-function org-agenda-skip "org-agenda" ())
4606 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4607 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4608 (declare-function org-indent-mode "org-indent" (&optional arg))
4609 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4610 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4611 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4612 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4613 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4614 (declare-function parse-time-string "parse-time" (string))
4615 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4617 (defvar align-mode-rules-list)
4618 (defvar calc-embedded-close-formula)
4619 (defvar calc-embedded-open-formula)
4620 (defvar calc-embedded-open-mode)
4621 (defvar font-lock-unfontify-region-function)
4622 (defvar iswitchb-temp-buflist)
4623 (defvar org-agenda-tags-todo-honor-ignore-options)
4624 (defvar remember-data-file)
4625 (defvar texmathp-why)
4627 ;;;###autoload
4628 (defun turn-on-orgtbl ()
4629 "Unconditionally turn on `orgtbl-mode'."
4630 (require 'org-table)
4631 (orgtbl-mode 1))
4633 (defun org-at-table-p (&optional table-type)
4634 "Non-nil if the cursor is inside an Org table.
4635 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4636 If `org-enable-table-editor' is nil, return nil unconditionally."
4637 (and
4638 org-enable-table-editor
4639 (save-excursion
4640 (beginning-of-line)
4641 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4642 (or (not (derived-mode-p 'org-mode))
4643 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4644 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4646 (defun org-at-table.el-p ()
4647 "Non-nil when point is at a table.el table."
4648 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4649 (let ((element (org-element-at-point)))
4650 (and (eq (org-element-type element) 'table)
4651 (eq (org-element-property :type element) 'table.el)))))
4653 (defun org-at-table-hline-p ()
4654 "Non-nil when point is inside a hline in a table.
4655 Assume point is already in a table. If `org-enable-table-editor'
4656 is nil, return nil unconditionally."
4657 (and org-enable-table-editor
4658 (save-excursion
4659 (beginning-of-line)
4660 (looking-at org-table-hline-regexp))))
4662 (defun org-table-map-tables (function &optional quietly)
4663 "Apply FUNCTION to the start of all tables in the buffer."
4664 (org-with-wide-buffer
4665 (goto-char (point-min))
4666 (while (re-search-forward org-table-any-line-regexp nil t)
4667 (unless quietly
4668 (message "Mapping tables: %d%%"
4669 (floor (* 100.0 (point)) (buffer-size))))
4670 (beginning-of-line 1)
4671 (when (and (looking-at org-table-line-regexp)
4672 ;; Exclude tables in src/example/verbatim/clocktable blocks
4673 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4674 (save-excursion (funcall function))
4675 (or (looking-at org-table-line-regexp)
4676 (forward-char 1)))
4677 (re-search-forward org-table-any-border-regexp nil 1)))
4678 (unless quietly (message "Mapping tables: done")))
4680 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4681 (declare-function org-clock-update-mode-line "org-clock" ())
4682 (declare-function org-resolve-clocks "org-clock"
4683 (&optional also-non-dangling-p prompt last-valid))
4685 (defun org-at-TBLFM-p (&optional pos)
4686 "Non-nil when point (or POS) is in #+TBLFM line."
4687 (save-excursion
4688 (goto-char (or pos (point)))
4689 (beginning-of-line)
4690 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4691 (eq (org-element-type (org-element-at-point)) 'table))))
4693 (defvar org-clock-start-time)
4694 (defvar org-clock-marker (make-marker)
4695 "Marker recording the last clock-in.")
4696 (defvar org-clock-hd-marker (make-marker)
4697 "Marker recording the last clock-in, but the headline position.")
4698 (defvar org-clock-heading ""
4699 "The heading of the current clock entry.")
4700 (defun org-clock-is-active ()
4701 "Return the buffer where the clock is currently running.
4702 Return nil if no clock is running."
4703 (marker-buffer org-clock-marker))
4705 (defun org-check-running-clock ()
4706 "Check if the current buffer contains the running clock.
4707 If yes, offer to stop it and to save the buffer with the changes."
4708 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4709 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4710 (buffer-name))))
4711 (org-clock-out)
4712 (when (y-or-n-p "Save changed buffer?")
4713 (save-buffer))))
4715 (defun org-clocktable-try-shift (dir n)
4716 "Check if this line starts a clock table, if yes, shift the time block."
4717 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4718 (org-clocktable-shift dir n)))
4720 ;;;###autoload
4721 (defun org-clock-persistence-insinuate ()
4722 "Set up hooks for clock persistence."
4723 (require 'org-clock)
4724 (add-hook 'org-mode-hook 'org-clock-load)
4725 (add-hook 'kill-emacs-hook 'org-clock-save))
4727 (defgroup org-archive nil
4728 "Options concerning archiving in Org mode."
4729 :tag "Org Archive"
4730 :group 'org-structure)
4732 (defcustom org-archive-location "%s_archive::"
4733 "The location where subtrees should be archived.
4735 The value of this variable is a string, consisting of two parts,
4736 separated by a double-colon. The first part is a filename and
4737 the second part is a headline.
4739 When the filename is omitted, archiving happens in the same file.
4740 %s in the filename will be replaced by the current file
4741 name (without the directory part). Archiving to a different file
4742 is useful to keep archived entries from contributing to the
4743 Org Agenda.
4745 The archived entries will be filed as subtrees of the specified
4746 headline. When the headline is omitted, the subtrees are simply
4747 filed away at the end of the file, as top-level entries. Also in
4748 the heading you can use %s to represent the file name, this can be
4749 useful when using the same archive for a number of different files.
4751 Here are a few examples:
4752 \"%s_archive::\"
4753 If the current file is Projects.org, archive in file
4754 Projects.org_archive, as top-level trees. This is the default.
4756 \"::* Archived Tasks\"
4757 Archive in the current file, under the top-level headline
4758 \"* Archived Tasks\".
4760 \"~/org/archive.org::\"
4761 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4763 \"~/org/archive.org::* From %s\"
4764 Archive in file ~/org/archive.org (absolute path), under headlines
4765 \"From FILENAME\" where file name is the current file name.
4767 \"~/org/datetree.org::datetree/* Finished Tasks\"
4768 The \"datetree/\" string is special, signifying to archive
4769 items to the datetree. Items are placed in either the CLOSED
4770 date of the item, or the current date if there is no CLOSED date.
4771 The heading will be a subentry to the current date. There doesn't
4772 need to be a heading, but there always needs to be a slash after
4773 datetree. For example, to store archived items directly in the
4774 datetree, use \"~/org/datetree.org::datetree/\".
4776 \"basement::** Finished Tasks\"
4777 Archive in file ./basement (relative path), as level 3 trees
4778 below the level 2 heading \"** Finished Tasks\".
4780 You may set this option on a per-file basis by adding to the buffer a
4781 line like
4783 #+ARCHIVE: basement::** Finished Tasks
4785 You may also define it locally for a subtree by setting an ARCHIVE property
4786 in the entry. If such a property is found in an entry, or anywhere up
4787 the hierarchy, it will be used."
4788 :group 'org-archive
4789 :type 'string)
4791 (defcustom org-agenda-skip-archived-trees t
4792 "Non-nil means the agenda will skip any items located in archived trees.
4793 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4794 variable is no longer recommended, you should leave it at the value t.
4795 Instead, use the key `v' to cycle the archives-mode in the agenda."
4796 :group 'org-archive
4797 :group 'org-agenda-skip
4798 :type 'boolean)
4800 (defcustom org-columns-skip-archived-trees t
4801 "Non-nil means ignore archived trees when creating column view."
4802 :group 'org-archive
4803 :group 'org-properties
4804 :type 'boolean)
4806 (defcustom org-cycle-open-archived-trees nil
4807 "Non-nil means `org-cycle' will open archived trees.
4808 An archived tree is a tree marked with the tag ARCHIVE.
4809 When nil, archived trees will stay folded. You can still open them with
4810 normal outline commands like `show-all', but not with the cycling commands."
4811 :group 'org-archive
4812 :group 'org-cycle
4813 :type 'boolean)
4815 (defcustom org-sparse-tree-open-archived-trees nil
4816 "Non-nil means sparse tree construction shows matches in archived trees.
4817 When nil, matches in these trees are highlighted, but the trees are kept in
4818 collapsed state."
4819 :group 'org-archive
4820 :group 'org-sparse-trees
4821 :type 'boolean)
4823 (defcustom org-sparse-tree-default-date-type nil
4824 "The default date type when building a sparse tree.
4825 When this is nil, a date is a scheduled or a deadline timestamp.
4826 Otherwise, these types are allowed:
4828 all: all timestamps
4829 active: only active timestamps (<...>)
4830 inactive: only inactive timestamps ([...])
4831 scheduled: only scheduled timestamps
4832 deadline: only deadline timestamps"
4833 :type '(choice (const :tag "Scheduled or deadline" nil)
4834 (const :tag "All timestamps" all)
4835 (const :tag "Only active timestamps" active)
4836 (const :tag "Only inactive timestamps" inactive)
4837 (const :tag "Only scheduled timestamps" scheduled)
4838 (const :tag "Only deadline timestamps" deadline)
4839 (const :tag "Only closed timestamps" closed))
4840 :version "25.2"
4841 :package-version '(Org . "8.3")
4842 :group 'org-sparse-trees)
4844 (defun org-cycle-hide-archived-subtrees (state)
4845 "Re-hide all archived subtrees after a visibility state change."
4846 (when (and (not org-cycle-open-archived-trees)
4847 (not (memq state '(overview folded))))
4848 (save-excursion
4849 (let* ((globalp (memq state '(contents all)))
4850 (beg (if globalp (point-min) (point)))
4851 (end (if globalp (point-max) (org-end-of-subtree t))))
4852 (org-hide-archived-subtrees beg end)
4853 (goto-char beg)
4854 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4855 (message "%s" (substitute-command-keys
4856 "Subtree is archived and stays closed. Use \
4857 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4859 (defun org-force-cycle-archived ()
4860 "Cycle subtree even if it is archived."
4861 (interactive)
4862 (setq this-command 'org-cycle)
4863 (let ((org-cycle-open-archived-trees t))
4864 (call-interactively 'org-cycle)))
4866 (defun org-hide-archived-subtrees (beg end)
4867 "Re-hide all archived subtrees after a visibility state change."
4868 (org-with-wide-buffer
4869 (let ((case-fold-search nil)
4870 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4871 (goto-char beg)
4872 ;; Include headline point is currently on.
4873 (beginning-of-line)
4874 (while (and (< (point) end) (re-search-forward re end t))
4875 (when (member org-archive-tag (org-get-tags))
4876 (org-flag-subtree t)
4877 (org-end-of-subtree t))))))
4879 (declare-function outline-end-of-heading "outline" ())
4880 (declare-function outline-flag-region "outline" (from to flag))
4881 (defun org-flag-subtree (flag)
4882 (save-excursion
4883 (org-back-to-heading t)
4884 (outline-end-of-heading)
4885 (outline-flag-region (point)
4886 (progn (org-end-of-subtree t) (point))
4887 flag)))
4889 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4891 ;; Declare Column View Code
4893 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4894 (declare-function org-columns-compute "org-colview" (property))
4896 ;; Declare ID code
4898 (declare-function org-id-store-link "org-id")
4899 (declare-function org-id-locations-load "org-id")
4900 (declare-function org-id-locations-save "org-id")
4901 (defvar org-id-track-globally)
4903 ;;; Variables for pre-computed regular expressions, all buffer local
4905 (defvar-local org-todo-regexp nil
4906 "Matches any of the TODO state keywords.")
4907 (defvar-local org-not-done-regexp nil
4908 "Matches any of the TODO state keywords except the last one.")
4909 (defvar-local org-not-done-heading-regexp nil
4910 "Matches a TODO headline that is not done.")
4911 (defvar-local org-todo-line-regexp nil
4912 "Matches a headline and puts TODO state into group 2 if present.")
4913 (defvar-local org-complex-heading-regexp nil
4914 "Matches a headline and puts everything into groups:
4916 group 1: the stars
4917 group 2: The todo keyword, maybe
4918 group 3: Priority cookie
4919 group 4: True headline
4920 group 5: Tags
4922 Since TODO keywords are case-sensitive, `case-fold-search' is
4923 expected to be bound to nil when matching this regexp.")
4924 (defvar-local org-complex-heading-regexp-format nil
4925 "Printf format to make regexp to match an exact headline.
4926 This regexp will match the headline of any node which has the
4927 exact headline text that is put into the format, but may have any
4928 TODO state, priority and tags.")
4929 (defvar-local org-todo-line-tags-regexp nil
4930 "Matches a headline and puts TODO state into group 2 if present.
4931 Also put tags into group 4 if tags are present.")
4933 (defconst org-plain-time-of-day-regexp
4934 (concat
4935 "\\(\\<[012]?[0-9]"
4936 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4937 "\\(--?"
4938 "\\(\\<[012]?[0-9]"
4939 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4940 "\\)?")
4941 "Regular expression to match a plain time or time range.
4942 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4943 groups carry important information:
4944 0 the full match
4945 1 the first time, range or not
4946 8 the second time, if it is a range.")
4948 (defconst org-plain-time-extension-regexp
4949 (concat
4950 "\\(\\<[012]?[0-9]"
4951 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4952 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4953 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4954 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4955 groups carry important information:
4956 0 the full match
4957 7 hours of duration
4958 9 minutes of duration")
4960 (defconst org-stamp-time-of-day-regexp
4961 (concat
4962 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4963 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4964 "\\(--?"
4965 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4966 "Regular expression to match a timestamp time or time range.
4967 After a match, the following groups carry important information:
4968 0 the full match
4969 1 date plus weekday, for back referencing to make sure both times are on the same day
4970 2 the first time, range or not
4971 4 the second time, if it is a range.")
4973 (defconst org-startup-options
4974 '(("fold" org-startup-folded t)
4975 ("overview" org-startup-folded t)
4976 ("nofold" org-startup-folded nil)
4977 ("showall" org-startup-folded nil)
4978 ("showeverything" org-startup-folded showeverything)
4979 ("content" org-startup-folded content)
4980 ("indent" org-startup-indented t)
4981 ("noindent" org-startup-indented nil)
4982 ("hidestars" org-hide-leading-stars t)
4983 ("showstars" org-hide-leading-stars nil)
4984 ("odd" org-odd-levels-only t)
4985 ("oddeven" org-odd-levels-only nil)
4986 ("align" org-startup-align-all-tables t)
4987 ("noalign" org-startup-align-all-tables nil)
4988 ("inlineimages" org-startup-with-inline-images t)
4989 ("noinlineimages" org-startup-with-inline-images nil)
4990 ("latexpreview" org-startup-with-latex-preview t)
4991 ("nolatexpreview" org-startup-with-latex-preview nil)
4992 ("customtime" org-display-custom-times t)
4993 ("logdone" org-log-done time)
4994 ("lognotedone" org-log-done note)
4995 ("nologdone" org-log-done nil)
4996 ("lognoteclock-out" org-log-note-clock-out t)
4997 ("nolognoteclock-out" org-log-note-clock-out nil)
4998 ("logrepeat" org-log-repeat state)
4999 ("lognoterepeat" org-log-repeat note)
5000 ("logdrawer" org-log-into-drawer t)
5001 ("nologdrawer" org-log-into-drawer nil)
5002 ("logstatesreversed" org-log-states-order-reversed t)
5003 ("nologstatesreversed" org-log-states-order-reversed nil)
5004 ("nologrepeat" org-log-repeat nil)
5005 ("logreschedule" org-log-reschedule time)
5006 ("lognotereschedule" org-log-reschedule note)
5007 ("nologreschedule" org-log-reschedule nil)
5008 ("logredeadline" org-log-redeadline time)
5009 ("lognoteredeadline" org-log-redeadline note)
5010 ("nologredeadline" org-log-redeadline nil)
5011 ("logrefile" org-log-refile time)
5012 ("lognoterefile" org-log-refile note)
5013 ("nologrefile" org-log-refile nil)
5014 ("fninline" org-footnote-define-inline t)
5015 ("nofninline" org-footnote-define-inline nil)
5016 ("fnlocal" org-footnote-section nil)
5017 ("fnauto" org-footnote-auto-label t)
5018 ("fnprompt" org-footnote-auto-label nil)
5019 ("fnconfirm" org-footnote-auto-label confirm)
5020 ("fnplain" org-footnote-auto-label plain)
5021 ("fnadjust" org-footnote-auto-adjust t)
5022 ("nofnadjust" org-footnote-auto-adjust nil)
5023 ("constcgs" constants-unit-system cgs)
5024 ("constSI" constants-unit-system SI)
5025 ("noptag" org-tag-persistent-alist nil)
5026 ("hideblocks" org-hide-block-startup t)
5027 ("nohideblocks" org-hide-block-startup nil)
5028 ("beamer" org-startup-with-beamer-mode t)
5029 ("entitiespretty" org-pretty-entities t)
5030 ("entitiesplain" org-pretty-entities nil))
5031 "Variable associated with STARTUP options for org-mode.
5032 Each element is a list of three items: the startup options (as written
5033 in the #+STARTUP line), the corresponding variable, and the value to set
5034 this variable to if the option is found. An optional forth element PUSH
5035 means to push this value onto the list in the variable.")
5037 (defcustom org-group-tags t
5038 "When non-nil (the default), use group tags.
5039 This can be turned on/off through `org-toggle-tags-groups'."
5040 :group 'org-tags
5041 :group 'org-startup
5042 :type 'boolean)
5044 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5046 (defun org-toggle-tags-groups ()
5047 "Toggle support for group tags.
5048 Support for group tags is controlled by the option
5049 `org-group-tags', which is non-nil by default."
5050 (interactive)
5051 (setq org-group-tags (not org-group-tags))
5052 (cond ((and (derived-mode-p 'org-agenda-mode)
5053 org-group-tags)
5054 (org-agenda-redo))
5055 ((derived-mode-p 'org-mode)
5056 (let ((org-inhibit-startup t)) (org-mode))))
5057 (message "Groups tags support has been turned %s"
5058 (if org-group-tags "on" "off")))
5060 (defun org-set-regexps-and-options (&optional tags-only)
5061 "Precompute regular expressions used in the current buffer.
5062 When optional argument TAGS-ONLY is non-nil, only compute tags
5063 related expressions."
5064 (when (derived-mode-p 'org-mode)
5065 (let ((alist (org--setup-collect-keywords
5066 (org-make-options-regexp
5067 (append '("FILETAGS" "TAGS" "SETUPFILE")
5068 (and (not tags-only)
5069 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
5070 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
5071 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
5072 ;; Startup options. Get this early since it does change
5073 ;; behavior for other options (e.g., tags).
5074 (let ((startup (cdr (assq 'startup alist))))
5075 (dolist (option startup)
5076 (let ((entry (assoc-string option org-startup-options t)))
5077 (when entry
5078 (let ((var (nth 1 entry))
5079 (val (nth 2 entry)))
5080 (if (not (nth 3 entry)) (set (make-local-variable var) val)
5081 (unless (listp (symbol-value var))
5082 (set (make-local-variable var) nil))
5083 (add-to-list var val)))))))
5084 (setq-local org-file-tags
5085 (mapcar #'org-add-prop-inherited
5086 (cdr (assq 'filetags alist))))
5087 (setq org-current-tag-alist
5088 (append org-tag-persistent-alist
5089 (let ((tags (cdr (assq 'tags alist))))
5090 (if tags (org-tag-string-to-alist tags)
5091 org-tag-alist))))
5092 (setq org-tag-groups-alist
5093 (org-tag-alist-to-groups org-current-tag-alist))
5094 (unless tags-only
5095 ;; File properties.
5096 (setq-local org-file-properties (cdr (assq 'property alist)))
5097 ;; Archive location.
5098 (let ((archive (cdr (assq 'archive alist))))
5099 (when archive (setq-local org-archive-location archive)))
5100 ;; Category.
5101 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
5102 (when cat
5103 (setq-local org-category (intern cat))
5104 (setq-local org-file-properties
5105 (org--update-property-plist
5106 "CATEGORY" cat org-file-properties))))
5107 ;; Columns.
5108 (let ((column (cdr (assq 'columns alist))))
5109 (when column (setq-local org-columns-default-format column)))
5110 ;; Constants.
5111 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
5112 ;; Link abbreviations.
5113 (let ((links (cdr (assq 'link alist))))
5114 (when links (setq org-link-abbrev-alist-local (nreverse links))))
5115 ;; Priorities.
5116 (let ((priorities (cdr (assq 'priorities alist))))
5117 (when priorities
5118 (setq-local org-highest-priority (nth 0 priorities))
5119 (setq-local org-lowest-priority (nth 1 priorities))
5120 (setq-local org-default-priority (nth 2 priorities))))
5121 ;; Scripts.
5122 (let ((scripts (assq 'scripts alist)))
5123 (when scripts
5124 (setq-local org-use-sub-superscripts (cdr scripts))))
5125 ;; TODO keywords.
5126 (setq-local org-todo-kwd-alist nil)
5127 (setq-local org-todo-key-alist nil)
5128 (setq-local org-todo-key-trigger nil)
5129 (setq-local org-todo-keywords-1 nil)
5130 (setq-local org-done-keywords nil)
5131 (setq-local org-todo-heads nil)
5132 (setq-local org-todo-sets nil)
5133 (setq-local org-todo-log-states nil)
5134 (let ((todo-sequences
5135 (or (nreverse (cdr (assq 'todo alist)))
5136 (let ((d (default-value 'org-todo-keywords)))
5137 (if (not (stringp (car d))) d
5138 ;; XXX: Backward compatibility code.
5139 (list (cons org-todo-interpretation d)))))))
5140 (dolist (sequence todo-sequences)
5141 (let* ((sequence (or (run-hook-with-args-until-success
5142 'org-todo-setup-filter-hook sequence)
5143 sequence))
5144 (sequence-type (car sequence))
5145 (keywords (cdr sequence))
5146 (sep (member "|" keywords))
5147 names alist)
5148 (dolist (k (remove "|" keywords))
5149 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5151 (error "Invalid TODO keyword %s" k))
5152 (let ((name (match-string 1 k))
5153 (key (match-string 2 k))
5154 (log (org-extract-log-state-settings k)))
5155 (push name names)
5156 (push (cons name (and key (string-to-char key))) alist)
5157 (when log (push log org-todo-log-states))))
5158 (let* ((names (nreverse names))
5159 (done (if sep (org-remove-keyword-keys (cdr sep))
5160 (last names)))
5161 (head (car names))
5162 (tail (list sequence-type head (car done) (org-last done))))
5163 (add-to-list 'org-todo-heads head 'append)
5164 (push names org-todo-sets)
5165 (setq org-done-keywords (append org-done-keywords done nil))
5166 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5167 (setq org-todo-key-alist
5168 (append org-todo-key-alist
5169 (and alist
5170 (append '((:startgroup))
5171 (nreverse alist)
5172 '((:endgroup))))))
5173 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5174 (setq org-todo-sets (nreverse org-todo-sets)
5175 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5176 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5177 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5178 ;; Compute the regular expressions and other local variables.
5179 ;; Using `org-outline-regexp-bol' would complicate them much,
5180 ;; because of the fixed white space at the end of that string.
5181 (unless org-done-keywords
5182 (setq org-done-keywords
5183 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5184 (setq org-not-done-keywords
5185 (org-delete-all org-done-keywords
5186 (copy-sequence org-todo-keywords-1))
5187 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5188 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5189 org-not-done-heading-regexp
5190 (format org-heading-keyword-regexp-format org-not-done-regexp)
5191 org-todo-line-regexp
5192 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5193 org-complex-heading-regexp
5194 (concat "^\\(\\*+\\)"
5195 "\\(?: +" org-todo-regexp "\\)?"
5196 "\\(?: +\\(\\[#.\\]\\)\\)?"
5197 "\\(?: +\\(.*?\\)\\)??"
5198 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5199 "[ \t]*$")
5200 org-complex-heading-regexp-format
5201 (concat "^\\(\\*+\\)"
5202 "\\(?: +" org-todo-regexp "\\)?"
5203 "\\(?: +\\(\\[#.\\]\\)\\)?"
5204 "\\(?: +"
5205 ;; Stats cookies can be stuck to body.
5206 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5207 "\\(%s\\)"
5208 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5209 "\\)"
5210 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5211 "[ \t]*$")
5212 org-todo-line-tags-regexp
5213 (concat "^\\(\\*+\\)"
5214 "\\(?: +" org-todo-regexp "\\)?"
5215 "\\(?: +\\(.*?\\)\\)??"
5216 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5217 "[ \t]*$"))
5218 (org-compute-latex-and-related-regexp)))))
5220 (defun org--setup-collect-keywords (regexp &optional files alist)
5221 "Return setup keywords values as an alist.
5223 REGEXP matches a subset of setup keywords. FILES is a list of
5224 file names already visited. It is used to avoid circular setup
5225 files. ALIST, when non-nil, is the alist computed so far.
5227 Return value contains the following keys: `archive', `category',
5228 `columns', `constants', `filetags', `link', `priorities',
5229 `property', `scripts', `startup', `tags' and `todo'."
5230 (org-with-wide-buffer
5231 (goto-char (point-min))
5232 (let ((case-fold-search t))
5233 (while (re-search-forward regexp nil t)
5234 (let ((element (org-element-at-point)))
5235 (when (eq (org-element-type element) 'keyword)
5236 (let ((key (org-element-property :key element))
5237 (value (org-element-property :value element)))
5238 (cond
5239 ((equal key "ARCHIVE")
5240 (when (org-string-nw-p value)
5241 (push (cons 'archive value) alist)))
5242 ((equal key "CATEGORY") (push (cons 'category value) alist))
5243 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5244 ((equal key "CONSTANTS")
5245 (let* ((constants (assq 'constants alist))
5246 (store (cdr constants)))
5247 (dolist (pair (org-split-string value))
5248 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5249 pair)
5250 (let* ((name (match-string 1 pair))
5251 (value (match-string 2 pair))
5252 (old (assoc name store)))
5253 (if old (setcdr old value)
5254 (push (cons name value) store)))))
5255 (if constants (setcdr constants store)
5256 (push (cons 'constants store) alist))))
5257 ((equal key "FILETAGS")
5258 (when (org-string-nw-p value)
5259 (let ((old (assq 'filetags alist))
5260 (new (apply #'nconc
5261 (mapcar (lambda (x) (org-split-string x ":"))
5262 (org-split-string value)))))
5263 (if old (setcdr old (append new (cdr old)))
5264 (push (cons 'filetags new) alist)))))
5265 ((equal key "LINK")
5266 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5267 (let ((links (assq 'link alist))
5268 (pair (cons (match-string-no-properties 1 value)
5269 (match-string-no-properties 2 value))))
5270 (if links (push pair (cdr links))
5271 (push (list 'link pair) alist)))))
5272 ((equal key "OPTIONS")
5273 (when (and (org-string-nw-p value)
5274 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5275 (push (cons 'scripts (read (match-string 1 value))) alist)))
5276 ((equal key "PRIORITIES")
5277 (push (cons 'priorities
5278 (let ((prio (org-split-string value)))
5279 (if (< (length prio) 3) '(?A ?C ?B)
5280 (mapcar #'string-to-char prio))))
5281 alist))
5282 ((equal key "PROPERTY")
5283 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5284 (let* ((property (assq 'property alist))
5285 (value (org--update-property-plist
5286 (match-string-no-properties 1 value)
5287 (match-string-no-properties 2 value)
5288 (cdr property))))
5289 (if property (setcdr property value)
5290 (push (cons 'property value) alist)))))
5291 ((equal key "STARTUP")
5292 (let ((startup (assq 'startup alist)))
5293 (if startup
5294 (setcdr startup
5295 (append (cdr startup) (org-split-string value)))
5296 (push (cons 'startup (org-split-string value)) alist))))
5297 ((equal key "TAGS")
5298 (let ((tag-cell (assq 'tags alist)))
5299 (if tag-cell
5300 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5301 (push (cons 'tags value) alist))))
5302 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5303 (let ((todo (assq 'todo alist))
5304 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5305 (org-split-string value))))
5306 (if todo (push value (cdr todo))
5307 (push (list 'todo value) alist))))
5308 ((equal key "SETUPFILE")
5309 (unless buffer-read-only ; Do not check in Gnus messages.
5310 (let ((f (and (org-string-nw-p value)
5311 (expand-file-name
5312 (org-unbracket-string "\"" "\"" value)))))
5313 (when (and f (file-readable-p f) (not (member f files)))
5314 (with-temp-buffer
5315 (setq default-directory (file-name-directory f))
5316 (insert-file-contents f)
5317 (setq alist
5318 ;; Fake Org mode to benefit from cache
5319 ;; without recurring needlessly.
5320 (let ((major-mode 'org-mode))
5321 (org--setup-collect-keywords
5322 regexp (cons f files) alist)))))))))))))))
5323 alist)
5325 (defun org-tag-string-to-alist (s)
5326 "Return tag alist associated to string S.
5327 S is a value for TAGS keyword or produced with
5328 `org-tag-alist-to-string'. Return value is an alist suitable for
5329 `org-tag-alist' or `org-tag-persistent-alist'."
5330 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5331 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5332 "\\|{.+?}\\)" ; regular expression
5333 "\\(?:(\\(.\\))\\)?\\'"))
5334 alist group-flag)
5335 (dolist (tokens lines (cdr (nreverse alist)))
5336 (push '(:newline) alist)
5337 (while tokens
5338 (let ((token (pop tokens)))
5339 (pcase token
5340 ("{"
5341 (push '(:startgroup) alist)
5342 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5343 ("}"
5344 (push '(:endgroup) alist)
5345 (setq group-flag nil))
5346 ("["
5347 (push '(:startgrouptag) alist)
5348 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5349 ("]"
5350 (push '(:endgrouptag) alist)
5351 (setq group-flag nil))
5352 (":"
5353 (push '(:grouptags) alist))
5354 ((guard (string-match tag-re token))
5355 (let ((tag (match-string 1 token))
5356 (key (and (match-beginning 2)
5357 (string-to-char (match-string 2 token)))))
5358 ;; Push all tags in groups, no matter if they already
5359 ;; appear somewhere else in the list.
5360 (when (or group-flag (not (assoc tag alist)))
5361 (push (cons tag key) alist))))))))))
5363 (defun org-tag-alist-to-string (alist &optional skip-key)
5364 "Return tag string associated to ALIST.
5366 ALIST is an alist, as defined in `org-tag-alist' or
5367 `org-tag-persistent-alist', or produced with
5368 `org-tag-string-to-alist'.
5370 Return value is a string suitable as a value for \"TAGS\"
5371 keyword.
5373 When optional argument SKIP-KEY is non-nil, skip selection keys
5374 next to tags."
5375 (mapconcat (lambda (token)
5376 (pcase token
5377 (`(:startgroup) "{")
5378 (`(:endgroup) "}")
5379 (`(:startgrouptag) "[")
5380 (`(:endgrouptag) "]")
5381 (`(:grouptags) ":")
5382 (`(:newline) "\\n")
5383 ((and
5384 (guard (not skip-key))
5385 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5386 (format "%s(%c)" tag key))
5387 (`(,(and tag (pred stringp)) . ,_) tag)
5388 (_ (user-error "Invalid tag token: %S" token))))
5389 alist
5390 " "))
5392 (defun org-tag-alist-to-groups (alist)
5393 "Return group alist from tag ALIST.
5394 ALIST is an alist, as defined in `org-tag-alist' or
5395 `org-tag-persistent-alist', or produced with
5396 `org-tag-string-to-alist'. Return value is an alist following
5397 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5398 a string, summarizing TAGS, as a list of strings."
5399 (let (groups group-status current-group)
5400 (dolist (token alist (nreverse groups))
5401 (pcase token
5402 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5403 (`(,(or :endgroup :endgrouptag))
5404 (when (eq group-status 'append)
5405 (push (nreverse current-group) groups))
5406 (setq group-status nil))
5407 (`(:grouptags) (setq group-status 'append))
5408 ((and `(,tag . ,_) (guard group-status))
5409 (if (eq group-status 'append) (push tag current-group)
5410 (setq current-group (list tag))))
5411 (_ nil)))))
5413 (defun org-file-contents (file &optional noerror)
5414 "Return the contents of FILE, as a string."
5415 (if (and file (file-readable-p file))
5416 (with-temp-buffer
5417 (insert-file-contents file)
5418 (buffer-string))
5419 (funcall (if noerror 'message 'error)
5420 "Cannot read file \"%s\"%s"
5421 file
5422 (let ((from (buffer-file-name (buffer-base-buffer))))
5423 (if from (concat " (referenced in file \"" from "\")") "")))))
5425 (defun org-extract-log-state-settings (x)
5426 "Extract the log state setting from a TODO keyword string.
5427 This will extract info from a string like \"WAIT(w@/!)\"."
5428 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5429 (let ((kw (match-string 1 x))
5430 (log1 (and (match-end 3) (match-string 3 x)))
5431 (log2 (and (match-end 4) (match-string 4 x))))
5432 (and (or log1 log2)
5433 (list kw
5434 (and log1 (if (equal log1 "!") 'time 'note))
5435 (and log2 (if (equal log2 "!") 'time 'note)))))))
5437 (defun org-remove-keyword-keys (list)
5438 "Remove a pair of parenthesis at the end of each string in LIST."
5439 (mapcar (lambda (x)
5440 (if (string-match "(.*)$" x)
5441 (substring x 0 (match-beginning 0))
5443 list))
5445 (defun org-assign-fast-keys (alist)
5446 "Assign fast keys to a keyword-key alist.
5447 Respect keys that are already there."
5448 (let (new e (alt ?0))
5449 (while (setq e (pop alist))
5450 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5451 (cdr e)) ;; Key already assigned.
5452 (push e new)
5453 (let ((clist (string-to-list (downcase (car e))))
5454 (used (append new alist)))
5455 (when (= (car clist) ?@)
5456 (pop clist))
5457 (while (and clist (rassoc (car clist) used))
5458 (pop clist))
5459 (unless clist
5460 (while (rassoc alt used)
5461 (cl-incf alt)))
5462 (push (cons (car e) (or (car clist) alt)) new))))
5463 (nreverse new)))
5465 ;;; Some variables used in various places
5467 (defvar org-window-configuration nil
5468 "Used in various places to store a window configuration.")
5469 (defvar org-selected-window nil
5470 "Used in various places to store a window configuration.")
5471 (defvar org-finish-function nil
5472 "Function to be called when `C-c C-c' is used.
5473 This is for getting out of special buffers like capture.")
5474 (defvar org-last-state)
5476 ;; Defined somewhere in this file, but used before definition.
5477 (defvar org-entities) ;; defined in org-entities.el
5478 (defvar org-struct-menu)
5479 (defvar org-org-menu)
5480 (defvar org-tbl-menu)
5482 ;;;; Define the Org mode
5484 ;; We use a before-change function to check if a table might need
5485 ;; an update.
5486 (defvar org-table-may-need-update t
5487 "Indicates that a table might need an update.
5488 This variable is set by `org-before-change-function'.
5489 `org-table-align' sets it back to nil.")
5490 (defun org-before-change-function (_beg _end)
5491 "Every change indicates that a table might need an update."
5492 (setq org-table-may-need-update t))
5493 (defvar org-mode-map)
5494 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5495 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5496 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5497 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5498 (defvar org-table-buffer-is-an nil)
5500 (defvar bidi-paragraph-direction)
5501 (defvar buffer-face-mode-face)
5503 (require 'outline)
5505 ;; Other stuff we need.
5506 (require 'time-date)
5507 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5508 (require 'easymenu)
5509 (autoload 'easy-menu-add "easymenu")
5510 (require 'overlay)
5512 ;; (require 'org-macs) moved higher up in the file before it is first used
5513 (require 'org-entities)
5514 ;; (require 'org-compat) moved higher up in the file before it is first used
5515 (require 'org-faces)
5516 (require 'org-list)
5517 (require 'org-pcomplete)
5518 (require 'org-src)
5519 (require 'org-footnote)
5520 (require 'org-macro)
5522 ;; babel
5523 (require 'ob)
5525 ;;;###autoload
5526 (define-derived-mode org-mode outline-mode "Org"
5527 "Outline-based notes management and organizer, alias
5528 \"Carsten's outline-mode for keeping track of everything.\"
5530 Org mode develops organizational tasks around a NOTES file which
5531 contains information about projects as plain text. Org mode is
5532 implemented on top of Outline mode, which is ideal to keep the content
5533 of large files well structured. It supports ToDo items, deadlines and
5534 time stamps, which magically appear in the diary listing of the Emacs
5535 calendar. Tables are easily created with a built-in table editor.
5536 Plain text URL-like links connect to websites, emails (VM), Usenet
5537 messages (Gnus), BBDB entries, and any files related to the project.
5538 For printing and sharing of notes, an Org file (or a part of it)
5539 can be exported as a structured ASCII or HTML file.
5541 The following commands are available:
5543 \\{org-mode-map}"
5545 ;; Get rid of Outline menus, they are not needed
5546 ;; Need to do this here because define-derived-mode sets up
5547 ;; the keymap so late. Still, it is a waste to call this each time
5548 ;; we switch another buffer into Org mode.
5549 (define-key org-mode-map [menu-bar headings] 'undefined)
5550 (define-key org-mode-map [menu-bar hide] 'undefined)
5551 (define-key org-mode-map [menu-bar show] 'undefined)
5553 (org-load-modules-maybe)
5554 (org-install-agenda-files-menu)
5555 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5556 (add-to-invisibility-spec '(org-cwidth))
5557 (add-to-invisibility-spec '(org-hide-block . t))
5558 (setq-local outline-regexp org-outline-regexp)
5559 (setq-local outline-level 'org-outline-level)
5560 (setq bidi-paragraph-direction 'left-to-right)
5561 (when (and org-ellipsis
5562 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5563 (fboundp 'make-glyph-code))
5564 (unless org-display-table
5565 (setq org-display-table (make-display-table)))
5566 (set-display-table-slot
5567 org-display-table 4
5568 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5569 (if (stringp org-ellipsis) org-ellipsis "..."))))
5570 (setq buffer-display-table org-display-table))
5571 (org-set-regexps-and-options)
5572 (org-set-font-lock-defaults)
5573 (when (and org-tag-faces (not org-tags-special-faces-re))
5574 ;; tag faces set outside customize.... force initialization.
5575 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5576 ;; Calc embedded
5577 (setq-local calc-embedded-open-mode "# ")
5578 ;; Modify a few syntax entries
5579 (modify-syntax-entry ?@ "w")
5580 (modify-syntax-entry ?\" "\"")
5581 (modify-syntax-entry ?\\ "_")
5582 (modify-syntax-entry ?~ "_")
5583 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5584 ;; Activate before-change-function
5585 (setq-local org-table-may-need-update t)
5586 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5587 ;; Check for running clock before killing a buffer
5588 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5589 ;; Initialize macros templates.
5590 (org-macro-initialize-templates)
5591 ;; Initialize radio targets.
5592 (org-update-radio-target-regexp)
5593 ;; Indentation.
5594 (setq-local indent-line-function 'org-indent-line)
5595 (setq-local indent-region-function 'org-indent-region)
5596 ;; Filling and auto-filling.
5597 (org-setup-filling)
5598 ;; Comments.
5599 (org-setup-comments-handling)
5600 ;; Initialize cache.
5601 (org-element-cache-reset)
5602 ;; Beginning/end of defun
5603 (setq-local beginning-of-defun-function 'org-backward-element)
5604 (setq-local end-of-defun-function
5605 (lambda ()
5606 (if (not (org-at-heading-p))
5607 (org-forward-element)
5608 (org-forward-element)
5609 (forward-char -1))))
5610 ;; Next error for sparse trees
5611 (setq-local next-error-function 'org-occur-next-match)
5612 ;; Make sure dependence stuff works reliably, even for users who set it
5613 ;; too late :-(
5614 (if org-enforce-todo-dependencies
5615 (add-hook 'org-blocker-hook
5616 'org-block-todo-from-children-or-siblings-or-parent)
5617 (remove-hook 'org-blocker-hook
5618 'org-block-todo-from-children-or-siblings-or-parent))
5619 (if org-enforce-todo-checkbox-dependencies
5620 (add-hook 'org-blocker-hook
5621 'org-block-todo-from-checkboxes)
5622 (remove-hook 'org-blocker-hook
5623 'org-block-todo-from-checkboxes))
5625 ;; Align options lines
5626 (setq-local
5627 align-mode-rules-list
5628 '((org-in-buffer-settings
5629 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5630 (modes . '(org-mode)))))
5632 ;; Imenu
5633 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5635 ;; Make isearch reveal context
5636 (setq-local outline-isearch-open-invisible-function
5637 (lambda (&rest _) (org-show-context 'isearch)))
5639 ;; Setup the pcomplete hooks
5640 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5641 (setq-local pcomplete-command-name-function 'org-command-at-point)
5642 (setq-local pcomplete-default-completion-function 'ignore)
5643 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5644 (setq-local pcomplete-termination-string "")
5645 (setq-local buffer-face-mode-face 'org-default)
5647 ;; If empty file that did not turn on Org mode automatically, make
5648 ;; it to.
5649 (when (and org-insert-mode-line-in-empty-file
5650 (called-interactively-p 'any)
5651 (= (point-min) (point-max)))
5652 (insert "# -*- mode: org -*-\n\n"))
5653 (unless org-inhibit-startup
5654 (org-unmodified
5655 (when org-startup-with-beamer-mode (org-beamer-mode))
5656 (when org-startup-align-all-tables
5657 (org-table-map-tables #'org-table-align t))
5658 (when org-startup-with-inline-images (org-display-inline-images))
5659 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5660 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5661 (when org-startup-truncated (setq truncate-lines t))
5662 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5663 (org-refresh-effort-properties)))
5664 ;; Try to set `org-hide' face correctly.
5665 (let ((foreground (org-find-invisible-foreground)))
5666 (when foreground
5667 (set-face-foreground 'org-hide foreground))))
5669 ;; Update `customize-package-emacs-version-alist'
5670 (add-to-list 'customize-package-emacs-version-alist
5671 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5672 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5673 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5674 ("9.0" . "25.2")))
5676 (defvar org-mode-transpose-word-syntax-table
5677 (let ((st (make-syntax-table text-mode-syntax-table)))
5678 (dolist (c org-emphasis-alist st)
5679 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5681 (when (fboundp 'abbrev-table-put)
5682 (abbrev-table-put org-mode-abbrev-table
5683 :parents (list text-mode-abbrev-table)))
5685 (defun org-find-invisible-foreground ()
5686 (let ((candidates (remove
5687 "unspecified-bg"
5688 (nconc
5689 (list (face-background 'default)
5690 (face-background 'org-default))
5691 (mapcar
5692 (lambda (alist)
5693 (when (boundp alist)
5694 (cdr (assq 'background-color (symbol-value alist)))))
5695 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5696 (list (face-foreground 'org-hide))))))
5697 (car (remove nil candidates))))
5699 (defun org-current-time (&optional rounding-minutes past)
5700 "Current time, possibly rounded to ROUNDING-MINUTES.
5701 When ROUNDING-MINUTES is not an integer, fall back on the car of
5702 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5703 the rounding returns a past time."
5704 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5705 (car org-time-stamp-rounding-minutes)))
5706 (time (decode-time)) res)
5707 (if (< r 1)
5708 (current-time)
5709 (setq res
5710 (apply 'encode-time
5711 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5712 (nthcdr 2 time))))
5713 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5714 (seconds-to-time (- (float-time res) (* r 60)))
5715 res))))
5717 (defun org-today ()
5718 "Return today date, considering `org-extend-today-until'."
5719 (time-to-days
5720 (time-subtract (current-time)
5721 (list 0 (* 3600 org-extend-today-until) 0))))
5723 ;;;; Font-Lock stuff, including the activators
5725 (defvar org-mouse-map (make-sparse-keymap))
5726 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5727 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5728 (when org-mouse-1-follows-link
5729 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5730 (when org-tab-follows-link
5731 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5732 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5734 (require 'font-lock)
5736 (defconst org-non-link-chars "]\t\n\r<>")
5737 (defvar org-link-types-re nil
5738 "Matches a link that has a url-like prefix like \"http:\"")
5739 (defvar org-link-re-with-space nil
5740 "Matches a link with spaces, optional angular brackets around it.")
5741 (defvar org-link-re-with-space2 nil
5742 "Matches a link with spaces, optional angular brackets around it.")
5743 (defvar org-link-re-with-space3 nil
5744 "Matches a link with spaces, only for internal part in bracket links.")
5745 (defvar org-angle-link-re nil
5746 "Matches link with angular brackets, spaces are allowed.")
5747 (defvar org-plain-link-re nil
5748 "Matches plain link, without spaces.")
5749 (defvar org-bracket-link-regexp nil
5750 "Matches a link in double brackets.")
5751 (defvar org-bracket-link-analytic-regexp nil
5752 "Regular expression used to analyze links.
5753 Here is what the match groups contain after a match:
5754 1: http:
5755 2: http
5756 3: path
5757 4: [desc]
5758 5: desc")
5759 (defvar org-bracket-link-analytic-regexp++ nil
5760 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5761 (defvar org-any-link-re nil
5762 "Regular expression matching any link.")
5764 (defconst org-match-sexp-depth 3
5765 "Number of stacked braces for sub/superscript matching.")
5767 (defun org-create-multibrace-regexp (left right n)
5768 "Create a regular expression which will match a balanced sexp.
5769 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5770 as single character strings.
5771 The regexp returned will match the entire expression including the
5772 delimiters. It will also define a single group which contains the
5773 match except for the outermost delimiters. The maximum depth of
5774 stacked delimiters is N. Escaping delimiters is not possible."
5775 (let* ((nothing (concat "[^" left right "]*?"))
5776 (or "\\|")
5777 (re nothing)
5778 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5779 (while (> n 1)
5780 (setq n (1- n)
5781 re (concat re or next)
5782 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5783 (concat left "\\(" re "\\)" right)))
5785 (defconst org-match-substring-regexp
5786 (concat
5787 "\\(\\S-\\)\\([_^]\\)\\("
5788 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5789 "\\|"
5790 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5791 "\\|"
5792 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5793 "The regular expression matching a sub- or superscript.")
5795 (defconst org-match-substring-with-braces-regexp
5796 (concat
5797 "\\(\\S-\\)\\([_^]\\)"
5798 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5799 "The regular expression matching a sub- or superscript, forcing braces.")
5801 (defun org-make-link-regexps ()
5802 "Update the link regular expressions.
5803 This should be called after the variable `org-link-parameters' has changed."
5804 (let ((types-re (regexp-opt (org-link-types) t)))
5805 (setq org-link-types-re
5806 (concat "\\`" types-re ":")
5807 org-link-re-with-space
5808 (concat "<?" types-re ":"
5809 "\\([^" org-non-link-chars " ]"
5810 "[^" org-non-link-chars "]*"
5811 "[^" org-non-link-chars " ]\\)>?")
5812 org-link-re-with-space2
5813 (concat "<?" types-re ":"
5814 "\\([^" org-non-link-chars " ]"
5815 "[^\t\n\r]*"
5816 "[^" org-non-link-chars " ]\\)>?")
5817 org-link-re-with-space3
5818 (concat "<?" types-re ":"
5819 "\\([^" org-non-link-chars " ]"
5820 "[^\t\n\r]*\\)")
5821 org-angle-link-re
5822 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5823 types-re)
5824 org-plain-link-re
5825 (concat
5826 "\\<" types-re ":"
5827 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5828 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5829 org-bracket-link-regexp
5830 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5831 org-bracket-link-analytic-regexp
5832 (concat
5833 "\\[\\["
5834 "\\(" types-re ":\\)?"
5835 "\\([^]]+\\)"
5836 "\\]"
5837 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5838 "\\]")
5839 org-bracket-link-analytic-regexp++
5840 (concat
5841 "\\[\\["
5842 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5843 "\\([^]]+\\)"
5844 "\\]"
5845 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5846 "\\]")
5847 org-any-link-re
5848 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5849 org-angle-link-re "\\)\\|\\("
5850 org-plain-link-re "\\)"))))
5852 (org-make-link-regexps)
5854 (defvar org-emph-face nil)
5856 (defun org-do-emphasis-faces (limit)
5857 "Run through the buffer and emphasize strings."
5858 (let (rtn a)
5859 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5860 (let* ((border (char-after (match-beginning 3)))
5861 (bre (regexp-quote (char-to-string border))))
5862 (when (and (not (= border (char-after (match-beginning 4))))
5863 (not (string-match-p (concat bre ".*" bre)
5864 (replace-regexp-in-string
5865 "\n" " "
5866 (substring (match-string 2) 1 -1)))))
5867 (setq rtn t)
5868 (setq a (assoc (match-string 3) org-emphasis-alist))
5869 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5870 'face
5871 (nth 1 a))
5872 (and (nth 2 a)
5873 (org-remove-flyspell-overlays-in
5874 (match-beginning 0) (match-end 0)))
5875 (add-text-properties (match-beginning 2) (match-end 2)
5876 '(font-lock-multiline t org-emphasis t))
5877 (when org-hide-emphasis-markers
5878 (add-text-properties (match-end 4) (match-beginning 5)
5879 '(invisible org-link))
5880 (add-text-properties (match-beginning 3) (match-end 3)
5881 '(invisible org-link)))))
5882 (goto-char (1+ (match-beginning 0))))
5883 rtn))
5885 (defun org-emphasize (&optional char)
5886 "Insert or change an emphasis, i.e. a font like bold or italic.
5887 If there is an active region, change that region to a new emphasis.
5888 If there is no region, just insert the marker characters and position
5889 the cursor between them.
5890 CHAR should be the marker character. If it is a space, it means to
5891 remove the emphasis of the selected region.
5892 If CHAR is not given (for example in an interactive call) it will be
5893 prompted for."
5894 (interactive)
5895 (let ((erc org-emphasis-regexp-components)
5896 (string "") beg end move s)
5897 (if (org-region-active-p)
5898 (setq beg (region-beginning)
5899 end (region-end)
5900 string (buffer-substring beg end))
5901 (setq move t))
5903 (unless char
5904 (message "Emphasis marker or tag: [%s]"
5905 (mapconcat #'car org-emphasis-alist ""))
5906 (setq char (read-char-exclusive)))
5907 (if (equal char ?\s)
5908 (setq s ""
5909 move nil)
5910 (unless (assoc (char-to-string char) org-emphasis-alist)
5911 (user-error "No such emphasis marker: \"%c\"" char))
5912 (setq s (char-to-string char)))
5913 (while (and (> (length string) 1)
5914 (equal (substring string 0 1) (substring string -1))
5915 (assoc (substring string 0 1) org-emphasis-alist))
5916 (setq string (substring string 1 -1)))
5917 (setq string (concat s string s))
5918 (when beg (delete-region beg end))
5919 (unless (or (bolp)
5920 (string-match (concat "[" (nth 0 erc) "\n]")
5921 (char-to-string (char-before (point)))))
5922 (insert " "))
5923 (unless (or (eobp)
5924 (string-match (concat "[" (nth 1 erc) "\n]")
5925 (char-to-string (char-after (point)))))
5926 (insert " ") (backward-char 1))
5927 (insert string)
5928 (and move (backward-char 1))))
5930 (defconst org-nonsticky-props
5931 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5933 (defsubst org-rear-nonsticky-at (pos)
5934 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5936 (defun org-activate-plain-links (limit)
5937 "Add link properties for plain links."
5938 (when (and (re-search-forward org-plain-link-re limit t)
5939 (not (org-in-src-block-p)))
5941 (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5942 'face))
5943 (link (match-string-no-properties 0))
5944 (type (match-string-no-properties 1))
5945 (path (match-string-no-properties 2))
5946 (link-start (match-beginning 0))
5947 (link-end (match-end 0))
5948 (link-face (org-link-get-parameter type :face))
5949 (help-echo (org-link-get-parameter type :help-echo))
5950 (htmlize-link (org-link-get-parameter type :htmlize-link))
5951 (activate-func (org-link-get-parameter type :activate-func)))
5952 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5953 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5954 (add-text-properties (match-beginning 0) (match-end 0)
5955 (list
5956 'mouse-face (or (org-link-get-parameter type :mouse-face)
5957 'highlight)
5958 'face (cond
5959 ;; A function that returns a face
5960 ((functionp link-face)
5961 (funcall link-face path))
5962 ;; a face
5963 ((facep link-face)
5964 link-face)
5965 ;; An anonymous face
5966 ((consp link-face)
5967 link-face)
5968 ;; default
5970 'org-link))
5971 'help-echo (cond
5972 ((stringp help-echo)
5973 help-echo)
5974 ((functionp help-echo)
5975 help-echo)
5977 (concat "LINK: "
5978 (save-match-data
5979 (org-link-unescape link)))))
5980 'htmlize-link (cond
5981 ((functionp htmlize-link)
5982 (funcall htmlize-link path))
5984 `(:uri ,link)))
5985 'keymap (or (org-link-get-parameter type :keymap)
5986 org-mouse-map)
5987 'org-link-start (match-beginning 0)))
5988 (org-rear-nonsticky-at (match-end 0))
5989 (when activate-func
5990 (funcall activate-func link-start link-end path nil))
5991 t))))
5993 (defun org-activate-code (limit)
5994 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5995 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5996 (remove-text-properties (match-beginning 0) (match-end 0)
5997 '(display t invisible t intangible t))
6000 (defcustom org-src-fontify-natively t
6001 "When non-nil, fontify code in code blocks.
6002 See also the `org-block' face."
6003 :type 'boolean
6004 :version "24.4"
6005 :package-version '(Org . "8.3")
6006 :group 'org-appearance
6007 :group 'org-babel)
6009 (defcustom org-allow-promoting-top-level-subtree nil
6010 "When non-nil, allow promoting a top level subtree.
6011 The leading star of the top level headline will be replaced
6012 by a #."
6013 :type 'boolean
6014 :version "24.1"
6015 :group 'org-appearance)
6017 (defun org-fontify-meta-lines-and-blocks (limit)
6018 (condition-case nil
6019 (org-fontify-meta-lines-and-blocks-1 limit)
6020 (error (message "org-mode fontification error in %S at %d"
6021 (current-buffer)
6022 (line-number-at-pos)))))
6024 (defun org-fontify-meta-lines-and-blocks-1 (limit)
6025 "Fontify #+ lines and blocks."
6026 (let ((case-fold-search t))
6027 (when (re-search-forward
6028 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
6029 limit t)
6030 (let ((beg (match-beginning 0))
6031 (block-start (match-end 0))
6032 (block-end nil)
6033 (lang (match-string 7))
6034 (beg1 (line-beginning-position 2))
6035 (dc1 (downcase (match-string 2)))
6036 (dc3 (downcase (match-string 3)))
6037 end end1 quoting block-type)
6038 (cond
6039 ((and (match-end 4) (equal dc3 "+begin"))
6040 ;; Truly a block
6041 (setq block-type (downcase (match-string 5))
6042 quoting (member block-type org-protecting-blocks))
6043 (when (re-search-forward
6044 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
6045 nil t) ;; on purpose, we look further than LIMIT
6046 (setq end (min (point-max) (match-end 0))
6047 end1 (min (point-max) (1- (match-beginning 0))))
6048 (setq block-end (match-beginning 0))
6049 (when quoting
6050 (org-remove-flyspell-overlays-in beg1 end1)
6051 (remove-text-properties beg end
6052 '(display t invisible t intangible t)))
6053 (add-text-properties
6054 beg end '(font-lock-fontified t font-lock-multiline t))
6055 (add-text-properties beg beg1 '(face org-meta-line))
6056 (org-remove-flyspell-overlays-in beg beg1)
6057 (add-text-properties ; For end_src
6058 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6059 (org-remove-flyspell-overlays-in end1 end)
6060 (cond
6061 ((and lang (not (string= lang "")) org-src-fontify-natively)
6062 (org-src-font-lock-fontify-block lang block-start block-end)
6063 (add-text-properties beg1 block-end '(src-block t)))
6064 (quoting
6065 (add-text-properties beg1 (min (point-max) (1+ end1))
6066 (list 'face
6067 (list :inherit
6068 (let ((face-name
6069 (intern (format "org-block-%s" lang))))
6070 (append (and (facep face-name) (list face-name))
6071 '(org-block))))))) ; end of source block
6072 ((not org-fontify-quote-and-verse-blocks))
6073 ((string= block-type "quote")
6074 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
6075 ((string= block-type "verse")
6076 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
6077 (add-text-properties beg beg1 '(face org-block-begin-line))
6078 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6079 '(face org-block-end-line))
6081 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6082 (org-remove-flyspell-overlays-in
6083 (match-beginning 0)
6084 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6085 (add-text-properties
6086 beg (match-end 3)
6087 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6088 '(font-lock-fontified t invisible t)
6089 '(font-lock-fontified t face org-document-info-keyword)))
6090 (add-text-properties
6091 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6092 (if (string-equal dc1 "+title:")
6093 '(font-lock-fontified t face org-document-title)
6094 '(font-lock-fontified t face org-document-info))))
6095 ((string-prefix-p "+caption" dc1)
6096 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6097 (remove-text-properties (match-beginning 0) (match-end 0)
6098 '(display t invisible t intangible t))
6099 ;; Handle short captions.
6100 (save-excursion
6101 (beginning-of-line)
6102 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6103 (add-text-properties (line-beginning-position) (match-end 1)
6104 '(font-lock-fontified t face org-meta-line))
6105 (add-text-properties (match-end 0) (line-end-position)
6106 '(font-lock-fontified t face org-block))
6108 ((member dc3 '(" " ""))
6109 (org-remove-flyspell-overlays-in beg (match-end 0))
6110 (add-text-properties
6111 beg (match-end 0)
6112 '(font-lock-fontified t face font-lock-comment-face)))
6113 (t ;; just any other in-buffer setting, but not indented
6114 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6115 (remove-text-properties (match-beginning 0) (match-end 0)
6116 '(display t invisible t intangible t))
6117 (add-text-properties beg (match-end 0)
6118 '(font-lock-fontified t face org-meta-line))
6119 t))))))
6121 (defun org-fontify-drawers (limit)
6122 "Fontify drawers."
6123 (when (re-search-forward org-drawer-regexp limit t)
6124 (add-text-properties
6125 (match-beginning 0) (match-end 0)
6126 '(font-lock-fontified t face org-special-keyword))
6127 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6130 (defun org-fontify-macros (limit)
6131 "Fontify macros."
6132 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6133 (add-text-properties
6134 (match-beginning 0) (match-end 0)
6135 '(font-lock-fontified t face org-macro))
6136 (when org-hide-macro-markers
6137 (add-text-properties (match-end 2) (match-beginning 2)
6138 '(invisible t))
6139 (add-text-properties (match-beginning 1) (match-end 1)
6140 '(invisible t)))
6141 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6144 (defun org-activate-angle-links (limit)
6145 "Add text properties for angle links."
6146 (when (and (re-search-forward org-angle-link-re limit t)
6147 (not (org-in-src-block-p)))
6148 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6149 (add-text-properties (match-beginning 0) (match-end 0)
6150 (list 'mouse-face 'highlight
6151 'keymap org-mouse-map
6152 'font-lock-multiline t))
6153 (org-rear-nonsticky-at (match-end 0))
6156 (defun org-activate-footnote-links (limit)
6157 "Add text properties for footnotes."
6158 (let ((fn (org-footnote-next-reference-or-definition limit)))
6159 (when fn
6160 (let* ((beg (nth 1 fn))
6161 (end (nth 2 fn))
6162 (label (car fn))
6163 (referencep (/= (line-beginning-position) beg)))
6164 (when (and referencep (nth 3 fn))
6165 (save-excursion
6166 (goto-char beg)
6167 (search-forward (or label "fn:"))
6168 (org-remove-flyspell-overlays-in beg (match-end 0))))
6169 (add-text-properties beg end
6170 (list 'mouse-face 'highlight
6171 'keymap org-mouse-map
6172 'help-echo
6173 (if referencep "Footnote reference"
6174 "Footnote definition")
6175 'font-lock-fontified t
6176 'font-lock-multiline t
6177 'face 'org-footnote))))))
6179 (defun org-activate-bracket-links (limit)
6180 "Add text properties for bracketed links."
6181 (when (and (re-search-forward org-bracket-link-regexp limit t)
6182 (not (org-in-src-block-p)))
6183 (let* ((hl (save-match-data
6184 (org-link-expand-abbrev (match-string-no-properties 1))))
6185 (type (save-match-data
6186 (and (string-match org-plain-link-re hl)
6187 (match-string-no-properties 1 hl))))
6188 (path (save-match-data
6189 (and (string-match org-plain-link-re hl)
6190 (match-string-no-properties 2 hl))))
6191 (link-start (match-beginning 0))
6192 (link-end (match-end 0))
6193 (bracketp t)
6194 (help-echo (org-link-get-parameter type :help-echo))
6195 (help (cond
6196 ((stringp help-echo)
6197 help-echo)
6198 ((functionp help-echo)
6199 help-echo)
6201 (concat "LINK: "
6202 (save-match-data
6203 (org-link-unescape hl))))))
6204 (link-face (org-link-get-parameter type :face))
6205 (face (cond
6206 ;; A function that returns a face
6207 ((functionp link-face)
6208 (funcall link-face path))
6209 ;; a face
6210 ((facep link-face)
6211 link-face)
6212 ;; An anonymous face
6213 ((consp link-face)
6214 link-face)
6215 ;; default
6217 'org-link)))
6218 (keymap (or (org-link-get-parameter type :keymap)
6219 org-mouse-map))
6220 (mouse-face (or (org-link-get-parameter type :mouse-face)
6221 'highlight))
6222 (htmlize (org-link-get-parameter type :htmlize-link))
6223 (htmlize-link (cond
6224 ((functionp htmlize)
6225 (funcall htmlize))
6227 `(:uri ,(format "%s:%s" type path)))))
6228 (activate-func (org-link-get-parameter type :activate-func))
6229 ;; invisible part
6230 (ip (list 'invisible (or
6231 (org-link-get-parameter type :display)
6232 'org-link)
6233 'face face
6234 'keymap keymap
6235 'mouse-face mouse-face
6236 'font-lock-multiline t
6237 'help-echo help
6238 'htmlize-link htmlize-link))
6239 ;; visible part
6240 (vp (list 'keymap keymap
6241 'face face
6242 'mouse-face mouse-face
6243 'font-lock-multiline t
6244 'help-echo help
6245 'htmlize-link htmlize-link)))
6246 ;; We need to remove the invisible property here. Table narrowing
6247 ;; may have made some of this invisible.
6248 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6249 (remove-text-properties (match-beginning 0) (match-end 0)
6250 '(invisible nil))
6251 (if (match-end 3)
6252 (progn
6253 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6254 (org-rear-nonsticky-at (match-beginning 3))
6255 (add-text-properties (match-beginning 3) (match-end 3) vp)
6256 (org-rear-nonsticky-at (match-end 3))
6257 (add-text-properties (match-end 3) (match-end 0) ip)
6258 (org-rear-nonsticky-at (match-end 0)))
6259 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6260 (org-rear-nonsticky-at (match-beginning 1))
6261 (add-text-properties (match-beginning 1) (match-end 1) vp)
6262 (org-rear-nonsticky-at (match-end 1))
6263 (add-text-properties (match-end 1) (match-end 0) ip)
6264 (org-rear-nonsticky-at (match-end 0)))
6265 (when activate-func
6266 (funcall activate-func link-start link-end path bracketp))
6267 t)))
6269 (defun org-activate-dates (limit)
6270 "Add text properties for dates."
6271 (when (and (re-search-forward org-tsr-regexp-both limit t)
6272 (not (equal (char-before (match-beginning 0)) 91)))
6273 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6274 (add-text-properties (match-beginning 0) (match-end 0)
6275 (list 'mouse-face 'highlight
6276 'keymap org-mouse-map))
6277 (org-rear-nonsticky-at (match-end 0))
6278 (when org-display-custom-times
6279 (if (match-end 3)
6280 (org-display-custom-time (match-beginning 3) (match-end 3))
6281 (org-display-custom-time (match-beginning 1) (match-end 1))))
6284 (defvar-local org-target-link-regexp nil
6285 "Regular expression matching radio targets in plain text.")
6287 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6288 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6289 border border border))
6290 "Regular expression matching a link target.")
6292 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6293 "Regular expression matching a radio target.")
6295 (defconst org-any-target-regexp
6296 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6297 "Regular expression matching any target.")
6299 (defun org-activate-target-links (limit)
6300 "Add text properties for target matches."
6301 (when org-target-link-regexp
6302 (let ((case-fold-search t))
6303 (when (re-search-forward org-target-link-regexp limit t)
6304 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6305 (add-text-properties (match-beginning 1) (match-end 1)
6306 (list 'mouse-face 'highlight
6307 'keymap org-mouse-map
6308 'help-echo "Radio target link"
6309 'org-linked-text t))
6310 (org-rear-nonsticky-at (match-end 1))
6311 t))))
6313 (defun org-update-radio-target-regexp ()
6314 "Find all radio targets in this file and update the regular expression.
6315 Also refresh fontification if needed."
6316 (interactive)
6317 (let ((old-regexp org-target-link-regexp)
6318 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6319 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6320 (targets
6321 (org-with-wide-buffer
6322 (goto-char (point-min))
6323 (let (rtn)
6324 (while (re-search-forward org-radio-target-regexp nil t)
6325 ;; Make sure point is really within the object.
6326 (backward-char)
6327 (let ((obj (org-element-context)))
6328 (when (eq (org-element-type obj) 'radio-target)
6329 (cl-pushnew (org-element-property :value obj) rtn
6330 :test #'equal))))
6331 rtn))))
6332 (setq org-target-link-regexp
6333 (and targets
6334 (concat before-re
6335 (mapconcat
6336 (lambda (x)
6337 (replace-regexp-in-string
6338 " +" "\\s-+" (regexp-quote x) t t))
6339 targets
6340 "\\|")
6341 after-re)))
6342 (unless (equal old-regexp org-target-link-regexp)
6343 ;; Clean-up cache.
6344 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6345 ((not org-target-link-regexp) old-regexp)
6347 (concat before-re
6348 (mapconcat
6349 (lambda (re)
6350 (substring re (length before-re)
6351 (- (length after-re))))
6352 (list old-regexp org-target-link-regexp)
6353 "\\|")
6354 after-re)))))
6355 (org-with-wide-buffer
6356 (goto-char (point-min))
6357 (while (re-search-forward regexp nil t)
6358 (org-element-cache-refresh (match-beginning 1)))))
6359 ;; Re fontify buffer.
6360 (when (memq 'radio org-highlight-links)
6361 (org-restart-font-lock)))))
6363 (defun org-hide-wide-columns (limit)
6364 (let (s e)
6365 (setq s (text-property-any (point) (or limit (point-max))
6366 'org-cwidth t))
6367 (when s
6368 (setq e (next-single-property-change s 'org-cwidth))
6369 (add-text-properties s e '(invisible org-cwidth))
6370 (goto-char e)
6371 t)))
6373 (defvar org-latex-and-related-regexp nil
6374 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6376 (defun org-compute-latex-and-related-regexp ()
6377 "Compute regular expression for LaTeX, entities and sub/superscript.
6378 Result depends on variable `org-highlight-latex-and-related'."
6379 (setq-local
6380 org-latex-and-related-regexp
6381 (let* ((re-sub
6382 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6383 ((eq org-use-sub-superscripts '{})
6384 (list org-match-substring-with-braces-regexp))
6385 (org-use-sub-superscripts (list org-match-substring-regexp))))
6386 (re-latex
6387 (when (memq 'latex org-highlight-latex-and-related)
6388 (let ((matchers (plist-get org-format-latex-options :matchers)))
6389 (delq nil
6390 (mapcar (lambda (x)
6391 (and (member (car x) matchers) (nth 1 x)))
6392 org-latex-regexps)))))
6393 (re-entities
6394 (when (memq 'entities org-highlight-latex-and-related)
6395 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6396 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6398 (defun org-do-latex-and-related (limit)
6399 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6400 LIMIT bounds the search for syntax to highlight. Stop at first
6401 highlighted object, if any. Return t if some highlighting was
6402 done, nil otherwise."
6403 (when (org-string-nw-p org-latex-and-related-regexp)
6404 (catch 'found
6405 (while (re-search-forward org-latex-and-related-regexp limit t)
6406 (unless
6407 (cl-some
6408 (lambda (f)
6409 (memq f '(org-code org-verbatim underline org-special-keyword)))
6410 (save-excursion
6411 (goto-char (1+ (match-beginning 0)))
6412 (face-at-point nil t)))
6413 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6414 '(?_ ?^))
6416 0)))
6417 (font-lock-prepend-text-property
6418 (+ offset (match-beginning 0)) (match-end 0)
6419 'face 'org-latex-and-related)
6420 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6421 '(font-lock-multiline t)))
6422 (throw 'found t)))
6423 nil)))
6425 (defun org-restart-font-lock ()
6426 "Restart `font-lock-mode', to force refontification."
6427 (when (and (boundp 'font-lock-mode) font-lock-mode)
6428 (font-lock-mode -1)
6429 (font-lock-mode 1)))
6431 (defun org-activate-tags (limit)
6432 (when (re-search-forward
6433 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6434 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6435 (add-text-properties (match-beginning 1) (match-end 1)
6436 (list 'mouse-face 'highlight
6437 'keymap org-mouse-map))
6438 (org-rear-nonsticky-at (match-end 1))
6441 (defun org-outline-level ()
6442 "Compute the outline level of the heading at point.
6444 If this is called at a normal headline, the level is the number
6445 of stars. Use `org-reduced-level' to remove the effect of
6446 `org-odd-levels'. Unlike to `org-current-level', this function
6447 takes into consideration inlinetasks."
6448 (org-with-wide-buffer
6449 (end-of-line)
6450 (if (re-search-backward org-outline-regexp-bol nil t)
6451 (1- (- (match-end 0) (match-beginning 0)))
6452 0)))
6454 (defvar org-font-lock-keywords nil)
6456 (defsubst org-re-property (property &optional literal allow-null value)
6457 "Return a regexp matching a PROPERTY line.
6459 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6460 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6461 non-nil, match properties even without a value.
6463 Match group 3 is set to the value when it exists. If there is no
6464 value and ALLOW-NULL is non-nil, it is set to the empty string.
6466 With optional argument VALUE, match only property lines with
6467 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6468 unless LITERAL is non-nil."
6469 (concat
6470 "^\\(?4:[ \t]*\\)"
6471 (format "\\(?1::\\(?2:%s\\):\\)"
6472 (if literal property (regexp-quote property)))
6473 (cond (value
6474 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6475 (if literal value (regexp-quote value))))
6476 (allow-null
6477 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6479 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6481 (defconst org-property-re
6482 (org-re-property "\\S-+" 'literal t)
6483 "Regular expression matching a property line.
6484 There are four matching groups:
6485 1: :PROPKEY: including the leading and trailing colon,
6486 2: PROPKEY without the leading and trailing colon,
6487 3: PROPVAL without leading or trailing spaces,
6488 4: the indentation of the current line,
6489 5: trailing whitespace.")
6491 (defvar org-font-lock-hook nil
6492 "Functions to be called for special font lock stuff.")
6494 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6496 (defvar org-font-lock-set-keywords-hook nil
6497 "Functions that can manipulate `org-font-lock-extra-keywords'.
6498 This is called after `org-font-lock-extra-keywords' is defined, but before
6499 it is installed to be used by font lock. This can be useful if something
6500 needs to be inserted at a specific position in the font-lock sequence.")
6502 (defun org-font-lock-hook (limit)
6503 "Run `org-font-lock-hook' within LIMIT."
6504 (run-hook-with-args 'org-font-lock-hook limit))
6506 (defun org-set-font-lock-defaults ()
6507 "Set font lock defaults for the current buffer."
6508 (let* ((em org-fontify-emphasized-text)
6509 (lk org-highlight-links)
6510 (org-font-lock-extra-keywords
6511 (list
6512 ;; Call the hook
6513 '(org-font-lock-hook)
6514 ;; Headlines
6515 `(,(if org-fontify-whole-heading-line
6516 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6517 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6518 (1 (org-get-level-face 1))
6519 (2 (org-get-level-face 2))
6520 (3 (org-get-level-face 3)))
6521 ;; Table lines
6522 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6523 (1 'org-table t))
6524 ;; Table internals
6525 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6526 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6527 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6528 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6529 ;; Drawers
6530 '(org-fontify-drawers)
6531 ;; Properties
6532 (list org-property-re
6533 '(1 'org-special-keyword t)
6534 '(3 'org-property-value t))
6535 ;; Links
6536 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6537 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6538 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
6539 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
6540 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6541 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6542 (when (memq 'footnote lk) '(org-activate-footnote-links))
6543 ;; Targets.
6544 (list org-any-target-regexp '(0 'org-target t))
6545 ;; Diary sexps.
6546 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6547 ;; Macro
6548 '(org-fontify-macros)
6549 '(org-hide-wide-columns (0 nil append))
6550 ;; TODO keyword
6551 (list (format org-heading-keyword-regexp-format
6552 org-todo-regexp)
6553 '(2 (org-get-todo-face 2) t))
6554 ;; DONE
6555 (if org-fontify-done-headline
6556 (list (format org-heading-keyword-regexp-format
6557 (concat
6558 "\\(?:"
6559 (mapconcat 'regexp-quote org-done-keywords "\\|")
6560 "\\)"))
6561 '(2 'org-headline-done t))
6562 nil)
6563 ;; Priorities
6564 '(org-font-lock-add-priority-faces)
6565 ;; Tags
6566 '(org-font-lock-add-tag-faces)
6567 ;; Tags groups
6568 (when (and org-group-tags org-tag-groups-alist)
6569 (list (concat org-outline-regexp-bol ".+\\(:"
6570 (regexp-opt (mapcar 'car org-tag-groups-alist))
6571 ":\\).*$")
6572 '(1 'org-tag-group prepend)))
6573 ;; Special keywords
6574 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6575 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6576 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6577 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6578 ;; Emphasis
6579 (when em '(org-do-emphasis-faces))
6580 ;; Checkboxes
6581 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6582 1 'org-checkbox prepend)
6583 (when (cdr (assq 'checkbox org-list-automatic-rules))
6584 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6585 (0 (org-get-checkbox-statistics-face) t)))
6586 ;; Description list items
6587 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6588 1 'org-list-dt prepend)
6589 ;; ARCHIVEd headings
6590 (list (concat
6591 org-outline-regexp-bol
6592 "\\(.*:" org-archive-tag ":.*\\)")
6593 '(1 'org-archived prepend))
6594 ;; Specials
6595 '(org-do-latex-and-related)
6596 '(org-fontify-entities)
6597 '(org-raise-scripts)
6598 ;; Code
6599 '(org-activate-code (1 'org-code t))
6600 ;; COMMENT
6601 (list (format
6602 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6603 org-todo-regexp
6604 org-comment-string)
6605 '(9 'org-special-keyword t))
6606 ;; Blocks and meta lines
6607 '(org-fontify-meta-lines-and-blocks))))
6608 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6609 (run-hooks 'org-font-lock-set-keywords-hook)
6610 ;; Now set the full font-lock-keywords
6611 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6612 (setq-local font-lock-defaults
6613 '(org-font-lock-keywords t nil nil backward-paragraph))
6614 (kill-local-variable 'font-lock-keywords)
6615 nil))
6617 (defun org-toggle-pretty-entities ()
6618 "Toggle the composition display of entities as UTF8 characters."
6619 (interactive)
6620 (setq-local org-pretty-entities (not org-pretty-entities))
6621 (org-restart-font-lock)
6622 (if org-pretty-entities
6623 (message "Entities are now displayed as UTF8 characters")
6624 (save-restriction
6625 (widen)
6626 (decompose-region (point-min) (point-max))
6627 (message "Entities are now displayed as plain text"))))
6629 (defvar-local org-custom-properties-overlays nil
6630 "List of overlays used for custom properties.")
6632 (defun org-toggle-custom-properties-visibility ()
6633 "Display or hide properties in `org-custom-properties'."
6634 (interactive)
6635 (if org-custom-properties-overlays
6636 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6637 (setq org-custom-properties-overlays nil))
6638 (when org-custom-properties
6639 (org-with-wide-buffer
6640 (goto-char (point-min))
6641 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6642 (while (re-search-forward regexp nil t)
6643 (let ((end (cdr (save-match-data (org-get-property-block)))))
6644 (when (and end (< (point) end))
6645 ;; Hide first custom property in current drawer.
6646 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6647 (overlay-put o 'invisible t)
6648 (overlay-put o 'org-custom-property t)
6649 (push o org-custom-properties-overlays))
6650 ;; Hide additional custom properties in the same drawer.
6651 (while (re-search-forward regexp end t)
6652 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6653 (overlay-put o 'invisible t)
6654 (overlay-put o 'org-custom-property t)
6655 (push o org-custom-properties-overlays)))))
6656 ;; Each entry is limited to a single property drawer.
6657 (outline-next-heading)))))))
6659 (defun org-fontify-entities (limit)
6660 "Find an entity to fontify."
6661 (let (ee)
6662 (when org-pretty-entities
6663 (catch 'match
6664 ;; "\_ "-family is left out on purpose. Only the first one,
6665 ;; i.e., "\_ ", could be fontified anyway, and it would be
6666 ;; confusing when adding a second white space character.
6667 (while (re-search-forward
6668 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6669 limit t)
6670 (when (and (not (org-at-comment-p))
6671 (setq ee (org-entity-get (match-string 1)))
6672 (= (length (nth 6 ee)) 1))
6673 (let* ((end (if (equal (match-string 2) "{}")
6674 (match-end 2)
6675 (match-end 1))))
6676 (add-text-properties
6677 (match-beginning 0) end
6678 (list 'font-lock-fontified t))
6679 (compose-region (match-beginning 0) end
6680 (nth 6 ee) nil)
6681 (backward-char 1)
6682 (throw 'match t))))
6683 nil))))
6685 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6686 "Fontify string S like in Org mode."
6687 (with-temp-buffer
6688 (insert s)
6689 (let ((org-odd-levels-only odd-levels))
6690 (org-mode)
6691 (org-font-lock-ensure)
6692 (buffer-string))))
6694 (defvar org-m nil)
6695 (defvar org-l nil)
6696 (defvar org-f nil)
6697 (defun org-get-level-face (n)
6698 "Get the right face for match N in font-lock matching of headlines."
6699 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6700 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6701 (if org-cycle-level-faces
6702 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6703 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6704 (cond
6705 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6706 ((eq n 2) org-f)
6707 (t (unless org-level-color-stars-only org-f))))
6709 (defun org-face-from-face-or-color (context inherit face-or-color)
6710 "Create a face list that inherits INHERIT, but sets the foreground color.
6711 When FACE-OR-COLOR is not a string, just return it."
6712 (if (stringp face-or-color)
6713 (list :inherit inherit
6714 (cdr (assoc context org-faces-easy-properties))
6715 face-or-color)
6716 face-or-color))
6718 (defun org-get-todo-face (kwd)
6719 "Get the right face for a TODO keyword KWD.
6720 If KWD is a number, get the corresponding match group."
6721 (when (numberp kwd) (setq kwd (match-string kwd)))
6722 (or (org-face-from-face-or-color
6723 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6724 (and (member kwd org-done-keywords) 'org-done)
6725 'org-todo))
6727 (defun org-get-priority-face (priority)
6728 "Get the right face for PRIORITY.
6729 PRIORITY is a character."
6730 (or (org-face-from-face-or-color
6731 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6732 'org-priority))
6734 (defun org-get-tag-face (tag)
6735 "Get the right face for TAG.
6736 If TAG is a number, get the corresponding match group."
6737 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6738 (or (org-face-from-face-or-color
6739 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6740 'org-tag)))
6742 (defun org-font-lock-add-priority-faces (limit)
6743 "Add the special priority faces."
6744 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6745 (add-text-properties
6746 (match-beginning 1) (match-end 1)
6747 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6748 'font-lock-fontified t))))
6750 (defun org-font-lock-add-tag-faces (limit)
6751 "Add the special tag faces."
6752 (when (and org-tag-faces org-tags-special-faces-re)
6753 (while (re-search-forward org-tags-special-faces-re limit t)
6754 (add-text-properties (match-beginning 1) (match-end 1)
6755 (list 'face (org-get-tag-face 1)
6756 'font-lock-fontified t))
6757 (backward-char 1))))
6759 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6760 "Remove fontification and activation overlays from links."
6761 (font-lock-default-unfontify-region beg end)
6762 (let* ((buffer-undo-list t)
6763 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6764 (inhibit-modification-hooks t)
6765 deactivate-mark buffer-file-name buffer-file-truename)
6766 (decompose-region beg end)
6767 (remove-text-properties beg end
6768 '(mouse-face t keymap t org-linked-text t
6769 invisible t intangible t
6770 org-emphasis t))
6771 (org-remove-font-lock-display-properties beg end)))
6773 (defconst org-script-display '(((raise -0.3) (height 0.7))
6774 ((raise 0.3) (height 0.7))
6775 ((raise -0.5))
6776 ((raise 0.5)))
6777 "Display properties for showing superscripts and subscripts.")
6779 (defun org-remove-font-lock-display-properties (beg end)
6780 "Remove specific display properties that have been added by font lock.
6781 The will remove the raise properties that are used to show superscripts
6782 and subscripts."
6783 (let (next prop)
6784 (while (< beg end)
6785 (setq next (next-single-property-change beg 'display nil end)
6786 prop (get-text-property beg 'display))
6787 (when (member prop org-script-display)
6788 (put-text-property beg next 'display nil))
6789 (setq beg next))))
6791 (defun org-raise-scripts (limit)
6792 "Add raise properties to sub/superscripts."
6793 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6794 (re-search-forward
6795 (if (eq org-use-sub-superscripts t)
6796 org-match-substring-regexp
6797 org-match-substring-with-braces-regexp)
6798 limit t))
6799 (let* ((pos (point)) table-p comment-p
6800 (mpos (match-beginning 3))
6801 (emph-p (get-text-property mpos 'org-emphasis))
6802 (link-p (get-text-property mpos 'mouse-face))
6803 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6804 (goto-char (point-at-bol))
6805 (setq table-p (looking-at-p org-table-dataline-regexp)
6806 comment-p (looking-at-p "^[ \t]*#[ +]"))
6807 (goto-char pos)
6808 ;; Handle a_b^c
6809 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6810 (unless (or comment-p emph-p link-p keyw-p)
6811 (put-text-property (match-beginning 3) (match-end 0)
6812 'display
6813 (if (equal (char-after (match-beginning 2)) ?^)
6814 (nth (if table-p 3 1) org-script-display)
6815 (nth (if table-p 2 0) org-script-display)))
6816 (add-text-properties (match-beginning 2) (match-end 2)
6817 (list 'invisible t
6818 'org-dwidth t 'org-dwidth-n 1))
6819 (if (and (eq (char-after (match-beginning 3)) ?{)
6820 (eq (char-before (match-end 3)) ?}))
6821 (progn
6822 (add-text-properties
6823 (match-beginning 3) (1+ (match-beginning 3))
6824 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6825 (add-text-properties
6826 (1- (match-end 3)) (match-end 3)
6827 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6828 t)))
6830 ;;;; Visibility cycling, including org-goto and indirect buffer
6832 ;;; Cycling
6834 (defvar-local org-cycle-global-status nil)
6835 (put 'org-cycle-global-status 'org-state t)
6836 (defvar-local org-cycle-subtree-status nil)
6837 (put 'org-cycle-subtree-status 'org-state t)
6839 (defvar org-inlinetask-min-level)
6841 (defun org-unlogged-message (&rest args)
6842 "Display a message, but avoid logging it in the *Messages* buffer."
6843 (let ((message-log-max nil))
6844 (apply 'message args)))
6846 ;;;###autoload
6847 (defun org-cycle (&optional arg)
6848 "TAB-action and visibility cycling for Org mode.
6850 This is the command invoked in Org mode by the `TAB' key. Its main
6851 purpose is outline visibility cycling, but it also invokes other actions
6852 in special contexts.
6854 When this function is called with a `\\[universal-argument]' prefix, rotate \
6855 the entire
6856 buffer through 3 states (global cycling)
6857 1. OVERVIEW: Show only top-level headlines.
6858 2. CONTENTS: Show all headlines of all levels, but no body text.
6859 3. SHOW ALL: Show everything.
6861 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6862 switch to the startup visibility,
6863 determined by the variable `org-startup-folded', and by any VISIBILITY
6864 properties in the buffer.
6866 With a `\\[universal-argument] \\[universal-argument] \
6867 \\[universal-argument]' prefix argument, show the entire buffer, including
6868 any drawers.
6870 When inside a table, re-align the table and move to the next field.
6872 When point is at the beginning of a headline, rotate the subtree started
6873 by this line through 3 different states (local cycling)
6874 1. FOLDED: Only the main headline is shown.
6875 2. CHILDREN: The main headline and the direct children are shown.
6876 From this state, you can move to one of the children
6877 and zoom in further.
6878 3. SUBTREE: Show the entire subtree, including body text.
6879 If there is no subtree, switch directly from CHILDREN to FOLDED.
6881 When point is at the beginning of an empty headline and the variable
6882 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6883 of the headline by demoting and promoting it to likely levels. This
6884 speeds up creation document structure by pressing `TAB' once or several
6885 times right after creating a new headline.
6887 When there is a numeric prefix, go up to a heading with level ARG, do
6888 a `show-subtree' and return to the previous cursor position. If ARG
6889 is negative, go up that many levels.
6891 When point is not at the beginning of a headline, execute the global
6892 binding for `TAB', which is re-indenting the line. See the option
6893 `org-cycle-emulate-tab' for details.
6895 As a special case, if point is at the beginning of the buffer and there is
6896 no headline in line 1, this function will act as if called with prefix arg
6897 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6898 prefix arg, but only
6899 if the variable `org-cycle-global-at-bob' is t."
6900 (interactive "P")
6901 (org-load-modules-maybe)
6902 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6903 (and org-cycle-level-after-item/entry-creation
6904 (or (org-cycle-level)
6905 (org-cycle-item-indentation))))
6906 (let* ((limit-level
6907 (or org-cycle-max-level
6908 (and (boundp 'org-inlinetask-min-level)
6909 org-inlinetask-min-level
6910 (1- org-inlinetask-min-level))))
6911 (nstars (and limit-level
6912 (if org-odd-levels-only
6913 (and limit-level (1- (* limit-level 2)))
6914 limit-level)))
6915 (org-outline-regexp
6916 (if (not (derived-mode-p 'org-mode))
6917 outline-regexp
6918 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6919 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6920 (not (looking-at org-outline-regexp))))
6921 (org-cycle-hook
6922 (if bob-special
6923 (delq 'org-optimize-window-after-visibility-change
6924 (copy-sequence org-cycle-hook))
6925 org-cycle-hook))
6926 (pos (point)))
6928 (cond
6930 ((equal arg '(16))
6931 (setq last-command 'dummy)
6932 (org-set-startup-visibility)
6933 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6935 ((equal arg '(64))
6936 (outline-show-all)
6937 (org-unlogged-message "Entire buffer visible, including drawers"))
6939 ((equal arg '(4)) (org-cycle-internal-global))
6941 ;; Try hiding block at point.
6942 ((org-hide-block-toggle-maybe))
6944 ;; Try cdlatex TAB completion
6945 ((org-try-cdlatex-tab))
6947 ;; Table: enter it or move to the next field.
6948 ((org-at-table-p 'any)
6949 (if (org-at-table.el-p)
6950 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6951 Use `\\[org-edit-special]' to edit table.el tables"))
6952 (if arg (org-table-edit-field t)
6953 (org-table-justify-field-maybe)
6954 (call-interactively 'org-table-next-field))))
6956 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6958 ;; Global cycling: delegate to `org-cycle-internal-global'.
6959 (bob-special (org-cycle-internal-global))
6961 ;; Drawers: delegate to `org-flag-drawer'.
6962 ((save-excursion
6963 (beginning-of-line 1)
6964 (looking-at org-drawer-regexp))
6965 (org-flag-drawer ; toggle block visibility
6966 (not (get-char-property (match-end 0) 'invisible))))
6968 ;; Show-subtree, ARG levels up from here.
6969 ((integerp arg)
6970 (save-excursion
6971 (org-back-to-heading)
6972 (outline-up-heading (if (< arg 0) (- arg)
6973 (- (funcall outline-level) arg)))
6974 (org-show-subtree)))
6976 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6977 ((and (featurep 'org-inlinetask)
6978 (org-inlinetask-at-task-p)
6979 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6980 (org-inlinetask-toggle-visibility))
6982 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6983 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6984 (save-excursion (move-beginning-of-line 1)
6985 (looking-at org-outline-regexp)))
6986 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6987 (org-cycle-internal-local))
6989 ;; From there: TAB emulation and template completion.
6990 (buffer-read-only (org-back-to-heading))
6992 ((run-hook-with-args-until-success
6993 'org-tab-after-check-for-cycling-hook))
6995 ((org-try-structure-completion))
6997 ((run-hook-with-args-until-success
6998 'org-tab-before-tab-emulation-hook))
7000 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
7001 (or (not (bolp))
7002 (not (looking-at org-outline-regexp))))
7003 (call-interactively (global-key-binding "\t")))
7005 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
7006 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
7007 (or (and (eq org-cycle-emulate-tab 'white)
7008 (= (match-end 0) (point-at-eol)))
7009 (and (eq org-cycle-emulate-tab 'whitestart)
7010 (>= (match-end 0) pos))))
7012 (eq org-cycle-emulate-tab t))
7013 (call-interactively (global-key-binding "\t")))
7015 (t (save-excursion
7016 (org-back-to-heading)
7017 (org-cycle)))))))
7019 (defun org-cycle-internal-global ()
7020 "Do the global cycling action."
7021 ;; Hack to avoid display of messages for .org attachments in Gnus
7022 (let ((ga (string-match "\\*fontification" (buffer-name))))
7023 (cond
7024 ((and (eq last-command this-command)
7025 (eq org-cycle-global-status 'overview))
7026 ;; We just created the overview - now do table of contents
7027 ;; This can be slow in very large buffers, so indicate action
7028 (run-hook-with-args 'org-pre-cycle-hook 'contents)
7029 (unless ga (org-unlogged-message "CONTENTS..."))
7030 (org-content)
7031 (unless ga (org-unlogged-message "CONTENTS...done"))
7032 (setq org-cycle-global-status 'contents)
7033 (run-hook-with-args 'org-cycle-hook 'contents))
7035 ((and (eq last-command this-command)
7036 (eq org-cycle-global-status 'contents))
7037 ;; We just showed the table of contents - now show everything
7038 (run-hook-with-args 'org-pre-cycle-hook 'all)
7039 (outline-show-all)
7040 (unless ga (org-unlogged-message "SHOW ALL"))
7041 (setq org-cycle-global-status 'all)
7042 (run-hook-with-args 'org-cycle-hook 'all))
7045 ;; Default action: go to overview
7046 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7047 (org-overview)
7048 (unless ga (org-unlogged-message "OVERVIEW"))
7049 (setq org-cycle-global-status 'overview)
7050 (run-hook-with-args 'org-cycle-hook 'overview)))))
7052 (defvar org-called-with-limited-levels nil
7053 "Non-nil when `org-with-limited-levels' is currently active.")
7055 (defun org-cycle-internal-local ()
7056 "Do the local cycling action."
7057 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7058 ;; First, determine end of headline (EOH), end of subtree or item
7059 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7060 (save-excursion
7061 (if (org-at-item-p)
7062 (progn
7063 (beginning-of-line)
7064 (setq struct (org-list-struct))
7065 (setq eoh (point-at-eol))
7066 (setq eos (org-list-get-item-end-before-blank (point) struct))
7067 (setq has-children (org-list-has-child-p (point) struct)))
7068 (org-back-to-heading)
7069 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7070 (setq eos (save-excursion (org-end-of-subtree t t)
7071 (when (bolp) (backward-char)) (point)))
7072 (setq has-children
7073 (or (save-excursion
7074 (let ((level (funcall outline-level)))
7075 (outline-next-heading)
7076 (and (org-at-heading-p t)
7077 (> (funcall outline-level) level))))
7078 (save-excursion
7079 (org-list-search-forward (org-item-beginning-re) eos t)))))
7080 ;; Determine end invisible part of buffer (EOL)
7081 (beginning-of-line 2)
7082 (while (and (not (eobp)) ;This is like `next-line'.
7083 (get-char-property (1- (point)) 'invisible))
7084 (goto-char (next-single-char-property-change (point) 'invisible))
7085 (and (eolp) (beginning-of-line 2)))
7086 (setq eol (point)))
7087 ;; Find out what to do next and set `this-command'
7088 (cond
7089 ((= eos eoh)
7090 ;; Nothing is hidden behind this heading
7091 (unless (org-before-first-heading-p)
7092 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7093 (org-unlogged-message "EMPTY ENTRY")
7094 (setq org-cycle-subtree-status nil)
7095 (save-excursion
7096 (goto-char eos)
7097 (outline-next-heading)
7098 (when (outline-invisible-p) (org-flag-heading nil))))
7099 ((and (or (>= eol eos)
7100 (not (string-match "\\S-" (buffer-substring eol eos))))
7101 (or has-children
7102 (not (setq children-skipped
7103 org-cycle-skip-children-state-if-no-children))))
7104 ;; Entire subtree is hidden in one line: children view
7105 (unless (org-before-first-heading-p)
7106 (run-hook-with-args 'org-pre-cycle-hook 'children))
7107 (if (org-at-item-p)
7108 (org-list-set-item-visibility (point-at-bol) struct 'children)
7109 (org-show-entry)
7110 (org-with-limited-levels (org-show-children))
7111 ;; FIXME: This slows down the func way too much.
7112 ;; How keep drawers hidden in subtree anyway?
7113 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
7114 ;; (org-cycle-hide-drawers 'subtree))
7116 ;; Fold every list in subtree to top-level items.
7117 (when (eq org-cycle-include-plain-lists 'integrate)
7118 (save-excursion
7119 (org-back-to-heading)
7120 (while (org-list-search-forward (org-item-beginning-re) eos t)
7121 (beginning-of-line 1)
7122 (let* ((struct (org-list-struct))
7123 (prevs (org-list-prevs-alist struct))
7124 (end (org-list-get-bottom-point struct)))
7125 (dolist (e (org-list-get-all-items (point) struct prevs))
7126 (org-list-set-item-visibility e struct 'folded))
7127 (goto-char (if (< end eos) end eos)))))))
7128 (org-unlogged-message "CHILDREN")
7129 (save-excursion
7130 (goto-char eos)
7131 (outline-next-heading)
7132 (when (outline-invisible-p) (org-flag-heading nil)))
7133 (setq org-cycle-subtree-status 'children)
7134 (unless (org-before-first-heading-p)
7135 (run-hook-with-args 'org-cycle-hook 'children)))
7136 ((or children-skipped
7137 (and (eq last-command this-command)
7138 (eq org-cycle-subtree-status 'children)))
7139 ;; We just showed the children, or no children are there,
7140 ;; now show everything.
7141 (unless (org-before-first-heading-p)
7142 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7143 (outline-flag-region eoh eos nil)
7144 (org-unlogged-message
7145 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7146 (setq org-cycle-subtree-status 'subtree)
7147 (unless (org-before-first-heading-p)
7148 (run-hook-with-args 'org-cycle-hook 'subtree)))
7150 ;; Default action: hide the subtree.
7151 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7152 (outline-flag-region eoh eos t)
7153 (org-unlogged-message "FOLDED")
7154 (setq org-cycle-subtree-status 'folded)
7155 (unless (org-before-first-heading-p)
7156 (run-hook-with-args 'org-cycle-hook 'folded))))))
7158 ;;;###autoload
7159 (defun org-global-cycle (&optional arg)
7160 "Cycle the global visibility. For details see `org-cycle'.
7161 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7162 With a numeric prefix, show all headlines up to that level."
7163 (interactive "P")
7164 (let ((org-cycle-include-plain-lists
7165 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7166 (cond
7167 ((integerp arg)
7168 (outline-show-all)
7169 (outline-hide-sublevels arg)
7170 (setq org-cycle-global-status 'contents))
7171 ((equal arg '(4))
7172 (org-set-startup-visibility)
7173 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7175 (org-cycle '(4))))))
7177 (defun org-set-startup-visibility ()
7178 "Set the visibility required by startup options and properties."
7179 (cond
7180 ((eq org-startup-folded t)
7181 (org-overview))
7182 ((eq org-startup-folded 'content)
7183 (org-content))
7184 ((or (eq org-startup-folded 'showeverything)
7185 (eq org-startup-folded nil))
7186 (outline-show-all)))
7187 (unless (eq org-startup-folded 'showeverything)
7188 (when org-hide-block-startup (org-hide-block-all))
7189 (org-set-visibility-according-to-property 'no-cleanup)
7190 (org-cycle-hide-archived-subtrees 'all)
7191 (org-cycle-hide-drawers 'all)
7192 (org-cycle-show-empty-lines t)))
7194 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7195 "Switch subtree visibilities according to :VISIBILITY: property."
7196 (interactive)
7197 (org-with-wide-buffer
7198 (goto-char (point-min))
7199 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7200 (if (not (org-at-property-p)) (outline-next-heading)
7201 (let ((state (match-string 3)))
7202 (save-excursion
7203 (org-back-to-heading t)
7204 (outline-hide-subtree)
7205 (org-reveal)
7206 (cond
7207 ((equal state "folded")
7208 (outline-hide-subtree))
7209 ((equal state "children")
7210 (org-show-hidden-entry)
7211 (org-show-children))
7212 ((equal state "content")
7213 (save-excursion
7214 (save-restriction
7215 (org-narrow-to-subtree)
7216 (org-content))))
7217 ((member state '("all" "showall"))
7218 (outline-show-subtree)))))))
7219 (unless no-cleanup
7220 (org-cycle-hide-archived-subtrees 'all)
7221 (org-cycle-hide-drawers 'all)
7222 (org-cycle-show-empty-lines 'all))))
7224 ;; This function uses outline-regexp instead of the more fundamental
7225 ;; org-outline-regexp so that org-cycle-global works outside of Org
7226 ;; buffers, where outline-regexp is needed.
7227 (defun org-overview ()
7228 "Switch to overview mode, showing only top-level headlines.
7229 This shows all headlines with a level equal or greater than the level
7230 of the first headline in the buffer. This is important, because if the
7231 first headline is not level one, then (hide-sublevels 1) gives confusing
7232 results."
7233 (interactive)
7234 (save-excursion
7235 (let ((level
7236 (save-excursion
7237 (goto-char (point-min))
7238 (when (re-search-forward (concat "^" outline-regexp) nil t)
7239 (goto-char (match-beginning 0))
7240 (funcall outline-level)))))
7241 (and level (outline-hide-sublevels level)))))
7243 (defun org-content (&optional arg)
7244 "Show all headlines in the buffer, like a table of contents.
7245 With numerical argument N, show content up to level N."
7246 (interactive "P")
7247 (org-overview)
7248 (save-excursion
7249 ;; Visit all headings and show their offspring
7250 (and (integerp arg) (org-overview))
7251 (goto-char (point-max))
7252 (catch 'exit
7253 (while (and (progn (condition-case nil
7254 (outline-previous-visible-heading 1)
7255 (error (goto-char (point-min))))
7257 (looking-at org-outline-regexp))
7258 (if (integerp arg)
7259 (org-show-children (1- arg))
7260 (outline-show-branches))
7261 (when (bobp) (throw 'exit nil))))))
7263 (defun org-optimize-window-after-visibility-change (state)
7264 "Adjust the window after a change in outline visibility.
7265 This function is the default value of the hook `org-cycle-hook'."
7266 (when (get-buffer-window (current-buffer))
7267 (cond
7268 ((eq state 'content) nil)
7269 ((eq state 'all) nil)
7270 ((eq state 'folded) nil)
7271 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7272 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7274 (defun org-remove-empty-overlays-at (pos)
7275 "Remove outline overlays that do not contain non-white stuff."
7276 (dolist (o (overlays-at pos))
7277 (and (eq 'outline (overlay-get o 'invisible))
7278 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7279 (overlay-end o))))
7280 (delete-overlay o))))
7282 (defun org-clean-visibility-after-subtree-move ()
7283 "Fix visibility issues after moving a subtree."
7284 ;; First, find a reasonable region to look at:
7285 ;; Start two siblings above, end three below
7286 (let* ((beg (save-excursion
7287 (and (org-get-last-sibling)
7288 (org-get-last-sibling))
7289 (point)))
7290 (end (save-excursion
7291 (and (org-get-next-sibling)
7292 (org-get-next-sibling)
7293 (org-get-next-sibling))
7294 (if (org-at-heading-p)
7295 (point-at-eol)
7296 (point))))
7297 (level (looking-at "\\*+"))
7298 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7299 (save-excursion
7300 (save-restriction
7301 (narrow-to-region beg end)
7302 (when re
7303 ;; Properly fold already folded siblings
7304 (goto-char (point-min))
7305 (while (re-search-forward re nil t)
7306 (when (and (not (outline-invisible-p))
7307 (save-excursion
7308 (goto-char (point-at-eol)) (outline-invisible-p)))
7309 (outline-hide-entry))))
7310 (org-cycle-show-empty-lines 'overview)
7311 (org-cycle-hide-drawers 'overview)))))
7313 (defun org-cycle-show-empty-lines (state)
7314 "Show empty lines above all visible headlines.
7315 The region to be covered depends on STATE when called through
7316 `org-cycle-hook'. Lisp program can use t for STATE to get the
7317 entire buffer covered. Note that an empty line is only shown if there
7318 are at least `org-cycle-separator-lines' empty lines before the headline."
7319 (when (/= org-cycle-separator-lines 0)
7320 (save-excursion
7321 (let* ((n (abs org-cycle-separator-lines))
7322 (re (cond
7323 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7324 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7325 (t (let ((ns (number-to-string (- n 2))))
7326 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7327 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7328 beg end)
7329 (cond
7330 ((memq state '(overview contents t))
7331 (setq beg (point-min) end (point-max)))
7332 ((memq state '(children folded))
7333 (setq beg (point)
7334 end (progn (org-end-of-subtree t t)
7335 (line-beginning-position 2)))))
7336 (when beg
7337 (goto-char beg)
7338 (while (re-search-forward re end t)
7339 (unless (get-char-property (match-end 1) 'invisible)
7340 (let ((e (match-end 1))
7341 (b (if (>= org-cycle-separator-lines 0)
7342 (match-beginning 1)
7343 (save-excursion
7344 (goto-char (match-beginning 0))
7345 (skip-chars-backward " \t\n")
7346 (line-end-position)))))
7347 (outline-flag-region b e nil))))))))
7348 ;; Never hide empty lines at the end of the file.
7349 (save-excursion
7350 (goto-char (point-max))
7351 (outline-previous-heading)
7352 (outline-end-of-heading)
7353 (when (and (looking-at "[ \t\n]+")
7354 (= (match-end 0) (point-max)))
7355 (outline-flag-region (point) (match-end 0) nil))))
7357 (defun org-show-empty-lines-in-parent ()
7358 "Move to the parent and re-show empty lines before visible headlines."
7359 (save-excursion
7360 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7361 (org-cycle-show-empty-lines context))))
7363 (defun org-files-list ()
7364 "Return `org-agenda-files' list, plus all open Org files.
7365 This is useful for operations that need to scan all of a user's
7366 open and agenda-wise Org files."
7367 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7368 (dolist (buf (buffer-list))
7369 (with-current-buffer buf
7370 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7371 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7372 files))
7374 (defsubst org-entry-beginning-position ()
7375 "Return the beginning position of the current entry."
7376 (save-excursion (org-back-to-heading t) (point)))
7378 (defsubst org-entry-end-position ()
7379 "Return the end position of the current entry."
7380 (save-excursion (outline-next-heading) (point)))
7382 (defun org-cycle-hide-drawers (state &optional exceptions)
7383 "Re-hide all drawers after a visibility state change.
7384 When non-nil, optional argument EXCEPTIONS is a list of strings
7385 specifying which drawers should not be hidden."
7386 (when (and (derived-mode-p 'org-mode)
7387 (not (memq state '(overview folded contents))))
7388 (save-excursion
7389 (let* ((globalp (memq state '(contents all)))
7390 (beg (if globalp (point-min) (point)))
7391 (end (if globalp (point-max)
7392 (if (eq state 'children)
7393 (save-excursion (outline-next-heading) (point))
7394 (org-end-of-subtree t)))))
7395 (goto-char beg)
7396 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7397 (unless (member-ignore-case (match-string 1) exceptions)
7398 (let ((drawer (org-element-at-point)))
7399 (when (memq (org-element-type drawer) '(drawer property-drawer))
7400 (org-flag-drawer t drawer)
7401 ;; Make sure to skip drawer entirely or we might flag
7402 ;; it another time when matching its ending line with
7403 ;; `org-drawer-regexp'.
7404 (goto-char (org-element-property :end drawer))))))))))
7406 (defun org-flag-drawer (flag &optional element)
7407 "When FLAG is non-nil, hide the drawer we are at.
7408 Otherwise make it visible. When optional argument ELEMENT is
7409 a parsed drawer, as returned by `org-element-at-point', hide or
7410 show that drawer instead."
7411 (let ((drawer (or element
7412 (and (save-excursion
7413 (beginning-of-line)
7414 (looking-at-p org-drawer-regexp))
7415 (org-element-at-point)))))
7416 (when (memq (org-element-type drawer) '(drawer property-drawer))
7417 (let ((post (org-element-property :post-affiliated drawer)))
7418 (save-excursion
7419 (outline-flag-region
7420 (progn (goto-char post) (line-end-position))
7421 (progn (goto-char (org-element-property :end drawer))
7422 (skip-chars-backward " \r\t\n")
7423 (line-end-position))
7424 flag))
7425 ;; When the drawer is hidden away, make sure point lies in
7426 ;; a visible part of the buffer.
7427 (when (and flag (> (line-beginning-position) post))
7428 (goto-char post))))))
7430 (defun org-subtree-end-visible-p ()
7431 "Is the end of the current subtree visible?"
7432 (pos-visible-in-window-p
7433 (save-excursion (org-end-of-subtree t) (point))))
7435 (defun org-first-headline-recenter ()
7436 "Move cursor to the first headline and recenter the headline."
7437 (let ((window (get-buffer-window)))
7438 (when window
7439 (goto-char (point-min))
7440 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7441 (set-window-start window (line-beginning-position))))))
7443 ;;; Saving and restoring visibility
7445 (defun org-outline-overlay-data (&optional use-markers)
7446 "Return a list of the locations of all outline overlays.
7447 These are overlays with the `invisible' property value `outline'.
7448 The return value is a list of cons cells, with start and stop
7449 positions for each overlay.
7450 If USE-MARKERS is set, return the positions as markers."
7451 (let (beg end)
7452 (org-with-wide-buffer
7453 (delq nil
7454 (mapcar (lambda (o)
7455 (when (eq (overlay-get o 'invisible) 'outline)
7456 (setq beg (overlay-start o)
7457 end (overlay-end o))
7458 (and beg end (> end beg)
7459 (if use-markers
7460 (cons (copy-marker beg)
7461 (copy-marker end t))
7462 (cons beg end)))))
7463 (overlays-in (point-min) (point-max)))))))
7465 (defun org-set-outline-overlay-data (data)
7466 "Create visibility overlays for all positions in DATA.
7467 DATA should have been made by `org-outline-overlay-data'."
7468 (org-with-wide-buffer
7469 (outline-show-all)
7470 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7472 ;;; Folding of blocks
7474 (defvar-local org-hide-block-overlays nil
7475 "Overlays hiding blocks.")
7477 (defun org-block-map (function &optional start end)
7478 "Call FUNCTION at the head of all source blocks in the current buffer.
7479 Optional arguments START and END can be used to limit the range."
7480 (let ((start (or start (point-min)))
7481 (end (or end (point-max))))
7482 (save-excursion
7483 (goto-char start)
7484 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7485 (save-excursion
7486 (save-match-data
7487 (goto-char (match-beginning 0))
7488 (funcall function)))))))
7490 (defun org-hide-block-toggle-all ()
7491 "Toggle the visibility of all blocks in the current buffer."
7492 (org-block-map 'org-hide-block-toggle))
7494 (defun org-hide-block-all ()
7495 "Fold all blocks in the current buffer."
7496 (interactive)
7497 (org-show-block-all)
7498 (org-block-map 'org-hide-block-toggle-maybe))
7500 (defun org-show-block-all ()
7501 "Unfold all blocks in the current buffer."
7502 (interactive)
7503 (mapc #'delete-overlay org-hide-block-overlays)
7504 (setq org-hide-block-overlays nil))
7506 (defun org-hide-block-toggle-maybe ()
7507 "Toggle visibility of block at point.
7508 Unlike to `org-hide-block-toggle', this function does not throw
7509 an error. Return a non-nil value when toggling is successful."
7510 (interactive)
7511 (ignore-errors (org-hide-block-toggle)))
7513 (defun org-hide-block-toggle (&optional force)
7514 "Toggle the visibility of the current block.
7515 When optional argument FORCE is `off', make block visible. If it
7516 is non-nil, hide it unconditionally. Throw an error when not at
7517 a block. Return a non-nil value when toggling is successful."
7518 (interactive)
7519 (let ((element (org-element-at-point)))
7520 (unless (memq (org-element-type element)
7521 '(center-block comment-block dynamic-block example-block
7522 export-block quote-block special-block
7523 src-block verse-block))
7524 (user-error "Not at a block"))
7525 (let* ((start (save-excursion
7526 (goto-char (org-element-property :post-affiliated element))
7527 (line-end-position)))
7528 (end (save-excursion
7529 (goto-char (org-element-property :end element))
7530 (skip-chars-backward " \r\t\n")
7531 (line-end-position)))
7532 (overlays (overlays-at start)))
7533 (cond
7534 ;; Do nothing when not before or at the block opening line or
7535 ;; at the block closing line.
7536 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7537 ((and (not (eq force 'off))
7538 (not (memq t (mapcar
7539 (lambda (o)
7540 (eq (overlay-get o 'invisible) 'org-hide-block))
7541 overlays))))
7542 (let ((ov (make-overlay start end)))
7543 (overlay-put ov 'invisible 'org-hide-block)
7544 ;; Make the block accessible to `isearch'.
7545 (overlay-put
7546 ov 'isearch-open-invisible
7547 (lambda (ov)
7548 (when (memq ov org-hide-block-overlays)
7549 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7550 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7551 (delete-overlay ov))))
7552 (push ov org-hide-block-overlays)
7553 ;; When the block is hidden away, make sure point is left in
7554 ;; a visible part of the buffer.
7555 (when (> (line-beginning-position) start)
7556 (goto-char start)
7557 (beginning-of-line))
7558 ;; Signal successful toggling.
7560 ((or (not force) (eq force 'off))
7561 (dolist (ov overlays t)
7562 (when (memq ov org-hide-block-overlays)
7563 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7564 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7565 (delete-overlay ov))))))))
7567 ;; Remove overlays when changing major mode
7568 (add-hook 'org-mode-hook
7569 (lambda () (add-hook 'change-major-mode-hook
7570 'org-show-block-all 'append 'local)))
7572 ;;; Org-goto
7574 (defvar org-goto-window-configuration nil)
7575 (defvar org-goto-marker nil)
7576 (defvar org-goto-map)
7577 (defun org-goto-map ()
7578 "Set the keymap `org-goto'."
7579 (setq org-goto-map
7580 (let ((map (make-sparse-keymap)))
7581 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7582 mouse-drag-region universal-argument org-occur)))
7583 (dolist (cmd cmds)
7584 (substitute-key-definition cmd cmd map global-map)))
7585 (suppress-keymap map)
7586 (org-defkey map "\C-m" 'org-goto-ret)
7587 (org-defkey map [(return)] 'org-goto-ret)
7588 (org-defkey map [(left)] 'org-goto-left)
7589 (org-defkey map [(right)] 'org-goto-right)
7590 (org-defkey map [(control ?g)] 'org-goto-quit)
7591 (org-defkey map "\C-i" 'org-cycle)
7592 (org-defkey map [(tab)] 'org-cycle)
7593 (org-defkey map [(down)] 'outline-next-visible-heading)
7594 (org-defkey map [(up)] 'outline-previous-visible-heading)
7595 (if org-goto-auto-isearch
7596 (if (fboundp 'define-key-after)
7597 (define-key-after map [t] 'org-goto-local-auto-isearch)
7598 nil)
7599 (org-defkey map "q" 'org-goto-quit)
7600 (org-defkey map "n" 'outline-next-visible-heading)
7601 (org-defkey map "p" 'outline-previous-visible-heading)
7602 (org-defkey map "f" 'outline-forward-same-level)
7603 (org-defkey map "b" 'outline-backward-same-level)
7604 (org-defkey map "u" 'outline-up-heading))
7605 (org-defkey map "/" 'org-occur)
7606 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7607 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7608 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7609 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7610 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7611 map)))
7613 (defconst org-goto-help
7614 "Browse buffer copy, to find location or copy text.%s
7615 RET=jump to location C-g=quit and return to previous location
7616 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7618 (defvar org-goto-start-pos) ; dynamically scoped parameter
7620 (defun org-goto (&optional alternative-interface)
7621 "Look up a different location in the current file, keeping current visibility.
7623 When you want look-up or go to a different location in a
7624 document, the fastest way is often to fold the entire buffer and
7625 then dive into the tree. This method has the disadvantage, that
7626 the previous location will be folded, which may not be what you
7627 want.
7629 This command works around this by showing a copy of the current
7630 buffer in an indirect buffer, in overview mode. You can dive
7631 into the tree in that copy, use org-occur and incremental search
7632 to find a location. When pressing RET or `Q', the command
7633 returns to the original buffer in which the visibility is still
7634 unchanged. After RET it will also jump to the location selected
7635 in the indirect buffer and expose the headline hierarchy above.
7637 With a prefix argument, use the alternative interface: e.g., if
7638 `org-goto-interface' is `outline' use `outline-path-completion'."
7639 (interactive "P")
7640 (org-goto-map)
7641 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7642 (org-refile-use-outline-path t)
7643 (org-refile-target-verify-function nil)
7644 (interface
7645 (if (not alternative-interface)
7646 org-goto-interface
7647 (if (eq org-goto-interface 'outline)
7648 'outline-path-completion
7649 'outline)))
7650 (org-goto-start-pos (point))
7651 (selected-point
7652 (if (eq interface 'outline)
7653 (car (org-get-location (current-buffer) org-goto-help))
7654 (let ((pa (org-refile-get-location "Goto")))
7655 (org-refile-check-position pa)
7656 (nth 3 pa)))))
7657 (if selected-point
7658 (progn
7659 (org-mark-ring-push org-goto-start-pos)
7660 (goto-char selected-point)
7661 (when (or (outline-invisible-p) (org-invisible-p2))
7662 (org-show-context 'org-goto)))
7663 (message "Quit"))))
7665 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7666 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7667 (defvar org-goto-local-auto-isearch-map) ; defined below
7669 (defun org-get-location (_buf help)
7670 "Let the user select a location in current buffer.
7671 This function uses a recursive edit. It returns the selected position
7672 or nil."
7673 (org-no-popups
7674 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7675 (isearch-hide-immediately nil)
7676 (isearch-search-fun-function
7677 (lambda () 'org-goto-local-search-headings))
7678 (org-goto-selected-point org-goto-exit-command))
7679 (save-excursion
7680 (save-window-excursion
7681 (delete-other-windows)
7682 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7683 (pop-to-buffer-same-window
7684 (condition-case nil
7685 (make-indirect-buffer (current-buffer) "*org-goto*")
7686 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7687 (with-output-to-temp-buffer "*Org Help*"
7688 (princ (format help (if org-goto-auto-isearch
7689 " Just type for auto-isearch."
7690 " n/p/f/b/u to navigate, q to quit."))))
7691 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7692 (setq buffer-read-only nil)
7693 (let ((org-startup-truncated t)
7694 (org-startup-folded nil)
7695 (org-startup-align-all-tables nil))
7696 (org-mode)
7697 (org-overview))
7698 (setq buffer-read-only t)
7699 (if (and (boundp 'org-goto-start-pos)
7700 (integer-or-marker-p org-goto-start-pos))
7701 (progn (goto-char org-goto-start-pos)
7702 (when (outline-invisible-p)
7703 (org-show-set-visibility 'lineage)))
7704 (goto-char (point-min)))
7705 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7706 (message "Select location and press RET")
7707 (use-local-map org-goto-map)
7708 (recursive-edit)))
7709 (kill-buffer "*org-goto*")
7710 (cons org-goto-selected-point org-goto-exit-command))))
7712 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7713 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7714 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7715 (if (fboundp 'isearch-other-control-char)
7716 (progn
7717 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7718 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7719 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7720 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7721 (define-key org-goto-local-auto-isearch-map [return] nil))
7723 (defun org-goto-local-search-headings (string bound noerror)
7724 "Search and make sure that any matches are in headlines."
7725 (catch 'return
7726 (while (if isearch-forward
7727 (search-forward string bound noerror)
7728 (search-backward string bound noerror))
7729 (when (save-match-data
7730 (and (save-excursion
7731 (beginning-of-line)
7732 (looking-at org-complex-heading-regexp))
7733 (or (not (match-beginning 5))
7734 (< (point) (match-beginning 5)))))
7735 (throw 'return (point))))))
7737 (defun org-goto-local-auto-isearch ()
7738 "Start isearch."
7739 (interactive)
7740 (goto-char (point-min))
7741 (let ((keys (this-command-keys)))
7742 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7743 (isearch-mode t)
7744 (isearch-process-search-char (string-to-char keys)))))
7746 (defun org-goto-ret (&optional _arg)
7747 "Finish `org-goto' by going to the new location."
7748 (interactive "P")
7749 (setq org-goto-selected-point (point))
7750 (setq org-goto-exit-command 'return)
7751 (throw 'exit nil))
7753 (defun org-goto-left ()
7754 "Finish `org-goto' by going to the new location."
7755 (interactive)
7756 (if (org-at-heading-p)
7757 (progn
7758 (beginning-of-line 1)
7759 (setq org-goto-selected-point (point)
7760 org-goto-exit-command 'left)
7761 (throw 'exit nil))
7762 (user-error "Not on a heading")))
7764 (defun org-goto-right ()
7765 "Finish `org-goto' by going to the new location."
7766 (interactive)
7767 (if (org-at-heading-p)
7768 (progn
7769 (setq org-goto-selected-point (point)
7770 org-goto-exit-command 'right)
7771 (throw 'exit nil))
7772 (user-error "Not on a heading")))
7774 (defun org-goto-quit ()
7775 "Finish `org-goto' without cursor motion."
7776 (interactive)
7777 (setq org-goto-selected-point nil)
7778 (setq org-goto-exit-command 'quit)
7779 (throw 'exit nil))
7781 ;;; Indirect buffer display of subtrees
7783 (defvar org-indirect-dedicated-frame nil
7784 "This is the frame being used for indirect tree display.")
7785 (defvar org-last-indirect-buffer nil)
7787 (defun org-tree-to-indirect-buffer (&optional arg)
7788 "Create indirect buffer and narrow it to current subtree.
7790 With a numerical prefix ARG, go up to this level and then take that tree.
7791 If ARG is negative, go up that many levels.
7793 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7794 indirect buffer previously made with this command, to avoid proliferation of
7795 indirect buffers. However, when you call the command with a \
7796 `\\[universal-argument]' prefix, or
7797 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7798 so that you can work with several indirect buffers at the same time. If
7799 `org-indirect-buffer-display' is `dedicated-frame', the \
7800 `\\[universal-argument]' prefix also
7801 requests that a new frame be made for the new buffer, so that the dedicated
7802 frame is not changed."
7803 (interactive "P")
7804 (let ((cbuf (current-buffer))
7805 (cwin (selected-window))
7806 (pos (point))
7807 beg end level heading ibuf)
7808 (save-excursion
7809 (org-back-to-heading t)
7810 (when (numberp arg)
7811 (setq level (org-outline-level))
7812 (when (< arg 0) (setq arg (+ level arg)))
7813 (while (> (setq level (org-outline-level)) arg)
7814 (org-up-heading-safe)))
7815 (setq beg (point)
7816 heading (org-get-heading 'no-tags))
7817 (org-end-of-subtree t t)
7818 (when (org-at-heading-p) (backward-char 1))
7819 (setq end (point)))
7820 (when (and (buffer-live-p org-last-indirect-buffer)
7821 (not (eq org-indirect-buffer-display 'new-frame))
7822 (not arg))
7823 (kill-buffer org-last-indirect-buffer))
7824 (setq ibuf (org-get-indirect-buffer cbuf heading)
7825 org-last-indirect-buffer ibuf)
7826 (cond
7827 ((or (eq org-indirect-buffer-display 'new-frame)
7828 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7829 (select-frame (make-frame))
7830 (delete-other-windows)
7831 (pop-to-buffer-same-window ibuf)
7832 (org-set-frame-title heading))
7833 ((eq org-indirect-buffer-display 'dedicated-frame)
7834 (raise-frame
7835 (select-frame (or (and org-indirect-dedicated-frame
7836 (frame-live-p org-indirect-dedicated-frame)
7837 org-indirect-dedicated-frame)
7838 (setq org-indirect-dedicated-frame (make-frame)))))
7839 (delete-other-windows)
7840 (pop-to-buffer-same-window ibuf)
7841 (org-set-frame-title (concat "Indirect: " heading)))
7842 ((eq org-indirect-buffer-display 'current-window)
7843 (pop-to-buffer-same-window ibuf))
7844 ((eq org-indirect-buffer-display 'other-window)
7845 (pop-to-buffer ibuf))
7846 (t (error "Invalid value")))
7847 (narrow-to-region beg end)
7848 (outline-show-all)
7849 (goto-char pos)
7850 (run-hook-with-args 'org-cycle-hook 'all)
7851 (and (window-live-p cwin) (select-window cwin))))
7853 (defun org-get-indirect-buffer (&optional buffer heading)
7854 (setq buffer (or buffer (current-buffer)))
7855 (let ((n 1) (base (buffer-name buffer)) bname)
7856 (while (buffer-live-p
7857 (get-buffer
7858 (setq bname
7859 (concat base "-"
7860 (if heading (concat heading "-" (number-to-string n))
7861 (number-to-string n))))))
7862 (setq n (1+ n)))
7863 (condition-case nil
7864 (make-indirect-buffer buffer bname 'clone)
7865 (error (make-indirect-buffer buffer bname)))))
7867 (defun org-set-frame-title (title)
7868 "Set the title of the current frame to the string TITLE."
7869 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7871 ;;;; Structure editing
7873 ;;; Inserting headlines
7875 (defun org--line-empty-p (n)
7876 "Is the Nth next line empty?
7878 Counts the current line as N = 1 and the previous line as N = 0;
7879 see `beginning-of-line'."
7880 (save-excursion
7881 (and (not (bobp))
7882 (or (beginning-of-line n) t)
7883 (save-match-data
7884 (looking-at "[ \t]*$")))))
7886 (defun org-previous-line-empty-p ()
7887 "Is the previous line a blank line?
7888 When NEXT is non-nil, check the next line instead."
7889 (org--line-empty-p 0))
7891 (defun org-next-line-empty-p ()
7892 "Is the previous line a blank line?
7893 When NEXT is non-nil, check the next line instead."
7894 (org--line-empty-p 2))
7896 (defun org-insert-heading (&optional arg invisible-ok top)
7897 "Insert a new heading or an item with the same depth at point.
7899 If point is at the beginning of a heading or a list item, insert
7900 a new heading or a new item above the current one. When at the
7901 beginning of a regular line of text, turn it into a heading.
7903 If point is in the middle of a line, split it and create a new
7904 headline/item with the text in the current line after point (see
7905 `org-M-RET-may-split-line' on how to modify this behavior). As
7906 a special case, on a headline, splitting can only happen on the
7907 title itself. E.g., this excludes breaking stars or tags.
7909 With a `\\[universal-argument]' prefix, set \
7910 `org-insert-heading-respect-content' to
7911 a non-nil value for the duration of the command. This forces the
7912 insertion of a heading after the current subtree, independently
7913 on the location of point.
7915 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7916 insert the heading at the end of the tree
7917 above the current heading. For example, if point is within a
7918 2nd-level heading, then it will insert a 2nd-level heading at
7919 the end of the 1st-level parent subtree.
7921 When INVISIBLE-OK is set, stop at invisible headlines when going
7922 back. This is important for non-interactive uses of the
7923 command.
7925 When optional argument TOP is non-nil, insert a level 1 heading,
7926 unconditionally."
7927 (interactive "P")
7928 (let ((itemp (and (not top) (org-in-item-p)))
7929 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7930 (respect-content (or org-insert-heading-respect-content
7931 (equal arg '(4))))
7932 (initial-content ""))
7934 (cond
7936 ((or (= (buffer-size) 0)
7937 (and (not (save-excursion
7938 (and (ignore-errors (org-back-to-heading invisible-ok))
7939 (org-at-heading-p))))
7940 (or arg (not itemp))))
7941 ;; At beginning of buffer or so high up that only a heading
7942 ;; makes sense.
7943 (cond ((and (bolp) (not respect-content)) (insert "* "))
7944 ((not respect-content)
7945 (unless may-split (end-of-line))
7946 (insert "\n* "))
7947 ((re-search-forward org-outline-regexp-bol nil t)
7948 (beginning-of-line)
7949 (insert "* \n")
7950 (backward-char))
7951 (t (goto-char (point-max))
7952 (insert "\n* ")))
7953 (run-hooks 'org-insert-heading-hook))
7955 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7958 ;; Maybe move at the end of the subtree
7959 (when (equal arg '(16))
7960 (org-up-heading-safe)
7961 (org-end-of-subtree t))
7962 ;; Insert a heading
7963 (save-restriction
7964 (widen)
7965 (let* ((level nil)
7966 (on-heading (org-at-heading-p))
7967 (empty-line-p (if on-heading
7968 (org-previous-line-empty-p)
7969 ;; We will decide later
7970 nil))
7971 ;; Get a level string to fall back on.
7972 (fix-level
7973 (if (org-before-first-heading-p) "*"
7974 (save-excursion
7975 (org-back-to-heading t)
7976 (when (org-previous-line-empty-p) (setq empty-line-p t))
7977 (looking-at org-outline-regexp)
7978 (make-string (1- (length (match-string 0))) ?*))))
7979 (stars
7980 (save-excursion
7981 (condition-case nil
7982 (if top "* "
7983 (org-back-to-heading invisible-ok)
7984 (when (and (not on-heading)
7985 (featurep 'org-inlinetask)
7986 (integerp org-inlinetask-min-level)
7987 (>= (length (match-string 0))
7988 org-inlinetask-min-level))
7989 ;; Find a heading level before the inline
7990 ;; task.
7991 (while (and (setq level (org-up-heading-safe))
7992 (>= level org-inlinetask-min-level)))
7993 (if (org-at-heading-p)
7994 (org-back-to-heading invisible-ok)
7995 (error "This should not happen")))
7996 (unless (and (save-excursion
7997 (save-match-data
7998 (org-backward-heading-same-level
7999 1 invisible-ok))
8000 (= (point) (match-beginning 0)))
8001 (not (org-next-line-empty-p)))
8002 (setq empty-line-p (or empty-line-p
8003 (org-previous-line-empty-p))))
8004 (match-string 0))
8005 (error (or fix-level "* ")))))
8006 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
8007 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
8009 ;; If we insert after content, move there and clean up
8010 ;; whitespace.
8011 (when respect-content
8012 (if (not (org-before-first-heading-p))
8013 (org-end-of-subtree nil t)
8014 (re-search-forward org-outline-regexp-bol)
8015 (beginning-of-line 0))
8016 (skip-chars-backward " \r\t\n")
8017 (and (not (looking-back "^\\*+" (line-beginning-position)))
8018 (looking-at "[ \t]+") (replace-match ""))
8019 (unless (eobp) (forward-char 1))
8020 (when (looking-at "^\\*")
8021 (unless (bobp) (backward-char 1))
8022 (insert "\n")))
8024 ;; If we are splitting, grab the text that should be moved
8025 ;; to the new headline.
8026 (when may-split
8027 (if (org-at-heading-p)
8028 ;; This is a heading: split intelligently (keeping
8029 ;; tags).
8030 (let ((pos (point)))
8031 (beginning-of-line)
8032 (let ((case-fold-search nil))
8033 (unless (looking-at org-complex-heading-regexp)
8034 (error "This should not happen")))
8035 (when (and (match-beginning 4)
8036 (> pos (match-beginning 4))
8037 (< pos (match-end 4)))
8038 (setq initial-content (buffer-substring pos (match-end 4)))
8039 (goto-char pos)
8040 (delete-region (point) (match-end 4))
8041 (if (looking-at "[ \t]*$")
8042 (replace-match "")
8043 (insert (make-string (length initial-content) ?\s)))
8044 (setq initial-content (org-trim initial-content)))
8045 (goto-char pos))
8046 ;; A normal line.
8047 (setq initial-content
8048 (org-trim
8049 (delete-and-extract-region (point) (line-end-position))))))
8051 ;; If we are at the beginning of the line, insert before it.
8052 ;; Otherwise, after it.
8053 (cond
8054 ((and (bolp) (looking-at "[ \t]*$")))
8055 ((bolp) (save-excursion (insert "\n")))
8056 (t (end-of-line)
8057 (insert "\n")))
8059 ;; Insert the new heading
8060 (insert stars)
8061 (just-one-space)
8062 (insert initial-content)
8063 (unless (and blank (org-previous-line-empty-p))
8064 (org-N-empty-lines-before-current (if blank 1 0)))
8065 ;; Adjust visibility, which may be messed up if we removed
8066 ;; blank lines while previous entry was hidden.
8067 (let ((bol (line-beginning-position)))
8068 (dolist (o (overlays-at (1- bol)))
8069 (when (and (eq (overlay-get o 'invisible) 'outline)
8070 (eq (overlay-end o) bol))
8071 (move-overlay o (overlay-start o) (1- bol)))))
8072 (run-hooks 'org-insert-heading-hook)))))))
8074 (defun org-N-empty-lines-before-current (N)
8075 "Make the number of empty lines before current exactly N.
8076 So this will delete or add empty lines."
8077 (save-excursion
8078 (beginning-of-line)
8079 (let ((p (point)))
8080 (skip-chars-backward " \r\t\n")
8081 (unless (bolp) (forward-line))
8082 (delete-region (point) p))
8083 (when (> N 0) (insert (make-string N ?\n)))))
8085 (defun org-get-heading (&optional no-tags no-todo)
8086 "Return the heading of the current entry, without the stars.
8087 When NO-TAGS is non-nil, don't include tags.
8088 When NO-TODO is non-nil, don't include TODO keywords."
8089 (save-excursion
8090 (org-back-to-heading t)
8091 (let ((case-fold-search nil))
8092 (cond
8093 ((and no-tags no-todo)
8094 (looking-at org-complex-heading-regexp)
8095 ;; Return value has to be a string, but match group 4 is
8096 ;; optional.
8097 (or (match-string 4) ""))
8098 (no-tags
8099 (looking-at (concat org-outline-regexp
8100 "\\(.*?\\)"
8101 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8102 (match-string 1))
8103 (no-todo
8104 (looking-at org-todo-line-regexp)
8105 (match-string 3))
8106 (t (looking-at org-heading-regexp)
8107 (match-string 2))))))
8109 (defvar orgstruct-mode) ; defined below
8111 (defun org-heading-components ()
8112 "Return the components of the current heading.
8113 This is a list with the following elements:
8114 - the level as an integer
8115 - the reduced level, different if `org-odd-levels-only' is set.
8116 - the TODO keyword, or nil
8117 - the priority character, like ?A, or nil if no priority is given
8118 - the headline text itself, or the tags string if no headline text
8119 - the tags string, or nil."
8120 (save-excursion
8121 (org-back-to-heading t)
8122 (when (let (case-fold-search)
8123 (looking-at
8124 (if orgstruct-mode
8125 org-heading-regexp
8126 org-complex-heading-regexp)))
8127 (if orgstruct-mode
8128 (list (length (match-string 1))
8129 (org-reduced-level (length (match-string 1)))
8132 (match-string 2)
8133 nil)
8134 (list (length (match-string 1))
8135 (org-reduced-level (length (match-string 1)))
8136 (match-string-no-properties 2)
8137 (and (match-end 3) (aref (match-string 3) 2))
8138 (match-string-no-properties 4)
8139 (match-string-no-properties 5))))))
8141 (defun org-get-entry ()
8142 "Get the entry text, after heading, entire subtree."
8143 (save-excursion
8144 (org-back-to-heading t)
8145 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8147 (defun org-edit-headline (&optional heading)
8148 "Edit the current headline.
8149 Set it to HEADING when provided."
8150 (interactive)
8151 (org-with-wide-buffer
8152 (org-back-to-heading t)
8153 (let ((case-fold-search nil))
8154 (when (looking-at org-complex-heading-regexp)
8155 (let* ((old (match-string-no-properties 4))
8156 (new (save-match-data
8157 (org-trim (or heading (read-string "Edit: " old))))))
8158 (unless (equal old new)
8159 (if old (replace-match new t t nil 4)
8160 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8161 (insert " " new))
8162 (org-set-tags nil t)
8163 (when (looking-at "[ \t]*$") (replace-match ""))))))))
8165 (defun org-insert-heading-after-current ()
8166 "Insert a new heading with same level as current, after current subtree."
8167 (interactive)
8168 (org-back-to-heading)
8169 (org-insert-heading)
8170 (org-move-subtree-down)
8171 (end-of-line 1))
8173 (defun org-insert-heading-respect-content (&optional invisible-ok)
8174 "Insert heading with `org-insert-heading-respect-content' set to t."
8175 (interactive)
8176 (org-insert-heading '(4) invisible-ok))
8178 (defun org-insert-todo-heading-respect-content (&optional force-state)
8179 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8180 (interactive)
8181 (org-insert-todo-heading force-state '(4)))
8183 (defun org-insert-todo-heading (arg &optional force-heading)
8184 "Insert a new heading with the same level and TODO state as current heading.
8186 If the heading has no TODO state, or if the state is DONE, use
8187 the first state (TODO by default). Also with one prefix arg,
8188 force first state. With two prefix args, force inserting at the
8189 end of the parent subtree.
8191 When called at a plain list item, insert a new item with an
8192 unchecked check box."
8193 (interactive "P")
8194 (when (or force-heading (not (org-insert-item 'checkbox)))
8195 (org-insert-heading (or (and (equal arg '(16)) '(16))
8196 force-heading))
8197 (save-excursion
8198 (org-back-to-heading)
8199 (outline-previous-heading)
8200 (looking-at org-todo-line-regexp))
8201 (let* ((new-mark-x
8202 (if (or (equal arg '(4))
8203 (not (match-beginning 2))
8204 (member (match-string 2) org-done-keywords))
8205 (car org-todo-keywords-1)
8206 (match-string 2)))
8207 (new-mark
8209 (run-hook-with-args-until-success
8210 'org-todo-get-default-hook new-mark-x nil)
8211 new-mark-x)))
8212 (beginning-of-line 1)
8213 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8214 (if org-treat-insert-todo-heading-as-state-change
8215 (org-todo new-mark)
8216 (insert new-mark " "))))
8217 (when org-provide-todo-statistics
8218 (org-update-parent-todo-statistics))))
8220 (defun org-insert-subheading (arg)
8221 "Insert a new subheading and demote it.
8222 Works for outline headings and for plain lists alike."
8223 (interactive "P")
8224 (org-insert-heading arg)
8225 (cond
8226 ((org-at-heading-p) (org-do-demote))
8227 ((org-at-item-p) (org-indent-item))))
8229 (defun org-insert-todo-subheading (arg)
8230 "Insert a new subheading with TODO keyword or checkbox and demote it.
8231 Works for outline headings and for plain lists alike."
8232 (interactive "P")
8233 (org-insert-todo-heading arg)
8234 (cond
8235 ((org-at-heading-p) (org-do-demote))
8236 ((org-at-item-p) (org-indent-item))))
8238 ;;; Promotion and Demotion
8240 (defvar org-after-demote-entry-hook nil
8241 "Hook run after an entry has been demoted.
8242 The cursor will be at the beginning of the entry.
8243 When a subtree is being demoted, the hook will be called for each node.")
8245 (defvar org-after-promote-entry-hook nil
8246 "Hook run after an entry has been promoted.
8247 The cursor will be at the beginning of the entry.
8248 When a subtree is being promoted, the hook will be called for each node.")
8250 (defun org-promote-subtree ()
8251 "Promote the entire subtree.
8252 See also `org-promote'."
8253 (interactive)
8254 (save-excursion
8255 (org-with-limited-levels (org-map-tree 'org-promote)))
8256 (org-fix-position-after-promote))
8258 (defun org-demote-subtree ()
8259 "Demote the entire subtree.
8260 See `org-demote' and `org-promote'."
8261 (interactive)
8262 (save-excursion
8263 (org-with-limited-levels (org-map-tree 'org-demote)))
8264 (org-fix-position-after-promote))
8266 (defun org-do-promote ()
8267 "Promote the current heading higher up the tree.
8268 If the region is active in `transient-mark-mode', promote all
8269 headings in the region."
8270 (interactive)
8271 (save-excursion
8272 (if (org-region-active-p)
8273 (org-map-region 'org-promote (region-beginning) (region-end))
8274 (org-promote)))
8275 (org-fix-position-after-promote))
8277 (defun org-do-demote ()
8278 "Demote the current heading lower down the tree.
8279 If the region is active in `transient-mark-mode', demote all
8280 headings in the region."
8281 (interactive)
8282 (save-excursion
8283 (if (org-region-active-p)
8284 (org-map-region 'org-demote (region-beginning) (region-end))
8285 (org-demote)))
8286 (org-fix-position-after-promote))
8288 (defun org-fix-position-after-promote ()
8289 "Fix cursor position and indentation after demoting/promoting."
8290 (let ((pos (point)))
8291 (when (save-excursion
8292 (beginning-of-line 1)
8293 (looking-at org-todo-line-regexp)
8294 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8295 (cond ((eobp) (insert " "))
8296 ((eolp) (insert " "))
8297 ((equal (char-after) ?\ ) (forward-char 1))))))
8299 (defun org-current-level ()
8300 "Return the level of the current entry, or nil if before the first headline.
8301 The level is the number of stars at the beginning of the
8302 headline. Use `org-reduced-level' to remove the effect of
8303 `org-odd-levels'. Unlike to `org-outline-level', this function
8304 ignores inlinetasks."
8305 (let ((level (org-with-limited-levels (org-outline-level))))
8306 (and (> level 0) level)))
8308 (defun org-get-previous-line-level ()
8309 "Return the outline depth of the last headline before the current line.
8310 Returns 0 for the first headline in the buffer, and nil if before the
8311 first headline."
8312 (and (org-current-level)
8313 (or (and (/= (line-beginning-position) (point-min))
8314 (save-excursion (beginning-of-line 0) (org-current-level)))
8315 0)))
8317 (defun org-reduced-level (l)
8318 "Compute the effective level of a heading.
8319 This takes into account the setting of `org-odd-levels-only'."
8320 (cond
8321 ((zerop l) 0)
8322 (org-odd-levels-only (1+ (floor (/ l 2))))
8323 (t l)))
8325 (defun org-level-increment ()
8326 "Return the number of stars that will be added or removed at a
8327 time to headlines when structure editing, based on the value of
8328 `org-odd-levels-only'."
8329 (if org-odd-levels-only 2 1))
8331 (defun org-get-valid-level (level &optional change)
8332 "Rectify a level change under the influence of `org-odd-levels-only'
8333 LEVEL is a current level, CHANGE is by how much the level should be
8334 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8335 even level numbers will become the next higher odd number."
8336 (if org-odd-levels-only
8337 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8338 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8339 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8340 (max 1 (+ level (or change 0)))))
8342 (defun org-promote ()
8343 "Promote the current heading higher up the tree."
8344 (org-with-wide-buffer
8345 (org-back-to-heading t)
8346 (let* ((after-change-functions (remq 'flyspell-after-change-function
8347 after-change-functions))
8348 (level (save-match-data (funcall outline-level)))
8349 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8350 (diff (abs (- level (length up-head) -1))))
8351 (cond
8352 ((and (= level 1) org-allow-promoting-top-level-subtree)
8353 (replace-match "# " nil t))
8354 ((= level 1)
8355 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8356 (t (replace-match up-head nil t)))
8357 (unless (= level 1)
8358 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8359 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8360 (run-hooks 'org-after-promote-entry-hook))))
8362 (defun org-demote ()
8363 "Demote the current heading lower down the tree."
8364 (org-with-wide-buffer
8365 (org-back-to-heading t)
8366 (let* ((after-change-functions (remq 'flyspell-after-change-function
8367 after-change-functions))
8368 (level (save-match-data (funcall outline-level)))
8369 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8370 (diff (abs (- level (length down-head) -1))))
8371 (replace-match down-head nil t)
8372 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8373 (when org-adapt-indentation (org-fixup-indentation diff))
8374 (run-hooks 'org-after-demote-entry-hook))))
8376 (defun org-cycle-level ()
8377 "Cycle the level of an empty headline through possible states.
8378 This goes first to child, then to parent, level, then up the hierarchy.
8379 After top level, it switches back to sibling level."
8380 (interactive)
8381 (let ((org-adapt-indentation nil))
8382 (when (org-point-at-end-of-empty-headline)
8383 (setq this-command 'org-cycle-level) ; Only needed for caching
8384 (let ((cur-level (org-current-level))
8385 (prev-level (org-get-previous-line-level)))
8386 (cond
8387 ;; If first headline in file, promote to top-level.
8388 ((= prev-level 0)
8389 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8390 do (org-do-promote)))
8391 ;; If same level as prev, demote one.
8392 ((= prev-level cur-level)
8393 (org-do-demote))
8394 ;; If parent is top-level, promote to top level if not already.
8395 ((= prev-level 1)
8396 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8397 do (org-do-promote)))
8398 ;; If top-level, return to prev-level.
8399 ((= cur-level 1)
8400 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8401 do (org-do-demote)))
8402 ;; If less than prev-level, promote one.
8403 ((< cur-level prev-level)
8404 (org-do-promote))
8405 ;; If deeper than prev-level, promote until higher than
8406 ;; prev-level.
8407 ((> cur-level prev-level)
8408 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8409 do (org-do-promote))))
8410 t))))
8412 (defun org-map-tree (fun)
8413 "Call FUN for every heading underneath the current one."
8414 (org-back-to-heading t)
8415 (let ((level (funcall outline-level)))
8416 (save-excursion
8417 (funcall fun)
8418 (while (and (progn
8419 (outline-next-heading)
8420 (> (funcall outline-level) level))
8421 (not (eobp)))
8422 (funcall fun)))))
8424 (defun org-map-region (fun beg end)
8425 "Call FUN for every heading between BEG and END."
8426 (let ((org-ignore-region t))
8427 (save-excursion
8428 (setq end (copy-marker end))
8429 (goto-char beg)
8430 (when (and (re-search-forward org-outline-regexp-bol nil t)
8431 (< (point) end))
8432 (funcall fun))
8433 (while (and (progn
8434 (outline-next-heading)
8435 (< (point) end))
8436 (not (eobp)))
8437 (funcall fun)))))
8439 (defun org-fixup-indentation (diff)
8440 "Change the indentation in the current entry by DIFF.
8442 DIFF is an integer. Indentation is done according to the
8443 following rules:
8445 - Planning information and property drawers are always indented
8446 according to the new level of the headline;
8448 - Footnote definitions and their contents are ignored;
8450 - Inlinetasks' boundaries are not shifted;
8452 - Empty lines are ignored;
8454 - Other lines' indentation are shifted by DIFF columns, unless
8455 it would introduce a structural change in the document, in
8456 which case no shifting is done at all.
8458 Assume point is at a heading or an inlinetask beginning."
8459 (org-with-wide-buffer
8460 (narrow-to-region (line-beginning-position)
8461 (save-excursion
8462 (if (org-with-limited-levels (org-at-heading-p))
8463 (org-with-limited-levels (outline-next-heading))
8464 (org-inlinetask-goto-end))
8465 (point)))
8466 (forward-line)
8467 ;; Indent properly planning info and property drawer.
8468 (when (looking-at-p org-planning-line-re)
8469 (org-indent-line)
8470 (forward-line))
8471 (when (looking-at org-property-drawer-re)
8472 (goto-char (match-end 0))
8473 (forward-line)
8474 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8475 (catch 'no-shift
8476 (when (zerop diff) (throw 'no-shift nil))
8477 ;; If DIFF is negative, first check if a shift is possible at all
8478 ;; (e.g., it doesn't break structure). This can only happen if
8479 ;; some contents are not properly indented.
8480 (let ((case-fold-search t))
8481 (when (< diff 0)
8482 (let ((diff (- diff))
8483 (forbidden-re (concat org-outline-regexp
8484 "\\|"
8485 (substring org-footnote-definition-re 1))))
8486 (save-excursion
8487 (while (not (eobp))
8488 (cond
8489 ((looking-at-p "[ \t]*$") (forward-line))
8490 ((and (looking-at-p org-footnote-definition-re)
8491 (let ((e (org-element-at-point)))
8492 (and (eq (org-element-type e) 'footnote-definition)
8493 (goto-char (org-element-property :end e))))))
8494 ((looking-at-p org-outline-regexp) (forward-line))
8495 ;; Give up if shifting would move before column 0 or
8496 ;; if it would introduce a headline or a footnote
8497 ;; definition.
8499 (skip-chars-forward " \t")
8500 (let ((ind (current-column)))
8501 (when (or (< ind diff)
8502 (and (= ind diff) (looking-at-p forbidden-re)))
8503 (throw 'no-shift nil)))
8504 ;; Ignore contents of example blocks and source
8505 ;; blocks if their indentation is meant to be
8506 ;; preserved. Jump to block's closing line.
8507 (beginning-of-line)
8508 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8509 (let ((e (org-element-at-point)))
8510 (and (memq (org-element-type e)
8511 '(example-block src-block))
8512 (or org-src-preserve-indentation
8513 (org-element-property :preserve-indent e))
8514 (goto-char (org-element-property :end e))
8515 (progn (skip-chars-backward " \r\t\n")
8516 (beginning-of-line)
8517 t))))
8518 (forward-line))))))))
8519 ;; Shift lines but footnote definitions, inlinetasks boundaries
8520 ;; by DIFF. Also skip contents of source or example blocks
8521 ;; when indentation is meant to be preserved.
8522 (while (not (eobp))
8523 (cond
8524 ((and (looking-at-p org-footnote-definition-re)
8525 (let ((e (org-element-at-point)))
8526 (and (eq (org-element-type e) 'footnote-definition)
8527 (goto-char (org-element-property :end e))))))
8528 ((looking-at-p org-outline-regexp) (forward-line))
8529 ((looking-at-p "[ \t]*$") (forward-line))
8531 (indent-line-to (+ (org-get-indentation) diff))
8532 (beginning-of-line)
8533 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8534 (let ((e (org-element-at-point)))
8535 (and (memq (org-element-type e)
8536 '(example-block src-block))
8537 (or org-src-preserve-indentation
8538 (org-element-property :preserve-indent e))
8539 (goto-char (org-element-property :end e))
8540 (progn (skip-chars-backward " \r\t\n")
8541 (beginning-of-line)
8542 t))))
8543 (forward-line)))))))))
8545 (defun org-convert-to-odd-levels ()
8546 "Convert an Org file with all levels allowed to one with odd levels.
8547 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8548 level 5 etc."
8549 (interactive)
8550 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8551 (let ((outline-level 'org-outline-level)
8552 (org-odd-levels-only nil) n)
8553 (save-excursion
8554 (goto-char (point-min))
8555 (while (re-search-forward "^\\*\\*+ " nil t)
8556 (setq n (- (length (match-string 0)) 2))
8557 (while (>= (setq n (1- n)) 0)
8558 (org-demote))
8559 (end-of-line 1))))))
8561 (defun org-convert-to-oddeven-levels ()
8562 "Convert an Org file with only odd levels to one with odd/even levels.
8563 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8564 file contains a section with an even level, conversion would
8565 destroy the structure of the file. An error is signaled in this
8566 case."
8567 (interactive)
8568 (goto-char (point-min))
8569 ;; First check if there are no even levels
8570 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8571 (org-show-set-visibility 'canonical)
8572 (error "Not all levels are odd in this file. Conversion not possible"))
8573 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8574 (let ((outline-regexp org-outline-regexp)
8575 (outline-level 'org-outline-level)
8576 (org-odd-levels-only nil) n)
8577 (save-excursion
8578 (goto-char (point-min))
8579 (while (re-search-forward "^\\*\\*+ " nil t)
8580 (setq n (/ (1- (length (match-string 0))) 2))
8581 (while (>= (setq n (1- n)) 0)
8582 (org-promote))
8583 (end-of-line 1))))))
8585 (defun org-tr-level (n)
8586 "Make N odd if required."
8587 (if org-odd-levels-only (1+ (/ n 2)) n))
8589 ;;; Vertical tree motion, cutting and pasting of subtrees
8591 (defun org-move-subtree-up (&optional arg)
8592 "Move the current subtree up past ARG headlines of the same level."
8593 (interactive "p")
8594 (org-move-subtree-down (- (prefix-numeric-value arg))))
8596 (defun org-move-subtree-down (&optional arg)
8597 "Move the current subtree down past ARG headlines of the same level."
8598 (interactive "p")
8599 (setq arg (prefix-numeric-value arg))
8600 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8601 'org-get-last-sibling))
8602 (ins-point (make-marker))
8603 (cnt (abs arg))
8604 (col (current-column))
8605 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8606 ;; Select the tree
8607 (org-back-to-heading)
8608 (setq beg0 (point))
8609 (save-excursion
8610 (setq ne-beg (org-back-over-empty-lines))
8611 (setq beg (point)))
8612 (save-match-data
8613 (save-excursion (outline-end-of-heading)
8614 (setq folded (outline-invisible-p)))
8615 (progn (org-end-of-subtree nil t)
8616 (unless (eobp) (backward-char))))
8617 (outline-next-heading)
8618 (setq ne-end (org-back-over-empty-lines))
8619 (setq end (point))
8620 (goto-char beg0)
8621 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8622 ;; include less whitespace
8623 (save-excursion
8624 (goto-char beg)
8625 (forward-line (- ne-beg ne-end))
8626 (setq beg (point))))
8627 ;; Find insertion point, with error handling
8628 (while (> cnt 0)
8629 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8630 (progn (goto-char beg0)
8631 (user-error "Cannot move past superior level or buffer limit")))
8632 (setq cnt (1- cnt)))
8633 (when (> arg 0)
8634 ;; Moving forward - still need to move over subtree
8635 (org-end-of-subtree t t)
8636 (save-excursion
8637 (org-back-over-empty-lines)
8638 (or (bolp) (newline))))
8639 (setq ne-ins (org-back-over-empty-lines))
8640 (move-marker ins-point (point))
8641 (setq txt (buffer-substring beg end))
8642 (org-save-markers-in-region beg end)
8643 (delete-region beg end)
8644 (org-remove-empty-overlays-at beg)
8645 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8646 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8647 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8648 (let ((bbb (point)))
8649 (insert-before-markers txt)
8650 (org-reinstall-markers-in-region bbb)
8651 (move-marker ins-point bbb))
8652 (or (bolp) (insert "\n"))
8653 (setq ins-end (point))
8654 (goto-char ins-point)
8655 (org-skip-whitespace)
8656 (when (and (< arg 0)
8657 (org-first-sibling-p)
8658 (> ne-ins ne-beg))
8659 ;; Move whitespace back to beginning
8660 (save-excursion
8661 (goto-char ins-end)
8662 (let ((kill-whole-line t))
8663 (kill-line (- ne-ins ne-beg)) (point)))
8664 (insert (make-string (- ne-ins ne-beg) ?\n)))
8665 (move-marker ins-point nil)
8666 (if folded
8667 (outline-hide-subtree)
8668 (org-show-entry)
8669 (org-show-children)
8670 (org-cycle-hide-drawers 'children))
8671 (org-clean-visibility-after-subtree-move)
8672 ;; move back to the initial column we were at
8673 (move-to-column col)))
8675 (defvar org-subtree-clip ""
8676 "Clipboard for cut and paste of subtrees.
8677 This is actually only a copy of the kill, because we use the normal kill
8678 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8680 (defvar org-subtree-clip-folded nil
8681 "Was the last copied subtree folded?
8682 This is used to fold the tree back after pasting.")
8684 (defun org-cut-subtree (&optional n)
8685 "Cut the current subtree into the clipboard.
8686 With prefix arg N, cut this many sequential subtrees.
8687 This is a short-hand for marking the subtree and then cutting it."
8688 (interactive "p")
8689 (org-copy-subtree n 'cut))
8691 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8692 "Copy the current subtree it in the clipboard.
8693 With prefix arg N, copy this many sequential subtrees.
8694 This is a short-hand for marking the subtree and then copying it.
8695 If CUT is non-nil, actually cut the subtree.
8696 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8697 of some markers in the region, even if CUT is non-nil. This is
8698 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8699 (interactive "p")
8700 (let (beg end folded (beg0 (point)))
8701 (if (called-interactively-p 'any)
8702 (org-back-to-heading nil) ; take what looks like a subtree
8703 (org-back-to-heading t)) ; take what is really there
8704 (setq beg (point))
8705 (skip-chars-forward " \t\r\n")
8706 (save-match-data
8707 (if nosubtrees
8708 (outline-next-heading)
8709 (save-excursion (outline-end-of-heading)
8710 (setq folded (outline-invisible-p)))
8711 (ignore-errors (org-forward-heading-same-level (1- n) t))
8712 (org-end-of-subtree t t)))
8713 ;; Include the end of an inlinetask
8714 (when (and (featurep 'org-inlinetask)
8715 (looking-at-p (concat (org-inlinetask-outline-regexp)
8716 "END[ \t]*$")))
8717 (end-of-line))
8718 (setq end (point))
8719 (goto-char beg0)
8720 (when (> end beg)
8721 (setq org-subtree-clip-folded folded)
8722 (when (or cut force-store-markers)
8723 (org-save-markers-in-region beg end))
8724 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8725 (setq org-subtree-clip (current-kill 0))
8726 (message "%s: Subtree(s) with %d characters"
8727 (if cut "Cut" "Copied")
8728 (length org-subtree-clip)))))
8730 (defun org-paste-subtree (&optional level tree for-yank remove)
8731 "Paste the clipboard as a subtree, with modification of headline level.
8732 The entire subtree is promoted or demoted in order to match a new headline
8733 level.
8735 If the cursor is at the beginning of a headline, the same level as
8736 that headline is used to paste the tree.
8738 If not, the new level is derived from the *visible* headings
8739 before and after the insertion point, and taken to be the inferior headline
8740 level of the two. So if the previous visible heading is level 3 and the
8741 next is level 4 (or vice versa), level 4 will be used for insertion.
8742 This makes sure that the subtree remains an independent subtree and does
8743 not swallow low level entries.
8745 You can also force a different level, either by using a numeric prefix
8746 argument, or by inserting the heading marker by hand. For example, if the
8747 cursor is after \"*****\", then the tree will be shifted to level 5.
8749 If optional TREE is given, use this text instead of the kill ring.
8751 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8752 move back over whitespace before inserting, and move point to the end of
8753 the inserted text when done.
8755 When REMOVE is non-nil, remove the subtree from the clipboard."
8756 (interactive "P")
8757 (setq tree (or tree (and kill-ring (current-kill 0))))
8758 (unless (org-kill-is-subtree-p tree)
8759 (user-error "%s"
8760 (substitute-command-keys
8761 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8762 (org-with-limited-levels
8763 (let* ((visp (not (outline-invisible-p)))
8764 (txt tree)
8765 (^re_ "\\(\\*+\\)[ \t]*")
8766 (old-level (if (string-match org-outline-regexp-bol txt)
8767 (- (match-end 0) (match-beginning 0) 1)
8768 -1))
8769 (force-level (cond (level (prefix-numeric-value level))
8770 ((and (looking-at "[ \t]*$")
8771 (string-match
8772 "^\\*+$" (buffer-substring
8773 (point-at-bol) (point))))
8774 (- (match-end 0) (match-beginning 0)))
8775 ((and (bolp)
8776 (looking-at org-outline-regexp))
8777 (- (match-end 0) (point) 1))))
8778 (previous-level (save-excursion
8779 (condition-case nil
8780 (progn
8781 (outline-previous-visible-heading 1)
8782 (if (looking-at ^re_)
8783 (- (match-end 0) (match-beginning 0) 1)
8785 (error 1))))
8786 (next-level (save-excursion
8787 (condition-case nil
8788 (progn
8789 (or (looking-at org-outline-regexp)
8790 (outline-next-visible-heading 1))
8791 (if (looking-at ^re_)
8792 (- (match-end 0) (match-beginning 0) 1)
8794 (error 1))))
8795 (new-level (or force-level (max previous-level next-level)))
8796 (shift (if (or (= old-level -1)
8797 (= new-level -1)
8798 (= old-level new-level))
8800 (- new-level old-level)))
8801 (delta (if (> shift 0) -1 1))
8802 (func (if (> shift 0) 'org-demote 'org-promote))
8803 (org-odd-levels-only nil)
8804 beg end newend)
8805 ;; Remove the forced level indicator
8806 (when force-level
8807 (delete-region (point-at-bol) (point)))
8808 ;; Paste
8809 (beginning-of-line (if (bolp) 1 2))
8810 (setq beg (point))
8811 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8812 (insert-before-markers txt)
8813 (unless (string-suffix-p "\n" txt) (insert "\n"))
8814 (setq newend (point))
8815 (org-reinstall-markers-in-region beg)
8816 (setq end (point))
8817 (goto-char beg)
8818 (skip-chars-forward " \t\n\r")
8819 (setq beg (point))
8820 (when (and (outline-invisible-p) visp)
8821 (save-excursion (outline-show-heading)))
8822 ;; Shift if necessary
8823 (unless (= shift 0)
8824 (save-restriction
8825 (narrow-to-region beg end)
8826 (while (not (= shift 0))
8827 (org-map-region func (point-min) (point-max))
8828 (setq shift (+ delta shift)))
8829 (goto-char (point-min))
8830 (setq newend (point-max))))
8831 (when (or (called-interactively-p 'interactive) for-yank)
8832 (message "Clipboard pasted as level %d subtree" new-level))
8833 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8834 kill-ring
8835 (eq org-subtree-clip (current-kill 0))
8836 org-subtree-clip-folded)
8837 ;; The tree was folded before it was killed/copied
8838 (outline-hide-subtree))
8839 (and for-yank (goto-char newend))
8840 (and remove (setq kill-ring (cdr kill-ring))))))
8842 (defun org-kill-is-subtree-p (&optional txt)
8843 "Check if the current kill is an outline subtree, or a set of trees.
8844 Returns nil if kill does not start with a headline, or if the first
8845 headline level is not the largest headline level in the tree.
8846 So this will actually accept several entries of equal levels as well,
8847 which is OK for `org-paste-subtree'.
8848 If optional TXT is given, check this string instead of the current kill."
8849 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8850 (re (org-get-limited-outline-regexp))
8851 (^re (concat "^" re))
8852 (start-level (and kill
8853 (string-match
8854 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8855 kill)
8856 (- (match-end 2) (match-beginning 2) 1)))
8857 (start (1+ (or (match-beginning 2) -1))))
8858 (if (not start-level)
8859 (progn
8860 nil) ;; does not even start with a heading
8861 (catch 'exit
8862 (while (setq start (string-match ^re kill (1+ start)))
8863 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8864 (throw 'exit nil)))
8865 t))))
8867 (defvar org-markers-to-move nil
8868 "Markers that should be moved with a cut-and-paste operation.
8869 Those markers are stored together with their positions relative to
8870 the start of the region.")
8872 (defun org-save-markers-in-region (beg end)
8873 "Check markers in region.
8874 If these markers are between BEG and END, record their position relative
8875 to BEG, so that after moving the block of text, we can put the markers back
8876 into place.
8877 This function gets called just before an entry or tree gets cut from the
8878 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8879 called immediately, to move the markers with the entries."
8880 (setq org-markers-to-move nil)
8881 (when (featurep 'org-clock)
8882 (org-clock-save-markers-for-cut-and-paste beg end))
8883 (when (featurep 'org-agenda)
8884 (org-agenda-save-markers-for-cut-and-paste beg end)))
8886 (defun org-check-and-save-marker (marker beg end)
8887 "Check if MARKER is between BEG and END.
8888 If yes, remember the marker and the distance to BEG."
8889 (when (and (marker-buffer marker)
8890 (equal (marker-buffer marker) (current-buffer))
8891 (>= marker beg) (< marker end))
8892 (push (cons marker (- marker beg)) org-markers-to-move)))
8894 (defun org-reinstall-markers-in-region (beg)
8895 "Move all remembered markers to their position relative to BEG."
8896 (dolist (x org-markers-to-move)
8897 (move-marker (car x) (+ beg (cdr x))))
8898 (setq org-markers-to-move nil))
8900 (defun org-narrow-to-subtree ()
8901 "Narrow buffer to the current subtree."
8902 (interactive)
8903 (save-excursion
8904 (save-match-data
8905 (org-with-limited-levels
8906 (narrow-to-region
8907 (progn (org-back-to-heading t) (point))
8908 (progn (org-end-of-subtree t t)
8909 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8910 (point)))))))
8912 (defun org-narrow-to-block ()
8913 "Narrow buffer to the current block."
8914 (interactive)
8915 (let* ((case-fold-search t)
8916 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8917 "^[ \t]*#\\+end_.*")))
8918 (if blockp
8919 (narrow-to-region (car blockp) (cdr blockp))
8920 (user-error "Not in a block"))))
8922 (defun org-clone-subtree-with-time-shift (n &optional shift)
8923 "Clone the task (subtree) at point N times.
8924 The clones will be inserted as siblings.
8926 In interactive use, the user will be prompted for the number of
8927 clones to be produced. If the entry has a timestamp, the user
8928 will also be prompted for a time shift, which may be a repeater
8929 as used in time stamps, for example `+3d'. To disable this,
8930 you can call the function with a universal prefix argument.
8932 When a valid repeater is given and the entry contains any time
8933 stamps, the clones will become a sequence in time, with time
8934 stamps in the subtree shifted for each clone produced. If SHIFT
8935 is nil or the empty string, time stamps will be left alone. The
8936 ID property of the original subtree is removed.
8938 In each clone, all the CLOCK entries will be removed. This
8939 prevents Org from considering that the clocked times overlap.
8941 If the original subtree did contain time stamps with a repeater,
8942 the following will happen:
8943 - the repeater will be removed in each clone
8944 - an additional clone will be produced, with the current, unshifted
8945 date(s) in the entry.
8946 - the original entry will be placed *after* all the clones, with
8947 repeater intact.
8948 - the start days in the repeater in the original entry will be shifted
8949 to past the last clone.
8950 In this way you can spell out a number of instances of a repeating task,
8951 and still retain the repeater to cover future instances of the task.
8953 As described above, N+1 clones are produced when the original
8954 subtree has a repeater. Setting N to 0, then, can be used to
8955 remove the repeater from a subtree and create a shifted clone
8956 with the original repeater."
8957 (interactive "nNumber of clones to produce: ")
8958 (let ((shift
8959 (or shift
8960 (if (and (not (equal current-prefix-arg '(4)))
8961 (save-excursion
8962 (re-search-forward org-ts-regexp-both
8963 (save-excursion
8964 (org-end-of-subtree t)
8965 (point)) t)))
8966 (read-from-minibuffer
8967 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8968 ""))) ;; No time shift
8969 (n-no-remove -1)
8970 (drawer-re org-drawer-regexp)
8971 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8972 beg end template task idprop
8973 shift-n shift-what doshift nmin nmax)
8974 (unless (wholenump n)
8975 (user-error "Invalid number of replications %s" n))
8976 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8977 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8978 shift)))
8979 (user-error "Invalid shift specification %s" shift))
8980 (when doshift
8981 (setq shift-n (string-to-number (match-string 1 shift))
8982 shift-what (cdr (assoc (match-string 2 shift)
8983 '(("d" . day) ("w" . week)
8984 ("m" . month) ("y" . year))))))
8985 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8986 (setq nmin 1 nmax n)
8987 (org-back-to-heading t)
8988 (setq beg (point))
8989 (setq idprop (org-entry-get nil "ID"))
8990 (org-end-of-subtree t t)
8991 (or (bolp) (insert "\n"))
8992 (setq end (point))
8993 (setq template (buffer-substring beg end))
8994 (when (and doshift
8995 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8996 (delete-region beg end)
8997 (setq end beg)
8998 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8999 (goto-char end)
9000 (cl-loop for n from nmin to nmax do
9001 ;; prepare clone
9002 (with-temp-buffer
9003 (insert template)
9004 (org-mode)
9005 (goto-char (point-min))
9006 (org-show-subtree)
9007 (and idprop (if org-clone-delete-id
9008 (org-entry-delete nil "ID")
9009 (org-id-get-create t)))
9010 (unless (= n 0)
9011 (while (re-search-forward org-clock-re nil t)
9012 (kill-whole-line))
9013 (goto-char (point-min))
9014 (while (re-search-forward drawer-re nil t)
9015 (org-remove-empty-drawer-at (point))))
9016 (goto-char (point-min))
9017 (when doshift
9018 (while (re-search-forward org-ts-regexp-both nil t)
9019 (org-timestamp-change (* n shift-n) shift-what))
9020 (unless (= n n-no-remove)
9021 (goto-char (point-min))
9022 (while (re-search-forward org-ts-regexp nil t)
9023 (save-excursion
9024 (goto-char (match-beginning 0))
9025 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
9026 (delete-region (match-beginning 1) (match-end 1)))))))
9027 (setq task (buffer-string)))
9028 (insert task))
9029 (goto-char beg)))
9031 ;;; Outline Sorting
9033 (defun org-sort (with-case)
9034 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
9035 Optional argument WITH-CASE means sort case-sensitively."
9036 (interactive "P")
9037 (cond
9038 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
9039 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
9041 (org-call-with-arg 'org-sort-entries with-case))))
9043 (defun org-sort-remove-invisible (s)
9044 "Remove invisible links from string S."
9045 (remove-text-properties 0 (length s) org-rm-props s)
9046 (while (string-match org-bracket-link-regexp s)
9047 (setq s (replace-match (if (match-end 2)
9048 (match-string 3 s)
9049 (match-string 1 s))
9050 t t s)))
9051 (let ((st (format " %s " s)))
9052 (while (string-match org-emph-re st)
9053 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
9054 (setq s (substring st 1 -1)))
9057 (defvar org-priority-regexp) ; defined later in the file
9059 (defvar org-after-sorting-entries-or-items-hook nil
9060 "Hook that is run after a bunch of entries or items have been sorted.
9061 When children are sorted, the cursor is in the parent line when this
9062 hook gets called. When a region or a plain list is sorted, the cursor
9063 will be in the first entry of the sorted region/list.")
9065 (defun org-sort-entries
9066 (&optional with-case sorting-type getkey-func compare-func property)
9067 "Sort entries on a certain level of an outline tree.
9068 If there is an active region, the entries in the region are sorted.
9069 Else, if the cursor is before the first entry, sort the top-level items.
9070 Else, the children of the entry at point are sorted.
9072 Sorting can be alphabetically, numerically, by date/time as given by
9073 a time stamp, by a property, by priority order, or by a custom function.
9075 The command prompts for the sorting type unless it has been given to the
9076 function through the SORTING-TYPE argument, which needs to be a character,
9077 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9078 the precise meaning of each character:
9080 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9081 c By creation time, which is assumed to be the first inactive time stamp
9082 at the beginning of a line.
9083 d By deadline date/time.
9084 k By clocking time.
9085 n Numerically, by converting the beginning of the entry/item to a number.
9086 o By order of TODO keywords.
9087 p By priority according to the cookie.
9088 r By the value of a property.
9089 s By scheduled date/time.
9090 t By date/time, either the first active time stamp in the entry, or, if
9091 none exist, by the first inactive one.
9093 Capital letters will reverse the sort order.
9095 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9096 called with point at the beginning of the record. It must return either
9097 a string or a number that should serve as the sorting key for that record.
9099 Comparing entries ignores case by default. However, with an optional argument
9100 WITH-CASE, the sorting considers case as well.
9102 Sorting is done against the visible part of the headlines, it ignores hidden
9103 links.
9105 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
9106 (interactive "P")
9107 (let ((case-func (if with-case 'identity 'downcase))
9108 (cmstr
9109 ;; The clock marker is lost when using `sort-subr', let's
9110 ;; store the clocking string.
9111 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9112 (save-excursion
9113 (goto-char org-clock-marker)
9114 (buffer-substring-no-properties (line-beginning-position)
9115 (point)))))
9116 start beg end stars re re2
9117 txt what tmp)
9118 ;; Find beginning and end of region to sort
9119 (cond
9120 ((org-region-active-p)
9121 ;; we will sort the region
9122 (setq end (region-end)
9123 what "region")
9124 (goto-char (region-beginning))
9125 (unless (org-at-heading-p) (outline-next-heading))
9126 (setq start (point)))
9127 ((or (org-at-heading-p)
9128 (ignore-errors (progn (org-back-to-heading) t)))
9129 ;; we will sort the children of the current headline
9130 (org-back-to-heading)
9131 (setq start (point)
9132 end (progn (org-end-of-subtree t t)
9133 (or (bolp) (insert "\n"))
9134 (when (>= (org-back-over-empty-lines) 1)
9135 (forward-line 1))
9136 (point))
9137 what "children")
9138 (goto-char start)
9139 (outline-show-subtree)
9140 (outline-next-heading))
9142 ;; we will sort the top-level entries in this file
9143 (goto-char (point-min))
9144 (or (org-at-heading-p) (outline-next-heading))
9145 (setq start (point))
9146 (goto-char (point-max))
9147 (beginning-of-line 1)
9148 (when (looking-at ".*?\\S-")
9149 ;; File ends in a non-white line
9150 (end-of-line 1)
9151 (insert "\n"))
9152 (setq end (point-max))
9153 (setq what "top-level")
9154 (goto-char start)
9155 (outline-show-all)))
9157 (setq beg (point))
9158 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9160 (looking-at "\\(\\*+\\)")
9161 (setq stars (match-string 1)
9162 re (concat "^" (regexp-quote stars) " +")
9163 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9164 txt (buffer-substring beg end))
9165 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9166 (when (and (not (equal stars "*")) (string-match re2 txt))
9167 (user-error "Region to sort contains a level above the first entry"))
9169 (unless sorting-type
9170 (message
9171 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9172 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9173 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9174 what)
9175 (setq sorting-type (read-char-exclusive))
9177 (unless getkey-func
9178 (and (= (downcase sorting-type) ?f)
9179 (setq getkey-func
9180 (completing-read "Sort using function: "
9181 obarray 'fboundp t nil nil))
9182 (setq getkey-func (intern getkey-func))))
9184 (and (= (downcase sorting-type) ?r)
9185 (not property)
9186 (setq property
9187 (completing-read "Property: "
9188 (mapcar #'list (org-buffer-property-keys t))
9189 nil t))))
9191 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9192 (message "Sorting entries...")
9194 (save-restriction
9195 (narrow-to-region start end)
9196 (let ((dcst (downcase sorting-type))
9197 (case-fold-search nil)
9198 (now (current-time)))
9199 (sort-subr
9200 (/= dcst sorting-type)
9201 ;; This function moves to the beginning character of the "record" to
9202 ;; be sorted.
9203 (lambda nil
9204 (if (re-search-forward re nil t)
9205 (goto-char (match-beginning 0))
9206 (goto-char (point-max))))
9207 ;; This function moves to the last character of the "record" being
9208 ;; sorted.
9209 (lambda nil
9210 (save-match-data
9211 (condition-case nil
9212 (outline-forward-same-level 1)
9213 (error
9214 (goto-char (point-max))))))
9215 ;; This function returns the value that gets sorted against.
9216 (lambda nil
9217 (cond
9218 ((= dcst ?n)
9219 (if (looking-at org-complex-heading-regexp)
9220 (string-to-number (org-sort-remove-invisible (match-string 4)))
9221 nil))
9222 ((= dcst ?a)
9223 (if (looking-at org-complex-heading-regexp)
9224 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9225 nil))
9226 ((= dcst ?k)
9227 (or (get-text-property (point) :org-clock-minutes) 0))
9228 ((= dcst ?t)
9229 (let ((end (save-excursion (outline-next-heading) (point))))
9230 (if (or (re-search-forward org-ts-regexp end t)
9231 (re-search-forward org-ts-regexp-both end t))
9232 (org-time-string-to-seconds (match-string 0))
9233 (float-time now))))
9234 ((= dcst ?c)
9235 (let ((end (save-excursion (outline-next-heading) (point))))
9236 (if (re-search-forward
9237 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9238 end t)
9239 (org-time-string-to-seconds (match-string 0))
9240 (float-time now))))
9241 ((= dcst ?s)
9242 (let ((end (save-excursion (outline-next-heading) (point))))
9243 (if (re-search-forward org-scheduled-time-regexp end t)
9244 (org-time-string-to-seconds (match-string 1))
9245 (float-time now))))
9246 ((= dcst ?d)
9247 (let ((end (save-excursion (outline-next-heading) (point))))
9248 (if (re-search-forward org-deadline-time-regexp end t)
9249 (org-time-string-to-seconds (match-string 1))
9250 (float-time now))))
9251 ((= dcst ?p)
9252 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9253 (string-to-char (match-string 2))
9254 org-default-priority))
9255 ((= dcst ?r)
9256 (or (org-entry-get nil property) ""))
9257 ((= dcst ?o)
9258 (when (looking-at org-complex-heading-regexp)
9259 (let* ((m (match-string 2))
9260 (s (if (member m org-done-keywords) '- '+)))
9261 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9262 ((= dcst ?f)
9263 (if getkey-func
9264 (progn
9265 (setq tmp (funcall getkey-func))
9266 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9267 tmp)
9268 (error "Invalid key function `%s'" getkey-func)))
9269 (t (error "Invalid sorting type `%c'" sorting-type))))
9271 (cond
9272 ((= dcst ?a) 'string<)
9273 ((= dcst ?f) compare-func)
9274 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9275 (run-hooks 'org-after-sorting-entries-or-items-hook)
9276 ;; Reset the clock marker if needed
9277 (when cmstr
9278 (save-excursion
9279 (goto-char start)
9280 (search-forward cmstr nil t)
9281 (move-marker org-clock-marker (point))))
9282 (message "Sorting entries...done")))
9284 ;;; The orgstruct minor mode
9286 ;; Define a minor mode which can be used in other modes in order to
9287 ;; integrate the Org mode structure editing commands.
9289 ;; This is really a hack, because the Org mode structure commands use
9290 ;; keys which normally belong to the major mode. Here is how it
9291 ;; works: The minor mode defines all the keys necessary to operate the
9292 ;; structure commands, but wraps the commands into a function which
9293 ;; tests if the cursor is currently at a headline or a plain list
9294 ;; item. If that is the case, the structure command is used,
9295 ;; temporarily setting many Org mode variables like regular
9296 ;; expressions for filling etc. However, when any of those keys is
9297 ;; used at a different location, function uses `key-binding' to look
9298 ;; up if the key has an associated command in another currently active
9299 ;; keymap (minor modes, major mode, global), and executes that
9300 ;; command. There might be problems if any of the keys is otherwise
9301 ;; used as a prefix key.
9303 (defcustom orgstruct-heading-prefix-regexp ""
9304 "Regexp that matches the custom prefix of Org headlines in
9305 orgstruct(++)-mode."
9306 :group 'org
9307 :version "24.4"
9308 :package-version '(Org . "8.3")
9309 :type 'regexp)
9310 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9312 (defcustom orgstruct-setup-hook nil
9313 "Hook run after orgstruct-mode-map is filled."
9314 :group 'org
9315 :version "24.4"
9316 :package-version '(Org . "8.0")
9317 :type 'hook)
9319 (defvar orgstruct-initialized nil)
9321 (defvar org-local-vars nil
9322 "List of local variables, for use by `orgstruct-mode'.")
9324 ;;;###autoload
9325 (define-minor-mode orgstruct-mode
9326 "Toggle the minor mode `orgstruct-mode'.
9327 This mode is for using Org mode structure commands in other
9328 modes. The following keys behave as if Org mode were active, if
9329 the cursor is on a headline, or on a plain list item (both as
9330 defined by Org mode)."
9331 nil " OrgStruct" (make-sparse-keymap)
9332 (funcall (if orgstruct-mode
9333 'add-to-invisibility-spec
9334 'remove-from-invisibility-spec)
9335 '(outline . t))
9336 (when orgstruct-mode
9337 (org-load-modules-maybe)
9338 (unless orgstruct-initialized
9339 (orgstruct-setup)
9340 (setq orgstruct-initialized t))))
9342 ;;;###autoload
9343 (defun turn-on-orgstruct ()
9344 "Unconditionally turn on `orgstruct-mode'."
9345 (orgstruct-mode 1))
9347 (defvar-local orgstruct-is-++ nil
9348 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9349 (defvar-local org-fb-vars nil)
9350 (defun orgstruct++-mode (&optional arg)
9351 "Toggle `orgstruct-mode', the enhanced version of it.
9352 In addition to setting orgstruct-mode, this also exports all
9353 indentation and autofilling variables from Org mode into the
9354 buffer. It will also recognize item context in multiline items."
9355 (interactive "P")
9356 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9357 (if (< arg 1)
9358 (progn (orgstruct-mode -1)
9359 (dolist (v org-fb-vars)
9360 (set (make-local-variable (car v))
9361 (if (eq (car-safe (cadr v)) 'quote)
9362 (cl-cadadr v)
9363 (nth 1 v)))))
9364 (orgstruct-mode 1)
9365 (setq org-fb-vars nil)
9366 (unless org-local-vars
9367 (setq org-local-vars (org-get-local-variables)))
9368 (let (var val)
9369 (dolist (x org-local-vars)
9370 (when (string-match
9371 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9372 \\|fill-prefix\\|indent-\\)"
9373 (symbol-name (car x)))
9374 (setq var (car x) val (nth 1 x))
9375 (push (list var `(quote ,(eval var))) org-fb-vars)
9376 (set (make-local-variable var)
9377 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9378 (setq-local orgstruct-is-++ t))))
9380 ;;;###autoload
9381 (defun turn-on-orgstruct++ ()
9382 "Unconditionally turn on `orgstruct++-mode'."
9383 (orgstruct++-mode 1))
9385 (defun orgstruct-error ()
9386 "Error when there is no default binding for a structure key."
9387 (interactive)
9388 (funcall (if (fboundp 'user-error)
9389 'user-error
9390 'error)
9391 "This key has no function outside structure elements"))
9393 (defun orgstruct-setup ()
9394 "Setup orgstruct keymap."
9395 (dolist (cell '((org-demote . t)
9396 (org-metaleft . t)
9397 (org-metaright . t)
9398 (org-promote . t)
9399 (org-shiftmetaleft . t)
9400 (org-shiftmetaright . t)
9401 org-backward-element
9402 org-backward-heading-same-level
9403 org-ctrl-c-ret
9404 org-ctrl-c-minus
9405 org-ctrl-c-star
9406 org-cycle
9407 org-force-cycle-archived
9408 org-forward-heading-same-level
9409 org-insert-heading
9410 org-insert-heading-respect-content
9411 org-kill-note-or-show-branches
9412 org-mark-subtree
9413 org-meta-return
9414 org-metadown
9415 org-metaup
9416 org-narrow-to-subtree
9417 org-promote-subtree
9418 org-reveal
9419 org-shiftdown
9420 org-shiftleft
9421 org-shiftmetadown
9422 org-shiftmetaup
9423 org-shiftright
9424 org-shifttab
9425 org-shifttab
9426 org-shiftup
9427 org-show-children
9428 org-show-subtree
9429 org-sort
9430 org-up-element
9431 outline-demote
9432 outline-next-visible-heading
9433 outline-previous-visible-heading
9434 outline-promote
9435 outline-up-heading))
9436 (let ((f (or (car-safe cell) cell))
9437 (disable-when-heading-prefix (cdr-safe cell)))
9438 (when (fboundp f)
9439 (let ((new-bindings))
9440 (dolist (binding (nconc (where-is-internal f org-mode-map)
9441 (where-is-internal f outline-mode-map)))
9442 (push binding new-bindings)
9443 ;; TODO use local-function-key-map
9444 (dolist (rep '(("<tab>" . "TAB")
9445 ("<return>" . "RET")
9446 ("<escape>" . "ESC")
9447 ("<delete>" . "DEL")))
9448 (setq binding (read-kbd-macro
9449 (let ((case-fold-search))
9450 (replace-regexp-in-string
9451 (regexp-quote (cdr rep))
9452 (car rep)
9453 (key-description binding)))))
9454 (cl-pushnew binding new-bindings :test 'equal)))
9455 (dolist (binding new-bindings)
9456 (let ((key (lookup-key orgstruct-mode-map binding)))
9457 (when (or (not key) (numberp key))
9458 (ignore-errors
9459 (org-defkey orgstruct-mode-map
9460 binding
9461 (orgstruct-make-binding
9462 f binding disable-when-heading-prefix))))))))))
9463 (run-hooks 'orgstruct-setup-hook))
9465 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9466 "Create a function for binding in the structure minor mode.
9467 FUN is the command to call inside a table. KEY is the key that
9468 should be checked in for a command to execute outside of tables.
9469 Non-nil `disable-when-heading-prefix' means to disable the command
9470 if `orgstruct-heading-prefix-regexp' is not empty."
9471 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9472 (let ((nname name)
9473 (i 0))
9474 (while (fboundp (intern nname))
9475 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9476 (setq name (intern nname)))
9477 (eval
9478 (let ((bindings '((org-heading-regexp
9479 (concat "^"
9480 orgstruct-heading-prefix-regexp
9481 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9482 (org-outline-regexp
9483 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9484 (org-outline-regexp-bol
9485 (concat "^" org-outline-regexp))
9486 (outline-regexp org-outline-regexp)
9487 (outline-heading-end-regexp "\n")
9488 (outline-level 'org-outline-level)
9489 (outline-heading-alist))))
9490 `(defun ,name (arg)
9491 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9492 "Outside of structure, run the binding of `"
9493 (key-description key) "'."
9494 (when disable-when-heading-prefix
9495 (concat
9496 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9497 "back to the default binding due to limitations of Org's implementation of\n"
9498 "`" (symbol-name fun) "'.")))
9499 (interactive "p")
9500 (let* ((disable
9501 ,(and disable-when-heading-prefix
9502 '(not (string= orgstruct-heading-prefix-regexp ""))))
9503 (fallback
9504 (or disable
9505 (not
9506 (let* ,bindings
9507 (org-context-p 'headline 'item
9508 ,(when (memq fun
9509 '(org-insert-heading
9510 org-insert-heading-respect-content
9511 org-meta-return))
9512 '(when orgstruct-is-++
9513 'item-body))))))))
9514 (if fallback
9515 (let* ((orgstruct-mode)
9516 (binding
9517 (let ((key ,key))
9518 (catch 'exit
9519 (dolist
9520 (rep
9521 '(nil
9522 ("<\\([^>]*\\)tab>" . "\\1TAB")
9523 ("<\\([^>]*\\)return>" . "\\1RET")
9524 ("<\\([^>]*\\)escape>" . "\\1ESC")
9525 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9526 nil)
9527 (when rep
9528 (setq key (read-kbd-macro
9529 (let ((case-fold-search))
9530 (replace-regexp-in-string
9531 (car rep)
9532 (cdr rep)
9533 (key-description key))))))
9534 (when (key-binding key)
9535 (throw 'exit (key-binding key))))))))
9536 (if (keymapp binding)
9537 (org-set-transient-map binding)
9538 (let ((func (or binding
9539 (unless disable
9540 'orgstruct-error))))
9541 (when func
9542 (call-interactively func)))))
9543 (org-run-like-in-org-mode
9544 (lambda ()
9545 (interactive)
9546 (let* ,bindings
9547 (call-interactively ',fun)))))))))
9548 name))
9550 (defun org-contextualize-keys (alist contexts)
9551 "Return valid elements in ALIST depending on CONTEXTS.
9553 `org-agenda-custom-commands' or `org-capture-templates' are the
9554 values used for ALIST, and `org-agenda-custom-commands-contexts'
9555 or `org-capture-templates-contexts' are the associated contexts
9556 definitions."
9557 (let ((contexts
9558 ;; normalize contexts
9559 (mapcar
9560 (lambda(c) (cond ((listp (cadr c))
9561 (list (car c) (car c) (nth 1 c)))
9562 ((string= "" (cadr c))
9563 (list (car c) (car c) (nth 2 c)))
9564 (t c)))
9565 contexts))
9566 (a alist) r s)
9567 ;; loop over all commands or templates
9568 (dolist (c a)
9569 (let (vrules repl)
9570 (cond
9571 ((not (assoc (car c) contexts))
9572 (push c r))
9573 ((and (assoc (car c) contexts)
9574 (setq vrules (org-contextualize-validate-key
9575 (car c) contexts)))
9576 (mapc (lambda (vr)
9577 (unless (equal (car vr) (cadr vr))
9578 (setq repl vr)))
9579 vrules)
9580 (if (not repl) (push c r)
9581 (push (cadr repl) s)
9582 (push
9583 (cons (car c)
9584 (cdr (or (assoc (cadr repl) alist)
9585 (error "Undefined key `%s' as contextual replacement for `%s'"
9586 (cadr repl) (car c)))))
9587 r))))))
9588 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9589 (delq
9591 (delete-dups
9592 (mapcar (lambda (x)
9593 (let ((tpl (car x)))
9594 (unless (delq
9596 (mapcar (lambda (y)
9597 (equal y tpl))
9599 x)))
9600 (reverse r))))))
9602 (defun org-contextualize-validate-key (key contexts)
9603 "Check CONTEXTS for agenda or capture KEY."
9604 (let (res)
9605 (dolist (r contexts)
9606 (dolist (rr (car (last r)))
9607 (when
9608 (and (equal key (car r))
9609 (if (functionp rr) (funcall rr)
9610 (or (and (eq (car rr) 'in-file)
9611 (buffer-file-name)
9612 (string-match (cdr rr) (buffer-file-name)))
9613 (and (eq (car rr) 'in-mode)
9614 (string-match (cdr rr) (symbol-name major-mode)))
9615 (and (eq (car rr) 'in-buffer)
9616 (string-match (cdr rr) (buffer-name)))
9617 (when (and (eq (car rr) 'not-in-file)
9618 (buffer-file-name))
9619 (not (string-match (cdr rr) (buffer-file-name))))
9620 (when (eq (car rr) 'not-in-mode)
9621 (not (string-match (cdr rr) (symbol-name major-mode))))
9622 (when (eq (car rr) 'not-in-buffer)
9623 (not (string-match (cdr rr) (buffer-name)))))))
9624 (push r res))))
9625 (delete-dups (delq nil res))))
9627 (defun org-context-p (&rest contexts)
9628 "Check if local context is any of CONTEXTS.
9629 Possible values in the list of contexts are `table', `headline', and `item'."
9630 (let ((pos (point)))
9631 (goto-char (point-at-bol))
9632 (prog1 (or (and (memq 'table contexts)
9633 (looking-at "[ \t]*|"))
9634 (and (memq 'headline contexts)
9635 (looking-at org-outline-regexp))
9636 (and (memq 'item contexts)
9637 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9638 (and (memq 'item-body contexts)
9639 (org-in-item-p)))
9640 (goto-char pos))))
9642 (defconst org-unique-local-variables
9643 '(org-element--cache
9644 org-element--cache-objects
9645 org-element--cache-sync-keys
9646 org-element--cache-sync-requests
9647 org-element--cache-sync-timer)
9648 "List of local variables that cannot be transferred to another buffer.")
9650 (defun org-get-local-variables ()
9651 "Return a list of all local variables in an Org mode buffer."
9652 (delq nil
9653 (mapcar
9654 (lambda (x)
9655 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9656 (name (car binding)))
9657 (and (not (get name 'org-state))
9658 (not (memq name org-unique-local-variables))
9659 (string-match-p
9660 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9661 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9662 (symbol-name name))
9663 binding)))
9664 (with-temp-buffer
9665 (org-mode)
9666 (buffer-local-variables)))))
9668 (defun org-clone-local-variables (from-buffer &optional regexp)
9669 "Clone local variables from FROM-BUFFER.
9670 Optional argument REGEXP selects variables to clone."
9671 (dolist (pair (buffer-local-variables from-buffer))
9672 (let ((name (car pair)))
9673 (when (and (symbolp name)
9674 (not (memq name org-unique-local-variables))
9675 (or (null regexp) (string-match regexp (symbol-name name))))
9676 (set (make-local-variable name) (cdr pair))))))
9678 ;;;###autoload
9679 (defun org-run-like-in-org-mode (cmd)
9680 "Run a command, pretending that the current buffer is in Org mode.
9681 This will temporarily bind local variables that are typically bound in
9682 Org mode to the values they have in Org mode, and then interactively
9683 call CMD."
9684 (org-load-modules-maybe)
9685 (unless org-local-vars
9686 (setq org-local-vars (org-get-local-variables)))
9687 (let (binds)
9688 (dolist (var org-local-vars)
9689 (when (or (not (boundp (car var)))
9690 (eq (symbol-value (car var))
9691 (default-value (car var))))
9692 (push (list (car var) `(quote ,(cadr var))) binds)))
9693 (eval `(let ,binds
9694 (call-interactively (quote ,cmd))))))
9696 (defun org-get-category (&optional pos force-refresh)
9697 "Get the category applying to position POS."
9698 (save-match-data
9699 (when force-refresh (org-refresh-category-properties))
9700 (let ((pos (or pos (point))))
9701 (or (get-text-property pos 'org-category)
9702 (progn (org-refresh-category-properties)
9703 (get-text-property pos 'org-category))))))
9705 ;;; Refresh properties
9707 (defun org-refresh-properties (dprop tprop)
9708 "Refresh buffer text properties.
9709 DPROP is the drawer property and TPROP is either the
9710 corresponding text property to set, or an alist with each element
9711 being a text property (as a symbol) and a function to apply to
9712 the value of the drawer property."
9713 (let ((case-fold-search t)
9714 (inhibit-read-only t))
9715 (org-with-silent-modifications
9716 (org-with-wide-buffer
9717 (goto-char (point-min))
9718 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9719 (org-refresh-property tprop (match-string-no-properties 1)))))))
9721 (defun org-refresh-property (tprop p)
9722 "Refresh the buffer text property TPROP from the drawer property P.
9723 The refresh happens only for the current tree (not subtree)."
9724 (unless (org-before-first-heading-p)
9725 (save-excursion
9726 (org-back-to-heading t)
9727 (if (symbolp tprop)
9728 ;; TPROP is a text property symbol
9729 (put-text-property
9730 (point) (or (outline-next-heading) (point-max)) tprop p)
9731 ;; TPROP is an alist with (properties . function) elements
9732 (dolist (al tprop)
9733 (save-excursion
9734 (put-text-property
9735 (line-beginning-position) (or (outline-next-heading) (point-max))
9736 (car al)
9737 (funcall (cdr al) p))))))))
9739 (defun org-refresh-category-properties ()
9740 "Refresh category text properties in the buffer."
9741 (let ((case-fold-search t)
9742 (inhibit-read-only t)
9743 (default-category
9744 (cond ((null org-category)
9745 (if buffer-file-name
9746 (file-name-sans-extension
9747 (file-name-nondirectory buffer-file-name))
9748 "???"))
9749 ((symbolp org-category) (symbol-name org-category))
9750 (t org-category))))
9751 (org-with-silent-modifications
9752 (org-with-wide-buffer
9753 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9754 ;; This is the default category for the buffer. If none is
9755 ;; found, fall-back to `org-category' or buffer file name.
9756 (put-text-property
9757 (point-min) (point-max)
9758 'org-category
9759 (catch 'buffer-category
9760 (goto-char (point-max))
9761 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9762 (let ((element (org-element-at-point)))
9763 (when (eq (org-element-type element) 'keyword)
9764 (throw 'buffer-category
9765 (org-element-property :value element)))))
9766 default-category))
9767 ;; Set sub-tree specific categories.
9768 (goto-char (point-min))
9769 (let ((regexp (org-re-property "CATEGORY")))
9770 (while (re-search-forward regexp nil t)
9771 (let ((value (match-string-no-properties 3)))
9772 (when (org-at-property-p)
9773 (put-text-property
9774 (save-excursion (org-back-to-heading t) (point))
9775 (save-excursion (org-end-of-subtree t t) (point))
9776 'org-category
9777 value)))))))))
9779 (defun org-refresh-stats-properties ()
9780 "Refresh stats text properties in the buffer."
9781 (let (stats)
9782 (org-with-silent-modifications
9783 (org-with-wide-buffer
9784 (goto-char (point-min))
9785 (while (re-search-forward
9786 (concat org-outline-regexp-bol ".*"
9787 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9788 nil t)
9789 (setq stats (cond ((equal (match-string 3) "0") 0)
9790 ((match-string 2)
9791 (/ (* (string-to-number (match-string 2)) 100)
9792 (string-to-number (match-string 3))))
9793 (t (string-to-number (match-string 1)))))
9794 (org-back-to-heading t)
9795 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9796 'org-stats stats))))))
9798 (defun org-refresh-effort-properties ()
9799 "Refresh effort properties"
9800 (org-refresh-properties
9801 org-effort-property
9802 '((effort . identity)
9803 (effort-minutes . org-duration-string-to-minutes))))
9805 ;;;; Link Stuff
9807 ;;; Link abbreviations
9809 (defun org-link-expand-abbrev (link)
9810 "Apply replacements as defined in `org-link-abbrev-alist'."
9811 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9812 (let* ((key (match-string 1 link))
9813 (as (or (assoc key org-link-abbrev-alist-local)
9814 (assoc key org-link-abbrev-alist)))
9815 (tag (and (match-end 2) (match-string 3 link)))
9816 rpl)
9817 (if (not as)
9818 link
9819 (setq rpl (cdr as))
9820 (cond
9821 ((symbolp rpl) (funcall rpl tag))
9822 ((string-match "%(\\([^)]+\\))" rpl)
9823 (replace-match
9824 (save-match-data
9825 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9826 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9827 ((string-match "%h" rpl)
9828 (replace-match (url-hexify-string (or tag "")) t t rpl))
9829 (t (concat rpl tag)))))
9830 link))
9832 ;;; Storing and inserting links
9834 (defvar org-insert-link-history nil
9835 "Minibuffer history for links inserted with `org-insert-link'.")
9837 (defvar org-stored-links nil
9838 "Contains the links stored with `org-store-link'.")
9840 (defvar org-store-link-plist nil
9841 "Plist with info about the most recently link created with `org-store-link'.")
9843 (defun org-store-link-functions ()
9844 "Return a list of functions that are called to create and store a link.
9845 The functions defined in the :store property of
9846 `org-link-parameters'.
9848 Each function will be called in turn until one returns a non-nil
9849 value. Each function should check if it is responsible for
9850 creating this link (for example by looking at the major mode).
9851 If not, it must exit and return nil. If yes, it should return
9852 a non-nil value after calling `org-store-link-props' with a list
9853 of properties and values. Special properties are:
9855 :type The link prefix, like \"http\". This must be given.
9856 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9857 This is obligatory as well.
9858 :description Optional default description for the second pair
9859 of brackets in an Org mode link. The user can still change
9860 this when inserting this link into an Org mode buffer.
9862 In addition to these, any additional properties can be specified
9863 and then used in capture templates."
9864 (cl-loop for link in org-link-parameters
9865 with store-func
9866 do (setq store-func (org-link-get-parameter (car link) :store))
9867 if store-func
9868 collect store-func))
9870 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9871 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9873 ;;;###autoload
9874 (defun org-store-link (arg)
9875 "Store an org-link to the current location.
9876 \\<org-mode-map>
9877 This link is added to `org-stored-links' and can later be inserted
9878 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9880 For some link types, a `\\[universal-argument]' prefix ARG is interpreted.
9881 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9882 For file links, ARG negates `org-context-in-file-links'.
9884 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9885 skipping storing functions that are not
9886 part of Org core.
9888 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9889 prefix ARG forces storing a link for each line in the
9890 active region."
9891 (interactive "P")
9892 (org-load-modules-maybe)
9893 (if (and (equal arg '(64)) (org-region-active-p))
9894 (save-excursion
9895 (let ((end (region-end)))
9896 (goto-char (region-beginning))
9897 (set-mark (point))
9898 (while (< (point-at-eol) end)
9899 (move-end-of-line 1) (activate-mark)
9900 (let (current-prefix-arg)
9901 (call-interactively 'org-store-link))
9902 (move-beginning-of-line 2)
9903 (set-mark (point)))))
9904 (setq org-store-link-plist nil)
9905 (let (link cpltxt desc description search
9906 txt custom-id agenda-link sfuns sfunsn)
9907 (cond
9909 ;; Store a link using an external link type
9910 ((and (not (equal arg '(16)))
9911 (setq sfuns
9912 (delq
9913 nil (mapcar (lambda (f)
9914 (let (fs) (if (funcall f) (push f fs))))
9915 (org-store-link-functions)))
9916 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9917 (or (and (cdr sfuns)
9918 (funcall (intern
9919 (completing-read
9920 "Which function for creating the link? "
9921 sfunsn nil t (car sfunsn)))))
9922 (funcall (caar sfuns)))
9923 (setq link (plist-get org-store-link-plist :link)
9924 desc (or (plist-get org-store-link-plist
9925 :description)
9926 link))))
9928 ;; Store a link from a source code buffer.
9929 ((org-src-edit-buffer-p)
9930 (let ((coderef-format (org-src-coderef-format)))
9931 (cond ((save-excursion
9932 (beginning-of-line)
9933 (looking-at (org-src-coderef-regexp coderef-format)))
9934 (setq link (format "(%s)" (match-string-no-properties 3))))
9935 ((called-interactively-p 'any)
9936 (let ((label (read-string "Code line label: ")))
9937 (end-of-line)
9938 (setq link (format coderef-format label))
9939 (let ((gc (- 79 (length link))))
9940 (if (< (current-column) gc)
9941 (org-move-to-column gc t)
9942 (insert " ")))
9943 (insert link)
9944 (setq link (concat "(" label ")"))
9945 (setq desc nil)))
9946 (t (setq link nil)))))
9948 ;; We are in the agenda, link to referenced location
9949 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9950 (let ((m (or (get-text-property (point) 'org-hd-marker)
9951 (get-text-property (point) 'org-marker))))
9952 (when m
9953 (org-with-point-at m
9954 (setq agenda-link
9955 (if (called-interactively-p 'any)
9956 (call-interactively 'org-store-link)
9957 (org-store-link nil)))))))
9959 ((eq major-mode 'calendar-mode)
9960 (let ((cd (calendar-cursor-to-date)))
9961 (setq link
9962 (format-time-string
9963 (car org-time-stamp-formats)
9964 (apply 'encode-time
9965 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9966 nil nil nil))))
9967 (org-store-link-props :type "calendar" :date cd)))
9969 ((eq major-mode 'help-mode)
9970 (setq link (concat "help:" (save-excursion
9971 (goto-char (point-min))
9972 (looking-at "^[^ ]+")
9973 (match-string 0))))
9974 (org-store-link-props :type "help"))
9976 ((eq major-mode 'w3-mode)
9977 (setq cpltxt (if (and (buffer-name)
9978 (not (string-match "Untitled" (buffer-name))))
9979 (buffer-name)
9980 (url-view-url t))
9981 link (url-view-url t))
9982 (org-store-link-props :type "w3" :url (url-view-url t)))
9984 ((eq major-mode 'image-mode)
9985 (setq cpltxt (concat "file:"
9986 (abbreviate-file-name buffer-file-name))
9987 link cpltxt)
9988 (org-store-link-props :type "image" :file buffer-file-name))
9990 ;; In dired, store a link to the file of the current line
9991 ((derived-mode-p 'dired-mode)
9992 (let ((file (dired-get-filename nil t)))
9993 (setq file (if file
9994 (abbreviate-file-name
9995 (expand-file-name (dired-get-filename nil t)))
9996 ;; otherwise, no file so use current directory.
9997 default-directory))
9998 (setq cpltxt (concat "file:" file)
9999 link cpltxt)))
10001 ((setq search (run-hook-with-args-until-success
10002 'org-create-file-search-functions))
10003 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
10004 "::" search))
10005 (setq cpltxt (or description link)))
10007 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
10008 (org-with-limited-levels
10009 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
10010 (cond
10011 ;; Store a link using the target at point
10012 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
10013 (setq cpltxt
10014 (concat "file:"
10015 (abbreviate-file-name
10016 (buffer-file-name (buffer-base-buffer)))
10017 "::" (match-string 1))
10018 link cpltxt))
10019 ((and (featurep 'org-id)
10020 (or (eq org-id-link-to-org-use-id t)
10021 (and (called-interactively-p 'any)
10022 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
10023 (and (eq org-id-link-to-org-use-id
10024 'create-if-interactive-and-no-custom-id)
10025 (not custom-id))))
10026 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
10027 ;; Store a link using the ID at point
10028 (setq link (condition-case nil
10029 (prog1 (org-id-store-link)
10030 (setq desc (or (plist-get org-store-link-plist
10031 :description)
10032 "")))
10033 (error
10034 ;; Probably before first headline, link only to file
10035 (concat "file:"
10036 (abbreviate-file-name
10037 (buffer-file-name (buffer-base-buffer))))))))
10039 ;; Just link to current headline
10040 (setq cpltxt (concat "file:"
10041 (abbreviate-file-name
10042 (buffer-file-name (buffer-base-buffer)))))
10043 ;; Add a context search string
10044 (when (org-xor org-context-in-file-links arg)
10045 (let* ((element (org-element-at-point))
10046 (name (org-element-property :name element)))
10047 (setq txt (cond
10048 ((org-at-heading-p) nil)
10049 (name)
10050 ((org-region-active-p)
10051 (buffer-substring (region-beginning) (region-end)))))
10052 (when (or (null txt) (string-match "\\S-" txt))
10053 (setq cpltxt
10054 (concat cpltxt "::"
10055 (condition-case nil
10056 (org-make-org-heading-search-string txt)
10057 (error "")))
10058 desc (or name
10059 (nth 4 (ignore-errors (org-heading-components)))
10060 "NONE")))))
10061 (when (string-match "::\\'" cpltxt)
10062 (setq cpltxt (substring cpltxt 0 -2)))
10063 (setq link cpltxt)))))
10065 ((buffer-file-name (buffer-base-buffer))
10066 ;; Just link to this file here.
10067 (setq cpltxt (concat "file:"
10068 (abbreviate-file-name
10069 (buffer-file-name (buffer-base-buffer)))))
10070 ;; Add a context string.
10071 (when (org-xor org-context-in-file-links arg)
10072 (setq txt (if (org-region-active-p)
10073 (buffer-substring (region-beginning) (region-end))
10074 (buffer-substring (point-at-bol) (point-at-eol))))
10075 ;; Only use search option if there is some text.
10076 (when (string-match "\\S-" txt)
10077 (setq cpltxt
10078 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10079 desc "NONE")))
10080 (setq link cpltxt))
10082 ((called-interactively-p 'interactive)
10083 (user-error "No method for storing a link from this buffer"))
10085 (t (setq link nil)))
10087 ;; We're done setting link and desc, clean up
10088 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10089 (setq link (or link cpltxt)
10090 desc (or desc cpltxt))
10091 (cond ((not desc))
10092 ((equal desc "NONE") (setq desc nil))
10093 (t (setq desc
10094 (replace-regexp-in-string
10095 org-bracket-link-analytic-regexp
10096 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10097 desc))))
10098 ;; Return the link
10099 (if (not (and (or (called-interactively-p 'any)
10100 executing-kbd-macro)
10101 link))
10102 (or agenda-link (and link (org-make-link-string link desc)))
10103 (push (list link desc) org-stored-links)
10104 (message "Stored: %s" (or desc link))
10105 (when custom-id
10106 (setq link (concat "file:" (abbreviate-file-name
10107 (buffer-file-name)) "::#" custom-id))
10108 (push (list link desc) org-stored-links))
10109 (car org-stored-links)))))
10111 (defun org-store-link-props (&rest plist)
10112 "Store link properties, extract names, addresses and dates."
10113 (let ((x (plist-get plist :from)))
10114 (when x
10115 (let ((adr (mail-extract-address-components x)))
10116 (setq plist (plist-put plist :fromname (car adr)))
10117 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10118 (let ((x (plist-get plist :to)))
10119 (when x
10120 (let ((adr (mail-extract-address-components x)))
10121 (setq plist (plist-put plist :toname (car adr)))
10122 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10123 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10124 (when x
10125 (setq plist (plist-put plist :date-timestamp
10126 (format-time-string
10127 (org-time-stamp-format t) x)))
10128 (setq plist (plist-put plist :date-timestamp-inactive
10129 (format-time-string
10130 (org-time-stamp-format t t) x)))))
10131 (let ((from (plist-get plist :from))
10132 (to (plist-get plist :to)))
10133 (when (and from to org-from-is-user-regexp)
10134 (setq plist
10135 (plist-put plist :fromto
10136 (if (string-match org-from-is-user-regexp from)
10137 (concat "to %t")
10138 (concat "from %f"))))))
10139 (setq org-store-link-plist plist))
10141 (defun org-add-link-props (&rest plist)
10142 "Add these properties to the link property list."
10143 (let (key value)
10144 (while plist
10145 (setq key (pop plist) value (pop plist))
10146 (setq org-store-link-plist
10147 (plist-put org-store-link-plist key value)))))
10149 (defun org-email-link-description (&optional fmt)
10150 "Return the description part of an email link.
10151 This takes information from `org-store-link-plist' and formats it
10152 according to FMT (default from `org-email-link-description-format')."
10153 (setq fmt (or fmt org-email-link-description-format))
10154 (let* ((p org-store-link-plist)
10155 (to (plist-get p :toaddress))
10156 (from (plist-get p :fromaddress))
10157 (table
10158 (list
10159 (cons "%c" (plist-get p :fromto))
10160 (cons "%F" (plist-get p :from))
10161 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10162 (cons "%T" (plist-get p :to))
10163 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10164 (cons "%s" (plist-get p :subject))
10165 (cons "%d" (plist-get p :date))
10166 (cons "%m" (plist-get p :message-id)))))
10167 (when (string-match "%c" fmt)
10168 ;; Check if the user wrote this message
10169 (if (and org-from-is-user-regexp from to
10170 (save-match-data (string-match org-from-is-user-regexp from)))
10171 (setq fmt (replace-match "to %t" t t fmt))
10172 (setq fmt (replace-match "from %f" t t fmt))))
10173 (org-replace-escapes fmt table)))
10175 (defun org-make-org-heading-search-string (&optional string)
10176 "Make search string for the current headline or STRING."
10177 (let ((s (or string
10178 (and (derived-mode-p 'org-mode)
10179 (save-excursion
10180 (org-back-to-heading t)
10181 (org-element-property :raw-value (org-element-at-point))))))
10182 (lines org-context-in-file-links))
10183 (or string (setq s (concat "*" s))) ; Add * for headlines
10184 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10185 (when (and string (integerp lines) (> lines 0))
10186 (let ((slines (org-split-string s "\n")))
10187 (when (< lines (length slines))
10188 (setq s (mapconcat
10189 'identity
10190 (reverse (nthcdr (- (length slines) lines)
10191 (reverse slines))) "\n")))))
10192 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10194 (defun org-make-link-string (link &optional description)
10195 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10196 (unless (org-string-nw-p link) (error "Empty link"))
10197 (let ((uri (cond ((string-match org-link-types-re link)
10198 (concat (match-string 1 link)
10199 (org-link-escape (substring link (match-end 1)))))
10200 ;; For readability, url-encode internal links only
10201 ;; when absolutely needed (i.e, when they contain
10202 ;; square brackets). File links however, are
10203 ;; encoded since, e.g., spaces are significant.
10204 ((or (file-name-absolute-p link)
10205 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10206 (org-link-escape link))
10207 (t link)))
10208 (description
10209 (and (org-string-nw-p description)
10210 ;; Remove brackets from description, as they are fatal.
10211 (replace-regexp-in-string
10212 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10213 (org-trim description)))))
10214 (format "[[%s]%s]"
10216 (if description (format "[%s]" description) ""))))
10218 (defconst org-link-escape-chars
10219 ;;%20 %5B %5D %25
10220 '(?\s ?\[ ?\] ?%)
10221 "List of characters that should be escaped in a link when stored to Org.
10222 This is the list that is used for internal purposes.")
10224 (defun org-link-escape (text &optional table merge)
10225 "Return percent escaped representation of TEXT.
10226 TEXT is a string with the text to escape.
10227 Optional argument TABLE is a list with characters that should be
10228 escaped. When nil, `org-link-escape-chars' is used.
10229 If optional argument MERGE is set, merge TABLE into
10230 `org-link-escape-chars'."
10231 (let ((characters-to-encode
10232 (cond ((null table) org-link-escape-chars)
10233 (merge (append org-link-escape-chars table))
10234 (t table))))
10235 (mapconcat
10236 (lambda (c)
10237 (if (or (memq c characters-to-encode)
10238 (and org-url-hexify-p (or (< c 32) (> c 126))))
10239 (mapconcat (lambda (e) (format "%%%.2X" e))
10240 (or (encode-coding-char c 'utf-8)
10241 (error "Unable to percent escape character: %c" c))
10243 (char-to-string c)))
10244 text "")))
10246 (defun org-link-unescape (str)
10247 "Unhex hexified Unicode parts in string STR.
10248 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10249 reciprocal of `org-link-escape', which see."
10250 (if (org-string-nw-p str)
10251 (replace-regexp-in-string
10252 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10253 str))
10255 (defun org-link-unescape-compound (hex)
10256 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10257 Note: this function also decodes single byte encodings like
10258 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10259 (save-match-data
10260 (let* ((bytes (cdr (split-string hex "%")))
10261 (ret "")
10262 (eat 0)
10263 (sum 0))
10264 (while bytes
10265 (let* ((val (string-to-number (pop bytes) 16))
10266 (shift-xor
10267 (if (= 0 eat)
10268 (cond
10269 ((>= val 252) (cons 6 252))
10270 ((>= val 248) (cons 5 248))
10271 ((>= val 240) (cons 4 240))
10272 ((>= val 224) (cons 3 224))
10273 ((>= val 192) (cons 2 192))
10274 (t (cons 0 0)))
10275 (cons 6 128))))
10276 (when (>= val 192) (setq eat (car shift-xor)))
10277 (setq val (logxor val (cdr shift-xor)))
10278 (setq sum (+ (lsh sum (car shift-xor)) val))
10279 (when (> eat 0) (setq eat (- eat 1)))
10280 (cond
10281 ((= 0 eat) ;multi byte
10282 (setq ret (concat ret (char-to-string sum)))
10283 (setq sum 0))
10284 ((not bytes) ; single byte(s)
10285 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10286 ret)))
10288 (defun org-link-unescape-single-byte-sequence (hex)
10289 "Unhexify hex-encoded single byte character sequences."
10290 (mapconcat (lambda (byte)
10291 (char-to-string (string-to-number byte 16)))
10292 (cdr (split-string hex "%")) ""))
10294 (defun org-xor (a b)
10295 "Exclusive or."
10296 (if a (not b) b))
10298 (defun org-fixup-message-id-for-http (s)
10299 "Replace special characters in a message id, so it can be used in an http query."
10300 (when (string-match "%" s)
10301 (setq s (mapconcat (lambda (c)
10302 (if (eq c ?%)
10303 "%25"
10304 (char-to-string c)))
10305 s "")))
10306 (while (string-match "<" s)
10307 (setq s (replace-match "%3C" t t s)))
10308 (while (string-match ">" s)
10309 (setq s (replace-match "%3E" t t s)))
10310 (while (string-match "@" s)
10311 (setq s (replace-match "%40" t t s)))
10314 (defun org-link-prettify (link)
10315 "Return a human-readable representation of LINK.
10316 The car of LINK must be a raw link.
10317 The cdr of LINK must be either a link description or nil."
10318 (let ((desc (or (cadr link) "<no description>")))
10319 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10320 "<" (car link) ">")))
10322 ;;;###autoload
10323 (defun org-insert-link-global ()
10324 "Insert a link like Org mode does.
10325 This command can be called in any mode to insert a link in Org syntax."
10326 (interactive)
10327 (org-load-modules-maybe)
10328 (org-run-like-in-org-mode 'org-insert-link))
10330 (defun org-insert-all-links (arg &optional pre post)
10331 "Insert all links in `org-stored-links'.
10332 When a universal prefix, do not delete the links from `org-stored-links'.
10333 When `ARG' is a number, insert the last N link(s).
10334 `PRE' and `POST' are optional arguments to define a string to
10335 prepend or to append."
10336 (interactive "P")
10337 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10338 (links (copy-sequence org-stored-links))
10339 (pr (or pre "- "))
10340 (po (or post "\n"))
10341 (cnt 1) l)
10342 (if (null org-stored-links)
10343 (message "No link to insert")
10344 (while (and (or (listp arg) (>= arg cnt))
10345 (setq l (if (listp arg)
10346 (pop links)
10347 (pop org-stored-links))))
10348 (setq cnt (1+ cnt))
10349 (insert pr)
10350 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10351 (insert po)))))
10353 (defun org-insert-last-stored-link (arg)
10354 "Insert the last link stored in `org-stored-links'."
10355 (interactive "p")
10356 (org-insert-all-links arg "" "\n"))
10358 (defun org-link-fontify-links-to-this-file ()
10359 "Fontify links to the current file in `org-stored-links'."
10360 (let ((f (buffer-file-name)) a b)
10361 (setq a (mapcar (lambda(l)
10362 (let ((ll (car l)))
10363 (when (and (string-match "^file:\\(.+\\)::" ll)
10364 (equal f (expand-file-name (match-string 1 ll))))
10365 ll)))
10366 org-stored-links))
10367 (when (featurep 'org-id)
10368 (setq b (mapcar (lambda(l)
10369 (let ((ll (car l)))
10370 (when (and (string-match "^id:\\(.+\\)$" ll)
10371 (equal f (expand-file-name
10372 (or (org-id-find-id-file
10373 (match-string 1 ll)) ""))))
10374 ll)))
10375 org-stored-links)))
10376 (mapcar (lambda(l)
10377 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10378 (delq nil (append a b)))))
10380 (defvar org--links-history nil)
10381 (defun org-insert-link (&optional complete-file link-location default-description)
10382 "Insert a link. At the prompt, enter the link.
10384 Completion can be used to insert any of the link protocol prefixes in use.
10386 The history can be used to select a link previously stored with
10387 `org-store-link'. When the empty string is entered (i.e. if you just
10388 press `RET' at the prompt), the link defaults to the most recently
10389 stored link. As `SPC' triggers completion in the minibuffer, you need to
10390 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10392 You will also be prompted for a description, and if one is given, it will
10393 be displayed in the buffer instead of the link.
10395 If there is already a link at point, this command will allow you to edit
10396 link and description parts.
10398 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10399 file name can be
10400 selected using completion. The path to the file will be relative to the
10401 current directory if the file is in the current directory or a subdirectory.
10402 Otherwise, the link will be the absolute path as completed in the minibuffer
10403 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10404 option `org-link-file-path-type'.
10406 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10407 absolute path even if the file is in
10408 the current directory or below.
10410 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10411 prefix negates `org-keep-stored-link-after-insertion'.
10413 If `org-make-link-description-function' is non-nil, this function will be
10414 called with the link target, and the result will be the default
10415 link description.
10417 If the LINK-LOCATION parameter is non-nil, this value will be used as
10418 the link location instead of reading one interactively.
10420 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10421 as the default description."
10422 (interactive "P")
10423 (let* ((wcf (current-window-configuration))
10424 (origbuf (current-buffer))
10425 (region (when (org-region-active-p)
10426 (buffer-substring (region-beginning) (region-end))))
10427 (remove (and region (list (region-beginning) (region-end))))
10428 (desc region)
10429 (link link-location)
10430 (abbrevs org-link-abbrev-alist-local)
10431 entry all-prefixes auto-desc)
10432 (cond
10433 (link-location) ; specified by arg, just use it.
10434 ((org-in-regexp org-bracket-link-regexp 1)
10435 ;; We do have a link at point, and we are going to edit it.
10436 (setq remove (list (match-beginning 0) (match-end 0)))
10437 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10438 (setq link (read-string "Link: "
10439 (org-link-unescape
10440 (match-string-no-properties 1)))))
10441 ((or (org-in-regexp org-angle-link-re)
10442 (org-in-regexp org-plain-link-re))
10443 ;; Convert to bracket link
10444 (setq remove (list (match-beginning 0) (match-end 0))
10445 link (read-string "Link: "
10446 (org-unbracket-string "<" ">" (match-string 0)))))
10447 ((member complete-file '((4) (16)))
10448 ;; Completing read for file names.
10449 (setq link (org-file-complete-link complete-file)))
10451 ;; Read link, with completion for stored links.
10452 (org-link-fontify-links-to-this-file)
10453 (org-switch-to-buffer-other-window "*Org Links*")
10454 (with-current-buffer "*Org Links*"
10455 (erase-buffer)
10456 (insert "Insert a link.
10457 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10458 (when org-stored-links
10459 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10460 (insert (mapconcat 'org-link-prettify
10461 (reverse org-stored-links) "\n")))
10462 (goto-char (point-min)))
10463 (let ((cw (selected-window)))
10464 (select-window (get-buffer-window "*Org Links*" 'visible))
10465 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10466 (unless (pos-visible-in-window-p (point-max))
10467 (org-fit-window-to-buffer))
10468 (and (window-live-p cw) (select-window cw)))
10469 (setq all-prefixes (append (mapcar 'car abbrevs)
10470 (mapcar 'car org-link-abbrev-alist)
10471 (org-link-types)))
10472 (unwind-protect
10473 ;; Fake a link history, containing the stored links.
10474 (let ((org--links-history
10475 (append (mapcar #'car org-stored-links)
10476 org-insert-link-history)))
10477 (setq link
10478 (org-completing-read
10479 "Link: "
10480 (append
10481 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10482 (mapcar #'car org-stored-links))
10483 nil nil nil
10484 'org--links-history
10485 (caar org-stored-links)))
10486 (unless (org-string-nw-p link) (user-error "No link selected"))
10487 (dolist (l org-stored-links)
10488 (when (equal link (cadr l))
10489 (setq link (car l))
10490 (setq auto-desc t)))
10491 (when (or (member link all-prefixes)
10492 (and (equal ":" (substring link -1))
10493 (member (substring link 0 -1) all-prefixes)
10494 (setq link (substring link 0 -1))))
10495 (setq link (with-current-buffer origbuf
10496 (org-link-try-special-completion link)))))
10497 (set-window-configuration wcf)
10498 (kill-buffer "*Org Links*"))
10499 (setq entry (assoc link org-stored-links))
10500 (or entry (push link org-insert-link-history))
10501 (setq desc (or desc (nth 1 entry)))))
10503 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10504 (not org-keep-stored-link-after-insertion))
10505 (setq org-stored-links (delq (assoc link org-stored-links)
10506 org-stored-links)))
10508 (when (and (string-match org-plain-link-re link)
10509 (not (string-match org-ts-regexp link)))
10510 ;; URL-like link, normalize the use of angular brackets.
10511 (setq link (org-unbracket-string "<" ">" link)))
10513 ;; Check if we are linking to the current file with a search
10514 ;; option If yes, simplify the link by using only the search
10515 ;; option.
10516 (when (and buffer-file-name
10517 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10518 (let* ((path (match-string 1 link))
10519 (case-fold-search nil)
10520 (search (match-string 2 link)))
10521 (save-match-data
10522 (when (equal (file-truename buffer-file-name) (file-truename path))
10523 ;; We are linking to this same file, with a search option
10524 (setq link search)))))
10526 ;; Check if we can/should use a relative path. If yes, simplify the link
10527 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10528 (let* ((type (match-string 1 link))
10529 (path (match-string 2 link))
10530 (origpath path)
10531 (case-fold-search nil))
10532 (cond
10533 ((or (eq org-link-file-path-type 'absolute)
10534 (equal complete-file '(16)))
10535 (setq path (abbreviate-file-name (expand-file-name path))))
10536 ((eq org-link-file-path-type 'noabbrev)
10537 (setq path (expand-file-name path)))
10538 ((eq org-link-file-path-type 'relative)
10539 (setq path (file-relative-name path)))
10541 (save-match-data
10542 (if (string-match (concat "^" (regexp-quote
10543 (expand-file-name
10544 (file-name-as-directory
10545 default-directory))))
10546 (expand-file-name path))
10547 ;; We are linking a file with relative path name.
10548 (setq path (substring (expand-file-name path)
10549 (match-end 0)))
10550 (setq path (abbreviate-file-name (expand-file-name path)))))))
10551 (setq link (concat type path))
10552 (when (equal desc origpath)
10553 (setq desc path))))
10555 (if org-make-link-description-function
10556 (setq desc
10557 (or (condition-case nil
10558 (funcall org-make-link-description-function link desc)
10559 (error (progn (message "Can't get link description from `%s'"
10560 (symbol-name org-make-link-description-function))
10561 (sit-for 2) nil)))
10562 (read-string "Description: " default-description)))
10563 (if default-description (setq desc default-description)
10564 (setq desc (or (and auto-desc desc)
10565 (read-string "Description: " desc)))))
10567 (unless (string-match "\\S-" desc) (setq desc nil))
10568 (when remove (apply 'delete-region remove))
10569 (insert (org-make-link-string link desc))
10570 ;; Redisplay so as the new link has proper invisible characters.
10571 (sit-for 0)))
10573 (defun org-link-try-special-completion (type)
10574 "If there is completion support for link type TYPE, offer it."
10575 (let ((fun (org-link-get-parameter type :complete)))
10576 (if (functionp fun)
10577 (funcall fun)
10578 (read-string "Link (no completion support): " (concat type ":")))))
10580 (defun org-file-complete-link (&optional arg)
10581 "Create a file link using completion."
10582 (let ((file (read-file-name "File: "))
10583 (pwd (file-name-as-directory (expand-file-name ".")))
10584 (pwd1 (file-name-as-directory (abbreviate-file-name
10585 (expand-file-name ".")))))
10586 (cond ((equal arg '(16))
10587 (concat "file:"
10588 (abbreviate-file-name (expand-file-name file))))
10589 ((string-match
10590 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10591 (concat "file:" (match-string 1 file)))
10592 ((string-match
10593 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10594 (expand-file-name file))
10595 (concat "file:"
10596 (match-string 1 (expand-file-name file))))
10597 (t (concat "file:" file)))))
10599 (defun org-completing-read (&rest args)
10600 "Completing-read with SPACE being a normal character."
10601 (let ((enable-recursive-minibuffers t)
10602 (minibuffer-local-completion-map
10603 (copy-keymap minibuffer-local-completion-map)))
10604 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10605 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10606 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10607 'org-time-stamp-inactive)
10608 (apply #'completing-read args)))
10610 ;;; Opening/following a link
10612 (defvar org-link-search-failed nil)
10614 (defvar org-open-link-functions nil
10615 "Hook for functions finding a plain text link.
10616 These functions must take a single argument, the link content.
10617 They will be called for links that look like [[link text][description]]
10618 when LINK TEXT does not have a protocol like \"http:\" and does not look
10619 like a filename (e.g. \"./blue.png\").
10621 These functions will be called *before* Org attempts to resolve the
10622 link by doing text searches in the current buffer - so if you want a
10623 link \"[[target]]\" to still find \"<<target>>\", your function should
10624 handle this as a special case.
10626 When the function does handle the link, it must return a non-nil value.
10627 If it decides that it is not responsible for this link, it must return
10628 nil to indicate that that Org can continue with other options like
10629 exact and fuzzy text search.")
10631 (defun org-next-link (&optional search-backward)
10632 "Move forward to the next link.
10633 If the link is in hidden text, expose it."
10634 (interactive "P")
10635 (when (and org-link-search-failed (eq this-command last-command))
10636 (goto-char (point-min))
10637 (message "Link search wrapped back to beginning of buffer"))
10638 (setq org-link-search-failed nil)
10639 (let* ((pos (point))
10640 (ct (org-context))
10641 (a (assq :link ct))
10642 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10643 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10644 ((looking-at org-any-link-re)
10645 ;; Don't stay stuck at link without an org-link face
10646 (forward-char (if search-backward -1 1))))
10647 (if (funcall srch-fun org-any-link-re nil t)
10648 (progn
10649 (goto-char (match-beginning 0))
10650 (when (outline-invisible-p) (org-show-context)))
10651 (goto-char pos)
10652 (setq org-link-search-failed t)
10653 (message "No further link found"))))
10655 (defun org-previous-link ()
10656 "Move backward to the previous link.
10657 If the link is in hidden text, expose it."
10658 (interactive)
10659 (funcall 'org-next-link t))
10661 (defun org-translate-link (s)
10662 "Translate a link string if a translation function has been defined."
10663 (with-temp-buffer
10664 (insert (org-trim s))
10665 (org-trim (org-element-interpret-data (org-element-context)))))
10667 (defun org-translate-link-from-planner (type path)
10668 "Translate a link from Emacs Planner syntax so that Org can follow it.
10669 This is still an experimental function, your mileage may vary."
10670 (cond
10671 ((member type '("http" "https" "news" "ftp"))
10672 ;; standard Internet links are the same.
10673 nil)
10674 ((and (equal type "irc") (string-match "^//" path))
10675 ;; Planner has two / at the beginning of an irc link, we have 1.
10676 ;; We should have zero, actually....
10677 (setq path (substring path 1)))
10678 ((and (equal type "lisp") (string-match "^/" path))
10679 ;; Planner has a slash, we do not.
10680 (setq type "elisp" path (substring path 1)))
10681 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10682 ;; A typical message link. Planner has the id after the final slash,
10683 ;; we separate it with a hash mark
10684 (setq path (concat (match-string 1 path) "#"
10685 (org-unbracket-string "<" ">" (match-string 2 path))))))
10686 (cons type path))
10688 (defun org-find-file-at-mouse (ev)
10689 "Open file link or URL at mouse."
10690 (interactive "e")
10691 (mouse-set-point ev)
10692 (org-open-at-point 'in-emacs))
10694 (defun org-open-at-mouse (ev)
10695 "Open file link or URL at mouse.
10696 See the docstring of `org-open-file' for details."
10697 (interactive "e")
10698 (mouse-set-point ev)
10699 (when (eq major-mode 'org-agenda-mode)
10700 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10701 (org-open-at-point))
10703 (defvar org-window-config-before-follow-link nil
10704 "The window configuration before following a link.
10705 This is saved in case the need arises to restore it.")
10707 ;;;###autoload
10708 (defun org-open-at-point-global ()
10709 "Follow a link or time-stamp like Org mode does.
10710 This command can be called in any mode to follow an external link
10711 or a time-stamp that has Org mode syntax. Its behavior is
10712 undefined when called on internal links (e.g., fuzzy links).
10713 Raise an error when there is nothing to follow. "
10714 (interactive)
10715 (cond ((org-in-regexp org-any-link-re)
10716 (org-open-link-from-string (match-string-no-properties 0)))
10717 ((or (org-in-regexp org-ts-regexp-both nil t)
10718 (org-in-regexp org-tsr-regexp-both nil t))
10719 (org-follow-timestamp-link))
10720 (t (user-error "No link found"))))
10722 ;;;###autoload
10723 (defun org-open-link-from-string (s &optional arg reference-buffer)
10724 "Open a link in the string S, as if it was in Org mode."
10725 (interactive "sLink: \nP")
10726 (let ((reference-buffer (or reference-buffer (current-buffer))))
10727 (with-temp-buffer
10728 (let ((org-inhibit-startup (not reference-buffer)))
10729 (org-mode)
10730 (insert s)
10731 (goto-char (point-min))
10732 (when reference-buffer
10733 (setq org-link-abbrev-alist-local
10734 (with-current-buffer reference-buffer
10735 org-link-abbrev-alist-local)))
10736 (org-open-at-point arg reference-buffer)))))
10738 (defvar org-open-at-point-functions nil
10739 "Hook that is run when following a link at point.
10741 Functions in this hook must return t if they identify and follow
10742 a link at point. If they don't find anything interesting at point,
10743 they must return nil.")
10745 (defvar org-link-search-inhibit-query nil)
10746 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10747 (defun org--open-doi-link (path)
10748 "Open a \"doi\" type link.
10749 PATH is a the path to search for, as a string."
10750 (browse-url (url-encode-url (concat org-doi-server-url path))))
10752 (defun org--open-elisp-link (path)
10753 "Open a \"elisp\" type link.
10754 PATH is the sexp to evaluate, as a string."
10755 (let ((cmd path))
10756 (if (or (and (org-string-nw-p
10757 org-confirm-elisp-link-not-regexp)
10758 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10759 (not org-confirm-elisp-link-function)
10760 (funcall org-confirm-elisp-link-function
10761 (format "Execute \"%s\" as elisp? "
10762 (org-add-props cmd nil 'face 'org-warning))))
10763 (message "%s => %s" cmd
10764 (if (eq (string-to-char cmd) ?\()
10765 (eval (read cmd))
10766 (call-interactively (read cmd))))
10767 (user-error "Abort"))))
10769 (defun org--open-help-link (path)
10770 "Open a \"help\" type link.
10771 PATH is a symbol name, as a string."
10772 (pcase (intern path)
10773 ((and (pred fboundp) variable) (describe-function variable))
10774 ((and (pred boundp) function) (describe-variable function))
10775 (name (user-error "Unknown function or variable: %s" name))))
10777 (defun org--open-shell-link (path)
10778 "Open a \"shell\" type link.
10779 PATH is the command to execute, as a string."
10780 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10781 (cmd path))
10782 (if (or (and (org-string-nw-p
10783 org-confirm-shell-link-not-regexp)
10784 (string-match
10785 org-confirm-shell-link-not-regexp cmd))
10786 (not org-confirm-shell-link-function)
10787 (funcall org-confirm-shell-link-function
10788 (format "Execute \"%s\" in shell? "
10789 (org-add-props cmd nil
10790 'face 'org-warning))))
10791 (progn
10792 (message "Executing %s" cmd)
10793 (shell-command cmd buf)
10794 (when (featurep 'midnight)
10795 (setq clean-buffer-list-kill-buffer-names
10796 (cons (buffer-name buf)
10797 clean-buffer-list-kill-buffer-names))))
10798 (user-error "Abort"))))
10800 (defun org-open-at-point (&optional arg reference-buffer)
10801 "Open link, timestamp, footnote or tags at point.
10803 When point is on a link, follow it. Normally, files will be
10804 opened by an appropriate application. If the optional prefix
10805 argument ARG is non-nil, Emacs will visit the file. With
10806 a double prefix argument, try to open outside of Emacs, in the
10807 application the system uses for this file type.
10809 When point is on a timestamp, open the agenda at the day
10810 specified.
10812 When point is a footnote definition, move to the first reference
10813 found. If it is on a reference, move to the associated
10814 definition.
10816 When point is on a headline, display a list of every link in the
10817 entry, so it is possible to pick one, or all, of them. If point
10818 is on a tag, call `org-tags-view' instead.
10820 When optional argument REFERENCE-BUFFER is non-nil, it should
10821 specify a buffer from where the link search should happen. This
10822 is used internally by `org-open-link-from-string'.
10824 On top of syntactically correct links, this function will open
10825 the link at point in comments or comment blocks and the first
10826 link in a property drawer line."
10827 (interactive "P")
10828 ;; On a code block, open block's results.
10829 (unless (call-interactively 'org-babel-open-src-block-result)
10830 (org-load-modules-maybe)
10831 (setq org-window-config-before-follow-link (current-window-configuration))
10832 (org-remove-occur-highlights nil nil t)
10833 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10834 (let* ((context
10835 ;; Only consider supported types, even if they are not
10836 ;; the closest one.
10837 (org-element-lineage
10838 (org-element-context)
10839 '(clock comment comment-block footnote-definition
10840 footnote-reference headline inlinetask keyword link
10841 node-property timestamp)
10843 (type (org-element-type context))
10844 (value (org-element-property :value context)))
10845 (cond
10846 ((not context) (user-error "No link found"))
10847 ;; Exception: open timestamps and links in properties
10848 ;; drawers, keywords and comments.
10849 ((memq type '(comment comment-block keyword node-property))
10850 (call-interactively #'org-open-at-point-global))
10851 ;; On a headline or an inlinetask, but not on a timestamp,
10852 ;; a link, a footnote reference or on tags.
10853 ((and (memq type '(headline inlinetask))
10854 ;; Not on tags.
10855 (let ((case-fold-search nil))
10856 (save-excursion
10857 (beginning-of-line)
10858 (looking-at org-complex-heading-regexp))
10859 (or (not (match-beginning 5))
10860 (< (point) (match-beginning 5)))))
10861 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10862 (links (car data))
10863 (links-end (cdr data)))
10864 (if links
10865 (dolist (link (if (stringp links) (list links) links))
10866 (search-forward link nil links-end)
10867 (goto-char (match-beginning 0))
10868 (org-open-at-point))
10869 (require 'org-attach)
10870 (org-attach-reveal 'if-exists))))
10871 ;; On a clock line, make sure point is on the timestamp
10872 ;; before opening it.
10873 ((and (eq type 'clock)
10874 value
10875 (>= (point) (org-element-property :begin value))
10876 (<= (point) (org-element-property :end value)))
10877 (org-follow-timestamp-link))
10878 ;; Do nothing on white spaces after an object.
10879 ((>= (point)
10880 (save-excursion
10881 (goto-char (org-element-property :end context))
10882 (skip-chars-backward " \t")
10883 (point)))
10884 (user-error "No link found"))
10885 ((eq type 'timestamp) (org-follow-timestamp-link))
10886 ;; On tags within a headline or an inlinetask.
10887 ((and (memq type '(headline inlinetask))
10888 (let ((case-fold-search nil))
10889 (save-excursion (beginning-of-line)
10890 (looking-at org-complex-heading-regexp))
10891 (and (match-beginning 5)
10892 (>= (point) (match-beginning 5)))))
10893 (org-tags-view arg (substring (match-string 5) 0 -1)))
10894 ((eq type 'link)
10895 ;; When link is located within the description of another
10896 ;; link (e.g., an inline image), always open the parent
10897 ;; link.
10898 (let* ((link (let ((up (org-element-property :parent context)))
10899 (if (eq (org-element-type up) 'link) up context)))
10900 (type (org-element-property :type link))
10901 (path (org-link-unescape (org-element-property :path link))))
10902 ;; Switch back to REFERENCE-BUFFER needed when called in
10903 ;; a temporary buffer through `org-open-link-from-string'.
10904 (with-current-buffer (or reference-buffer (current-buffer))
10905 (cond
10906 ((equal type "file")
10907 (if (string-match "[*?{]" (file-name-nondirectory path))
10908 (dired path)
10909 ;; Look into `org-link-parameters' in order to find
10910 ;; a DEDICATED-FUNCTION to open file. The function
10911 ;; will be applied on raw link instead of parsed
10912 ;; link due to the limitation in `org-add-link-type'
10913 ;; ("open" function called with a single argument).
10914 ;; If no such function is found, fallback to
10915 ;; `org-open-file'.
10916 (let* ((option (org-element-property :search-option link))
10917 (app (org-element-property :application link))
10918 (dedicated-function
10919 (org-link-get-parameter
10920 (if app (concat type "+" app) type)
10921 :follow)))
10922 (if dedicated-function
10923 (funcall dedicated-function
10924 (concat path
10925 (and option (concat "::" option))))
10926 (apply #'org-open-file
10927 path
10928 (cond (arg)
10929 ((equal app "emacs") 'emacs)
10930 ((equal app "sys") 'system))
10931 (cond ((not option) nil)
10932 ((string-match-p "\\`[0-9]+\\'" option)
10933 (list (string-to-number option)))
10934 (t (list nil
10935 (org-link-unescape option)))))))))
10936 ((functionp (org-link-get-parameter type :follow))
10937 (funcall (org-link-get-parameter type :follow) path))
10938 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10939 (unless (run-hook-with-args-until-success
10940 'org-open-link-functions path)
10941 (if (not arg) (org-mark-ring-push)
10942 (switch-to-buffer-other-window
10943 (org-get-buffer-for-internal-link (current-buffer))))
10944 (let ((destination
10945 (org-with-wide-buffer
10946 (if (equal type "radio")
10947 (org-search-radio-target
10948 (org-element-property :path link))
10949 (org-link-search
10950 (if (member type '("custom-id" "coderef"))
10951 (org-element-property :raw-link link)
10952 path)
10953 ;; Prevent fuzzy links from matching
10954 ;; themselves.
10955 (and (equal type "fuzzy")
10956 (+ 2 (org-element-property :begin link)))))
10957 (point))))
10958 (unless (and (<= (point-min) destination)
10959 (>= (point-max) destination))
10960 (widen))
10961 (goto-char destination))))
10962 (t (browse-url-at-point))))))
10963 ;; On a footnote reference or at a footnote definition's label.
10964 ((or (eq type 'footnote-reference)
10965 (and (eq type 'footnote-definition)
10966 (save-excursion
10967 ;; Do not validate action when point is on the
10968 ;; spaces right after the footnote label, in
10969 ;; order to be on par with behaviour on links.
10970 (skip-chars-forward " \t")
10971 (let ((begin
10972 (org-element-property :contents-begin context)))
10973 (if begin (< (point) begin)
10974 (= (org-element-property :post-affiliated context)
10975 (line-beginning-position)))))))
10976 (org-footnote-action))
10977 (t (user-error "No link found")))))
10978 (run-hook-with-args 'org-follow-link-hook)))
10980 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10981 "Offer links in the current entry and return the selected link.
10982 If there is only one link, return it.
10983 If NTH is an integer, return the NTH link found.
10984 If ZERO is a string, check also this string for a link, and if
10985 there is one, return it."
10986 (with-current-buffer buffer
10987 (org-with-wide-buffer
10988 (goto-char marker)
10989 (let ((cnt ?0)
10990 have-zero end links link c)
10991 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10992 (push (match-string 0 zero) links)
10993 (setq cnt (1- cnt) have-zero t))
10994 (save-excursion
10995 (org-back-to-heading t)
10996 (setq end (save-excursion (outline-next-heading) (point)))
10997 (while (re-search-forward org-any-link-re end t)
10998 (push (match-string 0) links))
10999 (setq links (org-uniquify (reverse links))))
11000 (cond
11001 ((null links)
11002 (message "No links"))
11003 ((equal (length links) 1)
11004 (setq link (car links)))
11005 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
11006 (setq link (nth (if have-zero nth (1- nth)) links)))
11007 (t ; we have to select a link
11008 (save-excursion
11009 (save-window-excursion
11010 (delete-other-windows)
11011 (with-output-to-temp-buffer "*Select Link*"
11012 (dolist (l links)
11013 (cond
11014 ((not (string-match org-bracket-link-regexp l))
11015 (princ (format "[%c] %s\n" (cl-incf cnt)
11016 (org-unbracket-string "<" ">" l))))
11017 ((match-end 3)
11018 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
11019 (match-string 3 l) (match-string 1 l))))
11020 (t (princ (format "[%c] %s\n" (cl-incf cnt)
11021 (match-string 1 l)))))))
11022 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
11023 (message "Select link to open, RET to open all:")
11024 (setq c (read-char-exclusive))
11025 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
11026 (when (equal c ?q) (user-error "Abort"))
11027 (if (equal c ?\C-m)
11028 (setq link links)
11029 (setq nth (- c ?0))
11030 (when have-zero (setq nth (1+ nth)))
11031 (unless (and (integerp nth) (>= (length links) nth))
11032 (user-error "Invalid link selection"))
11033 (setq link (nth (1- nth) links)))))
11034 (cons link end)))))
11036 ;; TODO: These functions are deprecated since `org-open-at-point'
11037 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
11038 (defun org-open-file-with-system (path)
11039 "Open file at PATH using the system way of opening it."
11040 (org-open-file path 'system))
11041 (defun org-open-file-with-emacs (path)
11042 "Open file at PATH in Emacs."
11043 (org-open-file path 'emacs))
11046 ;;; File search
11048 (defvar org-create-file-search-functions nil
11049 "List of functions to construct the right search string for a file link.
11050 These functions are called in turn with point at the location to
11051 which the link should point.
11053 A function in the hook should first test if it would like to
11054 handle this file type, for example by checking the `major-mode'
11055 or the file extension. If it decides not to handle this file, it
11056 should just return nil to give other functions a chance. If it
11057 does handle the file, it must return the search string to be used
11058 when following the link. The search string will be part of the
11059 file link, given after a double colon, and `org-open-at-point'
11060 will automatically search for it. If special measures must be
11061 taken to make the search successful, another function should be
11062 added to the companion hook `org-execute-file-search-functions',
11063 which see.
11065 A function in this hook may also use `setq' to set the variable
11066 `description' to provide a suggestion for the descriptive text to
11067 be used for this link when it gets inserted into an Org buffer
11068 with \\[org-insert-link].")
11070 (defvar org-execute-file-search-functions nil
11071 "List of functions to execute a file search triggered by a link.
11073 Functions added to this hook must accept a single argument, the
11074 search string that was part of the file link, the part after the
11075 double colon. The function must first check if it would like to
11076 handle this search, for example by checking the `major-mode' or
11077 the file extension. If it decides not to handle this search, it
11078 should just return nil to give other functions a chance. If it
11079 does handle the search, it must return a non-nil value to keep
11080 other functions from trying.
11082 Each function can access the current prefix argument through the
11083 variable `current-prefix-arg'. Note that a single prefix is used
11084 to force opening a link in Emacs, so it may be good to only use a
11085 numeric or double prefix to guide the search function.
11087 In case this is needed, a function in this hook can also restore
11088 the window configuration before `org-open-at-point' was called using:
11090 (set-window-configuration org-window-config-before-follow-link)")
11092 (defun org-search-radio-target (target)
11093 "Search a radio target matching TARGET in current buffer.
11094 White spaces are not significant."
11095 (let ((re (format "<<<%s>>>"
11096 (mapconcat #'regexp-quote
11097 (org-split-string target "[ \t\n]+")
11098 "[ \t]+\\(?:\n[ \t]*\\)?")))
11099 (origin (point)))
11100 (goto-char (point-min))
11101 (catch :radio-match
11102 (while (re-search-forward re nil t)
11103 (backward-char)
11104 (let ((object (org-element-context)))
11105 (when (eq (org-element-type object) 'radio-target)
11106 (goto-char (org-element-property :begin object))
11107 (org-show-context 'link-search)
11108 (throw :radio-match nil))))
11109 (goto-char origin)
11110 (user-error "No match for radio target: %s" target))))
11112 (defun org-link-search (s &optional avoid-pos stealth)
11113 "Search for a search string S.
11115 If S starts with \"#\", it triggers a custom ID search.
11117 If S is enclosed within parenthesis, it initiates a coderef
11118 search.
11120 If S is surrounded by forward slashes, it is interpreted as
11121 a regular expression. In Org mode files, this will create an
11122 `org-occur' sparse tree. In ordinary files, `occur' will be used
11123 to list matches. If the current buffer is in `dired-mode', grep
11124 will be used to search in all files.
11126 When AVOID-POS is given, ignore matches near that position.
11128 When optional argument STEALTH is non-nil, do not modify
11129 visibility around point, thus ignoring `org-show-context-detail'
11130 variable.
11132 Search is case-insensitive and ignores white spaces. Return type
11133 of matched result, which is either `dedicated' or `fuzzy'."
11134 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11135 (let* ((case-fold-search t)
11136 (origin (point))
11137 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11138 (words (org-split-string s "[ \t\n]+"))
11139 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11140 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11141 type)
11142 (cond
11143 ;; Check if there are any special search functions.
11144 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11145 ((eq (string-to-char s) ?#)
11146 ;; Look for a custom ID S if S starts with "#".
11147 (let* ((id (substring normalized 1))
11148 (match (org-find-property "CUSTOM_ID" id)))
11149 (if match (progn (goto-char match) (setf type 'dedicated))
11150 (error "No match for custom ID: %s" id))))
11151 ((string-match "\\`(\\(.*\\))\\'" normalized)
11152 ;; Look for coderef targets if S is enclosed within parenthesis.
11153 (let ((coderef (match-string-no-properties 1 normalized))
11154 (re (substring s-single-re 1 -1)))
11155 (goto-char (point-min))
11156 (catch :coderef-match
11157 (while (re-search-forward re nil t)
11158 (let ((element (org-element-at-point)))
11159 (when (and (memq (org-element-type element)
11160 '(example-block src-block))
11161 ;; Build proper regexp according to current
11162 ;; block's label format.
11163 (let ((label-fmt
11164 (regexp-quote
11165 (or (org-element-property :label-fmt element)
11166 org-coderef-label-format))))
11167 (save-excursion
11168 (beginning-of-line)
11169 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11170 (format label-fmt coderef))))))
11171 (setq type 'dedicated)
11172 (goto-char (match-beginning 1))
11173 (throw :coderef-match nil))))
11174 (goto-char origin)
11175 (error "No match for coderef: %s" coderef))))
11176 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11177 ;; Look for a regular expression.
11178 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11179 (match-string 1 s)))
11180 ;; Fuzzy links.
11182 (let ((starred (eq (string-to-char normalized) ?*)))
11183 (cond
11184 ;; Look for targets, only if not in a headline search.
11185 ((and (not starred)
11186 (let ((target (format "<<%s>>" s-multi-re)))
11187 (catch :target-match
11188 (goto-char (point-min))
11189 (while (re-search-forward target nil t)
11190 (backward-char)
11191 (let ((context (org-element-context)))
11192 (when (eq (org-element-type context) 'target)
11193 (setq type 'dedicated)
11194 (goto-char (org-element-property :begin context))
11195 (throw :target-match t))))
11196 nil))))
11197 ;; Look for elements named after S, only if not in a headline
11198 ;; search.
11199 ((and (not starred)
11200 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11201 (catch :name-match
11202 (goto-char (point-min))
11203 (while (re-search-forward name nil t)
11204 (let ((element (org-element-at-point)))
11205 (when (equal (org-split-string
11206 (org-element-property :name element)
11207 "[ \t]+")
11208 words)
11209 (setq type 'dedicated)
11210 (beginning-of-line)
11211 (throw :name-match t))))
11212 nil))))
11213 ;; Regular text search. Prefer headlines in Org mode
11214 ;; buffers.
11215 ((and (derived-mode-p 'org-mode)
11216 (let* ((wspace "[ \t]")
11217 (wspaceopt (concat wspace "*"))
11218 (cookie (concat "\\(?:"
11219 wspaceopt
11220 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11221 wspaceopt
11222 "\\)"))
11223 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11224 (re (concat
11225 org-outline-regexp-bol
11226 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11227 "\\(?:\\[#.\\][ \t]+\\)?"
11228 "\\(?:" org-comment-string "[ \t]+\\)?"
11229 sep "?"
11230 (let ((title (mapconcat #'regexp-quote
11231 words
11232 sep)))
11233 (if starred (substring title 1) title))
11234 sep "?"
11235 "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
11236 "[ \t]*$")))
11237 (goto-char (point-min))
11238 (re-search-forward re nil t)))
11239 (goto-char (match-beginning 0))
11240 (setq type 'dedicated))
11241 ;; Offer to create non-existent headline depending on
11242 ;; `org-link-search-must-match-exact-headline'.
11243 ((and (derived-mode-p 'org-mode)
11244 (not org-link-search-inhibit-query)
11245 (eq org-link-search-must-match-exact-headline 'query-to-create)
11246 (yes-or-no-p "No match - create this as a new heading? "))
11247 (goto-char (point-max))
11248 (unless (bolp) (newline))
11249 (org-insert-heading nil t t)
11250 (insert s "\n")
11251 (beginning-of-line 0))
11252 ;; Only headlines are looked after. No need to process
11253 ;; further: throw an error.
11254 ((and (derived-mode-p 'org-mode)
11255 (or starred org-link-search-must-match-exact-headline))
11256 (goto-char origin)
11257 (error "No match for fuzzy expression: %s" normalized))
11258 ;; Regular text search.
11259 ((catch :fuzzy-match
11260 (goto-char (point-min))
11261 (while (re-search-forward s-multi-re nil t)
11262 ;; Skip match if it contains AVOID-POS or it is included
11263 ;; in a link with a description but outside the
11264 ;; description.
11265 (unless (or (and avoid-pos
11266 (<= (match-beginning 0) avoid-pos)
11267 (> (match-end 0) avoid-pos))
11268 (and (save-match-data
11269 (org-in-regexp org-bracket-link-regexp))
11270 (match-beginning 3)
11271 (or (> (match-beginning 3) (point))
11272 (<= (match-end 3) (point)))
11273 (org-element-lineage
11274 (save-match-data (org-element-context))
11275 '(link) t)))
11276 (goto-char (match-beginning 0))
11277 (setq type 'fuzzy)
11278 (throw :fuzzy-match t)))
11279 nil))
11280 ;; All failed. Throw an error.
11281 (t (goto-char origin)
11282 (error "No match for fuzzy expression: %s" normalized))))))
11283 ;; Disclose surroundings of match, if appropriate.
11284 (when (and (derived-mode-p 'org-mode) (not stealth))
11285 (org-show-context 'link-search))
11286 type))
11288 (defun org-get-buffer-for-internal-link (buffer)
11289 "Return a buffer to be used for displaying the link target of internal links."
11290 (cond
11291 ((not org-display-internal-link-with-indirect-buffer)
11292 buffer)
11293 ((string-suffix-p "(Clone)" (buffer-name buffer))
11294 (message "Buffer is already a clone, not making another one")
11295 ;; we also do not modify visibility in this case
11296 buffer)
11297 (t ; make a new indirect buffer for displaying the link
11298 (let* ((bn (buffer-name buffer))
11299 (ibn (concat bn "(Clone)"))
11300 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11301 (with-current-buffer ib (org-overview))
11302 ib))))
11304 (defun org-do-occur (regexp &optional cleanup)
11305 "Call the Emacs command `occur'.
11306 If CLEANUP is non-nil, remove the printout of the regular expression
11307 in the *Occur* buffer. This is useful if the regex is long and not useful
11308 to read."
11309 (occur regexp)
11310 (when cleanup
11311 (let ((cwin (selected-window)) win beg end)
11312 (when (setq win (get-buffer-window "*Occur*"))
11313 (select-window win))
11314 (goto-char (point-min))
11315 (when (re-search-forward "match[a-z]+" nil t)
11316 (setq beg (match-end 0))
11317 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11318 (setq end (1- (match-beginning 0)))))
11319 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11320 (goto-char (point-min))
11321 (select-window cwin))))
11323 ;;; The mark ring for links jumps
11325 (defvar org-mark-ring nil
11326 "Mark ring for positions before jumps in Org mode.")
11327 (defvar org-mark-ring-last-goto nil
11328 "Last position in the mark ring used to go back.")
11329 ;; Fill and close the ring
11330 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11331 (dotimes (_ org-mark-ring-length)
11332 (push (make-marker) org-mark-ring))
11333 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11334 org-mark-ring)
11336 (defun org-mark-ring-push (&optional pos buffer)
11337 "Put the current position or POS into the mark ring and rotate it."
11338 (interactive)
11339 (setq pos (or pos (point)))
11340 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11341 (move-marker (car org-mark-ring)
11342 (or pos (point))
11343 (or buffer (current-buffer)))
11344 (message "%s"
11345 (substitute-command-keys
11346 "Position saved to mark ring, go back with \
11347 `\\[org-mark-ring-goto]'.")))
11349 (defun org-mark-ring-goto (&optional n)
11350 "Jump to the previous position in the mark ring.
11351 With prefix arg N, jump back that many stored positions. When
11352 called several times in succession, walk through the entire ring.
11353 Org mode commands jumping to a different position in the current file,
11354 or to another Org file, automatically push the old position onto the ring."
11355 (interactive "p")
11356 (let (p m)
11357 (if (eq last-command this-command)
11358 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11359 (setq p org-mark-ring))
11360 (setq org-mark-ring-last-goto p)
11361 (setq m (car p))
11362 (pop-to-buffer-same-window (marker-buffer m))
11363 (goto-char m)
11364 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11366 (defun org-add-angle-brackets (s)
11367 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11368 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11371 ;;; Following specific links
11373 (defvar org-agenda-buffer-tmp-name)
11374 (defvar org-agenda-start-on-weekday)
11375 (defun org-follow-timestamp-link ()
11376 "Open an agenda view for the time-stamp date/range at point."
11377 (cond
11378 ((org-at-date-range-p t)
11379 (let ((org-agenda-start-on-weekday)
11380 (t1 (match-string 1))
11381 (t2 (match-string 2)) tt1 tt2)
11382 (setq tt1 (time-to-days (org-time-string-to-time t1))
11383 tt2 (time-to-days (org-time-string-to-time t2)))
11384 (let ((org-agenda-buffer-tmp-name
11385 (format "*Org Agenda(a:%s)"
11386 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11387 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11388 ((org-at-timestamp-p t)
11389 (let ((org-agenda-buffer-tmp-name
11390 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11391 (org-agenda-list nil (time-to-days (org-time-string-to-time
11392 (substring (match-string 1) 0 10)))
11393 1)))
11394 (t (error "This should not happen"))))
11397 ;;; Following file links
11398 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11399 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11400 (declare-function mailcap-mime-info
11401 "mailcap" (string &optional request no-decode))
11402 (defvar org-wait nil)
11403 (defun org-open-file (path &optional in-emacs line search)
11404 "Open the file at PATH.
11405 First, this expands any special file name abbreviations. Then the
11406 configuration variable `org-file-apps' is checked if it contains an
11407 entry for this file type, and if yes, the corresponding command is launched.
11409 If no application is found, Emacs simply visits the file.
11411 With optional prefix argument IN-EMACS, Emacs will visit the file.
11412 With a double \\[universal-argument] \\[universal-argument] \
11413 prefix arg, Org tries to avoid opening in Emacs
11414 and to use an external application to visit the file.
11416 Optional LINE specifies a line to go to, optional SEARCH a string
11417 to search for. If LINE or SEARCH is given, the file will be
11418 opened in Emacs, unless an entry from org-file-apps that makes
11419 use of groups in a regexp matches.
11421 If you want to change the way frames are used when following a
11422 link, please customize `org-link-frame-setup'.
11424 If the file does not exist, an error is thrown."
11425 (let* ((file (if (equal path "")
11426 buffer-file-name
11427 (substitute-in-file-name (expand-file-name path))))
11428 (file-apps (append org-file-apps (org-default-apps)))
11429 (apps (cl-remove-if
11430 'org-file-apps-entry-match-against-dlink-p file-apps))
11431 (apps-dlink (cl-remove-if-not
11432 'org-file-apps-entry-match-against-dlink-p file-apps))
11433 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11434 (dirp (unless remp (file-directory-p file)))
11435 (file (if (and dirp org-open-directory-means-index-dot-org)
11436 (concat (file-name-as-directory file) "index.org")
11437 file))
11438 (a-m-a-p (assq 'auto-mode apps))
11439 (dfile (downcase file))
11440 ;; Reconstruct the original link from the PATH, LINE and
11441 ;; SEARCH args.
11442 (link (cond (line (concat file "::" (number-to-string line)))
11443 (search (concat file "::" search))
11444 (t file)))
11445 (dlink (downcase link))
11446 (old-buffer (current-buffer))
11447 (old-pos (point))
11448 (old-mode major-mode)
11449 (ext
11450 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11451 (match-string 1 dfile)))
11452 cmd link-match-data)
11453 (cond
11454 ((member in-emacs '((16) system))
11455 (setq cmd (cdr (assq 'system apps))))
11456 (in-emacs (setq cmd 'emacs))
11458 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11459 (and dirp (cdr (assq 'directory apps)))
11460 ;; First, try matching against apps-dlink if we
11461 ;; get a match here, store the match data for
11462 ;; later.
11463 (let ((match (assoc-default dlink apps-dlink
11464 'string-match)))
11465 (if match
11466 (progn (setq link-match-data (match-data))
11467 match)
11468 (progn (setq in-emacs (or in-emacs line search))
11469 nil))) ; if we have no match in apps-dlink,
11470 ; always open the file in emacs if line or search
11471 ; is given (for backwards compatibility)
11472 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11473 'string-match)
11474 (cdr (assoc ext apps))
11475 (cdr (assq t apps))))))
11476 (when (eq cmd 'system)
11477 (setq cmd (cdr (assq 'system apps))))
11478 (when (eq cmd 'default)
11479 (setq cmd (cdr (assoc t apps))))
11480 (when (eq cmd 'mailcap)
11481 (require 'mailcap)
11482 (mailcap-parse-mailcaps)
11483 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11484 (command (mailcap-mime-info mime-type)))
11485 (if (stringp command)
11486 (setq cmd command)
11487 (setq cmd 'emacs))))
11488 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11489 (not (file-exists-p file))
11490 (not org-open-non-existing-files))
11491 (user-error "No such file: %s" file))
11492 (cond
11493 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11494 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11495 (while (string-match "['\"]%s['\"]" cmd)
11496 (setq cmd (replace-match "%s" t t cmd)))
11497 (setq cmd (replace-regexp-in-string
11498 "%s"
11499 (shell-quote-argument (convert-standard-filename file))
11501 nil t))
11503 ;; Replace "%1", "%2" etc. in command with group matches from regex
11504 (save-match-data
11505 (let ((match-index 1)
11506 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11507 (set-match-data link-match-data)
11508 (while (<= match-index number-of-groups)
11509 (let ((regex (concat "%" (number-to-string match-index)))
11510 (replace-with (match-string match-index dlink)))
11511 (while (string-match regex cmd)
11512 (setq cmd (replace-match replace-with t t cmd))))
11513 (setq match-index (+ match-index 1)))))
11515 (save-window-excursion
11516 (message "Running %s...done" cmd)
11517 (start-process-shell-command cmd nil cmd)
11518 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11519 ((or (stringp cmd)
11520 (eq cmd 'emacs))
11521 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11522 (widen)
11523 (cond (line (org-goto-line line)
11524 (when (derived-mode-p 'org-mode) (org-reveal)))
11525 (search (org-link-search search))))
11526 ((functionp cmd)
11527 (save-match-data
11528 (set-match-data link-match-data)
11529 (condition-case nil
11530 (funcall cmd file link)
11531 ;; FIXME: Remove this check when most default installations
11532 ;; of Emacs have at least Org 9.0.
11533 ((debug wrong-number-of-arguments wrong-type-argument
11534 invalid-function)
11535 (user-error "Please see Org News for version 9.0 about \
11536 `org-file-apps'--Lisp error: %S" cmd)))))
11537 ((consp cmd)
11538 ;; FIXME: Remove this check when most default installations of
11539 ;; Emacs have at least Org 9.0.
11540 ;; Heads-up instead of silently fall back to
11541 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11542 ;; with sexp instead of a function for `cmd'.
11543 (user-error "Please see Org News for version 9.0 about \
11544 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11545 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11546 (and (derived-mode-p 'org-mode)
11547 (eq old-mode 'org-mode)
11548 (or (not (eq old-buffer (current-buffer)))
11549 (not (eq old-pos (point))))
11550 (org-mark-ring-push old-pos old-buffer))))
11552 (defun org-file-apps-entry-match-against-dlink-p (entry)
11553 "This function returns non-nil if `entry' uses a regular
11554 expression which should be matched against the whole link by
11555 org-open-file.
11557 It assumes that is the case when the entry uses a regular
11558 expression which has at least one grouping construct and the
11559 action is either a lisp form or a command string containing
11560 `%1', i.e. using at least one subexpression match as a
11561 parameter."
11562 (let ((selector (car entry))
11563 (action (cdr entry)))
11564 (if (stringp selector)
11565 (and (> (regexp-opt-depth selector) 0)
11566 (or (and (stringp action)
11567 (string-match "%[0-9]" action))
11568 (consp action)))
11569 nil)))
11571 (defun org-default-apps ()
11572 "Return the default applications for this operating system."
11573 (cond
11574 ((eq system-type 'darwin)
11575 org-file-apps-defaults-macosx)
11576 ((eq system-type 'windows-nt)
11577 org-file-apps-defaults-windowsnt)
11578 (t org-file-apps-defaults-gnu)))
11580 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11581 "Convert extensions to regular expressions in the cars of LIST.
11582 Also, weed out any non-string entries, because the return value is used
11583 only for regexp matching.
11584 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11585 point to the symbol `emacs', indicating that the file should
11586 be opened in Emacs."
11587 (append
11588 (delq nil
11589 (mapcar (lambda (x)
11590 (unless (not (stringp (car x)))
11591 (if (string-match "\\W" (car x))
11593 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11594 list))
11595 (when add-auto-mode
11596 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11598 (defvar ange-ftp-name-format)
11599 (defun org-file-remote-p (file)
11600 "Test whether FILE specifies a location on a remote system.
11601 Return non-nil if the location is indeed remote.
11603 For example, the filename \"/user@host:/foo\" specifies a location
11604 on the system \"/user@host:\"."
11605 (cond ((fboundp 'file-remote-p)
11606 (file-remote-p file))
11607 ((fboundp 'tramp-handle-file-remote-p)
11608 (tramp-handle-file-remote-p file))
11609 ((and (boundp 'ange-ftp-name-format)
11610 (string-match (car ange-ftp-name-format) file))
11611 t)))
11614 ;;;; Refiling
11616 (defun org-get-org-file ()
11617 "Read a filename, with default directory `org-directory'."
11618 (let ((default (or org-default-notes-file remember-data-file)))
11619 (read-file-name (format "File name [%s]: " default)
11620 (file-name-as-directory org-directory)
11621 default)))
11623 (defun org-notes-order-reversed-p ()
11624 "Check if the current file should receive notes in reversed order."
11625 (cond
11626 ((not org-reverse-note-order) nil)
11627 ((eq t org-reverse-note-order) t)
11628 ((not (listp org-reverse-note-order)) nil)
11629 (t (catch 'exit
11630 (dolist (entry org-reverse-note-order)
11631 (when (string-match (car entry) buffer-file-name)
11632 (throw 'exit (cdr entry))))))))
11634 (defvar org-refile-target-table nil
11635 "The list of refile targets, created by `org-refile'.")
11637 (defvar org-agenda-new-buffers nil
11638 "Buffers created to visit agenda files.")
11640 (defvar org-refile-cache nil
11641 "Cache for refile targets.")
11643 (defvar org-refile-markers nil
11644 "All the markers used for caching refile locations.")
11646 (defun org-refile-marker (pos)
11647 "Get a new refile marker, but only if caching is in use."
11648 (if (not org-refile-use-cache)
11650 (let ((m (make-marker)))
11651 (move-marker m pos)
11652 (push m org-refile-markers)
11653 m)))
11655 (defun org-refile-cache-clear ()
11656 "Clear the refile cache and disable all the markers."
11657 (dolist (m org-refile-markers) (move-marker m nil))
11658 (setq org-refile-markers nil)
11659 (setq org-refile-cache nil)
11660 (message "Refile cache has been cleared"))
11662 (defun org-refile-cache-check-set (set)
11663 "Check if all the markers in the cache still have live buffers."
11664 (let (marker)
11665 (catch 'exit
11666 (while (and set (setq marker (nth 3 (pop set))))
11667 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11668 (when (and marker (null (marker-buffer marker)))
11669 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11670 (sit-for 3)
11671 (throw 'exit nil)))
11672 t)))
11674 (defun org-refile-cache-put (set &rest identifiers)
11675 "Push the refile targets SET into the cache, under IDENTIFIERS."
11676 (let* ((key (sha1 (prin1-to-string identifiers)))
11677 (entry (assoc key org-refile-cache)))
11678 (if entry
11679 (setcdr entry set)
11680 (push (cons key set) org-refile-cache))))
11682 (defun org-refile-cache-get (&rest identifiers)
11683 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11684 (cond
11685 ((not org-refile-cache) nil)
11686 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11688 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11689 org-refile-cache))))
11690 (and set (org-refile-cache-check-set set) set)))))
11692 (defvar org-outline-path-cache nil
11693 "Alist between buffer positions and outline paths.
11694 It value is an alist (POSITION . PATH) where POSITION is the
11695 buffer position at the beginning of an entry and PATH is a list
11696 of strings describing the outline path for that entry, in reverse
11697 order.")
11699 (defun org-refile-get-targets (&optional default-buffer)
11700 "Produce a table with refile targets."
11701 (let ((case-fold-search nil)
11702 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11703 (entries (or org-refile-targets '((nil . (:level . 1)))))
11704 targets tgs files desc descre)
11705 (message "Getting targets...")
11706 (with-current-buffer (or default-buffer (current-buffer))
11707 (dolist (entry entries)
11708 (setq files (car entry) desc (cdr entry))
11709 (cond
11710 ((null files) (setq files (list (current-buffer))))
11711 ((eq files 'org-agenda-files)
11712 (setq files (org-agenda-files 'unrestricted)))
11713 ((and (symbolp files) (fboundp files))
11714 (setq files (funcall files)))
11715 ((and (symbolp files) (boundp files))
11716 (setq files (symbol-value files))))
11717 (when (stringp files) (setq files (list files)))
11718 (cond
11719 ((eq (car desc) :tag)
11720 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11721 ((eq (car desc) :todo)
11722 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11723 ((eq (car desc) :regexp)
11724 (setq descre (cdr desc)))
11725 ((eq (car desc) :level)
11726 (setq descre (concat "^\\*\\{" (number-to-string
11727 (if org-odd-levels-only
11728 (1- (* 2 (cdr desc)))
11729 (cdr desc)))
11730 "\\}[ \t]")))
11731 ((eq (car desc) :maxlevel)
11732 (setq descre (concat "^\\*\\{1," (number-to-string
11733 (if org-odd-levels-only
11734 (1- (* 2 (cdr desc)))
11735 (cdr desc)))
11736 "\\}[ \t]")))
11737 (t (error "Bad refiling target description %s" desc)))
11738 (dolist (f files)
11739 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11741 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11742 (progn
11743 (when (bufferp f)
11744 (setq f (buffer-file-name (buffer-base-buffer f))))
11745 (setq f (and f (expand-file-name f)))
11746 (when (eq org-refile-use-outline-path 'file)
11747 (push (list (file-name-nondirectory f) f nil nil) tgs))
11748 (org-with-wide-buffer
11749 (goto-char (point-min))
11750 (setq org-outline-path-cache nil)
11751 (while (re-search-forward descre nil t)
11752 (beginning-of-line)
11753 (let ((case-fold-search nil))
11754 (looking-at org-complex-heading-regexp))
11755 (let ((begin (point))
11756 (heading (match-string-no-properties 4)))
11757 (unless (or (and
11758 org-refile-target-verify-function
11759 (not
11760 (funcall org-refile-target-verify-function)))
11761 (not heading))
11762 (let ((re (format org-complex-heading-regexp-format
11763 (regexp-quote heading)))
11764 (target
11765 (if (not org-refile-use-outline-path) heading
11766 (mapconcat
11767 #'org-protect-slash
11768 (append
11769 (pcase org-refile-use-outline-path
11770 (`file (list (file-name-nondirectory
11771 (buffer-file-name
11772 (buffer-base-buffer)))))
11773 (`full-file-path
11774 (list (buffer-file-name
11775 (buffer-base-buffer))))
11776 (_ nil))
11777 (org-get-outline-path t t))
11778 "/"))))
11779 (push (list target f re (org-refile-marker (point)))
11780 tgs)))
11781 (when (= (point) begin)
11782 ;; Verification function has not moved point.
11783 (end-of-line)))))))
11784 (when org-refile-use-cache
11785 (org-refile-cache-put tgs (buffer-file-name) descre))
11786 (setq targets (append tgs targets))))))
11787 (message "Getting targets...done")
11788 (nreverse targets)))
11790 (defun org-protect-slash (s)
11791 (replace-regexp-in-string "/" "\\/" s nil t))
11793 (defun org--get-outline-path-1 (&optional use-cache)
11794 "Return outline path to current headline.
11796 Outline path is a list of strings, in reverse order. When
11797 optional argument USE-CACHE is non-nil, make use of a cache. See
11798 `org-get-outline-path' for details.
11800 Assume buffer is widened and point is on a headline."
11801 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11802 (let ((p (point))
11803 (heading (let ((case-fold-search nil))
11804 (looking-at org-complex-heading-regexp)
11805 (if (not (match-end 4)) ""
11806 ;; Remove statistics cookies.
11807 (org-trim
11808 (org-link-display-format
11809 (replace-regexp-in-string
11810 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11811 (match-string-no-properties 4))))))))
11812 (if (org-up-heading-safe)
11813 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11814 (when use-cache
11815 (push (cons p path) org-outline-path-cache))
11816 path)
11817 ;; This is a new root node. Since we assume we are moving
11818 ;; forward, we can drop previous cache so as to limit number
11819 ;; of associations there.
11820 (let ((path (list heading)))
11821 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11822 path)))))
11824 (defun org-get-outline-path (&optional with-self use-cache)
11825 "Return the outline path to the current entry.
11827 An outline path is a list of ancestors for current headline, as
11828 a list of strings. Statistics cookies are removed and links are
11829 replaced with their description, if any, or their path otherwise.
11831 When optional argument WITH-SELF is non-nil, the path also
11832 includes the current headline.
11834 When optional argument USE-CACHE is non-nil, cache outline paths
11835 between calls to this function so as to avoid backtracking. This
11836 argument is useful when planning to find more than one outline
11837 path in the same document. In that case, there are two
11838 conditions to satisfy:
11839 - `org-outline-path-cache' is set to nil before starting the
11840 process;
11841 - outline paths are computed by increasing buffer positions."
11842 (org-with-wide-buffer
11843 (and (or (and with-self (org-back-to-heading t))
11844 (org-up-heading-safe))
11845 (reverse (org--get-outline-path-1 use-cache)))))
11847 (defun org-format-outline-path (path &optional width prefix separator)
11848 "Format the outline path PATH for display.
11849 WIDTH is the maximum number of characters that is available.
11850 PREFIX is a prefix to be included in the returned string,
11851 such as the file name.
11852 SEPARATOR is inserted between the different parts of the path,
11853 the default is \"/\"."
11854 (setq width (or width 79))
11855 (setq path (delq nil path))
11856 (unless (> width 0)
11857 (user-error "Argument `width' must be positive"))
11858 (setq separator (or separator "/"))
11859 (let* ((org-odd-levels-only nil)
11860 (fpath (concat
11861 prefix (and prefix path separator)
11862 (mapconcat
11863 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11864 (cl-loop for head in path
11865 for n from 0
11866 collect (org-add-props
11867 head nil 'face
11868 (nth (% n org-n-level-faces) org-level-faces)))
11869 separator))))
11870 (when (> (length fpath) width)
11871 (if (< width 7)
11872 ;; It's unlikely that `width' will be this small, but don't
11873 ;; waste characters by adding ".." if it is.
11874 (setq fpath (substring fpath 0 width))
11875 (setf (substring fpath (- width 2)) "..")))
11876 fpath))
11878 (defun org-display-outline-path (&optional file current separator just-return-string)
11879 "Display the current outline path in the echo area.
11881 If FILE is non-nil, prepend the output with the file name.
11882 If CURRENT is non-nil, append the current heading to the output.
11883 SEPARATOR is passed through to `org-format-outline-path'. It separates
11884 the different parts of the path and defaults to \"/\".
11885 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11886 (interactive "P")
11887 (let* (case-fold-search
11888 (bfn (buffer-file-name (buffer-base-buffer)))
11889 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11890 res)
11891 (when current (setq path (append path
11892 (save-excursion
11893 (org-back-to-heading t)
11894 (when (looking-at org-complex-heading-regexp)
11895 (list (match-string 4)))))))
11896 (setq res
11897 (org-format-outline-path
11898 path
11899 (1- (frame-width))
11900 (and file bfn (concat (file-name-nondirectory bfn) separator))
11901 separator))
11902 (if just-return-string
11903 (org-no-properties res)
11904 (org-unlogged-message "%s" res))))
11906 (defvar org-refile-history nil
11907 "History for refiling operations.")
11909 (defvar org-after-refile-insert-hook nil
11910 "Hook run after `org-refile' has inserted its stuff at the new location.
11911 Note that this is still *before* the stuff will be removed from
11912 the *old* location.")
11914 (defvar org-capture-last-stored-marker)
11915 (defvar org-refile-keep nil
11916 "Non-nil means `org-refile' will copy instead of refile.")
11918 (defun org-copy ()
11919 "Like `org-refile', but copy."
11920 (interactive)
11921 (let ((org-refile-keep t))
11922 (funcall 'org-refile nil nil nil "Copy")))
11924 (defun org-refile (&optional arg default-buffer rfloc msg)
11925 "Move the entry or entries at point to another heading.
11927 The list of target headings is compiled using the information in
11928 `org-refile-targets', which see.
11930 At the target location, the entry is filed as a subitem of the
11931 target heading. Depending on `org-reverse-note-order', the new
11932 subitem will either be the first or the last subitem.
11934 If there is an active region, all entries in that region will be
11935 refiled. However, the region must fulfill the requirement that
11936 the first heading sets the top-level of the moved text.
11938 With a `\\[universal-argument]' ARG, the command will only visit the target \
11939 location
11940 and not actually move anything.
11942 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11943 location where the last
11944 refiling operation has put the subtree.
11946 With a numeric prefix argument of `2', refile to the running clock.
11948 With a numeric prefix argument of `3', emulate `org-refile-keep'
11949 being set to t and copy to the target location, don't move it.
11950 Beware that keeping refiled entries may result in duplicated ID
11951 properties.
11953 RFLOC can be a refile location obtained in a different way.
11955 MSG is a string to replace \"Refile\" in the default prompt with
11956 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11958 See also `org-refile-use-outline-path'.
11960 If you are using target caching (see `org-refile-use-cache'), you
11961 have to clear the target cache in order to find new targets.
11962 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11963 prefix argument (`C-u C-u C-u C-c C-w')."
11964 (interactive "P")
11965 (if (member arg '(0 (64)))
11966 (org-refile-cache-clear)
11967 (let* ((actionmsg (cond (msg msg)
11968 ((equal arg 3) "Refile (and keep)")
11969 (t "Refile")))
11970 (regionp (org-region-active-p))
11971 (region-start (and regionp (region-beginning)))
11972 (region-end (and regionp (region-end)))
11973 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11974 pos it nbuf file level reversed)
11975 (setq last-command nil)
11976 (when regionp
11977 (goto-char region-start)
11978 (or (bolp) (goto-char (point-at-bol)))
11979 (setq region-start (point))
11980 (unless (or (org-kill-is-subtree-p
11981 (buffer-substring region-start region-end))
11982 (prog1 org-refile-active-region-within-subtree
11983 (let ((s (point-at-eol)))
11984 (org-toggle-heading)
11985 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11986 (user-error "The region is not a (sequence of) subtree(s)")))
11987 (if (equal arg '(16))
11988 (org-refile-goto-last-stored)
11989 (when (or
11990 (and (equal arg 2)
11991 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11992 (prog1
11993 (setq it (list (or org-clock-heading "running clock")
11994 (buffer-file-name
11995 (marker-buffer org-clock-hd-marker))
11997 (marker-position org-clock-hd-marker)))
11998 (setq arg nil)))
11999 (setq it
12000 (or rfloc
12001 (let (heading-text)
12002 (save-excursion
12003 (unless (and arg (listp arg))
12004 (org-back-to-heading t)
12005 (setq heading-text
12006 (replace-regexp-in-string
12007 org-bracket-link-regexp
12008 "\\3"
12009 (or (nth 4 (org-heading-components))
12010 ""))))
12011 (org-refile-get-location
12012 (cond ((and arg (listp arg)) "Goto")
12013 (regionp (concat actionmsg " region to"))
12014 (t (concat actionmsg " subtree \""
12015 heading-text "\" to")))
12016 default-buffer
12017 (and (not (equal '(4) arg))
12018 org-refile-allow-creating-parent-nodes)))))))
12019 (setq file (nth 1 it)
12020 pos (nth 3 it))
12021 (when (and (not arg)
12023 (equal (buffer-file-name) file)
12024 (if regionp
12025 (and (>= pos region-start)
12026 (<= pos region-end))
12027 (and (>= pos (point))
12028 (< pos (save-excursion
12029 (org-end-of-subtree t t))))))
12030 (error "Cannot refile to position inside the tree or region"))
12031 (setq nbuf (or (find-buffer-visiting file)
12032 (find-file-noselect file)))
12033 (if (and arg (not (equal arg 3)))
12034 (progn
12035 (pop-to-buffer-same-window nbuf)
12036 (goto-char pos)
12037 (org-show-context 'org-goto))
12038 (if regionp
12039 (progn
12040 (org-kill-new (buffer-substring region-start region-end))
12041 (org-save-markers-in-region region-start region-end))
12042 (org-copy-subtree 1 nil t))
12043 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
12044 (find-file-noselect file)))
12045 (setq reversed (org-notes-order-reversed-p))
12046 (org-with-wide-buffer
12047 (if pos
12048 (progn
12049 (goto-char pos)
12050 (looking-at org-outline-regexp)
12051 (setq level (org-get-valid-level (funcall outline-level) 1))
12052 (goto-char
12053 (if reversed
12054 (or (outline-next-heading) (point-max))
12055 (or (save-excursion (org-get-next-sibling))
12056 (org-end-of-subtree t t)
12057 (point-max)))))
12058 (setq level 1)
12059 (if (not reversed)
12060 (goto-char (point-max))
12061 (goto-char (point-min))
12062 (or (outline-next-heading) (goto-char (point-max)))))
12063 (unless (bolp) (newline))
12064 (org-paste-subtree level nil nil t)
12065 (when org-log-refile
12066 (org-add-log-setup 'refile nil nil org-log-refile)
12067 (unless (eq org-log-refile 'note)
12068 (save-excursion (org-add-log-note))))
12069 (and org-auto-align-tags
12070 (let ((org-loop-over-headlines-in-active-region nil))
12071 (org-set-tags nil t)))
12072 (let ((bookmark-name (plist-get org-bookmark-names-plist
12073 :last-refile)))
12074 (when bookmark-name
12075 (with-demoted-errors
12076 (bookmark-set bookmark-name))))
12077 ;; If we are refiling for capture, make sure that the
12078 ;; last-capture pointers point here
12079 (when (bound-and-true-p org-capture-is-refiling)
12080 (let ((bookmark-name (plist-get org-bookmark-names-plist
12081 :last-capture-marker)))
12082 (when bookmark-name
12083 (with-demoted-errors
12084 (bookmark-set bookmark-name))))
12085 (move-marker org-capture-last-stored-marker (point)))
12086 (when (fboundp 'deactivate-mark) (deactivate-mark))
12087 (run-hooks 'org-after-refile-insert-hook)))
12088 (unless org-refile-keep
12089 (if regionp
12090 (delete-region (point) (+ (point) (- region-end region-start)))
12091 (delete-region
12092 (and (org-back-to-heading t) (point))
12093 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12094 (when (featurep 'org-inlinetask)
12095 (org-inlinetask-remove-END-maybe))
12096 (setq org-markers-to-move nil)
12097 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12099 (defun org-refile-goto-last-stored ()
12100 "Go to the location where the last refile was stored."
12101 (interactive)
12102 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12103 (message "This is the location of the last refile"))
12105 (defun org-refile--get-location (refloc tbl)
12106 "When user refile to REFLOC, find the associated target in TBL.
12107 Also check `org-refile-target-table'."
12108 (car (delq
12110 (mapcar
12111 (lambda (r) (or (assoc r tbl)
12112 (assoc r org-refile-target-table)))
12113 (list (replace-regexp-in-string "/$" "" refloc)
12114 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12116 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12117 "Prompt the user for a refile location, using PROMPT.
12118 PROMPT should not be suffixed with a colon and a space, because
12119 this function appends the default value from
12120 `org-refile-history' automatically, if that is not empty."
12121 (let ((org-refile-targets org-refile-targets)
12122 (org-refile-use-outline-path org-refile-use-outline-path))
12123 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12124 (unless org-refile-target-table
12125 (user-error "No refile targets"))
12126 (let* ((cbuf (current-buffer))
12127 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12128 (cfunc (if (and org-refile-use-outline-path
12129 org-outline-path-complete-in-steps)
12130 #'org-olpath-completing-read
12131 #'completing-read))
12132 (extra (if org-refile-use-outline-path "/" ""))
12133 (cbnex (concat (buffer-name) extra))
12134 (filename (and cfn (expand-file-name cfn)))
12135 (tbl (mapcar
12136 (lambda (x)
12137 (if (and (not (member org-refile-use-outline-path
12138 '(file full-file-path)))
12139 (not (equal filename (nth 1 x))))
12140 (cons (concat (car x) extra " ("
12141 (file-name-nondirectory (nth 1 x)) ")")
12142 (cdr x))
12143 (cons (concat (car x) extra) (cdr x))))
12144 org-refile-target-table))
12145 (completion-ignore-case t)
12146 cdef
12147 (prompt (concat prompt
12148 (or (and (car org-refile-history)
12149 (concat " (default " (car org-refile-history) ")"))
12150 (and (assoc cbnex tbl) (setq cdef cbnex)
12151 (concat " (default " cbnex ")"))) ": "))
12152 pa answ parent-target child parent old-hist)
12153 (setq old-hist org-refile-history)
12154 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12155 nil 'org-refile-history (or cdef (car org-refile-history))))
12156 (if (setq pa (org-refile--get-location answ tbl))
12157 (progn
12158 (org-refile-check-position pa)
12159 (when (or (not org-refile-history)
12160 (not (eq old-hist org-refile-history))
12161 (not (equal (car pa) (car org-refile-history))))
12162 (setq org-refile-history
12163 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12164 org-refile-history
12165 (cdr org-refile-history))))
12166 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12167 (pop org-refile-history)))
12169 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12170 (progn
12171 (setq parent (match-string 1 answ)
12172 child (match-string 2 answ))
12173 (setq parent-target (org-refile--get-location parent tbl))
12174 (when (and parent-target
12175 (or (eq new-nodes t)
12176 (and (eq new-nodes 'confirm)
12177 (y-or-n-p (format "Create new node \"%s\"? "
12178 child)))))
12179 (org-refile-new-child parent-target child)))
12180 (user-error "Invalid target location")))))
12182 (declare-function org-string-nw-p "org-macs" (s))
12183 (defun org-refile-check-position (refile-pointer)
12184 "Check if the refile pointer matches the headline to which it points."
12185 (let* ((file (nth 1 refile-pointer))
12186 (re (nth 2 refile-pointer))
12187 (pos (nth 3 refile-pointer))
12188 buffer)
12189 (if (and (not (markerp pos)) (not file))
12190 (user-error "Please indicate a target file in the refile path")
12191 (when (org-string-nw-p re)
12192 (setq buffer (if (markerp pos)
12193 (marker-buffer pos)
12194 (or (find-buffer-visiting file)
12195 (find-file-noselect file))))
12196 (with-current-buffer buffer
12197 (org-with-wide-buffer
12198 (goto-char pos)
12199 (beginning-of-line 1)
12200 (unless (looking-at-p re)
12201 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12203 (defun org-refile-new-child (parent-target child)
12204 "Use refile target PARENT-TARGET to add new CHILD below it."
12205 (unless parent-target
12206 (error "Cannot find parent for new node"))
12207 (let ((file (nth 1 parent-target))
12208 (pos (nth 3 parent-target))
12209 level)
12210 (with-current-buffer (or (find-buffer-visiting file)
12211 (find-file-noselect file))
12212 (org-with-wide-buffer
12213 (if pos
12214 (goto-char pos)
12215 (goto-char (point-max))
12216 (unless (bolp) (newline)))
12217 (when (looking-at org-outline-regexp)
12218 (setq level (funcall outline-level))
12219 (org-end-of-subtree t t))
12220 (org-back-over-empty-lines)
12221 (insert "\n" (make-string
12222 (if pos (org-get-valid-level level 1) 1) ?*)
12223 " " child "\n")
12224 (beginning-of-line 0)
12225 (list (concat (car parent-target) "/" child) file "" (point))))))
12227 (defun org-olpath-completing-read (prompt collection &rest args)
12228 "Read an outline path like a file name."
12229 (let ((thetable collection))
12230 (apply #'completing-read
12231 prompt
12232 (lambda (string predicate &optional flag)
12233 (cond
12234 ((eq flag nil) (try-completion string thetable))
12235 ((eq flag t)
12236 (let ((l (length string)))
12237 (mapcar (lambda (x)
12238 (let ((r (substring x l))
12239 (f (if (string-match " ([^)]*)$" x)
12240 (match-string 0 x)
12241 "")))
12242 (if (string-match "/" r)
12243 (concat string (substring r 0 (match-end 0)) f)
12244 x)))
12245 (all-completions string thetable predicate))))
12246 ;; Exact match?
12247 ((eq flag 'lambda) (assoc string thetable))))
12248 args)))
12250 ;;;; Dynamic blocks
12252 (defun org-find-dblock (name)
12253 "Find the first dynamic block with name NAME in the buffer.
12254 If not found, stay at current position and return nil."
12255 (let ((case-fold-search t) pos)
12256 (save-excursion
12257 (goto-char (point-min))
12258 (setq pos (and (re-search-forward
12259 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12260 (match-beginning 0))))
12261 (when pos (goto-char pos))
12262 pos))
12264 (defun org-create-dblock (plist)
12265 "Create a dynamic block section, with parameters taken from PLIST.
12266 PLIST must contain a :name entry which is used as the name of the block."
12267 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12268 (end-of-line 1)
12269 (newline))
12270 (let ((col (current-column))
12271 (name (plist-get plist :name)))
12272 (insert "#+BEGIN: " name)
12273 (while plist
12274 (if (eq (car plist) :name)
12275 (setq plist (cddr plist))
12276 (insert " " (prin1-to-string (pop plist)))))
12277 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12278 (beginning-of-line -2)))
12280 (defun org-prepare-dblock ()
12281 "Prepare dynamic block for refresh.
12282 This empties the block, puts the cursor at the insert position and returns
12283 the property list including an extra property :name with the block name."
12284 (unless (looking-at org-dblock-start-re)
12285 (user-error "Not at a dynamic block"))
12286 (let* ((begdel (1+ (match-end 0)))
12287 (name (org-no-properties (match-string 1)))
12288 (params (append (list :name name)
12289 (read (concat "(" (match-string 3) ")")))))
12290 (save-excursion
12291 (beginning-of-line 1)
12292 (skip-chars-forward " \t")
12293 (setq params (plist-put params :indentation-column (current-column))))
12294 (unless (re-search-forward org-dblock-end-re nil t)
12295 (error "Dynamic block not terminated"))
12296 (setq params
12297 (append params
12298 (list :content (buffer-substring
12299 begdel (match-beginning 0)))))
12300 (delete-region begdel (match-beginning 0))
12301 (goto-char begdel)
12302 (open-line 1)
12303 params))
12305 (defun org-map-dblocks (&optional command)
12306 "Apply COMMAND to all dynamic blocks in the current buffer.
12307 If COMMAND is not given, use `org-update-dblock'."
12308 (let ((cmd (or command 'org-update-dblock)))
12309 (save-excursion
12310 (goto-char (point-min))
12311 (while (re-search-forward org-dblock-start-re nil t)
12312 (goto-char (match-beginning 0))
12313 (save-excursion
12314 (condition-case nil
12315 (funcall cmd)
12316 (error (message "Error during update of dynamic block"))))
12317 (unless (re-search-forward org-dblock-end-re nil t)
12318 (error "Dynamic block not terminated"))))))
12320 (defun org-dblock-update (&optional arg)
12321 "User command for updating dynamic blocks.
12322 Update the dynamic block at point. With prefix ARG, update all dynamic
12323 blocks in the buffer."
12324 (interactive "P")
12325 (if arg
12326 (org-update-all-dblocks)
12327 (or (looking-at org-dblock-start-re)
12328 (org-beginning-of-dblock))
12329 (org-update-dblock)))
12331 (defun org-update-dblock ()
12332 "Update the dynamic block at point.
12333 This means to empty the block, parse for parameters and then call
12334 the correct writing function."
12335 (interactive)
12336 (save-excursion
12337 (let* ((win (selected-window))
12338 (pos (point))
12339 (line (org-current-line))
12340 (params (org-prepare-dblock))
12341 (name (plist-get params :name))
12342 (indent (plist-get params :indentation-column))
12343 (cmd (intern (concat "org-dblock-write:" name))))
12344 (message "Updating dynamic block `%s' at line %d..." name line)
12345 (funcall cmd params)
12346 (message "Updating dynamic block `%s' at line %d...done" name line)
12347 (goto-char pos)
12348 (when (and indent (> indent 0))
12349 (setq indent (make-string indent ?\ ))
12350 (save-excursion
12351 (select-window win)
12352 (org-beginning-of-dblock)
12353 (forward-line 1)
12354 (while (not (looking-at org-dblock-end-re))
12355 (insert indent)
12356 (beginning-of-line 2))
12357 (when (looking-at org-dblock-end-re)
12358 (and (looking-at "[ \t]+")
12359 (replace-match ""))
12360 (insert indent)))))))
12362 (defun org-beginning-of-dblock ()
12363 "Find the beginning of the dynamic block at point.
12364 Error if there is no such block at point."
12365 (let ((pos (point))
12366 beg)
12367 (end-of-line 1)
12368 (if (and (re-search-backward org-dblock-start-re nil t)
12369 (setq beg (match-beginning 0))
12370 (re-search-forward org-dblock-end-re nil t)
12371 (> (match-end 0) pos))
12372 (goto-char beg)
12373 (goto-char pos)
12374 (error "Not in a dynamic block"))))
12376 (defun org-update-all-dblocks ()
12377 "Update all dynamic blocks in the buffer.
12378 This function can be used in a hook."
12379 (interactive)
12380 (when (derived-mode-p 'org-mode)
12381 (org-map-dblocks 'org-update-dblock)))
12384 ;;;; Completion
12386 (declare-function org-export-backend-options "ox" (cl-x) t)
12387 (defun org-get-export-keywords ()
12388 "Return a list of all currently understood export keywords.
12389 Export keywords include options, block names, attributes and
12390 keywords relative to each registered export back-end."
12391 (let (keywords)
12392 (dolist (backend
12393 (bound-and-true-p org-export-registered-backends)
12394 (delq nil keywords))
12395 ;; Back-end name (for keywords, like #+LATEX:)
12396 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12397 (dolist (option-entry (org-export-backend-options backend))
12398 ;; Back-end options.
12399 (push (nth 1 option-entry) keywords)))))
12401 (defconst org-options-keywords
12402 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12403 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12404 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12405 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12406 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12408 (defcustom org-structure-template-alist
12409 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12410 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12411 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12412 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12413 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12414 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12415 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12416 ("L" "#+LaTeX: ")
12417 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12418 ("H" "#+HTML: ")
12419 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12420 ("A" "#+ASCII: ")
12421 ("i" "#+INDEX: ?")
12422 ("I" "#+INCLUDE: %file ?"))
12423 "Structure completion elements.
12424 This is a list of abbreviation keys and values. The value gets inserted
12425 if you type `<' followed by the key and then press the completion key,
12426 usually `TAB'. %file will be replaced by a file name after prompting
12427 for the file using completion. The cursor will be placed at the position
12428 of the `?' in the template.
12429 There are two templates for each key, the first uses the original Org syntax,
12430 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12431 the default when the /org-mtags.el/ module has been loaded. See also the
12432 variable `org-mtags-prefer-muse-templates'."
12433 :group 'org-completion
12434 :type '(repeat
12435 (list
12436 (string :tag "Key")
12437 (string :tag "Template")))
12438 :version "25.2"
12439 :package-version '(Org . "8.3"))
12441 (defun org-try-structure-completion ()
12442 "Try to complete a structure template before point.
12443 This looks for strings like \"<e\" on an otherwise empty line and
12444 expands them."
12445 (let ((l (buffer-substring (point-at-bol) (point)))
12447 (when (and (looking-at "[ \t]*$")
12448 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12449 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12450 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12451 (match-beginning 1)) a)
12452 t)))
12454 (defun org-complete-expand-structure-template (start cell)
12455 "Expand a structure template."
12456 (let ((rpl (nth 1 cell))
12457 (ind ""))
12458 (delete-region start (point))
12459 (when (string-match "\\`[ \t]*#\\+" rpl)
12460 (cond
12461 ((bolp))
12462 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12463 (setq ind (buffer-substring (point-at-bol) (point))))
12464 (t (newline))))
12465 (setq start (point))
12466 (when (string-match "%file" rpl)
12467 (setq rpl (replace-match
12468 (concat
12469 "\""
12470 (save-match-data
12471 (abbreviate-file-name (read-file-name "Include file: ")))
12472 "\"")
12473 t t rpl)))
12474 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12475 (concat "\n" ind)))
12476 (insert rpl)
12477 (when (re-search-backward "\\?" start t) (delete-char 1))))
12479 ;;;; TODO, DEADLINE, Comments
12481 (defun org-toggle-comment ()
12482 "Change the COMMENT state of an entry."
12483 (interactive)
12484 (save-excursion
12485 (org-back-to-heading)
12486 (let ((case-fold-search nil))
12487 (looking-at org-complex-heading-regexp))
12488 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12489 (skip-chars-forward " \t")
12490 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12491 (if (org-in-commented-heading-p t)
12492 (delete-region (point)
12493 (progn (search-forward " " (line-end-position) 'move)
12494 (skip-chars-forward " \t")
12495 (point)))
12496 (insert org-comment-string)
12497 (unless (eolp) (insert " ")))))
12499 (defvar org-last-todo-state-is-todo nil
12500 "This is non-nil when the last TODO state change led to a TODO state.
12501 If the last change removed the TODO tag or switched to DONE, then
12502 this is nil.")
12504 (defvar org-setting-tags nil) ; dynamically skipped
12506 (defvar org-todo-setup-filter-hook nil
12507 "Hook for functions that pre-filter todo specs.
12508 Each function takes a todo spec and returns either nil or the spec
12509 transformed into canonical form." )
12511 (defvar org-todo-get-default-hook nil
12512 "Hook for functions that get a default item for todo.
12513 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12514 nil or a string to be used for the todo mark." )
12516 (defvar org-agenda-headline-snapshot-before-repeat)
12518 (defun org-current-effective-time ()
12519 "Return current time adjusted for `org-extend-today-until' variable."
12520 (let* ((ct (org-current-time))
12521 (dct (decode-time ct))
12522 (ct1
12523 (cond
12524 (org-use-last-clock-out-time-as-effective-time
12525 (or (org-clock-get-last-clock-out-time) ct))
12526 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12527 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12528 (t ct))))
12529 ct1))
12531 (defun org-todo-yesterday (&optional arg)
12532 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12533 (interactive "P")
12534 (if (eq major-mode 'org-agenda-mode)
12535 (apply 'org-agenda-todo-yesterday arg)
12536 (let* ((org-use-effective-time t)
12537 (hour (nth 2 (decode-time (org-current-time))))
12538 (org-extend-today-until (1+ hour)))
12539 (org-todo arg))))
12541 (defvar org-block-entry-blocking ""
12542 "First entry preventing the TODO state change.")
12544 (defun org-cancel-repeater ()
12545 "Cancel a repeater by setting its numeric value to zero."
12546 (interactive)
12547 (save-excursion
12548 (org-back-to-heading t)
12549 (let ((bound1 (point))
12550 (bound0 (save-excursion (outline-next-heading) (point))))
12551 (when (and (re-search-forward
12552 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12553 org-deadline-time-regexp "\\)\\|\\("
12554 org-ts-regexp "\\)")
12555 bound0 t)
12556 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12557 bound1 t))
12558 (replace-match "0" t nil nil 1)))))
12560 (defvar org-state) ;; dynamically scoped into this function
12561 (defun org-todo (&optional arg)
12562 "Change the TODO state of an item.
12564 The state of an item is given by a keyword at the start of the heading,
12565 like
12566 *** TODO Write paper
12567 *** DONE Call mom
12569 The different keywords are specified in the variable `org-todo-keywords'.
12570 By default the available states are \"TODO\" and \"DONE\". So, for this
12571 example: when the item starts with TODO, it is changed to DONE.
12572 When it starts with DONE, the DONE is removed. And when neither TODO nor
12573 DONE are present, add TODO at the beginning of the heading.
12575 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12576 state.
12577 With numeric prefix ARG, switch to that state.
12578 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12579 next set of TODO \
12580 keywords (nextset).
12581 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12582 prefix, circumvent any state blocking.
12583 With a numeric prefix arg of 0, inhibit note taking for the change.
12584 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12586 When called through ELisp, arg is also interpreted in the following way:
12587 `none' -> empty state
12588 \"\" -> switch to empty state
12589 `done' -> switch to DONE
12590 `nextset' -> switch to the next set of keywords
12591 `previousset' -> switch to the previous set of keywords
12592 \"WAITING\" -> switch to the specified keyword, but only if it
12593 really is a member of `org-todo-keywords'."
12594 (interactive "P")
12595 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12596 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12597 'region-start-level 'region))
12598 org-loop-over-headlines-in-active-region)
12599 (org-map-entries
12600 `(org-todo ,arg)
12601 org-loop-over-headlines-in-active-region
12602 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12603 (when (equal arg '(16)) (setq arg 'nextset))
12604 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12605 (let ((org-blocker-hook org-blocker-hook)
12606 commentp
12607 case-fold-search)
12608 (when (equal arg '(64))
12609 (setq arg nil org-blocker-hook nil))
12610 (when (and org-blocker-hook
12611 (or org-inhibit-blocking
12612 (org-entry-get nil "NOBLOCKING")))
12613 (setq org-blocker-hook nil))
12614 (save-excursion
12615 (catch 'exit
12616 (org-back-to-heading t)
12617 (when (org-in-commented-heading-p t)
12618 (org-toggle-comment)
12619 (setq commentp t))
12620 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12621 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12622 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12623 (let* ((match-data (match-data))
12624 (startpos (point-at-bol))
12625 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12626 (org-log-done org-log-done)
12627 (org-log-repeat org-log-repeat)
12628 (org-todo-log-states org-todo-log-states)
12629 (org-inhibit-logging
12630 (if (equal arg 0)
12631 (progn (setq arg nil) 'note) org-inhibit-logging))
12632 (this (match-string 1))
12633 (hl-pos (match-beginning 0))
12634 (head (org-get-todo-sequence-head this))
12635 (ass (assoc head org-todo-kwd-alist))
12636 (interpret (nth 1 ass))
12637 (done-word (nth 3 ass))
12638 (final-done-word (nth 4 ass))
12639 (org-last-state (or this ""))
12640 (completion-ignore-case t)
12641 (member (member this org-todo-keywords-1))
12642 (tail (cdr member))
12643 (org-state (cond
12644 ((and org-todo-key-trigger
12645 (or (and (equal arg '(4))
12646 (eq org-use-fast-todo-selection 'prefix))
12647 (and (not arg) org-use-fast-todo-selection
12648 (not (eq org-use-fast-todo-selection
12649 'prefix)))))
12650 ;; Use fast selection
12651 (org-fast-todo-selection))
12652 ((and (equal arg '(4))
12653 (or (not org-use-fast-todo-selection)
12654 (not org-todo-key-trigger)))
12655 ;; Read a state with completion
12656 (completing-read
12657 "State: " (mapcar #'list org-todo-keywords-1)
12658 nil t))
12659 ((eq arg 'right)
12660 (if this
12661 (if tail (car tail) nil)
12662 (car org-todo-keywords-1)))
12663 ((eq arg 'left)
12664 (unless (equal member org-todo-keywords-1)
12665 (if this
12666 (nth (- (length org-todo-keywords-1)
12667 (length tail) 2)
12668 org-todo-keywords-1)
12669 (org-last org-todo-keywords-1))))
12670 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12671 (setq arg nil))) ; hack to fall back to cycling
12672 (arg
12673 ;; user or caller requests a specific state
12674 (cond
12675 ((equal arg "") nil)
12676 ((eq arg 'none) nil)
12677 ((eq arg 'done) (or done-word (car org-done-keywords)))
12678 ((eq arg 'nextset)
12679 (or (car (cdr (member head org-todo-heads)))
12680 (car org-todo-heads)))
12681 ((eq arg 'previousset)
12682 (let ((org-todo-heads (reverse org-todo-heads)))
12683 (or (car (cdr (member head org-todo-heads)))
12684 (car org-todo-heads))))
12685 ((car (member arg org-todo-keywords-1)))
12686 ((stringp arg)
12687 (user-error "State `%s' not valid in this file" arg))
12688 ((nth (1- (prefix-numeric-value arg))
12689 org-todo-keywords-1))))
12690 ((null member) (or head (car org-todo-keywords-1)))
12691 ((equal this final-done-word) nil) ;; -> make empty
12692 ((null tail) nil) ;; -> first entry
12693 ((memq interpret '(type priority))
12694 (if (eq this-command last-command)
12695 (car tail)
12696 (if (> (length tail) 0)
12697 (or done-word (car org-done-keywords))
12698 nil)))
12700 (car tail))))
12701 (org-state (or
12702 (run-hook-with-args-until-success
12703 'org-todo-get-default-hook org-state org-last-state)
12704 org-state))
12705 (next (if org-state (concat " " org-state " ") " "))
12706 (change-plist (list :type 'todo-state-change :from this :to org-state
12707 :position startpos))
12708 dolog now-done-p)
12709 (when org-blocker-hook
12710 (setq org-last-todo-state-is-todo
12711 (not (member this org-done-keywords)))
12712 (unless (save-excursion
12713 (save-match-data
12714 (org-with-wide-buffer
12715 (run-hook-with-args-until-failure
12716 'org-blocker-hook change-plist))))
12717 (if (called-interactively-p 'interactive)
12718 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12719 this org-state org-block-entry-blocking)
12720 ;; fail silently
12721 (message "TODO state change from %s to %s blocked (by \"%s\")"
12722 this org-state org-block-entry-blocking)
12723 (throw 'exit nil))))
12724 (store-match-data match-data)
12725 (replace-match next t t)
12726 (cond ((equal this org-state)
12727 (message "TODO state was already %s" (org-trim next)))
12728 ((pos-visible-in-window-p hl-pos)
12729 (message "TODO state changed to %s" (org-trim next))))
12730 (unless head
12731 (setq head (org-get-todo-sequence-head org-state)
12732 ass (assoc head org-todo-kwd-alist)
12733 interpret (nth 1 ass)
12734 done-word (nth 3 ass)
12735 final-done-word (nth 4 ass)))
12736 (when (memq arg '(nextset previousset))
12737 (message "Keyword-Set %d/%d: %s"
12738 (- (length org-todo-sets) -1
12739 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12740 (length org-todo-sets)
12741 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12742 (setq org-last-todo-state-is-todo
12743 (not (member org-state org-done-keywords)))
12744 (setq now-done-p (and (member org-state org-done-keywords)
12745 (not (member this org-done-keywords))))
12746 (and logging (org-local-logging logging))
12747 (when (and (or org-todo-log-states org-log-done)
12748 (not (eq org-inhibit-logging t))
12749 (not (memq arg '(nextset previousset))))
12750 ;; we need to look at recording a time and note
12751 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12752 (nth 2 (assoc this org-todo-log-states))))
12753 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12754 (setq dolog 'time))
12755 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12756 (and org-state
12757 (member org-state org-not-done-keywords)
12758 (not (member this org-not-done-keywords))))
12759 ;; This is now a todo state and was not one before
12760 ;; If there was a CLOSED time stamp, get rid of it.
12761 (org-add-planning-info nil nil 'closed))
12762 (when (and now-done-p org-log-done)
12763 ;; It is now done, and it was not done before
12764 (org-add-planning-info 'closed (org-current-effective-time))
12765 (when (and (not dolog) (eq 'note org-log-done))
12766 (org-add-log-setup 'done org-state this 'note)))
12767 (when (and org-state dolog)
12768 ;; This is a non-nil state, and we need to log it
12769 (org-add-log-setup 'state org-state this dolog)))
12770 ;; Fixup tag positioning
12771 (org-todo-trigger-tag-changes org-state)
12772 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12773 (when org-provide-todo-statistics
12774 (org-update-parent-todo-statistics))
12775 (run-hooks 'org-after-todo-state-change-hook)
12776 (when (and arg (not (member org-state org-done-keywords)))
12777 (setq head (org-get-todo-sequence-head org-state)))
12778 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12779 ;; Do we need to trigger a repeat?
12780 (when now-done-p
12781 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12782 ;; This is for the agenda, take a snapshot of the headline.
12783 (save-match-data
12784 (setq org-agenda-headline-snapshot-before-repeat
12785 (org-get-heading))))
12786 (org-auto-repeat-maybe org-state))
12787 ;; Fixup cursor location if close to the keyword
12788 (when (and (outline-on-heading-p)
12789 (not (bolp))
12790 (save-excursion (beginning-of-line 1)
12791 (looking-at org-todo-line-regexp))
12792 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12793 (goto-char (or (match-end 2) (match-end 1)))
12794 (and (looking-at " ") (just-one-space)))
12795 (when org-trigger-hook
12796 (save-excursion
12797 (run-hook-with-args 'org-trigger-hook change-plist)))
12798 (when commentp (org-toggle-comment))))))))
12800 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12801 "Block turning an entry into a TODO, using the hierarchy.
12802 This checks whether the current task should be blocked from state
12803 changes. Such blocking occurs when:
12805 1. The task has children which are not all in a completed state.
12807 2. A task has a parent with the property :ORDERED:, and there
12808 are siblings prior to the current task with incomplete
12809 status.
12811 3. The parent of the task is blocked because it has siblings that should
12812 be done first, or is child of a block grandparent TODO entry."
12814 (if (not org-enforce-todo-dependencies)
12815 t ; if locally turned off don't block
12816 (catch 'dont-block
12817 ;; If this is not a todo state change, or if this entry is already DONE,
12818 ;; do not block
12819 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12820 (member (plist-get change-plist :from)
12821 (cons 'done org-done-keywords))
12822 (member (plist-get change-plist :to)
12823 (cons 'todo org-not-done-keywords))
12824 (not (plist-get change-plist :to)))
12825 (throw 'dont-block t))
12826 ;; If this task has children, and any are undone, it's blocked
12827 (save-excursion
12828 (org-back-to-heading t)
12829 (let ((this-level (funcall outline-level)))
12830 (outline-next-heading)
12831 (let ((child-level (funcall outline-level)))
12832 (while (and (not (eobp))
12833 (> child-level this-level))
12834 ;; this todo has children, check whether they are all
12835 ;; completed
12836 (when (and (not (org-entry-is-done-p))
12837 (org-entry-is-todo-p))
12838 (setq org-block-entry-blocking (org-get-heading))
12839 (throw 'dont-block nil))
12840 (outline-next-heading)
12841 (setq child-level (funcall outline-level))))))
12842 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12843 ;; any previous siblings are undone, it's blocked
12844 (save-excursion
12845 (org-back-to-heading t)
12846 (let* ((pos (point))
12847 (parent-pos (and (org-up-heading-safe) (point))))
12848 (unless parent-pos (throw 'dont-block t)) ; no parent
12849 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12850 (forward-line 1)
12851 (re-search-forward org-not-done-heading-regexp pos t))
12852 (setq org-block-entry-blocking (match-string 0))
12853 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12854 ;; Search further up the hierarchy, to see if an ancestor is blocked
12855 (while t
12856 (goto-char parent-pos)
12857 (unless (looking-at org-not-done-heading-regexp)
12858 (throw 'dont-block t)) ; do not block, parent is not a TODO
12859 (setq pos (point))
12860 (setq parent-pos (and (org-up-heading-safe) (point)))
12861 (unless parent-pos (throw 'dont-block t)) ; no parent
12862 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12863 (forward-line 1)
12864 (re-search-forward org-not-done-heading-regexp pos t)
12865 (setq org-block-entry-blocking (org-get-heading)))
12866 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12868 (defcustom org-track-ordered-property-with-tag nil
12869 "Should the ORDERED property also be shown as a tag?
12870 The ORDERED property decides if an entry should require subtasks to be
12871 completed in sequence. Since a property is not very visible, setting
12872 this option means that toggling the ORDERED property with the command
12873 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12874 not relevant for the behavior, but it makes things more visible.
12876 Note that toggling the tag with tags commands will not change the property
12877 and therefore not influence behavior!
12879 This can be t, meaning the tag ORDERED should be used, It can also be a
12880 string to select a different tag for this task."
12881 :group 'org-todo
12882 :type '(choice
12883 (const :tag "No tracking" nil)
12884 (const :tag "Track with ORDERED tag" t)
12885 (string :tag "Use other tag")))
12887 (defun org-toggle-ordered-property ()
12888 "Toggle the ORDERED property of the current entry.
12889 For better visibility, you can track the value of this property with a tag.
12890 See variable `org-track-ordered-property-with-tag'."
12891 (interactive)
12892 (let* ((t1 org-track-ordered-property-with-tag)
12893 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12894 (save-excursion
12895 (org-back-to-heading)
12896 (if (org-entry-get nil "ORDERED")
12897 (progn
12898 (org-delete-property "ORDERED")
12899 (and tag (org-toggle-tag tag 'off))
12900 (message "Subtasks can be completed in arbitrary order"))
12901 (org-entry-put nil "ORDERED" "t")
12902 (and tag (org-toggle-tag tag 'on))
12903 (message "Subtasks must be completed in sequence")))))
12905 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12906 (defun org-block-todo-from-checkboxes (change-plist)
12907 "Block turning an entry into a TODO, using checkboxes.
12908 This checks whether the current task should be blocked from state
12909 changes because there are unchecked boxes in this entry."
12910 (if (not org-enforce-todo-checkbox-dependencies)
12911 t ; if locally turned off don't block
12912 (catch 'dont-block
12913 ;; If this is not a todo state change, or if this entry is already DONE,
12914 ;; do not block
12915 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12916 (member (plist-get change-plist :from)
12917 (cons 'done org-done-keywords))
12918 (member (plist-get change-plist :to)
12919 (cons 'todo org-not-done-keywords))
12920 (not (plist-get change-plist :to)))
12921 (throw 'dont-block t))
12922 ;; If this task has checkboxes that are not checked, it's blocked
12923 (save-excursion
12924 (org-back-to-heading t)
12925 (let ((beg (point)) end)
12926 (outline-next-heading)
12927 (setq end (point))
12928 (goto-char beg)
12929 (when (org-list-search-forward
12930 (concat (org-item-beginning-re)
12931 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12932 "\\[[- ]\\]")
12933 end t)
12934 (when (boundp 'org-blocked-by-checkboxes)
12935 (setq org-blocked-by-checkboxes t))
12936 (throw 'dont-block nil))))
12937 t))) ; do not block
12939 (defun org-entry-blocked-p ()
12940 "Non-nil if entry at point is blocked."
12941 (and (not (org-entry-get nil "NOBLOCKING"))
12942 (member (org-entry-get nil "TODO") org-not-done-keywords)
12943 (not (run-hook-with-args-until-failure
12944 'org-blocker-hook
12945 (list :type 'todo-state-change
12946 :position (point)
12947 :from 'todo
12948 :to 'done)))))
12950 (defun org-update-statistics-cookies (all)
12951 "Update the statistics cookie, either from TODO or from checkboxes.
12952 This should be called with the cursor in a line with a statistics
12953 cookie. When called with a \\[universal-argument] prefix, update
12954 all statistics cookies in the buffer."
12955 (interactive "P")
12956 (if all
12957 (progn
12958 (org-update-checkbox-count 'all)
12959 (org-map-entries 'org-update-parent-todo-statistics))
12960 (if (not (org-at-heading-p))
12961 (org-update-checkbox-count)
12962 (let ((pos (point-marker))
12963 end l1 l2)
12964 (ignore-errors (org-back-to-heading t))
12965 (if (not (org-at-heading-p))
12966 (org-update-checkbox-count)
12967 (setq l1 (org-outline-level))
12968 (setq end (save-excursion
12969 (outline-next-heading)
12970 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12971 (point)))
12972 (if (and (save-excursion
12973 (re-search-forward
12974 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12975 (not (save-excursion (re-search-forward
12976 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12977 (org-update-checkbox-count)
12978 (if (and l2 (> l2 l1))
12979 (progn
12980 (goto-char end)
12981 (org-update-parent-todo-statistics))
12982 (goto-char pos)
12983 (beginning-of-line 1)
12984 (while (re-search-forward
12985 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12986 (point-at-eol) t)
12987 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12988 (goto-char pos)
12989 (move-marker pos nil)))))
12991 (defvar org-entry-property-inherited-from) ;; defined below
12992 (defun org-update-parent-todo-statistics ()
12993 "Update any statistics cookie in the parent of the current headline.
12994 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12995 the entire subtree and this will travel up the hierarchy and update
12996 statistics everywhere."
12997 (let* ((prop (save-excursion (org-up-heading-safe)
12998 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12999 (recursive (or (not org-hierarchical-todo-statistics)
13000 (and prop (string-match "\\<recursive\\>" prop))))
13001 (lim (or (and prop (marker-position org-entry-property-inherited-from))
13003 (first t)
13004 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
13005 level ltoggle l1 new ndel
13006 (cnt-all 0) (cnt-done 0) is-percent kwd
13007 checkbox-beg cookie-present)
13008 (catch 'exit
13009 (save-excursion
13010 (beginning-of-line 1)
13011 (setq ltoggle (funcall outline-level))
13012 ;; Three situations are to consider:
13014 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
13015 ;; to the top-level ancestor on the headline;
13017 ;; 2. If parent has "recursive" property, repeat up to the
13018 ;; headline setting that property, taking inheritance into
13019 ;; account;
13021 ;; 3. Else, move up to direct parent and proceed only once.
13022 (while (and (setq level (org-up-heading-safe))
13023 (or recursive first)
13024 (>= (point) lim))
13025 (setq first nil cookie-present nil)
13026 (unless (and level
13027 (not (string-match
13028 "\\<checkbox\\>"
13029 (downcase (or (org-entry-get nil "COOKIE_DATA")
13030 "")))))
13031 (throw 'exit nil))
13032 (while (re-search-forward box-re (point-at-eol) t)
13033 (setq cnt-all 0 cnt-done 0 cookie-present t)
13034 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
13035 (save-match-data
13036 (unless (outline-next-heading) (throw 'exit nil))
13037 (while (and (looking-at org-complex-heading-regexp)
13038 (> (setq l1 (length (match-string 1))) level))
13039 (setq kwd (and (or recursive (= l1 ltoggle))
13040 (match-string 2)))
13041 (if (or (eq org-provide-todo-statistics 'all-headlines)
13042 (and (eq org-provide-todo-statistics t)
13043 (or (member kwd org-done-keywords)))
13044 (and (listp org-provide-todo-statistics)
13045 (stringp (car org-provide-todo-statistics))
13046 (or (member kwd org-provide-todo-statistics)
13047 (member kwd org-done-keywords)))
13048 (and (listp org-provide-todo-statistics)
13049 (listp (car org-provide-todo-statistics))
13050 (or (member kwd (car org-provide-todo-statistics))
13051 (and (member kwd org-done-keywords)
13052 (member kwd (cadr org-provide-todo-statistics))))))
13053 (setq cnt-all (1+ cnt-all))
13054 (and (eq org-provide-todo-statistics t)
13056 (setq cnt-all (1+ cnt-all))))
13057 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
13058 (member kwd org-done-keywords))
13059 (and (listp org-provide-todo-statistics)
13060 (listp (car org-provide-todo-statistics))
13061 (member kwd org-done-keywords)
13062 (member kwd (cadr org-provide-todo-statistics)))
13063 (and (listp org-provide-todo-statistics)
13064 (stringp (car org-provide-todo-statistics))
13065 (member kwd org-done-keywords)))
13066 (setq cnt-done (1+ cnt-done)))
13067 (outline-next-heading)))
13068 (setq new
13069 (if is-percent
13070 (format "[%d%%]" (floor (* 100.0 cnt-done)
13071 (max 1 cnt-all)))
13072 (format "[%d/%d]" cnt-done cnt-all))
13073 ndel (- (match-end 0) checkbox-beg))
13074 (goto-char checkbox-beg)
13075 (insert new)
13076 (delete-region (point) (+ (point) ndel))
13077 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
13078 (when cookie-present
13079 (run-hook-with-args 'org-after-todo-statistics-hook
13080 cnt-done (- cnt-all cnt-done))))))
13081 (run-hooks 'org-todo-statistics-hook)))
13083 (defvar org-after-todo-statistics-hook nil
13084 "Hook that is called after a TODO statistics cookie has been updated.
13085 Each function is called with two arguments: the number of not-done entries
13086 and the number of done entries.
13088 For example, the following function, when added to this hook, will switch
13089 an entry to DONE when all children are done, and back to TODO when new
13090 entries are set to a TODO status. Note that this hook is only called
13091 when there is a statistics cookie in the headline!
13093 (defun org-summary-todo (n-done n-not-done)
13094 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13095 (let (org-log-done org-log-states) ; turn off logging
13096 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13099 (defvar org-todo-statistics-hook nil
13100 "Hook that is run whenever Org thinks TODO statistics should be updated.
13101 This hook runs even if there is no statistics cookie present, in which case
13102 `org-after-todo-statistics-hook' would not run.")
13104 (defun org-todo-trigger-tag-changes (state)
13105 "Apply the changes defined in `org-todo-state-tags-triggers'."
13106 (let ((l org-todo-state-tags-triggers)
13107 changes)
13108 (when (or (not state) (equal state ""))
13109 (setq changes (append changes (cdr (assoc "" l)))))
13110 (when (and (stringp state) (> (length state) 0))
13111 (setq changes (append changes (cdr (assoc state l)))))
13112 (when (member state org-not-done-keywords)
13113 (setq changes (append changes (cdr (assq 'todo l)))))
13114 (when (member state org-done-keywords)
13115 (setq changes (append changes (cdr (assq 'done l)))))
13116 (dolist (c changes)
13117 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13119 (defun org-local-logging (value)
13120 "Get logging settings from a property VALUE."
13121 ;; Directly set the variables, they are already local.
13122 (setq org-log-done nil
13123 org-log-repeat nil
13124 org-todo-log-states nil)
13125 (dolist (w (org-split-string value))
13126 (let (a)
13127 (cond
13128 ((setq a (assoc w org-startup-options))
13129 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13130 (set (nth 1 a) (nth 2 a))))
13131 ((setq a (org-extract-log-state-settings w))
13132 (and (member (car a) org-todo-keywords-1)
13133 (push a org-todo-log-states)))))))
13135 (defun org-get-todo-sequence-head (kwd)
13136 "Return the head of the TODO sequence to which KWD belongs.
13137 If KWD is not set, check if there is a text property remembering the
13138 right sequence."
13139 (let (p)
13140 (cond
13141 ((not kwd)
13142 (or (get-text-property (point-at-bol) 'org-todo-head)
13143 (progn
13144 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13145 nil (point-at-eol)))
13146 (get-text-property p 'org-todo-head))))
13147 ((not (member kwd org-todo-keywords-1))
13148 (car org-todo-keywords-1))
13149 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13151 (defun org-fast-todo-selection ()
13152 "Fast TODO keyword selection with single keys.
13153 Returns the new TODO keyword, or nil if no state change should occur."
13154 (let* ((fulltable org-todo-key-alist)
13155 (done-keywords org-done-keywords) ;; needed for the faces.
13156 (maxlen (apply 'max (mapcar
13157 (lambda (x)
13158 (if (stringp (car x)) (string-width (car x)) 0))
13159 fulltable)))
13160 (expert nil)
13161 (fwidth (+ maxlen 3 1 3))
13162 (ncol (/ (- (window-width) 4) fwidth))
13163 tg cnt e c tbl
13164 groups ingroup)
13165 (save-excursion
13166 (save-window-excursion
13167 (if expert
13168 (set-buffer (get-buffer-create " *Org todo*"))
13169 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13170 (erase-buffer)
13171 (setq-local org-done-keywords done-keywords)
13172 (setq tbl fulltable cnt 0)
13173 (while (setq e (pop tbl))
13174 (cond
13175 ((equal e '(:startgroup))
13176 (push '() groups) (setq ingroup t)
13177 (unless (= cnt 0)
13178 (setq cnt 0)
13179 (insert "\n"))
13180 (insert "{ "))
13181 ((equal e '(:endgroup))
13182 (setq ingroup nil cnt 0)
13183 (insert "}\n"))
13184 ((equal e '(:newline))
13185 (unless (= cnt 0)
13186 (setq cnt 0)
13187 (insert "\n")
13188 (setq e (car tbl))
13189 (while (equal (car tbl) '(:newline))
13190 (insert "\n")
13191 (setq tbl (cdr tbl)))))
13193 (setq tg (car e) c (cdr e))
13194 (when ingroup (push tg (car groups)))
13195 (setq tg (org-add-props tg nil 'face
13196 (org-get-todo-face tg)))
13197 (when (and (= cnt 0) (not ingroup)) (insert " "))
13198 (insert "[" c "] " tg (make-string
13199 (- fwidth 4 (length tg)) ?\ ))
13200 (when (= (setq cnt (1+ cnt)) ncol)
13201 (insert "\n")
13202 (when ingroup (insert " "))
13203 (setq cnt 0)))))
13204 (insert "\n")
13205 (goto-char (point-min))
13206 (unless expert (org-fit-window-to-buffer))
13207 (message "[a-z..]:Set [SPC]:clear")
13208 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13209 (cond
13210 ((or (= c ?\C-g)
13211 (and (= c ?q) (not (rassoc c fulltable))))
13212 (setq quit-flag t))
13213 ((= c ?\ ) nil)
13214 ((setq e (rassoc c fulltable) tg (car e))
13216 (t (setq quit-flag t)))))))
13218 (defun org-entry-is-todo-p ()
13219 (member (org-get-todo-state) org-not-done-keywords))
13221 (defun org-entry-is-done-p ()
13222 (member (org-get-todo-state) org-done-keywords))
13224 (defun org-get-todo-state ()
13225 "Return the TODO keyword of the current subtree."
13226 (save-excursion
13227 (org-back-to-heading t)
13228 (and (looking-at org-todo-line-regexp)
13229 (match-end 2)
13230 (match-string 2))))
13232 (defun org-at-date-range-p (&optional inactive-ok)
13233 "Non-nil if point is inside a date range.
13235 When optional argument INACTIVE-OK is non-nil, also consider
13236 inactive time ranges.
13238 When this function returns a non-nil value, match data is set
13239 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13240 on INACTIVE-OK."
13241 (interactive)
13242 (save-excursion
13243 (catch 'exit
13244 (let ((pos (point)))
13245 (skip-chars-backward "^[<\r\n")
13246 (skip-chars-backward "<[")
13247 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13248 (>= (match-end 0) pos)
13249 (throw 'exit t))
13250 (skip-chars-backward "^<[\r\n")
13251 (skip-chars-backward "<[")
13252 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13253 (>= (match-end 0) pos)
13254 (throw 'exit t)))
13255 nil)))
13257 (defun org-get-repeat (&optional tagline)
13258 "Check if there is a deadline/schedule with repeater in this entry."
13259 (save-match-data
13260 (save-excursion
13261 (org-back-to-heading t)
13262 (and (re-search-forward (if tagline
13263 (concat tagline "\\s-*" org-repeat-re)
13264 org-repeat-re)
13265 (org-entry-end-position) t)
13266 (match-string-no-properties 1)))))
13268 (defvar org-last-changed-timestamp)
13269 (defvar org-last-inserted-timestamp)
13270 (defvar org-log-post-message)
13271 (defvar org-log-note-purpose)
13272 (defvar org-log-note-how nil)
13273 (defvar org-log-note-extra)
13274 (defun org-auto-repeat-maybe (done-word)
13275 "Check if the current headline contains a repeated time-stamp.
13277 If yes, set TODO state back to what it was and change the base date
13278 of repeating deadline/scheduled time stamps to new date.
13280 This function is run automatically after each state change to a DONE state."
13281 (let* ((repeat (org-get-repeat))
13282 (aa (assoc org-last-state org-todo-kwd-alist))
13283 (interpret (nth 1 aa))
13284 (head (nth 2 aa))
13285 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13286 (msg "Entry repeats: ")
13287 (org-log-done nil)
13288 (org-todo-log-states nil))
13289 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13290 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13291 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13292 org-todo-repeat-to-state)))
13293 (unless (and to-state (member to-state org-todo-keywords-1))
13294 (setq to-state (if (eq interpret 'type) org-last-state head)))
13295 (org-todo to-state))
13296 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13297 (org-entry-put nil "LAST_REPEAT" (format-time-string
13298 (org-time-stamp-format t t))))
13299 (when org-log-repeat
13300 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13301 (memq 'org-add-log-note post-command-hook))
13302 ;; We are already setup for some record.
13303 (when (eq org-log-repeat 'note)
13304 ;; Make sure we take a note, not only a time stamp.
13305 (setq org-log-note-how 'note))
13306 ;; Set up for taking a record.
13307 (org-add-log-setup 'state
13308 (or done-word (car org-done-keywords))
13309 org-last-state
13310 org-log-repeat)))
13311 (org-back-to-heading t)
13312 (org-add-planning-info nil nil 'closed)
13313 (let ((end (save-excursion (outline-next-heading) (point))))
13314 (while (re-search-forward org-ts-regexp end t)
13315 (when (save-match-data
13316 (or (org-at-planning-p)
13317 (org-at-property-p)
13318 (eq (org-element-type (save-excursion
13319 (backward-char)
13320 (org-element-context)))
13321 'timestamp)))
13322 (let ((type (cond ((match-end 1) org-scheduled-string)
13323 ((match-end 3) org-deadline-string)
13324 (t "Plain:")))
13325 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13326 (cond
13327 ((not
13328 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13329 ;; Time-stamps without a repeater are usually skipped.
13330 ;; However, a SCHEDULED time-stamp without one is
13331 ;; removed, as it is considered as no longer relevant.
13332 (when (equal type org-scheduled-string)
13333 (org-remove-timestamp-with-keyword type)))
13335 (let ((n (string-to-number (match-string 2 ts)))
13336 (what (match-string 3 ts)))
13337 (when (equal what "w") (setq n (* n 7) what "d"))
13338 (when (and (equal what "h")
13339 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13340 ts)))
13341 (user-error
13342 "Cannot repeat in Repeat in %d hour(s) because no hour \
13343 has been set"
13345 ;; Preparation, see if we need to modify the start
13346 ;; date for the change.
13347 (when (match-end 1)
13348 (let ((time (save-match-data (org-time-string-to-time ts))))
13349 (cond
13350 ((equal (match-string 1 ts) ".")
13351 ;; Shift starting date to today
13352 (org-timestamp-change
13353 (- (org-today) (time-to-days time))
13354 'day))
13355 ((equal (match-string 1 ts) "+")
13356 (let ((nshiftmax 10)
13357 (nshift 0))
13358 (while (or (= nshift 0)
13359 (not (time-less-p (current-time) time)))
13360 (when (= (cl-incf nshift) nshiftmax)
13361 (or (y-or-n-p
13362 (format "%d repeater intervals were not \
13363 enough to shift date past today. Continue? "
13364 nshift))
13365 (user-error "Abort")))
13366 (org-timestamp-change n (cdr (assoc what whata)))
13367 (org-at-timestamp-p t)
13368 (setq ts (match-string 1))
13369 (setq time
13370 (save-match-data
13371 (org-time-string-to-time ts)))))
13372 (org-timestamp-change (- n) (cdr (assoc what whata)))
13373 ;; Rematch, so that we have everything in
13374 ;; place for the real shift.
13375 (org-at-timestamp-p t)
13376 (setq ts (match-string 1))
13377 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13378 ts)))))
13379 (save-excursion
13380 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13381 (setq msg
13382 (concat
13383 msg type " " org-last-changed-timestamp " ")))))))))
13384 (setq org-log-post-message msg)
13385 (message "%s" msg))))
13387 (defun org-show-todo-tree (arg)
13388 "Make a compact tree which shows all headlines marked with TODO.
13389 The tree will show the lines where the regexp matches, and all higher
13390 headlines above the match.
13391 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13392 With a numeric prefix N, construct a sparse tree for the Nth element
13393 of `org-todo-keywords-1'."
13394 (interactive "P")
13395 (let ((case-fold-search nil)
13396 (kwd-re
13397 (cond ((null arg) org-not-done-regexp)
13398 ((equal arg '(4))
13399 (let ((kwd
13400 (completing-read "Keyword (or KWD1|KWD2|...): "
13401 (mapcar #'list org-todo-keywords-1))))
13402 (concat "\\("
13403 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13404 "\\)\\>")))
13405 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13406 (regexp-quote (nth (1- (prefix-numeric-value arg))
13407 org-todo-keywords-1)))
13408 (t (user-error "Invalid prefix argument: %s" arg)))))
13409 (message "%d TODO entries found"
13410 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13412 (defun org-deadline (arg &optional time)
13413 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13414 With one universal prefix argument, remove any deadline from the item.
13415 With two universal prefix arguments, prompt for a warning delay.
13416 With argument TIME, set the deadline at the corresponding date. TIME
13417 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13418 (interactive "P")
13419 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13420 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13421 'region-start-level 'region))
13422 org-loop-over-headlines-in-active-region)
13423 (org-map-entries
13424 `(org-deadline ',arg ,time)
13425 org-loop-over-headlines-in-active-region
13426 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13427 (let* ((old-date (org-entry-get nil "DEADLINE"))
13428 (old-date-time (when old-date (org-time-string-to-time old-date)))
13429 (repeater (and old-date
13430 (string-match
13431 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13432 old-date)
13433 (match-string 1 old-date))))
13434 (cond
13435 ((equal arg '(4))
13436 (when (and old-date org-log-redeadline)
13437 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13438 (org-remove-timestamp-with-keyword org-deadline-string)
13439 (message "Item no longer has a deadline."))
13440 ((equal arg '(16))
13441 (save-excursion
13442 (org-back-to-heading t)
13443 (if (re-search-forward
13444 org-deadline-time-regexp
13445 (save-excursion (outline-next-heading) (point)) t)
13446 (let* ((rpl0 (match-string 1))
13447 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13448 (replace-match
13449 (concat org-deadline-string
13450 " <" rpl
13451 (format " -%dd"
13452 (abs
13453 (- (time-to-days
13454 (save-match-data
13455 (org-read-date nil t nil "Warn starting from" old-date-time)))
13456 (time-to-days old-date-time))))
13457 ">") t t))
13458 (user-error "No deadline information to update"))))
13460 (org-add-planning-info 'deadline time 'closed)
13461 (when (and old-date
13462 org-log-redeadline
13463 (not (equal old-date org-last-inserted-timestamp)))
13464 (org-add-log-setup
13465 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13466 (when repeater
13467 (save-excursion
13468 (org-back-to-heading t)
13469 (when (re-search-forward (concat org-deadline-string " "
13470 org-last-inserted-timestamp)
13471 (save-excursion
13472 (outline-next-heading) (point)) t)
13473 (goto-char (1- (match-end 0)))
13474 (insert " " repeater)
13475 (setq org-last-inserted-timestamp
13476 (concat (substring org-last-inserted-timestamp 0 -1)
13477 " " repeater
13478 (substring org-last-inserted-timestamp -1))))))
13479 (message "Deadline on %s" org-last-inserted-timestamp))))))
13481 (defun org-schedule (arg &optional time)
13482 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13483 With one universal prefix argument, remove any scheduling date from the item.
13484 With two universal prefix arguments, prompt for a delay cookie.
13485 With argument TIME, scheduled at the corresponding date. TIME can
13486 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13487 (interactive "P")
13488 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13489 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13490 'region-start-level 'region))
13491 org-loop-over-headlines-in-active-region)
13492 (org-map-entries
13493 `(org-schedule ',arg ,time)
13494 org-loop-over-headlines-in-active-region
13495 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13496 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13497 (old-date-time (when old-date (org-time-string-to-time old-date)))
13498 (repeater (and old-date
13499 (string-match
13500 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13501 old-date)
13502 (match-string 1 old-date))))
13503 (cond
13504 ((equal arg '(4))
13505 (progn
13506 (when (and old-date org-log-reschedule)
13507 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13508 (org-remove-timestamp-with-keyword org-scheduled-string)
13509 (message "Item is no longer scheduled.")))
13510 ((equal arg '(16))
13511 (save-excursion
13512 (org-back-to-heading t)
13513 (if (re-search-forward
13514 org-scheduled-time-regexp
13515 (save-excursion (outline-next-heading) (point)) t)
13516 (let* ((rpl0 (match-string 1))
13517 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13518 (replace-match
13519 (concat org-scheduled-string
13520 " <" rpl
13521 (format " -%dd"
13522 (abs
13523 (- (time-to-days
13524 (save-match-data
13525 (org-read-date nil t nil "Delay until" old-date-time)))
13526 (time-to-days old-date-time))))
13527 ">") t t))
13528 (user-error "No scheduled information to update"))))
13530 (org-add-planning-info 'scheduled time 'closed)
13531 (when (and old-date
13532 org-log-reschedule
13533 (not (equal old-date org-last-inserted-timestamp)))
13534 (org-add-log-setup
13535 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13536 (when repeater
13537 (save-excursion
13538 (org-back-to-heading t)
13539 (when (re-search-forward (concat org-scheduled-string " "
13540 org-last-inserted-timestamp)
13541 (save-excursion
13542 (outline-next-heading) (point)) t)
13543 (goto-char (1- (match-end 0)))
13544 (insert " " repeater)
13545 (setq org-last-inserted-timestamp
13546 (concat (substring org-last-inserted-timestamp 0 -1)
13547 " " repeater
13548 (substring org-last-inserted-timestamp -1))))))
13549 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13551 (defun org-get-scheduled-time (pom &optional inherit)
13552 "Get the scheduled time as a time tuple, of a format suitable
13553 for calling org-schedule with, or if there is no scheduling,
13554 returns nil."
13555 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13556 (when time
13557 (apply 'encode-time (org-parse-time-string time)))))
13559 (defun org-get-deadline-time (pom &optional inherit)
13560 "Get the deadline as a time tuple, of a format suitable for
13561 calling org-deadline with, or if there is no scheduling, returns
13562 nil."
13563 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13564 (when time
13565 (apply 'encode-time (org-parse-time-string time)))))
13567 (defun org-remove-timestamp-with-keyword (keyword)
13568 "Remove all time stamps with KEYWORD in the current entry."
13569 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13570 beg)
13571 (save-excursion
13572 (org-back-to-heading t)
13573 (setq beg (point))
13574 (outline-next-heading)
13575 (while (re-search-backward re beg t)
13576 (replace-match "")
13577 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13578 (equal (char-before) ?\ ))
13579 (backward-delete-char 1)
13580 (when (string-match "^[ \t]*$" (buffer-substring
13581 (point-at-bol) (point-at-eol)))
13582 (delete-region (point-at-bol)
13583 (min (point-max) (1+ (point-at-eol))))))))))
13585 (defvar org-time-was-given) ; dynamically scoped parameter
13586 (defvar org-end-time-was-given) ; dynamically scoped parameter
13588 (defun org-at-planning-p ()
13589 "Non-nil when point is on a planning info line."
13590 ;; This is as accurate and faster than `org-element-at-point' since
13591 ;; planning info location is fixed in the section.
13592 (org-with-wide-buffer
13593 (beginning-of-line)
13594 (and (looking-at-p org-planning-line-re)
13595 (eq (point)
13596 (ignore-errors
13597 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13598 (org-back-to-heading t)
13599 (org-with-limited-levels (org-back-to-heading t)))
13600 (line-beginning-position 2))))))
13602 (defun org-add-planning-info (what &optional time &rest remove)
13603 "Insert new timestamp with keyword in the planning line.
13604 WHAT indicates what kind of time stamp to add. It is a symbol
13605 among `closed', `deadline', `scheduled' and nil. TIME indicates
13606 the time to use. If none is given, the user is prompted for
13607 a date. REMOVE indicates what kind of entries to remove. An old
13608 WHAT entry will also be removed."
13609 (let (org-time-was-given org-end-time-was-given default-time default-input)
13610 (catch 'exit
13611 (when (and (memq what '(scheduled deadline))
13612 (or (not time)
13613 (and (stringp time)
13614 (string-match "^[-+]+[0-9]" time))))
13615 ;; Try to get a default date/time from existing timestamp
13616 (save-excursion
13617 (org-back-to-heading t)
13618 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13619 (when (re-search-forward (if (eq what 'scheduled)
13620 org-scheduled-time-regexp
13621 org-deadline-time-regexp)
13622 end t)
13623 (setq ts (match-string 1)
13624 default-time (apply 'encode-time (org-parse-time-string ts))
13625 default-input (and ts (org-get-compact-tod ts)))))))
13626 (when what
13627 (setq time
13628 (if (stringp time)
13629 ;; This is a string (relative or absolute), set
13630 ;; proper date.
13631 (apply #'encode-time
13632 (org-read-date-analyze
13633 time default-time (decode-time default-time)))
13634 ;; If necessary, get the time from the user
13635 (or time (org-read-date nil 'to-time nil nil
13636 default-time default-input)))))
13638 (org-with-wide-buffer
13639 (org-back-to-heading t)
13640 (forward-line)
13641 (unless (bolp) (insert "\n"))
13642 (cond ((looking-at-p org-planning-line-re)
13643 ;; Move to current indentation.
13644 (skip-chars-forward " \t")
13645 ;; Check if we have to remove something.
13646 (dolist (type (if what (cons what remove) remove))
13647 (save-excursion
13648 (when (re-search-forward
13649 (cl-case type
13650 (closed org-closed-time-regexp)
13651 (deadline org-deadline-time-regexp)
13652 (scheduled org-scheduled-time-regexp)
13653 (otherwise
13654 (error "Invalid planning type: %s" type)))
13655 (line-end-position) t)
13656 ;; Delete until next keyword or end of line.
13657 (delete-region
13658 (match-beginning 0)
13659 (if (re-search-forward org-keyword-time-not-clock-regexp
13660 (line-end-position)
13662 (match-beginning 0)
13663 (line-end-position))))))
13664 ;; If there is nothing more to add and no more keyword
13665 ;; is left, remove the line completely.
13666 (if (and (looking-at-p "[ \t]*$") (not what))
13667 (delete-region (line-beginning-position)
13668 (line-beginning-position 2))
13669 ;; If we removed last keyword, do not leave trailing
13670 ;; white space at the end of line.
13671 (let ((p (point)))
13672 (save-excursion
13673 (end-of-line)
13674 (unless (= (skip-chars-backward " \t" p) 0)
13675 (delete-region (point) (line-end-position)))))))
13676 ((not what) (throw 'exit nil)) ; Nothing to do.
13677 (t (insert-before-markers "\n")
13678 (backward-char 1)
13679 (when org-adapt-indentation
13680 (indent-to-column (1+ (org-outline-level))))))
13681 (when what
13682 ;; Insert planning keyword.
13683 (insert (cl-case what
13684 (closed org-closed-string)
13685 (deadline org-deadline-string)
13686 (scheduled org-scheduled-string)
13687 (otherwise (error "Invalid planning type: %s" what)))
13688 " ")
13689 ;; Insert associated timestamp.
13690 (let ((ts (org-insert-time-stamp
13691 time
13692 (or org-time-was-given
13693 (and (eq what 'closed) org-log-done-with-time))
13694 (eq what 'closed)
13695 nil nil (list org-end-time-was-given))))
13696 (unless (eolp) (insert " "))
13697 ts))))))
13699 (defvar org-log-note-marker (make-marker)
13700 "Marker pointing at the entry where the note is to be inserted.")
13701 (defvar org-log-note-purpose nil)
13702 (defvar org-log-note-state nil)
13703 (defvar org-log-note-previous-state nil)
13704 (defvar org-log-note-extra nil)
13705 (defvar org-log-note-window-configuration nil)
13706 (defvar org-log-note-return-to (make-marker))
13707 (defvar org-log-note-effective-time nil
13708 "Remembered current time so that dynamically scoped
13709 `org-extend-today-until' affects timestamps in state change log")
13711 (defvar org-log-post-message nil
13712 "Message to be displayed after a log note has been stored.
13713 The auto-repeater uses this.")
13715 (defun org-add-note ()
13716 "Add a note to the current entry.
13717 This is done in the same way as adding a state change note."
13718 (interactive)
13719 (org-add-log-setup 'note))
13721 (defun org-log-beginning (&optional create)
13722 "Return expected start of log notes in current entry.
13723 When optional argument CREATE is non-nil, the function creates
13724 a drawer to store notes, if necessary. Returned position ignores
13725 narrowing."
13726 (org-with-wide-buffer
13727 (let ((drawer (org-log-into-drawer)))
13728 (cond
13729 (drawer
13730 (org-end-of-meta-data)
13731 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13732 (end (if (org-at-heading-p) (point)
13733 (save-excursion (outline-next-heading) (point))))
13734 (case-fold-search t))
13735 (catch 'exit
13736 ;; Try to find existing drawer.
13737 (while (re-search-forward regexp end t)
13738 (let ((element (org-element-at-point)))
13739 (when (eq (org-element-type element) 'drawer)
13740 (let ((cend (org-element-property :contents-end element)))
13741 (when (and (not org-log-states-order-reversed) cend)
13742 (goto-char cend)))
13743 (throw 'exit nil))))
13744 ;; No drawer found. Create one, if permitted.
13745 (when create
13746 (unless (bolp) (insert "\n"))
13747 (let ((beg (point)))
13748 (insert ":" drawer ":\n:END:\n")
13749 (org-indent-region beg (point)))
13750 (end-of-line -1)))))
13752 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13753 (skip-chars-forward " \t\n")
13754 (beginning-of-line)
13755 (unless org-log-states-order-reversed
13756 (org-skip-over-state-notes)
13757 (skip-chars-backward " \t\n")
13758 (forward-line)))))
13759 (if (bolp) (point) (line-beginning-position 2))))
13761 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13762 "Set up the post command hook to take a note.
13763 If this is about to TODO state change, the new state is expected in STATE.
13764 HOW is an indicator what kind of note should be created.
13765 EXTRA is additional text that will be inserted into the notes buffer."
13766 (move-marker org-log-note-marker (point))
13767 (setq org-log-note-purpose purpose
13768 org-log-note-state state
13769 org-log-note-previous-state prev-state
13770 org-log-note-how how
13771 org-log-note-extra extra
13772 org-log-note-effective-time (org-current-effective-time))
13773 (add-hook 'post-command-hook 'org-add-log-note 'append))
13775 (defun org-skip-over-state-notes ()
13776 "Skip past the list of State notes in an entry."
13777 (when (ignore-errors (goto-char (org-in-item-p)))
13778 (let* ((struct (org-list-struct))
13779 (prevs (org-list-prevs-alist struct))
13780 (regexp
13781 (concat "[ \t]*- +"
13782 (replace-regexp-in-string
13783 " +" " +"
13784 (org-replace-escapes
13785 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13786 `(("%d" . ,org-ts-regexp-inactive)
13787 ("%D" . ,org-ts-regexp)
13788 ("%s" . "\"\\S-+\"")
13789 ("%S" . "\"\\S-+\"")
13790 ("%t" . ,org-ts-regexp-inactive)
13791 ("%T" . ,org-ts-regexp)
13792 ("%u" . ".*?")
13793 ("%U" . ".*?")))))))
13794 (while (looking-at-p regexp)
13795 (goto-char (or (org-list-get-next-item (point) struct prevs)
13796 (org-list-get-item-end (point) struct)))))))
13798 (defun org-add-log-note (&optional _purpose)
13799 "Pop up a window for taking a note, and add this note later."
13800 (remove-hook 'post-command-hook 'org-add-log-note)
13801 (setq org-log-note-window-configuration (current-window-configuration))
13802 (delete-other-windows)
13803 (move-marker org-log-note-return-to (point))
13804 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13805 (goto-char org-log-note-marker)
13806 (org-switch-to-buffer-other-window "*Org Note*")
13807 (erase-buffer)
13808 (if (memq org-log-note-how '(time state))
13809 (let (current-prefix-arg) (org-store-log-note))
13810 (let ((org-inhibit-startup t)) (org-mode))
13811 (insert (format "# Insert note for %s.
13812 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13813 (cond
13814 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13815 ((eq org-log-note-purpose 'done) "closed todo item")
13816 ((eq org-log-note-purpose 'state)
13817 (format "state change from \"%s\" to \"%s\""
13818 (or org-log-note-previous-state "")
13819 (or org-log-note-state "")))
13820 ((eq org-log-note-purpose 'reschedule)
13821 "rescheduling")
13822 ((eq org-log-note-purpose 'delschedule)
13823 "no longer scheduled")
13824 ((eq org-log-note-purpose 'redeadline)
13825 "changing deadline")
13826 ((eq org-log-note-purpose 'deldeadline)
13827 "removing deadline")
13828 ((eq org-log-note-purpose 'refile)
13829 "refiling")
13830 ((eq org-log-note-purpose 'note)
13831 "this entry")
13832 (t (error "This should not happen")))))
13833 (when org-log-note-extra (insert org-log-note-extra))
13834 (setq-local org-finish-function 'org-store-log-note)
13835 (run-hooks 'org-log-buffer-setup-hook)))
13837 (defvar org-note-abort nil) ; dynamically scoped
13838 (defun org-store-log-note ()
13839 "Finish taking a log note, and insert it to where it belongs."
13840 (let ((txt (prog1 (buffer-string)
13841 (kill-buffer)))
13842 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13843 lines)
13844 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13845 (setq txt (replace-match "" t t txt)))
13846 (when (string-match "\\s-+\\'" txt)
13847 (setq txt (replace-match "" t t txt)))
13848 (setq lines (org-split-string txt "\n"))
13849 (when (org-string-nw-p note)
13850 (setq note
13851 (org-replace-escapes
13852 note
13853 (list (cons "%u" (user-login-name))
13854 (cons "%U" user-full-name)
13855 (cons "%t" (format-time-string
13856 (org-time-stamp-format 'long 'inactive)
13857 org-log-note-effective-time))
13858 (cons "%T" (format-time-string
13859 (org-time-stamp-format 'long nil)
13860 org-log-note-effective-time))
13861 (cons "%d" (format-time-string
13862 (org-time-stamp-format nil 'inactive)
13863 org-log-note-effective-time))
13864 (cons "%D" (format-time-string
13865 (org-time-stamp-format nil nil)
13866 org-log-note-effective-time))
13867 (cons "%s" (cond
13868 ((not org-log-note-state) "")
13869 ((string-match-p org-ts-regexp
13870 org-log-note-state)
13871 (format "\"[%s]\""
13872 (substring org-log-note-state 1 -1)))
13873 (t (format "\"%s\"" org-log-note-state))))
13874 (cons "%S"
13875 (cond
13876 ((not org-log-note-previous-state) "")
13877 ((string-match-p org-ts-regexp
13878 org-log-note-previous-state)
13879 (format "\"[%s]\""
13880 (substring
13881 org-log-note-previous-state 1 -1)))
13882 (t (format "\"%s\""
13883 org-log-note-previous-state)))))))
13884 (when lines (setq note (concat note " \\\\")))
13885 (push note lines))
13886 (when (and lines (not (or current-prefix-arg org-note-abort)))
13887 (with-current-buffer (marker-buffer org-log-note-marker)
13888 (org-with-wide-buffer
13889 ;; Find location for the new note.
13890 (goto-char org-log-note-marker)
13891 (set-marker org-log-note-marker nil)
13892 (goto-char (org-log-beginning t))
13893 ;; Make sure point is at the beginning of an empty line.
13894 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13895 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13896 ;; In an existing list, add a new item at the top level.
13897 ;; Otherwise, indent line like a regular one.
13898 (let ((itemp (org-in-item-p)))
13899 (if itemp
13900 (indent-line-to
13901 (let ((struct (save-excursion
13902 (goto-char itemp) (org-list-struct))))
13903 (org-list-get-ind (org-list-get-top-point struct) struct)))
13904 (org-indent-line)))
13905 (insert (org-list-bullet-string "-") (pop lines))
13906 (let ((ind (org-list-item-body-column (line-beginning-position))))
13907 (dolist (line lines)
13908 (insert "\n")
13909 (indent-line-to ind)
13910 (insert line)))
13911 (message "Note stored")
13912 (org-back-to-heading t)
13913 (org-cycle-hide-drawers 'children))
13914 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13915 ;; from within `org-add-log-note' because `buffer-undo-list'
13916 ;; is then modified outside of `org-with-remote-undo'.
13917 (when (eq this-command 'org-agenda-todo)
13918 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13919 ;; Don't add undo information when called from `org-agenda-todo'.
13920 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13921 (set-window-configuration org-log-note-window-configuration)
13922 (with-current-buffer (marker-buffer org-log-note-return-to)
13923 (goto-char org-log-note-return-to))
13924 (move-marker org-log-note-return-to nil)
13925 (when org-log-post-message (message "%s" org-log-post-message))))
13927 (defun org-remove-empty-drawer-at (pos)
13928 "Remove an empty drawer at position POS.
13929 POS may also be a marker."
13930 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13931 (org-with-wide-buffer
13932 (goto-char pos)
13933 (let ((drawer (org-element-at-point)))
13934 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13935 (not (org-element-property :contents-begin drawer)))
13936 (delete-region (org-element-property :begin drawer)
13937 (progn (goto-char (org-element-property :end drawer))
13938 (skip-chars-backward " \r\t\n")
13939 (forward-line)
13940 (point))))))))
13942 (defvar org-ts-type nil)
13943 (defun org-sparse-tree (&optional arg type)
13944 "Create a sparse tree, prompt for the details.
13945 This command can create sparse trees. You first need to select the type
13946 of match used to create the tree:
13948 t Show all TODO entries.
13949 T Show entries with a specific TODO keyword.
13950 m Show entries selected by a tags/property match.
13951 p Enter a property name and its value (both with completion on existing
13952 names/values) and show entries with that property.
13953 r Show entries matching a regular expression (`/' can be used as well).
13954 b Show deadlines and scheduled items before a date.
13955 a Show deadlines and scheduled items after a date.
13956 d Show deadlines due within `org-deadline-warning-days'.
13957 D Show deadlines and scheduled items between a date range."
13958 (interactive "P")
13959 (setq type (or type org-sparse-tree-default-date-type))
13960 (setq org-ts-type type)
13961 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13962 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13963 \[c]ycle through date types: %s"
13964 (cl-case type
13965 (all "all timestamps")
13966 (scheduled "only scheduled")
13967 (deadline "only deadline")
13968 (active "only active timestamps")
13969 (inactive "only inactive timestamps")
13970 (closed "with a closed time-stamp")
13971 (otherwise "scheduled/deadline")))
13972 (let ((answer (read-char-exclusive)))
13973 (cl-case answer
13975 (org-sparse-tree
13977 (cadr
13978 (memq type '(nil all scheduled deadline active inactive closed)))))
13979 (?d (call-interactively 'org-check-deadlines))
13980 (?b (call-interactively 'org-check-before-date))
13981 (?a (call-interactively 'org-check-after-date))
13982 (?D (call-interactively 'org-check-dates-range))
13983 (?t (call-interactively 'org-show-todo-tree))
13984 (?T (org-show-todo-tree '(4)))
13985 (?m (call-interactively 'org-match-sparse-tree))
13986 ((?p ?P)
13987 (let* ((kwd (completing-read
13988 "Property: " (mapcar #'list (org-buffer-property-keys))))
13989 (value (completing-read
13990 "Value: " (mapcar #'list (org-property-values kwd)))))
13991 (unless (string-match "\\`{.*}\\'" value)
13992 (setq value (concat "\"" value "\"")))
13993 (org-match-sparse-tree arg (concat kwd "=" value))))
13994 ((?r ?R ?/) (call-interactively 'org-occur))
13995 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13997 (defvar-local org-occur-highlights nil
13998 "List of overlays used for occur matches.")
13999 (defvar-local org-occur-parameters nil
14000 "Parameters of the active org-occur calls.
14001 This is a list, each call to org-occur pushes as cons cell,
14002 containing the regular expression and the callback, onto the list.
14003 The list can contain several entries if `org-occur' has been called
14004 several time with the KEEP-PREVIOUS argument. Otherwise, this list
14005 will only contain one set of parameters. When the highlights are
14006 removed (for example with `C-c C-c', or with the next edit (depending
14007 on `org-remove-highlights-with-change'), this variable is emptied
14008 as well.")
14010 (defun org-occur (regexp &optional keep-previous callback)
14011 "Make a compact tree which shows all matches of REGEXP.
14013 The tree will show the lines where the regexp matches, and any other context
14014 defined in `org-show-context-detail', which see.
14016 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
14017 done by a previous call to `org-occur' will be kept, to allow stacking of
14018 calls to this command.
14020 Optional argument CALLBACK can be a function of no argument. In this case,
14021 it is called with point at the end of the match, match data being set
14022 accordingly. Current match is shown only if the return value is non-nil.
14023 The function must neither move point nor alter narrowing."
14024 (interactive "sRegexp: \nP")
14025 (when (equal regexp "")
14026 (user-error "Regexp cannot be empty"))
14027 (unless keep-previous
14028 (org-remove-occur-highlights nil nil t))
14029 (push (cons regexp callback) org-occur-parameters)
14030 (let ((cnt 0))
14031 (save-excursion
14032 (goto-char (point-min))
14033 (when (or (not keep-previous) ; do not want to keep
14034 (not org-occur-highlights)) ; no previous matches
14035 ;; hide everything
14036 (org-overview))
14037 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
14038 (isearch-no-upper-case-p regexp t)
14039 org-occur-case-fold-search)))
14040 (while (re-search-forward regexp nil t)
14041 (when (or (not callback)
14042 (save-match-data (funcall callback)))
14043 (setq cnt (1+ cnt))
14044 (when org-highlight-sparse-tree-matches
14045 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14046 (org-show-context 'occur-tree)))))
14047 (when org-remove-highlights-with-change
14048 (add-hook 'before-change-functions 'org-remove-occur-highlights
14049 nil 'local))
14050 (unless org-sparse-tree-open-archived-trees
14051 (org-hide-archived-subtrees (point-min) (point-max)))
14052 (run-hooks 'org-occur-hook)
14053 (when (called-interactively-p 'interactive)
14054 (message "%d match(es) for regexp %s" cnt regexp))
14055 cnt))
14057 (defun org-occur-next-match (&optional n _reset)
14058 "Function for `next-error-function' to find sparse tree matches.
14059 N is the number of matches to move, when negative move backwards.
14060 This function always goes back to the starting point when no
14061 match is found."
14062 (let* ((limit (if (< n 0) (point-min) (point-max)))
14063 (search-func (if (< n 0)
14064 'previous-single-char-property-change
14065 'next-single-char-property-change))
14066 (n (abs n))
14067 (pos (point))
14069 (catch 'exit
14070 (while (setq p1 (funcall search-func (point) 'org-type))
14071 (when (equal p1 limit)
14072 (goto-char pos)
14073 (user-error "No more matches"))
14074 (when (equal (get-char-property p1 'org-type) 'org-occur)
14075 (setq n (1- n))
14076 (when (= n 0)
14077 (goto-char p1)
14078 (throw 'exit (point))))
14079 (goto-char p1))
14080 (goto-char p1)
14081 (user-error "No more matches"))))
14083 (defun org-show-context (&optional key)
14084 "Make sure point and context are visible.
14085 Optional argument KEY, when non-nil, is a symbol. See
14086 `org-show-context-detail' for allowed values and how much is to
14087 be shown."
14088 (org-show-set-visibility
14089 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14090 ((cdr (assq key org-show-context-detail)))
14091 (t (cdr (assq 'default org-show-context-detail))))))
14093 (defun org-show-set-visibility (detail)
14094 "Set visibility around point according to DETAIL.
14095 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14096 `tree', `canonical' or t. See `org-show-context-detail' for more
14097 information."
14098 ;; Show current heading and possibly its entry, following headline
14099 ;; or all children.
14100 (if (and (org-at-heading-p) (not (eq detail 'local)))
14101 (org-flag-heading nil)
14102 (org-show-entry)
14103 ;; If point is hidden within a drawer or a block, make sure to
14104 ;; expose it.
14105 (dolist (o (overlays-at (point)))
14106 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14107 (delete-overlay o)))
14108 (unless (org-before-first-heading-p)
14109 (org-with-limited-levels
14110 (cl-case detail
14111 ((tree canonical t) (org-show-children))
14112 ((nil minimal ancestors))
14113 (t (save-excursion
14114 (outline-next-heading)
14115 (org-flag-heading nil)))))))
14116 ;; Show all siblings.
14117 (when (eq detail 'lineage) (org-show-siblings))
14118 ;; Show ancestors, possibly with their children.
14119 (when (memq detail '(ancestors lineage tree canonical t))
14120 (save-excursion
14121 (while (org-up-heading-safe)
14122 (org-flag-heading nil)
14123 (when (memq detail '(canonical t)) (org-show-entry))
14124 (when (memq detail '(tree canonical t)) (org-show-children))))))
14126 (defvar org-reveal-start-hook nil
14127 "Hook run before revealing a location.")
14129 (defun org-reveal (&optional siblings)
14130 "Show current entry, hierarchy above it, and the following headline.
14132 This can be used to show a consistent set of context around
14133 locations exposed with `org-show-context'.
14135 With optional argument SIBLINGS, on each level of the hierarchy all
14136 siblings are shown. This repairs the tree structure to what it would
14137 look like when opened with hierarchical calls to `org-cycle'.
14139 With a \\[universal-argument] \\[universal-argument] prefix, \
14140 go to the parent and show the entire tree."
14141 (interactive "P")
14142 (run-hooks 'org-reveal-start-hook)
14143 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14144 ((equal siblings '(16))
14145 (save-excursion
14146 (when (org-up-heading-safe)
14147 (org-show-subtree)
14148 (run-hook-with-args 'org-cycle-hook 'subtree))))
14149 (t (org-show-set-visibility 'lineage))))
14151 (defun org-highlight-new-match (beg end)
14152 "Highlight from BEG to END and mark the highlight is an occur headline."
14153 (let ((ov (make-overlay beg end)))
14154 (overlay-put ov 'face 'secondary-selection)
14155 (overlay-put ov 'org-type 'org-occur)
14156 (push ov org-occur-highlights)))
14158 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14159 "Remove the occur highlights from the buffer.
14160 BEG and END are ignored. If NOREMOVE is nil, remove this function
14161 from the `before-change-functions' in the current buffer."
14162 (interactive)
14163 (unless org-inhibit-highlight-removal
14164 (mapc #'delete-overlay org-occur-highlights)
14165 (setq org-occur-highlights nil)
14166 (setq org-occur-parameters nil)
14167 (unless noremove
14168 (remove-hook 'before-change-functions
14169 'org-remove-occur-highlights 'local))))
14171 ;;;; Priorities
14173 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14174 "Regular expression matching the priority indicator.")
14176 (defvar org-remove-priority-next-time nil)
14178 (defun org-priority-up ()
14179 "Increase the priority of the current item."
14180 (interactive)
14181 (org-priority 'up))
14183 (defun org-priority-down ()
14184 "Decrease the priority of the current item."
14185 (interactive)
14186 (org-priority 'down))
14188 (defun org-priority (&optional action _show)
14189 "Change the priority of an item.
14190 ACTION can be `set', `up', `down', or a character."
14191 (interactive "P")
14192 (if (equal action '(4))
14193 (org-show-priority)
14194 (unless org-enable-priority-commands
14195 (user-error "Priority commands are disabled"))
14196 (setq action (or action 'set))
14197 (let (current new news have remove)
14198 (save-excursion
14199 (org-back-to-heading t)
14200 (when (looking-at org-priority-regexp)
14201 (setq current (string-to-char (match-string 2))
14202 have t))
14203 (cond
14204 ((eq action 'remove)
14205 (setq remove t new ?\ ))
14206 ((or (eq action 'set)
14207 (integerp action))
14208 (if (not (eq action 'set))
14209 (setq new action)
14210 (message "Priority %c-%c, SPC to remove: "
14211 org-highest-priority org-lowest-priority)
14212 (save-match-data
14213 (setq new (read-char-exclusive))))
14214 (when (and (= (upcase org-highest-priority) org-highest-priority)
14215 (= (upcase org-lowest-priority) org-lowest-priority))
14216 (setq new (upcase new)))
14217 (cond ((equal new ?\ ) (setq remove t))
14218 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14219 (user-error "Priority must be between `%c' and `%c'"
14220 org-highest-priority org-lowest-priority))))
14221 ((eq action 'up)
14222 (setq new (if have
14223 (1- current) ; normal cycling
14224 ;; last priority was empty
14225 (if (eq last-command this-command)
14226 org-lowest-priority ; wrap around empty to lowest
14227 ;; default
14228 (if org-priority-start-cycle-with-default
14229 org-default-priority
14230 (1- org-default-priority))))))
14231 ((eq action 'down)
14232 (setq new (if have
14233 (1+ current) ; normal cycling
14234 ;; last priority was empty
14235 (if (eq last-command this-command)
14236 org-highest-priority ; wrap around empty to highest
14237 ;; default
14238 (if org-priority-start-cycle-with-default
14239 org-default-priority
14240 (1+ org-default-priority))))))
14241 (t (user-error "Invalid action")))
14242 (when (or (< (upcase new) org-highest-priority)
14243 (> (upcase new) org-lowest-priority))
14244 (if (and (memq action '(up down))
14245 (not have) (not (eq last-command this-command)))
14246 ;; `new' is from default priority
14247 (error
14248 "The default can not be set, see `org-default-priority' why")
14249 ;; normal cycling: `new' is beyond highest/lowest priority
14250 ;; and is wrapped around to the empty priority
14251 (setq remove t)))
14252 (setq news (format "%c" new))
14253 (if have
14254 (if remove
14255 (replace-match "" t t nil 1)
14256 (replace-match news t t nil 2))
14257 (if remove
14258 (user-error "No priority cookie found in line")
14259 (let ((case-fold-search nil))
14260 (looking-at org-todo-line-regexp))
14261 (if (match-end 2)
14262 (progn
14263 (goto-char (match-end 2))
14264 (insert " [#" news "]"))
14265 (goto-char (match-beginning 3))
14266 (insert "[#" news "] "))))
14267 (org-set-tags nil 'align))
14268 (if remove
14269 (message "Priority removed")
14270 (message "Priority of current item set to %s" news)))))
14272 (defun org-show-priority ()
14273 "Show the priority of the current item.
14274 This priority is composed of the main priority given with the [#A] cookies,
14275 and by additional input from the age of a schedules or deadline entry."
14276 (interactive)
14277 (let ((pri (if (eq major-mode 'org-agenda-mode)
14278 (org-get-at-bol 'priority)
14279 (save-excursion
14280 (save-match-data
14281 (beginning-of-line)
14282 (and (looking-at org-heading-regexp)
14283 (org-get-priority (match-string 0))))))))
14284 (message "Priority is %d" (if pri pri -1000))))
14286 (defun org-get-priority (s)
14287 "Find priority cookie and return priority."
14288 (save-match-data
14289 (if (functionp org-get-priority-function)
14290 (funcall org-get-priority-function)
14291 (if (not (string-match org-priority-regexp s))
14292 (* 1000 (- org-lowest-priority org-default-priority))
14293 (* 1000 (- org-lowest-priority
14294 (string-to-char (match-string 2 s))))))))
14296 ;;;; Tags
14298 (defvar org-agenda-archives-mode)
14299 (defvar org-map-continue-from nil
14300 "Position from where mapping should continue.
14301 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14303 (defvar org-scanner-tags nil
14304 "The current tag list while the tags scanner is running.")
14306 (defvar org-trust-scanner-tags nil
14307 "Should `org-get-tags-at' use the tags for the scanner.
14308 This is for internal dynamical scoping only.
14309 When this is non-nil, the function `org-get-tags-at' will return the value
14310 of `org-scanner-tags' instead of building the list by itself. This
14311 can lead to large speed-ups when the tags scanner is used in a file with
14312 many entries, and when the list of tags is retrieved, for example to
14313 obtain a list of properties. Building the tags list for each entry in such
14314 a file becomes an N^2 operation - but with this variable set, it scales
14315 as N.")
14317 (defvar org--matcher-tags-todo-only nil)
14319 (defun org-scan-tags (action matcher todo-only &optional start-level)
14320 "Scan headline tags with inheritance and produce output ACTION.
14322 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14323 or `agenda' to produce an entry list for an agenda view. It can also be
14324 a Lisp form or a function that should be called at each matched headline, in
14325 this case the return value is a list of all return values from these calls.
14327 MATCHER is a function accepting three arguments, returning
14328 a non-nil value whenever a given set of tags qualifies a headline
14329 for inclusion. See `org-make-tags-matcher' for more information.
14330 As a special case, it can also be set to t (respectively nil) in
14331 order to match all (respectively none) headline.
14333 When TODO-ONLY is non-nil, only lines with a not-done TODO
14334 keyword are included in the output.
14336 START-LEVEL can be a string with asterisks, reducing the scope to
14337 headlines matching this string."
14338 (require 'org-agenda)
14339 (let* ((re (concat "^"
14340 (if start-level
14341 ;; Get the correct level to match
14342 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14343 org-outline-regexp)
14344 " *\\(\\<\\("
14345 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14346 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14347 (props (list 'face 'default
14348 'done-face 'org-agenda-done
14349 'undone-face 'default
14350 'mouse-face 'highlight
14351 'org-not-done-regexp org-not-done-regexp
14352 'org-todo-regexp org-todo-regexp
14353 'org-complex-heading-regexp org-complex-heading-regexp
14354 'help-echo
14355 (format "mouse-2 or RET jump to org file %s"
14356 (abbreviate-file-name
14357 (or (buffer-file-name (buffer-base-buffer))
14358 (buffer-name (buffer-base-buffer)))))))
14359 (org-map-continue-from nil)
14360 lspos tags tags-list
14361 (tags-alist (list (cons 0 org-file-tags)))
14362 (llast 0) rtn rtn1 level category i txt
14363 todo marker entry priority
14364 ts-date ts-date-type ts-date-pair)
14365 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14366 (setq action (list 'lambda nil action)))
14367 (save-excursion
14368 (goto-char (point-min))
14369 (when (eq action 'sparse-tree)
14370 (org-overview)
14371 (org-remove-occur-highlights))
14372 (while (let (case-fold-search)
14373 (re-search-forward re nil t))
14374 (setq org-map-continue-from nil)
14375 (catch :skip
14376 (setq todo
14377 ;; TODO: is the 1-2 difference a bug?
14378 (when (match-end 1) (match-string-no-properties 2))
14379 tags (when (match-end 4) (match-string-no-properties 4)))
14380 (goto-char (setq lspos (match-beginning 0)))
14381 (setq level (org-reduced-level (org-outline-level))
14382 category (org-get-category))
14383 (when (eq action 'agenda)
14384 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14385 ts-date (car ts-date-pair)
14386 ts-date-type (cdr ts-date-pair)))
14387 (setq i llast llast level)
14388 ;; remove tag lists from same and sublevels
14389 (while (>= i level)
14390 (when (setq entry (assoc i tags-alist))
14391 (setq tags-alist (delete entry tags-alist)))
14392 (setq i (1- i)))
14393 ;; add the next tags
14394 (when tags
14395 (setq tags (org-split-string tags ":")
14396 tags-alist
14397 (cons (cons level tags) tags-alist)))
14398 ;; compile tags for current headline
14399 (setq tags-list
14400 (if org-use-tag-inheritance
14401 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14402 tags)
14403 org-scanner-tags tags-list)
14404 (when org-use-tag-inheritance
14405 (setcdr (car tags-alist)
14406 (mapcar (lambda (x)
14407 (setq x (copy-sequence x))
14408 (org-add-prop-inherited x))
14409 (cdar tags-alist))))
14410 (when (and tags org-use-tag-inheritance
14411 (or (not (eq t org-use-tag-inheritance))
14412 org-tags-exclude-from-inheritance))
14413 ;; Selective inheritance, remove uninherited ones.
14414 (setcdr (car tags-alist)
14415 (org-remove-uninherited-tags (cdar tags-alist))))
14416 (when (and
14418 ;; eval matcher only when the todo condition is OK
14419 (and (or (not todo-only) (member todo org-not-done-keywords))
14420 (if (functionp matcher)
14421 (let ((case-fold-search t) (org-trust-scanner-tags t))
14422 (funcall matcher todo tags-list level))
14423 matcher))
14425 ;; Call the skipper, but return t if it does not
14426 ;; skip, so that the `and' form continues evaluating.
14427 (progn
14428 (unless (eq action 'sparse-tree) (org-agenda-skip))
14431 ;; Check if timestamps are deselecting this entry
14432 (or (not todo-only)
14433 (and (member todo org-not-done-keywords)
14434 (or (not org-agenda-tags-todo-honor-ignore-options)
14435 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14437 ;; select this headline
14438 (cond
14439 ((eq action 'sparse-tree)
14440 (and org-highlight-sparse-tree-matches
14441 (org-get-heading) (match-end 0)
14442 (org-highlight-new-match
14443 (match-beginning 1) (match-end 1)))
14444 (org-show-context 'tags-tree))
14445 ((eq action 'agenda)
14446 (setq txt (org-agenda-format-item
14448 (concat
14449 (if (eq org-tags-match-list-sublevels 'indented)
14450 (make-string (1- level) ?.) "")
14451 (org-get-heading))
14452 (make-string level ?\s)
14453 category
14454 tags-list)
14455 priority (org-get-priority txt))
14456 (goto-char lspos)
14457 (setq marker (org-agenda-new-marker))
14458 (org-add-props txt props
14459 'org-marker marker 'org-hd-marker marker 'org-category category
14460 'todo-state todo
14461 'ts-date ts-date
14462 'priority priority
14463 'type (concat "tagsmatch" ts-date-type))
14464 (push txt rtn))
14465 ((functionp action)
14466 (setq org-map-continue-from nil)
14467 (save-excursion
14468 (setq rtn1 (funcall action))
14469 (push rtn1 rtn)))
14470 (t (user-error "Invalid action")))
14472 ;; if we are to skip sublevels, jump to end of subtree
14473 (unless org-tags-match-list-sublevels
14474 (org-end-of-subtree t)
14475 (backward-char 1))))
14476 ;; Get the correct position from where to continue
14477 (if org-map-continue-from
14478 (goto-char org-map-continue-from)
14479 (and (= (point) lspos) (end-of-line 1)))))
14480 (when (and (eq action 'sparse-tree)
14481 (not org-sparse-tree-open-archived-trees))
14482 (org-hide-archived-subtrees (point-min) (point-max)))
14483 (nreverse rtn)))
14485 (defun org-remove-uninherited-tags (tags)
14486 "Remove all tags that are not inherited from the list TAGS."
14487 (cond
14488 ((eq org-use-tag-inheritance t)
14489 (if org-tags-exclude-from-inheritance
14490 (org-delete-all org-tags-exclude-from-inheritance tags)
14491 tags))
14492 ((not org-use-tag-inheritance) nil)
14493 ((stringp org-use-tag-inheritance)
14494 (delq nil (mapcar
14495 (lambda (x)
14496 (if (and (string-match org-use-tag-inheritance x)
14497 (not (member x org-tags-exclude-from-inheritance)))
14498 x nil))
14499 tags)))
14500 ((listp org-use-tag-inheritance)
14501 (delq nil (mapcar
14502 (lambda (x)
14503 (if (member x org-use-tag-inheritance) x nil))
14504 tags)))))
14506 (defun org-match-sparse-tree (&optional todo-only match)
14507 "Create a sparse tree according to tags string MATCH.
14508 MATCH can contain positive and negative selection of tags, like
14509 \"+WORK+URGENT-WITHBOSS\".
14510 If optional argument TODO-ONLY is non-nil, only select lines that are
14511 also TODO lines."
14512 (interactive "P")
14513 (org-agenda-prepare-buffers (list (current-buffer)))
14514 (let ((org--matcher-tags-todo-only todo-only))
14515 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14516 org--matcher-tags-todo-only)))
14518 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14520 (defvar org-cached-props nil)
14521 (defun org-cached-entry-get (pom property)
14522 (if (or (eq t org-use-property-inheritance)
14523 (and (stringp org-use-property-inheritance)
14524 (let ((case-fold-search t))
14525 (string-match-p org-use-property-inheritance property)))
14526 (and (listp org-use-property-inheritance)
14527 (member-ignore-case property org-use-property-inheritance)))
14528 ;; Caching is not possible, check it directly.
14529 (org-entry-get pom property 'inherit)
14530 ;; Get all properties, so we can do complicated checks easily.
14531 (cdr (assoc-string property
14532 (or org-cached-props
14533 (setq org-cached-props (org-entry-properties pom)))
14534 t))))
14536 (defun org-global-tags-completion-table (&optional files)
14537 "Return the list of all tags in all agenda buffer/files.
14538 Optional FILES argument is a list of files which can be used
14539 instead of the agenda files."
14540 (save-excursion
14541 (org-uniquify
14542 (delq nil
14543 (apply #'append
14544 (mapcar
14545 (lambda (file)
14546 (set-buffer (find-file-noselect file))
14547 (mapcar (lambda (x)
14548 (and (stringp (car-safe x))
14549 (list (car-safe x))))
14550 (or org-current-tag-alist (org-get-buffer-tags))))
14551 (if (car-safe files) files
14552 (org-agenda-files))))))))
14554 (defun org-make-tags-matcher (match)
14555 "Create the TAGS/TODO matcher form for the selection string MATCH.
14557 Returns a cons of the selection string MATCH and a function
14558 implementing the matcher.
14560 The matcher is to be called at an Org entry, with point on the
14561 headline, and returns non-nil if the entry matches the selection
14562 string MATCH. It must be called with three arguments: the TODO
14563 keyword at the entry (or nil if none), the list of all tags at
14564 the entry including inherited ones and the reduced level of the
14565 headline. Additionally, the category of the entry, if any, must
14566 be specified as the text property `org-category' on the headline.
14568 This function sets the variable `org--matcher-tags-todo-only' to
14569 a non-nil value if the matcher restricts matching to TODO
14570 entries, otherwise it is not touched.
14572 See also `org-scan-tags'."
14573 (unless match
14574 ;; Get a new match request, with completion against the global
14575 ;; tags table and the local tags in current buffer.
14576 (let ((org-last-tags-completion-table
14577 (org-uniquify
14578 (delq nil (append (org-get-buffer-tags)
14579 (org-global-tags-completion-table))))))
14580 (setq match
14581 (completing-read
14582 "Match: "
14583 'org-tags-completion-function nil nil nil 'org-tags-history))))
14585 (let ((match0 match)
14586 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14587 (start 0)
14588 tagsmatch todomatch tagsmatcher todomatcher)
14590 ;; Expand group tags.
14591 (setq match (org-tags-expand match))
14593 ;; Check if there is a TODO part of this match, which would be the
14594 ;; part after a "/". To make sure that this slash is not part of
14595 ;; a property value to be matched against, we also check that
14596 ;; there is no / after that slash. First, find the last slash.
14597 (let ((s 0))
14598 (while (string-match "/+" match s)
14599 (setq start (match-beginning 0))
14600 (setq s (match-end 0))))
14601 (if (and (string-match "/+" match start)
14602 (not (string-match-p "\"" match start)))
14603 ;; Match contains also a TODO-matching request.
14604 (progn
14605 (setq tagsmatch (substring match 0 (match-beginning 0)))
14606 (setq todomatch (substring match (match-end 0)))
14607 (when (string-prefix-p "!" todomatch)
14608 (setq org--matcher-tags-todo-only t)
14609 (setq todomatch (substring todomatch 1)))
14610 (when (string-match "\\`\\s-*\\'" todomatch)
14611 (setq todomatch nil)))
14612 ;; Only matching tags.
14613 (setq tagsmatch match)
14614 (setq todomatch nil))
14616 ;; Make the tags matcher.
14617 (when (org-string-nw-p tagsmatch)
14618 (let ((orlist nil)
14619 (orterms (org-split-string tagsmatch "|"))
14620 term)
14621 (while (setq term (pop orterms))
14622 (while (and (equal (substring term -1) "\\") orterms)
14623 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14624 (while (string-match re term)
14625 (let* ((rest (substring term (match-end 0)))
14626 (minus (and (match-end 1)
14627 (equal (match-string 1 term) "-")))
14628 (tag (save-match-data
14629 (replace-regexp-in-string
14630 "\\\\-" "-" (match-string 2 term))))
14631 (regexp (eq (string-to-char tag) ?{))
14632 (levelp (match-end 4))
14633 (propp (match-end 5))
14635 (cond
14636 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14637 (levelp
14638 `(,(org-op-to-function (match-string 3 term))
14639 level
14640 ,(string-to-number (match-string 4 term))))
14641 (propp
14642 (let* ((gv (pcase (upcase (match-string 5 term))
14643 ("CATEGORY"
14644 '(get-text-property (point) 'org-category))
14645 ("TODO" 'todo)
14646 (p `(org-cached-entry-get nil ,p))))
14647 (pv (match-string 7 term))
14648 (regexp (eq (string-to-char pv) ?{))
14649 (strp (eq (string-to-char pv) ?\"))
14650 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14651 (po (org-op-to-function (match-string 6 term)
14652 (if timep 'time strp))))
14653 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14654 (when timep (setq pv (org-matcher-time pv)))
14655 (cond ((and regexp (eq po 'org<>))
14656 `(not (string-match ,pv (or ,gv ""))))
14657 (regexp `(string-match ,pv (or ,gv "")))
14658 (strp `(,po (or ,gv "") ,pv))
14660 `(,po
14661 (string-to-number (or ,gv ""))
14662 ,(string-to-number pv))))))
14663 (t `(member ,tag tags-list)))))
14664 (push (if minus `(not ,mm) mm) tagsmatcher)
14665 (setq term rest)))
14666 (push `(and ,@tagsmatcher) orlist)
14667 (setq tagsmatcher nil))
14668 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14670 ;; Make the TODO matcher.
14671 (when (org-string-nw-p todomatch)
14672 (let ((orlist nil))
14673 (dolist (term (org-split-string todomatch "|"))
14674 (while (string-match re term)
14675 (let* ((minus (and (match-end 1)
14676 (equal (match-string 1 term) "-")))
14677 (kwd (match-string 2 term))
14678 (regexp (eq (string-to-char kwd) ?{))
14679 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14680 `(equal todo ,kwd))))
14681 (push (if minus `(not ,mm) mm) todomatcher))
14682 (setq term (substring term (match-end 0))))
14683 (push (if (> (length todomatcher) 1)
14684 (cons 'and todomatcher)
14685 (car todomatcher))
14686 orlist)
14687 (setq todomatcher nil))
14688 (setq todomatcher (cons 'or orlist))))
14690 ;; Return the string and function of the matcher. If no
14691 ;; tags-specific or todo-specific matcher exists, match
14692 ;; everything.
14693 (let ((matcher (if (and tagsmatcher todomatcher)
14694 `(and ,tagsmatcher ,todomatcher)
14695 (or tagsmatcher todomatcher t))))
14696 (when org--matcher-tags-todo-only
14697 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14698 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14700 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14701 "Expand group tags in MATCH.
14703 This replaces every group tag in MATCH with a regexp tag search.
14704 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14705 will be replaced like this:
14707 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14708 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14709 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14711 Replacing by a regexp preserves the structure of the match.
14712 E.g., this expansion
14714 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14716 will match anything tagged with \"Lab\" and \"Home\", or tagged
14717 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14719 A group tag in MATCH can contain regular expressions of its own.
14720 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14721 will be replaced like this:
14723 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14725 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14726 assumed to be a single group tag, and the function will return
14727 the list of tags in this group.
14729 When DOWNCASE is non-nil, expand downcased TAGS."
14730 (if org-group-tags
14731 (let* ((case-fold-search t)
14732 (stable org-mode-syntax-table)
14733 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14734 (taggroups (if downcased
14735 (mapcar (lambda (tg) (mapcar #'downcase tg))
14736 taggroups)
14737 taggroups))
14738 (taggroups-keys (mapcar #'car taggroups))
14739 (return-match (if downcased (downcase match) match))
14740 (count 0)
14741 (work-already-expanded tags-already-expanded)
14742 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14743 ;; @ and _ are allowed as word-components in tags.
14744 (modify-syntax-entry ?@ "w" stable)
14745 (modify-syntax-entry ?_ "w" stable)
14746 ;; Temporarily replace regexp-expressions in the match-expression.
14747 (while (string-match "{.+?}" return-match)
14748 (cl-incf count)
14749 (push (match-string 0 return-match) regexps-in-match)
14750 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14751 (while (and taggroups-keys
14752 (with-syntax-table stable
14753 (string-match
14754 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14755 (regexp-opt taggroups-keys) "\\>\\)")
14756 return-match)))
14757 (let* ((dir (match-string 1 return-match))
14758 (tag (match-string 2 return-match))
14759 (tag (if downcased (downcase tag) tag)))
14760 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14761 (member tag work-already-expanded))
14762 (setq tags-in-group (assoc tag taggroups))
14763 (push tag work-already-expanded)
14764 ;; Recursively expand each tag in the group, if the tag hasn't
14765 ;; already been expanded. Restore the match-data after all recursive calls.
14766 (save-match-data
14767 (let (tags-expanded)
14768 (dolist (x (cdr tags-in-group))
14769 (if (and (member x taggroups-keys)
14770 (not (member x work-already-expanded)))
14771 (setq tags-expanded
14772 (delete-dups
14773 (append
14774 (org-tags-expand x t downcased
14775 work-already-expanded)
14776 tags-expanded)))
14777 (setq tags-expanded
14778 (append (list x) tags-expanded)))
14779 (setq work-already-expanded
14780 (delete-dups
14781 (append tags-expanded
14782 work-already-expanded))))
14783 (setq tags-in-group
14784 (delete-dups (cons (car tags-in-group)
14785 tags-expanded)))))
14786 ;; Filter tag-regexps from tags.
14787 (setq regexp-in-group-escaped
14788 (delq nil (mapcar (lambda (x)
14789 (if (stringp x)
14790 (and (equal "{" (substring x 0 1))
14791 (equal "}" (substring x -1))
14794 tags-in-group))
14795 regexp-in-group
14796 (mapcar (lambda (x)
14797 (substring x 1 -1))
14798 regexp-in-group-escaped)
14799 tags-in-group
14800 (delq nil (mapcar (lambda (x)
14801 (if (stringp x)
14802 (and (not (equal "{" (substring x 0 1)))
14803 (not (equal "}" (substring x -1)))
14806 tags-in-group)))
14807 ;; If single-as-list, do no more in the while-loop.
14808 (if (not single-as-list)
14809 (progn
14810 (when regexp-in-group
14811 (setq regexp-in-group
14812 (concat "\\|"
14813 (mapconcat 'identity regexp-in-group
14814 "\\|"))))
14815 (setq tags-in-group
14816 (concat dir
14817 "{\\<"
14818 (regexp-opt tags-in-group)
14819 "\\>"
14820 regexp-in-group
14821 "}"))
14822 (when (stringp tags-in-group)
14823 (org-add-props tags-in-group '(grouptag t)))
14824 (setq return-match
14825 (replace-match tags-in-group t t return-match)))
14826 (setq tags-in-group
14827 (append regexp-in-group-escaped tags-in-group))))
14828 (setq taggroups-keys (delete tag taggroups-keys))))
14829 ;; Add the regular expressions back into the match-expression again.
14830 (while regexps-in-match
14831 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14832 (pop regexps-in-match)
14833 return-match t t))
14834 (cl-decf count))
14835 (if single-as-list
14836 (if tags-in-group tags-in-group (list return-match))
14837 return-match))
14838 (if single-as-list
14839 (list (if downcased (downcase match) match))
14840 match)))
14842 (defun org-op-to-function (op &optional stringp)
14843 "Turn an operator into the appropriate function."
14844 (setq op
14845 (cond
14846 ((equal op "<" ) '(< string< org-time<))
14847 ((equal op ">" ) '(> org-string> org-time>))
14848 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14849 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14850 ((member op '("=" "==")) '(= string= org-time=))
14851 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14852 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14854 (defun org<> (a b) (not (= a b)))
14855 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14856 (defun org-string>= (a b) (not (string< a b)))
14857 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14858 (defun org-string<> (a b) (not (string= a b)))
14859 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14860 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14861 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14862 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14863 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14864 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14865 (defun org-2ft (s)
14866 "Convert S to a floating point time.
14867 If S is already a number, just return it. If it is a string, parse
14868 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14869 (cond
14870 ((numberp s) s)
14871 ((stringp s)
14872 (condition-case nil
14873 (float-time (apply 'encode-time (org-parse-time-string s)))
14874 (error 0.)))
14875 (t 0.)))
14877 (defun org-time-today ()
14878 "Time in seconds today at 0:00.
14879 Returns the float number of seconds since the beginning of the
14880 epoch to the beginning of today (00:00)."
14881 (float-time (apply 'encode-time
14882 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14884 (defun org-matcher-time (s)
14885 "Interpret a time comparison value."
14886 (save-match-data
14887 (cond
14888 ((string= s "<now>") (float-time))
14889 ((string= s "<today>") (org-time-today))
14890 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14891 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14892 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14893 (+ (org-time-today)
14894 (* (string-to-number (match-string 1 s))
14895 (cdr (assoc (match-string 2 s)
14896 '(("d" . 86400.0) ("w" . 604800.0)
14897 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14898 (t (org-2ft s)))))
14900 (defun org-match-any-p (re list)
14901 "Does re match any element of list?"
14902 (setq list (mapcar (lambda (x) (string-match re x)) list))
14903 (delq nil list))
14905 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14906 (defvar org-tags-overlay (make-overlay 1 1))
14907 (delete-overlay org-tags-overlay)
14909 (defun org-get-local-tags-at (&optional pos)
14910 "Get a list of tags defined in the current headline."
14911 (org-get-tags-at pos 'local))
14913 (defun org-get-local-tags ()
14914 "Get a list of tags defined in the current headline."
14915 (org-get-tags-at nil 'local))
14917 (defun org-get-tags-at (&optional pos local)
14918 "Get a list of all headline tags applicable at POS.
14919 POS defaults to point. If tags are inherited, the list contains
14920 the targets in the same sequence as the headlines appear, i.e.
14921 the tags of the current headline come last.
14922 When LOCAL is non-nil, only return tags from the current headline,
14923 ignore inherited ones."
14924 (interactive)
14925 (if (and org-trust-scanner-tags
14926 (or (not pos) (equal pos (point)))
14927 (not local))
14928 org-scanner-tags
14929 (let (tags ltags lastpos parent)
14930 (save-excursion
14931 (save-restriction
14932 (widen)
14933 (goto-char (or pos (point)))
14934 (save-match-data
14935 (catch 'done
14936 (condition-case nil
14937 (progn
14938 (org-back-to-heading t)
14939 (while (not (equal lastpos (point)))
14940 (setq lastpos (point))
14941 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14942 (setq ltags (org-split-string
14943 (match-string-no-properties 1) ":"))
14944 (when parent
14945 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14946 (setq tags (append
14947 (if parent
14948 (org-remove-uninherited-tags ltags)
14949 ltags)
14950 tags)))
14951 (or org-use-tag-inheritance (throw 'done t))
14952 (when local (throw 'done t))
14953 (or (org-up-heading-safe) (error nil))
14954 (setq parent t)))
14955 (error nil)))))
14956 (if local
14957 tags
14958 (reverse (delete-dups
14959 (reverse (append
14960 (org-remove-uninherited-tags
14961 org-file-tags)
14962 tags)))))))))
14964 (defun org-add-prop-inherited (s)
14965 (add-text-properties 0 (length s) '(inherited t) s)
14968 (defun org-toggle-tag (tag &optional onoff)
14969 "Toggle the tag TAG for the current line.
14970 If ONOFF is `on' or `off', don't toggle but set to this state."
14971 (let (res current)
14972 (save-excursion
14973 (org-back-to-heading t)
14974 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14975 (point-at-eol) t)
14976 (progn
14977 (setq current (match-string 1))
14978 (replace-match ""))
14979 (setq current ""))
14980 (setq current (nreverse (org-split-string current ":")))
14981 (cond
14982 ((eq onoff 'on)
14983 (setq res t)
14984 (or (member tag current) (push tag current)))
14985 ((eq onoff 'off)
14986 (or (not (member tag current)) (setq current (delete tag current))))
14987 (t (if (member tag current)
14988 (setq current (delete tag current))
14989 (setq res t)
14990 (push tag current))))
14991 (end-of-line 1)
14992 (if current
14993 (progn
14994 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14995 (org-set-tags nil t))
14996 (delete-horizontal-space))
14997 (run-hooks 'org-after-tags-change-hook))
14998 res))
15000 (defun org--align-tags-here (to-col)
15001 "Align tags on the current headline to TO-COL.
15002 Assume point is on a headline."
15003 (let ((pos (point)))
15004 (beginning-of-line)
15005 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15006 (>= pos (match-beginning 2)))
15007 ;; No tags or point within tags: do not align.
15008 (goto-char pos)
15009 (goto-char (match-beginning 1))
15010 (let ((shift (max (- (if (>= to-col 0) to-col
15011 (- (abs to-col) (string-width (match-string 2))))
15012 (current-column))
15013 1)))
15014 (replace-match (make-string shift ?\s) nil nil nil 1)
15015 ;; Preserve initial position, if possible. In any case, stop
15016 ;; before tags.
15017 (when (< pos (point)) (goto-char pos))))))
15019 (defun org-set-tags-command (&optional arg just-align)
15020 "Call the set-tags command for the current entry."
15021 (interactive "P")
15022 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
15023 (org-set-tags arg just-align)
15024 (save-excursion
15025 (unless (and (org-region-active-p)
15026 org-loop-over-headlines-in-active-region)
15027 (org-back-to-heading t))
15028 (org-set-tags arg just-align))))
15030 (defun org-set-tags-to (data)
15031 "Set the tags of the current entry to DATA, replacing the current tags.
15032 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
15033 If DATA is nil or the empty string, any tags will be removed."
15034 (interactive "sTags: ")
15035 (setq data
15036 (cond
15037 ((eq data nil) "")
15038 ((equal data "") "")
15039 ((stringp data)
15040 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
15041 ":"))
15042 ((listp data)
15043 (concat ":" (mapconcat 'identity data ":") ":"))))
15044 (when data
15045 (save-excursion
15046 (org-back-to-heading t)
15047 (when (let ((case-fold-search nil))
15048 (looking-at org-complex-heading-regexp))
15049 (if (match-end 5)
15050 (progn
15051 (goto-char (match-beginning 5))
15052 (insert data)
15053 (delete-region (point) (point-at-eol))
15054 (org-set-tags nil 'align))
15055 (goto-char (point-at-eol))
15056 (insert " " data)
15057 (org-set-tags nil 'align)))
15058 (beginning-of-line 1)
15059 (when (looking-at ".*?\\([ \t]+\\)$")
15060 (delete-region (match-beginning 1) (match-end 1))))))
15062 (defun org-align-all-tags ()
15063 "Align the tags in all headings."
15064 (interactive)
15065 (save-excursion
15066 (or (ignore-errors (org-back-to-heading t))
15067 (outline-next-heading))
15068 (if (org-at-heading-p)
15069 (org-set-tags t)
15070 (message "No headings"))))
15072 (defvar org-indent-indentation-per-level)
15073 (defun org-set-tags (&optional arg just-align)
15074 "Set the tags for the current headline.
15075 With prefix ARG, realign all tags in headings in the current buffer.
15076 When JUST-ALIGN is non-nil, only align tags."
15077 (interactive "P")
15078 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15079 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15080 'region-start-level
15081 'region))
15082 org-loop-over-headlines-in-active-region)
15083 (org-map-entries
15084 ;; We don't use ARG and JUST-ALIGN here because these args
15085 ;; are not useful when looping over headlines.
15086 #'org-set-tags
15087 org-loop-over-headlines-in-active-region
15089 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15090 (let ((org-setting-tags t))
15091 (if arg
15092 (save-excursion
15093 (goto-char (point-min))
15094 (while (re-search-forward org-outline-regexp-bol nil t)
15095 (org-set-tags nil t)
15096 (end-of-line))
15097 (message "All tags realigned to column %d" org-tags-column))
15098 (let* ((current (org-get-tags-string))
15099 (tags
15100 (if just-align current
15101 ;; Get a new set of tags from the user.
15102 (save-excursion
15103 (let* ((seen)
15104 (table
15105 (setq
15106 org-last-tags-completion-table
15107 ;; Uniquify tags in alists, yet preserve
15108 ;; structure (i.e., keywords).
15109 (delq nil
15110 (mapcar
15111 (lambda (pair)
15112 (let ((head (car pair)))
15113 (cond ((symbolp head) pair)
15114 ((member head seen) nil)
15115 (t (push head seen)
15116 pair))))
15117 (append
15118 (or org-current-tag-alist
15119 (org-get-buffer-tags))
15120 (and
15121 org-complete-tags-always-offer-all-agenda-tags
15122 (org-global-tags-completion-table
15123 (org-agenda-files))))))))
15124 (current-tags (org-split-string current ":"))
15125 (inherited-tags
15126 (nreverse (nthcdr (length current-tags)
15127 (nreverse (org-get-tags-at))))))
15128 (replace-regexp-in-string
15129 "\\([-+&]+\\|,\\)"
15131 (if (or (eq t org-use-fast-tag-selection)
15132 (and org-use-fast-tag-selection
15133 (delq nil (mapcar #'cdr table))))
15134 (org-fast-tag-selection
15135 current-tags inherited-tags table
15136 (and org-fast-tag-selection-include-todo
15137 org-todo-key-alist))
15138 (let ((org-add-colon-after-tag-completion
15139 (< 1 (length table))))
15140 (org-trim
15141 (completing-read
15142 "Tags: "
15143 #'org-tags-completion-function
15144 nil nil current 'org-tags-history))))))))))
15146 (when org-tags-sort-function
15147 (setq tags
15148 (mapconcat
15149 #'identity
15150 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15151 org-tags-sort-function)
15152 ":")))
15154 (if (not (org-string-nw-p tags)) (setq tags "")
15155 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
15156 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
15158 ;; Insert new tags at the correct column.
15159 (unless (equal current tags)
15160 (save-excursion
15161 (beginning-of-line)
15162 (let ((case-fold-search nil))
15163 (looking-at org-complex-heading-regexp))
15164 ;; Remove current tags, if any.
15165 (when (match-end 5) (replace-match "" nil nil nil 5))
15166 ;; Insert new tags, if any. Otherwise, remove trailing
15167 ;; white spaces.
15168 (end-of-line)
15169 (if (not (equal tags ""))
15170 (insert " " tags)
15171 (skip-chars-backward " \t")
15172 (delete-region (point) (line-end-position)))))
15173 ;; Align tags, if any. Fix tags column if `org-indent-mode'
15174 ;; is on.
15175 (unless (equal tags "")
15176 (let* ((level (save-excursion
15177 (beginning-of-line)
15178 (skip-chars-forward "\\*")))
15179 (offset (if (bound-and-true-p org-indent-mode)
15180 (* (1- org-indent-indentation-per-level)
15181 (1- level))
15183 (tags-column
15184 (+ org-tags-column
15185 (if (> org-tags-column 0) (- offset) offset))))
15186 (org--align-tags-here tags-column))))
15187 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15189 (defun org-change-tag-in-region (beg end tag off)
15190 "Add or remove TAG for each entry in the region.
15191 This works in the agenda, and also in an Org buffer."
15192 (interactive
15193 (list (region-beginning) (region-end)
15194 (let ((org-last-tags-completion-table
15195 (if (derived-mode-p 'org-mode)
15196 (org-uniquify
15197 (delq nil (append (org-get-buffer-tags)
15198 (org-global-tags-completion-table))))
15199 (org-global-tags-completion-table))))
15200 (completing-read
15201 "Tag: " 'org-tags-completion-function nil nil nil
15202 'org-tags-history))
15203 (progn
15204 (message "[s]et or [r]emove? ")
15205 (equal (read-char-exclusive) ?r))))
15206 (when (fboundp 'deactivate-mark) (deactivate-mark))
15207 (let ((agendap (equal major-mode 'org-agenda-mode))
15208 l1 l2 m buf pos newhead (cnt 0))
15209 (goto-char end)
15210 (setq l2 (1- (org-current-line)))
15211 (goto-char beg)
15212 (setq l1 (org-current-line))
15213 (cl-loop for l from l1 to l2 do
15214 (org-goto-line l)
15215 (setq m (get-text-property (point) 'org-hd-marker))
15216 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15217 (and agendap m))
15218 (setq buf (if agendap (marker-buffer m) (current-buffer))
15219 pos (if agendap m (point)))
15220 (with-current-buffer buf
15221 (save-excursion
15222 (save-restriction
15223 (goto-char pos)
15224 (setq cnt (1+ cnt))
15225 (org-toggle-tag tag (if off 'off 'on))
15226 (setq newhead (org-get-heading)))))
15227 (and agendap (org-agenda-change-all-lines newhead m))))
15228 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15230 (defun org-tags-completion-function (string _predicate &optional flag)
15231 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15232 (confirm (lambda (x) (stringp (car x)))))
15233 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15234 (setq s1 (match-string 1 string)
15235 s2 (match-string 2 string))
15236 (setq s1 "" s2 string))
15237 (cond
15238 ((eq flag nil)
15239 ;; try completion
15240 (setq rtn (try-completion s2 ctable confirm))
15241 (when (stringp rtn)
15242 (setq rtn
15243 (concat s1 s2 (substring rtn (length s2))
15244 (if (and org-add-colon-after-tag-completion
15245 (assoc rtn ctable))
15246 ":" ""))))
15247 rtn)
15248 ((eq flag t)
15249 ;; all-completions
15250 (all-completions s2 ctable confirm))
15251 ((eq flag 'lambda)
15252 ;; exact match?
15253 (assoc s2 ctable)))))
15255 (defun org-fast-tag-insert (kwd tags face &optional end)
15256 "Insert KDW, and the TAGS, the latter with face FACE.
15257 Also insert END."
15258 (insert (format "%-12s" (concat kwd ":"))
15259 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15260 (or end "")))
15262 (defun org-fast-tag-show-exit (flag)
15263 (save-excursion
15264 (org-goto-line 3)
15265 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15266 (replace-match ""))
15267 (when flag
15268 (end-of-line 1)
15269 (org-move-to-column (- (window-width) 19) t)
15270 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15272 (defun org-set-current-tags-overlay (current prefix)
15273 "Add an overlay to CURRENT tag with PREFIX."
15274 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15275 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15276 (org-overlay-display org-tags-overlay (concat prefix s))))
15278 (defvar org-last-tag-selection-key nil)
15279 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15280 "Fast tag selection with single keys.
15281 CURRENT is the current list of tags in the headline, INHERITED is the
15282 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15283 possibly with grouping information. TODO-TABLE is a similar table with
15284 TODO keywords, should these have keys assigned to them.
15285 If the keys are nil, a-z are automatically assigned.
15286 Returns the new tags string, or nil to not change the current settings."
15287 (let* ((fulltable (append table todo-table))
15288 (maxlen (apply 'max (mapcar
15289 (lambda (x)
15290 (if (stringp (car x)) (string-width (car x)) 0))
15291 fulltable)))
15292 (buf (current-buffer))
15293 (expert (eq org-fast-tag-selection-single-key 'expert))
15294 (buffer-tags nil)
15295 (fwidth (+ maxlen 3 1 3))
15296 (ncol (/ (- (window-width) 4) fwidth))
15297 (i-face 'org-done)
15298 (c-face 'org-todo)
15299 tg cnt e c char c1 c2 ntable tbl rtn
15300 ov-start ov-end ov-prefix
15301 (exit-after-next org-fast-tag-selection-single-key)
15302 (done-keywords org-done-keywords)
15303 groups ingroup intaggroup)
15304 (save-excursion
15305 (beginning-of-line 1)
15306 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15307 (setq ov-start (match-beginning 1)
15308 ov-end (match-end 1)
15309 ov-prefix "")
15310 (setq ov-start (1- (point-at-eol))
15311 ov-end (1+ ov-start))
15312 (skip-chars-forward "^\n\r")
15313 (setq ov-prefix
15314 (concat
15315 (buffer-substring (1- (point)) (point))
15316 (if (> (current-column) org-tags-column)
15318 (make-string (- org-tags-column (current-column)) ?\ ))))))
15319 (move-overlay org-tags-overlay ov-start ov-end)
15320 (save-window-excursion
15321 (if expert
15322 (set-buffer (get-buffer-create " *Org tags*"))
15323 (delete-other-windows)
15324 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15325 (org-switch-to-buffer-other-window " *Org tags*"))
15326 (erase-buffer)
15327 (setq-local org-done-keywords done-keywords)
15328 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15329 (org-fast-tag-insert "Current" current c-face "\n\n")
15330 (org-fast-tag-show-exit exit-after-next)
15331 (org-set-current-tags-overlay current ov-prefix)
15332 (setq tbl fulltable char ?a cnt 0)
15333 (while (setq e (pop tbl))
15334 (cond
15335 ((eq (car e) :startgroup)
15336 (push '() groups) (setq ingroup t)
15337 (unless (zerop cnt)
15338 (setq cnt 0)
15339 (insert "\n"))
15340 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15341 ((eq (car e) :endgroup)
15342 (setq ingroup nil cnt 0)
15343 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15344 ((eq (car e) :startgrouptag)
15345 (setq intaggroup t)
15346 (unless (zerop cnt)
15347 (setq cnt 0)
15348 (insert "\n"))
15349 (insert "[ "))
15350 ((eq (car e) :endgrouptag)
15351 (setq intaggroup nil cnt 0)
15352 (insert "]\n"))
15353 ((equal e '(:newline))
15354 (unless (zerop cnt)
15355 (setq cnt 0)
15356 (insert "\n")
15357 (setq e (car tbl))
15358 (while (equal (car tbl) '(:newline))
15359 (insert "\n")
15360 (setq tbl (cdr tbl)))))
15361 ((equal e '(:grouptags)) (insert " : "))
15363 (setq tg (copy-sequence (car e)) c2 nil)
15364 (if (cdr e)
15365 (setq c (cdr e))
15366 ;; automatically assign a character.
15367 (setq c1 (string-to-char
15368 (downcase (substring
15369 tg (if (= (string-to-char tg) ?@) 1 0)))))
15370 (if (or (rassoc c1 ntable) (rassoc c1 table))
15371 (while (or (rassoc char ntable) (rassoc char table))
15372 (setq char (1+ char)))
15373 (setq c2 c1))
15374 (setq c (or c2 char)))
15375 (when ingroup (push tg (car groups)))
15376 (setq tg (org-add-props tg nil 'face
15377 (cond
15378 ((not (assoc tg table))
15379 (org-get-todo-face tg))
15380 ((member tg current) c-face)
15381 ((member tg inherited) i-face))))
15382 (when (equal (caar tbl) :grouptags)
15383 (org-add-props tg nil 'face 'org-tag-group))
15384 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15385 (insert "[" c "] " tg (make-string
15386 (- fwidth 4 (length tg)) ?\ ))
15387 (push (cons tg c) ntable)
15388 (when (= (cl-incf cnt) ncol)
15389 (insert "\n")
15390 (when (or ingroup intaggroup) (insert " "))
15391 (setq cnt 0)))))
15392 (setq ntable (nreverse ntable))
15393 (insert "\n")
15394 (goto-char (point-min))
15395 (unless expert (org-fit-window-to-buffer))
15396 (setq rtn
15397 (catch 'exit
15398 (while t
15399 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15400 (if (not groups) "no " "")
15401 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15402 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15403 (setq org-last-tag-selection-key c)
15404 (cond
15405 ((= c ?\r) (throw 'exit t))
15406 ((= c ?!)
15407 (setq groups (not groups))
15408 (goto-char (point-min))
15409 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15410 ((= c ?\C-c)
15411 (if (not expert)
15412 (org-fast-tag-show-exit
15413 (setq exit-after-next (not exit-after-next)))
15414 (setq expert nil)
15415 (delete-other-windows)
15416 (set-window-buffer (split-window-vertically) " *Org tags*")
15417 (org-switch-to-buffer-other-window " *Org tags*")
15418 (org-fit-window-to-buffer)))
15419 ((or (= c ?\C-g)
15420 (and (= c ?q) (not (rassoc c ntable))))
15421 (delete-overlay org-tags-overlay)
15422 (setq quit-flag t))
15423 ((= c ?\ )
15424 (setq current nil)
15425 (when exit-after-next (setq exit-after-next 'now)))
15426 ((= c ?\t)
15427 (condition-case nil
15428 (setq tg (completing-read
15429 "Tag: "
15430 (or buffer-tags
15431 (with-current-buffer buf
15432 (setq buffer-tags
15433 (org-get-buffer-tags))))))
15434 (quit (setq tg "")))
15435 (when (string-match "\\S-" tg)
15436 (cl-pushnew (list tg) buffer-tags :test #'equal)
15437 (if (member tg current)
15438 (setq current (delete tg current))
15439 (push tg current)))
15440 (when exit-after-next (setq exit-after-next 'now)))
15441 ((setq e (rassoc c todo-table) tg (car e))
15442 (with-current-buffer buf
15443 (save-excursion (org-todo tg)))
15444 (when exit-after-next (setq exit-after-next 'now)))
15445 ((setq e (rassoc c ntable) tg (car e))
15446 (if (member tg current)
15447 (setq current (delete tg current))
15448 (cl-loop for g in groups do
15449 (when (member tg g)
15450 (dolist (x g) (setq current (delete x current)))))
15451 (push tg current))
15452 (when exit-after-next (setq exit-after-next 'now))))
15454 ;; Create a sorted list
15455 (setq current
15456 (sort current
15457 (lambda (a b)
15458 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15459 (when (eq exit-after-next 'now) (throw 'exit t))
15460 (goto-char (point-min))
15461 (beginning-of-line 2)
15462 (delete-region (point) (point-at-eol))
15463 (org-fast-tag-insert "Current" current c-face)
15464 (org-set-current-tags-overlay current ov-prefix)
15465 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15466 (setq tg (match-string 1))
15467 (add-text-properties
15468 (match-beginning 1) (match-end 1)
15469 (list 'face
15470 (cond
15471 ((member tg current) c-face)
15472 ((member tg inherited) i-face)
15473 (t (get-text-property (match-beginning 1) 'face))))))
15474 (goto-char (point-min)))))
15475 (delete-overlay org-tags-overlay)
15476 (if rtn
15477 (mapconcat 'identity current ":")
15478 nil))))
15480 (defun org-get-tags-string ()
15481 "Get the TAGS string in the current headline."
15482 (unless (org-at-heading-p t)
15483 (user-error "Not on a heading"))
15484 (save-excursion
15485 (beginning-of-line 1)
15486 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15487 (match-string-no-properties 1)
15488 "")))
15490 (defun org-get-tags ()
15491 "Get the list of tags specified in the current headline."
15492 (org-split-string (org-get-tags-string) ":"))
15494 (defun org-get-buffer-tags ()
15495 "Get a table of all tags used in the buffer, for completion."
15496 (org-with-wide-buffer
15497 (goto-char (point-min))
15498 (let ((tag-re (concat org-outline-regexp-bol
15499 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15500 tags)
15501 (while (re-search-forward tag-re nil t)
15502 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15503 (push tag tags)))
15504 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15506 ;;;; The mapping API
15508 (defvar org-agenda-skip-comment-trees)
15509 (defvar org-agenda-skip-function)
15510 (defun org-map-entries (func &optional match scope &rest skip)
15511 "Call FUNC at each headline selected by MATCH in SCOPE.
15513 FUNC is a function or a lisp form. The function will be called without
15514 arguments, with the cursor positioned at the beginning of the headline.
15515 The return values of all calls to the function will be collected and
15516 returned as a list.
15518 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15519 does not need to preserve point. After evaluation, the cursor will be
15520 moved to the end of the line (presumably of the headline of the
15521 processed entry) and search continues from there. Under some
15522 circumstances, this may not produce the wanted results. For example,
15523 if you have removed (e.g. archived) the current (sub)tree it could
15524 mean that the next entry will be skipped entirely. In such cases, you
15525 can specify the position from where search should continue by making
15526 FUNC set the variable `org-map-continue-from' to the desired buffer
15527 position.
15529 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15530 Only headlines that are matched by this query will be considered during
15531 the iteration. When MATCH is nil or t, all headlines will be
15532 visited by the iteration.
15534 SCOPE determines the scope of this command. It can be any of:
15536 nil The current buffer, respecting the restriction if any
15537 tree The subtree started with the entry at point
15538 region The entries within the active region, if any
15539 region-start-level
15540 The entries within the active region, but only those at
15541 the same level than the first one.
15542 file The current buffer, without restriction
15543 file-with-archives
15544 The current buffer, and any archives associated with it
15545 agenda All agenda files
15546 agenda-with-archives
15547 All agenda files with any archive files associated with them
15548 \(file1 file2 ...)
15549 If this is a list, all files in the list will be scanned
15551 The remaining args are treated as settings for the skipping facilities of
15552 the scanner. The following items can be given here:
15554 archive skip trees with the archive tag
15555 comment skip trees with the COMMENT keyword
15556 function or Emacs Lisp form:
15557 will be used as value for `org-agenda-skip-function', so
15558 whenever the function returns a position, FUNC will not be
15559 called for that entry and search will continue from the
15560 position returned
15562 If your function needs to retrieve the tags including inherited tags
15563 at the *current* entry, you can use the value of the variable
15564 `org-scanner-tags' which will be much faster than getting the value
15565 with `org-get-tags-at'. If your function gets properties with
15566 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15567 to t around the call to `org-entry-properties' to get the same speedup.
15568 Note that if your function moves around to retrieve tags and properties at
15569 a *different* entry, you cannot use these techniques."
15570 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15571 (not (org-region-active-p)))
15572 (let* ((org-agenda-archives-mode nil) ; just to make sure
15573 (org-agenda-skip-archived-trees (memq 'archive skip))
15574 (org-agenda-skip-comment-trees (memq 'comment skip))
15575 (org-agenda-skip-function
15576 (car (org-delete-all '(comment archive) skip)))
15577 (org-tags-match-list-sublevels t)
15578 (start-level (eq scope 'region-start-level))
15579 matcher res
15580 org-todo-keywords-for-agenda
15581 org-done-keywords-for-agenda
15582 org-todo-keyword-alist-for-agenda
15583 org-tag-alist-for-agenda
15584 org--matcher-tags-todo-only)
15586 (cond
15587 ((eq match t) (setq matcher t))
15588 ((eq match nil) (setq matcher t))
15589 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15591 (save-excursion
15592 (save-restriction
15593 (cond ((eq scope 'tree)
15594 (org-back-to-heading t)
15595 (org-narrow-to-subtree)
15596 (setq scope nil))
15597 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15598 (org-region-active-p))
15599 ;; If needed, set start-level to a string like "2"
15600 (when start-level
15601 (save-excursion
15602 (goto-char (region-beginning))
15603 (unless (org-at-heading-p) (outline-next-heading))
15604 (setq start-level (org-current-level))))
15605 (narrow-to-region (region-beginning)
15606 (save-excursion
15607 (goto-char (region-end))
15608 (unless (and (bolp) (org-at-heading-p))
15609 (outline-next-heading))
15610 (point)))
15611 (setq scope nil)))
15613 (if (not scope)
15614 (progn
15615 (org-agenda-prepare-buffers
15616 (and buffer-file-name (list buffer-file-name)))
15617 (setq res
15618 (org-scan-tags
15619 func matcher org--matcher-tags-todo-only start-level)))
15620 ;; Get the right scope
15621 (cond
15622 ((and scope (listp scope) (symbolp (car scope)))
15623 (setq scope (eval scope)))
15624 ((eq scope 'agenda)
15625 (setq scope (org-agenda-files t)))
15626 ((eq scope 'agenda-with-archives)
15627 (setq scope (org-agenda-files t))
15628 (setq scope (org-add-archive-files scope)))
15629 ((eq scope 'file)
15630 (setq scope (and buffer-file-name (list buffer-file-name))))
15631 ((eq scope 'file-with-archives)
15632 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15633 (org-agenda-prepare-buffers scope)
15634 (dolist (file scope)
15635 (with-current-buffer (org-find-base-buffer-visiting file)
15636 (org-with-wide-buffer
15637 (goto-char (point-min))
15638 (setq res
15639 (append
15641 (org-scan-tags
15642 func matcher org--matcher-tags-todo-only)))))))))
15643 res)))
15645 ;;; Properties API
15647 (defconst org-special-properties
15648 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15649 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15650 "The special properties valid in Org mode.
15651 These are properties that are not defined in the property drawer,
15652 but in some other way.")
15654 (defconst org-default-properties
15655 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15656 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15657 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15658 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15659 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15660 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15661 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15662 "Some properties that are used by Org mode for various purposes.
15663 Being in this list makes sure that they are offered for completion.")
15665 (defun org--valid-property-p (property)
15666 "Non nil when string PROPERTY is a valid property name."
15667 (not
15668 (or (equal property "")
15669 (string-match-p "\\s-" property))))
15671 (defun org--update-property-plist (key val props)
15672 "Associate KEY to VAL in alist PROPS.
15673 Modifications are made by side-effect. Return new alist."
15674 (let* ((appending (string= (substring key -1) "+"))
15675 (key (if appending (substring key 0 -1) key))
15676 (old (assoc-string key props t)))
15677 (if (not old) (cons (cons key val) props)
15678 (setcdr old (if appending (concat (cdr old) " " val) val))
15679 props)))
15681 (defun org-get-property-block (&optional beg force)
15682 "Return the (beg . end) range of the body of the property drawer.
15683 BEG is the beginning of the current subtree, or of the part
15684 before the first headline. If it is not given, it will be found.
15685 If the drawer does not exist, create it if FORCE is non-nil, or
15686 return nil."
15687 (org-with-wide-buffer
15688 (when beg (goto-char beg))
15689 (unless (org-before-first-heading-p)
15690 (let ((beg (cond (beg)
15691 ((or (not (featurep 'org-inlinetask))
15692 (org-inlinetask-in-task-p))
15693 (org-back-to-heading t))
15694 (t (org-with-limited-levels (org-back-to-heading t))))))
15695 (forward-line)
15696 (when (looking-at-p org-planning-line-re) (forward-line))
15697 (cond ((looking-at org-property-drawer-re)
15698 (forward-line)
15699 (cons (point) (progn (goto-char (match-end 0))
15700 (line-beginning-position))))
15701 (force
15702 (goto-char beg)
15703 (org-insert-property-drawer)
15704 (let ((pos (save-excursion (search-forward ":END:")
15705 (line-beginning-position))))
15706 (cons pos pos))))))))
15708 (defun org-at-property-p ()
15709 "Non-nil when point is inside a property drawer.
15710 See `org-property-re' for match data, if applicable."
15711 (save-excursion
15712 (beginning-of-line)
15713 (and (looking-at org-property-re)
15714 (let ((property-drawer (save-match-data (org-get-property-block))))
15715 (and property-drawer
15716 (>= (point) (car property-drawer))
15717 (< (point) (cdr property-drawer)))))))
15719 (defun org-property-action ()
15720 "Do an action on properties."
15721 (interactive)
15722 (unless (org-at-property-p) (user-error "Not at a property"))
15723 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15724 (let ((c (read-char-exclusive)))
15725 (cl-case c
15726 (?s (call-interactively #'org-set-property))
15727 (?d (call-interactively #'org-delete-property))
15728 (?D (call-interactively #'org-delete-property-globally))
15729 (?c (call-interactively #'org-compute-property-at-point))
15730 (otherwise (user-error "No such property action %c" c)))))
15732 (defun org-inc-effort ()
15733 "Increment the value of the effort property in the current entry."
15734 (interactive)
15735 (org-set-effort nil t))
15737 (defvar org-clock-effort) ; Defined in org-clock.el.
15738 (defvar org-clock-current-task) ; Defined in org-clock.el.
15739 (defun org-set-effort (&optional value increment)
15740 "Set the effort property of the current entry.
15741 With numerical prefix arg, use the nth allowed value, 0 stands for the
15742 10th allowed value.
15744 When INCREMENT is non-nil, set the property to the next allowed value."
15745 (interactive "P")
15746 (when (equal value 0) (setq value 10))
15747 (let* ((completion-ignore-case t)
15748 (prop org-effort-property)
15749 (cur (org-entry-get nil prop))
15750 (allowed (org-property-get-allowed-values nil prop 'table))
15751 (existing (mapcar 'list (org-property-values prop)))
15752 (heading (nth 4 (org-heading-components)))
15754 (val (cond
15755 ((stringp value) value)
15756 ((and allowed (integerp value))
15757 (or (car (nth (1- value) allowed))
15758 (car (org-last allowed))))
15759 ((and allowed increment)
15760 (or (cl-caadr (member (list cur) allowed))
15761 (user-error "Allowed effort values are not set")))
15762 (allowed
15763 (message "Select 1-9,0, [RET%s]: %s"
15764 (if cur (concat "=" cur) "")
15765 (mapconcat 'car allowed " "))
15766 (setq rpl (read-char-exclusive))
15767 (if (equal rpl ?\r)
15769 (setq rpl (- rpl ?0))
15770 (when (equal rpl 0) (setq rpl 10))
15771 (if (and (> rpl 0) (<= rpl (length allowed)))
15772 (car (nth (1- rpl) allowed))
15773 (org-completing-read "Effort: " allowed nil))))
15775 (org-completing-read
15776 (concat "Effort" (and cur (string-match "\\S-" cur)
15777 (concat " [" cur "]"))
15778 ": ")
15779 existing nil nil "" nil cur)))))
15780 (unless (equal (org-entry-get nil prop) val)
15781 (org-entry-put nil prop val))
15782 (org-refresh-property
15783 '((effort . identity)
15784 (effort-minutes . org-duration-string-to-minutes))
15785 val)
15786 (when (equal heading (bound-and-true-p org-clock-current-task))
15787 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15788 (org-clock-update-mode-line))
15789 (message "%s is now %s" prop val)))
15791 (defun org-entry-properties (&optional pom which)
15792 "Get all properties of the current entry.
15794 When POM is a buffer position, get all properties from the entry
15795 there instead.
15797 This includes the TODO keyword, the tags, time strings for
15798 deadline, scheduled, and clocking, and any additional properties
15799 defined in the entry.
15801 If WHICH is nil or `all', get all properties. If WHICH is
15802 `special' or `standard', only get that subclass. If WHICH is
15803 a string, only get that property.
15805 Return value is an alist. Keys are properties, as upcased
15806 strings."
15807 (org-with-point-at pom
15808 (when (and (derived-mode-p 'org-mode)
15809 (ignore-errors (org-back-to-heading t)))
15810 (catch 'exit
15811 (let* ((beg (point))
15812 (specific (and (stringp which) (upcase which)))
15813 (which (cond ((not specific) which)
15814 ((member specific org-special-properties) 'special)
15815 (t 'standard)))
15816 props)
15817 ;; Get the special properties, like TODO and TAGS.
15818 (when (memq which '(nil all special))
15819 (when (or (not specific) (string= specific "CLOCKSUM"))
15820 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15821 (when clocksum
15822 (push (cons "CLOCKSUM"
15823 (org-minutes-to-clocksum-string clocksum))
15824 props)))
15825 (when specific (throw 'exit props)))
15826 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15827 (let ((clocksumt (get-text-property (point)
15828 :org-clock-minutes-today)))
15829 (when clocksumt
15830 (push (cons "CLOCKSUM_T"
15831 (org-minutes-to-clocksum-string clocksumt))
15832 props)))
15833 (when specific (throw 'exit props)))
15834 (when (or (not specific) (string= specific "ITEM"))
15835 (let ((case-fold-search nil))
15836 (when (looking-at org-complex-heading-regexp)
15837 (push (cons "ITEM"
15838 (let ((title (match-string-no-properties 4)))
15839 (if (org-string-nw-p title)
15840 (org-remove-tabs title)
15841 "")))
15842 props)))
15843 (when specific (throw 'exit props)))
15844 (when (or (not specific) (string= specific "TODO"))
15845 (let ((case-fold-search nil))
15846 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15847 (push (cons "TODO" (match-string-no-properties 2)) props)))
15848 (when specific (throw 'exit props)))
15849 (when (or (not specific) (string= specific "PRIORITY"))
15850 (push (cons "PRIORITY"
15851 (if (looking-at org-priority-regexp)
15852 (match-string-no-properties 2)
15853 (char-to-string org-default-priority)))
15854 props)
15855 (when specific (throw 'exit props)))
15856 (when (or (not specific) (string= specific "FILE"))
15857 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15858 props)
15859 (when specific (throw 'exit props)))
15860 (when (or (not specific) (string= specific "TAGS"))
15861 (let ((value (org-string-nw-p (org-get-tags-string))))
15862 (when value (push (cons "TAGS" value) props)))
15863 (when specific (throw 'exit props)))
15864 (when (or (not specific) (string= specific "ALLTAGS"))
15865 (let ((value (org-get-tags-at)))
15866 (when value
15867 (push (cons "ALLTAGS"
15868 (format ":%s:" (mapconcat #'identity value ":")))
15869 props)))
15870 (when specific (throw 'exit props)))
15871 (when (or (not specific) (string= specific "BLOCKED"))
15872 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15873 (when specific (throw 'exit props)))
15874 (when (or (not specific)
15875 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15876 (forward-line)
15877 (when (looking-at-p org-planning-line-re)
15878 (end-of-line)
15879 (let ((bol (line-beginning-position))
15880 ;; Backward compatibility: time keywords used to
15881 ;; be configurable (before 8.3). Make sure we
15882 ;; get the correct keyword.
15883 (key-assoc `(("CLOSED" . ,org-closed-string)
15884 ("DEADLINE" . ,org-deadline-string)
15885 ("SCHEDULED" . ,org-scheduled-string))))
15886 (dolist (pair (if specific (list (assoc specific key-assoc))
15887 key-assoc))
15888 (save-excursion
15889 (when (search-backward (cdr pair) bol t)
15890 (goto-char (match-end 0))
15891 (skip-chars-forward " \t")
15892 (and (looking-at org-ts-regexp-both)
15893 (push (cons (car pair)
15894 (match-string-no-properties 0))
15895 props)))))))
15896 (when specific (throw 'exit props)))
15897 (when (or (not specific)
15898 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15899 (let ((find-ts
15900 (lambda (end ts)
15901 ;; Fix next time-stamp before END. TS is the
15902 ;; list of time-stamps found so far.
15903 (let ((ts ts)
15904 (regexp (cond
15905 ((string= specific "TIMESTAMP")
15906 org-ts-regexp)
15907 ((string= specific "TIMESTAMP_IA")
15908 org-ts-regexp-inactive)
15909 ((assoc "TIMESTAMP_IA" ts)
15910 org-ts-regexp)
15911 ((assoc "TIMESTAMP" ts)
15912 org-ts-regexp-inactive)
15913 (t org-ts-regexp-both))))
15914 (catch 'next
15915 (while (re-search-forward regexp end t)
15916 (backward-char)
15917 (let ((object (org-element-context)))
15918 ;; Accept to match timestamps in node
15919 ;; properties, too.
15920 (when (memq (org-element-type object)
15921 '(node-property timestamp))
15922 (let ((type
15923 (org-element-property :type object)))
15924 (cond
15925 ((and (memq type '(active active-range))
15926 (not (equal specific "TIMESTAMP_IA")))
15927 (unless (assoc "TIMESTAMP" ts)
15928 (push (cons "TIMESTAMP"
15929 (org-element-property
15930 :raw-value object))
15932 (when specific (throw 'exit ts))))
15933 ((and (memq type '(inactive inactive-range))
15934 (not (string= specific "TIMESTAMP")))
15935 (unless (assoc "TIMESTAMP_IA" ts)
15936 (push (cons "TIMESTAMP_IA"
15937 (org-element-property
15938 :raw-value object))
15940 (when specific (throw 'exit ts))))))
15941 ;; Both timestamp types are found,
15942 ;; move to next part.
15943 (when (= (length ts) 2) (throw 'next ts)))))
15944 ts)))))
15945 (goto-char beg)
15946 ;; First look for timestamps within headline.
15947 (let ((ts (funcall find-ts (line-end-position) nil)))
15948 (if (= (length ts) 2) (setq props (nconc ts props))
15949 (forward-line)
15950 ;; Then find timestamps in the section, skipping
15951 ;; planning line.
15952 (when (looking-at-p org-planning-line-re)
15953 (forward-line))
15954 (let ((end (save-excursion (outline-next-heading))))
15955 (setq props (nconc (funcall find-ts end ts) props))))))))
15956 ;; Get the standard properties, like :PROP:.
15957 (when (memq which '(nil all standard))
15958 ;; If we are looking after a specific property, delegate
15959 ;; to `org-entry-get', which is faster. However, make an
15960 ;; exception for "CATEGORY", since it can be also set
15961 ;; through keywords (i.e. #+CATEGORY).
15962 (if (and specific (not (equal specific "CATEGORY")))
15963 (let ((value (org-entry-get beg specific nil t)))
15964 (throw 'exit (and value (list (cons specific value)))))
15965 (let ((range (org-get-property-block beg)))
15966 (when range
15967 (let ((end (cdr range)) seen-base)
15968 (goto-char (car range))
15969 ;; Unlike to `org--update-property-plist', we
15970 ;; handle the case where base values is found
15971 ;; after its extension. We also forbid standard
15972 ;; properties to be named as special properties.
15973 (while (re-search-forward org-property-re end t)
15974 (let* ((key (upcase (match-string-no-properties 2)))
15975 (extendp (string-match-p "\\+\\'" key))
15976 (key-base (if extendp (substring key 0 -1) key))
15977 (value (match-string-no-properties 3)))
15978 (cond
15979 ((member-ignore-case key-base org-special-properties))
15980 (extendp
15981 (setq props
15982 (org--update-property-plist key value props)))
15983 ((member key seen-base))
15984 (t (push key seen-base)
15985 (let ((p (assoc-string key props t)))
15986 (if p (setcdr p (concat value " " (cdr p)))
15987 (push (cons key value) props))))))))))))
15988 (unless (assoc "CATEGORY" props)
15989 (push (cons "CATEGORY" (org-get-category beg)) props)
15990 (when (string= specific "CATEGORY") (throw 'exit props)))
15991 ;; Return value.
15992 props)))))
15994 (defun org-property--local-values (property literal-nil)
15995 "Return value for PROPERTY in current entry.
15996 Value is a list whose car is the base value for PROPERTY and cdr
15997 a list of accumulated values. Return nil if neither is found in
15998 the entry. Also return nil when PROPERTY is set to \"nil\",
15999 unless LITERAL-NIL is non-nil."
16000 (let ((range (org-get-property-block)))
16001 (when range
16002 (goto-char (car range))
16003 (let* ((case-fold-search t)
16004 (end (cdr range))
16005 (value
16006 ;; Base value.
16007 (save-excursion
16008 (let ((v (and (re-search-forward
16009 (org-re-property property nil t) end t)
16010 (match-string-no-properties 3))))
16011 (list (if literal-nil v (org-not-nil v)))))))
16012 ;; Find additional values.
16013 (let* ((property+ (org-re-property (concat property "+") nil t)))
16014 (while (re-search-forward property+ end t)
16015 (push (match-string-no-properties 3) value)))
16016 ;; Return final values.
16017 (and (not (equal value '(nil))) (nreverse value))))))
16019 (defun org-entry-get (pom property &optional inherit literal-nil)
16020 "Get value of PROPERTY for entry or content at point-or-marker POM.
16022 If INHERIT is non-nil and the entry does not have the property,
16023 then also check higher levels of the hierarchy. If INHERIT is
16024 the symbol `selective', use inheritance only if the setting in
16025 `org-use-property-inheritance' selects PROPERTY for inheritance.
16027 If the property is present but empty, the return value is the
16028 empty string. If the property is not present at all, nil is
16029 returned. In any other case, return the value as a string.
16030 Search is case-insensitive.
16032 If LITERAL-NIL is set, return the string value \"nil\" as
16033 a string, do not interpret it as the list atom nil. This is used
16034 for inheritance when a \"nil\" value can supersede a non-nil
16035 value higher up the hierarchy."
16036 (org-with-point-at pom
16037 (cond
16038 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
16039 ;; We need a special property. Use `org-entry-properties' to
16040 ;; retrieve it, but specify the wanted property.
16041 (cdr (assoc-string property (org-entry-properties nil property))))
16042 ((and inherit
16043 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
16044 (org-entry-get-with-inheritance property literal-nil))
16046 (let* ((local (org-property--local-values property literal-nil))
16047 (value (and local (mapconcat #'identity (delq nil local) " "))))
16048 (if literal-nil value (org-not-nil value)))))))
16050 (defun org-property-or-variable-value (var &optional inherit)
16051 "Check if there is a property fixing the value of VAR.
16052 If yes, return this value. If not, return the current value of the variable."
16053 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
16054 (if (and prop (stringp prop) (string-match "\\S-" prop))
16055 (read prop)
16056 (symbol-value var))))
16058 (defun org-entry-delete (pom property)
16059 "Delete PROPERTY from entry at point-or-marker POM.
16060 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16061 non-nil when a property was removed."
16062 (unless (member property org-special-properties)
16063 (org-with-point-at pom
16064 (let ((range (org-get-property-block)))
16065 (when range
16066 (let* ((begin (car range))
16067 (origin (cdr range))
16068 (end (copy-marker origin))
16069 (re (org-re-property
16070 (concat (regexp-quote property) "\\+?") t t)))
16071 (goto-char begin)
16072 (while (re-search-forward re end t)
16073 (delete-region (match-beginning 0) (line-beginning-position 2)))
16074 ;; If drawer is empty, remove it altogether.
16075 (when (= begin end)
16076 (delete-region (line-beginning-position 0)
16077 (line-beginning-position 2)))
16078 ;; Return non-nil if some property was removed.
16079 (prog1 (/= end origin) (set-marker end nil))))))))
16081 ;; Multi-values properties are properties that contain multiple values
16082 ;; These values are assumed to be single words, separated by whitespace.
16083 (defun org-entry-add-to-multivalued-property (pom property value)
16084 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16085 (let* ((old (org-entry-get pom property))
16086 (values (and old (org-split-string old "[ \t]"))))
16087 (setq value (org-entry-protect-space value))
16088 (unless (member value values)
16089 (setq values (append values (list value)))
16090 (org-entry-put pom property
16091 (mapconcat 'identity values " ")))))
16093 (defun org-entry-remove-from-multivalued-property (pom property value)
16094 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16095 (let* ((old (org-entry-get pom property))
16096 (values (and old (org-split-string old "[ \t]"))))
16097 (setq value (org-entry-protect-space value))
16098 (when (member value values)
16099 (setq values (delete value values))
16100 (org-entry-put pom property
16101 (mapconcat 'identity values " ")))))
16103 (defun org-entry-member-in-multivalued-property (pom property value)
16104 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16105 (let* ((old (org-entry-get pom property))
16106 (values (and old (org-split-string old "[ \t]"))))
16107 (setq value (org-entry-protect-space value))
16108 (member value values)))
16110 (defun org-entry-get-multivalued-property (pom property)
16111 "Return a list of values in a multivalued property."
16112 (let* ((value (org-entry-get pom property))
16113 (values (and value (org-split-string value "[ \t]"))))
16114 (mapcar 'org-entry-restore-space values)))
16116 (defun org-entry-put-multivalued-property (pom property &rest values)
16117 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16118 VALUES should be a list of strings. Spaces will be protected."
16119 (org-entry-put pom property
16120 (mapconcat 'org-entry-protect-space values " "))
16121 (let* ((value (org-entry-get pom property))
16122 (values (and value (org-split-string value "[ \t]"))))
16123 (mapcar 'org-entry-restore-space values)))
16125 (defun org-entry-protect-space (s)
16126 "Protect spaces and newline in string S."
16127 (while (string-match " " s)
16128 (setq s (replace-match "%20" t t s)))
16129 (while (string-match "\n" s)
16130 (setq s (replace-match "%0A" t t s)))
16133 (defun org-entry-restore-space (s)
16134 "Restore spaces and newline in string S."
16135 (while (string-match "%20" s)
16136 (setq s (replace-match " " t t s)))
16137 (while (string-match "%0A" s)
16138 (setq s (replace-match "\n" t t s)))
16141 (defvar org-entry-property-inherited-from (make-marker)
16142 "Marker pointing to the entry from where a property was inherited.
16143 Each call to `org-entry-get-with-inheritance' will set this marker to the
16144 location of the entry where the inheritance search matched. If there was
16145 no match, the marker will point nowhere.
16146 Note that also `org-entry-get' calls this function, if the INHERIT flag
16147 is set.")
16149 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16150 "Get PROPERTY of entry or content at point, search higher levels if needed.
16151 The search will stop at the first ancestor which has the property defined.
16152 If the value found is \"nil\", return nil to show that the property
16153 should be considered as undefined (this is the meaning of nil here).
16154 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16155 (move-marker org-entry-property-inherited-from nil)
16156 (org-with-wide-buffer
16157 (let (value)
16158 (catch 'exit
16159 (while t
16160 (let ((v (org-property--local-values property literal-nil)))
16161 (when v
16162 (setq value
16163 (concat (mapconcat #'identity (delq nil v) " ")
16164 (and value " ")
16165 value)))
16166 (cond
16167 ((car v)
16168 (org-back-to-heading t)
16169 (move-marker org-entry-property-inherited-from (point))
16170 (throw 'exit nil))
16171 ((org-up-heading-safe))
16173 (let ((global
16174 (cdr (or (assoc-string property org-file-properties t)
16175 (assoc-string property org-global-properties t)
16176 (assoc-string property org-global-properties-fixed t)))))
16177 (cond ((not global))
16178 (value (setq value (concat global " " value)))
16179 (t (setq value global))))
16180 (throw 'exit nil))))))
16181 (if literal-nil value (org-not-nil value)))))
16183 (defvar org-property-changed-functions nil
16184 "Hook called when the value of a property has changed.
16185 Each hook function should accept two arguments, the name of the property
16186 and the new value.")
16188 (defun org-entry-put (pom property value)
16189 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16191 If the value is nil, it is converted to the empty string. If it
16192 is not a string, an error is raised. Also raise an error on
16193 invalid property names.
16195 PROPERTY can be any regular property (see
16196 `org-special-properties'). It can also be \"TODO\",
16197 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16199 For the last two properties, VALUE may have any of the special
16200 values \"earlier\" and \"later\". The function then increases or
16201 decreases scheduled or deadline date by one day."
16202 (cond ((null value) (setq value ""))
16203 ((not (stringp value)) (error "Properties values should be strings"))
16204 ((not (org--valid-property-p property))
16205 (user-error "Invalid property name: \"%s\"" property)))
16206 (org-with-point-at pom
16207 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16208 (org-back-to-heading t)
16209 (org-with-limited-levels (org-back-to-heading t)))
16210 (let ((beg (point)))
16211 (cond
16212 ((equal property "TODO")
16213 (cond ((not (org-string-nw-p value)) (setq value 'none))
16214 ((not (member value org-todo-keywords-1))
16215 (user-error "\"%s\" is not a valid TODO state" value)))
16216 (org-todo value)
16217 (org-set-tags nil 'align))
16218 ((equal property "PRIORITY")
16219 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16220 (org-set-tags nil 'align))
16221 ((equal property "SCHEDULED")
16222 (forward-line)
16223 (if (and (looking-at-p org-planning-line-re)
16224 (re-search-forward
16225 org-scheduled-time-regexp (line-end-position) t))
16226 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16227 ((string= value "later") (org-timestamp-change 1 'day))
16228 ((string= value "") (org-schedule '(4)))
16229 (t (org-schedule nil value)))
16230 (if (member value '("earlier" "later" ""))
16231 (call-interactively #'org-schedule)
16232 (org-schedule nil value))))
16233 ((equal property "DEADLINE")
16234 (forward-line)
16235 (if (and (looking-at-p org-planning-line-re)
16236 (re-search-forward
16237 org-deadline-time-regexp (line-end-position) t))
16238 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16239 ((string= value "later") (org-timestamp-change 1 'day))
16240 ((string= value "") (org-deadline '(4)))
16241 (t (org-deadline nil value)))
16242 (if (member value '("earlier" "later" ""))
16243 (call-interactively #'org-deadline)
16244 (org-deadline nil value))))
16245 ((member property org-special-properties)
16246 (error "The %s property cannot be set with `org-entry-put'" property))
16248 (let* ((range (org-get-property-block beg 'force))
16249 (end (cdr range))
16250 (case-fold-search t))
16251 (goto-char (car range))
16252 (if (re-search-forward (org-re-property property nil t) end t)
16253 (progn (delete-region (match-beginning 0) (match-end 0))
16254 (goto-char (match-beginning 0)))
16255 (goto-char end)
16256 (insert "\n")
16257 (backward-char))
16258 (insert ":" property ":")
16259 (when value (insert " " value))
16260 (org-indent-line)))))
16261 (run-hook-with-args 'org-property-changed-functions property value)))
16263 (defun org-buffer-property-keys
16264 (&optional specials defaults columns ignore-malformed)
16265 "Get all property keys in the current buffer.
16267 When SPECIALS is non-nil, also list the special properties that
16268 reflect things like tags and TODO state.
16270 When DEFAULTS is non-nil, also include properties that has
16271 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16272 DESCRIPTION, LOCATION, and LOGGING and others.
16274 When COLUMNS in non-nil, also include property names given in
16275 COLUMN formats in the current buffer.
16277 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16278 automatically performed, such drawers will be silently ignored."
16279 (let ((case-fold-search t)
16280 (props (append
16281 (and specials org-special-properties)
16282 (and defaults (cons org-effort-property org-default-properties))
16283 nil)))
16284 (org-with-wide-buffer
16285 (goto-char (point-min))
16286 (while (re-search-forward org-property-start-re nil t)
16287 (let ((range (org-get-property-block)))
16288 (catch 'skip
16289 (unless range
16290 (when (and (not ignore-malformed)
16291 (not (org-before-first-heading-p))
16292 (y-or-n-p (format "Malformed drawer at %d, repair?"
16293 (line-beginning-position))))
16294 (org-get-property-block nil t))
16295 (throw 'skip nil))
16296 (goto-char (car range))
16297 (let ((begin (car range))
16298 (end (cdr range)))
16299 ;; Make sure that found property block is not located
16300 ;; before current point, as it would generate an infloop.
16301 ;; It can happen, for example, in the following
16302 ;; situation:
16304 ;; * Headline
16305 ;; :PROPERTIES:
16306 ;; ...
16307 ;; :END:
16308 ;; *************** Inlinetask
16309 ;; #+BEGIN_EXAMPLE
16310 ;; :PROPERTIES:
16311 ;; #+END_EXAMPLE
16313 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16314 (while (< (point) end)
16315 (let ((p (progn (looking-at org-property-re)
16316 (match-string-no-properties 2))))
16317 ;; Only add true property name, not extension symbol.
16318 (push (if (not (string-match-p "\\+\\'" p)) p
16319 (substring p 0 -1))
16320 props))
16321 (forward-line))))
16322 (outline-next-heading)))
16323 (when columns
16324 (goto-char (point-min))
16325 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16326 (let ((element (org-element-at-point)))
16327 (when (memq (org-element-type element) '(keyword node-property))
16328 (let ((value (org-element-property :value element))
16329 (start 0))
16330 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16331 (setq start (match-end 0))
16332 (let ((p (match-string-no-properties 1 value)))
16333 (unless (member-ignore-case p org-special-properties)
16334 (push p props))))))))))
16335 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16337 (defun org-property-values (key)
16338 "List all non-nil values of property KEY in current buffer."
16339 (org-with-wide-buffer
16340 (goto-char (point-min))
16341 (let ((case-fold-search t)
16342 (re (org-re-property key))
16343 values)
16344 (while (re-search-forward re nil t)
16345 (push (org-entry-get (point) key) values))
16346 (delete-dups values))))
16348 (defun org-insert-property-drawer ()
16349 "Insert a property drawer into the current entry."
16350 (org-with-wide-buffer
16351 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16352 (org-back-to-heading t)
16353 (org-with-limited-levels (org-back-to-heading t)))
16354 (forward-line)
16355 (when (looking-at-p org-planning-line-re) (forward-line))
16356 (unless (looking-at-p org-property-drawer-re)
16357 ;; Make sure we start editing a line from current entry, not from
16358 ;; next one. It prevents extending text properties or overlays
16359 ;; belonging to the latter.
16360 (when (bolp) (backward-char))
16361 (let ((begin (1+ (point)))
16362 (inhibit-read-only t))
16363 (insert "\n:PROPERTIES:\n:END:")
16364 (when (eobp) (insert "\n"))
16365 (org-indent-region begin (point))))))
16367 (defun org-insert-drawer (&optional arg drawer)
16368 "Insert a drawer at point.
16370 When optional argument ARG is non-nil, insert a property drawer.
16372 Optional argument DRAWER, when non-nil, is a string representing
16373 drawer's name. Otherwise, the user is prompted for a name.
16375 If a region is active, insert the drawer around that region
16376 instead.
16378 Point is left between drawer's boundaries."
16379 (interactive "P")
16380 (let* ((drawer (if arg "PROPERTIES"
16381 (or drawer (read-from-minibuffer "Drawer: ")))))
16382 (cond
16383 ;; With C-u, fall back on `org-insert-property-drawer'
16384 (arg (org-insert-property-drawer))
16385 ;; Check validity of suggested drawer's name.
16386 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16387 (user-error "Invalid drawer name"))
16388 ;; With an active region, insert a drawer at point.
16389 ((not (org-region-active-p))
16390 (progn
16391 (unless (bolp) (insert "\n"))
16392 (insert (format ":%s:\n\n:END:\n" drawer))
16393 (forward-line -2)))
16394 ;; Otherwise, insert the drawer at point
16396 (let ((rbeg (region-beginning))
16397 (rend (copy-marker (region-end))))
16398 (unwind-protect
16399 (progn
16400 (goto-char rbeg)
16401 (beginning-of-line)
16402 (when (save-excursion
16403 (re-search-forward org-outline-regexp-bol rend t))
16404 (user-error "Drawers cannot contain headlines"))
16405 ;; Position point at the beginning of the first
16406 ;; non-blank line in region. Insert drawer's opening
16407 ;; there, then indent it.
16408 (org-skip-whitespace)
16409 (beginning-of-line)
16410 (insert ":" drawer ":\n")
16411 (forward-line -1)
16412 (indent-for-tab-command)
16413 ;; Move point to the beginning of the first blank line
16414 ;; after the last non-blank line in region. Insert
16415 ;; drawer's closing, then indent it.
16416 (goto-char rend)
16417 (skip-chars-backward " \r\t\n")
16418 (insert "\n:END:")
16419 (deactivate-mark t)
16420 (indent-for-tab-command)
16421 (unless (eolp) (insert "\n")))
16422 ;; Clear marker, whatever the outcome of insertion is.
16423 (set-marker rend nil)))))))
16425 (defvar org-property-set-functions-alist nil
16426 "Property set function alist.
16427 Each entry should have the following format:
16429 (PROPERTY . READ-FUNCTION)
16431 The read function will be called with the same argument as
16432 `org-completing-read'.")
16434 (defun org-set-property-function (property)
16435 "Get the function that should be used to set PROPERTY.
16436 This is computed according to `org-property-set-functions-alist'."
16437 (or (cdr (assoc property org-property-set-functions-alist))
16438 'org-completing-read))
16440 (defun org-read-property-value (property)
16441 "Read PROPERTY value from user."
16442 (let* ((completion-ignore-case t)
16443 (allowed (org-property-get-allowed-values nil property 'table))
16444 (cur (org-entry-get nil property))
16445 (prompt (concat property " value"
16446 (if (and cur (string-match "\\S-" cur))
16447 (concat " [" cur "]") "") ": "))
16448 (set-function (org-set-property-function property))
16449 (val (if allowed
16450 (funcall set-function prompt allowed nil
16451 (not (get-text-property 0 'org-unrestricted
16452 (caar allowed))))
16453 (funcall set-function prompt
16454 (mapcar 'list (org-property-values property))
16455 nil nil "" nil cur))))
16456 (org-trim val)))
16458 (defvar org-last-set-property nil)
16459 (defvar org-last-set-property-value nil)
16460 (defun org-read-property-name ()
16461 "Read a property name."
16462 (let ((completion-ignore-case t)
16463 (default-prop (or (and (org-at-property-p)
16464 (match-string-no-properties 2))
16465 org-last-set-property)))
16466 (org-completing-read
16467 (concat "Property"
16468 (if default-prop (concat " [" default-prop "]") "")
16469 ": ")
16470 (mapcar #'list (org-buffer-property-keys nil t t))
16471 nil nil nil nil default-prop)))
16473 (defun org-set-property-and-value (use-last)
16474 "Allow to set [PROPERTY]: [value] direction from prompt.
16475 When use-default, don't even ask, just use the last
16476 \"[PROPERTY]: [value]\" string from the history."
16477 (interactive "P")
16478 (let* ((completion-ignore-case t)
16479 (pv (or (and use-last org-last-set-property-value)
16480 (org-completing-read
16481 "Enter a \"[Property]: [value]\" pair: "
16482 nil nil nil nil nil
16483 org-last-set-property-value)))
16484 prop val)
16485 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16486 (setq prop (match-string 1 pv)
16487 val (match-string 2 pv))
16488 (org-set-property prop val))))
16490 (defun org-set-property (property value)
16491 "In the current entry, set PROPERTY to VALUE.
16493 When called interactively, this will prompt for a property name, offering
16494 completion on existing and default properties. And then it will prompt
16495 for a value, offering completion either on allowed values (via an inherited
16496 xxx_ALL property) or on existing values in other instances of this property
16497 in the current file.
16499 Throw an error when trying to set a property with an invalid name."
16500 (interactive (list nil nil))
16501 (let ((property (or property (org-read-property-name))))
16502 ;; `org-entry-put' also makes the following check, but this one
16503 ;; avoids polluting `org-last-set-property' and
16504 ;; `org-last-set-property-value' needlessly.
16505 (unless (org--valid-property-p property)
16506 (user-error "Invalid property name: \"%s\"" property))
16507 (let ((value (or value (org-read-property-value property)))
16508 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16509 (setq org-last-set-property property)
16510 (setq org-last-set-property-value (concat property ": " value))
16511 ;; Possibly postprocess the inserted value:
16512 (when fn (setq value (funcall fn value)))
16513 (unless (equal (org-entry-get nil property) value)
16514 (org-entry-put nil property value)))))
16516 (defun org-find-property (property &optional value)
16517 "Find first entry in buffer that sets PROPERTY.
16519 When optional argument VALUE is non-nil, only consider an entry
16520 if it contains PROPERTY set to this value. If PROPERTY should be
16521 explicitly set to nil, use string \"nil\" for VALUE.
16523 Return position where the entry begins, or nil if there is no
16524 such entry. If narrowing is in effect, only search the visible
16525 part of the buffer."
16526 (save-excursion
16527 (goto-char (point-min))
16528 (let ((case-fold-search t)
16529 (re (org-re-property property nil (not value) value)))
16530 (catch 'exit
16531 (while (re-search-forward re nil t)
16532 (when (if value (org-at-property-p)
16533 (org-entry-get (point) property nil t))
16534 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16536 (defun org-delete-property (property)
16537 "In the current entry, delete PROPERTY."
16538 (interactive
16539 (let* ((completion-ignore-case t)
16540 (cat (org-entry-get (point) "CATEGORY"))
16541 (props0 (org-entry-properties nil 'standard))
16542 (props (if cat props0
16543 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16544 (prop (if (< 1 (length props))
16545 (completing-read "Property: " props nil t)
16546 (caar props))))
16547 (list prop)))
16548 (if (not property)
16549 (message "No property to delete in this entry")
16550 (org-entry-delete nil property)
16551 (message "Property \"%s\" deleted" property)))
16553 (defun org-delete-property-globally (property)
16554 "Remove PROPERTY globally, from all entries.
16555 This function ignores narrowing, if any."
16556 (interactive
16557 (let* ((completion-ignore-case t)
16558 (prop (completing-read
16559 "Globally remove property: "
16560 (mapcar #'list (org-buffer-property-keys)))))
16561 (list prop)))
16562 (org-with-wide-buffer
16563 (goto-char (point-min))
16564 (let ((count 0)
16565 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16566 (while (re-search-forward re nil t)
16567 (when (org-entry-delete (point) property) (cl-incf count)))
16568 (message "Property \"%s\" removed from %d entries" property count))))
16570 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16572 (defun org-compute-property-at-point ()
16573 "Compute the property at point.
16574 This looks for an enclosing column format, extracts the operator and
16575 then applies it to the property in the column format's scope."
16576 (interactive)
16577 (unless (org-at-property-p)
16578 (user-error "Not at a property"))
16579 (let ((prop (match-string-no-properties 2)))
16580 (org-columns-get-format-and-top-level)
16581 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16582 (user-error "No operator defined for property %s" prop))
16583 (org-columns-compute prop)))
16585 (defvar org-property-allowed-value-functions nil
16586 "Hook for functions supplying allowed values for a specific property.
16587 The functions must take a single argument, the name of the property, and
16588 return a flat list of allowed values. If \":ETC\" is one of
16589 the values, this means that these values are intended as defaults for
16590 completion, but that other values should be allowed too.
16591 The functions must return nil if they are not responsible for this
16592 property.")
16594 (defun org-property-get-allowed-values (pom property &optional table)
16595 "Get allowed values for the property PROPERTY.
16596 When TABLE is non-nil, return an alist that can directly be used for
16597 completion."
16598 (let (vals)
16599 (cond
16600 ((equal property "TODO")
16601 (setq vals (org-with-point-at pom
16602 (append org-todo-keywords-1 '("")))))
16603 ((equal property "PRIORITY")
16604 (let ((n org-lowest-priority))
16605 (while (>= n org-highest-priority)
16606 (push (char-to-string n) vals)
16607 (setq n (1- n)))))
16608 ((equal property "CATEGORY"))
16609 ((member property org-special-properties))
16610 ((setq vals (run-hook-with-args-until-success
16611 'org-property-allowed-value-functions property)))
16613 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16614 (when (and vals (string-match "\\S-" vals))
16615 (setq vals (car (read-from-string (concat "(" vals ")"))))
16616 (setq vals (mapcar (lambda (x)
16617 (cond ((stringp x) x)
16618 ((numberp x) (number-to-string x))
16619 ((symbolp x) (symbol-name x))
16620 (t "???")))
16621 vals)))))
16622 (when (member ":ETC" vals)
16623 (setq vals (remove ":ETC" vals))
16624 (org-add-props (car vals) '(org-unrestricted t)))
16625 (if table (mapcar 'list vals) vals)))
16627 (defun org-property-previous-allowed-value (&optional _previous)
16628 "Switch to the next allowed value for this property."
16629 (interactive)
16630 (org-property-next-allowed-value t))
16632 (defun org-property-next-allowed-value (&optional previous)
16633 "Switch to the next allowed value for this property."
16634 (interactive)
16635 (unless (org-at-property-p)
16636 (user-error "Not at a property"))
16637 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16638 (key (match-string 2))
16639 (value (match-string 3))
16640 (allowed (or (org-property-get-allowed-values (point) key)
16641 (and (member value '("[ ]" "[-]" "[X]"))
16642 '("[ ]" "[X]"))))
16643 (heading (save-match-data (nth 4 (org-heading-components))))
16644 nval)
16645 (unless allowed
16646 (user-error "Allowed values for this property have not been defined"))
16647 (when previous (setq allowed (reverse allowed)))
16648 (when (member value allowed)
16649 (setq nval (car (cdr (member value allowed)))))
16650 (setq nval (or nval (car allowed)))
16651 (when (equal nval value)
16652 (user-error "Only one allowed value for this property"))
16653 (org-at-property-p)
16654 (replace-match (concat " :" key ": " nval) t t)
16655 (org-indent-line)
16656 (beginning-of-line 1)
16657 (skip-chars-forward " \t")
16658 (when (equal prop org-effort-property)
16659 (org-refresh-property
16660 '((effort . identity)
16661 (effort-minutes . org-duration-string-to-minutes))
16662 nval)
16663 (when (string= org-clock-current-task heading)
16664 (setq org-clock-effort nval)
16665 (org-clock-update-mode-line)))
16666 (run-hook-with-args 'org-property-changed-functions key nval)))
16668 (defun org-find-olp (path &optional this-buffer)
16669 "Return a marker pointing to the entry at outline path OLP.
16670 If anything goes wrong, throw an error.
16671 You can wrap this call to catch the error like this:
16673 (condition-case msg
16674 (org-mobile-locate-entry (match-string 4))
16675 (error (nth 1 msg)))
16677 The return value will then be either a string with the error message,
16678 or a marker if everything is OK.
16680 If THIS-BUFFER is set, the outline path does not contain a file,
16681 only headings."
16682 (let* ((file (if this-buffer buffer-file-name (pop path)))
16683 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16684 (level 1)
16685 (lmin 1)
16686 (lmax 1)
16687 end found flevel)
16688 (unless buffer (error "File not found :%s" file))
16689 (with-current-buffer buffer
16690 (org-with-wide-buffer
16691 (goto-char (point-min))
16692 (dolist (heading path)
16693 (let ((re (format org-complex-heading-regexp-format
16694 (regexp-quote heading)))
16695 (cnt 0))
16696 (while (re-search-forward re end t)
16697 (setq level (- (match-end 1) (match-beginning 1)))
16698 (when (and (>= level lmin) (<= level lmax))
16699 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16700 (when (= cnt 0)
16701 (error "Heading not found on level %d: %s" lmax heading))
16702 (when (> cnt 1)
16703 (error "Heading not unique on level %d: %s" lmax heading))
16704 (goto-char found)
16705 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16706 (setq end (save-excursion (org-end-of-subtree t t)))))
16707 (when (org-at-heading-p)
16708 (point-marker))))))
16710 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16711 "Find node HEADING in BUFFER.
16712 Return a marker to the heading if it was found, or nil if not.
16713 If POS-ONLY is set, return just the position instead of a marker.
16715 The heading text must match exact, but it may have a TODO keyword,
16716 a priority cookie and tags in the standard locations."
16717 (with-current-buffer (or buffer (current-buffer))
16718 (org-with-wide-buffer
16719 (goto-char (point-min))
16720 (let (case-fold-search)
16721 (when (re-search-forward
16722 (format org-complex-heading-regexp-format
16723 (regexp-quote heading)) nil t)
16724 (if pos-only
16725 (match-beginning 0)
16726 (move-marker (make-marker) (match-beginning 0))))))))
16728 (defun org-find-exact-heading-in-directory (heading &optional dir)
16729 "Find Org node headline HEADING in all .org files in directory DIR.
16730 When the target headline is found, return a marker to this location."
16731 (let ((files (directory-files (or dir default-directory)
16732 t "\\`[^.#].*\\.org\\'"))
16733 visiting m buffer)
16734 (catch 'found
16735 (dolist (file files)
16736 (message "trying %s" file)
16737 (setq visiting (org-find-base-buffer-visiting file))
16738 (setq buffer (or visiting (find-file-noselect file)))
16739 (setq m (org-find-exact-headline-in-buffer
16740 heading buffer))
16741 (when (and (not m) (not visiting)) (kill-buffer buffer))
16742 (and m (throw 'found m))))))
16744 (defun org-find-entry-with-id (ident)
16745 "Locate the entry that contains the ID property with exact value IDENT.
16746 IDENT can be a string, a symbol or a number, this function will search for
16747 the string representation of it.
16748 Return the position where this entry starts, or nil if there is no such entry."
16749 (interactive "sID: ")
16750 (let ((id (cond
16751 ((stringp ident) ident)
16752 ((symbolp ident) (symbol-name ident))
16753 ((numberp ident) (number-to-string ident))
16754 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16755 (org-with-wide-buffer (org-find-property "ID" id))))
16757 ;;;; Timestamps
16759 (defvar org-last-changed-timestamp nil)
16760 (defvar org-last-inserted-timestamp nil
16761 "The last time stamp inserted with `org-insert-time-stamp'.")
16762 (defvar org-ts-what) ; dynamically scoped parameter
16764 (defun org-time-stamp (arg &optional inactive)
16765 "Prompt for a date/time and insert a time stamp.
16767 If the user specifies a time like HH:MM or if this command is
16768 called with at least one prefix argument, the time stamp contains
16769 the date and the time. Otherwise, only the date is included.
16771 All parts of a date not specified by the user are filled in from
16772 the timestamp at point, if any, or the current date/time
16773 otherwise.
16775 If there is already a timestamp at the cursor, it is replaced.
16777 With two universal prefix arguments, insert an active timestamp
16778 with the current time without prompting the user.
16780 When called from lisp, the timestamp is inactive if INACTIVE is
16781 non-nil."
16782 (interactive "P")
16783 (let* ((ts (cond
16784 ((org-at-date-range-p t)
16785 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16786 ((org-at-timestamp-p t) (match-string 0))))
16787 ;; Default time is either the timestamp at point or today.
16788 ;; When entering a range, only the range start is considered.
16789 (default-time (if (not ts) (current-time)
16790 (apply #'encode-time (org-parse-time-string ts))))
16791 (default-input (and ts (org-get-compact-tod ts)))
16792 (repeater (and ts
16793 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16794 (match-string 0 ts)))
16795 org-time-was-given
16796 org-end-time-was-given
16797 (time
16798 (and (if (equal arg '(16)) (current-time)
16799 ;; Preserve `this-command' and `last-command'.
16800 (let ((this-command this-command)
16801 (last-command last-command))
16802 (org-read-date
16803 arg 'totime nil nil default-time default-input
16804 inactive))))))
16805 (cond
16806 ((and ts
16807 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16808 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16809 (insert "--")
16810 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16812 ;; Make sure we're on a timestamp. When in the middle of a date
16813 ;; range, move arbitrarily to range end.
16814 (unless (org-at-timestamp-p t)
16815 (skip-chars-forward "-")
16816 (org-at-timestamp-p t))
16817 (replace-match "")
16818 (setq org-last-changed-timestamp
16819 (org-insert-time-stamp
16820 time (or org-time-was-given arg)
16821 inactive nil nil (list org-end-time-was-given)))
16822 (when repeater
16823 (backward-char)
16824 (insert " " repeater)
16825 (setq org-last-changed-timestamp
16826 (concat (substring org-last-inserted-timestamp 0 -1)
16827 " " repeater ">")))
16828 (message "Timestamp updated"))
16829 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16830 (t (org-insert-time-stamp
16831 time (or org-time-was-given arg) inactive nil nil
16832 (list org-end-time-was-given))))))
16834 ;; FIXME: can we use this for something else, like computing time differences?
16835 (defun org-get-compact-tod (s)
16836 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16837 (let* ((t1 (match-string 1 s))
16838 (h1 (string-to-number (match-string 2 s)))
16839 (m1 (string-to-number (match-string 3 s)))
16840 (t2 (and (match-end 4) (match-string 5 s)))
16841 (h2 (and t2 (string-to-number (match-string 6 s))))
16842 (m2 (and t2 (string-to-number (match-string 7 s))))
16843 dh dm)
16844 (if (not t2)
16846 (setq dh (- h2 h1) dm (- m2 m1))
16847 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16848 (concat t1 "+" (number-to-string dh)
16849 (and (/= 0 dm) (format ":%02d" dm)))))))
16851 (defun org-time-stamp-inactive (&optional arg)
16852 "Insert an inactive time stamp.
16853 An inactive time stamp is enclosed in square brackets instead of angle
16854 brackets. It is inactive in the sense that it does not trigger agenda entries,
16855 does not link to the calendar and cannot be changed with the S-cursor keys.
16856 So these are more for recording a certain time/date."
16857 (interactive "P")
16858 (org-time-stamp arg 'inactive))
16860 (defvar org-date-ovl (make-overlay 1 1))
16861 (overlay-put org-date-ovl 'face 'org-date-selected)
16862 (delete-overlay org-date-ovl)
16864 (defvar org-ans1) ; dynamically scoped parameter
16865 (defvar org-ans2) ; dynamically scoped parameter
16867 (defvar org-plain-time-of-day-regexp) ; defined below
16869 (defvar org-overriding-default-time nil) ; dynamically scoped
16870 (defvar org-read-date-overlay nil)
16871 (defvar org-dcst nil) ; dynamically scoped
16872 (defvar org-read-date-history nil)
16873 (defvar org-read-date-final-answer nil)
16874 (defvar org-read-date-analyze-futurep nil)
16875 (defvar org-read-date-analyze-forced-year nil)
16876 (defvar org-read-date-inactive)
16878 (defvar org-read-date-minibuffer-local-map
16879 (let* ((map (make-sparse-keymap)))
16880 (set-keymap-parent map minibuffer-local-map)
16881 (org-defkey map (kbd ".")
16882 (lambda () (interactive)
16883 ;; Are we at the beginning of the prompt?
16884 (if (looking-back "^[^:]+: "
16885 (let ((inhibit-field-text-motion t))
16886 (line-beginning-position)))
16887 (org-eval-in-calendar '(calendar-goto-today))
16888 (insert "."))))
16889 (org-defkey map (kbd "C-.")
16890 (lambda () (interactive)
16891 (org-eval-in-calendar '(calendar-goto-today))))
16892 (org-defkey map [(meta shift left)]
16893 (lambda () (interactive)
16894 (org-eval-in-calendar '(calendar-backward-month 1))))
16895 (org-defkey map [(meta shift right)]
16896 (lambda () (interactive)
16897 (org-eval-in-calendar '(calendar-forward-month 1))))
16898 (org-defkey map [(meta shift up)]
16899 (lambda () (interactive)
16900 (org-eval-in-calendar '(calendar-backward-year 1))))
16901 (org-defkey map [(meta shift down)]
16902 (lambda () (interactive)
16903 (org-eval-in-calendar '(calendar-forward-year 1))))
16904 (org-defkey map [?\e (shift left)]
16905 (lambda () (interactive)
16906 (org-eval-in-calendar '(calendar-backward-month 1))))
16907 (org-defkey map [?\e (shift right)]
16908 (lambda () (interactive)
16909 (org-eval-in-calendar '(calendar-forward-month 1))))
16910 (org-defkey map [?\e (shift up)]
16911 (lambda () (interactive)
16912 (org-eval-in-calendar '(calendar-backward-year 1))))
16913 (org-defkey map [?\e (shift down)]
16914 (lambda () (interactive)
16915 (org-eval-in-calendar '(calendar-forward-year 1))))
16916 (org-defkey map [(shift up)]
16917 (lambda () (interactive)
16918 (org-eval-in-calendar '(calendar-backward-week 1))))
16919 (org-defkey map [(shift down)]
16920 (lambda () (interactive)
16921 (org-eval-in-calendar '(calendar-forward-week 1))))
16922 (org-defkey map [(shift left)]
16923 (lambda () (interactive)
16924 (org-eval-in-calendar '(calendar-backward-day 1))))
16925 (org-defkey map [(shift right)]
16926 (lambda () (interactive)
16927 (org-eval-in-calendar '(calendar-forward-day 1))))
16928 (org-defkey map "!"
16929 (lambda () (interactive)
16930 (org-eval-in-calendar '(diary-view-entries))
16931 (message "")))
16932 (org-defkey map ">"
16933 (lambda () (interactive)
16934 (org-eval-in-calendar '(calendar-scroll-left 1))))
16935 (org-defkey map "<"
16936 (lambda () (interactive)
16937 (org-eval-in-calendar '(calendar-scroll-right 1))))
16938 (org-defkey map "\C-v"
16939 (lambda () (interactive)
16940 (org-eval-in-calendar
16941 '(calendar-scroll-left-three-months 1))))
16942 (org-defkey map "\M-v"
16943 (lambda () (interactive)
16944 (org-eval-in-calendar
16945 '(calendar-scroll-right-three-months 1))))
16946 map)
16947 "Keymap for minibuffer commands when using `org-read-date'.")
16949 (defvar org-def)
16950 (defvar org-defdecode)
16951 (defvar org-with-time)
16953 (defvar calendar-setup) ; Dynamically scoped.
16954 (defun org-read-date (&optional with-time to-time from-string prompt
16955 default-time default-input inactive)
16956 "Read a date, possibly a time, and make things smooth for the user.
16957 The prompt will suggest to enter an ISO date, but you can also enter anything
16958 which will at least partially be understood by `parse-time-string'.
16959 Unrecognized parts of the date will default to the current day, month, year,
16960 hour and minute. If this command is called to replace a timestamp at point,
16961 or to enter the second timestamp of a range, the default time is taken
16962 from the existing stamp. Furthermore, the command prefers the future,
16963 so if you are giving a date where the year is not given, and the day-month
16964 combination is already past in the current year, it will assume you
16965 mean next year. For details, see the manual. A few examples:
16967 3-2-5 --> 2003-02-05
16968 feb 15 --> currentyear-02-15
16969 2/15 --> currentyear-02-15
16970 sep 12 9 --> 2009-09-12
16971 12:45 --> today 12:45
16972 22 sept 0:34 --> currentyear-09-22 0:34
16973 12 --> currentyear-currentmonth-12
16974 Fri --> nearest Friday after today
16975 -Tue --> last Tuesday
16976 etc.
16978 Furthermore you can specify a relative date by giving, as the *first* thing
16979 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16980 change in days weeks, months, years.
16981 With a single plus or minus, the date is relative to today. With a double
16982 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16983 +4d --> four days from today
16984 +4 --> same as above
16985 +2w --> two weeks from today
16986 ++5 --> five days from default date
16988 The function understands only English month and weekday abbreviations.
16990 While prompting, a calendar is popped up - you can also select the
16991 date with the mouse (button 1). The calendar shows a period of three
16992 months. To scroll it to other months, use the keys `>' and `<'.
16993 If you don't like the calendar, turn it off with
16994 (setq org-read-date-popup-calendar nil)
16996 With optional argument TO-TIME, the date will immediately be converted
16997 to an internal time.
16998 With an optional argument WITH-TIME, the prompt will suggest to
16999 also insert a time. Note that when WITH-TIME is not set, you can
17000 still enter a time, and this function will inform the calling routine
17001 about this change. The calling routine may then choose to change the
17002 format used to insert the time stamp into the buffer to include the time.
17003 With optional argument FROM-STRING, read from this string instead from
17004 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17005 the time/date that is used for everything that is not specified by the
17006 user."
17007 (require 'parse-time)
17008 (let* ((org-with-time with-time)
17009 (org-time-stamp-rounding-minutes
17010 (if (equal org-with-time '(16))
17011 '(0 0)
17012 org-time-stamp-rounding-minutes))
17013 (org-dcst org-display-custom-times)
17014 (ct (org-current-time))
17015 (org-def (or org-overriding-default-time default-time ct))
17016 (org-defdecode (decode-time org-def))
17017 (cur-frame (selected-frame))
17018 (mouse-autoselect-window nil) ; Don't let the mouse jump
17019 (calendar-setup
17020 (and (eq calendar-setup 'calendar-only) 'calendar-only))
17021 (calendar-move-hook nil)
17022 (calendar-view-diary-initially-flag nil)
17023 (calendar-view-holidays-initially-flag nil)
17024 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
17025 ;; Rationalize `org-def' and `org-defdecode', if required.
17026 (when (< (nth 2 org-defdecode) org-extend-today-until)
17027 (setf (nth 2 org-defdecode) -1)
17028 (setf (nth 1 org-defdecode) 59)
17029 (setq org-def (apply #'encode-time org-defdecode))
17030 (setq org-defdecode (decode-time org-def)))
17031 (let* ((timestr (format-time-string
17032 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
17033 org-def))
17034 (prompt (concat (if prompt (concat prompt " ") "")
17035 (format "Date+time [%s]: " timestr))))
17036 (cond
17037 (from-string (setq ans from-string))
17038 (org-read-date-popup-calendar
17039 (save-excursion
17040 (save-window-excursion
17041 (calendar)
17042 (when (eq calendar-setup 'calendar-only)
17043 (setq cal-frame
17044 (window-frame (get-buffer-window "*Calendar*" 'visible)))
17045 (select-frame cal-frame))
17046 (org-eval-in-calendar '(setq cursor-type nil) t)
17047 (unwind-protect
17048 (progn
17049 (calendar-forward-day (- (time-to-days org-def)
17050 (calendar-absolute-from-gregorian
17051 (calendar-current-date))))
17052 (org-eval-in-calendar nil t)
17053 (let* ((old-map (current-local-map))
17054 (map (copy-keymap calendar-mode-map))
17055 (minibuffer-local-map
17056 (copy-keymap org-read-date-minibuffer-local-map)))
17057 (org-defkey map (kbd "RET") 'org-calendar-select)
17058 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17059 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17060 (unwind-protect
17061 (progn
17062 (use-local-map map)
17063 (setq org-read-date-inactive inactive)
17064 (add-hook 'post-command-hook 'org-read-date-display)
17065 (setq org-ans0
17066 (read-string prompt
17067 default-input
17068 'org-read-date-history
17069 nil))
17070 ;; org-ans0: from prompt
17071 ;; org-ans1: from mouse click
17072 ;; org-ans2: from calendar motion
17073 (setq ans
17074 (concat org-ans0 " " (or org-ans1 org-ans2))))
17075 (remove-hook 'post-command-hook 'org-read-date-display)
17076 (use-local-map old-map)
17077 (when org-read-date-overlay
17078 (delete-overlay org-read-date-overlay)
17079 (setq org-read-date-overlay nil)))))
17080 (bury-buffer "*Calendar*")
17081 (when cal-frame
17082 (delete-frame cal-frame)
17083 (select-frame-set-input-focus cur-frame))))))
17085 (t ; Naked prompt only
17086 (unwind-protect
17087 (setq ans (read-string prompt default-input
17088 'org-read-date-history timestr))
17089 (when org-read-date-overlay
17090 (delete-overlay org-read-date-overlay)
17091 (setq org-read-date-overlay nil))))))
17093 (setq final (org-read-date-analyze ans org-def org-defdecode))
17095 (when org-read-date-analyze-forced-year
17096 (message "Year was forced into %s"
17097 (if org-read-date-force-compatible-dates
17098 "compatible range (1970-2037)"
17099 "range representable on this machine"))
17100 (ding))
17102 ;; One round trip to get rid of 34th of August and stuff like that....
17103 (setq final (decode-time (apply 'encode-time final)))
17105 (setq org-read-date-final-answer ans)
17107 (if to-time
17108 (apply 'encode-time final)
17109 (if (and (boundp 'org-time-was-given) org-time-was-given)
17110 (format "%04d-%02d-%02d %02d:%02d"
17111 (nth 5 final) (nth 4 final) (nth 3 final)
17112 (nth 2 final) (nth 1 final))
17113 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17115 (defun org-read-date-display ()
17116 "Display the current date prompt interpretation in the minibuffer."
17117 (when org-read-date-display-live
17118 (when org-read-date-overlay
17119 (delete-overlay org-read-date-overlay))
17120 (when (minibufferp (current-buffer))
17121 (save-excursion
17122 (end-of-line 1)
17123 (while (not (equal (buffer-substring
17124 (max (point-min) (- (point) 4)) (point))
17125 " "))
17126 (insert " ")))
17127 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17128 " " (or org-ans1 org-ans2)))
17129 (org-end-time-was-given nil)
17130 (f (org-read-date-analyze ans org-def org-defdecode))
17131 (fmts (if org-dcst
17132 org-time-stamp-custom-formats
17133 org-time-stamp-formats))
17134 (fmt (if (or org-with-time
17135 (and (boundp 'org-time-was-given) org-time-was-given))
17136 (cdr fmts)
17137 (car fmts)))
17138 (txt (format-time-string fmt (apply 'encode-time f)))
17139 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17140 (txt (concat "=> " txt)))
17141 (when (and org-end-time-was-given
17142 (string-match org-plain-time-of-day-regexp txt))
17143 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17144 org-end-time-was-given
17145 (substring txt (match-end 0)))))
17146 (when org-read-date-analyze-futurep
17147 (setq txt (concat txt " (=>F)")))
17148 (setq org-read-date-overlay
17149 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17150 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17152 (defun org-read-date-analyze (ans def defdecode)
17153 "Analyze the combined answer of the date prompt."
17154 ;; FIXME: cleanup and comment
17155 ;; Pass `current-time' result to `decode-time' (instead of calling
17156 ;; without arguments) so that only `current-time' has to be
17157 ;; overriden in tests.
17158 (let ((org-def def)
17159 (org-defdecode defdecode)
17160 (nowdecode (decode-time (current-time)))
17161 delta deltan deltaw deltadef year month day
17162 hour minute second wday pm h2 m2 tl wday1
17163 iso-year iso-weekday iso-week iso-date futurep kill-year)
17164 (setq org-read-date-analyze-futurep nil
17165 org-read-date-analyze-forced-year nil)
17166 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17167 (setq ans "+0"))
17169 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17170 (setq ans (replace-match "" t t ans)
17171 deltan (car delta)
17172 deltaw (nth 1 delta)
17173 deltadef (nth 2 delta)))
17175 ;; Check if there is an iso week date in there. If yes, store the
17176 ;; info and postpone interpreting it until the rest of the parsing
17177 ;; is done.
17178 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17179 (setq iso-year (when (match-end 1)
17180 (org-small-year-to-year
17181 (string-to-number (match-string 1 ans))))
17182 iso-weekday (when (match-end 3)
17183 (string-to-number (match-string 3 ans)))
17184 iso-week (string-to-number (match-string 2 ans)))
17185 (setq ans (replace-match "" t t ans)))
17187 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17188 (when (string-match
17189 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17190 (setq year (if (match-end 2)
17191 (string-to-number (match-string 2 ans))
17192 (progn (setq kill-year t)
17193 (string-to-number (format-time-string "%Y"))))
17194 month (string-to-number (match-string 3 ans))
17195 day (string-to-number (match-string 4 ans)))
17196 (setq year (org-small-year-to-year year))
17197 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17198 t nil ans)))
17200 ;; Help matching dotted european dates
17201 (when (string-match
17202 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17203 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17204 (setq kill-year t)
17205 (string-to-number (format-time-string "%Y")))
17206 day (string-to-number (match-string 1 ans))
17207 month (string-to-number (match-string 2 ans))
17208 ans (replace-match (format "%04d-%02d-%02d" year month day)
17209 t nil ans)))
17211 ;; Help matching american dates, like 5/30 or 5/30/7
17212 (when (string-match
17213 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17214 (setq year (if (match-end 4)
17215 (string-to-number (match-string 4 ans))
17216 (progn (setq kill-year t)
17217 (string-to-number (format-time-string "%Y"))))
17218 month (string-to-number (match-string 1 ans))
17219 day (string-to-number (match-string 2 ans)))
17220 (setq year (org-small-year-to-year year))
17221 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17222 t nil ans)))
17223 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17224 ;; If there is a time with am/pm, and *no* time without it, we convert
17225 ;; so that matching will be successful.
17226 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17227 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17228 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17229 (setq hour (string-to-number (match-string 1 ans))
17230 minute (if (match-end 3)
17231 (string-to-number (match-string 3 ans))
17233 pm (equal ?p
17234 (string-to-char (downcase (match-string 4 ans)))))
17235 (if (and (= hour 12) (not pm))
17236 (setq hour 0)
17237 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17238 (setq ans (replace-match (format "%02d:%02d" hour minute)
17239 t t ans))))
17241 ;; Check if a time range is given as a duration
17242 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17243 (setq hour (string-to-number (match-string 1 ans))
17244 h2 (+ hour (string-to-number (match-string 3 ans)))
17245 minute (string-to-number (match-string 2 ans))
17246 m2 (+ minute (if (match-end 5) (string-to-number
17247 (match-string 5 ans))0)))
17248 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17249 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17250 t t ans)))
17252 ;; Check if there is a time range
17253 (when (boundp 'org-end-time-was-given)
17254 (setq org-time-was-given nil)
17255 (when (and (string-match org-plain-time-of-day-regexp ans)
17256 (match-end 8))
17257 (setq org-end-time-was-given (match-string 8 ans))
17258 (setq ans (concat (substring ans 0 (match-beginning 7))
17259 (substring ans (match-end 7))))))
17261 (setq tl (parse-time-string ans)
17262 day (or (nth 3 tl) (nth 3 org-defdecode))
17263 month
17264 (cond ((nth 4 tl))
17265 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17266 ;; Day was specified. Make sure DAY+MONTH
17267 ;; combination happens in the future.
17268 ((nth 3 tl)
17269 (setq futurep t)
17270 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17271 (nth 4 nowdecode)))
17272 (t (nth 4 org-defdecode)))
17273 year
17274 (cond ((and (not kill-year) (nth 5 tl)))
17275 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17276 ;; Month was guessed in the future and is at least
17277 ;; equal to NOWDECODE's. Fix year accordingly.
17278 (futurep
17279 (if (or (> month (nth 4 nowdecode))
17280 (>= day (nth 3 nowdecode)))
17281 (nth 5 nowdecode)
17282 (1+ (nth 5 nowdecode))))
17283 ;; Month was specified. Make sure MONTH+YEAR
17284 ;; combination happens in the future.
17285 ((nth 4 tl)
17286 (setq futurep t)
17287 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17288 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17289 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17290 (t (nth 5 nowdecode))))
17291 (t (nth 5 org-defdecode)))
17292 hour (or (nth 2 tl) (nth 2 org-defdecode))
17293 minute (or (nth 1 tl) (nth 1 org-defdecode))
17294 second (or (nth 0 tl) 0)
17295 wday (nth 6 tl))
17297 (when (and (eq org-read-date-prefer-future 'time)
17298 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17299 (equal day (nth 3 nowdecode))
17300 (equal month (nth 4 nowdecode))
17301 (equal year (nth 5 nowdecode))
17302 (nth 2 tl)
17303 (or (< (nth 2 tl) (nth 2 nowdecode))
17304 (and (= (nth 2 tl) (nth 2 nowdecode))
17305 (nth 1 tl)
17306 (< (nth 1 tl) (nth 1 nowdecode)))))
17307 (setq day (1+ day)
17308 futurep t))
17310 ;; Special date definitions below
17311 (cond
17312 (iso-week
17313 ;; There was an iso week
17314 (require 'cal-iso)
17315 (setq futurep nil)
17316 (setq year (or iso-year year)
17317 day (or iso-weekday wday 1)
17318 wday nil ; to make sure that the trigger below does not match
17319 iso-date (calendar-gregorian-from-absolute
17320 (calendar-iso-to-absolute
17321 (list iso-week day year))))
17322 ; FIXME: Should we also push ISO weeks into the future?
17323 ; (when (and org-read-date-prefer-future
17324 ; (not iso-year)
17325 ; (< (calendar-absolute-from-gregorian iso-date)
17326 ; (time-to-days (current-time))))
17327 ; (setq year (1+ year)
17328 ; iso-date (calendar-gregorian-from-absolute
17329 ; (calendar-iso-to-absolute
17330 ; (list iso-week day year)))))
17331 (setq month (car iso-date)
17332 year (nth 2 iso-date)
17333 day (nth 1 iso-date)))
17334 (deltan
17335 (setq futurep nil)
17336 (unless deltadef
17337 ;; Pass `current-time' result to `decode-time' (instead of
17338 ;; calling without arguments) so that only `current-time' has
17339 ;; to be overriden in tests.
17340 (let ((now (decode-time (current-time))))
17341 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17342 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17343 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17344 ((equal deltaw "m") (setq month (+ month deltan)))
17345 ((equal deltaw "y") (setq year (+ year deltan)))))
17346 ((and wday (not (nth 3 tl)))
17347 ;; Weekday was given, but no day, so pick that day in the week
17348 ;; on or after the derived date.
17349 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17350 (unless (equal wday wday1)
17351 (setq day (+ day (% (- wday wday1 -7) 7))))))
17352 (when (and (boundp 'org-time-was-given)
17353 (nth 2 tl))
17354 (setq org-time-was-given t))
17355 (when (< year 100) (setq year (+ 2000 year)))
17356 ;; Check of the date is representable
17357 (if org-read-date-force-compatible-dates
17358 (progn
17359 (when (< year 1970)
17360 (setq year 1970 org-read-date-analyze-forced-year t))
17361 (when (> year 2037)
17362 (setq year 2037 org-read-date-analyze-forced-year t)))
17363 (condition-case nil
17364 (ignore (encode-time second minute hour day month year))
17365 (error
17366 (setq year (nth 5 org-defdecode))
17367 (setq org-read-date-analyze-forced-year t))))
17368 (setq org-read-date-analyze-futurep futurep)
17369 (list second minute hour day month year)))
17371 (defvar parse-time-weekdays)
17372 (defun org-read-date-get-relative (s today default)
17373 "Check string S for special relative date string.
17374 TODAY and DEFAULT are internal times, for today and for a default.
17375 Return shift list (N what def-flag)
17376 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17377 N is the number of WHATs to shift.
17378 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17379 the DEFAULT date rather than TODAY."
17380 (require 'parse-time)
17381 (when (and
17382 (string-match
17383 (concat
17384 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17385 "\\([0-9]+\\)?"
17386 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17387 "\\([ \t]\\|$\\)") s)
17388 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17389 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17390 (string-to-char (substring (match-string 1 s) -1))
17391 ?+))
17392 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17393 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17394 (what (if (match-end 3) (match-string 3 s) "d"))
17395 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17396 (date (if rel default today))
17397 (wday (nth 6 (decode-time date)))
17398 delta)
17399 (if wday1
17400 (progn
17401 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17402 (when (= delta 0) (setq delta 7))
17403 (when (= dir ?-)
17404 (setq delta (- delta 7))
17405 (when (= delta 0) (setq delta -7)))
17406 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17407 (list delta "d" rel))
17408 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17410 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17411 "Turn a user-specified date into the internal representation.
17412 The internal representation needed by the calendar is (month day year).
17413 This is a wrapper to handle the brain-dead convention in calendar that
17414 user function argument order change dependent on argument order."
17415 (pcase calendar-date-style
17416 (`american (list arg1 arg2 arg3))
17417 (`european (list arg2 arg1 arg3))
17418 (`iso (list arg2 arg3 arg1))))
17420 (defun org-eval-in-calendar (form &optional keepdate)
17421 "Eval FORM in the calendar window and return to current window.
17422 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17423 (let ((sf (selected-frame))
17424 (sw (selected-window)))
17425 (select-window (get-buffer-window "*Calendar*" t))
17426 (eval form)
17427 (when (and (not keepdate) (calendar-cursor-to-date))
17428 (let* ((date (calendar-cursor-to-date))
17429 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17430 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17431 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17432 (select-window sw)
17433 (select-frame-set-input-focus sf)))
17435 (defun org-calendar-select ()
17436 "Return to `org-read-date' with the date currently selected.
17437 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17438 (interactive)
17439 (when (calendar-cursor-to-date)
17440 (let* ((date (calendar-cursor-to-date))
17441 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17442 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17443 (when (active-minibuffer-window) (exit-minibuffer))))
17445 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17446 "Insert a date stamp for the date given by the internal TIME.
17447 See `format-time-string' for the format of TIME.
17448 WITH-HM means use the stamp format that includes the time of the day.
17449 INACTIVE means use square brackets instead of angular ones, so that the
17450 stamp will not contribute to the agenda.
17451 PRE and POST are optional strings to be inserted before and after the
17452 stamp.
17453 The command returns the inserted time stamp."
17454 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17455 stamp)
17456 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17457 (insert-before-markers (or pre ""))
17458 (when (listp extra)
17459 (setq extra (car extra))
17460 (if (and (stringp extra)
17461 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17462 (setq extra (format "-%02d:%02d"
17463 (string-to-number (match-string 1 extra))
17464 (string-to-number (match-string 2 extra))))
17465 (setq extra nil)))
17466 (when extra
17467 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17468 (insert-before-markers (setq stamp (format-time-string fmt time)))
17469 (insert-before-markers (or post ""))
17470 (setq org-last-inserted-timestamp stamp)))
17472 (defun org-toggle-time-stamp-overlays ()
17473 "Toggle the use of custom time stamp formats."
17474 (interactive)
17475 (setq org-display-custom-times (not org-display-custom-times))
17476 (unless org-display-custom-times
17477 (let ((p (point-min)) (bmp (buffer-modified-p)))
17478 (while (setq p (next-single-property-change p 'display))
17479 (when (and (get-text-property p 'display)
17480 (eq (get-text-property p 'face) 'org-date))
17481 (remove-text-properties
17482 p (setq p (next-single-property-change p 'display))
17483 '(display t))))
17484 (set-buffer-modified-p bmp)))
17485 (org-restart-font-lock)
17486 (setq org-table-may-need-update t)
17487 (if org-display-custom-times
17488 (message "Time stamps are overlaid with custom format")
17489 (message "Time stamp overlays removed")))
17491 (defun org-display-custom-time (beg end)
17492 "Overlay modified time stamp format over timestamp between BEG and END."
17493 (let* ((ts (buffer-substring beg end))
17494 t1 w1 with-hm tf time str w2 (off 0))
17495 (save-match-data
17496 (setq t1 (org-parse-time-string ts t))
17497 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17498 (setq off (- (match-end 0) (match-beginning 0)))))
17499 (setq end (- end off))
17500 (setq w1 (- end beg)
17501 with-hm (and (nth 1 t1) (nth 2 t1))
17502 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17503 time (org-fix-decoded-time t1)
17504 str (org-add-props
17505 (format-time-string
17506 (substring tf 1 -1) (apply 'encode-time time))
17507 nil 'mouse-face 'highlight)
17508 w2 (length str))
17509 (unless (= w2 w1)
17510 (add-text-properties (1+ beg) (+ 2 beg)
17511 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17512 (put-text-property beg end 'display str)))
17514 (defun org-fix-decoded-time (time)
17515 "Set 0 instead of nil for the first 6 elements of time.
17516 Don't touch the rest."
17517 (let ((n 0))
17518 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17520 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17521 "Difference between TIMESTAMP-STRING and now in days.
17522 If SECONDS is non-nil, return the difference in seconds."
17523 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17524 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17525 (funcall fdiff (current-time)))))
17527 (defun org-deadline-close-p (timestamp-string &optional ndays)
17528 "Is the time in TIMESTAMP-STRING close to the current date?"
17529 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17530 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17531 (not (org-entry-is-done-p))))
17533 (defun org-get-wdays (ts &optional delay zero-delay)
17534 "Get the deadline lead time appropriate for timestring TS.
17535 When DELAY is non-nil, get the delay time for scheduled items
17536 instead of the deadline lead time. When ZERO-DELAY is non-nil
17537 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17538 don't try to find the delay cookie in the scheduled timestamp."
17539 (let ((tv (if delay org-scheduled-delay-days
17540 org-deadline-warning-days)))
17541 (cond
17542 ((or (and delay (< tv 0))
17543 (and delay zero-delay (<= tv 0))
17544 (and (not delay) (<= tv 0)))
17545 ;; Enforce this value no matter what
17546 (- tv))
17547 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17548 ;; lead time is specified.
17549 (floor (* (string-to-number (match-string 1 ts))
17550 (cdr (assoc (match-string 2 ts)
17551 '(("d" . 1) ("w" . 7)
17552 ("m" . 30.4) ("y" . 365.25)
17553 ("h" . 0.041667)))))))
17554 ;; go for the default.
17555 (t tv))))
17557 (defun org-calendar-select-mouse (ev)
17558 "Return to `org-read-date' with the date currently selected.
17559 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17560 (interactive "e")
17561 (mouse-set-point ev)
17562 (when (calendar-cursor-to-date)
17563 (let* ((date (calendar-cursor-to-date))
17564 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17565 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17566 (when (active-minibuffer-window) (exit-minibuffer))))
17568 (defun org-check-deadlines (ndays)
17569 "Check if there are any deadlines due or past due.
17570 A deadline is considered due if it happens within `org-deadline-warning-days'
17571 days from today's date. If the deadline appears in an entry marked DONE,
17572 it is not shown. A numeric prefix argument NDAYS can be used to test that
17573 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17574 are shown."
17575 (interactive "P")
17576 (let* ((org-warn-days
17577 (cond
17578 ((equal ndays '(4)) 100000)
17579 (ndays (prefix-numeric-value ndays))
17580 (t (abs org-deadline-warning-days))))
17581 (case-fold-search nil)
17582 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17583 (callback
17584 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17585 (message "%d deadlines past-due or due within %d days"
17586 (org-occur regexp nil callback)
17587 org-warn-days)))
17589 (defsubst org-re-timestamp (type)
17590 "Return a regexp for timestamp TYPE.
17591 Allowed values for TYPE are:
17593 all: all timestamps
17594 active: only active timestamps (<...>)
17595 inactive: only inactive timestamps ([...])
17596 scheduled: only scheduled timestamps
17597 deadline: only deadline timestamps
17598 closed: only closed time-stamps
17600 When TYPE is nil, fall back on returning a regexp that matches
17601 both scheduled and deadline timestamps."
17602 (cl-case type
17603 (all org-ts-regexp-both)
17604 (active org-ts-regexp)
17605 (inactive org-ts-regexp-inactive)
17606 (scheduled org-scheduled-time-regexp)
17607 (deadline org-deadline-time-regexp)
17608 (closed org-closed-time-regexp)
17609 (otherwise
17610 (concat "\\<"
17611 (regexp-opt (list org-deadline-string org-scheduled-string))
17612 " *<\\([^>]+\\)>"))))
17614 (defun org-check-before-date (d)
17615 "Check if there are deadlines or scheduled entries before date D."
17616 (interactive (list (org-read-date)))
17617 (let* ((case-fold-search nil)
17618 (regexp (org-re-timestamp org-ts-type))
17619 (ts-type org-ts-type)
17620 (callback
17621 (lambda ()
17622 (let ((match (match-string 1)))
17623 (and (if (memq ts-type '(active inactive all))
17624 (eq (org-element-type (save-excursion
17625 (backward-char)
17626 (org-element-context)))
17627 'timestamp)
17628 (org-at-planning-p))
17629 (time-less-p
17630 (org-time-string-to-time match)
17631 (org-time-string-to-time d)))))))
17632 (message "%d entries before %s"
17633 (org-occur regexp nil callback)
17634 d)))
17636 (defun org-check-after-date (d)
17637 "Check if there are deadlines or scheduled entries after date D."
17638 (interactive (list (org-read-date)))
17639 (let* ((case-fold-search nil)
17640 (regexp (org-re-timestamp org-ts-type))
17641 (ts-type org-ts-type)
17642 (callback
17643 (lambda ()
17644 (let ((match (match-string 1)))
17645 (and (if (memq ts-type '(active inactive all))
17646 (eq (org-element-type (save-excursion
17647 (backward-char)
17648 (org-element-context)))
17649 'timestamp)
17650 (org-at-planning-p))
17651 (not (time-less-p
17652 (org-time-string-to-time match)
17653 (org-time-string-to-time d))))))))
17654 (message "%d entries after %s"
17655 (org-occur regexp nil callback)
17656 d)))
17658 (defun org-check-dates-range (start-date end-date)
17659 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17660 (interactive (list (org-read-date nil nil nil "Range starts")
17661 (org-read-date nil nil nil "Range end")))
17662 (let ((case-fold-search nil)
17663 (regexp (org-re-timestamp org-ts-type))
17664 (callback
17665 (let ((type org-ts-type))
17666 (lambda ()
17667 (let ((match (match-string 1)))
17668 (and
17669 (if (memq type '(active inactive all))
17670 (eq (org-element-type (save-excursion
17671 (backward-char)
17672 (org-element-context)))
17673 'timestamp)
17674 (org-at-planning-p))
17675 (not (time-less-p
17676 (org-time-string-to-time match)
17677 (org-time-string-to-time start-date)))
17678 (time-less-p
17679 (org-time-string-to-time match)
17680 (org-time-string-to-time end-date))))))))
17681 (message "%d entries between %s and %s"
17682 (org-occur regexp nil callback) start-date end-date)))
17684 (defun org-evaluate-time-range (&optional to-buffer)
17685 "Evaluate a time range by computing the difference between start and end.
17686 Normally the result is just printed in the echo area, but with prefix arg
17687 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17688 If the time range is actually in a table, the result is inserted into the
17689 next column.
17690 For time difference computation, a year is assumed to be exactly 365
17691 days in order to avoid rounding problems."
17692 (interactive "P")
17694 (org-clock-update-time-maybe)
17695 (save-excursion
17696 (unless (org-at-date-range-p t)
17697 (goto-char (point-at-bol))
17698 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17699 (unless (org-at-date-range-p t)
17700 (user-error "Not at a time-stamp range, and none found in current line")))
17701 (let* ((ts1 (match-string 1))
17702 (ts2 (match-string 2))
17703 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17704 (match-end (match-end 0))
17705 (time1 (org-time-string-to-time ts1))
17706 (time2 (org-time-string-to-time ts2))
17707 (t1 (float-time time1))
17708 (t2 (float-time time2))
17709 (diff (abs (- t2 t1)))
17710 (negative (< (- t2 t1) 0))
17711 ;; (ys (floor (* 365 24 60 60)))
17712 (ds (* 24 60 60))
17713 (hs (* 60 60))
17714 (fy "%dy %dd %02d:%02d")
17715 (fy1 "%dy %dd")
17716 (fd "%dd %02d:%02d")
17717 (fd1 "%dd")
17718 (fh "%02d:%02d")
17719 y d h m align)
17720 (if havetime
17721 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17723 d (floor (/ diff ds)) diff (mod diff ds)
17724 h (floor (/ diff hs)) diff (mod diff hs)
17725 m (floor (/ diff 60)))
17726 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17728 d (floor (+ (/ diff ds) 0.5))
17729 h 0 m 0))
17730 (if (not to-buffer)
17731 (message "%s" (org-make-tdiff-string y d h m))
17732 (if (org-at-table-p)
17733 (progn
17734 (goto-char match-end)
17735 (setq align t)
17736 (and (looking-at " *|") (goto-char (match-end 0))))
17737 (goto-char match-end))
17738 (when (looking-at
17739 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17740 (replace-match ""))
17741 (when negative (insert " -"))
17742 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17743 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17744 (insert " " (format fh h m))))
17745 (when align (org-table-align))
17746 (message "Time difference inserted")))))
17748 (defun org-make-tdiff-string (y d h m)
17749 (let ((fmt "")
17750 (l nil))
17751 (when (> y 0)
17752 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17753 (push y l))
17754 (when (> d 0)
17755 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17756 (push d l))
17757 (when (> h 0)
17758 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17759 (push h l))
17760 (when (> m 0)
17761 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17762 (push m l))
17763 (apply 'format fmt (nreverse l))))
17765 (defun org-time-string-to-time (s &optional buffer pos)
17766 "Convert a timestamp string into internal time."
17767 (condition-case errdata
17768 (apply 'encode-time (org-parse-time-string s))
17769 (error (error "Bad timestamp `%s'%s\nError was: %s"
17770 s (if (not (and buffer pos))
17772 (format-message " at %d in buffer `%s'" pos buffer))
17773 (cdr errdata)))))
17775 (defun org-time-string-to-seconds (s)
17776 "Convert a timestamp string to a number of seconds."
17777 (float-time (org-time-string-to-time s)))
17779 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17781 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17782 "Convert time stamp S to an absolute day number.
17784 If DAYNR in non-nil, and there is a specifier for a cyclic time
17785 stamp, get the closest date to DAYNR. If PREFER is
17786 `past' (respectively `future') return a date past (respectively
17787 after) or equal to DAYNR.
17789 POS is the location of time stamp S, as a buffer position in
17790 BUFFER.
17792 Diary sexp timestamps are matched against DAYNR, when non-nil.
17793 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17794 signalled."
17795 (cond
17796 ((string-match "\\`%%\\((.*)\\)" s)
17797 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17798 ;; only able to match individual dates. If it fails, raise an
17799 ;; error.
17800 (if (and daynr
17801 (org-diary-sexp-entry
17802 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17803 daynr
17804 (signal 'org-diary-sexp-no-match (list s))))
17805 ((and daynr show-all) (org-closest-date s daynr prefer))
17806 (t (time-to-days
17807 (condition-case errdata
17808 (apply #'encode-time (org-parse-time-string s))
17809 (error (error "Bad timestamp `%s'%s\nError was: %s"
17811 (if (not (and buffer pos)) ""
17812 (format-message " at %d in buffer `%s'" pos buffer))
17813 (cdr errdata))))))))
17815 (defun org-days-to-iso-week (days)
17816 "Return the iso week number."
17817 (require 'cal-iso)
17818 (car (calendar-iso-from-absolute days)))
17820 (defun org-small-year-to-year (year)
17821 "Convert 2-digit years into 4-digit years.
17822 YEAR is expanded into one of the 30 next years, if possible, or
17823 into a past one. Any year larger than 99 is returned unchanged."
17824 (if (>= year 100) year
17825 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17826 (century (/ current 100))
17827 (offset (- year (% current 100))))
17828 (cond ((> offset 30) (+ (* (1- century) 100) year))
17829 ((> offset -70) (+ (* century 100) year))
17830 (t (+ (* (1+ century) 100) year))))))
17832 (defun org-time-from-absolute (d)
17833 "Return the time corresponding to date D.
17834 D may be an absolute day number, or a calendar-type list (month day year)."
17835 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17836 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17838 (defvar org-agenda-current-date)
17839 (defun org-calendar-holiday ()
17840 "List of holidays, for Diary display in Org mode."
17841 (require 'holidays)
17842 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17843 (and hl (mapconcat #'identity hl "; "))))
17845 (defun org-diary-sexp-entry (sexp entry d)
17846 "Process a SEXP diary ENTRY for date D."
17847 (require 'diary-lib)
17848 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17849 ;; dynamically.
17850 (let* ((sexp `(let ((entry ,entry)
17851 (date ',d))
17852 ,(car (read-from-string sexp))))
17853 (result (if calendar-debug-sexp (eval sexp)
17854 (condition-case nil
17855 (eval sexp)
17856 (error
17857 (beep)
17858 (message "Bad sexp at line %d in %s: %s"
17859 (org-current-line)
17860 (buffer-file-name) sexp)
17861 (sleep-for 2))))))
17862 (cond ((stringp result) (split-string result "; "))
17863 ((and (consp result)
17864 (not (consp (cdr result)))
17865 (stringp (cdr result))) (cdr result))
17866 ((and (consp result)
17867 (stringp (car result))) result)
17868 (result entry))))
17870 (defun org-diary-to-ical-string (frombuf)
17871 "Get iCalendar entries from diary entries in buffer FROMBUF.
17872 This uses the icalendar.el library."
17873 (let* ((tmpdir temporary-file-directory)
17874 (tmpfile (make-temp-name
17875 (expand-file-name "orgics" tmpdir)))
17876 buf rtn b e)
17877 (with-current-buffer frombuf
17878 (icalendar-export-region (point-min) (point-max) tmpfile)
17879 (setq buf (find-buffer-visiting tmpfile))
17880 (set-buffer buf)
17881 (goto-char (point-min))
17882 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17883 (setq b (match-beginning 0)))
17884 (goto-char (point-max))
17885 (when (re-search-backward "^END:VEVENT" nil t)
17886 (setq e (match-end 0)))
17887 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17888 (kill-buffer buf)
17889 (delete-file tmpfile)
17890 rtn))
17892 (defun org-closest-date (start current prefer)
17893 "Return closest date to CURRENT starting from START.
17895 CURRENT and START are both time stamps.
17897 When PREFER is `past', return a date that is either CURRENT or
17898 past. When PREFER is `future', return a date that is either
17899 CURRENT or future.
17901 Only time stamps with a repeater are modified. Any other time
17902 stamp stay unchanged. In any case, return value is an absolute
17903 day number."
17904 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17905 ;; No repeater. Do not shift time stamp.
17906 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17907 (let ((value (string-to-number (match-string 1 start)))
17908 (type (match-string 2 start)))
17909 (if (= 0 value)
17910 ;; Repeater with a 0-value is considered as void.
17911 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17912 (let* ((base (org-date-to-gregorian start))
17913 (target (org-date-to-gregorian current))
17914 (sday (calendar-absolute-from-gregorian base))
17915 (cday (calendar-absolute-from-gregorian target))
17916 n1 n2)
17917 ;; If START is already past CURRENT, just return START.
17918 (if (<= cday sday) sday
17919 ;; Compute closest date before (N1) and closest date past
17920 ;; (N2) CURRENT.
17921 (pcase type
17922 ("h"
17923 (let ((missing-hours
17924 (mod (+ (- (* 24 (- cday sday))
17925 (nth 2 (org-parse-time-string start)))
17926 org-extend-today-until)
17927 value)))
17928 (setf n1 (if (= missing-hours 0) cday
17929 (- cday (1+ (/ missing-hours 24)))))
17930 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17931 ((or "d" "w")
17932 (let ((value (if (equal type "w") (* 7 value) value)))
17933 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17934 (setf n2 (+ n1 value))))
17935 ("m"
17936 (let* ((add-months
17937 (lambda (d n)
17938 ;; Add N months to gregorian date D, i.e.,
17939 ;; a list (MONTH DAY YEAR). Return a valid
17940 ;; gregorian date.
17941 (let ((m (+ (nth 0 d) n)))
17942 (list (mod m 12)
17943 (nth 1 d)
17944 (+ (/ m 12) (nth 2 d))))))
17945 (months ; Complete months to TARGET.
17946 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17947 (- (nth 0 target) (nth 0 base))
17948 ;; If START's day is greater than
17949 ;; TARGET's, remove incomplete month.
17950 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17951 value)
17952 value))
17953 (before (funcall add-months base months)))
17954 (setf n1 (calendar-absolute-from-gregorian before))
17955 (setf n2
17956 (calendar-absolute-from-gregorian
17957 (funcall add-months before value)))))
17959 (let* ((d (nth 1 base))
17960 (m (nth 0 base))
17961 (y (nth 2 base))
17962 (years ; Complete years to TARGET.
17963 (* (/ (- (nth 2 target)
17965 ;; If START's month and day are
17966 ;; greater than TARGET's, remove
17967 ;; incomplete year.
17968 (if (or (> (nth 0 target) m)
17969 (and (= (nth 0 target) m)
17970 (> (nth 1 target) d)))
17973 value)
17974 value))
17975 (before (list m d (+ y years))))
17976 (setf n1 (calendar-absolute-from-gregorian before))
17977 (setf n2 (calendar-absolute-from-gregorian
17978 (list m d (+ (nth 2 before) value)))))))
17979 ;; Handle PREFER parameter, if any.
17980 (cond
17981 ((eq prefer 'past) (if (= cday n2) n2 n1))
17982 ((eq prefer 'future) (if (= cday n1) n1 n2))
17983 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17985 (defun org-date-to-gregorian (d)
17986 "Turn any specification of date D into a Gregorian date for the calendar."
17987 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17988 ((and (listp d) (= (length d) 3)) d)
17989 ((stringp d)
17990 (let ((d (org-parse-time-string d)))
17991 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17992 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17994 (defun org-parse-time-string (s &optional nodefault)
17995 "Parse the standard Org time string.
17996 This should be a lot faster than the normal `parse-time-string'.
17997 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17998 hour and minute fields will be nil if not given."
17999 (cond ((string-match org-ts-regexp0 s)
18000 (list 0
18001 (when (or (match-beginning 8) (not nodefault))
18002 (string-to-number (or (match-string 8 s) "0")))
18003 (when (or (match-beginning 7) (not nodefault))
18004 (string-to-number (or (match-string 7 s) "0")))
18005 (string-to-number (match-string 4 s))
18006 (string-to-number (match-string 3 s))
18007 (string-to-number (match-string 2 s))
18008 nil nil nil))
18009 ((string-match "^<[^>]+>$" s)
18010 (decode-time (seconds-to-time (org-matcher-time s))))
18011 (t (error "Not a standard Org time string: %s" s))))
18013 (defun org-timestamp-up (&optional arg)
18014 "Increase the date item at the cursor by one.
18015 If the cursor is on the year, change the year. If it is on the month,
18016 the day or the time, change that.
18017 With prefix ARG, change by that many units."
18018 (interactive "p")
18019 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
18021 (defun org-timestamp-down (&optional arg)
18022 "Decrease the date item at the cursor by one.
18023 If the cursor is on the year, change the year. If it is on the month,
18024 the day or the time, change that.
18025 With prefix ARG, change by that many units."
18026 (interactive "p")
18027 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
18029 (defun org-timestamp-up-day (&optional arg)
18030 "Increase the date in the time stamp by one day.
18031 With prefix ARG, change that many days."
18032 (interactive "p")
18033 (if (and (not (org-at-timestamp-p t))
18034 (org-at-heading-p))
18035 (org-todo 'up)
18036 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
18038 (defun org-timestamp-down-day (&optional arg)
18039 "Decrease the date in the time stamp by one day.
18040 With prefix ARG, change that many days."
18041 (interactive "p")
18042 (if (and (not (org-at-timestamp-p t))
18043 (org-at-heading-p))
18044 (org-todo 'down)
18045 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
18047 (defun org-at-timestamp-p (&optional inactive-ok)
18048 "Non-nil if point is inside a timestamp.
18050 When optional argument INACTIVE-OK is non-nil, also consider
18051 inactive timestamps.
18053 When this function returns a non-nil value, match data is set
18054 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18055 INACTIVE-OK."
18056 (interactive)
18057 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18058 (pos (point))
18059 (ans (or (looking-at tsr)
18060 (save-excursion
18061 (skip-chars-backward "^[<\n\r\t")
18062 (when (> (point) (point-min)) (backward-char 1))
18063 (and (looking-at tsr)
18064 (> (- (match-end 0) pos) -1))))))
18065 (and ans
18066 (boundp 'org-ts-what)
18067 (setq org-ts-what
18068 (cond
18069 ((= pos (match-beginning 0)) 'bracket)
18070 ;; Point is considered to be "on the bracket" whether
18071 ;; it's really on it or right after it.
18072 ((= pos (1- (match-end 0))) 'bracket)
18073 ((= pos (match-end 0)) 'after)
18074 ((org-pos-in-match-range pos 2) 'year)
18075 ((org-pos-in-match-range pos 3) 'month)
18076 ((org-pos-in-match-range pos 7) 'hour)
18077 ((org-pos-in-match-range pos 8) 'minute)
18078 ((or (org-pos-in-match-range pos 4)
18079 (org-pos-in-match-range pos 5)) 'day)
18080 ((and (> pos (or (match-end 8) (match-end 5)))
18081 (< pos (match-end 0)))
18082 (- pos (or (match-end 8) (match-end 5))))
18083 (t 'day))))
18084 ans))
18086 (defun org-toggle-timestamp-type ()
18087 "Toggle the type (<active> or [inactive]) of a time stamp."
18088 (interactive)
18089 (when (org-at-timestamp-p t)
18090 (let ((beg (match-beginning 0)) (end (match-end 0))
18091 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18092 (save-excursion
18093 (goto-char beg)
18094 (while (re-search-forward "[][<>]" end t)
18095 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18096 t t)))
18097 (message "Timestamp is now %sactive"
18098 (if (equal (char-after beg) ?<) "" "in")))))
18100 (defun org-at-clock-log-p nil
18101 "Is the cursor on the clock log line?"
18102 (save-excursion
18103 (move-beginning-of-line 1)
18104 (looking-at org-clock-line-re)))
18106 (defvar org-clock-history) ; defined in org-clock.el
18107 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18108 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18109 "Change the date in the time stamp at point.
18110 The date will be changed by N times WHAT. WHAT can be `day', `month',
18111 `year', `minute', `second'. If WHAT is not given, the cursor position
18112 in the timestamp determines what will be changed.
18113 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18114 (let ((origin (point)) origin-cat
18115 with-hm inactive
18116 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18117 org-ts-what
18118 extra rem
18119 ts time time0 fixnext clrgx)
18120 (unless (org-at-timestamp-p t)
18121 (user-error "Not at a timestamp"))
18122 (if (and (not what) (eq org-ts-what 'bracket))
18123 (org-toggle-timestamp-type)
18124 ;; Point isn't on brackets. Remember the part of the time-stamp
18125 ;; the point was in. Indeed, size of time-stamps may change,
18126 ;; but point must be kept in the same category nonetheless.
18127 (setq origin-cat org-ts-what)
18128 (when (and (not what) (not (eq org-ts-what 'day))
18129 org-display-custom-times
18130 (get-text-property (point) 'display)
18131 (not (get-text-property (1- (point)) 'display)))
18132 (setq org-ts-what 'day))
18133 (setq org-ts-what (or what org-ts-what)
18134 inactive (= (char-after (match-beginning 0)) ?\[)
18135 ts (match-string 0))
18136 (replace-match "")
18137 (when (string-match
18138 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18140 (setq extra (match-string 1 ts))
18141 (when suppress-tmp-delay
18142 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18143 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18144 (setq with-hm t))
18145 (setq time0 (org-parse-time-string ts))
18146 (when (and updown
18147 (eq org-ts-what 'minute)
18148 (not current-prefix-arg))
18149 ;; This looks like s-up and s-down. Change by one rounding step.
18150 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18151 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18152 (setcar (cdr time0) (+ (nth 1 time0)
18153 (if (> n 0) (- rem) (- dm rem))))))
18154 (setq time
18155 (apply #'encode-time
18156 (or (car time0) 0)
18157 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18158 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18159 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18160 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18161 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18162 (nthcdr 6 time0)))
18163 (when (and (member org-ts-what '(hour minute))
18164 extra
18165 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18166 (setq extra (org-modify-ts-extra
18167 extra
18168 (if (eq org-ts-what 'hour) 2 5)
18169 n dm)))
18170 (when (integerp org-ts-what)
18171 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18172 (when (eq what 'calendar)
18173 (let ((cal-date (org-get-date-from-calendar)))
18174 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18175 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18176 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18177 (setcar time0 (or (car time0) 0))
18178 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18179 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18180 (setq time (apply 'encode-time time0))))
18181 ;; Insert the new time-stamp, and ensure point stays in the same
18182 ;; category as before (i.e. not after the last position in that
18183 ;; category).
18184 (let ((pos (point)))
18185 ;; Stay before inserted string. `save-excursion' is of no use.
18186 (setq org-last-changed-timestamp
18187 (org-insert-time-stamp time with-hm inactive nil nil extra))
18188 (goto-char pos))
18189 (save-match-data
18190 (looking-at org-ts-regexp3)
18191 (goto-char (cond
18192 ;; `day' category ends before `hour' if any, or at
18193 ;; the end of the day name.
18194 ((eq origin-cat 'day)
18195 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18196 ((eq origin-cat 'hour) (min (match-end 7) origin))
18197 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18198 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18199 ;; `year' and `month' have both fixed size: point
18200 ;; couldn't have moved into another part.
18201 (t origin))))
18202 ;; Update clock if on a CLOCK line.
18203 (org-clock-update-time-maybe)
18204 ;; Maybe adjust the closest clock in `org-clock-history'
18205 (when org-clock-adjust-closest
18206 (if (not (and (org-at-clock-log-p)
18207 (< 1 (length (delq nil (mapcar 'marker-position
18208 org-clock-history))))))
18209 (message "No clock to adjust")
18210 (cond ((save-excursion ; fix previous clock?
18211 (re-search-backward org-ts-regexp0 nil t)
18212 (looking-back (concat org-clock-string " \\[")
18213 (line-beginning-position)))
18214 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18215 ((save-excursion ; fix next clock?
18216 (re-search-backward org-ts-regexp0 nil t)
18217 (looking-at (concat org-ts-regexp0 "\\] =>")))
18218 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18219 (save-window-excursion
18220 ;; Find closest clock to point, adjust the previous/next one in history
18221 (let* ((p (save-excursion (org-back-to-heading t)))
18222 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18223 (clfixnth
18224 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18225 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18226 (if (not clfixpos)
18227 (message "No clock to adjust")
18228 (save-excursion
18229 (org-goto-marker-or-bmk clfixpos)
18230 (org-show-subtree)
18231 (when (re-search-forward clrgx nil t)
18232 (goto-char (match-beginning 1))
18233 (let (org-clock-adjust-closest)
18234 (org-timestamp-change n org-ts-what updown))
18235 (message "Clock adjusted in %s for heading: %s"
18236 (file-name-nondirectory (buffer-file-name))
18237 (org-get-heading t t)))))))))
18238 ;; Try to recenter the calendar window, if any.
18239 (when (and org-calendar-follow-timestamp-change
18240 (get-buffer-window "*Calendar*" t)
18241 (memq org-ts-what '(day month year)))
18242 (org-recenter-calendar (time-to-days time))))))
18244 (defun org-modify-ts-extra (s pos n dm)
18245 "Change the different parts of the lead-time and repeat fields in timestamp."
18246 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18247 ng h m new rem)
18248 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18249 (cond
18250 ((or (org-pos-in-match-range pos 2)
18251 (org-pos-in-match-range pos 3))
18252 (setq m (string-to-number (match-string 3 s))
18253 h (string-to-number (match-string 2 s)))
18254 (if (org-pos-in-match-range pos 2)
18255 (setq h (+ h n))
18256 (setq n (* dm (with-no-warnings (signum n))))
18257 (unless (= 0 (setq rem (% m dm)))
18258 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18259 (setq m (+ m n)))
18260 (when (< m 0) (setq m (+ m 60) h (1- h)))
18261 (when (> m 59) (setq m (- m 60) h (1+ h)))
18262 (setq h (mod h 24))
18263 (setq ng 1 new (format "-%02d:%02d" h m)))
18264 ((org-pos-in-match-range pos 6)
18265 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18266 ((org-pos-in-match-range pos 5)
18267 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18269 ((org-pos-in-match-range pos 9)
18270 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18271 ((org-pos-in-match-range pos 8)
18272 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18274 (when ng
18275 (setq s (concat
18276 (substring s 0 (match-beginning ng))
18278 (substring s (match-end ng))))))
18281 (defun org-recenter-calendar (d)
18282 "If the calendar is visible, recenter it to date D."
18283 (let ((cwin (get-buffer-window "*Calendar*" t)))
18284 (when cwin
18285 (let ((calendar-move-hook nil))
18286 (with-selected-window cwin
18287 (calendar-goto-date
18288 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18290 (defun org-goto-calendar (&optional arg)
18291 "Go to the Emacs calendar at the current date.
18292 If there is a time stamp in the current line, go to that date.
18293 A prefix ARG can be used to force the current date."
18294 (interactive "P")
18295 (let ((tsr org-ts-regexp) diff
18296 (calendar-move-hook nil)
18297 (calendar-view-holidays-initially-flag nil)
18298 (calendar-view-diary-initially-flag nil))
18299 (when (or (org-at-timestamp-p)
18300 (save-excursion
18301 (beginning-of-line 1)
18302 (looking-at (concat ".*" tsr))))
18303 (let ((d1 (time-to-days (current-time)))
18304 (d2 (time-to-days
18305 (org-time-string-to-time (match-string 1)))))
18306 (setq diff (- d2 d1))))
18307 (calendar)
18308 (calendar-goto-today)
18309 (when (and diff (not arg)) (calendar-forward-day diff))))
18311 (defun org-get-date-from-calendar ()
18312 "Return a list (month day year) of date at point in calendar."
18313 (with-current-buffer "*Calendar*"
18314 (save-match-data
18315 (calendar-cursor-to-date))))
18317 (defun org-date-from-calendar ()
18318 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18319 If there is already a time stamp at the cursor position, update it."
18320 (interactive)
18321 (if (org-at-timestamp-p t)
18322 (org-timestamp-change 0 'calendar)
18323 (let ((cal-date (org-get-date-from-calendar)))
18324 (org-insert-time-stamp
18325 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18327 (defcustom org-effort-durations
18328 `(("min" . 1)
18329 ("h" . 60)
18330 ("d" . ,(* 60 8))
18331 ("w" . ,(* 60 8 5))
18332 ("m" . ,(* 60 8 5 4))
18333 ("y" . ,(* 60 8 5 40)))
18334 "Conversion factor to minutes for an effort modifier.
18336 Each entry has the form (MODIFIER . MINUTES).
18338 In an effort string, a number followed by MODIFIER is multiplied
18339 by the specified number of MINUTES to obtain an effort in
18340 minutes.
18342 For example, if the value of this variable is ((\"hours\" . 60)), then an
18343 effort string \"2hours\" is equivalent to 120 minutes."
18344 :group 'org-agenda
18345 :version "25.2"
18346 :package-version '(Org . "8.3")
18347 :type '(alist :key-type (string :tag "Modifier")
18348 :value-type (number :tag "Minutes")))
18350 (defun org-minutes-to-clocksum-string (m)
18351 "Format number of minutes as a clocksum string.
18352 The format is determined by `org-time-clocksum-format',
18353 `org-time-clocksum-use-fractional' and
18354 `org-time-clocksum-fractional-format' and
18355 `org-time-clocksum-use-effort-durations'."
18356 (let ((clocksum "")
18357 (m (round m)) ; Don't allow fractions of minutes
18358 h d w mo y fmt n)
18359 (setq h (if org-time-clocksum-use-effort-durations
18360 (cdr (assoc "h" org-effort-durations)) 60)
18361 d (if org-time-clocksum-use-effort-durations
18362 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18363 w (if org-time-clocksum-use-effort-durations
18364 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18365 mo (if org-time-clocksum-use-effort-durations
18366 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18367 y (if org-time-clocksum-use-effort-durations
18368 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18369 ;; fractional format
18370 (if org-time-clocksum-use-fractional
18371 (cond
18372 ;; single format string
18373 ((stringp org-time-clocksum-fractional-format)
18374 (format org-time-clocksum-fractional-format (/ m (float h))))
18375 ;; choice of fractional formats for different time units
18376 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18377 (> (/ (truncate m) (* y d h)) 0))
18378 (format fmt (/ m (* y d (float h)))))
18379 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18380 (> (/ (truncate m) (* mo d h)) 0))
18381 (format fmt (/ m (* mo d (float h)))))
18382 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18383 (> (/ (truncate m) (* w d h)) 0))
18384 (format fmt (/ m (* w d (float h)))))
18385 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18386 (> (/ (truncate m) (* d h)) 0))
18387 (format fmt (/ m (* d (float h)))))
18388 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18389 (> (/ (truncate m) h) 0))
18390 (format fmt (/ m (float h))))
18391 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18392 (format fmt m))
18393 ;; fall back to smallest time unit with a format
18394 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18395 (format fmt (/ m (float h))))
18396 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18397 (format fmt (/ m (* d (float h)))))
18398 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18399 (format fmt (/ m (* w d (float h)))))
18400 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18401 (format fmt (/ m (* mo d (float h)))))
18402 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18403 (format fmt (/ m (* y d (float h))))))
18404 ;; standard (non-fractional) format, with single format string
18405 (if (stringp org-time-clocksum-format)
18406 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18407 ;; separate formats components
18408 (and (setq fmt (plist-get org-time-clocksum-format :years))
18409 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18410 (plist-get org-time-clocksum-format :require-years))
18411 (setq clocksum (concat clocksum (format fmt n))
18412 m (- m (* n y d h))))
18413 (and (setq fmt (plist-get org-time-clocksum-format :months))
18414 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18415 (plist-get org-time-clocksum-format :require-months))
18416 (setq clocksum (concat clocksum (format fmt n))
18417 m (- m (* n mo d h))))
18418 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18419 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18420 (plist-get org-time-clocksum-format :require-weeks))
18421 (setq clocksum (concat clocksum (format fmt n))
18422 m (- m (* n w d h))))
18423 (and (setq fmt (plist-get org-time-clocksum-format :days))
18424 (or (> (setq n (/ (truncate m) (* d h))) 0)
18425 (plist-get org-time-clocksum-format :require-days))
18426 (setq clocksum (concat clocksum (format fmt n))
18427 m (- m (* n d h))))
18428 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18429 (or (> (setq n (/ (truncate m) h)) 0)
18430 (plist-get org-time-clocksum-format :require-hours))
18431 (setq clocksum (concat clocksum (format fmt n))
18432 m (- m (* n h))))
18433 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18434 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18435 (setq clocksum (concat clocksum (format fmt m))))
18436 ;; return formatted time duration
18437 clocksum))))
18439 (defun org-hours-to-clocksum-string (n)
18440 (org-minutes-to-clocksum-string (* n 60)))
18442 (defun org-hh:mm-string-to-minutes (s)
18443 "Convert a string H:MM to a number of minutes.
18444 If the string is just a number, interpret it as minutes.
18445 In fact, the first hh:mm or number in the string will be taken,
18446 there can be extra stuff in the string.
18447 If no number is found, the return value is 0."
18448 (cond
18449 ((integerp s) s)
18450 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18451 (+ (* (string-to-number (match-string 1 s)) 60)
18452 (string-to-number (match-string 2 s))))
18453 ((string-match "\\([0-9]+\\)" s)
18454 (string-to-number (match-string 1 s)))
18455 (t 0)))
18457 (defcustom org-image-actual-width t
18458 "Should we use the actual width of images when inlining them?
18460 When set to t, always use the image width.
18462 When set to a number, use imagemagick (when available) to set
18463 the image's width to this value.
18465 When set to a number in a list, try to get the width from any
18466 #+ATTR.* keyword if it matches a width specification like
18468 #+ATTR_HTML: :width 300px
18470 and fall back on that number if none is found.
18472 When set to nil, try to get the width from an #+ATTR.* keyword
18473 and fall back on the original width if none is found.
18475 This requires Emacs >= 24.1, build with imagemagick support."
18476 :group 'org-appearance
18477 :version "24.4"
18478 :package-version '(Org . "8.0")
18479 :type '(choice
18480 (const :tag "Use the image width" t)
18481 (integer :tag "Use a number of pixels")
18482 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18483 (const :tag "Use #+ATTR* or don't resize" nil)))
18485 (defcustom org-agenda-inhibit-startup nil
18486 "Inhibit startup when preparing agenda buffers.
18487 When this variable is t, the initialization of the Org agenda
18488 buffers is inhibited: e.g. the visibility state is not set, the
18489 tables are not re-aligned, etc."
18490 :type 'boolean
18491 :version "24.3"
18492 :group 'org-agenda)
18494 (defcustom org-agenda-ignore-properties nil
18495 "Avoid updating text properties when building the agenda.
18496 Properties are used to prepare buffers for effort estimates,
18497 appointments, statistics and subtree-local categories.
18498 If you don't use these in the agenda, you can add them to this
18499 list and agenda building will be a bit faster.
18500 The value is a list, with zero or more of the symbols `effort', `appt',
18501 `stats' or `category'."
18502 :type '(set :greedy t
18503 (const effort)
18504 (const appt)
18505 (const stats)
18506 (const category))
18507 :version "25.2"
18508 :package-version '(Org . "8.3")
18509 :group 'org-agenda)
18511 (defun org-duration-string-to-minutes (s &optional output-to-string)
18512 "Convert a duration string S to minutes.
18514 A bare number is interpreted as minutes, modifiers can be set by
18515 customizing `org-effort-durations' (which see).
18517 Entries containing a colon are interpreted as H:MM by
18518 `org-hh:mm-string-to-minutes'."
18519 (let ((result 0)
18520 (re (concat "\\([0-9.]+\\) *\\("
18521 (regexp-opt (mapcar 'car org-effort-durations))
18522 "\\)")))
18523 (while (string-match re s)
18524 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18525 (string-to-number (match-string 1 s))))
18526 (setq s (replace-match "" nil t s)))
18527 (setq result (floor result))
18528 (cl-incf result (org-hh:mm-string-to-minutes s))
18529 (if output-to-string (number-to-string result) result)))
18531 ;;;; Files
18533 (defun org-save-all-org-buffers ()
18534 "Save all Org buffers without user confirmation."
18535 (interactive)
18536 (message "Saving all Org buffers...")
18537 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18538 (when (featurep 'org-id) (org-id-locations-save))
18539 (message "Saving all Org buffers... done"))
18541 (defun org-revert-all-org-buffers ()
18542 "Revert all Org buffers.
18543 Prompt for confirmation when there are unsaved changes.
18544 Be sure you know what you are doing before letting this function
18545 overwrite your changes.
18547 This function is useful in a setup where one tracks org files
18548 with a version control system, to revert on one machine after pulling
18549 changes from another. I believe the procedure must be like this:
18551 1. M-x org-save-all-org-buffers
18552 2. Pull changes from the other machine, resolve conflicts
18553 3. M-x org-revert-all-org-buffers"
18554 (interactive)
18555 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18556 (user-error "Abort"))
18557 (save-excursion
18558 (save-window-excursion
18559 (dolist (b (buffer-list))
18560 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18561 (with-current-buffer b buffer-file-name))
18562 (pop-to-buffer-same-window b)
18563 (revert-buffer t 'no-confirm)))
18564 (when (and (featurep 'org-id) org-id-track-globally)
18565 (org-id-locations-load)))))
18567 ;;;; Agenda files
18569 ;;;###autoload
18570 (defun org-switchb (&optional arg)
18571 "Switch between Org buffers.
18573 With `\\[universal-argument]' prefix, restrict available buffers to files.
18575 With `\\[universal-argument] \\[universal-argument]' \
18576 prefix, restrict available buffers to agenda files."
18577 (interactive "P")
18578 (let ((blist (org-buffer-list
18579 (cond ((equal arg '(4)) 'files)
18580 ((equal arg '(16)) 'agenda)))))
18581 (pop-to-buffer-same-window
18582 (completing-read "Org buffer: "
18583 (mapcar #'list (mapcar #'buffer-name blist))
18584 nil t))))
18586 (defun org-buffer-list (&optional predicate exclude-tmp)
18587 "Return a list of Org buffers.
18588 PREDICATE can be `export', `files' or `agenda'.
18590 export restrict the list to Export buffers.
18591 files restrict the list to buffers visiting Org files.
18592 agenda restrict the list to buffers visiting agenda files.
18594 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18595 (let* ((bfn nil)
18596 (agenda-files (and (eq predicate 'agenda)
18597 (mapcar 'file-truename (org-agenda-files t))))
18598 (filter
18599 (cond
18600 ((eq predicate 'files)
18601 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18602 ((eq predicate 'export)
18603 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18604 ((eq predicate 'agenda)
18605 (lambda (b)
18606 (with-current-buffer b
18607 (and (derived-mode-p 'org-mode)
18608 (setq bfn (buffer-file-name b))
18609 (member (file-truename bfn) agenda-files)))))
18610 (t (lambda (b) (with-current-buffer b
18611 (or (derived-mode-p 'org-mode)
18612 (string-match "\\*Org .*Export"
18613 (buffer-name b)))))))))
18614 (delq nil
18615 (mapcar
18616 (lambda(b)
18617 (if (and (funcall filter b)
18618 (or (not exclude-tmp)
18619 (not (string-match "tmp" (buffer-name b)))))
18621 nil))
18622 (buffer-list)))))
18624 (defun org-agenda-files (&optional unrestricted archives)
18625 "Get the list of agenda files.
18626 Optional UNRESTRICTED means return the full list even if a restriction
18627 is currently in place.
18628 When ARCHIVES is t, include all archive files that are really being
18629 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18630 `org-agenda-archives-mode' is t."
18631 (let ((files
18632 (cond
18633 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18634 ((stringp org-agenda-files) (org-read-agenda-file-list))
18635 ((listp org-agenda-files) org-agenda-files)
18636 (t (error "Invalid value of `org-agenda-files'")))))
18637 (setq files (apply 'append
18638 (mapcar (lambda (f)
18639 (if (file-directory-p f)
18640 (directory-files
18641 f t org-agenda-file-regexp)
18642 (list f)))
18643 files)))
18644 (when org-agenda-skip-unavailable-files
18645 (setq files (delq nil
18646 (mapcar (function
18647 (lambda (file)
18648 (and (file-readable-p file) file)))
18649 files))))
18650 (when (or (eq archives t)
18651 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18652 (setq files (org-add-archive-files files)))
18653 files))
18655 (defun org-agenda-file-p (&optional file)
18656 "Return non-nil, if FILE is an agenda file.
18657 If FILE is omitted, use the file associated with the current
18658 buffer."
18659 (let ((fname (or file (buffer-file-name))))
18660 (and fname
18661 (member (file-truename fname)
18662 (mapcar #'file-truename (org-agenda-files t))))))
18664 (defun org-edit-agenda-file-list ()
18665 "Edit the list of agenda files.
18666 Depending on setup, this either uses customize to edit the variable
18667 `org-agenda-files', or it visits the file that is holding the list. In the
18668 latter case, the buffer is set up in a way that saving it automatically kills
18669 the buffer and restores the previous window configuration."
18670 (interactive)
18671 (if (stringp org-agenda-files)
18672 (let ((cw (current-window-configuration)))
18673 (find-file org-agenda-files)
18674 (setq-local org-window-configuration cw)
18675 (add-hook 'after-save-hook
18676 (lambda ()
18677 (set-window-configuration
18678 (prog1 org-window-configuration
18679 (kill-buffer (current-buffer))))
18680 (org-install-agenda-files-menu)
18681 (message "New agenda file list installed"))
18682 nil 'local)
18683 (message "%s" (substitute-command-keys
18684 "Edit list and finish with \\[save-buffer]")))
18685 (customize-variable 'org-agenda-files)))
18687 (defun org-store-new-agenda-file-list (list)
18688 "Set new value for the agenda file list and save it correctly."
18689 (if (stringp org-agenda-files)
18690 (let ((fe (org-read-agenda-file-list t)) b u)
18691 (while (setq b (find-buffer-visiting org-agenda-files))
18692 (kill-buffer b))
18693 (with-temp-file org-agenda-files
18694 (insert
18695 (mapconcat
18696 (lambda (f) ;; Keep un-expanded entries.
18697 (if (setq u (assoc f fe))
18698 (cdr u)
18700 list "\n")
18701 "\n")))
18702 (let ((org-mode-hook nil) (org-inhibit-startup t)
18703 (org-insert-mode-line-in-empty-file nil))
18704 (setq org-agenda-files list)
18705 (customize-save-variable 'org-agenda-files org-agenda-files))))
18707 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18708 "Read the list of agenda files from a file.
18709 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18710 filenames, used by `org-store-new-agenda-file-list' to write back
18711 un-expanded file names."
18712 (when (file-directory-p org-agenda-files)
18713 (error "`org-agenda-files' cannot be a single directory"))
18714 (when (stringp org-agenda-files)
18715 (with-temp-buffer
18716 (insert-file-contents org-agenda-files)
18717 (mapcar
18718 (lambda (f)
18719 (let ((e (expand-file-name (substitute-in-file-name f)
18720 org-directory)))
18721 (if pair-with-expansion
18722 (cons e f)
18723 e)))
18724 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18726 ;;;###autoload
18727 (defun org-cycle-agenda-files ()
18728 "Cycle through the files in `org-agenda-files'.
18729 If the current buffer visits an agenda file, find the next one in the list.
18730 If the current buffer does not, find the first agenda file."
18731 (interactive)
18732 (let* ((fs (or (org-agenda-files t)
18733 (user-error "No agenda files")))
18734 (files (copy-sequence fs))
18735 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18736 file)
18737 (when tcf
18738 (while (and (setq file (pop files))
18739 (not (equal (file-truename file) tcf)))))
18740 (find-file (car (or files fs)))
18741 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18743 (defun org-agenda-file-to-front (&optional to-end)
18744 "Move/add the current file to the top of the agenda file list.
18745 If the file is not present in the list, it is added to the front. If it is
18746 present, it is moved there. With optional argument TO-END, add/move to the
18747 end of the list."
18748 (interactive "P")
18749 (let ((org-agenda-skip-unavailable-files nil)
18750 (file-alist (mapcar (lambda (x)
18751 (cons (file-truename x) x))
18752 (org-agenda-files t)))
18753 (ctf (file-truename
18754 (or buffer-file-name
18755 (user-error "Please save the current buffer to a file"))))
18756 x had)
18757 (setq x (assoc ctf file-alist) had x)
18759 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18760 (if to-end
18761 (setq file-alist (append (delq x file-alist) (list x)))
18762 (setq file-alist (cons x (delq x file-alist))))
18763 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18764 (org-install-agenda-files-menu)
18765 (message "File %s to %s of agenda file list"
18766 (if had "moved" "added") (if to-end "end" "front"))))
18768 (defun org-remove-file (&optional file)
18769 "Remove current file from the list of files in variable `org-agenda-files'.
18770 These are the files which are being checked for agenda entries.
18771 Optional argument FILE means use this file instead of the current."
18772 (interactive)
18773 (let* ((org-agenda-skip-unavailable-files nil)
18774 (file (or file buffer-file-name
18775 (user-error "Current buffer does not visit a file")))
18776 (true-file (file-truename file))
18777 (afile (abbreviate-file-name file))
18778 (files (delq nil (mapcar
18779 (lambda (x)
18780 (unless (equal true-file
18781 (file-truename x))
18783 (org-agenda-files t)))))
18784 (if (not (= (length files) (length (org-agenda-files t))))
18785 (progn
18786 (org-store-new-agenda-file-list files)
18787 (org-install-agenda-files-menu)
18788 (message "Removed from Org Agenda list: %s" afile))
18789 (message "File was not in list: %s (not removed)" afile))))
18791 (defun org-file-menu-entry (file)
18792 (vector file (list 'find-file file) t))
18794 (defun org-check-agenda-file (file)
18795 "Make sure FILE exists. If not, ask user what to do."
18796 (unless (file-exists-p file)
18797 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18798 (abbreviate-file-name file))
18799 (let ((r (downcase (read-char-exclusive))))
18800 (cond
18801 ((equal r ?r)
18802 (org-remove-file file)
18803 (throw 'nextfile t))
18804 (t (user-error "Abort"))))))
18806 (defun org-get-agenda-file-buffer (file)
18807 "Get an agenda buffer visiting FILE.
18808 If the buffer needs to be created, add it to the list of buffers
18809 which might be released later."
18810 (let ((buf (org-find-base-buffer-visiting file)))
18811 (if buf
18812 buf ; just return it
18813 ;; Make a new buffer and remember it
18814 (setq buf (find-file-noselect file))
18815 (when buf (push buf org-agenda-new-buffers))
18816 buf)))
18818 (defun org-release-buffers (blist)
18819 "Release all buffers in list, asking the user for confirmation when needed.
18820 When a buffer is unmodified, it is just killed. When modified, it is saved
18821 \(if the user agrees) and then killed."
18822 (let (file)
18823 (dolist (buf blist)
18824 (setq file (buffer-file-name buf))
18825 (when (and (buffer-modified-p buf)
18826 file
18827 (y-or-n-p (format "Save file %s? " file)))
18828 (with-current-buffer buf (save-buffer)))
18829 (kill-buffer buf))))
18831 (defun org-agenda-prepare-buffers (files)
18832 "Create buffers for all agenda files, protect archived trees and comments."
18833 (interactive)
18834 (let ((pa '(:org-archived t))
18835 (pc '(:org-comment t))
18836 (pall '(:org-archived t :org-comment t))
18837 (inhibit-read-only t)
18838 (org-inhibit-startup org-agenda-inhibit-startup)
18839 (rea (concat ":" org-archive-tag ":"))
18840 re pos)
18841 (setq org-tag-alist-for-agenda nil
18842 org-tag-groups-alist-for-agenda nil)
18843 (save-excursion
18844 (save-restriction
18845 (dolist (file files)
18846 (catch 'nextfile
18847 (if (bufferp file)
18848 (set-buffer file)
18849 (org-check-agenda-file file)
18850 (set-buffer (org-get-agenda-file-buffer file)))
18851 (widen)
18852 (org-set-regexps-and-options 'tags-only)
18853 (setq pos (point))
18854 (or (memq 'category org-agenda-ignore-properties)
18855 (org-refresh-category-properties))
18856 (or (memq 'stats org-agenda-ignore-properties)
18857 (org-refresh-stats-properties))
18858 (or (memq 'effort org-agenda-ignore-properties)
18859 (org-refresh-effort-properties))
18860 (or (memq 'appt org-agenda-ignore-properties)
18861 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18862 (setq org-todo-keywords-for-agenda
18863 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18864 (setq org-done-keywords-for-agenda
18865 (append org-done-keywords-for-agenda org-done-keywords))
18866 (setq org-todo-keyword-alist-for-agenda
18867 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18868 (setq org-tag-alist-for-agenda
18869 (org-uniquify
18870 (append org-tag-alist-for-agenda
18871 org-current-tag-alist)))
18872 ;; Merge current file's tag groups into global
18873 ;; `org-tag-groups-alist-for-agenda'.
18874 (when org-group-tags
18875 (dolist (alist org-tag-groups-alist)
18876 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18877 (if old
18878 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18879 (push alist org-tag-groups-alist-for-agenda)))))
18880 (org-with-silent-modifications
18881 (save-excursion
18882 (remove-text-properties (point-min) (point-max) pall)
18883 (when org-agenda-skip-archived-trees
18884 (goto-char (point-min))
18885 (while (re-search-forward rea nil t)
18886 (when (org-at-heading-p t)
18887 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18888 (goto-char (point-min))
18889 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18890 (while (re-search-forward re nil t)
18891 (when (save-match-data (org-in-commented-heading-p t))
18892 (add-text-properties
18893 (match-beginning 0) (org-end-of-subtree t) pc)))))
18894 (goto-char pos)))))
18895 (setq org-todo-keywords-for-agenda
18896 (org-uniquify org-todo-keywords-for-agenda))
18897 (setq org-todo-keyword-alist-for-agenda
18898 (org-uniquify org-todo-keyword-alist-for-agenda))))
18901 ;;;; CDLaTeX minor mode
18903 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18904 "Keymap for the minor `org-cdlatex-mode'.")
18906 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18907 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18908 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18909 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18910 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18912 (defvar org-cdlatex-texmathp-advice-is-done nil
18913 "Flag remembering if we have applied the advice to texmathp already.")
18915 (define-minor-mode org-cdlatex-mode
18916 "Toggle the minor `org-cdlatex-mode'.
18917 This mode supports entering LaTeX environment and math in LaTeX fragments
18918 in Org mode.
18919 \\{org-cdlatex-mode-map}"
18920 nil " OCDL" nil
18921 (when org-cdlatex-mode
18922 (require 'cdlatex)
18923 (run-hooks 'cdlatex-mode-hook)
18924 (cdlatex-compute-tables))
18925 (unless org-cdlatex-texmathp-advice-is-done
18926 (setq org-cdlatex-texmathp-advice-is-done t)
18927 (defadvice texmathp (around org-math-always-on activate)
18928 "Always return t in Org buffers.
18929 This is because we want to insert math symbols without dollars even outside
18930 the LaTeX math segments. If Org mode thinks that point is actually inside
18931 an embedded LaTeX fragment, let `texmathp' do its job.
18932 `\\[org-cdlatex-mode-map]'"
18933 (interactive)
18934 (let (p)
18935 (cond
18936 ((not (derived-mode-p 'org-mode)) ad-do-it)
18937 ((eq this-command 'cdlatex-math-symbol)
18938 (setq ad-return-value t
18939 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18941 (let ((p (org-inside-LaTeX-fragment-p)))
18942 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18943 (setq ad-return-value t
18944 texmathp-why '("Org mode embedded math" . 0))
18945 (when p ad-do-it)))))))))
18947 (defun turn-on-org-cdlatex ()
18948 "Unconditionally turn on `org-cdlatex-mode'."
18949 (org-cdlatex-mode 1))
18951 (defun org-try-cdlatex-tab ()
18952 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18953 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18954 - inside a LaTeX fragment, or
18955 - after the first word in a line, where an abbreviation expansion could
18956 insert a LaTeX environment."
18957 (when org-cdlatex-mode
18958 (cond
18959 ;; Before any word on the line: No expansion possible.
18960 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18961 ;; Just after first word on the line: Expand it. Make sure it
18962 ;; cannot happen on headlines, though.
18963 ((save-excursion
18964 (skip-chars-backward "a-zA-Z0-9*")
18965 (skip-chars-backward " \t")
18966 (and (bolp) (not (org-at-heading-p))))
18967 (cdlatex-tab) t)
18968 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18970 (defun org-cdlatex-underscore-caret (&optional _arg)
18971 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18972 Revert to the normal definition outside of these fragments."
18973 (interactive "P")
18974 (if (org-inside-LaTeX-fragment-p)
18975 (call-interactively 'cdlatex-sub-superscript)
18976 (let (org-cdlatex-mode)
18977 (call-interactively (key-binding (vector last-input-event))))))
18979 (defun org-cdlatex-math-modify (&optional _arg)
18980 "Execute `cdlatex-math-modify' in LaTeX fragments.
18981 Revert to the normal definition outside of these fragments."
18982 (interactive "P")
18983 (if (org-inside-LaTeX-fragment-p)
18984 (call-interactively 'cdlatex-math-modify)
18985 (let (org-cdlatex-mode)
18986 (call-interactively (key-binding (vector last-input-event))))))
18988 (defun org-cdlatex-environment-indent (&optional environment item)
18989 "Execute `cdlatex-environment' and indent the inserted environment.
18991 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18993 The inserted environment is indented to current indentation
18994 unless point is at the beginning of the line, in which the
18995 environment remains unintended."
18996 (interactive)
18997 ;; cdlatex-environment always return nil. Therefore, capture output
18998 ;; first and determine if an environment was selected.
18999 (let* ((beg (point-marker))
19000 (end (copy-marker (point) t))
19001 (inserted (progn
19002 (ignore-errors (cdlatex-environment environment item))
19003 (< beg end)))
19004 ;; Figure out how many lines to move forward after the
19005 ;; environment has been inserted.
19006 (lines (when inserted
19007 (save-excursion
19008 (- (cl-loop while (< beg (point))
19009 with x = 0
19010 do (forward-line -1)
19011 (cl-incf x)
19012 finally return x)
19013 (if (progn (goto-char beg)
19014 (and (progn (skip-chars-forward " \t") (eolp))
19015 (progn (skip-chars-backward " \t") (bolp))))
19016 1 0)))))
19017 (env (org-trim (delete-and-extract-region beg end))))
19018 (when inserted
19019 ;; Get indentation of next line unless at column 0.
19020 (let ((ind (if (bolp) 0
19021 (save-excursion
19022 (org-return-indent)
19023 (prog1 (org-get-indentation)
19024 (when (progn (skip-chars-forward " \t") (eolp))
19025 (delete-region beg (point)))))))
19026 (bol (progn (skip-chars-backward " \t") (bolp))))
19027 ;; Insert a newline before environment unless at column zero
19028 ;; to "escape" the current line. Insert a newline if
19029 ;; something is one the same line as \end{ENVIRONMENT}.
19030 (insert
19031 (concat (unless bol "\n") env
19032 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
19033 (unless (zerop ind)
19034 (save-excursion
19035 (goto-char beg)
19036 (while (< (point) end)
19037 (unless (eolp) (indent-line-to ind))
19038 (forward-line))))
19039 (goto-char beg)
19040 (forward-line lines)
19041 (indent-line-to ind)))
19042 (set-marker beg nil)
19043 (set-marker end nil)))
19046 ;;;; LaTeX fragments
19048 (defun org-inside-LaTeX-fragment-p ()
19049 "Test if point is inside a LaTeX fragment.
19050 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19051 sequence appearing also before point.
19052 Even though the matchers for math are configurable, this function assumes
19053 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19054 delimiters are skipped when they have been removed by customization.
19055 The return value is nil, or a cons cell with the delimiter and the
19056 position of this delimiter.
19058 This function does a reasonably good job, but can locally be fooled by
19059 for example currency specifications. For example it will assume being in
19060 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19061 fragments that are properly closed, but during editing, we have to live
19062 with the uncertainty caused by missing closing delimiters. This function
19063 looks only before point, not after."
19064 (catch 'exit
19065 (let ((pos (point))
19066 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19067 (lim (progn
19068 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19069 (point)))
19070 dd-on str (start 0) m re)
19071 (goto-char pos)
19072 (when dodollar
19073 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19074 re (nth 1 (assoc "$" org-latex-regexps)))
19075 (while (string-match re str start)
19076 (cond
19077 ((= (match-end 0) (length str))
19078 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19079 ((= (match-end 0) (- (length str) 5))
19080 (throw 'exit nil))
19081 (t (setq start (match-end 0))))))
19082 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19083 (goto-char pos)
19084 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19085 (and (match-beginning 2) (throw 'exit nil))
19086 ;; count $$
19087 (while (re-search-backward "\\$\\$" lim t)
19088 (setq dd-on (not dd-on)))
19089 (goto-char pos)
19090 (when dd-on (cons "$$" m))))))
19092 (defun org-inside-latex-macro-p ()
19093 "Is point inside a LaTeX macro or its arguments?"
19094 (save-match-data
19095 (org-in-regexp
19096 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19098 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19099 "Build an overlay between BEG and END using IMAGE file.
19100 Argument IMAGETYPE is the extension of the displayed image,
19101 as a string. It defaults to \"png\"."
19102 (let ((ov (make-overlay beg end))
19103 (imagetype (or (intern imagetype) 'png)))
19104 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19105 (overlay-put ov 'evaporate t)
19106 (overlay-put ov
19107 'modification-hooks
19108 (list (lambda (o _flag _beg _end &optional _l)
19109 (delete-overlay o))))
19110 (overlay-put ov
19111 'display
19112 (list 'image :type imagetype :file image :ascent 'center))))
19114 (defun org--list-latex-overlays (&optional beg end)
19115 "List all Org LaTeX overlays in current buffer.
19116 Limit to overlays between BEG and END when those are provided."
19117 (cl-remove-if-not
19118 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19119 (overlays-in (or beg (point-min)) (or end (point-max)))))
19121 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19122 "Remove all overlays with LaTeX fragment images in current buffer.
19123 When optional arguments BEG and END are non-nil, remove all
19124 overlays between them instead. Return a non-nil value when some
19125 overlays were removed, nil otherwise."
19126 (let ((overlays (org--list-latex-overlays beg end)))
19127 (mapc #'delete-overlay overlays)
19128 overlays))
19130 (defun org-toggle-latex-fragment (&optional arg)
19131 "Preview the LaTeX fragment at point, or all locally or globally.
19133 If the cursor is on a LaTeX fragment, create the image and overlay
19134 it over the source code, if there is none. Remove it otherwise.
19135 If there is no fragment at point, display all fragments in the
19136 current section.
19138 With prefix ARG, preview or clear image for all fragments in the
19139 current subtree or in the whole buffer when used before the first
19140 headline. With a prefix ARG `\\[universal-argument] \
19141 \\[universal-argument]' preview or clear images
19142 for all fragments in the buffer."
19143 (interactive "P")
19144 (when (display-graphic-p)
19145 (catch 'exit
19146 (save-excursion
19147 (let (beg end msg)
19148 (cond
19149 ((or (equal arg '(16))
19150 (and (equal arg '(4))
19151 (org-with-limited-levels (org-before-first-heading-p))))
19152 (if (org-remove-latex-fragment-image-overlays)
19153 (progn (message "LaTeX fragments images removed from buffer")
19154 (throw 'exit nil))
19155 (setq msg "Creating images for buffer...")))
19156 ((equal arg '(4))
19157 (org-with-limited-levels (org-back-to-heading t))
19158 (setq beg (point))
19159 (setq end (progn (org-end-of-subtree t) (point)))
19160 (if (org-remove-latex-fragment-image-overlays beg end)
19161 (progn
19162 (message "LaTeX fragment images removed from subtree")
19163 (throw 'exit nil))
19164 (setq msg "Creating images for subtree...")))
19165 ((let ((datum (org-element-context)))
19166 (when (memq (org-element-type datum)
19167 '(latex-environment latex-fragment))
19168 (setq beg (org-element-property :begin datum))
19169 (setq end (org-element-property :end datum))
19170 (if (org-remove-latex-fragment-image-overlays beg end)
19171 (progn (message "LaTeX fragment image removed")
19172 (throw 'exit nil))
19173 (setq msg "Creating image...")))))
19175 (org-with-limited-levels
19176 (setq beg (if (org-at-heading-p) (line-beginning-position)
19177 (outline-previous-heading)
19178 (point)))
19179 (setq end (progn (outline-next-heading) (point)))
19180 (if (org-remove-latex-fragment-image-overlays beg end)
19181 (progn
19182 (message "LaTeX fragment images removed from section")
19183 (throw 'exit nil))
19184 (setq msg "Creating images for section...")))))
19185 (let ((file (buffer-file-name (buffer-base-buffer))))
19186 (org-format-latex
19187 (concat org-preview-latex-image-directory "org-ltximg")
19188 beg end
19189 ;; Emacs cannot overlay images from remote hosts. Create
19190 ;; it in `temporary-file-directory' instead.
19191 (if (or (not file) (file-remote-p file))
19192 temporary-file-directory
19193 default-directory)
19194 'overlays msg 'forbuffer org-preview-latex-default-process))
19195 (message (concat msg "done")))))))
19197 (defun org-format-latex
19198 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19199 "Replace LaTeX fragments with links to an image.
19201 The function takes care of creating the replacement image.
19203 Only consider fragments between BEG and END when those are
19204 provided.
19206 When optional argument OVERLAYS is non-nil, display the image on
19207 top of the fragment instead of replacing it.
19209 PROCESSING-TYPE is the conversion method to use, as a symbol.
19211 Some of the options can be changed using the variable
19212 `org-format-latex-options', which see."
19213 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19214 (unless (eq processing-type 'verbatim)
19215 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19216 (cnt 0)
19217 checkdir-flag)
19218 (goto-char (or beg (point-min)))
19219 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19220 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19221 (overlay-recenter (or end (point-max))))
19222 (while (re-search-forward math-regexp end t)
19223 (unless (and overlays
19224 (eq (get-char-property (point) 'org-overlay-type)
19225 'org-latex-overlay))
19226 (let* ((context (org-element-context))
19227 (type (org-element-type context)))
19228 (when (memq type '(latex-environment latex-fragment))
19229 (let ((block-type (eq type 'latex-environment))
19230 (value (org-element-property :value context))
19231 (beg (org-element-property :begin context))
19232 (end (save-excursion
19233 (goto-char (org-element-property :end context))
19234 (skip-chars-backward " \r\t\n")
19235 (point))))
19236 (cond
19237 ((eq processing-type 'mathjax)
19238 ;; Prepare for MathJax processing.
19239 (if (not (string-match "\\`\\$\\$?" value))
19240 (goto-char end)
19241 (delete-region beg end)
19242 (if (string= (match-string 0 value) "$$")
19243 (insert "\\[" (substring value 2 -2) "\\]")
19244 (insert "\\(" (substring value 1 -1) "\\)"))))
19245 ((assq processing-type org-preview-latex-process-alist)
19246 ;; Process to an image.
19247 (cl-incf cnt)
19248 (goto-char beg)
19249 (let* ((processing-info
19250 (cdr (assq processing-type org-preview-latex-process-alist)))
19251 (face (face-at-point))
19252 ;; Get the colors from the face at point.
19254 (let ((color (plist-get org-format-latex-options
19255 :foreground)))
19256 (if (and forbuffer (eq color 'auto))
19257 (face-attribute face :foreground nil 'default)
19258 color)))
19260 (let ((color (plist-get org-format-latex-options
19261 :background)))
19262 (if (and forbuffer (eq color 'auto))
19263 (face-attribute face :background nil 'default)
19264 color)))
19265 (hash (sha1 (prin1-to-string
19266 (list org-format-latex-header
19267 org-latex-default-packages-alist
19268 org-latex-packages-alist
19269 org-format-latex-options
19270 forbuffer value fg bg))))
19271 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19272 (absprefix (expand-file-name prefix dir))
19273 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19274 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19275 (sep (and block-type "\n\n"))
19276 (link (concat sep "[[file:" linkfile "]]" sep))
19277 (options
19278 (org-combine-plists
19279 org-format-latex-options
19280 `(:foreground ,fg :background ,bg))))
19281 (when msg (message msg cnt))
19282 (unless checkdir-flag ; Ensure the directory exists.
19283 (setq checkdir-flag t)
19284 (let ((todir (file-name-directory absprefix)))
19285 (unless (file-directory-p todir)
19286 (make-directory todir t))))
19287 (unless (file-exists-p movefile)
19288 (org-create-formula-image
19289 value movefile options forbuffer processing-type))
19290 (if overlays
19291 (progn
19292 (dolist (o (overlays-in beg end))
19293 (when (eq (overlay-get o 'org-overlay-type)
19294 'org-latex-overlay)
19295 (delete-overlay o)))
19296 (org--format-latex-make-overlay beg end movefile imagetype)
19297 (goto-char end))
19298 (delete-region beg end)
19299 (insert
19300 (org-add-props link
19301 (list 'org-latex-src
19302 (replace-regexp-in-string "\"" "" value)
19303 'org-latex-src-embed-type
19304 (if block-type 'paragraph 'character)))))))
19305 ((eq processing-type 'mathml)
19306 ;; Process to MathML.
19307 (unless (org-format-latex-mathml-available-p)
19308 (user-error "LaTeX to MathML converter not configured"))
19309 (cl-incf cnt)
19310 (when msg (message msg cnt))
19311 (goto-char beg)
19312 (delete-region beg end)
19313 (insert (org-format-latex-as-mathml
19314 value block-type prefix dir)))
19316 (error "Unknown conversion process %s for LaTeX fragments"
19317 processing-type)))))))))))
19319 (defun org-create-math-formula (latex-frag &optional mathml-file)
19320 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19321 Use `org-latex-to-mathml-convert-command'. If the conversion is
19322 sucessful, return the portion between \"<math...> </math>\"
19323 elements otherwise return nil. When MATHML-FILE is specified,
19324 write the results in to that file. When invoked as an
19325 interactive command, prompt for LATEX-FRAG, with initial value
19326 set to the current active region and echo the results for user
19327 inspection."
19328 (interactive (list (let ((frag (when (org-region-active-p)
19329 (buffer-substring-no-properties
19330 (region-beginning) (region-end)))))
19331 (read-string "LaTeX Fragment: " frag nil frag))))
19332 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19333 (let* ((tmp-in-file
19334 (let ((file (file-relative-name
19335 (make-temp-name (expand-file-name "ltxmathml-in")))))
19336 (write-region latex-frag nil file)
19337 file))
19338 (tmp-out-file (file-relative-name
19339 (make-temp-name (expand-file-name "ltxmathml-out"))))
19340 (cmd (format-spec
19341 org-latex-to-mathml-convert-command
19342 `((?j . ,(and org-latex-to-mathml-jar-file
19343 (shell-quote-argument
19344 (expand-file-name
19345 org-latex-to-mathml-jar-file))))
19346 (?I . ,(shell-quote-argument tmp-in-file))
19347 (?i . ,latex-frag)
19348 (?o . ,(shell-quote-argument tmp-out-file)))))
19349 mathml shell-command-output)
19350 (when (called-interactively-p 'any)
19351 (unless (org-format-latex-mathml-available-p)
19352 (user-error "LaTeX to MathML converter not configured")))
19353 (message "Running %s" cmd)
19354 (setq shell-command-output (shell-command-to-string cmd))
19355 (setq mathml
19356 (when (file-readable-p tmp-out-file)
19357 (with-current-buffer (find-file-noselect tmp-out-file t)
19358 (goto-char (point-min))
19359 (when (re-search-forward
19360 (concat
19361 (regexp-quote
19362 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19363 "[^>]*?>"
19364 "\\(.\\|\n\\)*"
19365 "</math>")
19366 nil t)
19367 (prog1 (match-string 0) (kill-buffer))))))
19368 (cond
19369 (mathml
19370 (setq mathml
19371 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19372 (when mathml-file
19373 (write-region mathml nil mathml-file))
19374 (when (called-interactively-p 'any)
19375 (message mathml)))
19376 ((message "LaTeX to MathML conversion failed")
19377 (message shell-command-output)))
19378 (delete-file tmp-in-file)
19379 (when (file-exists-p tmp-out-file)
19380 (delete-file tmp-out-file))
19381 mathml))
19383 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19384 prefix &optional dir)
19385 "Use `org-create-math-formula' but check local cache first."
19386 (let* ((absprefix (expand-file-name prefix dir))
19387 (print-length nil) (print-level nil)
19388 (formula-id (concat
19389 "formula-"
19390 (sha1
19391 (prin1-to-string
19392 (list latex-frag
19393 org-latex-to-mathml-convert-command)))))
19394 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19395 (formula-cache-dir (file-name-directory formula-cache)))
19397 (unless (file-directory-p formula-cache-dir)
19398 (make-directory formula-cache-dir t))
19400 (unless (file-exists-p formula-cache)
19401 (org-create-math-formula latex-frag formula-cache))
19403 (if (file-exists-p formula-cache)
19404 ;; Successful conversion. Return the link to MathML file.
19405 (org-add-props
19406 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19407 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19408 'org-latex-src-embed-type (if latex-frag-type
19409 'paragraph 'character)))
19410 ;; Failed conversion. Return the LaTeX fragment verbatim
19411 latex-frag)))
19413 (declare-function org-export-get-backend "ox" (name))
19414 (declare-function org-export--get-global-options "ox" (&optional backend))
19415 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19416 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19417 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19418 (defun org-create-formula--latex-header ()
19419 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19420 (let ((info (org-combine-plists (org-export--get-global-options
19421 (org-export-get-backend 'latex))
19422 (org-export--get-inbuffer-options
19423 (org-export-get-backend 'latex)))))
19424 (org-latex-guess-babel-language
19425 (org-latex-guess-inputenc
19426 (org-splice-latex-header
19427 org-format-latex-header
19428 org-latex-default-packages-alist
19429 org-latex-packages-alist t
19430 (plist-get info :latex-header)))
19431 info)))
19433 (defun org--get-display-dpi ()
19434 "Get the DPI of the display.
19436 Assumes that the display has the same pixel width in the
19437 horizontal and vertical directions."
19438 (if (display-graphic-p)
19439 (round (/ (display-pixel-height)
19440 (/ (display-mm-height) 25.4)))
19441 (error "Attempt to calculate the dpi of a non-graphic display")))
19443 (defun org-create-formula-image
19444 (string tofile options buffer &optional processing-type)
19445 "Create an image from LaTeX source using external processes.
19447 The LaTeX STRING is saved to a temporary LaTeX file, then
19448 converted to an image file by process PROCESSING-TYPE defined in
19449 `org-preview-latex-process-alist'. A nil value defaults to
19450 `org-preview-latex-default-process'.
19452 The generated image file is eventually moved to TOFILE.
19454 The OPTIONS argument controls the size, foreground color and
19455 background color of the generated image.
19457 When BUFFER non-nil, this function is used for LaTeX previewing.
19458 Otherwise, it is used to deal with LaTeX snippets showed in
19459 a HTML file."
19460 (let* ((processing-type (or processing-type
19461 org-preview-latex-default-process))
19462 (processing-info
19463 (cdr (assq processing-type org-preview-latex-process-alist)))
19464 (programs (plist-get processing-info :programs))
19465 (error-message (or (plist-get processing-info :message) ""))
19466 (use-xcolor (plist-get processing-info :use-xcolor))
19467 (image-input-type (plist-get processing-info :image-input-type))
19468 (image-output-type (plist-get processing-info :image-output-type))
19469 (post-clean (or (plist-get processing-info :post-clean)
19470 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19471 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19472 (latex-header (or (plist-get processing-info :latex-header)
19473 (org-create-formula--latex-header)))
19474 (latex-compiler (plist-get processing-info :latex-compiler))
19475 (image-converter (plist-get processing-info :image-converter))
19476 (tmpdir temporary-file-directory)
19477 (texfilebase (make-temp-name
19478 (expand-file-name "orgtex" tmpdir)))
19479 (texfile (concat texfilebase ".tex"))
19480 (font-height (face-attribute 'default :height nil))
19481 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19482 '(1.0 . 1.0)))
19483 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19484 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19485 (dpi (* scale (floor (if buffer font-height 140.0))))
19486 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19487 "Black"))
19488 (bg (or (plist-get options (if buffer :background :html-background))
19489 "Transparent"))
19490 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19491 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19492 (dolist (program programs)
19493 (org-check-external-command program error-message))
19494 (if use-xcolor
19495 (progn (if (eq fg 'default)
19496 (setq fg (org-latex-color :foreground))
19497 (setq fg (org-latex-color-format fg)))
19498 (if (eq bg 'default)
19499 (setq bg (org-latex-color :background))
19500 (setq bg (org-latex-color-format
19501 (if (string= bg "Transparent") "white" bg))))
19502 (with-temp-file texfile
19503 (insert latex-header)
19504 (insert "\n\\begin{document}\n"
19505 "\\definecolor{fg}{rgb}{" fg "}\n"
19506 "\\definecolor{bg}{rgb}{" bg "}\n"
19507 "\n\\pagecolor{bg}\n"
19508 "\n{\\color{fg}\n"
19509 string
19510 "\n}\n"
19511 "\n\\end{document}\n")))
19512 (if (eq fg 'default)
19513 (setq fg (org-dvipng-color :foreground))
19514 (unless (string= fg "Transparent")
19515 (setq fg (org-dvipng-color-format fg))))
19516 (if (eq bg 'default)
19517 (setq bg (org-dvipng-color :background))
19518 (unless (string= bg "Transparent")
19519 (setq bg (org-dvipng-color-format bg))))
19520 (with-temp-file texfile
19521 (insert latex-header)
19522 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19524 (let* ((err-msg (format "Please adjust '%s' part of \
19525 `org-preview-latex-process-alist'."
19526 processing-type))
19527 (image-input-file
19528 (org-compile-file
19529 texfile latex-compiler image-input-type err-msg log-buf))
19530 (image-output-file
19531 (org-compile-file
19532 image-input-file image-converter image-output-type err-msg log-buf
19533 `((?F . ,(shell-quote-argument fg))
19534 (?B . ,(shell-quote-argument bg))
19535 (?D . ,(shell-quote-argument (format "%s" dpi)))
19536 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19537 (copy-file image-output-file tofile 'replace)
19538 (dolist (e post-clean)
19539 (when (file-exists-p (concat texfilebase e))
19540 (delete-file (concat texfilebase e))))
19541 image-output-file)))
19543 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19544 "Fill a LaTeX header template TPL.
19545 In the template, the following place holders will be recognized:
19547 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19548 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19549 [PACKAGES] \\usepackage statements for PKG
19550 [NO-PACKAGES] do not include PKG
19551 [EXTRA] the string EXTRA
19552 [NO-EXTRA] do not include EXTRA
19554 For backward compatibility, if both the positive and the negative place
19555 holder is missing, the positive one (without the \"NO-\") will be
19556 assumed to be present at the end of the template.
19557 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19558 EXTRA is a string.
19559 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19560 (let (rpl (end ""))
19561 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19562 (setq rpl (if (or (match-end 1) (not def-pkg))
19563 "" (org-latex-packages-to-string def-pkg snippets-p t))
19564 tpl (replace-match rpl t t tpl))
19565 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19567 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19568 (setq rpl (if (or (match-end 1) (not pkg))
19569 "" (org-latex-packages-to-string pkg snippets-p t))
19570 tpl (replace-match rpl t t tpl))
19571 (when pkg (setq end
19572 (concat end "\n"
19573 (org-latex-packages-to-string pkg snippets-p)))))
19575 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19576 (setq rpl (if (or (match-end 1) (not extra))
19577 "" (concat extra "\n"))
19578 tpl (replace-match rpl t t tpl))
19579 (when (and extra (string-match "\\S-" extra))
19580 (setq end (concat end "\n" extra))))
19582 (if (string-match "\\S-" end)
19583 (concat tpl "\n" end)
19584 tpl)))
19586 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19587 "Turn an alist of packages into a string with the \\usepackage macros."
19588 (setq pkg (mapconcat (lambda(p)
19589 (cond
19590 ((stringp p) p)
19591 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19592 (format "%% Package %s omitted" (cadr p)))
19593 ((equal "" (car p))
19594 (format "\\usepackage{%s}" (cadr p)))
19596 (format "\\usepackage[%s]{%s}"
19597 (car p) (cadr p)))))
19599 "\n"))
19600 (if newline (concat pkg "\n") pkg))
19602 (defun org-dvipng-color (attr)
19603 "Return a RGB color specification for dvipng."
19604 (org-dvipng-color-format (face-attribute 'default attr nil)))
19606 (defun org-dvipng-color-format (color-name)
19607 "Convert COLOR-NAME to a RGB color value for dvipng."
19608 (apply #'format "rgb %s %s %s"
19609 (mapcar 'org-normalize-color
19610 (color-values color-name))))
19612 (defun org-latex-color (attr)
19613 "Return a RGB color for the LaTeX color package."
19614 (org-latex-color-format (face-attribute 'default attr nil)))
19616 (defun org-latex-color-format (color-name)
19617 "Convert COLOR-NAME to a RGB color value."
19618 (apply #'format "%s,%s,%s"
19619 (mapcar 'org-normalize-color
19620 (color-values color-name))))
19622 (defun org-normalize-color (value)
19623 "Return string to be used as color value for an RGB component."
19624 (format "%g" (/ value 65535.0)))
19628 ;; Image display
19630 (defvar-local org-inline-image-overlays nil)
19632 (defun org-toggle-inline-images (&optional include-linked)
19633 "Toggle the display of inline images.
19634 INCLUDE-LINKED is passed to `org-display-inline-images'."
19635 (interactive "P")
19636 (if org-inline-image-overlays
19637 (progn
19638 (org-remove-inline-images)
19639 (when (called-interactively-p 'interactive)
19640 (message "Inline image display turned off")))
19641 (org-display-inline-images include-linked)
19642 (when (called-interactively-p 'interactive)
19643 (message (if org-inline-image-overlays
19644 (format "%d images displayed inline"
19645 (length org-inline-image-overlays))
19646 "No images to display inline")))))
19648 (defun org-redisplay-inline-images ()
19649 "Refresh the display of inline images."
19650 (interactive)
19651 (if (not org-inline-image-overlays)
19652 (org-toggle-inline-images)
19653 (org-toggle-inline-images)
19654 (org-toggle-inline-images)))
19656 (defun org-display-inline-images (&optional include-linked refresh beg end)
19657 "Display inline images.
19659 An inline image is a link which follows either of these
19660 conventions:
19662 1. Its path is a file with an extension matching return value
19663 from `image-file-name-regexp' and it has no contents.
19665 2. Its description consists in a single link of the previous
19666 type.
19668 When optional argument INCLUDE-LINKED is non-nil, also links with
19669 a text description part will be inlined. This can be nice for
19670 a quick look at those images, but it does not reflect what
19671 exported files will look like.
19673 When optional argument REFRESH is non-nil, refresh existing
19674 images between BEG and END. This will create new image displays
19675 only if necessary. BEG and END default to the buffer
19676 boundaries."
19677 (interactive "P")
19678 (when (display-graphic-p)
19679 (unless refresh
19680 (org-remove-inline-images)
19681 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19682 (org-with-wide-buffer
19683 (goto-char (or beg (point-min)))
19684 (let ((case-fold-search t)
19685 (file-extension-re (image-file-name-regexp)))
19686 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19687 (let ((link (save-match-data (org-element-context))))
19688 ;; Check if we're at an inline image.
19689 (when (and (equal (org-element-property :type link) "file")
19690 (or include-linked
19691 (not (org-element-property :contents-begin link)))
19692 (let ((parent (org-element-property :parent link)))
19693 (or (not (eq (org-element-type parent) 'link))
19694 (not (cdr (org-element-contents parent)))))
19695 (string-match-p file-extension-re
19696 (org-element-property :path link)))
19697 (let ((file (expand-file-name
19698 (org-link-unescape
19699 (org-element-property :path link)))))
19700 (when (file-exists-p file)
19701 (let ((width
19702 ;; Apply `org-image-actual-width' specifications.
19703 (cond
19704 ((not (image-type-available-p 'imagemagick)) nil)
19705 ((eq org-image-actual-width t) nil)
19706 ((listp org-image-actual-width)
19708 ;; First try to find a width among
19709 ;; attributes associated to the paragraph
19710 ;; containing link.
19711 (let ((paragraph
19712 (let ((e link))
19713 (while (and (setq e (org-element-property
19714 :parent e))
19715 (not (eq (org-element-type e)
19716 'paragraph))))
19717 e)))
19718 (when paragraph
19719 (save-excursion
19720 (goto-char (org-element-property :begin paragraph))
19721 (when
19722 (re-search-forward
19723 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19724 (org-element-property
19725 :post-affiliated paragraph)
19727 (string-to-number (match-string 1))))))
19728 ;; Otherwise, fall-back to provided number.
19729 (car org-image-actual-width)))
19730 ((numberp org-image-actual-width)
19731 org-image-actual-width)))
19732 (old (get-char-property-and-overlay
19733 (org-element-property :begin link)
19734 'org-image-overlay)))
19735 (if (and (car-safe old) refresh)
19736 (image-refresh (overlay-get (cdr old) 'display))
19737 (let ((image (create-image file
19738 (and width 'imagemagick)
19740 :width width)))
19741 (when image
19742 (let* ((link
19743 ;; If inline image is the description
19744 ;; of another link, be sure to
19745 ;; consider the latter as the one to
19746 ;; apply the overlay on.
19747 (let ((parent
19748 (org-element-property :parent link)))
19749 (if (eq (org-element-type parent) 'link)
19750 parent
19751 link)))
19752 (ov (make-overlay
19753 (org-element-property :begin link)
19754 (progn
19755 (goto-char
19756 (org-element-property :end link))
19757 (skip-chars-backward " \t")
19758 (point)))))
19759 (overlay-put ov 'display image)
19760 (overlay-put ov 'face 'default)
19761 (overlay-put ov 'org-image-overlay t)
19762 (overlay-put
19763 ov 'modification-hooks
19764 (list 'org-display-inline-remove-overlay))
19765 (push ov org-inline-image-overlays)))))))))))))))
19767 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19768 "Remove inline-display overlay if a corresponding region is modified."
19769 (let ((inhibit-modification-hooks t))
19770 (when (and ov after)
19771 (delete ov org-inline-image-overlays)
19772 (delete-overlay ov))))
19774 (defun org-remove-inline-images ()
19775 "Remove inline display of images."
19776 (interactive)
19777 (mapc #'delete-overlay org-inline-image-overlays)
19778 (setq org-inline-image-overlays nil))
19780 ;;;; Key bindings
19782 ;; Outline functions from `outline-mode-prefix-map'
19783 ;; that can be remapped in Org:
19784 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19785 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19786 (define-key org-mode-map [remap outline-forward-same-level]
19787 'org-forward-heading-same-level)
19788 (define-key org-mode-map [remap outline-backward-same-level]
19789 'org-backward-heading-same-level)
19790 (define-key org-mode-map [remap outline-show-branches]
19791 'org-kill-note-or-show-branches)
19792 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19793 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19794 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19795 (define-key org-mode-map [remap outline-next-visible-heading]
19796 'org-next-visible-heading)
19797 (define-key org-mode-map [remap outline-previous-visible-heading]
19798 'org-previous-visible-heading)
19799 (define-key org-mode-map [remap show-children] 'org-show-children)
19801 ;; Outline functions from `outline-mode-prefix-map' that can not
19802 ;; be remapped in Org:
19804 ;; - the column "key binding" shows whether the Outline function is still
19805 ;; available in Org mode on the same key that it has been bound to in
19806 ;; Outline mode:
19807 ;; - "overridden": key used for a different functionality in Org mode
19808 ;; - else: key still bound to the same Outline function in Org mode
19810 ;; | Outline function | key binding | Org replacement |
19811 ;; |------------------------------------+-------------+--------------------------|
19812 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19813 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19814 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19815 ;; | `show-entry' | overridden | no replacement |
19816 ;; | `show-branches' | `C-c C-k' | still same function |
19817 ;; | `show-subtree' | overridden | visibility cycling |
19818 ;; | `show-all' | overridden | no replacement |
19819 ;; | `hide-subtree' | overridden | visibility cycling |
19820 ;; | `hide-body' | overridden | no replacement |
19821 ;; | `hide-entry' | overridden | visibility cycling |
19822 ;; | `hide-leaves' | overridden | no replacement |
19823 ;; | `hide-sublevels' | overridden | no replacement |
19824 ;; | `hide-other' | overridden | no replacement |
19826 ;; Make `C-c C-x' a prefix key
19827 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19829 ;; TAB key with modifiers
19830 (org-defkey org-mode-map "\C-i" 'org-cycle)
19831 (org-defkey org-mode-map [(tab)] 'org-cycle)
19832 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19833 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19834 ;; The following line is necessary under Suse GNU/Linux
19835 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19836 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19837 (define-key org-mode-map [backtab] 'org-shifttab)
19839 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19840 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19841 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19843 ;; Cursor keys with modifiers
19844 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19845 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19846 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19847 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19849 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19850 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19851 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19852 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19853 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19854 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19856 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19857 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19858 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19859 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19861 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19862 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19863 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19864 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19866 ;; Babel keys
19867 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19868 (dolist (pair org-babel-key-bindings)
19869 (define-key org-babel-map (car pair) (cdr pair)))
19871 ;;; Extra keys for tty access.
19872 ;; We only set them when really needed because otherwise the
19873 ;; menus don't show the simple keys
19875 (when (or org-use-extra-keys (not window-system))
19876 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19877 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19878 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19879 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19880 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19881 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19882 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19883 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19884 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19885 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19886 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19887 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19888 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19889 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19890 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19891 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19892 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19893 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19894 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19895 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19896 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19897 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19898 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19899 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19900 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19901 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19902 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19903 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19905 ;; All the other keys
19907 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19908 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19909 (if (boundp 'narrow-map)
19910 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19911 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19912 (if (boundp 'narrow-map)
19913 (org-defkey narrow-map "b" 'org-narrow-to-block)
19914 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19915 (if (boundp 'narrow-map)
19916 (org-defkey narrow-map "e" 'org-narrow-to-element)
19917 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19918 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19919 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19920 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19921 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19922 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19923 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19924 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19925 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19926 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19927 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19928 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19929 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19930 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19931 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19932 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19933 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19934 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19935 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19936 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19937 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19938 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19939 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19940 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19941 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19942 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19943 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19944 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19945 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19946 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19947 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19948 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19949 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19950 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19951 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19952 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19953 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19954 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19955 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19956 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19957 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19958 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19959 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19960 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19961 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19962 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19963 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19964 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19965 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19966 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19967 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19968 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19969 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19970 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19971 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19972 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19973 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19974 (org-defkey org-mode-map "\C-c^" 'org-sort)
19975 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19976 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19977 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19978 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19979 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19980 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19981 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19982 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19983 (org-defkey org-mode-map "\C-m" 'org-return)
19984 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19985 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19986 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19987 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19988 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19989 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19990 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19991 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19992 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19993 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19994 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19995 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19996 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19997 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19998 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19999 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
20000 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
20001 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
20002 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
20003 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
20004 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
20005 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
20006 (org-defkey org-mode-map "\M-h" 'org-mark-element)
20007 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
20008 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
20010 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
20011 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
20012 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
20014 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
20015 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
20016 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
20017 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
20018 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
20019 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
20020 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
20021 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
20022 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
20023 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
20024 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
20025 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
20026 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
20027 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
20028 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
20029 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
20030 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
20031 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
20032 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
20033 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
20034 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
20035 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
20037 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
20038 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
20039 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
20040 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
20041 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
20043 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
20045 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
20047 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
20048 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
20050 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20053 (defconst org-speed-commands-default
20055 ("Outline Navigation")
20056 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20057 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20058 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20059 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20060 ("F" . org-next-block)
20061 ("B" . org-previous-block)
20062 ("u" . (org-speed-move-safe 'outline-up-heading))
20063 ("j" . org-goto)
20064 ("g" . (org-refile t))
20065 ("Outline Visibility")
20066 ("c" . org-cycle)
20067 ("C" . org-shifttab)
20068 (" " . org-display-outline-path)
20069 ("s" . org-narrow-to-subtree)
20070 ("=" . org-columns)
20071 ("Outline Structure Editing")
20072 ("U" . org-metaup)
20073 ("D" . org-metadown)
20074 ("r" . org-metaright)
20075 ("l" . org-metaleft)
20076 ("R" . org-shiftmetaright)
20077 ("L" . org-shiftmetaleft)
20078 ("i" . (progn (forward-char 1) (call-interactively
20079 'org-insert-heading-respect-content)))
20080 ("^" . org-sort)
20081 ("w" . org-refile)
20082 ("a" . org-archive-subtree-default-with-confirmation)
20083 ("@" . org-mark-subtree)
20084 ("#" . org-toggle-comment)
20085 ("Clock Commands")
20086 ("I" . org-clock-in)
20087 ("O" . org-clock-out)
20088 ("Meta Data Editing")
20089 ("t" . org-todo)
20090 ("," . (org-priority))
20091 ("0" . (org-priority ?\ ))
20092 ("1" . (org-priority ?A))
20093 ("2" . (org-priority ?B))
20094 ("3" . (org-priority ?C))
20095 (":" . org-set-tags-command)
20096 ("e" . org-set-effort)
20097 ("E" . org-inc-effort)
20098 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20099 (org-entry-put (point) "APPT_WARNTIME" m)))
20100 ("Agenda Views etc")
20101 ("v" . org-agenda)
20102 ("/" . org-sparse-tree)
20103 ("Misc")
20104 ("o" . org-open-at-point)
20105 ("?" . org-speed-command-help)
20106 ("<" . (org-agenda-set-restriction-lock 'subtree))
20107 (">" . (org-agenda-remove-restriction-lock))
20109 "The default speed commands.")
20111 (defun org-print-speed-command (e)
20112 (if (> (length (car e)) 1)
20113 (progn
20114 (princ "\n")
20115 (princ (car e))
20116 (princ "\n")
20117 (princ (make-string (length (car e)) ?-))
20118 (princ "\n"))
20119 (princ (car e))
20120 (princ " ")
20121 (if (symbolp (cdr e))
20122 (princ (symbol-name (cdr e)))
20123 (prin1 (cdr e)))
20124 (princ "\n")))
20126 (defun org-speed-command-help ()
20127 "Show the available speed commands."
20128 (interactive)
20129 (if (not org-use-speed-commands)
20130 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20131 (with-output-to-temp-buffer "*Help*"
20132 (princ "User-defined Speed commands\n===========================\n")
20133 (mapc #'org-print-speed-command org-speed-commands-user)
20134 (princ "\n")
20135 (princ "Built-in Speed commands\n=======================\n")
20136 (mapc #'org-print-speed-command org-speed-commands-default))
20137 (with-current-buffer "*Help*"
20138 (setq truncate-lines t))))
20140 (defun org-speed-move-safe (cmd)
20141 "Execute CMD, but make sure that the cursor always ends up in a headline.
20142 If not, return to the original position and throw an error."
20143 (interactive)
20144 (let ((pos (point)))
20145 (call-interactively cmd)
20146 (unless (and (bolp) (org-at-heading-p))
20147 (goto-char pos)
20148 (error "Boundary reached while executing %s" cmd))))
20150 (defvar org-self-insert-command-undo-counter 0)
20152 (defvar org-table-auto-blank-field) ; defined in org-table.el
20153 (defvar org-speed-command nil)
20155 (defun org-speed-command-activate (keys)
20156 "Hook for activating single-letter speed commands.
20157 `org-speed-commands-default' specifies a minimal command set.
20158 Use `org-speed-commands-user' for further customization."
20159 (when (or (and (bolp) (looking-at org-outline-regexp))
20160 (and (functionp org-use-speed-commands)
20161 (funcall org-use-speed-commands)))
20162 (cdr (assoc keys (append org-speed-commands-user
20163 org-speed-commands-default)))))
20165 (defun org-babel-speed-command-activate (keys)
20166 "Hook for activating single-letter code block commands."
20167 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20168 (cdr (assoc keys org-babel-key-bindings))))
20170 (defcustom org-speed-command-hook
20171 '(org-speed-command-default-hook org-babel-speed-command-hook)
20172 "Hook for activating speed commands at strategic locations.
20173 Hook functions are called in sequence until a valid handler is
20174 found.
20176 Each hook takes a single argument, a user-pressed command key
20177 which is also a `self-insert-command' from the global map.
20179 Within the hook, examine the cursor position and the command key
20180 and return nil or a valid handler as appropriate. Handler could
20181 be one of an interactive command, a function, or a form.
20183 Set `org-use-speed-commands' to non-nil value to enable this
20184 hook. The default setting is `org-speed-command-activate'."
20185 :group 'org-structure
20186 :version "24.1"
20187 :type 'hook)
20189 (defun org-self-insert-command (N)
20190 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20191 If the cursor is in a table looking at whitespace, the whitespace is
20192 overwritten, and the table is not marked as requiring realignment."
20193 (interactive "p")
20194 (org-check-before-invisible-edit 'insert)
20195 (cond
20196 ((and org-use-speed-commands
20197 (let ((kv (this-command-keys-vector)))
20198 (setq org-speed-command
20199 (run-hook-with-args-until-success
20200 'org-speed-command-hook
20201 (make-string 1 (aref kv (1- (length kv))))))))
20202 (cond
20203 ((commandp org-speed-command)
20204 (setq this-command org-speed-command)
20205 (call-interactively org-speed-command))
20206 ((functionp org-speed-command)
20207 (funcall org-speed-command))
20208 ((and org-speed-command (listp org-speed-command))
20209 (eval org-speed-command))
20210 (t (let (org-use-speed-commands)
20211 (call-interactively 'org-self-insert-command)))))
20212 ((and
20213 (org-at-table-p)
20214 (progn
20215 ;; Check if we blank the field, and if that triggers align.
20216 (and (featurep 'org-table) org-table-auto-blank-field
20217 (memq last-command
20218 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20219 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20220 ;; Got extra space, this field does not determine
20221 ;; column width.
20222 (let (org-table-may-need-update) (org-table-blank-field))
20223 ;; No extra space, this field may determine column
20224 ;; width.
20225 (org-table-blank-field)))
20227 (eq N 1)
20228 (looking-at "[^|\n]* \\( \\)|"))
20229 ;; There is room for insertion without re-aligning the table.
20230 (delete-region (match-beginning 1) (match-end 1))
20231 (self-insert-command N))
20233 (setq org-table-may-need-update t)
20234 (self-insert-command N)
20235 (org-fix-tags-on-the-fly)
20236 (when org-self-insert-cluster-for-undo
20237 (if (not (eq last-command 'org-self-insert-command))
20238 (setq org-self-insert-command-undo-counter 1)
20239 (if (>= org-self-insert-command-undo-counter 20)
20240 (setq org-self-insert-command-undo-counter 1)
20241 (and (> org-self-insert-command-undo-counter 0)
20242 buffer-undo-list (listp buffer-undo-list)
20243 (not (cadr buffer-undo-list)) ; remove nil entry
20244 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20245 (setq org-self-insert-command-undo-counter
20246 (1+ org-self-insert-command-undo-counter))))))))
20248 (defun org-check-before-invisible-edit (kind)
20249 "Check is editing if kind KIND would be dangerous with invisible text around.
20250 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20251 ;; First, try to get out of here as quickly as possible, to reduce overhead
20252 (when (and org-catch-invisible-edits
20253 (or (not (boundp 'visible-mode)) (not visible-mode))
20254 (or (get-char-property (point) 'invisible)
20255 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20256 ;; OK, we need to take a closer look
20257 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20258 (invisible-before-point (unless (bobp) (get-char-property
20259 (1- (point)) 'invisible)))
20260 (border-and-ok-direction
20262 ;; Check if we are acting predictably before invisible text
20263 (and invisible-at-point (not invisible-before-point)
20264 (memq kind '(insert delete-backward)))
20265 ;; Check if we are acting predictably after invisible text
20266 ;; This works not well, and I have turned it off. It seems
20267 ;; better to always show and stop after invisible text.
20268 ;; (and (not invisible-at-point) invisible-before-point
20269 ;; (memq kind '(insert delete)))
20271 (when (or (memq invisible-at-point '(outline org-hide-block t))
20272 (memq invisible-before-point '(outline org-hide-block t)))
20273 (when (eq org-catch-invisible-edits 'error)
20274 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20275 (if (and org-custom-properties-overlays
20276 (y-or-n-p "Display invisible properties in this buffer? "))
20277 (org-toggle-custom-properties-visibility)
20278 ;; Make the area visible
20279 (save-excursion
20280 (when invisible-before-point
20281 (goto-char (previous-single-char-property-change
20282 (point) 'invisible)))
20283 (outline-show-subtree))
20284 (cond
20285 ((eq org-catch-invisible-edits 'show)
20286 ;; That's it, we do the edit after showing
20287 (message
20288 "Unfolding invisible region around point before editing")
20289 (sit-for 1))
20290 ((and (eq org-catch-invisible-edits 'smart)
20291 border-and-ok-direction)
20292 (message "Unfolding invisible region around point before editing"))
20294 ;; Don't do the edit, make the user repeat it in full visibility
20295 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20297 (defun org-fix-tags-on-the-fly ()
20298 "Align tags in headline at point.
20299 Unlike to `org-set-tags', it ignores region and sorting."
20300 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
20301 (org-at-heading-p))
20302 (let ((org-ignore-region t)
20303 (org-tags-sort-function nil))
20304 (org-set-tags nil t))))
20306 (defun org-delete-backward-char (N)
20307 "Like `delete-backward-char', insert whitespace at field end in tables.
20308 When deleting backwards, in tables this function will insert whitespace in
20309 front of the next \"|\" separator, to keep the table aligned. The table will
20310 still be marked for re-alignment if the field did fill the entire column,
20311 because, in this case the deletion might narrow the column."
20312 (interactive "p")
20313 (save-match-data
20314 (org-check-before-invisible-edit 'delete-backward)
20315 (if (and (org-at-table-p)
20316 (eq N 1)
20317 (string-match "|" (buffer-substring (point-at-bol) (point)))
20318 (looking-at ".*?|"))
20319 (let ((pos (point))
20320 (noalign (looking-at "[^|\n\r]* |"))
20321 (c org-table-may-need-update))
20322 (backward-delete-char N)
20323 (unless overwrite-mode
20324 (skip-chars-forward "^|")
20325 (insert " ")
20326 (goto-char (1- pos)))
20327 ;; noalign: if there were two spaces at the end, this field
20328 ;; does not determine the width of the column.
20329 (when noalign (setq org-table-may-need-update c)))
20330 (backward-delete-char N)
20331 (org-fix-tags-on-the-fly))))
20333 (defun org-delete-char (N)
20334 "Like `delete-char', but insert whitespace at field end in tables.
20335 When deleting characters, in tables this function will insert whitespace in
20336 front of the next \"|\" separator, to keep the table aligned. The table will
20337 still be marked for re-alignment if the field did fill the entire column,
20338 because, in this case the deletion might narrow the column."
20339 (interactive "p")
20340 (save-match-data
20341 (org-check-before-invisible-edit 'delete)
20342 (if (and (org-at-table-p)
20343 (not (bolp))
20344 (not (= (char-after) ?|))
20345 (eq N 1))
20346 (if (looking-at ".*?|")
20347 (let ((pos (point))
20348 (noalign (looking-at "[^|\n\r]* |"))
20349 (c org-table-may-need-update))
20350 (replace-match
20351 (concat (substring (match-string 0) 1 -1) " |") nil t)
20352 (goto-char 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 (delete-char N))
20357 (delete-char N)
20358 (org-fix-tags-on-the-fly))))
20360 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20361 (put 'org-self-insert-command 'delete-selection
20362 (lambda ()
20363 (not (run-hook-with-args-until-success
20364 'self-insert-uses-region-functions))))
20365 (put 'orgtbl-self-insert-command 'delete-selection
20366 (lambda ()
20367 (not (run-hook-with-args-until-success
20368 'self-insert-uses-region-functions))))
20369 (put 'org-delete-char 'delete-selection 'supersede)
20370 (put 'org-delete-backward-char 'delete-selection 'supersede)
20371 (put 'org-yank 'delete-selection 'yank)
20373 ;; Make `flyspell-mode' delay after some commands
20374 (put 'org-self-insert-command 'flyspell-delayed t)
20375 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20376 (put 'org-delete-char 'flyspell-delayed t)
20377 (put 'org-delete-backward-char 'flyspell-delayed t)
20379 ;; Make pabbrev-mode expand after Org mode commands
20380 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20381 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20383 (defun org-remap (map &rest commands)
20384 "In MAP, remap the functions given in COMMANDS.
20385 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20386 (let (new old)
20387 (while commands
20388 (setq old (pop commands) new (pop commands))
20389 (org-defkey map (vector 'remap old) new))))
20391 (defun org-transpose-words ()
20392 "Transpose words for Org.
20393 This uses the `org-mode-transpose-word-syntax-table' syntax
20394 table, which interprets characters in `org-emphasis-alist' as
20395 word constituents."
20396 (interactive)
20397 (with-syntax-table org-mode-transpose-word-syntax-table
20398 (call-interactively 'transpose-words)))
20399 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20401 (when (eq org-enable-table-editor 'optimized)
20402 ;; If the user wants maximum table support, we need to hijack
20403 ;; some standard editing functions
20404 (org-remap org-mode-map
20405 'self-insert-command 'org-self-insert-command
20406 'delete-char 'org-delete-char
20407 'delete-backward-char 'org-delete-backward-char)
20408 (org-defkey org-mode-map "|" 'org-force-self-insert))
20410 (defvar org-ctrl-c-ctrl-c-hook nil
20411 "Hook for functions attaching themselves to `C-c C-c'.
20413 This can be used to add additional functionality to the C-c C-c
20414 key which executes context-dependent commands. This hook is run
20415 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20416 run after the last test.
20418 Each function will be called with no arguments. The function
20419 must check if the context is appropriate for it to act. If yes,
20420 it should do its thing and then return a non-nil value. If the
20421 context is wrong, just do nothing and return nil.")
20423 (defvar org-ctrl-c-ctrl-c-final-hook nil
20424 "Hook for functions attaching themselves to `C-c C-c'.
20426 This can be used to add additional functionality to the C-c C-c
20427 key which executes context-dependent commands. This hook is run
20428 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20429 before the first test.
20431 Each function will be called with no arguments. The function
20432 must check if the context is appropriate for it to act. If yes,
20433 it should do its thing and then return a non-nil value. If the
20434 context is wrong, just do nothing and return nil.")
20436 (defvar org-tab-first-hook nil
20437 "Hook for functions to attach themselves to TAB.
20438 See `org-ctrl-c-ctrl-c-hook' for more information.
20439 This hook runs as the first action when TAB is pressed, even before
20440 `org-cycle' messes around with the `outline-regexp' to cater for
20441 inline tasks and plain list item folding.
20442 If any function in this hook returns t, any other actions that
20443 would have been caused by TAB (such as table field motion or visibility
20444 cycling) will not occur.")
20446 (defvar org-tab-after-check-for-table-hook nil
20447 "Hook for functions to attach themselves to TAB.
20448 See `org-ctrl-c-ctrl-c-hook' for more information.
20449 This hook runs after it has been established that the cursor is not in a
20450 table, but before checking if the cursor is in a headline or if global cycling
20451 should be done.
20452 If any function in this hook returns t, not other actions like visibility
20453 cycling will be done.")
20455 (defvar org-tab-after-check-for-cycling-hook nil
20456 "Hook for functions to attach themselves to TAB.
20457 See `org-ctrl-c-ctrl-c-hook' for more information.
20458 This hook runs after it has been established that not table field motion and
20459 not visibility should be done because of current context. This is probably
20460 the place where a package like yasnippets can hook in.")
20462 (defvar org-tab-before-tab-emulation-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 after every other options for TAB have been exhausted, but
20466 before indentation and \t insertion takes place.")
20468 (defvar org-metaleft-hook nil
20469 "Hook for functions attaching themselves to `M-left'.
20470 See `org-ctrl-c-ctrl-c-hook' for more information.")
20471 (defvar org-metaright-hook nil
20472 "Hook for functions attaching themselves to `M-right'.
20473 See `org-ctrl-c-ctrl-c-hook' for more information.")
20474 (defvar org-metaup-hook nil
20475 "Hook for functions attaching themselves to `M-up'.
20476 See `org-ctrl-c-ctrl-c-hook' for more information.")
20477 (defvar org-metadown-hook nil
20478 "Hook for functions attaching themselves to `M-down'.
20479 See `org-ctrl-c-ctrl-c-hook' for more information.")
20480 (defvar org-shiftmetaleft-hook nil
20481 "Hook for functions attaching themselves to `M-S-left'.
20482 See `org-ctrl-c-ctrl-c-hook' for more information.")
20483 (defvar org-shiftmetaright-hook nil
20484 "Hook for functions attaching themselves to `M-S-right'.
20485 See `org-ctrl-c-ctrl-c-hook' for more information.")
20486 (defvar org-shiftmetaup-hook nil
20487 "Hook for functions attaching themselves to `M-S-up'.
20488 See `org-ctrl-c-ctrl-c-hook' for more information.")
20489 (defvar org-shiftmetadown-hook nil
20490 "Hook for functions attaching themselves to `M-S-down'.
20491 See `org-ctrl-c-ctrl-c-hook' for more information.")
20492 (defvar org-metareturn-hook nil
20493 "Hook for functions attaching themselves to `M-RET'.
20494 See `org-ctrl-c-ctrl-c-hook' for more information.")
20495 (defvar org-shiftup-hook nil
20496 "Hook for functions attaching themselves to `S-up'.
20497 See `org-ctrl-c-ctrl-c-hook' for more information.")
20498 (defvar org-shiftup-final-hook nil
20499 "Hook for functions attaching themselves to `S-up'.
20500 This one runs after all other options except shift-select have been excluded.
20501 See `org-ctrl-c-ctrl-c-hook' for more information.")
20502 (defvar org-shiftdown-hook nil
20503 "Hook for functions attaching themselves to `S-down'.
20504 See `org-ctrl-c-ctrl-c-hook' for more information.")
20505 (defvar org-shiftdown-final-hook nil
20506 "Hook for functions attaching themselves to `S-down'.
20507 This one runs after all other options except shift-select have been excluded.
20508 See `org-ctrl-c-ctrl-c-hook' for more information.")
20509 (defvar org-shiftleft-hook nil
20510 "Hook for functions attaching themselves to `S-left'.
20511 See `org-ctrl-c-ctrl-c-hook' for more information.")
20512 (defvar org-shiftleft-final-hook nil
20513 "Hook for functions attaching themselves to `S-left'.
20514 This one runs after all other options except shift-select have been excluded.
20515 See `org-ctrl-c-ctrl-c-hook' for more information.")
20516 (defvar org-shiftright-hook nil
20517 "Hook for functions attaching themselves to `S-right'.
20518 See `org-ctrl-c-ctrl-c-hook' for more information.")
20519 (defvar org-shiftright-final-hook nil
20520 "Hook for functions attaching themselves to `S-right'.
20521 This one runs after all other options except shift-select have been excluded.
20522 See `org-ctrl-c-ctrl-c-hook' for more information.")
20524 (defun org-modifier-cursor-error ()
20525 "Throw an error, a modified cursor command was applied in wrong context."
20526 (user-error "This command is active in special context like tables, headlines or items"))
20528 (defun org-shiftselect-error ()
20529 "Throw an error because Shift-Cursor command was applied in wrong context."
20530 (if (and (boundp 'shift-select-mode) shift-select-mode)
20531 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20532 (user-error "This command works only in special context like headlines or timestamps")))
20534 (defun org-call-for-shift-select (cmd)
20535 (let ((this-command-keys-shift-translated t))
20536 (call-interactively cmd)))
20538 (defun org-shifttab (&optional arg)
20539 "Global visibility cycling or move to previous table field.
20540 Call `org-table-previous-field' within a table.
20541 When ARG is nil, cycle globally through visibility states.
20542 When ARG is a numeric prefix, show contents of this level."
20543 (interactive "P")
20544 (cond
20545 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20546 ((integerp arg)
20547 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20548 (message "Content view to level: %d" arg)
20549 (org-content (prefix-numeric-value arg2))
20550 (org-cycle-show-empty-lines t)
20551 (setq org-cycle-global-status 'overview)))
20552 (t (call-interactively 'org-global-cycle))))
20554 (defun org-shiftmetaleft ()
20555 "Promote subtree or delete table column.
20556 Calls `org-promote-subtree', `org-outdent-item-tree', or
20557 `org-table-delete-column', depending on context. See the
20558 individual commands for more information."
20559 (interactive)
20560 (cond
20561 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20562 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20563 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20564 ((if (not (org-region-active-p)) (org-at-item-p)
20565 (save-excursion (goto-char (region-beginning))
20566 (org-at-item-p)))
20567 (call-interactively 'org-outdent-item-tree))
20568 (t (org-modifier-cursor-error))))
20570 (defun org-shiftmetaright ()
20571 "Demote subtree or insert table column.
20572 Calls `org-demote-subtree', `org-indent-item-tree', or
20573 `org-table-insert-column', depending on context. See the
20574 individual commands for more information."
20575 (interactive)
20576 (cond
20577 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20578 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20579 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20580 ((if (not (org-region-active-p)) (org-at-item-p)
20581 (save-excursion (goto-char (region-beginning))
20582 (org-at-item-p)))
20583 (call-interactively 'org-indent-item-tree))
20584 (t (org-modifier-cursor-error))))
20586 (defun org-shiftmetaup (&optional _arg)
20587 "Drag the line at point up.
20588 In a table, kill the current row.
20589 On a clock timestamp, update the value of the timestamp like `S-<up>'
20590 but also adjust the previous clocked item in the clock history.
20591 Everywhere else, drag the line at point up."
20592 (interactive "P")
20593 (cond
20594 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20595 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20596 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20597 (call-interactively 'org-timestamp-up)))
20598 (t (call-interactively 'org-drag-line-backward))))
20600 (defun org-shiftmetadown (&optional _arg)
20601 "Drag the line at point down.
20602 In a table, insert an empty row at the current line.
20603 On a clock timestamp, update the value of the timestamp like `S-<down>'
20604 but also adjust the previous clocked item in the clock history.
20605 Everywhere else, drag the line at point down."
20606 (interactive "P")
20607 (cond
20608 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20609 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20610 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20611 (call-interactively 'org-timestamp-down)))
20612 (t (call-interactively 'org-drag-line-forward))))
20614 (defsubst org-hidden-tree-error ()
20615 (user-error
20616 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20618 (defun org-metaleft (&optional _arg)
20619 "Promote heading, list item at point or move table column left.
20621 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20622 depending on context. With no specific context, calls the Emacs
20623 default `backward-word'. See the individual commands for more
20624 information.
20626 This function runs the hook `org-metaleft-hook' as a first step,
20627 and returns at first non-nil value."
20628 (interactive "P")
20629 (cond
20630 ((run-hook-with-args-until-success 'org-metaleft-hook))
20631 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20632 ((org-with-limited-levels
20633 (or (org-at-heading-p)
20634 (and (org-region-active-p)
20635 (save-excursion
20636 (goto-char (region-beginning))
20637 (org-at-heading-p)))))
20638 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20639 (call-interactively 'org-do-promote))
20640 ;; At an inline task.
20641 ((org-at-heading-p)
20642 (call-interactively 'org-inlinetask-promote))
20643 ((or (org-at-item-p)
20644 (and (org-region-active-p)
20645 (save-excursion
20646 (goto-char (region-beginning))
20647 (org-at-item-p))))
20648 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20649 (call-interactively 'org-outdent-item))
20650 (t (call-interactively 'backward-word))))
20652 (defun org-metaright (&optional _arg)
20653 "Demote heading, list item at point or move table column right.
20655 In front of a drawer or a block keyword, indent it correctly.
20657 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20658 `org-indent-drawer' or `org-indent-block' depending on context.
20659 With no specific context, calls the Emacs default `forward-word'.
20660 See the individual commands for more information.
20662 This function runs the hook `org-metaright-hook' as a first step,
20663 and returns at first non-nil value."
20664 (interactive "P")
20665 (cond
20666 ((run-hook-with-args-until-success 'org-metaright-hook))
20667 ((org-at-table-p) (call-interactively 'org-table-move-column))
20668 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20669 ((org-at-block-p) (call-interactively 'org-indent-block))
20670 ((org-with-limited-levels
20671 (or (org-at-heading-p)
20672 (and (org-region-active-p)
20673 (save-excursion
20674 (goto-char (region-beginning))
20675 (org-at-heading-p)))))
20676 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20677 (call-interactively 'org-do-demote))
20678 ;; At an inline task.
20679 ((org-at-heading-p)
20680 (call-interactively 'org-inlinetask-demote))
20681 ((or (org-at-item-p)
20682 (and (org-region-active-p)
20683 (save-excursion
20684 (goto-char (region-beginning))
20685 (org-at-item-p))))
20686 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20687 (call-interactively 'org-indent-item))
20688 (t (call-interactively 'forward-word))))
20690 (defun org-check-for-hidden (what)
20691 "Check if there are hidden headlines/items in the current visual line.
20692 WHAT can be either `headlines' or `items'. If the current line is
20693 an outline or item heading and it has a folded subtree below it,
20694 this function returns t, nil otherwise."
20695 (let ((re (cond
20696 ((eq what 'headlines) org-outline-regexp-bol)
20697 ((eq what 'items) (org-item-beginning-re))
20698 (t (error "This should not happen"))))
20699 beg end)
20700 (save-excursion
20701 (catch 'exit
20702 (unless (org-region-active-p)
20703 (setq beg (point-at-bol))
20704 (beginning-of-line 2)
20705 (while (and (not (eobp)) ;; this is like `next-line'
20706 (get-char-property (1- (point)) 'invisible))
20707 (beginning-of-line 2))
20708 (setq end (point))
20709 (goto-char beg)
20710 (goto-char (point-at-eol))
20711 (setq end (max end (point)))
20712 (while (re-search-forward re end t)
20713 (when (get-char-property (match-beginning 0) 'invisible)
20714 (throw 'exit t))))
20715 nil))))
20717 (defun org-metaup (&optional _arg)
20718 "Move subtree up or move table row up.
20719 Calls `org-move-subtree-up' or `org-table-move-row' or
20720 `org-move-item-up', depending on context. See the individual commands
20721 for more information."
20722 (interactive "P")
20723 (cond
20724 ((run-hook-with-args-until-success 'org-metaup-hook))
20725 ((org-region-active-p)
20726 (let* ((a (min (region-beginning) (region-end)))
20727 (b (1- (max (region-beginning) (region-end))))
20728 (c (save-excursion (goto-char a)
20729 (move-beginning-of-line 0)))
20730 (d (save-excursion (goto-char a)
20731 (move-end-of-line 0) (point))))
20732 (transpose-regions a b c d)
20733 (goto-char c)))
20734 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20735 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20736 ((org-at-item-p) (call-interactively 'org-move-item-up))
20737 (t (org-drag-element-backward))))
20739 (defun org-metadown (&optional _arg)
20740 "Move subtree down or move table row down.
20741 Calls `org-move-subtree-down' or `org-table-move-row' or
20742 `org-move-item-down', depending on context. See the individual
20743 commands for more information."
20744 (interactive "P")
20745 (cond
20746 ((run-hook-with-args-until-success 'org-metadown-hook))
20747 ((org-region-active-p)
20748 (let* ((a (min (region-beginning) (region-end)))
20749 (b (max (region-beginning) (region-end)))
20750 (c (save-excursion (goto-char b)
20751 (move-beginning-of-line 1)))
20752 (d (save-excursion (goto-char b)
20753 (move-end-of-line 1) (1+ (point)))))
20754 (transpose-regions a b c d)
20755 (goto-char d)))
20756 ((org-at-table-p) (call-interactively 'org-table-move-row))
20757 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20758 ((org-at-item-p) (call-interactively 'org-move-item-down))
20759 (t (org-drag-element-forward))))
20761 (defun org-shiftup (&optional arg)
20762 "Increase item in timestamp or increase priority of current headline.
20763 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20764 depending on context. See the individual commands for more information."
20765 (interactive "P")
20766 (cond
20767 ((run-hook-with-args-until-success 'org-shiftup-hook))
20768 ((and org-support-shift-select (org-region-active-p))
20769 (org-call-for-shift-select 'previous-line))
20770 ((org-at-timestamp-p t)
20771 (call-interactively (if org-edit-timestamp-down-means-later
20772 'org-timestamp-down 'org-timestamp-up)))
20773 ((and (not (eq org-support-shift-select 'always))
20774 org-enable-priority-commands
20775 (org-at-heading-p))
20776 (call-interactively 'org-priority-up))
20777 ((and (not org-support-shift-select) (org-at-item-p))
20778 (call-interactively 'org-previous-item))
20779 ((org-clocktable-try-shift 'up arg))
20780 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20781 (org-support-shift-select
20782 (org-call-for-shift-select 'previous-line))
20783 (t (org-shiftselect-error))))
20785 (defun org-shiftdown (&optional arg)
20786 "Decrease item in timestamp or decrease priority of current headline.
20787 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20788 depending on context. See the individual commands for more information."
20789 (interactive "P")
20790 (cond
20791 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20792 ((and org-support-shift-select (org-region-active-p))
20793 (org-call-for-shift-select 'next-line))
20794 ((org-at-timestamp-p t)
20795 (call-interactively (if org-edit-timestamp-down-means-later
20796 'org-timestamp-up 'org-timestamp-down)))
20797 ((and (not (eq org-support-shift-select 'always))
20798 org-enable-priority-commands
20799 (org-at-heading-p))
20800 (call-interactively 'org-priority-down))
20801 ((and (not org-support-shift-select) (org-at-item-p))
20802 (call-interactively 'org-next-item))
20803 ((org-clocktable-try-shift 'down arg))
20804 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20805 (org-support-shift-select
20806 (org-call-for-shift-select 'next-line))
20807 (t (org-shiftselect-error))))
20809 (defun org-shiftright (&optional arg)
20810 "Cycle the thing at point or in the current line, depending on context.
20811 Depending on context, this does one of the following:
20813 - switch a timestamp at point one day into the future
20814 - on a headline, switch to the next TODO keyword.
20815 - on an item, switch entire list to the next bullet type
20816 - on a property line, switch to the next allowed value
20817 - on a clocktable definition line, move time block into the future"
20818 (interactive "P")
20819 (cond
20820 ((run-hook-with-args-until-success 'org-shiftright-hook))
20821 ((and org-support-shift-select (org-region-active-p))
20822 (org-call-for-shift-select 'forward-char))
20823 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20824 ((and (not (eq org-support-shift-select 'always))
20825 (org-at-heading-p))
20826 (let ((org-inhibit-logging
20827 (not org-treat-S-cursor-todo-selection-as-state-change))
20828 (org-inhibit-blocking
20829 (not org-treat-S-cursor-todo-selection-as-state-change)))
20830 (org-call-with-arg 'org-todo 'right)))
20831 ((or (and org-support-shift-select
20832 (not (eq org-support-shift-select 'always))
20833 (org-at-item-bullet-p))
20834 (and (not org-support-shift-select) (org-at-item-p)))
20835 (org-call-with-arg 'org-cycle-list-bullet nil))
20836 ((and (not (eq org-support-shift-select 'always))
20837 (org-at-property-p))
20838 (call-interactively 'org-property-next-allowed-value))
20839 ((org-clocktable-try-shift 'right arg))
20840 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20841 (org-support-shift-select
20842 (org-call-for-shift-select 'forward-char))
20843 (t (org-shiftselect-error))))
20845 (defun org-shiftleft (&optional arg)
20846 "Cycle the thing at point or in the current line, depending on context.
20847 Depending on context, this does one of the following:
20849 - switch a timestamp at point one day into the past
20850 - on a headline, switch to the previous TODO keyword.
20851 - on an item, switch entire list to the previous bullet type
20852 - on a property line, switch to the previous allowed value
20853 - on a clocktable definition line, move time block into the past"
20854 (interactive "P")
20855 (cond
20856 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20857 ((and org-support-shift-select (org-region-active-p))
20858 (org-call-for-shift-select 'backward-char))
20859 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20860 ((and (not (eq org-support-shift-select 'always))
20861 (org-at-heading-p))
20862 (let ((org-inhibit-logging
20863 (not org-treat-S-cursor-todo-selection-as-state-change))
20864 (org-inhibit-blocking
20865 (not org-treat-S-cursor-todo-selection-as-state-change)))
20866 (org-call-with-arg 'org-todo 'left)))
20867 ((or (and org-support-shift-select
20868 (not (eq org-support-shift-select 'always))
20869 (org-at-item-bullet-p))
20870 (and (not org-support-shift-select) (org-at-item-p)))
20871 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20872 ((and (not (eq org-support-shift-select 'always))
20873 (org-at-property-p))
20874 (call-interactively 'org-property-previous-allowed-value))
20875 ((org-clocktable-try-shift 'left arg))
20876 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20877 (org-support-shift-select
20878 (org-call-for-shift-select 'backward-char))
20879 (t (org-shiftselect-error))))
20881 (defun org-shiftcontrolright ()
20882 "Switch to next TODO set."
20883 (interactive)
20884 (cond
20885 ((and org-support-shift-select (org-region-active-p))
20886 (org-call-for-shift-select 'forward-word))
20887 ((and (not (eq org-support-shift-select 'always))
20888 (org-at-heading-p))
20889 (org-call-with-arg 'org-todo 'nextset))
20890 (org-support-shift-select
20891 (org-call-for-shift-select 'forward-word))
20892 (t (org-shiftselect-error))))
20894 (defun org-shiftcontrolleft ()
20895 "Switch to previous TODO set."
20896 (interactive)
20897 (cond
20898 ((and org-support-shift-select (org-region-active-p))
20899 (org-call-for-shift-select 'backward-word))
20900 ((and (not (eq org-support-shift-select 'always))
20901 (org-at-heading-p))
20902 (org-call-with-arg 'org-todo 'previousset))
20903 (org-support-shift-select
20904 (org-call-for-shift-select 'backward-word))
20905 (t (org-shiftselect-error))))
20907 (defun org-shiftcontrolup (&optional n)
20908 "Change timestamps synchronously up in CLOCK log lines.
20909 Optional argument N tells to change by that many units."
20910 (interactive "P")
20911 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20912 (let (org-support-shift-select)
20913 (org-clock-timestamps-up n))
20914 (user-error "Not at a clock log")))
20916 (defun org-shiftcontroldown (&optional n)
20917 "Change timestamps synchronously down in CLOCK log lines.
20918 Optional argument N tells to change by that many units."
20919 (interactive "P")
20920 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20921 (let (org-support-shift-select)
20922 (org-clock-timestamps-down n))
20923 (user-error "Not at a clock log")))
20925 (defun org-increase-number-at-point (&optional inc)
20926 "Increment the number at point.
20927 With an optional prefix numeric argument INC, increment using
20928 this numeric value."
20929 (interactive "p")
20930 (if (not (number-at-point))
20931 (user-error "Not on a number")
20932 (unless inc (setq inc 1))
20933 (let ((pos (point))
20934 (beg (skip-chars-backward "-+^/*0-9eE."))
20935 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20936 (setq nap (buffer-substring-no-properties
20937 (+ pos beg) (+ pos beg end)))
20938 (delete-region (+ pos beg) (+ pos beg end))
20939 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20940 (when (org-at-table-p)
20941 (org-table-align)
20942 (org-table-end-of-field 1))))
20944 (defun org-decrease-number-at-point (&optional inc)
20945 "Decrement the number at point.
20946 With an optional prefix numeric argument INC, decrement using
20947 this numeric value."
20948 (interactive "p")
20949 (org-increase-number-at-point (- (or inc 1))))
20951 (defun org-ctrl-c-ret ()
20952 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20953 (interactive)
20954 (cond
20955 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20956 (t (call-interactively 'org-insert-heading))))
20958 (defun org-find-visible ()
20959 (let ((s (point)))
20960 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20961 (get-char-property s 'invisible)))
20963 (defun org-find-invisible ()
20964 (let ((s (point)))
20965 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20966 (not (get-char-property s 'invisible))))
20969 (defun org-copy-visible (beg end)
20970 "Copy the visible parts of the region."
20971 (interactive "r")
20972 (let (snippets s)
20973 (save-excursion
20974 (save-restriction
20975 (narrow-to-region beg end)
20976 (setq s (goto-char (point-min)))
20977 (while (not (= (point) (point-max)))
20978 (goto-char (org-find-invisible))
20979 (push (buffer-substring s (point)) snippets)
20980 (setq s (goto-char (org-find-visible))))))
20981 (kill-new (apply 'concat (nreverse snippets)))))
20983 (defun org-copy-special ()
20984 "Copy region in table or copy current subtree.
20985 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20986 context. See the individual commands for more information."
20987 (interactive)
20988 (call-interactively
20989 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20991 (defun org-cut-special ()
20992 "Cut region in table or cut current subtree.
20993 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20994 context. See the individual commands for more information."
20995 (interactive)
20996 (call-interactively
20997 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20999 (defun org-paste-special (arg)
21000 "Paste rectangular region into table, or past subtree relative to level.
21001 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
21002 See the individual commands for more information."
21003 (interactive "P")
21004 (if (org-at-table-p)
21005 (org-table-paste-rectangle)
21006 (org-paste-subtree arg)))
21008 (defun org-edit-special (&optional arg)
21009 "Call a special editor for the element at point.
21010 When at a table, call the formula editor with `org-table-edit-formulas'.
21011 When in a source code block, call `org-edit-src-code'.
21012 When in a fixed-width region, call `org-edit-fixed-width-region'.
21013 When in an export block, call `org-edit-export-block'.
21014 When at an #+INCLUDE keyword, visit the included file.
21015 When at a footnote reference, call `org-edit-footnote-reference'
21016 On a link, call `ffap' to visit the link at point.
21017 Otherwise, return a user error."
21018 (interactive "P")
21019 (let ((element (org-element-at-point)))
21020 (barf-if-buffer-read-only)
21021 (pcase (org-element-type element)
21022 (`src-block
21023 (if (not arg) (org-edit-src-code)
21024 (let* ((info (org-babel-get-src-block-info))
21025 (lang (nth 0 info))
21026 (params (nth 2 info))
21027 (session (cdr (assq :session params))))
21028 (if (not session) (org-edit-src-code)
21029 ;; At a src-block with a session and function called with
21030 ;; an ARG: switch to the buffer related to the inferior
21031 ;; process.
21032 (switch-to-buffer
21033 (funcall (intern (concat "org-babel-prep-session:" lang))
21034 session params))))))
21035 (`keyword
21036 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
21037 (org-open-link-from-string
21038 (format "[[%s]]"
21039 (expand-file-name
21040 (let ((value (org-element-property :value element)))
21041 (cond ((not (org-string-nw-p value))
21042 (user-error "No file to edit"))
21043 ((string-match "\\`\"\\(.*?\\)\"" value)
21044 (match-string 1 value))
21045 ((string-match "\\`[^ \t\"]\\S-*" value)
21046 (match-string 0 value))
21047 (t (user-error "No valid file specified")))))))
21048 (user-error "No special environment to edit here")))
21049 (`table
21050 (if (eq (org-element-property :type element) 'table.el)
21051 (org-edit-table.el)
21052 (call-interactively 'org-table-edit-formulas)))
21053 ;; Only Org tables contain `table-row' type elements.
21054 (`table-row (call-interactively 'org-table-edit-formulas))
21055 (`example-block (org-edit-src-code))
21056 (`export-block (org-edit-export-block))
21057 (`fixed-width (org-edit-fixed-width-region))
21059 ;; No notable element at point. Though, we may be at a link or
21060 ;; a footnote reference, which are objects. Thus, scan deeper.
21061 (let ((context (org-element-context element)))
21062 (pcase (org-element-type context)
21063 (`footnote-reference (org-edit-footnote-reference))
21064 (`inline-src-block (org-edit-inline-src-code))
21065 (`link (call-interactively #'ffap))
21066 (_ (user-error "No special environment to edit here"))))))))
21068 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21069 (defun org-ctrl-c-ctrl-c (&optional arg)
21070 "Set tags in headline, or update according to changed information at point.
21072 This command does many different things, depending on context:
21074 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21075 this is what we do.
21077 - If the cursor is on a statistics cookie, update it.
21079 - If the cursor is in a headline, prompt for tags and insert them
21080 into the current line, aligned to `org-tags-column'. When called
21081 with prefix arg, realign all tags in the current buffer.
21083 - If the cursor is in one of the special #+KEYWORD lines, this
21084 triggers scanning the buffer for these lines and updating the
21085 information.
21087 - If the cursor is inside a table, realign the table. This command
21088 works even if the automatic table editor has been turned off.
21090 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21091 the entire table.
21093 - If the cursor is at a footnote reference or definition, jump to
21094 the corresponding definition or references, respectively.
21096 - If the cursor is a the beginning of a dynamic block, update it.
21098 - If the current buffer is a capture buffer, close note and file it.
21100 - If the cursor is on a <<<target>>>, update radio targets and
21101 corresponding links in this buffer.
21103 - If the cursor is on a numbered item in a plain list, renumber the
21104 ordered list.
21106 - If the cursor is on a checkbox, toggle it.
21108 - If the cursor is on a code block, evaluate it. The variable
21109 `org-confirm-babel-evaluate' can be used to control prompting
21110 before code block evaluation, by default every code block
21111 evaluation requires confirmation. Code block evaluation can be
21112 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21113 (interactive "P")
21114 (cond
21115 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
21116 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21117 (org-remove-occur-highlights)
21118 (message "Temporary highlights/overlays removed from current buffer"))
21119 ((and (local-variable-p 'org-finish-function)
21120 (fboundp org-finish-function))
21121 (funcall org-finish-function))
21122 ((org-babel-hash-at-point))
21123 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21124 ((save-excursion (beginning-of-line) (looking-at-p "[ \t]*$"))
21125 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21126 (user-error
21127 (substitute-command-keys
21128 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
21130 (let* ((context
21131 (org-element-lineage
21132 (org-element-context)
21133 ;; Limit to supported contexts.
21134 '(babel-call clock dynamic-block footnote-definition
21135 footnote-reference inline-babel-call inline-src-block
21136 item keyword node-property paragraph plain-list
21137 property-drawer radio-target src-block
21138 statistics-cookie table table-cell table-row
21139 timestamp)
21141 (type (org-element-type context)))
21142 ;; For convenience: at the first line of a paragraph on the same
21143 ;; line as an item, apply function on that item instead.
21144 (when (eq type 'paragraph)
21145 (let ((parent (org-element-property :parent context)))
21146 (when (and (eq (org-element-type parent) 'item)
21147 (= (line-beginning-position)
21148 (org-element-property :begin parent)))
21149 (setq context parent)
21150 (setq type 'item))))
21151 ;; Act according to type of element or object at point.
21152 (pcase type
21153 ((or `babel-call `inline-babel-call)
21154 (let ((info (org-babel-lob-get-info context)))
21155 (when info (org-babel-execute-src-block nil info))))
21156 (`clock (org-clock-update-time-maybe))
21157 (`dynamic-block
21158 (save-excursion
21159 (goto-char (org-element-property :post-affiliated context))
21160 (org-update-dblock)))
21161 (`footnote-definition
21162 (goto-char (org-element-property :post-affiliated context))
21163 (call-interactively 'org-footnote-action))
21164 (`footnote-reference (call-interactively #'org-footnote-action))
21165 ((or `headline `inlinetask)
21166 (save-excursion (goto-char (org-element-property :begin context))
21167 (call-interactively #'org-set-tags)))
21168 ((or `inline-src-block `src-block)
21169 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
21170 (org-babel-eval-wipe-error-buffer)
21171 (org-babel-execute-src-block
21172 current-prefix-arg (org-babel-get-src-block-info nil context))))
21173 (`item
21174 ;; At an item: `C-u C-u' sets checkbox to "[-]"
21175 ;; unconditionally, whereas `C-u' will toggle its presence.
21176 ;; Without a universal argument, if the item has a checkbox,
21177 ;; toggle it. Otherwise repair the list.
21178 (let* ((box (org-element-property :checkbox context))
21179 (struct (org-element-property :structure context))
21180 (old-struct (copy-tree struct))
21181 (parents (org-list-parents-alist struct))
21182 (prevs (org-list-prevs-alist struct))
21183 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21184 (org-list-set-checkbox
21185 (org-element-property :begin context) struct
21186 (cond ((equal arg '(16)) "[-]")
21187 ((and (not box) (equal arg '(4))) "[ ]")
21188 ((or (not box) (equal arg '(4))) nil)
21189 ((eq box 'on) "[ ]")
21190 (t "[X]")))
21191 ;; Mimic `org-list-write-struct' but with grabbing a return
21192 ;; value from `org-list-struct-fix-box'.
21193 (org-list-struct-fix-ind struct parents 2)
21194 (org-list-struct-fix-item-end struct)
21195 (org-list-struct-fix-bul struct prevs)
21196 (org-list-struct-fix-ind struct parents)
21197 (let ((block-item
21198 (org-list-struct-fix-box struct parents prevs orderedp)))
21199 (if (and box (equal struct old-struct))
21200 (if (equal arg '(16))
21201 (message "Checkboxes already reset")
21202 (user-error "Cannot toggle this checkbox: %s"
21203 (if (eq box 'on)
21204 "all subitems checked"
21205 "unchecked subitems")))
21206 (org-list-struct-apply-struct struct old-struct)
21207 (org-update-checkbox-count-maybe))
21208 (when block-item
21209 (message "Checkboxes were removed due to empty box at line %d"
21210 (org-current-line block-item))))))
21211 (`keyword
21212 (let ((org-inhibit-startup-visibility-stuff t)
21213 (org-startup-align-all-tables nil))
21214 (when (boundp 'org-table-coordinate-overlays)
21215 (mapc #'delete-overlay org-table-coordinate-overlays)
21216 (setq org-table-coordinate-overlays nil))
21217 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21218 (message "Local setup has been refreshed"))
21219 (`plain-list
21220 ;; At a plain list, with a double C-u argument, set
21221 ;; checkboxes of each item to "[-]", whereas a single one
21222 ;; will toggle their presence according to the state of the
21223 ;; first item in the list. Without an argument, repair the
21224 ;; list.
21225 (let* ((begin (org-element-property :contents-begin context))
21226 (beginm (move-marker (make-marker) begin))
21227 (struct (org-element-property :structure context))
21228 (old-struct (copy-tree struct))
21229 (first-box (save-excursion
21230 (goto-char begin)
21231 (looking-at org-list-full-item-re)
21232 (match-string-no-properties 3)))
21233 (new-box (cond ((equal arg '(16)) "[-]")
21234 ((equal arg '(4)) (unless first-box "[ ]"))
21235 ((equal first-box "[X]") "[ ]")
21236 (t "[X]"))))
21237 (cond
21238 (arg
21239 (dolist (pos
21240 (org-list-get-all-items
21241 begin struct (org-list-prevs-alist struct)))
21242 (org-list-set-checkbox pos struct new-box)))
21243 ((and first-box (eq (point) begin))
21244 ;; For convenience, when point is at bol on the first
21245 ;; item of the list and no argument is provided, simply
21246 ;; toggle checkbox of that item, if any.
21247 (org-list-set-checkbox begin struct new-box)))
21248 (org-list-write-struct
21249 struct (org-list-parents-alist struct) old-struct)
21250 (org-update-checkbox-count-maybe)
21251 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21252 ((or `property-drawer `node-property)
21253 (call-interactively #'org-property-action))
21254 (`radio-target
21255 (call-interactively #'org-update-radio-target-regexp))
21256 (`statistics-cookie
21257 (call-interactively #'org-update-statistics-cookies))
21258 ((or `table `table-cell `table-row)
21259 ;; At a table, recalculate every field and align it. Also
21260 ;; send the table if necessary. If the table has
21261 ;; a `table.el' type, just give up. At a table row or cell,
21262 ;; maybe recalculate line but always align table.
21263 (if (eq (org-element-property :type context) 'table.el)
21264 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21265 Use `\\[org-edit-special]' to edit table.el tables"))
21266 (let ((org-enable-table-editor t))
21267 (if (or (eq type 'table)
21268 ;; Check if point is at a TBLFM line.
21269 (and (eq type 'table-row)
21270 (= (point) (org-element-property :end context))))
21271 (save-excursion
21272 (if (org-at-TBLFM-p)
21273 (progn (require 'org-table)
21274 (org-table-calc-current-TBLFM))
21275 (goto-char (org-element-property :contents-begin context))
21276 (org-call-with-arg 'org-table-recalculate (or arg t))
21277 (orgtbl-send-table 'maybe)))
21278 (org-table-maybe-eval-formula)
21279 (cond (arg (call-interactively #'org-table-recalculate))
21280 ((org-table-maybe-recalculate-line))
21281 (t (org-table-align)))))))
21282 (`timestamp (org-timestamp-change 0 'day))
21283 ((and `nil (guard (org-at-heading-p)))
21284 ;; When point is on an unsupported object type, we can miss
21285 ;; the fact that it also is at a heading. Handle it here.
21286 (call-interactively #'org-set-tags))
21287 ((guard
21288 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
21290 (user-error
21291 (substitute-command-keys
21292 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
21294 (defun org-mode-restart ()
21295 (interactive)
21296 (let ((indent-status (bound-and-true-p org-indent-mode)))
21297 (funcall major-mode)
21298 (hack-local-variables)
21299 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21300 (org-indent-mode -1)))
21301 (message "%s restarted" major-mode))
21303 (defun org-kill-note-or-show-branches ()
21304 "Abort storing current note, or call `outline-show-branches'."
21305 (interactive)
21306 (if (not org-finish-function)
21307 (progn
21308 (outline-hide-subtree)
21309 (call-interactively 'outline-show-branches))
21310 (let ((org-note-abort t))
21311 (funcall org-finish-function))))
21313 (defun org-delete-indentation (&optional arg)
21314 "Join current line to previous and fix whitespace at join.
21316 If previous line is a headline add to headline title. Otherwise
21317 the function calls `delete-indentation'.
21319 With a non-nil optional argument, join it to the following one."
21320 (interactive "*P")
21321 (if (save-excursion
21322 (beginning-of-line (if arg 1 0))
21323 (let ((case-fold-search nil))
21324 (looking-at org-complex-heading-regexp)))
21325 ;; At headline.
21326 (let ((tags-column (when (match-beginning 5)
21327 (save-excursion (goto-char (match-beginning 5))
21328 (current-column))))
21329 (string (concat " " (progn (when arg (forward-line 1))
21330 (org-trim (delete-and-extract-region
21331 (line-beginning-position)
21332 (line-end-position)))))))
21333 (unless (bobp) (delete-region (point) (1- (point))))
21334 (goto-char (or (match-end 4)
21335 (match-beginning 5)
21336 (match-end 0)))
21337 (skip-chars-backward " \t")
21338 (save-excursion (insert string))
21339 ;; Adjust alignment of tags.
21340 (cond
21341 ((not tags-column)) ;no tags
21342 (org-auto-align-tags (org-set-tags nil t))
21343 (t (org--align-tags-here tags-column)))) ;preserve tags column
21344 (delete-indentation arg)))
21346 (defun org-open-line (n)
21347 "Insert a new row in tables, call `open-line' elsewhere.
21348 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21349 As a special case, when a document starts with a table, allow to
21350 call `open-line' on the very first character."
21351 (interactive "*p")
21352 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21353 (org-table-insert-row)
21354 (open-line n)))
21356 (defun org-return (&optional indent)
21357 "Goto next table row or insert a newline.
21359 Calls `org-table-next-row' or `newline', depending on context.
21361 When optional INDENT argument is non-nil, call
21362 `newline-and-indent' instead of `newline'.
21364 When `org-return-follows-link' is non-nil and point is on
21365 a timestamp or a link, call `org-open-at-point'. However, it
21366 will not happen if point is in a table or on a \"dead\"
21367 object (e.g., within a comment). In these case, you need to use
21368 `org-open-at-point' directly."
21369 (interactive)
21370 (let ((context (if org-return-follows-link (org-element-context)
21371 (org-element-at-point))))
21372 (cond
21373 ;; In a table, call `org-table-next-row'.
21374 ((or (and (eq (org-element-type context) 'table)
21375 (>= (point) (org-element-property :contents-begin context))
21376 (< (point) (org-element-property :contents-end context)))
21377 (org-element-lineage context '(table-row table-cell) t))
21378 (org-table-justify-field-maybe)
21379 (call-interactively #'org-table-next-row))
21380 ;; On a link or a timestamp, call `org-open-at-point' if
21381 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21382 ;; locations, e.g., in a comment, as `org-open-at-point'.
21383 ((and org-return-follows-link
21384 (or (org-in-regexp org-ts-regexp-both nil t)
21385 (org-in-regexp org-tsr-regexp-both nil t)
21386 (org-in-regexp org-any-link-re nil t)))
21387 (call-interactively #'org-open-at-point))
21388 ;; Insert newline in heading, but preserve tags.
21389 ((and (not (bolp))
21390 (save-excursion (beginning-of-line)
21391 (let ((case-fold-search nil))
21392 (looking-at org-complex-heading-regexp))))
21393 ;; At headline. Split line. However, if point is on keyword,
21394 ;; priority cookie or tags, do not break any of them: add
21395 ;; a newline after the headline instead.
21396 (let ((tags-column (and (match-beginning 5)
21397 (save-excursion (goto-char (match-beginning 5))
21398 (current-column))))
21399 (string
21400 (when (and (match-end 4) (org-point-in-group (point) 4))
21401 (delete-and-extract-region (point) (match-end 4)))))
21402 ;; Adjust tag alignment.
21403 (cond
21404 ((not (and tags-column string)))
21405 (org-auto-align-tags (org-set-tags nil t))
21406 (t (org--align-tags-here tags-column))) ;preserve tags column
21407 (end-of-line)
21408 (org-show-entry)
21409 (if indent (newline-and-indent) (newline))
21410 (when string (save-excursion (insert (org-trim string))))))
21411 ;; In a list, make sure indenting keeps trailing text within.
21412 ((and indent
21413 (not (eolp))
21414 (org-element-lineage context '(item)))
21415 (let ((trailing-data
21416 (delete-and-extract-region (point) (line-end-position))))
21417 (newline-and-indent)
21418 (save-excursion (insert trailing-data))))
21419 (t (if indent (newline-and-indent) (newline))))))
21421 (defun org-return-indent ()
21422 "Goto next table row or insert a newline and indent.
21423 Calls `org-table-next-row' or `newline-and-indent', depending on
21424 context. See the individual commands for more information."
21425 (interactive)
21426 (org-return t))
21428 (defun org-ctrl-c-star ()
21429 "Compute table, or change heading status of lines.
21430 Calls `org-table-recalculate' or `org-toggle-heading',
21431 depending on context."
21432 (interactive)
21433 (cond
21434 ((org-at-table-p)
21435 (call-interactively 'org-table-recalculate))
21437 ;; Convert all lines in region to list items
21438 (call-interactively 'org-toggle-heading))))
21440 (defun org-ctrl-c-minus ()
21441 "Insert separator line in table or modify bullet status of line.
21442 Also turns a plain line or a region of lines into list items.
21443 Calls `org-table-insert-hline', `org-toggle-item', or
21444 `org-cycle-list-bullet', depending on context."
21445 (interactive)
21446 (cond
21447 ((org-at-table-p)
21448 (call-interactively 'org-table-insert-hline))
21449 ((org-region-active-p)
21450 (call-interactively 'org-toggle-item))
21451 ((org-in-item-p)
21452 (call-interactively 'org-cycle-list-bullet))
21454 (call-interactively 'org-toggle-item))))
21456 (defun org-toggle-heading (&optional nstars)
21457 "Convert headings to normal text, or items or text to headings.
21458 If there is no active region, only convert the current line.
21460 With a `\\[universal-argument]' prefix, convert the whole list at
21461 point into heading.
21463 In a region:
21465 - If the first non blank line is a headline, remove the stars
21466 from all headlines in the region.
21468 - If it is a normal line, turn each and every normal line (i.e.,
21469 not an heading or an item) in the region into headings. If you
21470 want to convert only the first line of this region, use one
21471 universal prefix argument.
21473 - If it is a plain list item, turn all plain list items into headings.
21475 When converting a line into a heading, the number of stars is chosen
21476 such that the lines become children of the current entry. However,
21477 when a numeric prefix argument is given, its value determines the
21478 number of stars to add."
21479 (interactive "P")
21480 (let ((skip-blanks
21481 (function
21482 ;; Return beginning of first non-blank line, starting from
21483 ;; line at POS.
21484 (lambda (pos)
21485 (save-excursion
21486 (goto-char pos)
21487 (while (org-at-comment-p) (forward-line))
21488 (skip-chars-forward " \r\t\n")
21489 (point-at-bol)))))
21490 beg end toggled)
21491 ;; Determine boundaries of changes. If a universal prefix has
21492 ;; been given, put the list in a region. If region ends at a bol,
21493 ;; do not consider the last line to be in the region.
21495 (when (and current-prefix-arg (org-at-item-p))
21496 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21497 (org-mark-element))
21499 (if (org-region-active-p)
21500 (setq beg (funcall skip-blanks (region-beginning))
21501 end (copy-marker (save-excursion
21502 (goto-char (region-end))
21503 (if (bolp) (point) (point-at-eol)))))
21504 (setq beg (funcall skip-blanks (point-at-bol))
21505 end (copy-marker (point-at-eol))))
21506 ;; Ensure inline tasks don't count as headings.
21507 (org-with-limited-levels
21508 (save-excursion
21509 (goto-char beg)
21510 (cond
21511 ;; Case 1. Started at an heading: de-star headings.
21512 ((org-at-heading-p)
21513 (while (< (point) end)
21514 (when (org-at-heading-p t)
21515 (looking-at org-outline-regexp) (replace-match "")
21516 (setq toggled t))
21517 (forward-line)))
21518 ;; Case 2. Started at an item: change items into headlines.
21519 ;; One star will be added by `org-list-to-subtree'.
21520 ((org-at-item-p)
21521 (while (< (point) end)
21522 (when (org-at-item-p)
21523 ;; Pay attention to cases when region ends before list.
21524 (let* ((struct (org-list-struct))
21525 (list-end
21526 (min (org-list-get-bottom-point struct) (1+ end))))
21527 (save-restriction
21528 (narrow-to-region (point) list-end)
21529 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21530 (setq toggled t))
21531 (forward-line)))
21532 ;; Case 3. Started at normal text: make every line an heading,
21533 ;; skipping headlines and items.
21534 (t (let* ((stars
21535 (make-string
21536 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21537 (add-stars
21538 (cond (nstars "") ; stars from prefix only
21539 ((equal stars "") "*") ; before first heading
21540 (org-odd-levels-only "**") ; inside heading, odd
21541 (t "*"))) ; inside heading, oddeven
21542 (rpl (concat stars add-stars " "))
21543 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21544 (while (< (point) (if (equal nstars '(4)) lend end))
21545 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21546 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21547 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21548 (forward-line)))))))
21549 (unless toggled (message "Cannot toggle heading from here"))))
21551 (defun org-meta-return (&optional _arg)
21552 "Insert a new heading or wrap a region in a table.
21553 Calls `org-insert-heading' or `org-table-wrap-region', depending
21554 on context. See the individual commands for more information."
21555 (interactive)
21556 (org-check-before-invisible-edit 'insert)
21557 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21558 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21559 #'org-insert-heading))))
21561 ;;; Menu entries
21563 (defsubst org-in-subtree-not-table-p ()
21564 "Are we in a subtree and not in a table?"
21565 (and (not (org-before-first-heading-p))
21566 (not (org-at-table-p))))
21568 ;; Define the Org mode menus
21569 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21570 '("Tbl"
21571 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21572 ["Next Field" org-cycle (org-at-table-p)]
21573 ["Previous Field" org-shifttab (org-at-table-p)]
21574 ["Next Row" org-return (org-at-table-p)]
21575 "--"
21576 ["Blank Field" org-table-blank-field (org-at-table-p)]
21577 ["Edit Field" org-table-edit-field (org-at-table-p)]
21578 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21579 "--"
21580 ("Column"
21581 ["Move Column Left" org-metaleft (org-at-table-p)]
21582 ["Move Column Right" org-metaright (org-at-table-p)]
21583 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21584 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21585 ("Row"
21586 ["Move Row Up" org-metaup (org-at-table-p)]
21587 ["Move Row Down" org-metadown (org-at-table-p)]
21588 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21589 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21590 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21591 "--"
21592 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21593 ("Rectangle"
21594 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21595 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21596 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21597 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21598 "--"
21599 ("Calculate"
21600 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21601 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21602 ["Edit Formulas" org-edit-special (org-at-table-p)]
21603 "--"
21604 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21605 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21606 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21607 "--"
21608 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21609 "--"
21610 ["Sum Column/Rectangle" org-table-sum
21611 (or (org-at-table-p) (org-region-active-p))]
21612 ["Which Column?" org-table-current-column (org-at-table-p)])
21613 ["Debug Formulas"
21614 org-table-toggle-formula-debugger
21615 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21616 ["Show Col/Row Numbers"
21617 org-table-toggle-coordinate-overlays
21618 :style toggle
21619 :selected (bound-and-true-p org-table-overlay-coordinates)]
21620 "--"
21621 ["Create" org-table-create (and (not (org-at-table-p))
21622 org-enable-table-editor)]
21623 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21624 ["Import from File" org-table-import (not (org-at-table-p))]
21625 ["Export to File" org-table-export (org-at-table-p)]
21626 "--"
21627 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21628 "--"
21629 ("Plot"
21630 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21631 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21633 (easy-menu-define org-org-menu org-mode-map "Org menu"
21634 '("Org"
21635 ("Show/Hide"
21636 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21637 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21638 ["Sparse Tree..." org-sparse-tree t]
21639 ["Reveal Context" org-reveal t]
21640 ["Show All" outline-show-all t]
21641 "--"
21642 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21643 "--"
21644 ["New Heading" org-insert-heading t]
21645 ("Navigate Headings"
21646 ["Up" outline-up-heading t]
21647 ["Next" outline-next-visible-heading t]
21648 ["Previous" outline-previous-visible-heading t]
21649 ["Next Same Level" outline-forward-same-level t]
21650 ["Previous Same Level" outline-backward-same-level t]
21651 "--"
21652 ["Jump" org-goto t])
21653 ("Edit Structure"
21654 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21655 "--"
21656 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21657 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21658 "--"
21659 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21660 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21661 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21662 "--"
21663 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21664 "--"
21665 ["Copy visible text" org-copy-visible t]
21666 "--"
21667 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21668 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21669 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21670 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21671 "--"
21672 ["Sort Region/Children" org-sort t]
21673 "--"
21674 ["Convert to odd levels" org-convert-to-odd-levels t]
21675 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21676 ("Editing"
21677 ["Emphasis..." org-emphasize t]
21678 ["Edit Source Example" org-edit-special t]
21679 "--"
21680 ["Footnote new/jump" org-footnote-action t]
21681 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21682 ("Archive"
21683 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21684 "--"
21685 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21686 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21687 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21689 "--"
21690 ("Hyperlinks"
21691 ["Store Link (Global)" org-store-link t]
21692 ["Find existing link to here" org-occur-link-in-agenda-files t]
21693 ["Insert Link" org-insert-link t]
21694 ["Follow Link" org-open-at-point t]
21695 "--"
21696 ["Next link" org-next-link t]
21697 ["Previous link" org-previous-link t]
21698 "--"
21699 ["Descriptive Links"
21700 org-toggle-link-display
21701 :style radio
21702 :selected org-descriptive-links
21704 ["Literal Links"
21705 org-toggle-link-display
21706 :style radio
21707 :selected (not org-descriptive-links)])
21708 "--"
21709 ("TODO Lists"
21710 ["TODO/DONE/-" org-todo t]
21711 ("Select keyword"
21712 ["Next keyword" org-shiftright (org-at-heading-p)]
21713 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21714 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21715 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21716 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21717 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21718 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21719 "--"
21720 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21721 :selected org-enforce-todo-dependencies :style toggle :active t]
21722 "Settings for tree at point"
21723 ["Do Children sequentially" org-toggle-ordered-property :style radio
21724 :selected (org-entry-get nil "ORDERED")
21725 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21726 ["Do Children parallel" org-toggle-ordered-property :style radio
21727 :selected (not (org-entry-get nil "ORDERED"))
21728 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21729 "--"
21730 ["Set Priority" org-priority t]
21731 ["Priority Up" org-shiftup t]
21732 ["Priority Down" org-shiftdown t]
21733 "--"
21734 ["Get news from all feeds" org-feed-update-all t]
21735 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21736 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21737 ("TAGS and Properties"
21738 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21739 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21740 "--"
21741 ["Set property" org-set-property (not (org-before-first-heading-p))]
21742 ["Column view of properties" org-columns t]
21743 ["Insert Column View DBlock" org-columns-insert-dblock t])
21744 ("Dates and Scheduling"
21745 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21746 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21747 ("Change Date"
21748 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21749 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21750 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21751 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21752 ["Compute Time Range" org-evaluate-time-range t]
21753 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21754 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21755 "--"
21756 ["Custom time format" org-toggle-time-stamp-overlays
21757 :style radio :selected org-display-custom-times]
21758 "--"
21759 ["Goto Calendar" org-goto-calendar t]
21760 ["Date from Calendar" org-date-from-calendar t]
21761 "--"
21762 ["Start/Restart Timer" org-timer-start t]
21763 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21764 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21765 ["Insert Timer String" org-timer t]
21766 ["Insert Timer Item" org-timer-item t])
21767 ("Logging work"
21768 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21769 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21770 ["Clock out" org-clock-out t]
21771 ["Clock cancel" org-clock-cancel t]
21772 "--"
21773 ["Mark as default task" org-clock-mark-default-task t]
21774 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21775 ["Goto running clock" org-clock-goto t]
21776 "--"
21777 ["Display times" org-clock-display t]
21778 ["Create clock table" org-clock-report t]
21779 "--"
21780 ["Record DONE time"
21781 (progn (setq org-log-done (not org-log-done))
21782 (message "Switching to %s will %s record a timestamp"
21783 (car org-done-keywords)
21784 (if org-log-done "automatically" "not")))
21785 :style toggle :selected org-log-done])
21786 "--"
21787 ["Agenda Command..." org-agenda t]
21788 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21789 ("File List for Agenda")
21790 ("Special views current file"
21791 ["TODO Tree" org-show-todo-tree t]
21792 ["Check Deadlines" org-check-deadlines t]
21793 ["Timeline" org-timeline t]
21794 ["Tags/Property tree" org-match-sparse-tree t])
21795 "--"
21796 ["Export/Publish..." org-export-dispatch t]
21797 ("LaTeX"
21798 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21799 :selected org-cdlatex-mode]
21800 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21801 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21802 ["Modify math symbol" org-cdlatex-math-modify
21803 (org-inside-LaTeX-fragment-p)]
21804 ["Insert citation" org-reftex-citation t])
21805 "--"
21806 ("MobileOrg"
21807 ["Push Files and Views" org-mobile-push t]
21808 ["Get Captured and Flagged" org-mobile-pull t]
21809 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21810 "--"
21811 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21812 "--"
21813 ("Documentation"
21814 ["Show Version" org-version t]
21815 ["Info Documentation" org-info t])
21816 ("Customize"
21817 ["Browse Org Group" org-customize t]
21818 "--"
21819 ["Expand This Menu" org-create-customize-menu
21820 (fboundp 'customize-menu-create)])
21821 ["Send bug report" org-submit-bug-report t]
21822 "--"
21823 ("Refresh/Reload"
21824 ["Refresh setup current buffer" org-mode-restart t]
21825 ["Reload Org (after update)" org-reload t]
21826 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21829 (defun org-info (&optional node)
21830 "Read documentation for Org in the info system.
21831 With optional NODE, go directly to that node."
21832 (interactive)
21833 (info (format "(org)%s" (or node ""))))
21835 ;;;###autoload
21836 (defun org-submit-bug-report ()
21837 "Submit a bug report on Org via mail.
21839 Don't hesitate to report any problems or inaccurate documentation.
21841 If you don't have setup sending mail from (X)Emacs, please copy the
21842 output buffer into your mail program, as it gives us important
21843 information about your Org version and configuration."
21844 (interactive)
21845 (require 'reporter)
21846 (defvar reporter-prompt-for-summary-p)
21847 (org-load-modules-maybe)
21848 (org-require-autoloaded-modules)
21849 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21850 (reporter-submit-bug-report
21851 "emacs-orgmode@gnu.org"
21852 (org-version nil 'full)
21853 (let (list)
21854 (save-window-excursion
21855 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21856 (delete-other-windows)
21857 (erase-buffer)
21858 (insert "You are about to submit a bug report to the Org mailing list.
21860 We would like to add your full Org and Outline configuration to the
21861 bug report. This greatly simplifies the work of the maintainer and
21862 other experts on the mailing list.
21864 HOWEVER, some variables you have customized may contain private
21865 information. The names of customers, colleagues, or friends, might
21866 appear in the form of file names, tags, todo states, or search strings.
21867 If you answer yes to the prompt, you might want to check and remove
21868 such private information before sending the email.")
21869 (add-text-properties (point-min) (point-max) '(face org-warning))
21870 (when (yes-or-no-p "Include your Org configuration ")
21871 (mapatoms
21872 (lambda (v)
21873 (and (boundp v)
21874 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21875 (or (and (symbol-value v)
21876 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21877 (and
21878 (get v 'custom-type) (get v 'standard-value)
21879 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21880 (push v list)))))
21881 (kill-buffer (get-buffer "*Warn about privacy*"))
21882 list))
21883 nil nil
21884 "Remember to cover the basics, that is, what you expected to happen and
21885 what in fact did happen. You don't know how to make a good report? See
21887 http://orgmode.org/manual/Feedback.html#Feedback
21889 Your bug report will be posted to the Org mailing list.
21890 ------------------------------------------------------------------------")
21891 (save-excursion
21892 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21893 (replace-match "\\1Bug: \\3 [\\2]")))))
21896 (defun org-install-agenda-files-menu ()
21897 (let ((bl (buffer-list)))
21898 (save-excursion
21899 (while bl
21900 (set-buffer (pop bl))
21901 (when (derived-mode-p 'org-mode) (setq bl nil)))
21902 (when (derived-mode-p 'org-mode)
21903 (easy-menu-change
21904 '("Org") "File List for Agenda"
21905 (append
21906 (list
21907 ["Edit File List" (org-edit-agenda-file-list) t]
21908 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21909 ["Remove Current File from List" org-remove-file t]
21910 ["Cycle through agenda files" org-cycle-agenda-files t]
21911 ["Occur in all agenda files" org-occur-in-agenda-files t]
21912 "--")
21913 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21915 ;;;; Documentation
21917 (defun org-require-autoloaded-modules ()
21918 (interactive)
21919 (mapc #'require
21920 '(org-agenda org-archive org-attach org-clock org-colview org-id
21921 org-table org-timer)))
21923 ;;;###autoload
21924 (defun org-reload (&optional uncompiled)
21925 "Reload all org lisp files.
21926 With prefix arg UNCOMPILED, load the uncompiled versions."
21927 (interactive "P")
21928 (require 'loadhist)
21929 (let* ((org-dir (org-find-library-dir "org"))
21930 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21931 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21932 (remove-re (format "\\`%s\\'"
21933 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21934 (feats (delete-dups
21935 (mapcar 'file-name-sans-extension
21936 (mapcar 'file-name-nondirectory
21937 (delq nil
21938 (mapcar 'feature-file
21939 features))))))
21940 (lfeat (append
21941 (sort
21942 (setq feats
21943 (delq nil (mapcar
21944 (lambda (f)
21945 (if (and (string-match feature-re f)
21946 (not (string-match remove-re f)))
21947 f nil))
21948 feats)))
21949 'string-lessp)
21950 (list "org-version" "org")))
21951 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21952 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21953 load-uncore load-misses)
21954 (setq load-misses
21955 (delq 't
21956 (mapcar (lambda (f)
21957 (or (org-load-noerror-mustsuffix (concat org-dir f))
21958 (and (string= org-dir contrib-dir)
21959 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21960 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21961 (add-to-list 'load-uncore f 'append)
21964 lfeat)))
21965 (when load-uncore
21966 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21967 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21968 (if load-misses
21969 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21970 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21971 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21973 ;;;###autoload
21974 (defun org-customize ()
21975 "Call the customize function with org as argument."
21976 (interactive)
21977 (org-load-modules-maybe)
21978 (org-require-autoloaded-modules)
21979 (customize-browse 'org))
21981 (defun org-create-customize-menu ()
21982 "Create a full customization menu for Org mode, insert it into the menu."
21983 (interactive)
21984 (org-load-modules-maybe)
21985 (org-require-autoloaded-modules)
21986 (if (fboundp 'customize-menu-create)
21987 (progn
21988 (easy-menu-change
21989 '("Org") "Customize"
21990 `(["Browse Org group" org-customize t]
21991 "--"
21992 ,(customize-menu-create 'org)
21993 ["Set" Custom-set t]
21994 ["Save" Custom-save t]
21995 ["Reset to Current" Custom-reset-current t]
21996 ["Reset to Saved" Custom-reset-saved t]
21997 ["Reset to Standard Settings" Custom-reset-standard t]))
21998 (message "\"Org\"-menu now contains full customization menu"))
21999 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22001 ;;;; Miscellaneous stuff
22003 ;;; Generally useful functions
22005 (defun org-get-at-eol (property n)
22006 "Get text property PROPERTY at the end of line less N characters."
22007 (get-text-property (- (point-at-eol) n) property))
22009 (defun org-find-text-property-in-string (prop s)
22010 "Return the first non-nil value of property PROP in string S."
22011 (or (get-text-property 0 prop s)
22012 (get-text-property (or (next-single-property-change 0 prop s) 0)
22013 prop s)))
22015 (defun org-display-warning (message)
22016 "Display the given MESSAGE as a warning."
22017 (display-warning 'org message :warning))
22019 (defun org-eval (form)
22020 "Eval FORM and return result."
22021 (condition-case error
22022 (eval form)
22023 (error (format "%%![Error: %s]" error))))
22025 (defun org-in-clocktable-p ()
22026 "Check if the cursor is in a clocktable."
22027 (let ((pos (point)) start)
22028 (save-excursion
22029 (end-of-line 1)
22030 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22031 (setq start (match-beginning 0))
22032 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22033 (>= (match-end 0) pos)
22034 start))))
22036 (defun org-in-verbatim-emphasis ()
22037 (save-match-data
22038 (and (org-in-regexp org-emph-re 2)
22039 (>= (point) (match-beginning 3))
22040 (<= (point) (match-end 4))
22041 (member (match-string 3) '("=" "~")))))
22043 (defun org-overlay-display (ovl text &optional face evap)
22044 "Make overlay OVL display TEXT with face FACE."
22045 (overlay-put ovl 'display text)
22046 (if face (overlay-put ovl 'face face))
22047 (if evap (overlay-put ovl 'evaporate t)))
22049 (defun org-overlay-before-string (ovl text &optional face evap)
22050 "Make overlay OVL display TEXT with face FACE."
22051 (if face (org-add-props text nil 'face face))
22052 (overlay-put ovl 'before-string text)
22053 (if evap (overlay-put ovl 'evaporate t)))
22055 (defun org-find-overlays (prop &optional pos delete)
22056 "Find all overlays specifying PROP at POS or point.
22057 If DELETE is non-nil, delete all those overlays."
22058 (let (found)
22059 (dolist (ov (overlays-at (or pos (point))) found)
22060 (cond ((not (overlay-get ov prop)))
22061 (delete (delete-overlay ov))
22062 (t (push ov found))))))
22064 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22065 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22066 (if (and marker (marker-buffer marker)
22067 (buffer-live-p (marker-buffer marker)))
22068 (progn
22069 (pop-to-buffer-same-window (marker-buffer marker))
22070 (when (or (> marker (point-max)) (< marker (point-min)))
22071 (widen))
22072 (goto-char marker)
22073 (org-show-context 'org-goto))
22074 (if bookmark
22075 (bookmark-jump bookmark)
22076 (error "Cannot find location"))))
22078 (defun org-quote-csv-field (s)
22079 "Quote field for inclusion in CSV material."
22080 (if (string-match "[\",]" s)
22081 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22084 (defun org-force-self-insert (N)
22085 "Needed to enforce self-insert under remapping."
22086 (interactive "p")
22087 (self-insert-command N))
22089 (defun org-string-width (s)
22090 "Compute width of string, ignoring invisible characters.
22091 This ignores character with invisibility property `org-link', and also
22092 characters with property `org-cwidth', because these will become invisible
22093 upon the next fontification round."
22094 (let (b l)
22095 (when (or (eq t buffer-invisibility-spec)
22096 (assq 'org-link buffer-invisibility-spec))
22097 (while (setq b (text-property-any 0 (length s)
22098 'invisible 'org-link s))
22099 (setq s (concat (substring s 0 b)
22100 (substring s (or (next-single-property-change
22101 b 'invisible s)
22102 (length s)))))))
22103 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22104 (setq s (concat (substring s 0 b)
22105 (substring s (or (next-single-property-change
22106 b 'org-cwidth s)
22107 (length s))))))
22108 (setq l (string-width s) b -1)
22109 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22110 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22113 (defun org-shorten-string (s maxlength)
22114 "Shorten string S so that it is no longer than MAXLENGTH characters.
22115 If the string is shorter or has length MAXLENGTH, just return the
22116 original string. If it is longer, the functions finds a space in the
22117 string, breaks this string off at that locations and adds three dots
22118 as ellipsis. Including the ellipsis, the string will not be longer
22119 than MAXLENGTH. If finding a good breaking point in the string does
22120 not work, the string is just chopped off in the middle of a word
22121 if necessary."
22122 (if (<= (length s) maxlength)
22124 (let* ((n (max (- maxlength 4) 1))
22125 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22126 (if (string-match re s)
22127 (concat (match-string 1 s) "...")
22128 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22130 (defun org-get-indentation (&optional line)
22131 "Get the indentation of the current line, interpreting tabs.
22132 When LINE is given, assume it represents a line and compute its indentation."
22133 (if line
22134 (when (string-match "^ *" (org-remove-tabs line))
22135 (match-end 0))
22136 (save-excursion
22137 (beginning-of-line 1)
22138 (skip-chars-forward " \t")
22139 (current-column))))
22141 (defun org-get-string-indentation (s)
22142 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22143 (let ((n -1) (i 0) (w tab-width) c)
22144 (catch 'exit
22145 (while (< (setq n (1+ n)) (length s))
22146 (setq c (aref s n))
22147 (cond ((= c ?\ ) (setq i (1+ i)))
22148 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22149 (t (throw 'exit t)))))
22152 (defun org-remove-tabs (s &optional width)
22153 "Replace tabulators in S with spaces.
22154 Assumes that s is a single line, starting in column 0."
22155 (setq width (or width tab-width))
22156 (while (string-match "\t" s)
22157 (setq s (replace-match
22158 (make-string
22159 (- (* width (/ (+ (match-beginning 0) width) width))
22160 (match-beginning 0)) ?\ )
22161 t t s)))
22164 (defun org-fix-indentation (line ind)
22165 "Fix indentation in LINE.
22166 IND is a cons cell with target and minimum indentation.
22167 If the current indentation in LINE is smaller than the minimum,
22168 leave it alone. If it is larger than ind, set it to the target."
22169 (let* ((l (org-remove-tabs line))
22170 (i (org-get-indentation l))
22171 (i1 (car ind)) (i2 (cdr ind)))
22172 (when (>= i i2) (setq l (substring line i2)))
22173 (if (> i1 0)
22174 (concat (make-string i1 ?\ ) l)
22175 l)))
22177 (defun org-remove-indentation (code &optional n)
22178 "Remove maximum common indentation in string CODE and return it.
22179 N may optionally be the number of columns to remove. Return CODE
22180 as-is if removal failed."
22181 (with-temp-buffer
22182 (insert code)
22183 (if (org-do-remove-indentation n) (buffer-string) code)))
22185 (defun org-do-remove-indentation (&optional n)
22186 "Remove the maximum common indentation from the buffer.
22187 When optional argument N is a positive integer, remove exactly
22188 that much characters from indentation, if possible. Return nil
22189 if it fails."
22190 (catch :exit
22191 (goto-char (point-min))
22192 ;; Find maximum common indentation, if not specified.
22193 (let ((n (or n
22194 (let ((min-ind (point-max)))
22195 (save-excursion
22196 (while (re-search-forward "^[ \t]*\\S-" nil t)
22197 (let ((ind (1- (current-column))))
22198 (if (zerop ind) (throw :exit nil)
22199 (setq min-ind (min min-ind ind))))))
22200 min-ind))))
22201 (if (zerop n) (throw :exit nil)
22202 ;; Remove exactly N indentation, but give up if not possible.
22203 (while (not (eobp))
22204 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22205 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22206 ((< ind n) (throw :exit nil))
22207 (t (indent-line-to (- ind n))))
22208 (forward-line)))
22209 ;; Signal success.
22210 t))))
22212 (defun org-fill-template (template alist)
22213 "Find each %key of ALIST in TEMPLATE and replace it."
22214 (let ((case-fold-search nil))
22215 (dolist (entry (sort (copy-sequence alist)
22216 (lambda (a b) (< (length (car a)) (length (car b))))))
22217 (setq template
22218 (replace-regexp-in-string
22219 (concat "%" (regexp-quote (car entry)))
22220 (or (cdr entry) "") template t t)))
22221 template))
22223 (defun org-base-buffer (buffer)
22224 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22225 (if (not buffer)
22226 buffer
22227 (or (buffer-base-buffer buffer)
22228 buffer)))
22230 (defun org-wrap (string &optional width lines)
22231 "Wrap string to either a number of lines, or a width in characters.
22232 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22233 that costs. If there is a word longer than WIDTH, the text is actually
22234 wrapped to the length of that word.
22235 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22236 many lines, whatever width that takes.
22237 The return value is a list of lines, without newlines at the end."
22238 (let* ((words (org-split-string string "[ \t\n]+"))
22239 (maxword (apply 'max (mapcar 'org-string-width words)))
22240 w ll)
22241 (cond (width
22242 (org-do-wrap words (max maxword width)))
22243 (lines
22244 (setq w maxword)
22245 (setq ll (org-do-wrap words maxword))
22246 (if (<= (length ll) lines)
22248 (setq ll words)
22249 (while (> (length ll) lines)
22250 (setq w (1+ w))
22251 (setq ll (org-do-wrap words w)))
22252 ll))
22253 (t (error "Cannot wrap this")))))
22255 (defun org-do-wrap (words width)
22256 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22257 (let (lines line)
22258 (while words
22259 (setq line (pop words))
22260 (while (and words (< (+ (length line) (length (car words))) width))
22261 (setq line (concat line " " (pop words))))
22262 (setq lines (push line lines)))
22263 (nreverse lines)))
22265 (defun org-split-string (string &optional separators)
22266 "Splits STRING into substrings at SEPARATORS.
22267 SEPARATORS is a regular expression.
22268 No empty strings are returned if there are matches at the beginning
22269 and end of string."
22270 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22271 (let ((start 0) notfirst list)
22272 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22273 (if (and notfirst
22274 (= start (match-beginning 0))
22275 (< start (length string)))
22276 (1+ start) start))
22277 (< (match-beginning 0) (length string)))
22278 (setq notfirst t)
22279 (or (eq (match-beginning 0) 0)
22280 (and (eq (match-beginning 0) (match-end 0))
22281 (eq (match-beginning 0) start))
22282 (push (substring string start (match-beginning 0)) list))
22283 (setq start (match-end 0)))
22284 (or (eq start (length string))
22285 (push (substring string start) list))
22286 (nreverse list)))
22288 (defun org-quote-vert (s)
22289 "Replace \"|\" with \"\\vert\"."
22290 (while (string-match "|" s)
22291 (setq s (replace-match "\\vert" t t s)))
22294 (defun org-uuidgen-p (s)
22295 "Is S an ID created by UUIDGEN?"
22296 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22298 (defun org-in-src-block-p (&optional inside)
22299 "Whether point is in a code source block.
22300 When INSIDE is non-nil, don't consider we are within a src block
22301 when point is at #+BEGIN_SRC or #+END_SRC."
22302 (let ((case-fold-search t))
22303 (or (and (eq (get-char-property (point) 'src-block) t))
22304 (and (not inside)
22305 (save-match-data
22306 (save-excursion
22307 (beginning-of-line)
22308 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22310 (defun org-context ()
22311 "Return a list of contexts of the current cursor position.
22312 If several contexts apply, all are returned.
22313 Each context entry is a list with a symbol naming the context, and
22314 two positions indicating start and end of the context. Possible
22315 contexts are:
22317 :headline anywhere in a headline
22318 :headline-stars on the leading stars in a headline
22319 :todo-keyword on a TODO keyword (including DONE) in a headline
22320 :tags on the TAGS in a headline
22321 :priority on the priority cookie in a headline
22322 :item on the first line of a plain list item
22323 :item-bullet on the bullet/number of a plain list item
22324 :checkbox on the checkbox in a plain list item
22325 :table in an Org table
22326 :table-special on a special filed in a table
22327 :table-table in a table.el table
22328 :clocktable in a clocktable
22329 :src-block in a source block
22330 :link on a hyperlink
22331 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22332 :target on a <<target>>
22333 :radio-target on a <<<radio-target>>>
22334 :latex-fragment on a LaTeX fragment
22335 :latex-preview on a LaTeX fragment with overlaid preview image
22337 This function expects the position to be visible because it uses font-lock
22338 faces as a help to recognize the following contexts: :table-special, :link,
22339 and :keyword."
22340 (let* ((f (get-text-property (point) 'face))
22341 (faces (if (listp f) f (list f)))
22342 (case-fold-search t)
22343 (p (point)) clist o)
22344 ;; First the large context
22345 (cond
22346 ((org-at-heading-p t)
22347 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22348 (when (progn
22349 (beginning-of-line 1)
22350 (looking-at org-todo-line-tags-regexp))
22351 (push (org-point-in-group p 1 :headline-stars) clist)
22352 (push (org-point-in-group p 2 :todo-keyword) clist)
22353 (push (org-point-in-group p 4 :tags) clist))
22354 (goto-char p)
22355 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22356 (when (looking-at "\\[#[A-Z0-9]\\]")
22357 (push (org-point-in-group p 0 :priority) clist)))
22359 ((org-at-item-p)
22360 (push (org-point-in-group p 2 :item-bullet) clist)
22361 (push (list :item (point-at-bol)
22362 (save-excursion (org-end-of-item) (point)))
22363 clist)
22364 (and (org-at-item-checkbox-p)
22365 (push (org-point-in-group p 0 :checkbox) clist)))
22367 ((org-at-table-p)
22368 (push (list :table (org-table-begin) (org-table-end)) clist)
22369 (when (memq 'org-formula faces)
22370 (push (list :table-special
22371 (previous-single-property-change p 'face)
22372 (next-single-property-change p 'face)) clist)))
22373 ((org-at-table-p 'any)
22374 (push (list :table-table) clist)))
22375 (goto-char p)
22377 (let ((case-fold-search t))
22378 ;; New the "medium" contexts: clocktables, source blocks
22379 (cond ((org-in-clocktable-p)
22380 (push (list :clocktable
22381 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22382 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22383 (match-beginning 1))
22384 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22385 (match-end 0))) clist))
22386 ((org-in-src-block-p)
22387 (push (list :src-block
22388 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22389 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22390 (match-beginning 1))
22391 (and (search-forward "#+END_SRC" nil t)
22392 (match-beginning 0))) clist))))
22393 (goto-char p)
22395 ;; Now the small context
22396 (cond
22397 ((org-at-timestamp-p)
22398 (push (org-point-in-group p 0 :timestamp) clist))
22399 ((memq 'org-link faces)
22400 (push (list :link
22401 (previous-single-property-change p 'face)
22402 (next-single-property-change p 'face)) clist))
22403 ((memq 'org-special-keyword faces)
22404 (push (list :keyword
22405 (previous-single-property-change p 'face)
22406 (next-single-property-change p 'face)) clist))
22407 ((org-at-target-p)
22408 (push (org-point-in-group p 0 :target) clist)
22409 (goto-char (1- (match-beginning 0)))
22410 (when (looking-at org-radio-target-regexp)
22411 (push (org-point-in-group p 0 :radio-target) clist))
22412 (goto-char p))
22413 ((setq o (cl-some
22414 (lambda (o)
22415 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22417 (overlays-at (point))))
22418 (push (list :latex-fragment
22419 (overlay-start o) (overlay-end o)) clist)
22420 (push (list :latex-preview
22421 (overlay-start o) (overlay-end o)) clist))
22422 ((org-inside-LaTeX-fragment-p)
22423 ;; FIXME: positions wrong.
22424 (push (list :latex-fragment (point) (point)) clist)))
22426 (setq clist (nreverse (delq nil clist)))
22427 clist))
22429 (defun org-in-regexp (regexp &optional nlines visually)
22430 "Check if point is inside a match of REGEXP.
22432 Normally only the current line is checked, but you can include
22433 NLINES extra lines around point into the search. If VISUALLY is
22434 set, require that the cursor is not after the match but really
22435 on, so that the block visually is on the match.
22437 Return nil or a cons cell (BEG . END) where BEG and END are,
22438 respectively, the positions at the beginning and the end of the
22439 match."
22440 (catch :exit
22441 (let ((pos (point))
22442 (eol (line-end-position (if nlines (1+ nlines) 1))))
22443 (save-excursion
22444 (beginning-of-line (- 1 (or nlines 0)))
22445 (while (and (re-search-forward regexp eol t)
22446 (<= (match-beginning 0) pos))
22447 (let ((end (match-end 0)))
22448 (when (or (> end pos) (and (= end pos) (not visually)))
22449 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22451 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22452 "Non-nil when point is between matches of START-RE and END-RE.
22454 Also return a non-nil value when point is on one of the matches.
22456 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22457 buffer positions. Default values are the positions of headlines
22458 surrounding the point.
22460 The functions returns a cons cell whose car (resp. cdr) is the
22461 position before START-RE (resp. after END-RE)."
22462 (save-match-data
22463 (let ((pos (point))
22464 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22465 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22466 beg end)
22467 (save-excursion
22468 ;; Point is on a block when on START-RE or if START-RE can be
22469 ;; found before it...
22470 (and (or (org-in-regexp start-re)
22471 (re-search-backward start-re limit-up t))
22472 (setq beg (match-beginning 0))
22473 ;; ... and END-RE after it...
22474 (goto-char (match-end 0))
22475 (re-search-forward end-re limit-down t)
22476 (> (setq end (match-end 0)) pos)
22477 ;; ... without another START-RE in-between.
22478 (goto-char (match-beginning 0))
22479 (not (re-search-backward start-re (1+ beg) t))
22480 ;; Return value.
22481 (cons beg end))))))
22483 (defun org-in-block-p (names)
22484 "Non-nil when point belongs to a block whose name belongs to NAMES.
22486 NAMES is a list of strings containing names of blocks.
22488 Return first block name matched, or nil. Beware that in case of
22489 nested blocks, the returned name may not belong to the closest
22490 block from point."
22491 (save-match-data
22492 (catch 'exit
22493 (let ((case-fold-search t)
22494 (lim-up (save-excursion (outline-previous-heading)))
22495 (lim-down (save-excursion (outline-next-heading))))
22496 (dolist (name names)
22497 (let ((n (regexp-quote name)))
22498 (when (org-between-regexps-p
22499 (concat "^[ \t]*#\\+begin_" n)
22500 (concat "^[ \t]*#\\+end_" n)
22501 lim-up lim-down)
22502 (throw 'exit n)))))
22503 nil)))
22505 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22506 "Call `multi-occur' with buffers for all agenda files."
22507 (interactive "sOrg-files matching: ")
22508 (let* ((files (org-agenda-files))
22509 (tnames (mapcar #'file-truename files))
22510 (extra org-agenda-text-search-extra-files))
22511 (when (eq (car extra) 'agenda-archives)
22512 (setq extra (cdr extra))
22513 (setq files (org-add-archive-files files)))
22514 (dolist (f extra)
22515 (unless (member (file-truename f) tnames)
22516 (unless (member f files) (setq files (append files (list f))))
22517 (setq tnames (append tnames (list (file-truename f))))))
22518 (multi-occur
22519 (mapcar (lambda (x)
22520 (with-current-buffer
22521 ;; FIXME: Why not just (find-file-noselect x)?
22522 ;; Is it to avoid the "revert buffer" prompt?
22523 (or (get-file-buffer x) (find-file-noselect x))
22524 (widen)
22525 (current-buffer)))
22526 files)
22527 regexp)))
22529 (add-hook 'occur-mode-find-occurrence-hook
22530 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22532 (defun org-occur-link-in-agenda-files ()
22533 "Create a link and search for it in the agendas.
22534 The link is not stored in `org-stored-links', it is just created
22535 for the search purpose."
22536 (interactive)
22537 (let ((link (condition-case nil
22538 (org-store-link nil)
22539 (error "Unable to create a link to here"))))
22540 (org-occur-in-agenda-files (regexp-quote link))))
22542 (defun org-reverse-string (string)
22543 "Return the reverse of STRING."
22544 (apply 'string (reverse (string-to-list string))))
22546 ;; defsubst org-uniquify must be defined before first use
22548 (defun org-uniquify-alist (alist)
22549 "Merge elements of ALIST with the same key.
22551 For example, in this alist:
22553 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22554 => \\='((a 1 3) (b 2))
22556 merge (a 1) and (a 3) into (a 1 3).
22558 The function returns the new ALIST."
22559 (let (rtn)
22560 (dolist (e alist rtn)
22561 (let (n)
22562 (if (not (assoc (car e) rtn))
22563 (push e rtn)
22564 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22565 (setq rtn (assq-delete-all (car e) rtn))
22566 (push n rtn))))))
22568 (defun org-delete-all (elts list)
22569 "Remove all elements in ELTS from LIST.
22570 Comparison is done with `equal'. It is a destructive operation
22571 that may remove elements by altering the list structure."
22572 (while elts
22573 (setq list (delete (pop elts) list)))
22574 list)
22576 (defun org-back-over-empty-lines ()
22577 "Move backwards over whitespace, to the beginning of the first empty line.
22578 Returns the number of empty lines passed."
22579 (let ((pos (point)))
22580 (if (cdr (assq 'heading org-blank-before-new-entry))
22581 (skip-chars-backward " \t\n\r")
22582 (unless (eobp)
22583 (forward-line -1)))
22584 (beginning-of-line 2)
22585 (goto-char (min (point) pos))
22586 (count-lines (point) pos)))
22588 (defun org-skip-whitespace ()
22589 (skip-chars-forward " \t\n\r"))
22591 (defun org-point-in-group (point group &optional context)
22592 "Check if POINT is in match-group GROUP.
22593 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22594 match. If the match group does not exist or point is not inside it,
22595 return nil."
22596 (and (match-beginning group)
22597 (>= point (match-beginning group))
22598 (<= point (match-end group))
22599 (if context
22600 (list context (match-beginning group) (match-end group))
22601 t)))
22603 (defun org-switch-to-buffer-other-window (&rest args)
22604 "Switch to buffer in a second window on the current frame.
22605 In particular, do not allow pop-up frames.
22606 Returns the newly created buffer."
22607 (org-no-popups
22608 (apply 'switch-to-buffer-other-window args)))
22610 (defun org-combine-plists (&rest plists)
22611 "Create a single property list from all plists in PLISTS.
22612 The process starts by copying the first list, and then setting properties
22613 from the other lists. Settings in the last list are the most significant
22614 ones and overrule settings in the other lists."
22615 (let ((rtn (copy-sequence (pop plists)))
22616 p v ls)
22617 (while plists
22618 (setq ls (pop plists))
22619 (while ls
22620 (setq p (pop ls) v (pop ls))
22621 (setq rtn (plist-put rtn p v))))
22622 rtn))
22624 (defun org-replace-escapes (string table)
22625 "Replace %-escapes in STRING with values in TABLE.
22626 TABLE is an association list with keys like \"%a\" and string values.
22627 The sequences in STRING may contain normal field width and padding information,
22628 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22629 so values can contain further %-escapes if they are define later in TABLE."
22630 (let ((tbl (copy-alist table))
22631 (case-fold-search nil)
22632 (pchg 0)
22633 re rpl)
22634 (dolist (e tbl)
22635 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22636 (when (and (cdr e) (string-match re (cdr e)))
22637 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22638 (safe "SREF"))
22639 (add-text-properties 0 3 (list 'sref sref) safe)
22640 (setcdr e (replace-match safe t t (cdr e)))))
22641 (while (string-match re string)
22642 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22643 (cdr e)))
22644 (setq string (replace-match rpl t t string))))
22645 (while (setq pchg (next-property-change pchg string))
22646 (let ((sref (get-text-property pchg 'sref string)))
22647 (when (and sref (string-match "SREF" string pchg))
22648 (setq string (replace-match sref t t string)))))
22649 string))
22651 (defun org-find-base-buffer-visiting (file)
22652 "Like `find-buffer-visiting' but always return the base buffer and
22653 not an indirect buffer."
22654 (let ((buf (or (get-file-buffer file)
22655 (find-buffer-visiting file))))
22656 (if buf
22657 (or (buffer-base-buffer buf) buf)
22658 nil)))
22660 ;;; TODO: Only called once, from ox-odt which should probably use
22661 ;;; org-export-inline-image-p or something.
22662 (defun org-file-image-p (file)
22663 "Return non-nil if FILE is an image."
22664 (save-match-data
22665 (string-match (image-file-name-regexp) file)))
22667 (defun org-get-cursor-date (&optional with-time)
22668 "Return the date at cursor in as a time.
22669 This works in the calendar and in the agenda, anywhere else it just
22670 returns the current time.
22671 If WITH-TIME is non-nil, returns the time of the event at point (in
22672 the agenda) or the current time of the day."
22673 (let (date day defd tp hod mod)
22674 (when with-time
22675 (setq tp (get-text-property (point) 'time))
22676 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22677 (setq hod (string-to-number (match-string 1 tp))
22678 mod (string-to-number (match-string 2 tp))))
22679 (or tp (let ((now (decode-time)))
22680 (setq hod (nth 2 now)
22681 mod (nth 1 now)))))
22682 (cond
22683 ((eq major-mode 'calendar-mode)
22684 (setq date (calendar-cursor-to-date)
22685 defd (encode-time 0 (or mod 0) (or hod 0)
22686 (nth 1 date) (nth 0 date) (nth 2 date))))
22687 ((eq major-mode 'org-agenda-mode)
22688 (setq day (get-text-property (point) 'day))
22689 (when day
22690 (setq date (calendar-gregorian-from-absolute day)
22691 defd (encode-time 0 (or mod 0) (or hod 0)
22692 (nth 1 date) (nth 0 date) (nth 2 date))))))
22693 (or defd (current-time))))
22695 (defun org-mark-subtree (&optional up)
22696 "Mark the current subtree.
22697 This puts point at the start of the current subtree, and mark at
22698 the end. If a numeric prefix UP is given, move up into the
22699 hierarchy of headlines by UP levels before marking the subtree."
22700 (interactive "P")
22701 (org-with-limited-levels
22702 (cond ((org-at-heading-p) (beginning-of-line))
22703 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22704 (t (outline-previous-visible-heading 1))))
22705 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22706 (if (called-interactively-p 'any)
22707 (call-interactively 'org-mark-element)
22708 (org-mark-element)))
22710 (defun org-file-newer-than-p (file time)
22711 "Non-nil if FILE is newer than TIME.
22712 FILE is a filename, as a string, TIME is a list of integers, as
22713 returned by, e.g., `current-time'."
22714 (and (file-exists-p file)
22715 ;; Only compare times up to whole seconds as some file-systems
22716 ;; (e.g. HFS+) do not retain any finer granularity. As
22717 ;; a consequence, make sure we return non-nil when the two
22718 ;; times are equal.
22719 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22720 (cl-subseq time 0 2)))))
22722 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22723 "Compile a SOURCE file using PROCESS.
22725 PROCESS is either a function or a list of shell commands, as
22726 strings. EXT is a file extension, without the leading dot, as
22727 a string. It is used to check if the process actually succeeded.
22729 PROCESS must create a file with the same base name and directory
22730 as SOURCE, but ending with EXT. The function then returns its
22731 filename. Otherwise, it raises an error. The error message can
22732 then be refined by providing string ERR-MSG, which is appended to
22733 the standard message.
22735 If PROCESS is a function, it is called with a single argument:
22736 the SOURCE file.
22738 If it is a list of commands, each of them is called using
22739 `shell-command'. By default, in each command, %b, %f, %F and %o
22740 are replaced with, respectively, SOURCE base name, name, full
22741 name and directory. It is possible, however, to use more
22742 place-holders by specifying them in optional argument SPEC, as an
22743 alist following the pattern (CHARACTER . REPLACEMENT-STRING).
22745 When PROCESS is a list of commands, optional argument LOG-BUF can
22746 be set to a buffer or a buffer name. `shell-command' then uses
22747 it for output.
22749 `default-directory' is set to SOURCE directory during the whole
22750 process."
22751 (let* ((source-name (file-name-nondirectory source))
22752 (base-name (file-name-sans-extension source-name))
22753 (full-name (file-truename source))
22754 (out-dir (file-name-directory source))
22755 (time (current-time))
22756 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22757 (save-window-excursion
22758 (let ((default-directory (file-name-directory full-name)))
22759 (pcase process
22760 ((pred functionp) (funcall process (shell-quote-argument source)))
22761 ((pred consp)
22762 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22763 (spec (append spec
22764 `((?b . ,(shell-quote-argument base-name))
22765 (?f . ,(shell-quote-argument source-name))
22766 (?F . ,(shell-quote-argument full-name))
22767 (?o . ,(shell-quote-argument out-dir))))))
22768 (dolist (command process)
22769 (shell-command (format-spec command spec) log-buf))))
22770 (_ (error "No valid command to process %S%s" source err-msg)))))
22771 ;; Check for process failure.
22772 (let ((output (concat out-dir base-name "." ext)))
22773 (unless (org-file-newer-than-p output time)
22774 (error (format "File %S wasn't produced%s" output err-msg)))
22775 output)))
22777 ;;; Indentation
22779 (defun org--get-expected-indentation (element contentsp)
22780 "Expected indentation column for current line, according to ELEMENT.
22781 ELEMENT is an element containing point. CONTENTSP is non-nil
22782 when indentation is to be computed according to contents of
22783 ELEMENT."
22784 (let ((type (org-element-type element))
22785 (start (org-element-property :begin element))
22786 (post-affiliated (org-element-property :post-affiliated element)))
22787 (org-with-wide-buffer
22788 (cond
22789 (contentsp
22790 (cl-case type
22791 ((diary-sexp footnote-definition) 0)
22792 ((headline inlinetask nil)
22793 (if (not org-adapt-indentation) 0
22794 (let ((level (org-current-level)))
22795 (if level (1+ level) 0))))
22796 ((item plain-list) (org-list-item-body-column post-affiliated))
22798 (goto-char start)
22799 (org-get-indentation))))
22800 ((memq type '(headline inlinetask nil))
22801 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22802 (org--get-expected-indentation element t)
22804 ((memq type '(diary-sexp footnote-definition)) 0)
22805 ;; First paragraph of a footnote definition or an item.
22806 ;; Indent like parent.
22807 ((< (line-beginning-position) start)
22808 (org--get-expected-indentation
22809 (org-element-property :parent element) t))
22810 ;; At first line: indent according to previous sibling, if any,
22811 ;; ignoring footnote definitions and inline tasks, or parent's
22812 ;; contents.
22813 ((= (line-beginning-position) start)
22814 (catch 'exit
22815 (while t
22816 (if (= (point-min) start) (throw 'exit 0)
22817 (goto-char (1- start))
22818 (let* ((previous (org-element-at-point))
22819 (parent previous))
22820 (while (and parent (<= (org-element-property :end parent) start))
22821 (setq previous parent
22822 parent (org-element-property :parent parent)))
22823 (cond
22824 ((not previous) (throw 'exit 0))
22825 ((> (org-element-property :end previous) start)
22826 (throw 'exit (org--get-expected-indentation previous t)))
22827 ((memq (org-element-type previous)
22828 '(footnote-definition inlinetask))
22829 (setq start (org-element-property :begin previous)))
22830 (t (goto-char (org-element-property :begin previous))
22831 (throw 'exit
22832 (if (bolp) (org-get-indentation)
22833 ;; At first paragraph in an item or
22834 ;; a footnote definition.
22835 (org--get-expected-indentation
22836 (org-element-property :parent previous) t))))))))))
22837 ;; Otherwise, move to the first non-blank line above.
22839 (beginning-of-line)
22840 (let ((pos (point)))
22841 (skip-chars-backward " \r\t\n")
22842 (cond
22843 ;; Two blank lines end a footnote definition or a plain
22844 ;; list. When we indent an empty line after them, the
22845 ;; containing list or footnote definition is over, so it
22846 ;; qualifies as a previous sibling. Therefore, we indent
22847 ;; like its first line.
22848 ((and (memq type '(footnote-definition plain-list))
22849 (> (count-lines (point) pos) 2))
22850 (goto-char start)
22851 (org-get-indentation))
22852 ;; Line above is the first one of a paragraph at the
22853 ;; beginning of an item or a footnote definition. Indent
22854 ;; like parent.
22855 ((< (line-beginning-position) start)
22856 (org--get-expected-indentation
22857 (org-element-property :parent element) t))
22858 ;; Line above is the beginning of an element, i.e., point
22859 ;; was originally on the blank lines between element's start
22860 ;; and contents.
22861 ((= (line-beginning-position) post-affiliated)
22862 (org--get-expected-indentation element t))
22863 ;; POS is after contents in a greater element. Indent like
22864 ;; the beginning of the element.
22866 ;; As a special case, if point is at the end of a footnote
22867 ;; definition or an item, indent like the very last element
22868 ;; within. If that last element is an item, indent like its
22869 ;; contents.
22870 ((and (not (eq type 'paragraph))
22871 (let ((cend (org-element-property :contents-end element)))
22872 (and cend (<= cend pos))))
22873 (if (memq type '(footnote-definition item plain-list))
22874 (let ((last (org-element-at-point)))
22875 (org--get-expected-indentation
22876 last (eq (org-element-type last) 'item)))
22877 (goto-char start)
22878 (org-get-indentation)))
22879 ;; In any other case, indent like the current line.
22880 (t (org-get-indentation)))))))))
22882 (defun org--align-node-property ()
22883 "Align node property at point.
22884 Alignment is done according to `org-property-format', which see."
22885 (when (save-excursion
22886 (beginning-of-line)
22887 (looking-at org-property-re))
22888 (replace-match
22889 (concat (match-string 4)
22890 (org-trim
22891 (format org-property-format (match-string 1) (match-string 3))))
22892 t t)))
22894 (defun org-indent-line ()
22895 "Indent line depending on context.
22897 Indentation is done according to the following rules:
22899 - Footnote definitions, diary sexps, headlines and inline tasks
22900 have to start at column 0.
22902 - On the very first line of an element, consider, in order, the
22903 next rules until one matches:
22905 1. If there's a sibling element before, ignoring footnote
22906 definitions and inline tasks, indent like its first line.
22908 2. If element has a parent, indent like its contents. More
22909 precisely, if parent is an item, indent after the
22910 description part, if any, or the bullet (see
22911 `org-list-description-max-indent'). Else, indent like
22912 parent's first line.
22914 3. Otherwise, indent relatively to current level, if
22915 `org-adapt-indentation' is non-nil, or to left margin.
22917 - On a blank line at the end of an element, indent according to
22918 the type of the element. More precisely
22920 1. If element is a plain list, an item, or a footnote
22921 definition, indent like the very last element within.
22923 2. If element is a paragraph, indent like its last non blank
22924 line.
22926 3. Otherwise, indent like its very first line.
22928 - In the code part of a source block, use language major mode
22929 to indent current line if `org-src-tab-acts-natively' is
22930 non-nil. If it is nil, do nothing.
22932 - Otherwise, indent like the first non-blank line above.
22934 The function doesn't indent an item as it could break the whole
22935 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22936 `\\[org-shiftmetaright]'.
22938 Also align node properties according to `org-property-format'."
22939 (interactive)
22940 (cond
22941 (orgstruct-is-++
22942 (let ((indent-line-function
22943 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22944 (indent-according-to-mode)))
22945 ((org-at-heading-p) 'noindent)
22947 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22948 (type (org-element-type element)))
22949 (cond ((and (memq type '(plain-list item))
22950 (= (line-beginning-position)
22951 (org-element-property :post-affiliated element)))
22952 'noindent)
22953 ((and (eq type 'src-block)
22954 org-src-tab-acts-natively
22955 (> (line-beginning-position)
22956 (org-element-property :post-affiliated element))
22957 (< (line-beginning-position)
22958 (org-with-wide-buffer
22959 (goto-char (org-element-property :end element))
22960 (skip-chars-backward " \r\t\n")
22961 (line-beginning-position))))
22962 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22964 (let ((column (org--get-expected-indentation element nil)))
22965 ;; Preserve current column.
22966 (if (<= (current-column) (current-indentation))
22967 (indent-line-to column)
22968 (save-excursion (indent-line-to column))))
22969 ;; Align node property. Also preserve current column.
22970 (when (eq type 'node-property)
22971 (let ((column (current-column)))
22972 (org--align-node-property)
22973 (org-move-to-column column)))))))))
22975 (defun org-indent-region (start end)
22976 "Indent each non-blank line in the region.
22977 Called from a program, START and END specify the region to
22978 indent. The function will not indent contents of example blocks,
22979 verse blocks and export blocks as leading white spaces are
22980 assumed to be significant there."
22981 (interactive "r")
22982 (save-excursion
22983 (goto-char start)
22984 (skip-chars-forward " \r\t\n")
22985 (unless (eobp) (beginning-of-line))
22986 (let ((indent-to
22987 (lambda (ind pos)
22988 ;; Set IND as indentation for all lines between point and
22989 ;; POS. Blank lines are ignored. Leave point after POS
22990 ;; once done.
22991 (let ((limit (copy-marker pos)))
22992 (while (< (point) limit)
22993 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22994 (forward-line))
22995 (set-marker limit nil))))
22996 (end (copy-marker end)))
22997 (while (< (point) end)
22998 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22999 (let* ((element (org-element-at-point))
23000 (type (org-element-type element))
23001 (element-end (copy-marker (org-element-property :end element)))
23002 (ind (org--get-expected-indentation element nil)))
23003 (cond
23004 ((or (memq type '(paragraph table table-row))
23005 (not (or (org-element-property :contents-begin element)
23006 (memq type
23007 '(example-block export-block src-block)))))
23008 ;; Elements here are indented as a single block. Also
23009 ;; align node properties.
23010 (when (eq type 'node-property)
23011 (org--align-node-property)
23012 (beginning-of-line))
23013 (funcall indent-to ind (min element-end end)))
23015 ;; Elements in this category consist of three parts:
23016 ;; before the contents, the contents, and after the
23017 ;; contents. The contents are treated specially,
23018 ;; according to the element type, or not indented at
23019 ;; all. Other parts are indented as a single block.
23020 (let* ((post (copy-marker
23021 (org-element-property :post-affiliated element)))
23022 (cbeg
23023 (copy-marker
23024 (cond
23025 ((not (org-element-property :contents-begin element))
23026 ;; Fake contents for source blocks.
23027 (org-with-wide-buffer
23028 (goto-char post)
23029 (forward-line)
23030 (point)))
23031 ((memq type '(footnote-definition item plain-list))
23032 ;; Contents in these elements could start on
23033 ;; the same line as the beginning of the
23034 ;; element. Make sure we start indenting
23035 ;; from the second line.
23036 (org-with-wide-buffer
23037 (goto-char post)
23038 (end-of-line)
23039 (skip-chars-forward " \r\t\n")
23040 (if (eobp) (point) (line-beginning-position))))
23041 (t (org-element-property :contents-begin element)))))
23042 (cend (copy-marker
23043 (or (org-element-property :contents-end element)
23044 ;; Fake contents for source blocks.
23045 (org-with-wide-buffer
23046 (goto-char element-end)
23047 (skip-chars-backward " \r\t\n")
23048 (line-beginning-position)))
23049 t)))
23050 ;; Do not change items indentation individually as it
23051 ;; might break the list as a whole. On the other
23052 ;; hand, when at a plain list, indent it as a whole.
23053 (cond ((eq type 'plain-list)
23054 (let ((offset (- ind (org-get-indentation))))
23055 (unless (zerop offset)
23056 (indent-rigidly (org-element-property :begin element)
23057 (org-element-property :end element)
23058 offset))
23059 (goto-char cbeg)))
23060 ((eq type 'item) (goto-char cbeg))
23061 (t (funcall indent-to ind (min cbeg end))))
23062 (when (< (point) end)
23063 (cl-case type
23064 ((example-block export-block verse-block))
23065 (src-block
23066 ;; In a source block, indent source code
23067 ;; according to language major mode, but only if
23068 ;; `org-src-tab-acts-natively' is non-nil.
23069 (when (and (< (point) end) org-src-tab-acts-natively)
23070 (ignore-errors
23071 (org-babel-do-in-edit-buffer
23072 (indent-region (point-min) (point-max))))))
23073 (t (org-indent-region (point) (min cend end))))
23074 (goto-char (min cend end))
23075 (when (< (point) end)
23076 (funcall indent-to ind (min element-end end))))
23077 (set-marker post nil)
23078 (set-marker cbeg nil)
23079 (set-marker cend nil))))
23080 (set-marker element-end nil))))
23081 (set-marker end nil))))
23083 (defun org-indent-drawer ()
23084 "Indent the drawer at point."
23085 (interactive)
23086 (unless (save-excursion
23087 (beginning-of-line)
23088 (looking-at-p org-drawer-regexp))
23089 (user-error "Not at a drawer"))
23090 (let ((element (org-element-at-point)))
23091 (unless (memq (org-element-type element) '(drawer property-drawer))
23092 (user-error "Not at a drawer"))
23093 (org-with-wide-buffer
23094 (org-indent-region (org-element-property :begin element)
23095 (org-element-property :end element))))
23096 (message "Drawer at point indented"))
23098 (defun org-indent-block ()
23099 "Indent the block at point."
23100 (interactive)
23101 (unless (save-excursion
23102 (beginning-of-line)
23103 (let ((case-fold-search t))
23104 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23105 (user-error "Not at a block"))
23106 (let ((element (org-element-at-point)))
23107 (unless (memq (org-element-type element)
23108 '(comment-block center-block dynamic-block example-block
23109 export-block quote-block special-block
23110 src-block verse-block))
23111 (user-error "Not at a block"))
23112 (org-with-wide-buffer
23113 (org-indent-region (org-element-property :begin element)
23114 (org-element-property :end element))))
23115 (message "Block at point indented"))
23118 ;;; Filling
23120 ;; We use our own fill-paragraph and auto-fill functions.
23122 ;; `org-fill-paragraph' relies on adaptive filling and context
23123 ;; checking. Appropriate `fill-prefix' is computed with
23124 ;; `org-adaptive-fill-function'.
23126 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23127 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23128 ;; `org-adaptive-fill-function' value. Internally,
23129 ;; `org-comment-line-break-function' breaks the line.
23131 ;; `org-setup-filling' installs filling and auto-filling related
23132 ;; variables during `org-mode' initialization.
23134 (defvar org-element-paragraph-separate) ; org-element.el
23135 (defun org-setup-filling ()
23136 (require 'org-element)
23137 ;; Prevent auto-fill from inserting unwanted new items.
23138 (when (boundp 'fill-nobreak-predicate)
23139 (setq-local
23140 fill-nobreak-predicate
23141 (org-uniquify
23142 (append fill-nobreak-predicate
23143 '(org-fill-line-break-nobreak-p
23144 org-fill-paragraph-with-timestamp-nobreak-p)))))
23145 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23146 (setq-local paragraph-start paragraph-ending)
23147 (setq-local paragraph-separate paragraph-ending))
23148 (setq-local fill-paragraph-function 'org-fill-paragraph)
23149 (setq-local auto-fill-inhibit-regexp nil)
23150 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23151 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23152 (setq-local comment-line-break-function 'org-comment-line-break-function))
23154 (defun org-fill-line-break-nobreak-p ()
23155 "Non-nil when a new line at point would create an Org line break."
23156 (save-excursion
23157 (skip-chars-backward "[ \t]")
23158 (skip-chars-backward "\\\\")
23159 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23161 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23162 "Non-nil when a new line at point would split a timestamp."
23163 (and (org-at-timestamp-p t)
23164 (not (looking-at org-ts-regexp-both))))
23166 (declare-function message-in-body-p "message" ())
23167 (defvar orgtbl-line-start-regexp) ; From org-table.el
23168 (defun org-adaptive-fill-function ()
23169 "Compute a fill prefix for the current line.
23170 Return fill prefix, as a string, or nil if current line isn't
23171 meant to be filled. For convenience, if `adaptive-fill-regexp'
23172 matches in paragraphs or comments, use it."
23173 (catch 'exit
23174 (when (derived-mode-p 'message-mode)
23175 (save-excursion
23176 (beginning-of-line)
23177 (cond ((not (message-in-body-p)) (throw 'exit nil))
23178 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23179 ((looking-at message-cite-prefix-regexp)
23180 (throw 'exit (match-string-no-properties 0)))
23181 ((looking-at org-outline-regexp)
23182 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23183 (org-with-wide-buffer
23184 (unless (org-at-heading-p)
23185 (let* ((p (line-beginning-position))
23186 (element (save-excursion
23187 (beginning-of-line)
23188 (org-element-at-point)))
23189 (type (org-element-type element))
23190 (post-affiliated (org-element-property :post-affiliated element)))
23191 (unless (< p post-affiliated)
23192 (cl-case type
23193 (comment
23194 (save-excursion
23195 (beginning-of-line)
23196 (looking-at "[ \t]*")
23197 (concat (match-string 0) "# ")))
23198 (footnote-definition "")
23199 ((item plain-list)
23200 (make-string (org-list-item-body-column post-affiliated) ?\s))
23201 (paragraph
23202 ;; Fill prefix is usually the same as the current line,
23203 ;; unless the paragraph is at the beginning of an item.
23204 (let ((parent (org-element-property :parent element)))
23205 (save-excursion
23206 (beginning-of-line)
23207 (cond ((eq (org-element-type parent) 'item)
23208 (make-string (org-list-item-body-column
23209 (org-element-property :begin parent))
23210 ?\s))
23211 ((and adaptive-fill-regexp
23212 ;; Locally disable
23213 ;; `adaptive-fill-function' to let
23214 ;; `fill-context-prefix' handle
23215 ;; `adaptive-fill-regexp' variable.
23216 (let (adaptive-fill-function)
23217 (fill-context-prefix
23218 post-affiliated
23219 (org-element-property :end element)))))
23220 ((looking-at "[ \t]+") (match-string 0))
23221 (t "")))))
23222 (comment-block
23223 ;; Only fill contents if P is within block boundaries.
23224 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23225 (forward-line)
23226 (point)))
23227 (cend (save-excursion
23228 (goto-char (org-element-property :end element))
23229 (skip-chars-backward " \r\t\n")
23230 (line-beginning-position))))
23231 (when (and (>= p cbeg) (< p cend))
23232 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23233 (match-string 0)
23234 "")))))))))))
23236 (declare-function message-goto-body "message" ())
23237 (defvar message-cite-prefix-regexp) ; From message.el
23238 (defun org-fill-paragraph (&optional justify)
23239 "Fill element at point, when applicable.
23241 This function only applies to comment blocks, comments, example
23242 blocks and paragraphs. Also, as a special case, re-align table
23243 when point is at one.
23245 If JUSTIFY is non-nil (interactively, with prefix argument),
23246 justify as well. If `sentence-end-double-space' is non-nil, then
23247 period followed by one space does not end a sentence, so don't
23248 break a line there. The variable `fill-column' controls the
23249 width for filling.
23251 For convenience, when point is at a plain list, an item or
23252 a footnote definition, try to fill the first paragraph within."
23253 (interactive)
23254 (if (and (derived-mode-p 'message-mode)
23255 (or (not (message-in-body-p))
23256 (save-excursion (move-beginning-of-line 1)
23257 (looking-at message-cite-prefix-regexp))))
23258 ;; First ensure filling is correct in message-mode.
23259 (let ((fill-paragraph-function
23260 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23261 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23262 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23263 (paragraph-separate
23264 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23265 (fill-paragraph nil))
23266 (with-syntax-table org-mode-transpose-word-syntax-table
23267 ;; Move to end of line in order to get the first paragraph
23268 ;; within a plain list or a footnote definition.
23269 (let ((element (save-excursion
23270 (end-of-line)
23271 (or (ignore-errors (org-element-at-point))
23272 (user-error "An element cannot be parsed line %d"
23273 (line-number-at-pos (point)))))))
23274 ;; First check if point is in a blank line at the beginning of
23275 ;; the buffer. In that case, ignore filling.
23276 (cl-case (org-element-type element)
23277 ;; Use major mode filling function is src blocks.
23278 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23279 ;; Align Org tables, leave table.el tables as-is.
23280 (table-row (org-table-align) t)
23281 (table
23282 (when (eq (org-element-property :type element) 'org)
23283 (save-excursion
23284 (goto-char (org-element-property :post-affiliated element))
23285 (org-table-align)))
23287 (paragraph
23288 ;; Paragraphs may contain `line-break' type objects.
23289 (let ((beg (max (point-min)
23290 (org-element-property :contents-begin element)))
23291 (end (min (point-max)
23292 (org-element-property :contents-end element))))
23293 ;; Do nothing if point is at an affiliated keyword.
23294 (if (< (line-end-position) beg) t
23295 (when (derived-mode-p 'message-mode)
23296 ;; In `message-mode', do not fill following citation
23297 ;; in current paragraph nor text before message body.
23298 (let ((body-start (save-excursion (message-goto-body))))
23299 (when body-start (setq beg (max body-start beg))))
23300 (when (save-excursion
23301 (re-search-forward
23302 (concat "^" message-cite-prefix-regexp) end t))
23303 (setq end (match-beginning 0))))
23304 ;; Fill paragraph, taking line breaks into account.
23305 (save-excursion
23306 (goto-char beg)
23307 (let ((cuts (list beg)))
23308 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23309 (when (eq 'line-break
23310 (org-element-type
23311 (save-excursion (backward-char)
23312 (org-element-context))))
23313 (push (point) cuts)))
23314 (dolist (c (delq end cuts))
23315 (fill-region-as-paragraph c end justify)
23316 (setq end c))))
23317 t)))
23318 ;; Contents of `comment-block' type elements should be
23319 ;; filled as plain text, but only if point is within block
23320 ;; markers.
23321 (comment-block
23322 (let* ((case-fold-search t)
23323 (beg (save-excursion
23324 (goto-char (org-element-property :begin element))
23325 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23326 (forward-line)
23327 (point)))
23328 (end (save-excursion
23329 (goto-char (org-element-property :end element))
23330 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23331 (line-beginning-position))))
23332 (if (or (< (point) beg) (> (point) end)) t
23333 (fill-region-as-paragraph
23334 (save-excursion (end-of-line)
23335 (re-search-backward "^[ \t]*$" beg 'move)
23336 (line-beginning-position))
23337 (save-excursion (beginning-of-line)
23338 (re-search-forward "^[ \t]*$" end 'move)
23339 (line-beginning-position))
23340 justify))))
23341 ;; Fill comments.
23342 (comment
23343 (let ((begin (org-element-property :post-affiliated element))
23344 (end (org-element-property :end element)))
23345 (when (and (>= (point) begin) (<= (point) end))
23346 (let ((begin (save-excursion
23347 (end-of-line)
23348 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23349 (progn (forward-line) (point))
23350 begin)))
23351 (end (save-excursion
23352 (end-of-line)
23353 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23354 (1- (line-beginning-position))
23355 (skip-chars-backward " \r\t\n")
23356 (line-end-position)))))
23357 ;; Do not fill comments when at a blank line.
23358 (when (> end begin)
23359 (let ((fill-prefix
23360 (save-excursion
23361 (beginning-of-line)
23362 (looking-at "[ \t]*#")
23363 (let ((comment-prefix (match-string 0)))
23364 (goto-char (match-end 0))
23365 (if (looking-at adaptive-fill-regexp)
23366 (concat comment-prefix (match-string 0))
23367 (concat comment-prefix " "))))))
23368 (save-excursion
23369 (fill-region-as-paragraph begin end justify))))))
23371 ;; Ignore every other element.
23372 (otherwise t))))))
23374 (defun org-auto-fill-function ()
23375 "Auto-fill function."
23376 ;; Check if auto-filling is meaningful.
23377 (let ((fc (current-fill-column)))
23378 (when (and fc (> (current-column) fc))
23379 (let* ((fill-prefix (org-adaptive-fill-function))
23380 ;; Enforce empty fill prefix, if required. Otherwise, it
23381 ;; will be computed again.
23382 (adaptive-fill-mode (not (equal fill-prefix ""))))
23383 (when fill-prefix (do-auto-fill))))))
23385 (defun org-comment-line-break-function (&optional soft)
23386 "Break line at point and indent, continuing comment if within one.
23387 The inserted newline is marked hard if variable
23388 `use-hard-newlines' is true, unless optional argument SOFT is
23389 non-nil."
23390 (if soft (insert-and-inherit ?\n) (newline 1))
23391 (save-excursion (forward-char -1) (delete-horizontal-space))
23392 (delete-horizontal-space)
23393 (indent-to-left-margin)
23394 (insert-before-markers-and-inherit fill-prefix))
23397 ;;; Fixed Width Areas
23399 (defun org-toggle-fixed-width ()
23400 "Toggle fixed-width markup.
23402 Add or remove fixed-width markup on current line, whenever it
23403 makes sense. Return an error otherwise.
23405 If a region is active and if it contains only fixed-width areas
23406 or blank lines, remove all fixed-width markup in it. If the
23407 region contains anything else, convert all non-fixed-width lines
23408 to fixed-width ones.
23410 Blank lines at the end of the region are ignored unless the
23411 region only contains such lines."
23412 (interactive)
23413 (if (not (org-region-active-p))
23414 ;; No region:
23416 ;; Remove fixed width marker only in a fixed-with element.
23418 ;; Add fixed width maker in paragraphs, in blank lines after
23419 ;; elements or at the beginning of a headline or an inlinetask,
23420 ;; and before any one-line elements (e.g., a clock).
23421 (progn
23422 (beginning-of-line)
23423 (let* ((element (org-element-at-point))
23424 (type (org-element-type element)))
23425 (cond
23426 ((and (eq type 'fixed-width)
23427 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23428 (replace-match
23429 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23430 ((and (memq type '(babel-call clock comment diary-sexp headline
23431 horizontal-rule keyword paragraph
23432 planning))
23433 (<= (org-element-property :post-affiliated element) (point)))
23434 (skip-chars-forward " \t")
23435 (insert ": "))
23436 ((and (looking-at-p "[ \t]*$")
23437 (or (eq type 'inlinetask)
23438 (save-excursion
23439 (skip-chars-forward " \r\t\n")
23440 (<= (org-element-property :end element) (point)))))
23441 (delete-region (point) (line-end-position))
23442 (org-indent-line)
23443 (insert ": "))
23444 (t (user-error "Cannot insert a fixed-width line here")))))
23445 ;; Region active.
23446 (let* ((begin (save-excursion
23447 (goto-char (region-beginning))
23448 (line-beginning-position)))
23449 (end (copy-marker
23450 (save-excursion
23451 (goto-char (region-end))
23452 (unless (eolp) (beginning-of-line))
23453 (if (save-excursion (re-search-backward "\\S-" begin t))
23454 (progn (skip-chars-backward " \r\t\n") (point))
23455 (point)))))
23456 (all-fixed-width-p
23457 (catch 'not-all-p
23458 (save-excursion
23459 (goto-char begin)
23460 (skip-chars-forward " \r\t\n")
23461 (when (eobp) (throw 'not-all-p nil))
23462 (while (< (point) end)
23463 (let ((element (org-element-at-point)))
23464 (if (eq (org-element-type element) 'fixed-width)
23465 (goto-char (org-element-property :end element))
23466 (throw 'not-all-p nil))))
23467 t))))
23468 (if all-fixed-width-p
23469 (save-excursion
23470 (goto-char begin)
23471 (while (< (point) end)
23472 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23473 (replace-match
23474 "" nil nil nil
23475 (if (= (line-end-position) (match-end 0)) 0 1)))
23476 (forward-line)))
23477 (let ((min-ind (point-max)))
23478 ;; Find minimum indentation across all lines.
23479 (save-excursion
23480 (goto-char begin)
23481 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23482 (setq min-ind 0)
23483 (catch 'zerop
23484 (while (< (point) end)
23485 (unless (looking-at-p "[ \t]*$")
23486 (let ((ind (org-get-indentation)))
23487 (setq min-ind (min min-ind ind))
23488 (when (zerop ind) (throw 'zerop t))))
23489 (forward-line)))))
23490 ;; Loop over all lines and add fixed-width markup everywhere
23491 ;; but in fixed-width lines.
23492 (save-excursion
23493 (goto-char begin)
23494 (while (< (point) end)
23495 (cond
23496 ((org-at-heading-p)
23497 (insert ": ")
23498 (forward-line)
23499 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23500 (insert ":")
23501 (forward-line)))
23502 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23503 (let* ((element (org-element-at-point))
23504 (element-end (org-element-property :end element)))
23505 (if (eq (org-element-type element) 'fixed-width)
23506 (progn (goto-char element-end)
23507 (skip-chars-backward " \r\t\n")
23508 (forward-line))
23509 (let ((limit (min end element-end)))
23510 (while (< (point) limit)
23511 (org-move-to-column min-ind t)
23512 (insert ": ")
23513 (forward-line))))))
23515 (org-move-to-column min-ind t)
23516 (insert ": ")
23517 (forward-line)))))))
23518 (set-marker end nil))))
23521 ;;; Comments
23523 ;; Org comments syntax is quite complex. It requires the entire line
23524 ;; to be just a comment. Also, even with the right syntax at the
23525 ;; beginning of line, some some elements (i.e. verse-block or
23526 ;; example-block) don't accept comments. Usual Emacs comment commands
23527 ;; cannot cope with those requirements. Therefore, Org replaces them.
23529 ;; Org still relies on `comment-dwim', but cannot trust
23530 ;; `comment-only-p'. So, `comment-region-function' and
23531 ;; `uncomment-region-function' both point
23532 ;; to`org-comment-or-uncomment-region'. Eventually,
23533 ;; `org-insert-comment' takes care of insertion of comments at the
23534 ;; beginning of line.
23536 ;; `org-setup-comments-handling' install comments related variables
23537 ;; during `org-mode' initialization.
23539 (defun org-setup-comments-handling ()
23540 (interactive)
23541 (setq-local comment-use-syntax nil)
23542 (setq-local comment-start "# ")
23543 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23544 (setq-local comment-insert-comment-function 'org-insert-comment)
23545 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23546 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23548 (defun org-insert-comment ()
23549 "Insert an empty comment above current line.
23550 If the line is empty, insert comment at its beginning. When
23551 point is within a source block, comment according to the related
23552 major mode."
23553 (if (let ((element (org-element-at-point)))
23554 (and (eq (org-element-type element) 'src-block)
23555 (< (save-excursion
23556 (goto-char (org-element-property :post-affiliated element))
23557 (line-end-position))
23558 (point))
23559 (> (save-excursion
23560 (goto-char (org-element-property :end element))
23561 (skip-chars-backward " \r\t\n")
23562 (line-beginning-position))
23563 (point))))
23564 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23565 (beginning-of-line)
23566 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23567 (open-line 1))
23568 (org-indent-line)
23569 (insert "# ")))
23571 (defvar comment-empty-lines) ; From newcomment.el.
23572 (defun org-comment-or-uncomment-region (beg end &rest _)
23573 "Comment or uncomment each non-blank line in the region.
23574 Uncomment each non-blank line between BEG and END if it only
23575 contains commented lines. Otherwise, comment them. If region is
23576 strictly within a source block, use appropriate comment syntax."
23577 (if (let ((element (org-element-at-point)))
23578 (and (eq (org-element-type element) 'src-block)
23579 (< (save-excursion
23580 (goto-char (org-element-property :post-affiliated element))
23581 (line-end-position))
23582 beg)
23583 (>= (save-excursion
23584 (goto-char (org-element-property :end element))
23585 (skip-chars-backward " \r\t\n")
23586 (line-beginning-position))
23587 end)))
23588 ;; Translate region boundaries for the Org buffer to the source
23589 ;; buffer.
23590 (let ((offset (- end beg)))
23591 (save-excursion
23592 (goto-char beg)
23593 (org-babel-do-in-edit-buffer
23594 (comment-or-uncomment-region (point) (+ offset (point))))))
23595 (save-restriction
23596 ;; Restrict region
23597 (narrow-to-region (save-excursion (goto-char beg)
23598 (skip-chars-forward " \r\t\n" end)
23599 (line-beginning-position))
23600 (save-excursion (goto-char end)
23601 (skip-chars-backward " \r\t\n" beg)
23602 (line-end-position)))
23603 (let ((uncommentp
23604 ;; UNCOMMENTP is non-nil when every non blank line between
23605 ;; BEG and END is a comment.
23606 (save-excursion
23607 (goto-char (point-min))
23608 (while (and (not (eobp))
23609 (let ((element (org-element-at-point)))
23610 (and (eq (org-element-type element) 'comment)
23611 (goto-char (min (point-max)
23612 (org-element-property
23613 :end element)))))))
23614 (eobp))))
23615 (if uncommentp
23616 ;; Only blank lines and comments in region: uncomment it.
23617 (save-excursion
23618 (goto-char (point-min))
23619 (while (not (eobp))
23620 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23621 (replace-match "" nil nil nil 1))
23622 (forward-line)))
23623 ;; Comment each line in region.
23624 (let ((min-indent (point-max)))
23625 ;; First find the minimum indentation across all lines.
23626 (save-excursion
23627 (goto-char (point-min))
23628 (while (and (not (eobp)) (not (zerop min-indent)))
23629 (unless (looking-at "[ \t]*$")
23630 (setq min-indent (min min-indent (current-indentation))))
23631 (forward-line)))
23632 ;; Then loop over all lines.
23633 (save-excursion
23634 (goto-char (point-min))
23635 (while (not (eobp))
23636 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23637 ;; Don't get fooled by invisible text (e.g. link path)
23638 ;; when moving to column MIN-INDENT.
23639 (let ((buffer-invisibility-spec nil))
23640 (org-move-to-column min-indent t))
23641 (insert comment-start))
23642 (forward-line)))))))))
23644 (defun org-comment-dwim (_arg)
23645 "Call `comment-dwim' within a source edit buffer if needed."
23646 (interactive "*P")
23647 (if (org-in-src-block-p)
23648 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23649 (call-interactively 'comment-dwim)))
23652 ;;; Timestamps API
23654 ;; This section contains tools to operate on timestamp objects, as
23655 ;; returned by, e.g. `org-element-context'.
23657 (defun org-timestamp--to-internal-time (timestamp &optional end)
23658 "Encode TIMESTAMP object into Emacs internal time.
23659 Use end of date range or time range when END is non-nil."
23660 (apply #'encode-time
23661 (cons 0
23662 (mapcar
23663 (lambda (prop) (or (org-element-property prop timestamp) 0))
23664 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23665 '(:minute-start :hour-start :day-start :month-start
23666 :year-start))))))
23668 (defun org-timestamp-has-time-p (timestamp)
23669 "Non-nil when TIMESTAMP has a time specified."
23670 (org-element-property :hour-start timestamp))
23672 (defun org-timestamp-format (timestamp format &optional end utc)
23673 "Format a TIMESTAMP object into a string.
23675 FORMAT is a format specifier to be passed to
23676 `format-time-string'.
23678 When optional argument END is non-nil, use end of date-range or
23679 time-range, if possible.
23681 When optional argument UTC is non-nil, time will be expressed as
23682 Universal Time."
23683 (format-time-string
23684 format (org-timestamp--to-internal-time timestamp end)
23685 (and utc t)))
23687 (defun org-timestamp-split-range (timestamp &optional end)
23688 "Extract a TIMESTAMP object from a date or time range.
23690 END, when non-nil, means extract the end of the range.
23691 Otherwise, extract its start.
23693 Return a new timestamp object."
23694 (let ((type (org-element-property :type timestamp)))
23695 (if (memq type '(active inactive diary)) timestamp
23696 (let ((split-ts (org-element-copy timestamp)))
23697 ;; Set new type.
23698 (org-element-put-property
23699 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23700 ;; Copy start properties over end properties if END is
23701 ;; non-nil. Otherwise, copy end properties over `start' ones.
23702 (let ((p-alist '((:minute-start . :minute-end)
23703 (:hour-start . :hour-end)
23704 (:day-start . :day-end)
23705 (:month-start . :month-end)
23706 (:year-start . :year-end))))
23707 (dolist (p-cell p-alist)
23708 (org-element-put-property
23709 split-ts
23710 (funcall (if end #'car #'cdr) p-cell)
23711 (org-element-property
23712 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23713 ;; Eventually refresh `:raw-value'.
23714 (org-element-put-property split-ts :raw-value nil)
23715 (org-element-put-property
23716 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23718 (defun org-timestamp-translate (timestamp &optional boundary)
23719 "Translate TIMESTAMP object to custom format.
23721 Format string is defined in `org-time-stamp-custom-formats',
23722 which see.
23724 When optional argument BOUNDARY is non-nil, it is either the
23725 symbol `start' or `end'. In this case, only translate the
23726 starting or ending part of TIMESTAMP if it is a date or time
23727 range. Otherwise, translate both parts.
23729 Return timestamp as-is if `org-display-custom-times' is nil or if
23730 it has a `diary' type."
23731 (let ((type (org-element-property :type timestamp)))
23732 (if (or (not org-display-custom-times) (eq type 'diary))
23733 (org-element-interpret-data timestamp)
23734 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23735 org-time-stamp-custom-formats)))
23736 (if (and (not boundary) (memq type '(active-range inactive-range)))
23737 (concat (org-timestamp-format timestamp fmt)
23738 "--"
23739 (org-timestamp-format timestamp fmt t))
23740 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23744 ;;; Other stuff.
23746 (defvar reftex-docstruct-symbol)
23747 (defvar org--rds)
23749 (defun org-reftex-citation ()
23750 "Use reftex-citation to insert a citation into the buffer.
23751 This looks for a line like
23753 #+BIBLIOGRAPHY: foo plain option:-d
23755 and derives from it that foo.bib is the bibliography file relevant
23756 for this document. It then installs the necessary environment for RefTeX
23757 to work in this buffer and calls `reftex-citation' to insert a citation
23758 into the buffer.
23760 Export of such citations to both LaTeX and HTML is handled by the contributed
23761 package ox-bibtex by Taru Karttunen."
23762 (interactive)
23763 (let ((reftex-docstruct-symbol 'org--rds)
23764 org--rds bib)
23765 (org-with-wide-buffer
23766 (let ((case-fold-search t)
23767 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23768 (if (not (save-excursion
23769 (or (re-search-forward re nil t)
23770 (re-search-backward re nil t))))
23771 (user-error "No bibliography defined in file")
23772 (setq bib (concat (match-string 1) ".bib")
23773 org--rds (list (list 'bib bib))))))
23774 (call-interactively 'reftex-citation)))
23776 ;;;; Functions extending outline functionality
23778 (defun org-beginning-of-line (&optional n)
23779 "Go to the beginning of the current visible line.
23781 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23782 tags on the first attempt, and only move to after the tags when
23783 the cursor is already beyond the end of the headline.
23785 With argument N not nil or 1, move forward N - 1 lines first."
23786 (interactive "^p")
23787 (let ((origin (point))
23788 (special (pcase org-special-ctrl-a/e
23789 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23790 deactivate-mark)
23791 ;; First move to a visible line.
23792 (if (bound-and-true-p visual-line-mode)
23793 (beginning-of-visual-line n)
23794 (move-beginning-of-line n)
23795 ;; `move-beginning-of-line' may leave point after invisible
23796 ;; characters if line starts with such of these (e.g., with
23797 ;; a link at column 0). Really move to the beginning of the
23798 ;; current visible line.
23799 (beginning-of-line))
23800 (cond
23801 ;; No special behavior. Point is already at the beginning of
23802 ;; a line, logical or visual.
23803 ((not special))
23804 ;; `beginning-of-visual-line' left point before logical beginning
23805 ;; of line: point is at the beginning of a visual line. Bail
23806 ;; out.
23807 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23808 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23809 ;; At a headline, special position is before the title, but
23810 ;; after any TODO keyword or priority cookie.
23811 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23812 (line-end-position)))
23813 (bol (point)))
23814 (if (eq special 'reversed)
23815 (when (and (= origin bol) (eq last-command this-command))
23816 (goto-char refpos))
23817 (when (or (> origin refpos) (= origin bol))
23818 (goto-char refpos)))))
23819 ((and (looking-at org-list-full-item-re)
23820 (memq (org-element-type (save-match-data (org-element-at-point)))
23821 '(item plain-list)))
23822 ;; Set special position at first white space character after
23823 ;; bullet, and check-box, if any.
23824 (let ((after-bullet
23825 (let ((box (match-end 3)))
23826 (cond ((not box) (match-end 1))
23827 ((eq (char-after box) ?\s) (1+ box))
23828 (t box)))))
23829 (if (eq special 'reversed)
23830 (when (and (= (point) origin) (eq last-command this-command))
23831 (goto-char after-bullet))
23832 (when (or (> origin after-bullet) (= (point) origin))
23833 (goto-char after-bullet)))))
23834 ;; No special context. Point is already at beginning of line.
23835 (t nil))))
23837 (defun org-end-of-line (&optional n)
23838 "Go to the end of the line, but before ellipsis, if any.
23840 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23841 tags on the first attempt, and only move to after the tags when
23842 the cursor is already beyond the end of the headline.
23844 With argument N not nil or 1, move forward N - 1 lines first."
23845 (interactive "^p")
23846 (let ((origin (point))
23847 (special (pcase org-special-ctrl-a/e
23848 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23849 deactivate-mark)
23850 ;; First move to a visible line.
23851 (if (bound-and-true-p visual-line-mode)
23852 (beginning-of-visual-line n)
23853 (move-beginning-of-line n))
23854 (cond
23855 ;; At a headline, with tags.
23856 ((and special
23857 (save-excursion
23858 (beginning-of-line)
23859 (let ((case-fold-search nil))
23860 (looking-at org-complex-heading-regexp)))
23861 (match-end 5))
23862 (let ((tags (save-excursion
23863 (goto-char (match-beginning 5))
23864 (skip-chars-backward " \t")
23865 (point)))
23866 (visual-end (and (bound-and-true-p visual-line-mode)
23867 (save-excursion
23868 (end-of-visual-line)
23869 (point)))))
23870 ;; If `end-of-visual-line' brings us before end of line or
23871 ;; even tags, i.e., the headline spans over multiple visual
23872 ;; lines, move there.
23873 (cond ((and visual-end
23874 (< visual-end tags)
23875 (<= origin visual-end))
23876 (goto-char visual-end))
23877 ((eq special 'reversed)
23878 (if (and (= origin (line-end-position))
23879 (eq this-command last-command))
23880 (goto-char tags)
23881 (end-of-line)))
23883 (if (or (< origin tags) (= origin (line-end-position)))
23884 (goto-char tags)
23885 (end-of-line))))))
23886 ((bound-and-true-p visual-line-mode)
23887 (let ((bol (line-beginning-position)))
23888 (end-of-visual-line)
23889 ;; If `end-of-visual-line' gets us past the ellipsis at the
23890 ;; end of a line, backtrack and use `end-of-line' instead.
23891 (when (/= bol (line-beginning-position))
23892 (goto-char bol)
23893 (end-of-line))))
23894 (t (end-of-line)))))
23896 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23897 (define-key org-mode-map "\C-e" 'org-end-of-line)
23899 (defun org-backward-sentence (&optional _arg)
23900 "Go to beginning of sentence, or beginning of table field.
23901 This will call `backward-sentence' or `org-table-beginning-of-field',
23902 depending on context."
23903 (interactive)
23904 (let* ((element (org-element-at-point))
23905 (contents-begin (org-element-property :contents-begin element))
23906 (table (org-element-lineage element '(table) t)))
23907 (if (and table
23908 (> (point) contents-begin)
23909 (<= (point) (org-element-property :contents-end table)))
23910 (call-interactively #'org-table-beginning-of-field)
23911 (save-restriction
23912 (when (and contents-begin
23913 (< (point-min) contents-begin)
23914 (> (point) contents-begin))
23915 (narrow-to-region contents-begin
23916 (org-element-property :contents-end element)))
23917 (call-interactively #'backward-sentence)))))
23919 (defun org-forward-sentence (&optional _arg)
23920 "Go to end of sentence, or end of table field.
23921 This will call `forward-sentence' or `org-table-end-of-field',
23922 depending on context."
23923 (interactive)
23924 (let* ((element (org-element-at-point))
23925 (contents-end (org-element-property :contents-end element))
23926 (table (org-element-lineage element '(table) t)))
23927 (if (and table
23928 (>= (point) (org-element-property :contents-begin table))
23929 (< (point) contents-end))
23930 (call-interactively #'org-table-end-of-field)
23931 (save-restriction
23932 (when (and contents-end
23933 (> (point-max) contents-end)
23934 ;; Skip blank lines between elements.
23935 (< (org-element-property :end element)
23936 (save-excursion (goto-char contents-end)
23937 (skip-chars-forward " \r\t\n"))))
23938 (narrow-to-region (org-element-property :contents-begin element)
23939 contents-end))
23940 (call-interactively #'forward-sentence)))))
23942 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23943 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23945 (defun org-kill-line (&optional _arg)
23946 "Kill line, to tags or end of line."
23947 (interactive)
23948 (cond
23949 ((or (not org-special-ctrl-k)
23950 (bolp)
23951 (not (org-at-heading-p)))
23952 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23953 org-ctrl-k-protect-subtree
23954 (or (eq org-ctrl-k-protect-subtree 'error)
23955 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23956 (user-error "C-k aborted as it would kill a hidden subtree"))
23957 (call-interactively
23958 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23959 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23960 (kill-region (point) (match-beginning 1))
23961 (org-set-tags nil t))
23962 (t (kill-region (point) (point-at-eol)))))
23964 (define-key org-mode-map "\C-k" 'org-kill-line)
23966 (defun org-yank (&optional arg)
23967 "Yank. If the kill is a subtree, treat it specially.
23968 This command will look at the current kill and check if is a single
23969 subtree, or a series of subtrees[1]. If it passes the test, and if the
23970 cursor is at the beginning of a line or after the stars of a currently
23971 empty headline, then the yank is handled specially. How exactly depends
23972 on the value of the following variables.
23974 `org-yank-folded-subtrees'
23975 By default, this variable is non-nil, which results in
23976 subtree(s) being folded after insertion, except if doing so
23977 would swallow text after the yanked text.
23979 `org-yank-adjusted-subtrees'
23980 When non-nil (the default value is nil), the subtree will be
23981 promoted or demoted in order to fit into the local outline tree
23982 structure, which means that the level will be adjusted so that it
23983 becomes the smaller one of the two *visible* surrounding headings.
23985 Any prefix to this command will cause `yank' to be called directly with
23986 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23987 will just
23988 plainly yank the text as it is.
23990 \[1] The test checks if the first non-white line is a heading
23991 and if there are no other headings with fewer stars."
23992 (interactive "P")
23993 (org-yank-generic 'yank arg))
23995 (defun org-yank-generic (command arg)
23996 "Perform some yank-like command.
23998 This function implements the behavior described in the `org-yank'
23999 documentation. However, it has been generalized to work for any
24000 interactive command with similar behavior."
24002 ;; pretend to be command COMMAND
24003 (setq this-command command)
24005 (if arg
24006 (call-interactively command)
24008 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24009 (and (org-kill-is-subtree-p)
24010 (or (bolp)
24011 (and (looking-at "[ \t]*$")
24012 (string-match
24013 "\\`\\*+\\'"
24014 (buffer-substring (point-at-bol) (point)))))))
24015 swallowp)
24016 (cond
24017 ((and subtreep org-yank-folded-subtrees)
24018 (let ((beg (point))
24019 end)
24020 (if (and subtreep org-yank-adjusted-subtrees)
24021 (org-paste-subtree nil nil 'for-yank)
24022 (call-interactively command))
24024 (setq end (point))
24025 (goto-char beg)
24026 (when (and (bolp) subtreep
24027 (not (setq swallowp
24028 (org-yank-folding-would-swallow-text beg end))))
24029 (org-with-limited-levels
24030 (or (looking-at org-outline-regexp)
24031 (re-search-forward org-outline-regexp-bol end t))
24032 (while (and (< (point) end) (looking-at org-outline-regexp))
24033 (outline-hide-subtree)
24034 (org-cycle-show-empty-lines 'folded)
24035 (condition-case nil
24036 (outline-forward-same-level 1)
24037 (error (goto-char end))))))
24038 (when swallowp
24039 (message
24040 "Inserted text not folded because that would swallow text"))
24042 (goto-char end)
24043 (skip-chars-forward " \t\n\r")
24044 (beginning-of-line 1)
24045 (push-mark beg 'nomsg)))
24046 ((and subtreep org-yank-adjusted-subtrees)
24047 (let ((beg (point-at-bol)))
24048 (org-paste-subtree nil nil 'for-yank)
24049 (push-mark beg 'nomsg)))
24051 (call-interactively command))))))
24053 (defun org-yank-folding-would-swallow-text (beg end)
24054 "Would hide-subtree at BEG swallow any text after END?"
24055 (let (level)
24056 (org-with-limited-levels
24057 (save-excursion
24058 (goto-char beg)
24059 (when (or (looking-at org-outline-regexp)
24060 (re-search-forward org-outline-regexp-bol end t))
24061 (setq level (org-outline-level)))
24062 (goto-char end)
24063 (skip-chars-forward " \t\r\n\v\f")
24064 (not (or (eobp)
24065 (and (bolp) (looking-at-p org-outline-regexp)
24066 (<= (org-outline-level) level))))))))
24068 (define-key org-mode-map "\C-y" 'org-yank)
24070 (defun org-truely-invisible-p ()
24071 "Check if point is at a character currently not visible.
24072 This version does not only check the character property, but also
24073 `visible-mode'."
24074 ;; Early versions of noutline don't have `outline-invisible-p'.
24075 (unless (bound-and-true-p visible-mode)
24076 (outline-invisible-p)))
24078 (defun org-invisible-p2 ()
24079 "Check if point is at a character currently not visible."
24080 (save-excursion
24081 (when (and (eolp) (not (bobp))) (backward-char 1))
24082 ;; Early versions of noutline don't have `outline-invisible-p'.
24083 (outline-invisible-p)))
24085 (defun org-back-to-heading (&optional invisible-ok)
24086 "Call `outline-back-to-heading', but provide a better error message."
24087 (condition-case nil
24088 (outline-back-to-heading invisible-ok)
24089 (error (error "Before first headline at position %d in buffer %s"
24090 (point) (current-buffer)))))
24092 (defun org-before-first-heading-p ()
24093 "Before first heading?"
24094 (save-excursion
24095 (end-of-line)
24096 (null (re-search-backward org-outline-regexp-bol nil t))))
24098 (defun org-at-heading-p (&optional ignored)
24099 (outline-on-heading-p t))
24101 (defun org-in-commented-heading-p (&optional no-inheritance)
24102 "Non-nil if point is under a commented heading.
24103 This function also checks ancestors of the current headline,
24104 unless optional argument NO-INHERITANCE is non-nil."
24105 (cond
24106 ((org-before-first-heading-p) nil)
24107 ((let ((headline (nth 4 (org-heading-components))))
24108 (and headline
24109 (let ((case-fold-search nil))
24110 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24111 headline)))))
24112 (no-inheritance nil)
24114 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24116 (defun org-at-comment-p nil
24117 "Is cursor in a commented line?"
24118 (save-excursion
24119 (save-match-data
24120 (beginning-of-line)
24121 (looking-at "^[ \t]*# "))))
24123 (defun org-at-drawer-p nil
24124 "Is cursor at a drawer keyword?"
24125 (save-excursion
24126 (move-beginning-of-line 1)
24127 (looking-at org-drawer-regexp)))
24129 (defun org-at-block-p nil
24130 "Is cursor at a block keyword?"
24131 (save-excursion
24132 (move-beginning-of-line 1)
24133 (looking-at org-block-regexp)))
24135 (defun org-point-at-end-of-empty-headline ()
24136 "If point is at the end of an empty headline, return t, else nil.
24137 If the heading only contains a TODO keyword, it is still still considered
24138 empty."
24139 (and (looking-at "[ \t]*$")
24140 (when org-todo-line-regexp
24141 (save-excursion
24142 (beginning-of-line 1)
24143 (let ((case-fold-search nil))
24144 (looking-at org-todo-line-regexp)
24145 (string= (match-string 3) ""))))))
24147 (defun org-at-heading-or-item-p ()
24148 (or (org-at-heading-p) (org-at-item-p)))
24150 (defun org-at-target-p ()
24151 (or (org-in-regexp org-radio-target-regexp)
24152 (org-in-regexp org-target-regexp)))
24153 ;; Compatibility alias with Org versions < 7.8.03
24154 (defalias 'org-on-target-p 'org-at-target-p)
24156 (defun org-up-heading-all (arg)
24157 "Move to the heading line of which the present line is a subheading.
24158 This function considers both visible and invisible heading lines.
24159 With argument, move up ARG levels."
24160 (outline-up-heading arg t))
24162 (defun org-up-heading-safe ()
24163 "Move to the heading line of which the present line is a subheading.
24164 This version will not throw an error. It will return the level of the
24165 headline found, or nil if no higher level is found.
24167 Also, this function will be a lot faster than `outline-up-heading',
24168 because it relies on stars being the outline starters. This can really
24169 make a significant difference in outlines with very many siblings."
24170 (when (ignore-errors (org-back-to-heading t))
24171 (let ((level-up (1- (funcall outline-level))))
24172 (and (> level-up 0)
24173 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24174 (funcall outline-level)))))
24176 (defun org-first-sibling-p ()
24177 "Is this heading the first child of its parents?"
24178 (interactive)
24179 (let ((re org-outline-regexp-bol)
24180 level l)
24181 (unless (org-at-heading-p t)
24182 (user-error "Not at a heading"))
24183 (setq level (funcall outline-level))
24184 (save-excursion
24185 (if (not (re-search-backward re nil t))
24187 (setq l (funcall outline-level))
24188 (< l level)))))
24190 (defun org-goto-sibling (&optional previous)
24191 "Goto the next sibling, even if it is invisible.
24192 When PREVIOUS is set, go to the previous sibling instead. Returns t
24193 when a sibling was found. When none is found, return nil and don't
24194 move point."
24195 (let ((fun (if previous 're-search-backward 're-search-forward))
24196 (pos (point))
24197 (re org-outline-regexp-bol)
24198 level l)
24199 (when (ignore-errors (org-back-to-heading t))
24200 (setq level (funcall outline-level))
24201 (catch 'exit
24202 (or previous (forward-char 1))
24203 (while (funcall fun re nil t)
24204 (setq l (funcall outline-level))
24205 (when (< l level) (goto-char pos) (throw 'exit nil))
24206 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24207 (goto-char pos)
24208 nil))))
24210 (defun org-show-siblings ()
24211 "Show all siblings of the current headline."
24212 (save-excursion
24213 (while (org-goto-sibling) (org-flag-heading nil)))
24214 (save-excursion
24215 (while (org-goto-sibling 'previous)
24216 (org-flag-heading nil))))
24218 (defun org-goto-first-child ()
24219 "Goto the first child, even if it is invisible.
24220 Return t when a child was found. Otherwise don't move point and
24221 return nil."
24222 (let (level (pos (point)) (re org-outline-regexp-bol))
24223 (when (ignore-errors (org-back-to-heading t))
24224 (setq level (outline-level))
24225 (forward-char 1)
24226 (if (and (re-search-forward re nil t) (> (outline-level) level))
24227 (progn (goto-char (match-beginning 0)) t)
24228 (goto-char pos) nil))))
24230 (defun org-show-hidden-entry ()
24231 "Show an entry where even the heading is hidden."
24232 (save-excursion
24233 (org-show-entry)))
24235 (defun org-flag-heading (flag &optional entry)
24236 "Flag the current heading. FLAG non-nil means make invisible.
24237 When ENTRY is non-nil, show the entire entry."
24238 (save-excursion
24239 (org-back-to-heading t)
24240 ;; Check if we should show the entire entry
24241 (if entry
24242 (progn
24243 (org-show-entry)
24244 (save-excursion
24245 (and (outline-next-heading)
24246 (org-flag-heading nil))))
24247 (outline-flag-region (max (point-min) (1- (point)))
24248 (save-excursion (outline-end-of-heading) (point))
24249 flag))))
24251 (defun org-get-next-sibling ()
24252 "Move to next heading of the same level, and return point.
24253 If there is no such heading, return nil.
24254 This is like outline-next-sibling, but invisible headings are ok."
24255 (let ((level (funcall outline-level)))
24256 (outline-next-heading)
24257 (while (and (not (eobp)) (> (funcall outline-level) level))
24258 (outline-next-heading))
24259 (unless (or (eobp) (< (funcall outline-level) level))
24260 (point))))
24262 (defun org-get-last-sibling ()
24263 "Move to previous heading of the same level, and return point.
24264 If there is no such heading, return nil."
24265 (let ((opoint (point))
24266 (level (funcall outline-level)))
24267 (outline-previous-heading)
24268 (when (and (/= (point) opoint) (outline-on-heading-p t))
24269 (while (and (> (funcall outline-level) level)
24270 (not (bobp)))
24271 (outline-previous-heading))
24272 (unless (< (funcall outline-level) level)
24273 (point)))))
24275 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24276 "Goto to the end of a subtree."
24277 ;; This contains an exact copy of the original function, but it uses
24278 ;; `org-back-to-heading', to make it work also in invisible
24279 ;; trees. And is uses an invisible-ok argument.
24280 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24281 ;; Furthermore, when used inside Org, finding the end of a large subtree
24282 ;; with many children and grandchildren etc, this can be much faster
24283 ;; than the outline version.
24284 (org-back-to-heading invisible-ok)
24285 (let ((first t)
24286 (level (funcall outline-level)))
24287 (if (and (derived-mode-p 'org-mode) (< level 1000))
24288 ;; A true heading (not a plain list item), in Org
24289 ;; This means we can easily find the end by looking
24290 ;; only for the right number of stars. Using a regexp to do
24291 ;; this is so much faster than using a Lisp loop.
24292 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24293 (forward-char 1)
24294 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24295 ;; something else, do it the slow way
24296 (while (and (not (eobp))
24297 (or first (> (funcall outline-level) level)))
24298 (setq first nil)
24299 (outline-next-heading)))
24300 (unless to-heading
24301 (when (memq (preceding-char) '(?\n ?\^M))
24302 ;; Go to end of line before heading
24303 (forward-char -1)
24304 (when (memq (preceding-char) '(?\n ?\^M))
24305 ;; leave blank line before heading
24306 (forward-char -1)))))
24307 (point))
24309 (defun org-end-of-meta-data (&optional full)
24310 "Skip planning line and properties drawer in current entry.
24311 When optional argument FULL is non-nil, also skip empty lines,
24312 clocking lines and regular drawers at the beginning of the
24313 entry."
24314 (org-back-to-heading t)
24315 (forward-line)
24316 (when (looking-at-p org-planning-line-re) (forward-line))
24317 (when (looking-at org-property-drawer-re)
24318 (goto-char (match-end 0))
24319 (forward-line))
24320 (when (and full (not (org-at-heading-p)))
24321 (catch 'exit
24322 (let ((end (save-excursion (outline-next-heading) (point)))
24323 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24324 (while (not (eobp))
24325 (cond ((looking-at-p org-drawer-regexp)
24326 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24327 (forward-line)
24328 (throw 'exit t)))
24329 ((looking-at-p re) (forward-line))
24330 (t (throw 'exit t))))))))
24332 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24333 "Move forward to the ARG'th subheading at same level as this one.
24334 Stop at the first and last subheadings of a superior heading.
24335 Normally this only looks at visible headings, but when INVISIBLE-OK is
24336 non-nil it will also look at invisible ones."
24337 (interactive "p")
24338 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24339 (if (and arg (< arg 0))
24340 (goto-char (point-min))
24341 (outline-next-heading))
24342 (org-at-heading-p)
24343 (let ((level (- (match-end 0) (match-beginning 0) 1))
24344 (f (if (and arg (< arg 0))
24345 're-search-backward
24346 're-search-forward))
24347 (count (if arg (abs arg) 1))
24348 (result (point)))
24349 (while (and (prog1 (> count 0)
24350 (forward-char (if (and arg (< arg 0)) -1 1)))
24351 (funcall f org-outline-regexp-bol nil 'move))
24352 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24353 (cond ((< l level) (setq count 0))
24354 ((and (= l level)
24355 (or invisible-ok
24356 (progn
24357 (goto-char (line-beginning-position))
24358 (not (outline-invisible-p)))))
24359 (setq count (1- count))
24360 (when (eq l level)
24361 (setq result (point)))))))
24362 (goto-char result))
24363 (beginning-of-line 1)))
24365 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24366 "Move backward to the ARG'th subheading at same level as this one.
24367 Stop at the first and last subheadings of a superior heading."
24368 (interactive "p")
24369 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24371 (defun org-next-visible-heading (arg)
24372 "Move to the next visible heading.
24374 This function wraps `outline-next-visible-heading' with
24375 `org-with-limited-levels' in order to skip over inline tasks and
24376 respect customization of `org-odd-levels-only'."
24377 (interactive "p")
24378 (org-with-limited-levels
24379 (outline-next-visible-heading arg)))
24381 (defun org-previous-visible-heading (arg)
24382 "Move to the previous visible heading.
24384 This function wraps `outline-previous-visible-heading' with
24385 `org-with-limited-levels' in order to skip over inline tasks and
24386 respect customization of `org-odd-levels-only'."
24387 (interactive "p")
24388 (org-with-limited-levels
24389 (outline-previous-visible-heading arg)))
24391 (defun org-next-block (arg &optional backward block-regexp)
24392 "Jump to the next block.
24394 With a prefix argument ARG, jump forward ARG many blocks.
24396 When BACKWARD is non-nil, jump to the previous block.
24398 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24399 Match data is set according to this regexp when the function
24400 returns.
24402 Return point at beginning of the opening line of found block.
24403 Throw an error if no block is found."
24404 (interactive "p")
24405 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24406 (case-fold-search t)
24407 (search-fn (if backward #'re-search-backward #'re-search-forward))
24408 (count (or arg 1))
24409 (origin (point))
24410 last-element)
24411 (if backward (beginning-of-line) (end-of-line))
24412 (while (and (> count 0) (funcall search-fn re nil t))
24413 (let ((element (save-excursion
24414 (goto-char (match-beginning 0))
24415 (save-match-data (org-element-at-point)))))
24416 (when (and (memq (org-element-type element)
24417 '(center-block comment-block dynamic-block
24418 example-block export-block quote-block
24419 special-block src-block verse-block))
24420 (<= (match-beginning 0)
24421 (org-element-property :post-affiliated element)))
24422 (setq last-element element)
24423 (cl-decf count))))
24424 (if (= count 0)
24425 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24426 (save-match-data (org-show-context)))
24427 (goto-char origin)
24428 (user-error "No %s code blocks" (if backward "previous" "further")))))
24430 (defun org-previous-block (arg &optional block-regexp)
24431 "Jump to the previous block.
24432 With a prefix argument ARG, jump backward ARG many source blocks.
24433 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24434 (interactive "p")
24435 (org-next-block arg t block-regexp))
24437 (defun org-forward-paragraph ()
24438 "Move forward to beginning of next paragraph or equivalent.
24440 The function moves point to the beginning of the next visible
24441 structural element, which can be a paragraph, a table, a list
24442 item, etc. It also provides some special moves for convenience:
24444 - On an affiliated keyword, jump to the beginning of the
24445 relative element.
24446 - On an item or a footnote definition, move to the second
24447 element inside, if any.
24448 - On a table or a property drawer, jump after it.
24449 - On a verse or source block, stop after blank lines."
24450 (interactive)
24451 (when (eobp) (user-error "Cannot move further down"))
24452 (let* ((deactivate-mark nil)
24453 (element (org-element-at-point))
24454 (type (org-element-type element))
24455 (post-affiliated (org-element-property :post-affiliated element))
24456 (contents-begin (org-element-property :contents-begin element))
24457 (contents-end (org-element-property :contents-end element))
24458 (end (let ((end (org-element-property :end element)) (parent element))
24459 (while (and (setq parent (org-element-property :parent parent))
24460 (= (org-element-property :contents-end parent) end))
24461 (setq end (org-element-property :end parent)))
24462 end)))
24463 (cond ((not element)
24464 (skip-chars-forward " \r\t\n")
24465 (or (eobp) (beginning-of-line)))
24466 ;; On affiliated keywords, move to element's beginning.
24467 ((< (point) post-affiliated)
24468 (goto-char post-affiliated))
24469 ;; At a table row, move to the end of the table. Similarly,
24470 ;; at a node property, move to the end of the property
24471 ;; drawer.
24472 ((memq type '(node-property table-row))
24473 (goto-char (org-element-property
24474 :end (org-element-property :parent element))))
24475 ((memq type '(property-drawer table)) (goto-char end))
24476 ;; Consider blank lines as separators in verse and source
24477 ;; blocks to ease editing.
24478 ((memq type '(src-block verse-block))
24479 (when (eq type 'src-block)
24480 (setq contents-end
24481 (save-excursion (goto-char end)
24482 (skip-chars-backward " \r\t\n")
24483 (line-beginning-position))))
24484 (beginning-of-line)
24485 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24486 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24487 (goto-char end)
24488 (skip-chars-forward " \r\t\n")
24489 (if (= (point) contents-end) (goto-char end)
24490 (beginning-of-line))))
24491 ;; With no contents, just skip element.
24492 ((not contents-begin) (goto-char end))
24493 ;; If contents are invisible, skip the element altogether.
24494 ((outline-invisible-p (line-end-position))
24495 (cl-case type
24496 (headline
24497 (org-with-limited-levels (outline-next-visible-heading 1)))
24498 ;; At a plain list, make sure we move to the next item
24499 ;; instead of skipping the whole list.
24500 (plain-list (forward-char)
24501 (org-forward-paragraph))
24502 (otherwise (goto-char end))))
24503 ((>= (point) contents-end) (goto-char end))
24504 ((>= (point) contents-begin)
24505 ;; This can only happen on paragraphs and plain lists.
24506 (cl-case type
24507 (paragraph (goto-char end))
24508 ;; At a plain list, try to move to second element in
24509 ;; first item, if possible.
24510 (plain-list (end-of-line)
24511 (org-forward-paragraph))))
24512 ;; When contents start on the middle of a line (e.g. in
24513 ;; items and footnote definitions), try to reach first
24514 ;; element starting after current line.
24515 ((> (line-end-position) contents-begin)
24516 (end-of-line)
24517 (org-forward-paragraph))
24518 (t (goto-char contents-begin)))))
24520 (defun org-backward-paragraph ()
24521 "Move backward to start of previous paragraph or equivalent.
24523 The function moves point to the beginning of the current
24524 structural element, which can be a paragraph, a table, a list
24525 item, etc., or to the beginning of the previous visible one if
24526 point is already there. It also provides some special moves for
24527 convenience:
24529 - On an affiliated keyword, jump to the first one.
24530 - On a table or a property drawer, move to its beginning.
24531 - On a verse or source block, stop before blank lines."
24532 (interactive)
24533 (when (bobp) (user-error "Cannot move further up"))
24534 (let* ((deactivate-mark nil)
24535 (element (org-element-at-point))
24536 (type (org-element-type element))
24537 (contents-begin (org-element-property :contents-begin element))
24538 (contents-end (org-element-property :contents-end element))
24539 (post-affiliated (org-element-property :post-affiliated element))
24540 (begin (org-element-property :begin element)))
24541 (cond
24542 ((not element) (goto-char (point-min)))
24543 ((= (point) begin)
24544 (backward-char)
24545 (org-backward-paragraph))
24546 ((<= (point) post-affiliated) (goto-char begin))
24547 ((memq type '(node-property table-row))
24548 (goto-char (org-element-property
24549 :post-affiliated (org-element-property :parent element))))
24550 ((memq type '(property-drawer table)) (goto-char begin))
24551 ((memq type '(src-block verse-block))
24552 (when (eq type 'src-block)
24553 (setq contents-begin
24554 (save-excursion (goto-char begin) (forward-line) (point))))
24555 (if (= (point) contents-begin) (goto-char post-affiliated)
24556 ;; Inside a verse block, see blank lines as paragraph
24557 ;; separators.
24558 (let ((origin (point)))
24559 (skip-chars-backward " \r\t\n" contents-begin)
24560 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24561 (skip-chars-forward " \r\t\n" origin)
24562 (if (= (point) origin) (goto-char contents-begin)
24563 (beginning-of-line))))))
24564 ((not contents-begin) (goto-char (or post-affiliated begin)))
24565 ((eq type 'paragraph)
24566 (goto-char contents-begin)
24567 ;; When at first paragraph in an item or a footnote definition,
24568 ;; move directly to beginning of line.
24569 (let ((parent-contents
24570 (org-element-property
24571 :contents-begin (org-element-property :parent element))))
24572 (when (and parent-contents (= parent-contents contents-begin))
24573 (beginning-of-line))))
24574 ;; At the end of a greater element, move to the beginning of the
24575 ;; last element within.
24576 ((>= (point) contents-end)
24577 (goto-char (1- contents-end))
24578 (org-backward-paragraph))
24579 (t (goto-char (or post-affiliated begin))))
24580 ;; Ensure we never leave point invisible.
24581 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24583 (defun org-forward-element ()
24584 "Move forward by one element.
24585 Move to the next element at the same level, when possible."
24586 (interactive)
24587 (cond ((eobp) (user-error "Cannot move further down"))
24588 ((org-with-limited-levels (org-at-heading-p))
24589 (let ((origin (point)))
24590 (goto-char (org-end-of-subtree nil t))
24591 (unless (org-with-limited-levels (org-at-heading-p))
24592 (goto-char origin)
24593 (user-error "Cannot move further down"))))
24595 (let* ((elem (org-element-at-point))
24596 (end (org-element-property :end elem))
24597 (parent (org-element-property :parent elem)))
24598 (cond ((and parent (= (org-element-property :contents-end parent) end))
24599 (goto-char (org-element-property :end parent)))
24600 ((integer-or-marker-p end) (goto-char end))
24601 (t (message "No element at point")))))))
24603 (defun org-backward-element ()
24604 "Move backward by one element.
24605 Move to the previous element at the same level, when possible."
24606 (interactive)
24607 (cond ((bobp) (user-error "Cannot move further up"))
24608 ((org-with-limited-levels (org-at-heading-p))
24609 ;; At a headline, move to the previous one, if any, or stay
24610 ;; here.
24611 (let ((origin (point)))
24612 (org-with-limited-levels (org-backward-heading-same-level 1))
24613 ;; When current headline has no sibling above, move to its
24614 ;; parent.
24615 (when (= (point) origin)
24616 (or (org-with-limited-levels (org-up-heading-safe))
24617 (progn (goto-char origin)
24618 (user-error "Cannot move further up"))))))
24620 (let* ((elem (org-element-at-point))
24621 (beg (org-element-property :begin elem)))
24622 (cond
24623 ;; Move to beginning of current element if point isn't
24624 ;; there already.
24625 ((null beg) (message "No element at point"))
24626 ((/= (point) beg) (goto-char beg))
24627 (t (goto-char beg)
24628 (skip-chars-backward " \r\t\n")
24629 (unless (bobp)
24630 (let ((prev (org-element-at-point)))
24631 (goto-char (org-element-property :begin prev))
24632 (while (and (setq prev (org-element-property :parent prev))
24633 (<= (org-element-property :end prev) beg))
24634 (goto-char (org-element-property :begin prev)))))))))))
24636 (defun org-up-element ()
24637 "Move to upper element."
24638 (interactive)
24639 (if (org-with-limited-levels (org-at-heading-p))
24640 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24641 (let* ((elem (org-element-at-point))
24642 (parent (org-element-property :parent elem)))
24643 (if parent (goto-char (org-element-property :begin parent))
24644 (if (org-with-limited-levels (org-before-first-heading-p))
24645 (user-error "No surrounding element")
24646 (org-with-limited-levels (org-back-to-heading)))))))
24648 (defvar org-element-greater-elements)
24649 (defun org-down-element ()
24650 "Move to inner element."
24651 (interactive)
24652 (let ((element (org-element-at-point)))
24653 (cond
24654 ((memq (org-element-type element) '(plain-list table))
24655 (goto-char (org-element-property :contents-begin element))
24656 (forward-char))
24657 ((memq (org-element-type element) org-element-greater-elements)
24658 ;; If contents are hidden, first disclose them.
24659 (when (outline-invisible-p (line-end-position)) (org-cycle))
24660 (goto-char (or (org-element-property :contents-begin element)
24661 (user-error "No content for this element"))))
24662 (t (user-error "No inner element")))))
24664 (defun org-drag-element-backward ()
24665 "Move backward element at point."
24666 (interactive)
24667 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24668 (let* ((elem (org-element-at-point))
24669 (prev-elem
24670 (save-excursion
24671 (goto-char (org-element-property :begin elem))
24672 (skip-chars-backward " \r\t\n")
24673 (unless (bobp)
24674 (let* ((beg (org-element-property :begin elem))
24675 (prev (org-element-at-point))
24676 (up prev))
24677 (while (and (setq up (org-element-property :parent up))
24678 (<= (org-element-property :end up) beg))
24679 (setq prev up))
24680 prev)))))
24681 ;; Error out if no previous element or previous element is
24682 ;; a parent of the current one.
24683 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24684 (user-error "Cannot drag element backward")
24685 (let ((pos (point)))
24686 (org-element-swap-A-B prev-elem elem)
24687 (goto-char (+ (org-element-property :begin prev-elem)
24688 (- pos (org-element-property :begin elem)))))))))
24690 (defun org-drag-element-forward ()
24691 "Move forward element at point."
24692 (interactive)
24693 (let* ((pos (point))
24694 (elem (org-element-at-point)))
24695 (when (= (point-max) (org-element-property :end elem))
24696 (user-error "Cannot drag element forward"))
24697 (goto-char (org-element-property :end elem))
24698 (let ((next-elem (org-element-at-point)))
24699 (when (or (org-element-nested-p elem next-elem)
24700 (and (eq (org-element-type next-elem) 'headline)
24701 (not (eq (org-element-type elem) 'headline))))
24702 (goto-char pos)
24703 (user-error "Cannot drag element forward"))
24704 ;; Compute new position of point: it's shifted by NEXT-ELEM
24705 ;; body's length (without final blanks) and by the length of
24706 ;; blanks between ELEM and NEXT-ELEM.
24707 (let ((size-next (- (save-excursion
24708 (goto-char (org-element-property :end next-elem))
24709 (skip-chars-backward " \r\t\n")
24710 (forward-line)
24711 ;; Small correction if buffer doesn't end
24712 ;; with a newline character.
24713 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24714 (org-element-property :begin next-elem)))
24715 (size-blank (- (org-element-property :end elem)
24716 (save-excursion
24717 (goto-char (org-element-property :end elem))
24718 (skip-chars-backward " \r\t\n")
24719 (forward-line)
24720 (point)))))
24721 (org-element-swap-A-B elem next-elem)
24722 (goto-char (+ pos size-next size-blank))))))
24724 (defun org-drag-line-forward (arg)
24725 "Drag the line at point ARG lines forward."
24726 (interactive "p")
24727 (dotimes (_ (abs arg))
24728 (let ((c (current-column)))
24729 (if (< 0 arg)
24730 (progn
24731 (beginning-of-line 2)
24732 (transpose-lines 1)
24733 (beginning-of-line 0))
24734 (transpose-lines 1)
24735 (beginning-of-line -1))
24736 (org-move-to-column c))))
24738 (defun org-drag-line-backward (arg)
24739 "Drag the line at point ARG lines backward."
24740 (interactive "p")
24741 (org-drag-line-forward (- arg)))
24743 (defun org-mark-element ()
24744 "Put point at beginning of this element, mark at end.
24746 Interactively, if this command is repeated or (in Transient Mark
24747 mode) if the mark is active, it marks the next element after the
24748 ones already marked."
24749 (interactive)
24750 (let (deactivate-mark)
24751 (if (and (called-interactively-p 'any)
24752 (or (and (eq last-command this-command) (mark t))
24753 (and transient-mark-mode mark-active)))
24754 (set-mark
24755 (save-excursion
24756 (goto-char (mark))
24757 (goto-char (org-element-property :end (org-element-at-point)))))
24758 (let ((element (org-element-at-point)))
24759 (end-of-line)
24760 (push-mark (org-element-property :end element) t t)
24761 (goto-char (org-element-property :begin element))))))
24763 (defun org-narrow-to-element ()
24764 "Narrow buffer to current element."
24765 (interactive)
24766 (let ((elem (org-element-at-point)))
24767 (cond
24768 ((eq (car elem) 'headline)
24769 (narrow-to-region
24770 (org-element-property :begin elem)
24771 (org-element-property :end elem)))
24772 ((memq (car elem) org-element-greater-elements)
24773 (narrow-to-region
24774 (org-element-property :contents-begin elem)
24775 (org-element-property :contents-end elem)))
24777 (narrow-to-region
24778 (org-element-property :begin elem)
24779 (org-element-property :end elem))))))
24781 (defun org-transpose-element ()
24782 "Transpose current and previous elements, keeping blank lines between.
24783 Point is moved after both elements."
24784 (interactive)
24785 (org-skip-whitespace)
24786 (let ((end (org-element-property :end (org-element-at-point))))
24787 (org-drag-element-backward)
24788 (goto-char end)))
24790 (defun org-unindent-buffer ()
24791 "Un-indent the visible part of the buffer.
24792 Relative indentation (between items, inside blocks, etc.) isn't
24793 modified."
24794 (interactive)
24795 (unless (eq major-mode 'org-mode)
24796 (user-error "Cannot un-indent a buffer not in Org mode"))
24797 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24798 (unindent-tree
24799 (lambda (contents)
24800 (dolist (element (reverse contents))
24801 (if (memq (org-element-type element) '(headline section))
24802 (funcall unindent-tree (org-element-contents element))
24803 (save-excursion
24804 (save-restriction
24805 (narrow-to-region
24806 (org-element-property :begin element)
24807 (org-element-property :end element))
24808 (org-do-remove-indentation))))))))
24809 (funcall unindent-tree (org-element-contents parse-tree))))
24811 (defun org-show-children (&optional level)
24812 "Show all direct subheadings of this heading.
24813 Prefix arg LEVEL is how many levels below the current level
24814 should be shown. Default is enough to cause the following
24815 heading to appear."
24816 (interactive "p")
24817 ;; If `orgstruct-mode' is active, use the slower version.
24818 (if orgstruct-mode (call-interactively #'outline-show-children)
24819 (save-excursion
24820 (org-back-to-heading t)
24821 (let* ((current-level (funcall outline-level))
24822 (max-level (org-get-valid-level
24823 current-level
24824 (if level (prefix-numeric-value level) 1)))
24825 (end (save-excursion (org-end-of-subtree t t)))
24826 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24827 (past-first-child nil)
24828 ;; Make sure to skip inlinetasks.
24829 (re (format regexp-fmt
24830 current-level
24831 (cond
24832 ((not (featurep 'org-inlinetask)) "")
24833 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24835 (t (1- org-inlinetask-min-level))))))
24836 ;; Display parent heading.
24837 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24838 (forward-line)
24839 ;; Display children. First child may be deeper than expected
24840 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24841 ;; MAX-LEVEL accordingly.
24842 (while (re-search-forward re end t)
24843 (unless past-first-child
24844 (setq re (format regexp-fmt
24845 current-level
24846 (max (funcall outline-level) max-level)))
24847 (setq past-first-child t))
24848 (outline-flag-region
24849 (line-end-position 0) (line-end-position) nil))))))
24851 (defun org-show-subtree ()
24852 "Show everything after this heading at deeper levels."
24853 (interactive)
24854 (outline-flag-region
24855 (point)
24856 (save-excursion
24857 (org-end-of-subtree t t))
24858 nil))
24860 (defun org-show-entry ()
24861 "Show the body directly following this heading.
24862 Show the heading too, if it is currently invisible."
24863 (interactive)
24864 (save-excursion
24865 (ignore-errors
24866 (org-back-to-heading t)
24867 (outline-flag-region
24868 (max (point-min) (1- (point)))
24869 (save-excursion
24870 (if (re-search-forward
24871 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24872 (match-beginning 1)
24873 (point-max)))
24874 nil)
24875 (org-cycle-hide-drawers 'children))))
24877 (defun org-make-options-regexp (kwds &optional extra)
24878 "Make a regular expression for keyword lines.
24879 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24880 when non-nil, is a regexp matching keywords names."
24881 (concat "^[ \t]*#\\+\\("
24882 (regexp-opt kwds)
24883 (and extra (concat (and kwds "\\|") extra))
24884 "\\):[ \t]*\\(.*\\)"))
24886 ;;;; Integration with and fixes for other packages
24888 ;;; Imenu support
24890 (defvar-local org-imenu-markers nil
24891 "All markers currently used by Imenu.")
24893 (defun org-imenu-new-marker (&optional pos)
24894 "Return a new marker for use by Imenu, and remember the marker."
24895 (let ((m (make-marker)))
24896 (move-marker m (or pos (point)))
24897 (push m org-imenu-markers)
24900 (defun org-imenu-get-tree ()
24901 "Produce the index for Imenu."
24902 (dolist (x org-imenu-markers) (move-marker x nil))
24903 (setq org-imenu-markers nil)
24904 (let* ((case-fold-search nil)
24905 (n org-imenu-depth)
24906 (re (concat "^" (org-get-limited-outline-regexp)))
24907 (subs (make-vector (1+ n) nil))
24908 (last-level 0)
24909 m level head0 head)
24910 (org-with-wide-buffer
24911 (goto-char (point-max))
24912 (while (re-search-backward re nil t)
24913 (setq level (org-reduced-level (funcall outline-level)))
24914 (when (and (<= level n)
24915 (looking-at org-complex-heading-regexp)
24916 (setq head0 (match-string-no-properties 4)))
24917 (setq head (org-link-display-format head0)
24918 m (org-imenu-new-marker))
24919 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24920 (if (>= level last-level)
24921 (push (cons head m) (aref subs level))
24922 (push (cons head (aref subs (1+ level))) (aref subs level))
24923 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24924 (setq last-level level))))
24925 (aref subs 1)))
24927 (eval-after-load "imenu"
24928 '(progn
24929 (add-hook 'imenu-after-jump-hook
24930 (lambda ()
24931 (when (derived-mode-p 'org-mode)
24932 (org-show-context 'org-goto))))))
24934 (defun org-link-display-format (s)
24935 "Replace links in string S with their description.
24936 If there is no description, use the link target."
24937 (save-match-data
24938 (replace-regexp-in-string
24939 org-bracket-link-analytic-regexp
24940 (lambda (m)
24941 (if (match-end 5) (match-string 5 m)
24942 (concat (match-string 1 m) (match-string 3 m))))
24943 s nil t)))
24945 (defun org-toggle-link-display ()
24946 "Toggle the literal or descriptive display of links."
24947 (interactive)
24948 (if org-descriptive-links
24949 (progn (org-remove-from-invisibility-spec '(org-link))
24950 (org-restart-font-lock)
24951 (setq org-descriptive-links nil))
24952 (progn (add-to-invisibility-spec '(org-link))
24953 (org-restart-font-lock)
24954 (setq org-descriptive-links t))))
24956 ;; Speedbar support
24958 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24959 "Overlay marking the agenda restriction line in speedbar.")
24960 (overlay-put org-speedbar-restriction-lock-overlay
24961 'face 'org-agenda-restriction-lock)
24962 (overlay-put org-speedbar-restriction-lock-overlay
24963 'help-echo "Agendas are currently limited to this item.")
24964 (delete-overlay org-speedbar-restriction-lock-overlay)
24966 (defun org-speedbar-set-agenda-restriction ()
24967 "Restrict future agenda commands to the location at point in speedbar.
24968 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24969 (interactive)
24970 (require 'org-agenda)
24971 (let (p m tp np dir txt)
24972 (cond
24973 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24974 'org-imenu t))
24975 (setq m (get-text-property p 'org-imenu-marker))
24976 (with-current-buffer (marker-buffer m)
24977 (goto-char m)
24978 (org-agenda-set-restriction-lock 'subtree)))
24979 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24980 'speedbar-function 'speedbar-find-file))
24981 (setq tp (previous-single-property-change
24982 (1+ p) 'speedbar-function)
24983 np (next-single-property-change
24984 tp 'speedbar-function)
24985 dir (speedbar-line-directory)
24986 txt (buffer-substring-no-properties (or tp (point-min))
24987 (or np (point-max))))
24988 (with-current-buffer (find-file-noselect
24989 (let ((default-directory dir))
24990 (expand-file-name txt)))
24991 (unless (derived-mode-p 'org-mode)
24992 (user-error "Cannot restrict to non-Org mode file"))
24993 (org-agenda-set-restriction-lock 'file)))
24994 (t (user-error "Don't know how to restrict Org mode agenda")))
24995 (move-overlay org-speedbar-restriction-lock-overlay
24996 (point-at-bol) (point-at-eol))
24997 (setq current-prefix-arg nil)
24998 (org-agenda-maybe-redo)))
25000 (defvar speedbar-file-key-map)
25001 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25002 (eval-after-load "speedbar"
25003 '(progn
25004 (speedbar-add-supported-extension ".org")
25005 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25006 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25007 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25008 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25009 (add-hook 'speedbar-visiting-tag-hook
25010 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25012 ;;; Fixes and Hacks for problems with other packages
25014 (defun org--flyspell-object-check-p (element)
25015 "Non-nil when Flyspell can check object at point.
25016 ELEMENT is the element at point."
25017 (let ((object (save-excursion
25018 (when (looking-at-p "\\>") (backward-char))
25019 (org-element-context element))))
25020 (cl-case (org-element-type object)
25021 ;; Prevent checks in links due to keybinding conflict with
25022 ;; Flyspell.
25023 ((code entity export-snippet inline-babel-call
25024 inline-src-block line-break latex-fragment link macro
25025 statistics-cookie target timestamp verbatim)
25026 nil)
25027 (footnote-reference
25028 ;; Only in inline footnotes, within the definition.
25029 (and (eq (org-element-property :type object) 'inline)
25030 (< (save-excursion
25031 (goto-char (org-element-property :begin object))
25032 (search-forward ":" nil t 2))
25033 (point))))
25034 (otherwise t))))
25036 (defun org-mode-flyspell-verify ()
25037 "Function used for `flyspell-generic-check-word-predicate'."
25038 (if (org-at-heading-p)
25039 ;; At a headline or an inlinetask, check title only. This is
25040 ;; faster than relying on `org-element-at-point'.
25041 (and (save-excursion (beginning-of-line)
25042 (and (let ((case-fold-search t))
25043 (not (looking-at-p "\\*+ END[ \t]*$")))
25044 (let ((case-fold-search nil))
25045 (looking-at org-complex-heading-regexp))))
25046 (match-beginning 4)
25047 (>= (point) (match-beginning 4))
25048 (or (not (match-beginning 5))
25049 (< (point) (match-beginning 5))))
25050 (let* ((element (org-element-at-point))
25051 (post-affiliated (org-element-property :post-affiliated element)))
25052 (cond
25053 ;; Ignore checks in all affiliated keywords but captions.
25054 ((< (point) post-affiliated)
25055 (and (save-excursion
25056 (beginning-of-line)
25057 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25058 (> (point) (match-end 0))
25059 (org--flyspell-object-check-p element)))
25060 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25061 ((let ((log (org-log-into-drawer)))
25062 (and log
25063 (let ((drawer (org-element-lineage element '(drawer))))
25064 (and drawer
25065 (eq (compare-strings
25066 log nil nil
25067 (org-element-property :drawer-name drawer) nil nil t)
25068 t)))))
25069 nil)
25071 (cl-case (org-element-type element)
25072 ((comment quote-section) t)
25073 (comment-block
25074 ;; Allow checks between block markers, not on them.
25075 (and (> (line-beginning-position) post-affiliated)
25076 (save-excursion
25077 (end-of-line)
25078 (skip-chars-forward " \r\t\n")
25079 (< (point) (org-element-property :end element)))))
25080 ;; Arbitrary list of keywords where checks are meaningful.
25081 ;; Make sure point is on the value part of the element.
25082 (keyword
25083 (and (member (org-element-property :key element)
25084 '("DESCRIPTION" "TITLE"))
25085 (save-excursion
25086 (search-backward ":" (line-beginning-position) t))))
25087 ;; Check is globally allowed in paragraphs verse blocks and
25088 ;; table rows (after affiliated keywords) but some objects
25089 ;; must not be affected.
25090 ((paragraph table-row verse-block)
25091 (let ((cbeg (org-element-property :contents-begin element))
25092 (cend (org-element-property :contents-end element)))
25093 (and cbeg (>= (point) cbeg) (< (point) cend)
25094 (org--flyspell-object-check-p element))))))))))
25095 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25097 (defun org-remove-flyspell-overlays-in (beg end)
25098 "Remove flyspell overlays in region."
25099 (and (bound-and-true-p flyspell-mode)
25100 (fboundp 'flyspell-delete-region-overlays)
25101 (flyspell-delete-region-overlays beg end)))
25103 (defvar flyspell-delayed-commands)
25104 (eval-after-load "flyspell"
25105 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25107 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25108 (eval-after-load "bookmark"
25109 '(if (boundp 'bookmark-after-jump-hook)
25110 ;; We can use the hook
25111 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25112 ;; Hook not available, use advice
25113 (defadvice bookmark-jump (after org-make-visible activate)
25114 "Make the position visible."
25115 (org-bookmark-jump-unhide))))
25117 ;; Make sure saveplace shows the location if it was hidden
25118 (eval-after-load "saveplace"
25119 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25120 "Make the position visible."
25121 (org-bookmark-jump-unhide)))
25123 ;; Make sure ecb shows the location if it was hidden
25124 (eval-after-load "ecb"
25125 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25126 "Make hierarchy visible when jumping into location from ECB tree buffer."
25127 (when (derived-mode-p 'org-mode)
25128 (org-show-context))))
25130 (defun org-bookmark-jump-unhide ()
25131 "Unhide the current position, to show the bookmark location."
25132 (and (derived-mode-p 'org-mode)
25133 (or (outline-invisible-p)
25134 (save-excursion (goto-char (max (point-min) (1- (point))))
25135 (outline-invisible-p)))
25136 (org-show-context 'bookmark-jump)))
25138 (defun org-mark-jump-unhide ()
25139 "Make the point visible with `org-show-context' after jumping to the mark."
25140 (when (and (derived-mode-p 'org-mode)
25141 (outline-invisible-p))
25142 (org-show-context 'mark-goto)))
25144 (eval-after-load "simple"
25145 '(defadvice pop-to-mark-command (after org-make-visible activate)
25146 "Make the point visible with `org-show-context'."
25147 (org-mark-jump-unhide)))
25149 (eval-after-load "simple"
25150 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25151 "Make the point visible with `org-show-context'."
25152 (org-mark-jump-unhide)))
25154 (eval-after-load "simple"
25155 '(defadvice pop-global-mark (after org-make-visible activate)
25156 "Make the point visible with `org-show-context'."
25157 (org-mark-jump-unhide)))
25159 ;; Make session.el ignore our circular variable
25160 (defvar session-globals-exclude)
25161 (eval-after-load "session"
25162 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25164 ;;;; Finish up
25166 (provide 'org)
25168 (run-hooks 'org-load-hook)
25170 ;;; org.el ends here