Avoid losing Ctrl-C keystrokes in compilation mode on MS-Windows
[emacs.git] / lisp / org / org.el
blob87758fdfdd069471101c3dd592e552d0784a400c
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the doc/ directory.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar-local org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (eq this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 (declare-function calendar-check-holidays "holidays" (date))
114 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
115 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
116 (declare-function org-add-archive-files "org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
118 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
119 (declare-function org-agenda-redo "org-agenda" (&optional all))
120 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
121 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
122 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
123 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
126 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
127 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
128 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
129 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
130 (declare-function org-clock-update-time-maybe "org-clock" ())
131 (declare-function org-clocking-buffer "org-clock" ())
132 (declare-function org-clocktable-shift "org-clock" (dir n))
133 (declare-function 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-link-parser "org-element" ())
142 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
143 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
144 (declare-function org-element-property "org-element" (property element))
145 (declare-function org-element-put-property "org-element" (element property value))
146 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
147 (declare-function org-element-type "org-element" (element))
148 (declare-function org-element-update-syntax "org-element" ())
149 (declare-function org-id-find-id-file "org-id" (id))
150 (declare-function org-id-get-create "org-id" (&optional force))
151 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
152 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
153 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
154 (declare-function org-plot/gnuplot "org-plot" (&optional params))
155 (declare-function org-table-align "org-table" ())
156 (declare-function org-table-begin "org-table" (&optional table-type))
157 (declare-function org-table-beginning-of-field "org-table" (&optional n))
158 (declare-function org-table-blank-field "org-table" ())
159 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
160 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
161 (declare-function org-table-cut-region "org-table" (beg end))
162 (declare-function org-table-edit-field "org-table" (arg))
163 (declare-function org-table-end "org-table" (&optional table-type))
164 (declare-function org-table-end-of-field "org-table" (&optional n))
165 (declare-function org-table-insert-row "org-table" (&optional arg))
166 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
167 (declare-function org-table-maybe-eval-formula "org-table" ())
168 (declare-function org-table-maybe-recalculate-line "org-table" ())
169 (declare-function org-table-next-row "org-table" ())
170 (declare-function org-table-paste-rectangle "org-table" ())
171 (declare-function org-table-recalculate "org-table" (&optional all noalign))
172 (declare-function org-table-wrap-region "org-table" (arg))
173 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
174 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
175 (declare-function orgtbl-mode "org-table" (&optional arg))
176 (declare-function org-export-get-backend "ox" (name))
177 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
178 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
180 (defsubst org-uniquify (list)
181 "Non-destructively remove duplicate elements from LIST."
182 (let ((res (copy-sequence list))) (delete-dups res)))
184 (defsubst org-get-at-bol (property)
185 "Get text property PROPERTY at the beginning of line."
186 (get-text-property (point-at-bol) property))
188 (defsubst org-trim (s &optional keep-lead)
189 "Remove whitespace at the beginning and the end of string S.
190 When optional argument KEEP-LEAD is non-nil, removing blank lines
191 at the beginning of the string does not affect leading indentation."
192 (replace-regexp-in-string
193 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
194 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
196 ;; load languages based on value of `org-babel-load-languages'
197 (defvar org-babel-load-languages)
199 ;;;###autoload
200 (defun org-babel-do-load-languages (sym value)
201 "Load the languages defined in `org-babel-load-languages'."
202 (set-default sym value)
203 (dolist (pair org-babel-load-languages)
204 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
205 (if active
206 (require (intern (concat "ob-" lang)))
207 (funcall 'fmakunbound
208 (intern (concat "org-babel-execute:" lang)))
209 (funcall 'fmakunbound
210 (intern (concat "org-babel-expand-body:" lang)))))))
212 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
213 ;;;###autoload
214 (defun org-babel-load-file (file &optional compile)
215 "Load Emacs Lisp source code blocks in the Org FILE.
216 This function exports the source code using `org-babel-tangle'
217 and then loads the resulting file using `load-file'. With prefix
218 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
219 file to byte-code before it is loaded."
220 (interactive "fFile to load: \nP")
221 (let* ((age (lambda (file)
222 (float-time
223 (time-subtract (current-time)
224 (nth 5 (or (file-attributes (file-truename file))
225 (file-attributes file)))))))
226 (base-name (file-name-sans-extension file))
227 (exported-file (concat base-name ".el")))
228 ;; tangle if the Org file is newer than the elisp file
229 (unless (and (file-exists-p exported-file)
230 (> (funcall age file) (funcall age exported-file)))
231 ;; Tangle-file traversal returns reversed list of tangled files
232 ;; and we want to evaluate the first target.
233 (setq exported-file
234 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
235 (message "%s %s"
236 (if compile
237 (progn (byte-compile-file exported-file 'load)
238 "Compiled and loaded")
239 (progn (load-file exported-file) "Loaded"))
240 exported-file)))
242 (defcustom org-babel-load-languages '((emacs-lisp . t))
243 "Languages which can be evaluated in Org buffers.
244 This list can be used to load support for any of the languages
245 below, note that each language will depend on a different set of
246 system executables and/or Emacs modes. When a language is
247 \"loaded\", then code blocks in that language can be evaluated
248 with `org-babel-execute-src-block' bound by default to C-c
249 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
250 be set to remove code block evaluation from the C-c C-c
251 keybinding. By default only Emacs Lisp (which has no
252 requirements) is loaded."
253 :group 'org-babel
254 :set 'org-babel-do-load-languages
255 :version "24.1"
256 :type '(alist :tag "Babel Languages"
257 :key-type
258 (choice
259 (const :tag "Awk" awk)
260 (const :tag "C" C)
261 (const :tag "R" R)
262 (const :tag "Asymptote" asymptote)
263 (const :tag "Calc" calc)
264 (const :tag "Clojure" clojure)
265 (const :tag "CSS" css)
266 (const :tag "Ditaa" ditaa)
267 (const :tag "Dot" dot)
268 (const :tag "Emacs Lisp" emacs-lisp)
269 (const :tag "Forth" forth)
270 (const :tag "Fortran" fortran)
271 (const :tag "Gnuplot" gnuplot)
272 (const :tag "Haskell" haskell)
273 (const :tag "IO" io)
274 (const :tag "J" J)
275 (const :tag "Java" java)
276 (const :tag "Javascript" js)
277 (const :tag "LaTeX" latex)
278 (const :tag "Ledger" ledger)
279 (const :tag "Lilypond" lilypond)
280 (const :tag "Lisp" lisp)
281 (const :tag "Makefile" makefile)
282 (const :tag "Maxima" maxima)
283 (const :tag "Matlab" matlab)
284 (const :tag "Mscgen" mscgen)
285 (const :tag "Ocaml" ocaml)
286 (const :tag "Octave" octave)
287 (const :tag "Org" org)
288 (const :tag "Perl" perl)
289 (const :tag "Pico Lisp" picolisp)
290 (const :tag "PlantUML" plantuml)
291 (const :tag "Python" python)
292 (const :tag "Ruby" ruby)
293 (const :tag "Sass" sass)
294 (const :tag "Scala" scala)
295 (const :tag "Scheme" scheme)
296 (const :tag "Screen" screen)
297 (const :tag "Shell Script" shell)
298 (const :tag "Shen" shen)
299 (const :tag "Sql" sql)
300 (const :tag "Sqlite" sqlite)
301 (const :tag "Stan" stan)
302 (const :tag "ebnf2ps" ebnf2ps))
303 :value-type (boolean :tag "Activate" :value t)))
305 ;;;; Customization variables
306 (defcustom org-clone-delete-id nil
307 "Remove ID property of clones of a subtree.
308 When non-nil, clones of a subtree don't inherit the ID property.
309 Otherwise they inherit the ID property with a new unique
310 identifier."
311 :type 'boolean
312 :version "24.1"
313 :group 'org-id)
315 ;;; Version
316 (org-check-version)
318 ;;;###autoload
319 (defun org-version (&optional here full message)
320 "Show the Org version.
321 Interactively, or when MESSAGE is non-nil, show it in echo area.
322 With prefix argument, or when HERE is non-nil, insert it at point.
323 In non-interactive uses, a reduced version string is output unless
324 FULL is given."
325 (interactive (list current-prefix-arg t (not current-prefix-arg)))
326 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
327 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
328 (load-suffixes (list ".el"))
329 (org-install-dir
330 (ignore-errors (org-find-library-dir "org-loaddefs"))))
331 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
332 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
333 (let* ((load-suffixes save-load-suffixes)
334 (release (org-release))
335 (git-version (org-git-version))
336 (version (format "Org mode version %s (%s @ %s)"
337 release
338 git-version
339 (if org-install-dir
340 (if (string= org-dir org-install-dir)
341 org-install-dir
342 (concat "mixed installation! "
343 org-install-dir
344 " and "
345 org-dir))
346 "org-loaddefs.el can not be found!")))
347 (version1 (if full version release)))
348 (when here (insert version1))
349 (when message (message "%s" version1))
350 version1)))
352 (defconst org-version (org-version))
355 ;;; Syntax Constants
357 ;;;; Block
359 (defconst org-block-regexp
360 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
361 "Regular expression for hiding blocks.")
363 (defconst org-dblock-start-re
364 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
365 "Matches the start line of a dynamic block, with parameters.")
367 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
368 "Matches the end of a dynamic block.")
370 ;;;; Clock and Planning
372 (defconst org-clock-string "CLOCK:"
373 "String used as prefix for timestamps clocking work hours on an item.")
375 (defvar org-closed-string "CLOSED:"
376 "String used as the prefix for timestamps logging closing a TODO entry.")
378 (defvar org-deadline-string "DEADLINE:"
379 "String to mark deadline entries.
380 \\<org-mode-map>
381 A deadline is this string, followed by a time stamp. It must be
382 a word, terminated by a colon. You can insert a schedule keyword
383 and a timestamp with `\\[org-deadline]'.")
385 (defvar org-scheduled-string "SCHEDULED:"
386 "String to mark scheduled TODO entries.
387 \\<org-mode-map>
388 A schedule is this string, followed by a time stamp. It must be
389 a word, terminated by a colon. You can insert a schedule keyword
390 and a timestamp with `\\[org-schedule]'.")
392 (defconst org-ds-keyword-length
393 (+ 2
394 (apply #'max
395 (mapcar #'length
396 (list org-deadline-string org-scheduled-string
397 org-clock-string org-closed-string))))
398 "Maximum length of the DEADLINE and SCHEDULED keywords.")
400 (defconst org-planning-line-re
401 (concat "^[ \t]*"
402 (regexp-opt
403 (list org-closed-string org-deadline-string org-scheduled-string)
405 "Matches a line with planning info.
406 Matched keyword is in group 1.")
408 (defconst org-clock-line-re
409 (concat "^[ \t]*" org-clock-string)
410 "Matches a line with clock info.")
412 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
413 "Matches the DEADLINE keyword.")
415 (defconst org-deadline-time-regexp
416 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
417 "Matches the DEADLINE keyword together with a time stamp.")
419 (defconst org-deadline-time-hour-regexp
420 (concat "\\<" org-deadline-string
421 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
422 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
424 (defconst org-deadline-line-regexp
425 (concat "\\<\\(" org-deadline-string "\\).*")
426 "Matches the DEADLINE keyword and the rest of the line.")
428 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
429 "Matches the SCHEDULED keyword.")
431 (defconst org-scheduled-time-regexp
432 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
433 "Matches the SCHEDULED keyword together with a time stamp.")
435 (defconst org-scheduled-time-hour-regexp
436 (concat "\\<" org-scheduled-string
437 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
438 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
440 (defconst org-closed-time-regexp
441 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
442 "Matches the CLOSED keyword together with a time stamp.")
444 (defconst org-keyword-time-regexp
445 (concat "\\<"
446 (regexp-opt
447 (list org-scheduled-string org-deadline-string org-closed-string
448 org-clock-string)
450 " *[[<]\\([^]>]+\\)[]>]")
451 "Matches any of the 4 keywords, together with the time stamp.")
453 (defconst org-keyword-time-not-clock-regexp
454 (concat
455 "\\<"
456 (regexp-opt
457 (list org-scheduled-string org-deadline-string org-closed-string) t)
458 " *[[<]\\([^]>]+\\)[]>]")
459 "Matches any of the 3 keywords, together with the time stamp.")
461 (defconst org-maybe-keyword-time-regexp
462 (concat "\\(\\<"
463 (regexp-opt
464 (list org-scheduled-string org-deadline-string org-closed-string
465 org-clock-string)
467 "\\)?"
468 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
469 "\\|"
470 "<%%([^\r\n>]*>\\)")
471 "Matches a timestamp, possibly preceded by a keyword.")
473 (defconst org-all-time-keywords
474 (mapcar (lambda (w) (substring w 0 -1))
475 (list org-scheduled-string org-deadline-string
476 org-clock-string org-closed-string))
477 "List of time keywords.")
479 ;;;; Drawer
481 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
482 "Matches first or last line of a hidden block.
483 Group 1 contains drawer's name or \"END\".")
485 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
486 "Regular expression matching the first line of a property drawer.")
488 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
489 "Regular expression matching the last line of a property drawer.")
491 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
492 "Regular expression matching the first line of a clock drawer.")
494 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
495 "Regular expression matching the last line of a clock drawer.")
497 (defconst org-property-drawer-re
498 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
499 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
500 "[ \t]*:END:[ \t]*$")
501 "Matches an entire property drawer.")
503 (defconst org-clock-drawer-re
504 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
505 org-clock-drawer-end-re "\\)\n?")
506 "Matches an entire clock drawer.")
508 ;;;; Headline
510 (defconst org-heading-keyword-regexp-format
511 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
512 "Printf format for a regexp matching a headline with some keyword.
513 This regexp will match the headline of any node which has the
514 exact keyword that is put into the format. The keyword isn't in
515 any group by default, but the stars and the body are.")
517 (defconst org-heading-keyword-maybe-regexp-format
518 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
519 "Printf format for a regexp matching a headline, possibly with some keyword.
520 This regexp can match any headline with the specified keyword, or
521 without a keyword. The keyword isn't in any group by default,
522 but the stars and the body are.")
524 (defconst org-archive-tag "ARCHIVE"
525 "The tag that marks a subtree as archived.
526 An archived subtree does not open during visibility cycling, and does
527 not contribute to the agenda listings.")
529 (defconst org-comment-string "COMMENT"
530 "Entries starting with this keyword will never be exported.
531 \\<org-mode-map>
532 An entry can be toggled between COMMENT and normal with
533 `\\[org-toggle-comment]'.")
536 ;;;; LaTeX Environments and Fragments
538 (defconst org-latex-regexps
539 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
540 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
541 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
542 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
543 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
544 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
545 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
546 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
547 "Regular expressions for matching embedded LaTeX.")
549 ;;;; Node Property
551 (defconst org-effort-property "Effort"
552 "The property that is being used to keep track of effort estimates.
553 Effort estimates given in this property need to have the format H:MM.")
555 ;;;; Table
557 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
558 "Detect an org-type or table-type table.")
560 (defconst org-table-line-regexp "^[ \t]*|"
561 "Detect an org-type table line.")
563 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
564 "Detect an org-type table line.")
566 (defconst org-table-hline-regexp "^[ \t]*|-"
567 "Detect an org-type table hline.")
569 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
570 "Detect a table-type table hline.")
572 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
573 "Detect the first line outside a table when searching from within it.
574 This works for both table types.")
576 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
577 "Detect a #+TBLFM line.")
579 ;;;; Timestamp
581 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
582 "Regular expression for fast time stamp matching.")
584 (defconst org-ts-regexp-inactive
585 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
586 "Regular expression for fast inactive time stamp matching.")
588 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
589 "Regular expression for fast time stamp matching.")
591 (defconst org-ts-regexp0
592 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
593 "Regular expression matching time strings for analysis.
594 This one does not require the space after the date, so it can be used
595 on a string that terminates immediately after the date.")
597 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
598 "Regular expression matching time strings for analysis.")
600 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
601 "Regular expression matching time stamps, with groups.")
603 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
604 "Regular expression matching time stamps (also [..]), with groups.")
606 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
607 "Regular expression matching a time stamp range.")
609 (defconst org-tr-regexp-both
610 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
611 "Regular expression matching a time stamp range.")
613 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
614 org-ts-regexp "\\)?")
615 "Regular expression matching a time stamp or time stamp range.")
617 (defconst org-tsr-regexp-both
618 (concat org-ts-regexp-both "\\(--?-?"
619 org-ts-regexp-both "\\)?")
620 "Regular expression matching a time stamp or time stamp range.
621 The time stamps may be either active or inactive.")
623 (defconst org-repeat-re
624 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
625 "Regular expression for specifying repeated events.
626 After a match, group 1 contains the repeat expression.")
628 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
629 "Formats for `format-time-string' which are used for time stamps.")
632 ;;; The custom variables
634 (defgroup org nil
635 "Outline-based notes management and organizer."
636 :tag "Org"
637 :group 'outlines
638 :group 'calendar)
640 (defcustom org-mode-hook nil
641 "Mode hook for Org mode, run after the mode was turned on."
642 :group 'org
643 :type 'hook)
645 (defcustom org-load-hook nil
646 "Hook that is run after org.el has been loaded."
647 :group 'org
648 :type 'hook)
650 (defcustom org-log-buffer-setup-hook nil
651 "Hook that is run after an Org log buffer is created."
652 :group 'org
653 :version "24.1"
654 :type 'hook)
656 (defvar org-modules) ; defined below
657 (defvar org-modules-loaded nil
658 "Have the modules been loaded already?")
660 (defun org-load-modules-maybe (&optional force)
661 "Load all extensions listed in `org-modules'."
662 (when (or force (not org-modules-loaded))
663 (dolist (ext org-modules)
664 (condition-case nil (require ext)
665 (error (message "Problems while trying to load feature `%s'" ext))))
666 (setq org-modules-loaded t)))
668 (defun org-set-modules (var value)
669 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
670 (set var value)
671 (when (featurep 'org)
672 (org-load-modules-maybe 'force)
673 (org-element-cache-reset 'all)))
675 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
676 "Modules that should always be loaded together with org.el.
678 If a description starts with <C>, the file is not part of Emacs
679 and loading it will require that you have downloaded and properly
680 installed the Org mode distribution.
682 You can also use this system to load external packages (i.e. neither Org
683 core modules, nor modules from the CONTRIB directory). Just add symbols
684 to the end of the list. If the package is called org-xyz.el, then you need
685 to add the symbol `xyz', and the package must have a call to:
687 (provide \\='org-xyz)
689 For export specific modules, see also `org-export-backends'."
690 :group 'org
691 :set 'org-set-modules
692 :version "24.4"
693 :package-version '(Org . "8.0")
694 :type
695 '(set :greedy t
696 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
697 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
698 (const :tag " crypt: Encryption of subtrees" org-crypt)
699 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
700 (const :tag " docview: Links to doc-view buffers" org-docview)
701 (const :tag " eww: Store link to url of eww" org-eww)
702 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
703 (const :tag " habit: Track your consistency with habits" org-habit)
704 (const :tag " id: Global IDs for identifying entries" org-id)
705 (const :tag " info: Links to Info nodes" org-info)
706 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
707 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
708 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
709 (const :tag " mouse: Additional mouse support" org-mouse)
710 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
711 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
712 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
714 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
715 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
716 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
717 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
718 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
719 (const :tag "C collector: Collect properties into tables" org-collector)
720 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
721 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
722 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
723 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
724 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
725 (const :tag "C eval: Include command output as text" org-eval)
726 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
727 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
728 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
729 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
730 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
731 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
732 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
733 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
734 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
735 (const :tag "C man: Support for links to manpages in Org mode" org-man)
736 (const :tag "C mew: Links to Mew folders/messages" org-mew)
737 (const :tag "C mtags: Support for muse-like tags" org-mtags)
738 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
739 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
740 (const :tag "C registry: A registry for Org links" org-registry)
741 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
742 (const :tag "C secretary: Team management with org-mode" org-secretary)
743 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
744 (const :tag "C toc: Table of contents for Org buffer" org-toc)
745 (const :tag "C track: Keep up with Org mode development" org-track)
746 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
747 (const :tag "C vm: Links to VM folders/messages" org-vm)
748 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
749 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
750 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
752 (defvar org-export-registered-backends) ; From ox.el.
753 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
754 (declare-function org-export-backend-name "ox" (backend) t)
755 (defcustom org-export-backends '(ascii html icalendar latex odt)
756 "List of export back-ends that should be always available.
758 If a description starts with <C>, the file is not part of Emacs
759 and loading it will require that you have downloaded and properly
760 installed the Org mode distribution.
762 Unlike to `org-modules', libraries in this list will not be
763 loaded along with Org, but only once the export framework is
764 needed.
766 This variable needs to be set before org.el is loaded. If you
767 need to make a change while Emacs is running, use the customize
768 interface or run the following code, where VAL stands for the new
769 value of the variable, after updating it:
771 (progn
772 (setq org-export-registered-backends
773 (cl-remove-if-not
774 (lambda (backend)
775 (let ((name (org-export-backend-name backend)))
776 (or (memq name val)
777 (catch \\='parentp
778 (dolist (b val)
779 (and (org-export-derived-backend-p b name)
780 (throw \\='parentp t)))))))
781 org-export-registered-backends))
782 (let ((new-list (mapcar #\\='org-export-backend-name
783 org-export-registered-backends)))
784 (dolist (backend val)
785 (cond
786 ((not (load (format \"ox-%s\" backend) t t))
787 (message \"Problems while trying to load export back-end \\=`%s\\='\"
788 backend))
789 ((not (memq backend new-list)) (push backend new-list))))
790 (set-default \\='org-export-backends new-list)))
792 Adding a back-end to this list will also pull the back-end it
793 depends on, if any."
794 :group 'org
795 :group 'org-export
796 :version "26.1"
797 :package-version '(Org . "9.0")
798 :initialize 'custom-initialize-set
799 :set (lambda (var val)
800 (if (not (featurep 'ox)) (set-default var val)
801 ;; Any back-end not required anymore (not present in VAL and not
802 ;; a parent of any back-end in the new value) is removed from the
803 ;; list of registered back-ends.
804 (setq org-export-registered-backends
805 (cl-remove-if-not
806 (lambda (backend)
807 (let ((name (org-export-backend-name backend)))
808 (or (memq name val)
809 (catch 'parentp
810 (dolist (b val)
811 (and (org-export-derived-backend-p b name)
812 (throw 'parentp t)))))))
813 org-export-registered-backends))
814 ;; Now build NEW-LIST of both new back-ends and required
815 ;; parents.
816 (let ((new-list (mapcar #'org-export-backend-name
817 org-export-registered-backends)))
818 (dolist (backend val)
819 (cond
820 ((not (load (format "ox-%s" backend) t t))
821 (message "Problems while trying to load export back-end `%s'"
822 backend))
823 ((not (memq backend new-list)) (push backend new-list))))
824 ;; Set VAR to that list with fixed dependencies.
825 (set-default var new-list))))
826 :type '(set :greedy t
827 (const :tag " ascii Export buffer to ASCII format" ascii)
828 (const :tag " beamer Export buffer to Beamer presentation" beamer)
829 (const :tag " html Export buffer to HTML format" html)
830 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
831 (const :tag " latex Export buffer to LaTeX format" latex)
832 (const :tag " man Export buffer to MAN format" man)
833 (const :tag " md Export buffer to Markdown format" md)
834 (const :tag " odt Export buffer to ODT format" odt)
835 (const :tag " org Export buffer to Org format" org)
836 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
837 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
838 (const :tag "C deck Export buffer to deck.js presentations" deck)
839 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
840 (const :tag "C groff Export buffer to Groff format" groff)
841 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
842 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
843 (const :tag "C s5 Export buffer to s5 presentations" s5)
844 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
846 (eval-after-load 'ox
847 '(dolist (backend org-export-backends)
848 (condition-case nil (require (intern (format "ox-%s" backend)))
849 (error (message "Problems while trying to load export back-end `%s'"
850 backend)))))
852 (defcustom org-support-shift-select nil
853 "Non-nil means make shift-cursor commands select text when possible.
854 \\<org-mode-map>\
856 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
857 start selecting a region, or enlarge regions started in this way.
858 In Org mode, in special contexts, these same keys are used for
859 other purposes, important enough to compete with shift selection.
860 Org tries to balance these needs by supporting `shift-select-mode'
861 outside these special contexts, under control of this variable.
863 The default of this variable is nil, to avoid confusing behavior. Shifted
864 cursor keys will then execute Org commands in the following contexts:
865 - on a headline, changing TODO state (left/right) and priority (up/down)
866 - on a time stamp, changing the time
867 - in a plain list item, changing the bullet type
868 - in a property definition line, switching between allowed values
869 - in the BEGIN line of a clock table (changing the time block).
870 Outside these contexts, the commands will throw an error.
872 When this variable is t and the cursor is not in a special
873 context, Org mode will support shift-selection for making and
874 enlarging regions. To make this more effective, the bullet
875 cycling will no longer happen anywhere in an item line, but only
876 if the cursor is exactly on the bullet.
878 If you set this variable to the symbol `always', then the keys
879 will not be special in headlines, property lines, and item lines,
880 to make shift selection work there as well. If this is what you
881 want, you can use the following alternative commands:
882 `\\[org-todo]' and `\\[org-priority]' \
883 to change TODO state and priority,
884 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
885 can be used to switch TODO sets,
886 `\\[org-ctrl-c-minus]' to cycle item bullet types,
887 and properties can be edited by hand or in column view.
889 However, when the cursor is on a timestamp, shift-cursor commands
890 will still edit the time stamp - this is just too good to give up."
891 :group 'org
892 :type '(choice
893 (const :tag "Never" nil)
894 (const :tag "When outside special context" t)
895 (const :tag "Everywhere except timestamps" always)))
897 (defcustom org-loop-over-headlines-in-active-region nil
898 "Shall some commands act upon headlines in the active region?
900 When set to t, some commands will be performed in all headlines
901 within the active region.
903 When set to `start-level', some commands will be performed in all
904 headlines within the active region, provided that these headlines
905 are of the same level than the first one.
907 When set to a string, those commands will be performed on the
908 matching headlines within the active region. Such string must be
909 a tags/property/todo match as it is used in the agenda tags view.
911 The list of commands is: `org-schedule', `org-deadline',
912 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
913 `org-archive-to-archive-sibling'. The archiving commands skip
914 already archived entries."
915 :type '(choice (const :tag "Don't loop" nil)
916 (const :tag "All headlines in active region" t)
917 (const :tag "In active region, headlines at the same level than the first one" start-level)
918 (string :tag "Tags/Property/Todo matcher"))
919 :version "24.1"
920 :group 'org-todo
921 :group 'org-archive)
923 (defgroup org-startup nil
924 "Options concerning startup of Org mode."
925 :tag "Org Startup"
926 :group 'org)
928 (defcustom org-startup-folded t
929 "Non-nil means entering Org mode will switch to OVERVIEW.
931 This can also be configured on a per-file basis by adding one of
932 the following lines anywhere in the buffer:
934 #+STARTUP: fold (or `overview', this is equivalent)
935 #+STARTUP: nofold (or `showall', this is equivalent)
936 #+STARTUP: content
937 #+STARTUP: showeverything
939 Set `org-agenda-inhibit-startup' to a non-nil value if you want
940 to ignore this option when Org opens agenda files for the first
941 time."
942 :group 'org-startup
943 :type '(choice
944 (const :tag "nofold: show all" nil)
945 (const :tag "fold: overview" t)
946 (const :tag "content: all headlines" content)
947 (const :tag "show everything, even drawers" showeverything)))
949 (defcustom org-startup-truncated t
950 "Non-nil means entering Org mode will set `truncate-lines'.
951 This is useful since some lines containing links can be very long and
952 uninteresting. Also tables look terrible when wrapped.
954 The variable `org-startup-truncated' allows to configure
955 truncation for Org mode different to the other modes that use the
956 variable `truncate-lines' and as a shortcut instead of putting
957 the variable `truncate-lines' into the `org-mode-hook'. If one
958 wants to configure truncation for Org mode not statically but
959 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
960 the variable `truncate-lines' has to be used because in such a
961 case it is too late to set the variable `org-startup-truncated'."
962 :group 'org-startup
963 :type 'boolean)
965 (defcustom org-startup-indented nil
966 "Non-nil means turn on `org-indent-mode' on startup.
967 This can also be configured on a per-file basis by adding one of
968 the following lines anywhere in the buffer:
970 #+STARTUP: indent
971 #+STARTUP: noindent"
972 :group 'org-structure
973 :type '(choice
974 (const :tag "Not" nil)
975 (const :tag "Globally (slow on startup in large files)" t)))
977 (defcustom org-use-sub-superscripts t
978 "Non-nil means interpret \"_\" and \"^\" for display.
980 If you want to control how Org exports those characters, see
981 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
982 used to be an alias for `org-export-with-sub-superscripts' in
983 Org <8.0, it is not anymore.
985 When this option is turned on, you can use TeX-like syntax for
986 sub- and superscripts within the buffer. Several characters after
987 \"_\" or \"^\" will be considered as a single item - so grouping
988 with {} is normally not needed. For example, the following things
989 will be parsed as single sub- or superscripts:
991 10^24 or 10^tau several digits will be considered 1 item.
992 10^-12 or 10^-tau a leading sign with digits or a word
993 x^2-y^3 will be read as x^2 - y^3, because items are
994 terminated by almost any nonword/nondigit char.
995 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
997 Still, ambiguity is possible. So when in doubt, use {} to enclose
998 the sub/superscript. If you set this variable to the symbol `{}',
999 the braces are *required* in order to trigger interpretations as
1000 sub/superscript. This can be helpful in documents that need \"_\"
1001 frequently in plain text."
1002 :group 'org-startup
1003 :version "24.4"
1004 :package-version '(Org . "8.0")
1005 :type '(choice
1006 (const :tag "Always interpret" t)
1007 (const :tag "Only with braces" {})
1008 (const :tag "Never interpret" nil)))
1010 (defcustom org-startup-with-beamer-mode nil
1011 "Non-nil means turn on `org-beamer-mode' on startup.
1012 This can also be configured on a per-file basis by adding one of
1013 the following lines anywhere in the buffer:
1015 #+STARTUP: beamer"
1016 :group 'org-startup
1017 :version "24.1"
1018 :type 'boolean)
1020 (defcustom org-startup-align-all-tables nil
1021 "Non-nil means align all tables when visiting a file.
1022 This is useful when the column width in tables is forced with <N> cookies
1023 in table fields. Such tables will look correct only after the first re-align.
1024 This can also be configured on a per-file basis by adding one of
1025 the following lines anywhere in the buffer:
1026 #+STARTUP: align
1027 #+STARTUP: noalign"
1028 :group 'org-startup
1029 :type 'boolean)
1031 (defcustom org-startup-with-inline-images nil
1032 "Non-nil means show inline images when loading a new Org file.
1033 This can also be configured on a per-file basis by adding one of
1034 the following lines anywhere in the buffer:
1035 #+STARTUP: inlineimages
1036 #+STARTUP: noinlineimages"
1037 :group 'org-startup
1038 :version "24.1"
1039 :type 'boolean)
1041 (defcustom org-startup-with-latex-preview nil
1042 "Non-nil means preview LaTeX fragments when loading a new Org file.
1044 This can also be configured on a per-file basis by adding one of
1045 the following lines anywhere in the buffer:
1046 #+STARTUP: latexpreview
1047 #+STARTUP: nolatexpreview"
1048 :group 'org-startup
1049 :version "24.4"
1050 :package-version '(Org . "8.0")
1051 :type 'boolean)
1053 (defcustom org-insert-mode-line-in-empty-file nil
1054 "Non-nil means insert the first line setting Org mode in empty files.
1055 When the function `org-mode' is called interactively in an empty file, this
1056 normally means that the file name does not automatically trigger Org mode.
1057 To ensure that the file will always be in Org mode in the future, a
1058 line enforcing Org mode will be inserted into the buffer, if this option
1059 has been set."
1060 :group 'org-startup
1061 :type 'boolean)
1063 (defcustom org-replace-disputed-keys nil
1064 "Non-nil means use alternative key bindings for some keys.
1065 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1066 These keys are also used by other packages like shift-selection-mode'
1067 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1068 If you want to use Org mode together with one of these other modes,
1069 or more generally if you would like to move some Org mode commands to
1070 other keys, set this variable and configure the keys with the variable
1071 `org-disputed-keys'.
1073 This option is only relevant at load-time of Org mode, and must be set
1074 *before* org.el is loaded. Changing it requires a restart of Emacs to
1075 become effective."
1076 :group 'org-startup
1077 :type 'boolean)
1079 (defcustom org-use-extra-keys nil
1080 "Non-nil means use extra key sequence definitions for certain commands.
1081 This happens automatically if `window-system' is nil. This
1082 variable lets you do the same manually. You must set it before
1083 loading Org."
1084 :group 'org-startup
1085 :type 'boolean)
1087 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1089 (defcustom org-disputed-keys
1090 '(([(shift up)] . [(meta p)])
1091 ([(shift down)] . [(meta n)])
1092 ([(shift left)] . [(meta -)])
1093 ([(shift right)] . [(meta +)])
1094 ([(control shift right)] . [(meta shift +)])
1095 ([(control shift left)] . [(meta shift -)]))
1096 "Keys for which Org mode and other modes compete.
1097 This is an alist, cars are the default keys, second element specifies
1098 the alternative to use when `org-replace-disputed-keys' is t.
1100 Keys can be specified in any syntax supported by `define-key'.
1101 The value of this option takes effect only at Org mode startup,
1102 therefore you'll have to restart Emacs to apply it after changing."
1103 :group 'org-startup
1104 :type 'alist)
1106 (defun org-key (key)
1107 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1108 Or return the original if not disputed."
1109 (when org-replace-disputed-keys
1110 (let* ((nkey (key-description key))
1111 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1112 org-disputed-keys)))
1113 (setq key (if x (cdr x) key))))
1114 key)
1116 (defun org-defkey (keymap key def)
1117 "Define a key, possibly translated, as returned by `org-key'."
1118 (define-key keymap (org-key key) def))
1120 (defcustom org-ellipsis nil
1121 "The ellipsis to use in the Org mode outline.
1123 When nil, just use the standard three dots. When a non-empty string,
1124 use that string instead.
1126 The change affects only Org mode (which will then use its own display table).
1127 Changing this requires executing `\\[org-mode]' in a buffer to become
1128 effective."
1129 :group 'org-startup
1130 :type '(choice (const :tag "Default" nil)
1131 (string :tag "String" :value "...#"))
1132 :safe (lambda (v) (and (string-or-null-p v) (not (equal "" v)))))
1134 (defvar org-display-table nil
1135 "The display table for Org mode, in case `org-ellipsis' is non-nil.")
1137 (defgroup org-keywords nil
1138 "Keywords in Org mode."
1139 :tag "Org Keywords"
1140 :group 'org)
1142 (defcustom org-closed-keep-when-no-todo nil
1143 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1144 :group 'org-todo
1145 :group 'org-keywords
1146 :version "24.4"
1147 :package-version '(Org . "8.0")
1148 :type 'boolean)
1150 (defgroup org-structure nil
1151 "Options concerning the general structure of Org files."
1152 :tag "Org Structure"
1153 :group 'org)
1155 (defgroup org-reveal-location nil
1156 "Options about how to make context of a location visible."
1157 :tag "Org Reveal Location"
1158 :group 'org-structure)
1160 (defcustom org-show-context-detail '((agenda . local)
1161 (bookmark-jump . lineage)
1162 (isearch . lineage)
1163 (default . ancestors))
1164 "Alist between context and visibility span when revealing a location.
1166 \\<org-mode-map>Some actions may move point into invisible
1167 locations. As a consequence, Org always expose a neighborhood
1168 around point. How much is shown depends on the initial action,
1169 or context. Valid contexts are
1171 agenda when exposing an entry from the agenda
1172 org-goto when using the command `org-goto' (`\\[org-goto]')
1173 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1174 tags-tree when constructing a sparse tree based on tags matches
1175 link-search when exposing search matches associated with a link
1176 mark-goto when exposing the jump goal of a mark
1177 bookmark-jump when exposing a bookmark location
1178 isearch when exiting from an incremental search
1179 default default for all contexts not set explicitly
1181 Allowed visibility spans are
1183 minimal show current headline; if point is not on headline,
1184 also show entry
1186 local show current headline, entry and next headline
1188 ancestors show current headline and its direct ancestors; if
1189 point is not on headline, also show entry
1191 lineage show current headline, its direct ancestors and all
1192 their children; if point is not on headline, also show
1193 entry and first child
1195 tree show current headline, its direct ancestors and all
1196 their children; if point is not on headline, also show
1197 entry and all children
1199 canonical show current headline, its direct ancestors along with
1200 their entries and children; if point is not located on
1201 the headline, also show current entry and all children
1203 As special cases, a nil or t value means show all contexts in
1204 `minimal' or `canonical' view, respectively.
1206 Some views can make displayed information very compact, but also
1207 make it harder to edit the location of the match. In such
1208 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1209 more context."
1210 :group 'org-reveal-location
1211 :version "26.1"
1212 :package-version '(Org . "9.0")
1213 :type '(choice
1214 (const :tag "Canonical" t)
1215 (const :tag "Minimal" nil)
1216 (repeat :greedy t :tag "Individual contexts"
1217 (cons
1218 (choice :tag "Context"
1219 (const agenda)
1220 (const org-goto)
1221 (const occur-tree)
1222 (const tags-tree)
1223 (const link-search)
1224 (const mark-goto)
1225 (const bookmark-jump)
1226 (const isearch)
1227 (const default))
1228 (choice :tag "Detail level"
1229 (const minimal)
1230 (const local)
1231 (const ancestors)
1232 (const lineage)
1233 (const tree)
1234 (const canonical))))))
1236 (defcustom org-indirect-buffer-display 'other-window
1237 "How should indirect tree buffers be displayed?
1239 This applies to indirect buffers created with the commands
1240 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1242 Valid values are:
1243 current-window Display in the current window
1244 other-window Just display in another window.
1245 dedicated-frame Create one new frame, and re-use it each time.
1246 new-frame Make a new frame each time. Note that in this case
1247 previously-made indirect buffers are kept, and you need to
1248 kill these buffers yourself."
1249 :group 'org-structure
1250 :group 'org-agenda-windows
1251 :type '(choice
1252 (const :tag "In current window" current-window)
1253 (const :tag "In current frame, other window" other-window)
1254 (const :tag "Each time a new frame" new-frame)
1255 (const :tag "One dedicated frame" dedicated-frame)))
1257 (defcustom org-use-speed-commands nil
1258 "Non-nil means activate single letter commands at beginning of a headline.
1259 This may also be a function to test for appropriate locations where speed
1260 commands should be active.
1262 For example, to activate speed commands when the point is on any
1263 star at the beginning of the headline, you can do this:
1265 (setq org-use-speed-commands
1266 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1267 :group 'org-structure
1268 :type '(choice
1269 (const :tag "Never" nil)
1270 (const :tag "At beginning of headline stars" t)
1271 (function)))
1273 (defcustom org-speed-commands-user nil
1274 "Alist of additional speed commands.
1275 This list will be checked before `org-speed-commands-default'
1276 when the variable `org-use-speed-commands' is non-nil
1277 and when the cursor is at the beginning of a headline.
1278 The car if each entry is a string with a single letter, which must
1279 be assigned to `self-insert-command' in the global map.
1280 The cdr is either a command to be called interactively, a function
1281 to be called, or a form to be evaluated.
1282 An entry that is just a list with a single string will be interpreted
1283 as a descriptive headline that will be added when listing the speed
1284 commands in the Help buffer using the `?' speed command."
1285 :group 'org-structure
1286 :type '(repeat :value ("k" . ignore)
1287 (choice :value ("k" . ignore)
1288 (list :tag "Descriptive Headline" (string :tag "Headline"))
1289 (cons :tag "Letter and Command"
1290 (string :tag "Command letter")
1291 (choice
1292 (function)
1293 (sexp))))))
1295 (defcustom org-bookmark-names-plist
1296 '(:last-capture "org-capture-last-stored"
1297 :last-refile "org-refile-last-stored"
1298 :last-capture-marker "org-capture-last-stored-marker")
1299 "Names for bookmarks automatically set by some Org commands.
1300 This can provide strings as names for a number of bookmarks Org sets
1301 automatically. The following keys are currently implemented:
1302 :last-capture
1303 :last-capture-marker
1304 :last-refile
1305 When a key does not show up in the property list, the corresponding bookmark
1306 is not set."
1307 :group 'org-structure
1308 :type 'plist)
1310 (defgroup org-cycle nil
1311 "Options concerning visibility cycling in Org mode."
1312 :tag "Org Cycle"
1313 :group 'org-structure)
1315 (defcustom org-cycle-skip-children-state-if-no-children t
1316 "Non-nil means skip CHILDREN state in entries that don't have any."
1317 :group 'org-cycle
1318 :type 'boolean)
1320 (defcustom org-cycle-max-level nil
1321 "Maximum level which should still be subject to visibility cycling.
1322 Levels higher than this will, for cycling, be treated as text, not a headline.
1323 When `org-odd-levels-only' is set, a value of N in this variable actually
1324 means 2N-1 stars as the limiting headline.
1325 When nil, cycle all levels.
1326 Note that the limiting level of cycling is also influenced by
1327 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1328 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1329 than its value."
1330 :group 'org-cycle
1331 :type '(choice
1332 (const :tag "No limit" nil)
1333 (integer :tag "Maximum level")))
1335 (defcustom org-hide-block-startup nil
1336 "Non-nil means entering Org mode will fold all blocks.
1337 This can also be set in on a per-file basis with
1339 #+STARTUP: hideblocks
1340 #+STARTUP: showblocks"
1341 :group 'org-startup
1342 :group 'org-cycle
1343 :type 'boolean)
1345 (defcustom org-cycle-global-at-bob nil
1346 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1348 This makes it possible to do global cycling without having to use `S-TAB'
1349 or `\\[universal-argument] TAB'. For this special case to work, the first \
1350 line of the buffer
1351 must not be a headline -- it may be empty or some other text.
1353 When used in this way, `org-cycle-hook' is disabled temporarily to make
1354 sure the cursor stays at the beginning of the buffer.
1356 When this option is nil, don't do anything special at the beginning of
1357 the buffer."
1358 :group 'org-cycle
1359 :type 'boolean)
1361 (defcustom org-cycle-level-after-item/entry-creation t
1362 "Non-nil means cycle entry level or item indentation in new empty entries.
1364 When the cursor is at the end of an empty headline, i.e., with only stars
1365 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1366 and then all possible ancestor states, before returning to the original state.
1367 This makes data entry extremely fast: M-RET to create a new headline,
1368 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1370 When the cursor is at the end of an empty plain list item, one TAB will
1371 make it a subitem, two or more tabs will back up to make this an item
1372 higher up in the item hierarchy."
1373 :group 'org-cycle
1374 :type 'boolean)
1376 (defcustom org-cycle-emulate-tab t
1377 "Where should `org-cycle' emulate TAB.
1378 nil Never
1379 white Only in completely white lines
1380 whitestart Only at the beginning of lines, before the first non-white char
1381 t Everywhere except in headlines
1382 exc-hl-bol Everywhere except at the start of a headline
1383 If TAB is used in a place where it does not emulate TAB, the current subtree
1384 visibility is cycled."
1385 :group 'org-cycle
1386 :type '(choice (const :tag "Never" nil)
1387 (const :tag "Only in completely white lines" white)
1388 (const :tag "Before first char in a line" whitestart)
1389 (const :tag "Everywhere except in headlines" t)
1390 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1392 (defcustom org-cycle-separator-lines 2
1393 "Number of empty lines needed to keep an empty line between collapsed trees.
1394 If you leave an empty line between the end of a subtree and the following
1395 headline, this empty line is hidden when the subtree is folded.
1396 Org mode will leave (exactly) one empty line visible if the number of
1397 empty lines is equal or larger to the number given in this variable.
1398 So the default 2 means at least 2 empty lines after the end of a subtree
1399 are needed to produce free space between a collapsed subtree and the
1400 following headline.
1402 If the number is negative, and the number of empty lines is at least -N,
1403 all empty lines are shown.
1405 Special case: when 0, never leave empty lines in collapsed view."
1406 :group 'org-cycle
1407 :type 'integer)
1408 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1410 (defcustom org-pre-cycle-hook nil
1411 "Hook that is run before visibility cycling is happening.
1412 The function(s) in this hook must accept a single argument which indicates
1413 the new state that will be set right after running this hook. The
1414 argument is a symbol. Before a global state change, it can have the values
1415 `overview', `content', or `all'. Before a local state change, it can have
1416 the values `folded', `children', or `subtree'."
1417 :group 'org-cycle
1418 :type 'hook)
1420 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1421 org-cycle-hide-drawers
1422 org-cycle-show-empty-lines
1423 org-optimize-window-after-visibility-change)
1424 "Hook that is run after `org-cycle' has changed the buffer visibility.
1425 The function(s) in this hook must accept a single argument which indicates
1426 the new state that was set by the most recent `org-cycle' command. The
1427 argument is a symbol. After a global state change, it can have the values
1428 `overview', `contents', or `all'. After a local state change, it can have
1429 the values `folded', `children', or `subtree'."
1430 :group 'org-cycle
1431 :type 'hook
1432 :version "26.1"
1433 :package-version '(Org . "8.3"))
1435 (defgroup org-edit-structure nil
1436 "Options concerning structure editing in Org mode."
1437 :tag "Org Edit Structure"
1438 :group 'org-structure)
1440 (defcustom org-odd-levels-only nil
1441 "Non-nil means skip even levels and only use odd levels for the outline.
1442 This has the effect that two stars are being added/taken away in
1443 promotion/demotion commands. It also influences how levels are
1444 handled by the exporters.
1445 Changing it requires restart of `font-lock-mode' to become effective
1446 for fontification also in regions already fontified.
1447 You may also set this on a per-file basis by adding one of the following
1448 lines to the buffer:
1450 #+STARTUP: odd
1451 #+STARTUP: oddeven"
1452 :group 'org-edit-structure
1453 :group 'org-appearance
1454 :type 'boolean)
1456 (defcustom org-adapt-indentation t
1457 "Non-nil means adapt indentation to outline node level.
1459 When this variable is set, Org assumes that you write outlines by
1460 indenting text in each node to align with the headline (after the
1461 stars). The following issues are influenced by this variable:
1463 - The indentation is increased by one space in a demotion
1464 command, and decreased by one in a promotion command. However,
1465 in the latter case, if shifting some line in the entry body
1466 would alter document structure (e.g., insert a new headline),
1467 indentation is not changed at all.
1469 - Property drawers and planning information is inserted indented
1470 when this variable is set. When nil, they will not be indented.
1472 - TAB indents a line relative to current level. The lines below
1473 a headline will be indented when this variable is set.
1475 Note that this is all about true indentation, by adding and
1476 removing space characters. See also `org-indent.el' which does
1477 level-dependent indentation in a virtual way, i.e. at display
1478 time in Emacs."
1479 :group 'org-edit-structure
1480 :type 'boolean)
1482 (defcustom org-special-ctrl-a/e nil
1483 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1485 When t, `C-a' will bring back the cursor to the beginning of the
1486 headline text, i.e. after the stars and after a possible TODO
1487 keyword. In an item, this will be the position after bullet and
1488 check-box, if any. When the cursor is already at that position,
1489 another `C-a' will bring it to the beginning of the line.
1491 `C-e' will jump to the end of the headline, ignoring the presence
1492 of tags in the headline. A second `C-e' will then jump to the
1493 true end of the line, after any tags. This also means that, when
1494 this variable is non-nil, `C-e' also will never jump beyond the
1495 end of the heading of a folded section, i.e. not after the
1496 ellipses.
1498 When set to the symbol `reversed', the first `C-a' or `C-e' works
1499 normally, going to the true line boundary first. Only a directly
1500 following, identical keypress will bring the cursor to the
1501 special positions.
1503 This may also be a cons cell where the behavior for `C-a' and
1504 `C-e' is set separately."
1505 :group 'org-edit-structure
1506 :type '(choice
1507 (const :tag "off" nil)
1508 (const :tag "on: after stars/bullet and before tags first" t)
1509 (const :tag "reversed: true line boundary first" reversed)
1510 (cons :tag "Set C-a and C-e separately"
1511 (choice :tag "Special C-a"
1512 (const :tag "off" nil)
1513 (const :tag "on: after stars/bullet first" t)
1514 (const :tag "reversed: before stars/bullet first" reversed))
1515 (choice :tag "Special C-e"
1516 (const :tag "off" nil)
1517 (const :tag "on: before tags first" t)
1518 (const :tag "reversed: after tags first" reversed)))))
1519 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1521 (defcustom org-special-ctrl-k nil
1522 "Non-nil means `C-k' will behave specially in headlines.
1523 When nil, `C-k' will call the default `kill-line' command.
1524 When t, the following will happen while the cursor is in the headline:
1526 - When the cursor is at the beginning of a headline, kill the entire
1527 line and possible the folded subtree below the line.
1528 - When in the middle of the headline text, kill the headline up to the tags.
1529 - When after the headline text, kill the tags."
1530 :group 'org-edit-structure
1531 :type 'boolean)
1533 (defcustom org-ctrl-k-protect-subtree nil
1534 "Non-nil means, do not delete a hidden subtree with C-k.
1535 When set to the symbol `error', simply throw an error when C-k is
1536 used to kill (part-of) a headline that has hidden text behind it.
1537 Any other non-nil value will result in a query to the user, if it is
1538 OK to kill that hidden subtree. When nil, kill without remorse."
1539 :group 'org-edit-structure
1540 :version "24.1"
1541 :type '(choice
1542 (const :tag "Do not protect hidden subtrees" nil)
1543 (const :tag "Protect hidden subtrees with a security query" t)
1544 (const :tag "Never kill a hidden subtree with C-k" error)))
1546 (defcustom org-special-ctrl-o t
1547 "Non-nil means, make `C-o' insert a row in tables."
1548 :group 'org-edit-structure
1549 :type 'boolean)
1551 (defcustom org-catch-invisible-edits nil
1552 "Check if in invisible region before inserting or deleting a character.
1553 Valid values are:
1555 nil Do not check, so just do invisible edits.
1556 error Throw an error and do nothing.
1557 show Make point visible, and do the requested edit.
1558 show-and-error Make point visible, then throw an error and abort the edit.
1559 smart Make point visible, and do insertion/deletion if it is
1560 adjacent to visible text and the change feels predictable.
1561 Never delete a previously invisible character or add in the
1562 middle or right after an invisible region. Basically, this
1563 allows insertion and backward-delete right before ellipses.
1564 FIXME: maybe in this case we should not even show?"
1565 :group 'org-edit-structure
1566 :version "24.1"
1567 :type '(choice
1568 (const :tag "Do not check" nil)
1569 (const :tag "Throw error when trying to edit" error)
1570 (const :tag "Unhide, but do not do the edit" show-and-error)
1571 (const :tag "Show invisible part and do the edit" show)
1572 (const :tag "Be smart and do the right thing" smart)))
1574 (defcustom org-yank-folded-subtrees t
1575 "Non-nil means when yanking subtrees, fold them.
1576 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1577 it starts with a heading and all other headings in it are either children
1578 or siblings, then fold all the subtrees. However, do this only if no
1579 text after the yank would be swallowed into a folded tree by this action."
1580 :group 'org-edit-structure
1581 :type 'boolean)
1583 (defcustom org-yank-adjusted-subtrees nil
1584 "Non-nil means when yanking subtrees, adjust the level.
1585 With this setting, `org-paste-subtree' is used to insert the subtree, see
1586 this function for details."
1587 :group 'org-edit-structure
1588 :type 'boolean)
1590 (defcustom org-M-RET-may-split-line '((default . t))
1591 "Non-nil means M-RET will split the line at the cursor position.
1592 When nil, it will go to the end of the line before making a
1593 new line.
1594 You may also set this option in a different way for different
1595 contexts. Valid contexts are:
1597 headline when creating a new headline
1598 item when creating a new item
1599 table in a table field
1600 default the value to be used for all contexts not explicitly
1601 customized"
1602 :group 'org-structure
1603 :group 'org-table
1604 :type '(choice
1605 (const :tag "Always" t)
1606 (const :tag "Never" nil)
1607 (repeat :greedy t :tag "Individual contexts"
1608 (cons
1609 (choice :tag "Context"
1610 (const headline)
1611 (const item)
1612 (const table)
1613 (const default))
1614 (boolean)))))
1617 (defcustom org-insert-heading-respect-content nil
1618 "Non-nil means insert new headings after the current subtree.
1619 \\<org-mode-map>
1620 When nil, the new heading is created directly after the current line.
1621 The commands `\\[org-insert-heading-respect-content]' and \
1622 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1623 for the duration of the command."
1624 :group 'org-structure
1625 :type 'boolean)
1627 (defcustom org-blank-before-new-entry '((heading . auto)
1628 (plain-list-item . auto))
1629 "Should `org-insert-heading' leave a blank line before new heading/item?
1630 The value is an alist, with `heading' and `plain-list-item' as CAR,
1631 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1632 which case Org will look at the surrounding headings/items and try to
1633 make an intelligent decision whether to insert a blank line or not."
1634 :group 'org-edit-structure
1635 :type '(list
1636 (cons (const heading)
1637 (choice (const :tag "Never" nil)
1638 (const :tag "Always" t)
1639 (const :tag "Auto" auto)))
1640 (cons (const plain-list-item)
1641 (choice (const :tag "Never" nil)
1642 (const :tag "Always" t)
1643 (const :tag "Auto" auto)))))
1645 (defcustom org-insert-heading-hook nil
1646 "Hook being run after inserting a new heading."
1647 :group 'org-edit-structure
1648 :type 'hook)
1650 (defcustom org-enable-fixed-width-editor t
1651 "Non-nil means lines starting with \":\" are treated as fixed-width.
1652 This currently only means they are never auto-wrapped.
1653 When nil, such lines will be treated like ordinary lines."
1654 :group 'org-edit-structure
1655 :type 'boolean)
1657 (defcustom org-goto-auto-isearch t
1658 "Non-nil means typing characters in `org-goto' starts incremental search.
1659 When nil, you can use these keybindings to navigate the buffer:
1661 q Quit the org-goto interface
1662 n Go to the next visible heading
1663 p Go to the previous visible heading
1664 f Go one heading forward on same level
1665 b Go one heading backward on same level
1666 u Go one heading up"
1667 :group 'org-edit-structure
1668 :type 'boolean)
1670 (defgroup org-sparse-trees nil
1671 "Options concerning sparse trees in Org mode."
1672 :tag "Org Sparse Trees"
1673 :group 'org-structure)
1675 (defcustom org-highlight-sparse-tree-matches t
1676 "Non-nil means highlight all matches that define a sparse tree.
1677 The highlights will automatically disappear the next time the buffer is
1678 changed by an edit command."
1679 :group 'org-sparse-trees
1680 :type 'boolean)
1682 (defcustom org-remove-highlights-with-change t
1683 "Non-nil means any change to the buffer will remove temporary highlights.
1684 \\<org-mode-map>\
1685 Such highlights are created by `org-occur' and `org-clock-display'.
1686 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1687 to get rid of the highlights.
1688 The highlights created by `org-toggle-latex-fragment' always need
1689 `\\[org-toggle-latex-fragment]' to be removed."
1690 :group 'org-sparse-trees
1691 :group 'org-time
1692 :type 'boolean)
1694 (defcustom org-occur-case-fold-search t
1695 "Non-nil means `org-occur' should be case-insensitive.
1696 If set to `smart' the search will be case-insensitive only if it
1697 doesn't specify any upper case character."
1698 :group 'org-sparse-trees
1699 :version "26.1"
1700 :type '(choice
1701 (const :tag "Case-sensitive" nil)
1702 (const :tag "Case-insensitive" t)
1703 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1705 (defcustom org-occur-hook '(org-first-headline-recenter)
1706 "Hook that is run after `org-occur' has constructed a sparse tree.
1707 This can be used to recenter the window to show as much of the structure
1708 as possible."
1709 :group 'org-sparse-trees
1710 :type 'hook)
1712 (defgroup org-imenu-and-speedbar nil
1713 "Options concerning imenu and speedbar in Org mode."
1714 :tag "Org Imenu and Speedbar"
1715 :group 'org-structure)
1717 (defcustom org-imenu-depth 2
1718 "The maximum level for Imenu access to Org headlines.
1719 This also applied for speedbar access."
1720 :group 'org-imenu-and-speedbar
1721 :type 'integer)
1723 (defgroup org-table nil
1724 "Options concerning tables in Org mode."
1725 :tag "Org Table"
1726 :group 'org)
1728 (defcustom org-enable-table-editor 'optimized
1729 "Non-nil means lines starting with \"|\" are handled by the table editor.
1730 When nil, such lines will be treated like ordinary lines.
1732 When equal to the symbol `optimized', the table editor will be optimized to
1733 do the following:
1734 - Automatic overwrite mode in front of whitespace in table fields.
1735 This makes the structure of the table stay in tact as long as the edited
1736 field does not exceed the column width.
1737 - Minimize the number of realigns. Normally, the table is aligned each time
1738 TAB or RET are pressed to move to another field. With optimization this
1739 happens only if changes to a field might have changed the column width.
1740 Optimization requires replacing the functions `self-insert-command',
1741 `delete-char', and `backward-delete-char' in Org buffers, with a
1742 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1743 good at guessing when a re-align will be necessary, but you can always
1744 force one with `\\[org-ctrl-c-ctrl-c]'.
1746 If you would like to use the optimized version in Org mode, but the
1747 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1749 This variable can be used to turn on and off the table editor during a session,
1750 but in order to toggle optimization, a restart is required.
1752 See also the variable `org-table-auto-blank-field'."
1753 :group 'org-table
1754 :type '(choice
1755 (const :tag "off" nil)
1756 (const :tag "on" t)
1757 (const :tag "on, optimized" optimized)))
1759 (defcustom org-self-insert-cluster-for-undo nil
1760 "Non-nil means cluster self-insert commands for undo when possible.
1761 If this is set, then, like in the Emacs command loop, 20 consecutive
1762 characters will be undone together.
1763 This is configurable, because there is some impact on typing performance."
1764 :group 'org-table
1765 :type 'boolean)
1767 (defcustom org-table-tab-recognizes-table.el t
1768 "Non-nil means TAB will automatically notice a table.el table.
1769 When it sees such a table, it moves point into it and - if necessary -
1770 calls `table-recognize-table'."
1771 :group 'org-table-editing
1772 :type 'boolean)
1774 (defgroup org-link nil
1775 "Options concerning links in Org mode."
1776 :tag "Org Link"
1777 :group 'org)
1779 (defvar-local org-link-abbrev-alist-local nil
1780 "Buffer-local version of `org-link-abbrev-alist', which see.
1781 The value of this is taken from the #+LINK lines.")
1783 (defcustom org-link-parameters
1784 '(("doi" :follow org--open-doi-link)
1785 ("elisp" :follow org--open-elisp-link)
1786 ("file" :complete org-file-complete-link)
1787 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1788 ("help" :follow org--open-help-link)
1789 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1790 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1791 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1792 ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
1793 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1794 ("shell" :follow org--open-shell-link))
1795 "An alist of properties that defines all the links in Org mode.
1796 The key in each association is a string of the link type.
1797 Subsequent optional elements make up a p-list of link properties.
1799 :follow - A function that takes the link path as an argument.
1801 :export - A function that takes the link path, description and
1802 export-backend as arguments.
1804 :store - A function responsible for storing the link. See the
1805 function `org-store-link-functions'.
1807 :complete - A function that inserts a link with completion. The
1808 function takes one optional prefix arg.
1810 :face - A face for the link, or a function that returns a face.
1811 The function takes one argument which is the link path. The
1812 default face is `org-link'.
1814 :mouse-face - The mouse-face. The default is `highlight'.
1816 :display - `full' will not fold the link in descriptive
1817 display. Default is `org-link'.
1819 :help-echo - A string or function that takes (window object position)
1820 as arguments and returns a string.
1822 :keymap - A keymap that is active on the link. The default is
1823 `org-mouse-map'.
1825 :htmlize-link - A function for the htmlize-link. Defaults
1826 to (list :uri \"type:path\")
1828 :activate-func - A function to run at the end of font-lock
1829 activation. The function must accept (link-start link-end path bracketp)
1830 as arguments."
1831 :group 'org-link
1832 :type '(alist :tag "Link display parameters"
1833 :value-type plist))
1835 (defun org-link-get-parameter (type key)
1836 "Get TYPE link property for KEY.
1837 TYPE is a string and KEY is a plist keyword."
1838 (plist-get
1839 (cdr (assoc type org-link-parameters))
1840 key))
1842 (defun org-link-set-parameters (type &rest parameters)
1843 "Set link TYPE properties to PARAMETERS.
1844 PARAMETERS should be :key val pairs."
1845 (let ((data (assoc type org-link-parameters)))
1846 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1847 (push (cons type parameters) org-link-parameters)
1848 (org-make-link-regexps)
1849 (org-element-update-syntax))))
1851 (defun org-link-types ()
1852 "Return a list of known link types."
1853 (mapcar #'car org-link-parameters))
1855 (defcustom org-link-abbrev-alist nil
1856 "Alist of link abbreviations.
1857 The car of each element is a string, to be replaced at the start of a link.
1858 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1859 links in Org buffers can have an optional tag after a double colon, e.g.,
1861 [[linkkey:tag][description]]
1863 The `linkkey' must be a single word, starting with a letter, followed
1864 by letters, numbers, `-' or `_'.
1866 If REPLACE is a string, the tag will simply be appended to create the link.
1867 If the string contains \"%s\", the tag will be inserted there. If the string
1868 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1869 at that point (see the function `url-hexify-string'). If the string contains
1870 the specifier \"%(my-function)\", then the custom function `my-function' will
1871 be invoked: this function takes the tag as its only argument and must return
1872 a string.
1874 REPLACE may also be a function that will be called with the tag as the
1875 only argument to create the link, which should be returned as a string.
1877 See the manual for examples."
1878 :group 'org-link
1879 :type '(repeat
1880 (cons
1881 (string :tag "Protocol")
1882 (choice
1883 (string :tag "Format")
1884 (function)))))
1886 (defcustom org-descriptive-links t
1887 "Non-nil means Org will display descriptive links.
1888 E.g. [[http://orgmode.org][Org website]] will be displayed as
1889 \"Org Website\", hiding the link itself and just displaying its
1890 description. When set to nil, Org will display the full links
1891 literally.
1893 You can interactively set the value of this variable by calling
1894 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1895 :group 'org-link
1896 :type 'boolean)
1898 (defcustom org-link-file-path-type 'adaptive
1899 "How the path name in file links should be stored.
1900 Valid values are:
1902 relative Relative to the current directory, i.e. the directory of the file
1903 into which the link is being inserted.
1904 absolute Absolute path, if possible with ~ for home directory.
1905 noabbrev Absolute path, no abbreviation of home directory.
1906 adaptive Use relative path for files in the current directory and sub-
1907 directories of it. For other files, use an absolute path."
1908 :group 'org-link
1909 :type '(choice
1910 (const relative)
1911 (const absolute)
1912 (const noabbrev)
1913 (const adaptive)))
1915 (defvaralias 'org-activate-links 'org-highlight-links)
1916 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1917 "Types of links that should be highlighted in Org files.
1919 This is a list of symbols, each one of them leading to the
1920 highlighting of a certain link type.
1922 You can still open links that are not highlighted.
1924 In principle, it does not hurt to turn on highlighting for all
1925 link types. There may be a small gain when turning off unused
1926 link types. The types are:
1928 bracket The recommended [[link][description]] or [[link]] links with hiding.
1929 angle Links in angular brackets that may contain whitespace like
1930 <bbdb:Carsten Dominik>.
1931 plain Plain links in normal text, no whitespace, like http://google.com.
1932 radio Text that is matched by a radio target, see manual for details.
1933 tag Tag settings in a headline (link to tag search).
1934 date Time stamps (link to calendar).
1935 footnote Footnote labels.
1937 If you set this variable during an Emacs session, use `org-mode-restart'
1938 in the Org buffer so that the change takes effect."
1939 :group 'org-link
1940 :group 'org-appearance
1941 :type '(set :greedy t
1942 (const :tag "Double bracket links" bracket)
1943 (const :tag "Angular bracket links" angle)
1944 (const :tag "Plain text links" plain)
1945 (const :tag "Radio target matches" radio)
1946 (const :tag "Tags" tag)
1947 (const :tag "Timestamps" date)
1948 (const :tag "Footnotes" footnote)))
1950 (defcustom org-make-link-description-function nil
1951 "Function to use for generating link descriptions from links.
1952 When nil, the link location will be used. This function must take
1953 two parameters: the first one is the link, the second one is the
1954 description generated by `org-insert-link'. The function should
1955 return the description to use."
1956 :group 'org-link
1957 :type '(choice (const nil) (function)))
1959 (defgroup org-link-store nil
1960 "Options concerning storing links in Org mode."
1961 :tag "Org Store Link"
1962 :group 'org-link)
1964 (defcustom org-url-hexify-p t
1965 "When non-nil, hexify URL when creating a link."
1966 :type 'boolean
1967 :version "24.3"
1968 :group 'org-link-store)
1970 (defcustom org-email-link-description-format "Email %c: %.30s"
1971 "Format of the description part of a link to an email or usenet message.
1972 The following %-escapes will be replaced by corresponding information:
1974 %F full \"From\" field
1975 %f name, taken from \"From\" field, address if no name
1976 %T full \"To\" field
1977 %t first name in \"To\" field, address if no name
1978 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1979 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1980 %s subject
1981 %d date
1982 %m message-id.
1984 You may use normal field width specification between the % and the letter.
1985 This is for example useful to limit the length of the subject.
1987 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1988 :group 'org-link-store
1989 :type 'string)
1991 (defcustom org-from-is-user-regexp
1992 (let (r1 r2)
1993 (when (and user-mail-address (not (string= user-mail-address "")))
1994 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1995 (when (and user-full-name (not (string= user-full-name "")))
1996 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1997 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1998 "Regexp matched against the \"From:\" header of an email or usenet message.
1999 It should match if the message is from the user him/herself."
2000 :group 'org-link-store
2001 :type 'regexp)
2003 (defcustom org-context-in-file-links t
2004 "Non-nil means file links from `org-store-link' contain context.
2005 \\<org-mode-map>
2006 A search string will be added to the file name with :: as separator
2007 and used to find the context when the link is activated by the command
2008 `org-open-at-point'. When this option is t, the entire active region
2009 will be placed in the search string of the file link. If set to a
2010 positive integer, only the first n lines of context will be stored.
2012 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2013 \\[org-store-link]')
2014 negates this setting for the duration of the command."
2015 :group 'org-link-store
2016 :type '(choice boolean integer))
2018 (defcustom org-keep-stored-link-after-insertion nil
2019 "Non-nil means keep link in list for entire session.
2020 \\<org-mode-map>
2021 The command `org-store-link' adds a link pointing to the current
2022 location to an internal list. These links accumulate during a session.
2023 The command `org-insert-link' can be used to insert links into any
2024 Org file (offering completion for all stored links).
2026 When this option is nil, every link which has been inserted once using
2027 `\\[org-insert-link]' will be removed from the list, to make completing the \
2028 unused
2029 links more efficient."
2030 :group 'org-link-store
2031 :type 'boolean)
2033 (defgroup org-link-follow nil
2034 "Options concerning following links in Org mode."
2035 :tag "Org Follow Link"
2036 :group 'org-link)
2038 (defcustom org-link-translation-function nil
2039 "Function to translate links with different syntax to Org syntax.
2040 This can be used to translate links created for example by the Planner
2041 or emacs-wiki packages to Org syntax.
2042 The function must accept two parameters, a TYPE containing the link
2043 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2044 which is everything after the link protocol. It should return a cons
2045 with possibly modified values of type and path.
2046 Org contains a function for this, so if you set this variable to
2047 `org-translate-link-from-planner', you should be able follow many
2048 links created by planner."
2049 :group 'org-link-follow
2050 :type '(choice (const nil) (function)))
2052 (defcustom org-follow-link-hook nil
2053 "Hook that is run after a link has been followed."
2054 :group 'org-link-follow
2055 :type 'hook)
2057 (defcustom org-tab-follows-link nil
2058 "Non-nil means on links TAB will follow the link.
2059 Needs to be set before org.el is loaded.
2060 This really should not be used, it does not make sense, and the
2061 implementation is bad."
2062 :group 'org-link-follow
2063 :type 'boolean)
2065 (defcustom org-return-follows-link nil
2066 "Non-nil means on links RET will follow the link.
2067 In tables, the special behavior of RET has precedence."
2068 :group 'org-link-follow
2069 :type 'boolean)
2071 (defcustom org-mouse-1-follows-link
2072 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2073 "Non-nil means mouse-1 on a link will follow the link.
2074 A longer mouse click will still set point. Needs to be set
2075 before org.el is loaded."
2076 :group 'org-link-follow
2077 :version "24.4"
2078 :package-version '(Org . "8.3")
2079 :type '(choice
2080 (const :tag "A double click follows the link" double)
2081 (const :tag "Unconditionally follow the link with mouse-1" t)
2082 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2084 (defcustom org-mark-ring-length 4
2085 "Number of different positions to be recorded in the ring.
2086 Changing this requires a restart of Emacs to work correctly."
2087 :group 'org-link-follow
2088 :type 'integer)
2090 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2091 "Non-nil means internal fuzzy links can only match headlines.
2093 When nil, the a fuzzy link may point to a target or a named
2094 construct in the document. When set to the special value
2095 `query-to-create', offer to create a new headline when none
2096 matched.
2098 Spaces and statistics cookies are ignored during heading searches."
2099 :group 'org-link-follow
2100 :version "24.1"
2101 :type '(choice
2102 (const :tag "Use fuzzy text search" nil)
2103 (const :tag "Match only exact headline" t)
2104 (const :tag "Match exact headline or query to create it"
2105 query-to-create))
2106 :safe #'symbolp)
2108 (defcustom org-link-frame-setup
2109 '((vm . vm-visit-folder-other-frame)
2110 (vm-imap . vm-visit-imap-folder-other-frame)
2111 (gnus . org-gnus-no-new-news)
2112 (file . find-file-other-window)
2113 (wl . wl-other-frame))
2114 "Setup the frame configuration for following links.
2115 When following a link with Emacs, it may often be useful to display
2116 this link in another window or frame. This variable can be used to
2117 set this up for the different types of links.
2118 For VM, use any of
2119 `vm-visit-folder'
2120 `vm-visit-folder-other-window'
2121 `vm-visit-folder-other-frame'
2122 For Gnus, use any of
2123 `gnus'
2124 `gnus-other-frame'
2125 `org-gnus-no-new-news'
2126 For FILE, use any of
2127 `find-file'
2128 `find-file-other-window'
2129 `find-file-other-frame'
2130 For Wanderlust use any of
2131 `wl'
2132 `wl-other-frame'
2133 For the calendar, use the variable `calendar-setup'.
2134 For BBDB, it is currently only possible to display the matches in
2135 another window."
2136 :group 'org-link-follow
2137 :type '(list
2138 (cons (const vm)
2139 (choice
2140 (const vm-visit-folder)
2141 (const vm-visit-folder-other-window)
2142 (const vm-visit-folder-other-frame)))
2143 (cons (const vm-imap)
2144 (choice
2145 (const vm-visit-imap-folder)
2146 (const vm-visit-imap-folder-other-window)
2147 (const vm-visit-imap-folder-other-frame)))
2148 (cons (const gnus)
2149 (choice
2150 (const gnus)
2151 (const gnus-other-frame)
2152 (const org-gnus-no-new-news)))
2153 (cons (const file)
2154 (choice
2155 (const find-file)
2156 (const find-file-other-window)
2157 (const find-file-other-frame)))
2158 (cons (const wl)
2159 (choice
2160 (const wl)
2161 (const wl-other-frame)))))
2163 (defcustom org-display-internal-link-with-indirect-buffer nil
2164 "Non-nil means use indirect buffer to display infile links.
2165 Activating internal links (from one location in a file to another location
2166 in the same file) normally just jumps to the location. When the link is
2167 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2168 is displayed in
2169 another window. When this option is set, the other window actually displays
2170 an indirect buffer clone of the current buffer, to avoid any visibility
2171 changes to the current buffer."
2172 :group 'org-link-follow
2173 :type 'boolean)
2175 (defcustom org-open-non-existing-files nil
2176 "Non-nil means `org-open-file' will open non-existing files.
2177 When nil, an error will be generated.
2178 This variable applies only to external applications because they
2179 might choke on non-existing files. If the link is to a file that
2180 will be opened in Emacs, the variable is ignored."
2181 :group 'org-link-follow
2182 :type 'boolean)
2184 (defcustom org-open-directory-means-index-dot-org nil
2185 "Non-nil means a link to a directory really means to index.org.
2186 When nil, following a directory link will run dired or open a finder/explorer
2187 window on that directory."
2188 :group 'org-link-follow
2189 :type 'boolean)
2191 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2192 "Non-nil means ask for confirmation before executing shell links.
2193 Shell links can be dangerous: just think about a link
2195 [[shell:rm -rf ~/*][Google Search]]
2197 This link would show up in your Org document as \"Google Search\",
2198 but really it would remove your entire home directory.
2199 Therefore we advise against setting this variable to nil.
2200 Just change it to `y-or-n-p' if you want to confirm with a
2201 single keystroke rather than having to type \"yes\"."
2202 :group 'org-link-follow
2203 :type '(choice
2204 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2205 (const :tag "with y-or-n (faster)" y-or-n-p)
2206 (const :tag "no confirmation (dangerous)" nil)))
2207 (put 'org-confirm-shell-link-function
2208 'safe-local-variable
2209 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2211 (defcustom org-confirm-shell-link-not-regexp ""
2212 "A regexp to skip confirmation for shell links."
2213 :group 'org-link-follow
2214 :version "24.1"
2215 :type 'regexp)
2217 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2218 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2219 Elisp links can be dangerous: just think about a link
2221 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2223 This link would show up in your Org document as \"Google Search\",
2224 but really it would remove your entire home directory.
2225 Therefore we advise against setting this variable to nil.
2226 Just change it to `y-or-n-p' if you want to confirm with a
2227 single keystroke rather than having to type \"yes\"."
2228 :group 'org-link-follow
2229 :type '(choice
2230 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2231 (const :tag "with y-or-n (faster)" y-or-n-p)
2232 (const :tag "no confirmation (dangerous)" nil)))
2233 (put 'org-confirm-shell-link-function
2234 'safe-local-variable
2235 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2237 (defcustom org-confirm-elisp-link-not-regexp ""
2238 "A regexp to skip confirmation for Elisp links."
2239 :group 'org-link-follow
2240 :version "24.1"
2241 :type 'regexp)
2243 (defconst org-file-apps-defaults-gnu
2244 '((remote . emacs)
2245 (system . mailcap)
2246 (t . mailcap))
2247 "Default file applications on a UNIX or GNU/Linux system.
2248 See `org-file-apps'.")
2250 (defconst org-file-apps-defaults-macosx
2251 '((remote . emacs)
2252 (system . "open %s")
2253 ("ps.gz" . "gv %s")
2254 ("eps.gz" . "gv %s")
2255 ("dvi" . "xdvi %s")
2256 ("fig" . "xfig %s")
2257 (t . "open %s"))
2258 "Default file applications on a macOS system.
2259 The system \"open\" is known as a default, but we use X11 applications
2260 for some files for which the OS does not have a good default.
2261 See `org-file-apps'.")
2263 (defconst org-file-apps-defaults-windowsnt
2264 (list '(remote . emacs)
2265 (cons 'system (lambda (file _path)
2266 (with-no-warnings (w32-shell-execute "open" file))))
2267 (cons t (lambda (file _path)
2268 (with-no-warnings (w32-shell-execute "open" file)))))
2269 "Default file applications on a Windows NT system.
2270 The system \"open\" is used for most files.
2271 See `org-file-apps'.")
2273 (defcustom org-file-apps
2274 '((auto-mode . emacs)
2275 ("\\.mm\\'" . default)
2276 ("\\.x?html?\\'" . default)
2277 ("\\.pdf\\'" . default))
2278 "External applications for opening `file:path' items in a document.
2279 \\<org-mode-map>\
2281 Org mode uses system defaults for different file types, but
2282 you can use this variable to set the application for a given file
2283 extension. The entries in this list are cons cells where the car identifies
2284 files and the cdr the corresponding command.
2286 Possible values for the file identifier are:
2288 \"string\" A string as a file identifier can be interpreted in different
2289 ways, depending on its contents:
2291 - Alphanumeric characters only:
2292 Match links with this file extension.
2293 Example: (\"pdf\" . \"evince %s\")
2294 to open PDFs with evince.
2296 - Regular expression: Match links where the
2297 filename matches the regexp. If you want to
2298 use groups here, use shy groups.
2300 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2301 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2302 to open *.html and *.xhtml with firefox.
2304 - Regular expression which contains (non-shy) groups:
2305 Match links where the whole link, including \"::\", and
2306 anything after that, matches the regexp.
2307 In a custom command string, %1, %2, etc. are replaced with
2308 the parts of the link that were matched by the groups.
2309 For backwards compatibility, if a command string is given
2310 that does not use any of the group matches, this case is
2311 handled identically to the second one (i.e. match against
2312 file name only).
2313 In a custom function, you can access the group matches with
2314 (match-string n link).
2316 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2317 \"evince -p %1 %s\")
2318 to open [[file:document.pdf::5]] with evince at page 5.
2320 `directory' Matches a directory
2321 `remote' Matches a remote file, accessible through tramp or efs.
2322 Remote files most likely should be visited through Emacs
2323 because external applications cannot handle such paths.
2324 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2325 so all files Emacs knows how to handle. Using this with
2326 command `emacs' will open most files in Emacs. Beware that this
2327 will also open html files inside Emacs, unless you add
2328 (\"html\" . default) to the list as well.
2329 `system' The system command to open files, like `open' on Windows
2330 and macOS, and mailcap under GNU/Linux. This is the command
2331 that will be selected if you call `org-open-at-point' with a
2332 double prefix argument (`\\[universal-argument] \
2333 \\[universal-argument] \\[org-open-at-point]').
2334 t Default for files not matched by any of the other options.
2336 Possible values for the command are:
2338 `emacs' The file will be visited by the current Emacs process.
2339 `default' Use the default application for this file type, which is the
2340 association for t in the list, most likely in the system-specific
2341 part. This can be used to overrule an unwanted setting in the
2342 system-specific variable.
2343 `system' Use the system command for opening files, like \"open\".
2344 This command is specified by the entry whose car is `system'.
2345 Most likely, the system-specific version of this variable
2346 does define this command, but you can overrule/replace it
2347 here.
2348 `mailcap' Use command specified in the mailcaps.
2349 string A command to be executed by a shell; %s will be replaced
2350 by the path to the file.
2351 function A Lisp function, which will be called with two arguments:
2352 the file path and the original link string, without the
2353 \"file:\" prefix.
2355 For more examples, see the system specific constants
2356 `org-file-apps-defaults-macosx'
2357 `org-file-apps-defaults-windowsnt'
2358 `org-file-apps-defaults-gnu'."
2359 :group 'org-link-follow
2360 :type '(repeat
2361 (cons (choice :value ""
2362 (string :tag "Extension")
2363 (const :tag "System command to open files" system)
2364 (const :tag "Default for unrecognized files" t)
2365 (const :tag "Remote file" remote)
2366 (const :tag "Links to a directory" directory)
2367 (const :tag "Any files that have Emacs modes"
2368 auto-mode))
2369 (choice :value ""
2370 (const :tag "Visit with Emacs" emacs)
2371 (const :tag "Use default" default)
2372 (const :tag "Use the system command" system)
2373 (string :tag "Command")
2374 (function :tag "Function")))))
2376 (defcustom org-doi-server-url "http://dx.doi.org/"
2377 "The URL of the DOI server."
2378 :type 'string
2379 :version "24.3"
2380 :group 'org-link-follow)
2382 (defgroup org-refile nil
2383 "Options concerning refiling entries in Org mode."
2384 :tag "Org Refile"
2385 :group 'org)
2387 (defcustom org-directory "~/org"
2388 "Directory with Org files.
2389 This is just a default location to look for Org files. There is no need
2390 at all to put your files into this directory. It is used in the
2391 following situations:
2393 1. When a capture template specifies a target file that is not an
2394 absolute path. The path will then be interpreted relative to
2395 `org-directory'
2396 2. When the value of variable `org-agenda-files' is a single file, any
2397 relative paths in this file will be taken as relative to
2398 `org-directory'."
2399 :group 'org-refile
2400 :group 'org-capture
2401 :type 'directory)
2403 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2404 "Default target for storing notes.
2405 Used as a fall back file for org-capture.el, for templates that
2406 do not specify a target file."
2407 :group 'org-refile
2408 :group 'org-capture
2409 :type 'file)
2411 (defcustom org-goto-interface 'outline
2412 "The default interface to be used for `org-goto'.
2413 Allowed values are:
2414 outline The interface shows an outline of the relevant file
2415 and the correct heading is found by moving through
2416 the outline or by searching with incremental search.
2417 outline-path-completion Headlines in the current buffer are offered via
2418 completion. This is the interface also used by
2419 the refile command."
2420 :group 'org-refile
2421 :type '(choice
2422 (const :tag "Outline" outline)
2423 (const :tag "Outline-path-completion" outline-path-completion)))
2425 (defcustom org-goto-max-level 5
2426 "Maximum target level when running `org-goto' with refile interface."
2427 :group 'org-refile
2428 :type 'integer)
2430 (defcustom org-reverse-note-order nil
2431 "Non-nil means store new notes at the beginning of a file or entry.
2432 When nil, new notes will be filed to the end of a file or entry.
2433 This can also be a list with cons cells of regular expressions that
2434 are matched against file names, and values."
2435 :group 'org-capture
2436 :group 'org-refile
2437 :type '(choice
2438 (const :tag "Reverse always" t)
2439 (const :tag "Reverse never" nil)
2440 (repeat :tag "By file name regexp"
2441 (cons regexp boolean))))
2443 (defcustom org-log-refile nil
2444 "Information to record when a task is refiled.
2446 Possible values are:
2448 nil Don't add anything
2449 time Add a time stamp to the task
2450 note Prompt for a note and add it with template `org-log-note-headings'
2452 This option can also be set with on a per-file-basis with
2454 #+STARTUP: nologrefile
2455 #+STARTUP: logrefile
2456 #+STARTUP: lognoterefile
2458 You can have local logging settings for a subtree by setting the LOGGING
2459 property to one or more of these keywords.
2461 When bulk-refiling from the agenda, the value `note' is forbidden and
2462 will temporarily be changed to `time'."
2463 :group 'org-refile
2464 :group 'org-progress
2465 :version "24.1"
2466 :type '(choice
2467 (const :tag "No logging" nil)
2468 (const :tag "Record timestamp" time)
2469 (const :tag "Record timestamp with note." note)))
2471 (defcustom org-refile-targets nil
2472 "Targets for refiling entries with `\\[org-refile]'.
2473 This is a list of cons cells. Each cell contains:
2474 - a specification of the files to be considered, either a list of files,
2475 or a symbol whose function or variable value will be used to retrieve
2476 a file name or a list of file names. If you use `org-agenda-files' for
2477 that, all agenda files will be scanned for targets. Nil means consider
2478 headings in the current buffer.
2479 - A specification of how to find candidate refile targets. This may be
2480 any of:
2481 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2482 This tag has to be present in all target headlines, inheritance will
2483 not be considered.
2484 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2485 todo keyword.
2486 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2487 headlines that are refiling targets.
2488 - a cons cell (:level . N). Any headline of level N is considered a target.
2489 Note that, when `org-odd-levels-only' is set, level corresponds to
2490 order in hierarchy, not to the number of stars.
2491 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2492 Note that, when `org-odd-levels-only' is set, level corresponds to
2493 order in hierarchy, not to the number of stars.
2495 Each element of this list generates a set of possible targets.
2496 The union of these sets is presented (with completion) to
2497 the user by `org-refile'.
2499 You can set the variable `org-refile-target-verify-function' to a function
2500 to verify each headline found by the simple criteria above.
2502 When this variable is nil, all top-level headlines in the current buffer
2503 are used, equivalent to the value `((nil . (:level . 1))'."
2504 :group 'org-refile
2505 :type '(repeat
2506 (cons
2507 (choice :value org-agenda-files
2508 (const :tag "All agenda files" org-agenda-files)
2509 (const :tag "Current buffer" nil)
2510 (function) (variable) (file))
2511 (choice :tag "Identify target headline by"
2512 (cons :tag "Specific tag" (const :value :tag) (string))
2513 (cons :tag "TODO keyword" (const :value :todo) (string))
2514 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2515 (cons :tag "Level number" (const :value :level) (integer))
2516 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2518 (defcustom org-refile-target-verify-function nil
2519 "Function to verify if the headline at point should be a refile target.
2520 The function will be called without arguments, with point at the
2521 beginning of the headline. It should return t and leave point
2522 where it is if the headline is a valid target for refiling.
2524 If the target should not be selected, the function must return nil.
2525 In addition to this, it may move point to a place from where the search
2526 should be continued. For example, the function may decide that the entire
2527 subtree of the current entry should be excluded and move point to the end
2528 of the subtree."
2529 :group 'org-refile
2530 :type '(choice
2531 (const nil)
2532 (function)))
2534 (defcustom org-refile-use-cache nil
2535 "Non-nil means cache refile targets to speed up the process.
2536 \\<org-mode-map>\
2537 The cache for a particular file will be updated automatically when
2538 the buffer has been killed, or when any of the marker used for flagging
2539 refile targets no longer points at a live buffer.
2540 If you have added new entries to a buffer that might themselves be targets,
2541 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2542 if you find that easier, \
2543 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2544 \\[org-refile]'."
2545 :group 'org-refile
2546 :version "24.1"
2547 :type 'boolean)
2549 (defcustom org-refile-use-outline-path nil
2550 "Non-nil means provide refile targets as paths.
2551 So a level 3 headline will be available as level1/level2/level3.
2553 When the value is `file', also include the file name (without directory)
2554 into the path. In this case, you can also stop the completion after
2555 the file name, to get entries inserted as top level in the file.
2557 When `full-file-path', include the full file path."
2558 :group 'org-refile
2559 :type '(choice
2560 (const :tag "Not" nil)
2561 (const :tag "Yes" t)
2562 (const :tag "Start with file name" file)
2563 (const :tag "Start with full file path" full-file-path)))
2565 (defcustom org-outline-path-complete-in-steps t
2566 "Non-nil means complete the outline path in hierarchical steps.
2567 When Org uses the refile interface to select an outline path (see
2568 `org-refile-use-outline-path'), the completion of the path can be
2569 done in a single go, or it can be done in steps down the headline
2570 hierarchy. Going in steps is probably the best if you do not use
2571 a special completion package like `ido' or `icicles'. However,
2572 when using these packages, going in one step can be very fast,
2573 while still showing the whole path to the entry."
2574 :group 'org-refile
2575 :type 'boolean)
2577 (defcustom org-refile-allow-creating-parent-nodes nil
2578 "Non-nil means allow the creation of new nodes as refile targets.
2579 New nodes are then created by adding \"/new node name\" to the completion
2580 of an existing node. When the value of this variable is `confirm',
2581 new node creation must be confirmed by the user (recommended).
2582 When nil, the completion must match an existing entry.
2584 Note that, if the new heading is not seen by the criteria
2585 listed in `org-refile-targets', multiple instances of the same
2586 heading would be created by trying again to file under the new
2587 heading."
2588 :group 'org-refile
2589 :type '(choice
2590 (const :tag "Never" nil)
2591 (const :tag "Always" t)
2592 (const :tag "Prompt for confirmation" confirm)))
2594 (defcustom org-refile-active-region-within-subtree nil
2595 "Non-nil means also refile active region within a subtree.
2597 By default `org-refile' doesn't allow refiling regions if they
2598 don't contain a set of subtrees, but it might be convenient to
2599 do so sometimes: in that case, the first line of the region is
2600 converted to a headline before refiling."
2601 :group 'org-refile
2602 :version "24.1"
2603 :type 'boolean)
2605 (defgroup org-todo nil
2606 "Options concerning TODO items in Org mode."
2607 :tag "Org TODO"
2608 :group 'org)
2610 (defgroup org-progress nil
2611 "Options concerning Progress logging in Org mode."
2612 :tag "Org Progress"
2613 :group 'org-time)
2615 (defvar org-todo-interpretation-widgets
2616 '((:tag "Sequence (cycling hits every state)" sequence)
2617 (:tag "Type (cycling directly to DONE)" type))
2618 "The available interpretation symbols for customizing `org-todo-keywords'.
2619 Interested libraries should add to this list.")
2621 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2622 "List of TODO entry keyword sequences and their interpretation.
2623 \\<org-mode-map>This is a list of sequences.
2625 Each sequence starts with a symbol, either `sequence' or `type',
2626 indicating if the keywords should be interpreted as a sequence of
2627 action steps, or as different types of TODO items. The first
2628 keywords are states requiring action - these states will select a headline
2629 for inclusion into the global TODO list Org produces. If one of the
2630 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2631 signify that no further action is necessary. If \"|\" is not found,
2632 the last keyword is treated as the only DONE state of the sequence.
2634 The command `\\[org-todo]' cycles an entry through these states, and one
2635 additional state where no keyword is present. For details about this
2636 cycling, see the manual.
2638 TODO keywords and interpretation can also be set on a per-file basis with
2639 the special #+SEQ_TODO and #+TYP_TODO lines.
2641 Each keyword can optionally specify a character for fast state selection
2642 \(in combination with the variable `org-use-fast-todo-selection')
2643 and specifiers for state change logging, using the same syntax that
2644 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2645 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2646 indicates to record a time stamp each time this state is selected.
2648 Each keyword may also specify if a timestamp or a note should be
2649 recorded when entering or leaving the state, by adding additional
2650 characters in the parenthesis after the keyword. This looks like this:
2651 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2652 record only the time of the state change. With X and Y being either
2653 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2654 Y when leaving the state if and only if the *target* state does not
2655 define X. You may omit any of the fast-selection key or X or /Y,
2656 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2658 For backward compatibility, this variable may also be just a list
2659 of keywords. In this case the interpretation (sequence or type) will be
2660 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2661 :group 'org-todo
2662 :group 'org-keywords
2663 :type '(choice
2664 (repeat :tag "Old syntax, just keywords"
2665 (string :tag "Keyword"))
2666 (repeat :tag "New syntax"
2667 (cons
2668 (choice
2669 :tag "Interpretation"
2670 ;;Quick and dirty way to see
2671 ;;`org-todo-interpretations'. This takes the
2672 ;;place of item arguments
2673 :convert-widget
2674 (lambda (widget)
2675 (widget-put widget
2676 :args (mapcar
2677 (lambda (x)
2678 (widget-convert
2679 (cons 'const x)))
2680 org-todo-interpretation-widgets))
2681 widget))
2682 (repeat
2683 (string :tag "Keyword"))))))
2685 (defvar-local org-todo-keywords-1 nil
2686 "All TODO and DONE keywords active in a buffer.")
2687 (defvar org-todo-keywords-for-agenda nil)
2688 (defvar org-done-keywords-for-agenda nil)
2689 (defvar org-todo-keyword-alist-for-agenda nil)
2690 (defvar org-tag-alist-for-agenda nil
2691 "Alist of all tags from all agenda files.")
2692 (defvar org-tag-groups-alist-for-agenda nil
2693 "Alist of all groups tags from all current agenda files.")
2694 (defvar-local org-tag-groups-alist nil)
2695 (defvar org-agenda-contributing-files nil)
2696 (defvar-local org-current-tag-alist nil
2697 "Alist of all tag groups in current buffer.
2698 This variable takes into consideration `org-tag-alist',
2699 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2700 (defvar-local org-not-done-keywords nil)
2701 (defvar-local org-done-keywords nil)
2702 (defvar-local org-todo-heads nil)
2703 (defvar-local org-todo-sets nil)
2704 (defvar-local org-todo-log-states nil)
2705 (defvar-local org-todo-kwd-alist nil)
2706 (defvar-local org-todo-key-alist nil)
2707 (defvar-local org-todo-key-trigger nil)
2709 (defcustom org-todo-interpretation 'sequence
2710 "Controls how TODO keywords are interpreted.
2711 This variable is in principle obsolete and is only used for
2712 backward compatibility, if the interpretation of todo keywords is
2713 not given already in `org-todo-keywords'. See that variable for
2714 more information."
2715 :group 'org-todo
2716 :group 'org-keywords
2717 :type '(choice (const sequence)
2718 (const type)))
2720 (defcustom org-use-fast-todo-selection t
2721 "\\<org-mode-map>\
2722 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2723 This variable describes if and under what circumstances the cycling
2724 mechanism for TODO keywords will be replaced by a single-key, direct
2725 selection scheme.
2727 When nil, fast selection is never used.
2729 When the symbol `prefix', it will be used when `org-todo' is called
2730 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2731 in an Org buffer, and
2732 `\\[universal-argument] t' in an agenda buffer.
2734 When t, fast selection is used by default. In this case, the prefix
2735 argument forces cycling instead.
2737 In all cases, the special interface is only used if access keys have
2738 actually been assigned by the user, i.e. if keywords in the configuration
2739 are followed by a letter in parenthesis, like TODO(t)."
2740 :group 'org-todo
2741 :type '(choice
2742 (const :tag "Never" nil)
2743 (const :tag "By default" t)
2744 (const :tag "Only with C-u C-c C-t" prefix)))
2746 (defcustom org-provide-todo-statistics t
2747 "Non-nil means update todo statistics after insert and toggle.
2748 ALL-HEADLINES means update todo statistics by including headlines
2749 with no TODO keyword as well, counting them as not done.
2750 A list of TODO keywords means the same, but skip keywords that are
2751 not in this list.
2752 When set to a list of two lists, the first list contains keywords
2753 to consider as TODO keywords, the second list contains keywords
2754 to consider as DONE keywords.
2756 When this is set, todo statistics is updated in the parent of the
2757 current entry each time a todo state is changed."
2758 :group 'org-todo
2759 :type '(choice
2760 (const :tag "Yes, only for TODO entries" t)
2761 (const :tag "Yes, including all entries" all-headlines)
2762 (repeat :tag "Yes, for TODOs in this list"
2763 (string :tag "TODO keyword"))
2764 (list :tag "Yes, for TODOs and DONEs in these lists"
2765 (repeat (string :tag "TODO keyword"))
2766 (repeat (string :tag "DONE keyword")))
2767 (other :tag "No TODO statistics" nil)))
2769 (defcustom org-hierarchical-todo-statistics t
2770 "Non-nil means TODO statistics covers just direct children.
2771 When nil, all entries in the subtree are considered.
2772 This has only an effect if `org-provide-todo-statistics' is set.
2773 To set this to nil for only a single subtree, use a COOKIE_DATA
2774 property and include the word \"recursive\" into the value."
2775 :group 'org-todo
2776 :type 'boolean)
2778 (defcustom org-after-todo-state-change-hook nil
2779 "Hook which is run after the state of a TODO item was changed.
2780 The new state (a string with a TODO keyword, or nil) is available in the
2781 Lisp variable `org-state'."
2782 :group 'org-todo
2783 :type 'hook)
2785 (defvar org-blocker-hook nil
2786 "Hook for functions that are allowed to block a state change.
2788 Functions in this hook should not modify the buffer.
2789 Each function gets as its single argument a property list,
2790 see `org-trigger-hook' for more information about this list.
2792 If any of the functions in this hook returns nil, the state change
2793 is blocked.")
2795 (defvar org-trigger-hook nil
2796 "Hook for functions that are triggered by a state change.
2798 Each function gets as its single argument a property list with at
2799 least the following elements:
2801 (:type type-of-change :position pos-at-entry-start
2802 :from old-state :to new-state)
2804 Depending on the type, more properties may be present.
2806 This mechanism is currently implemented for:
2808 TODO state changes
2809 ------------------
2810 :type todo-state-change
2811 :from previous state (keyword as a string), or nil, or a symbol
2812 `todo' or `done', to indicate the general type of state.
2813 :to new state, like in :from")
2815 (defcustom org-enforce-todo-dependencies nil
2816 "Non-nil means undone TODO entries will block switching the parent to DONE.
2817 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2818 be blocked if any prior sibling is not yet done.
2819 Finally, if the parent is blocked because of ordered siblings of its own,
2820 the child will also be blocked."
2821 :set (lambda (var val)
2822 (set var val)
2823 (if val
2824 (add-hook 'org-blocker-hook
2825 'org-block-todo-from-children-or-siblings-or-parent)
2826 (remove-hook 'org-blocker-hook
2827 'org-block-todo-from-children-or-siblings-or-parent)))
2828 :group 'org-todo
2829 :type 'boolean)
2831 (defcustom org-enforce-todo-checkbox-dependencies nil
2832 "Non-nil means unchecked boxes will block switching the parent to DONE.
2833 When this is nil, checkboxes have no influence on switching TODO states.
2834 When non-nil, you first need to check off all check boxes before the TODO
2835 entry can be switched to DONE.
2836 This variable needs to be set before org.el is loaded, and you need to
2837 restart Emacs after a change to make the change effective. The only way
2838 to change is while Emacs is running is through the customize interface."
2839 :set (lambda (var val)
2840 (set var val)
2841 (if val
2842 (add-hook 'org-blocker-hook
2843 'org-block-todo-from-checkboxes)
2844 (remove-hook 'org-blocker-hook
2845 'org-block-todo-from-checkboxes)))
2846 :group 'org-todo
2847 :type 'boolean)
2849 (defcustom org-treat-insert-todo-heading-as-state-change nil
2850 "Non-nil means inserting a TODO heading is treated as state change.
2851 So when the command `\\[org-insert-todo-heading]' is used, state change
2852 logging will apply if appropriate. When nil, the new TODO item will
2853 be inserted directly, and no logging will take place."
2854 :group 'org-todo
2855 :type 'boolean)
2857 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2858 "Non-nil means switching TODO states with S-cursor counts as state change.
2859 This is the default behavior. However, setting this to nil allows a
2860 convenient way to select a TODO state and bypass any logging associated
2861 with that."
2862 :group 'org-todo
2863 :type 'boolean)
2865 (defcustom org-todo-state-tags-triggers nil
2866 "Tag changes that should be triggered by TODO state changes.
2867 This is a list. Each entry is
2869 (state-change (tag . flag) .......)
2871 State-change can be a string with a state, and empty string to indicate the
2872 state that has no TODO keyword, or it can be one of the symbols `todo'
2873 or `done', meaning any not-done or done state, respectively."
2874 :group 'org-todo
2875 :group 'org-tags
2876 :type '(repeat
2877 (cons (choice :tag "When changing to"
2878 (const :tag "Not-done state" todo)
2879 (const :tag "Done state" done)
2880 (string :tag "State"))
2881 (repeat
2882 (cons :tag "Tag action"
2883 (string :tag "Tag")
2884 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2886 (defcustom org-log-done nil
2887 "Information to record when a task moves to the DONE state.
2889 Possible values are:
2891 nil Don't add anything, just change the keyword
2892 time Add a time stamp to the task
2893 note Prompt for a note and add it with template `org-log-note-headings'
2895 This option can also be set with on a per-file-basis with
2897 #+STARTUP: nologdone
2898 #+STARTUP: logdone
2899 #+STARTUP: lognotedone
2901 You can have local logging settings for a subtree by setting the LOGGING
2902 property to one or more of these keywords."
2903 :group 'org-todo
2904 :group 'org-progress
2905 :type '(choice
2906 (const :tag "No logging" nil)
2907 (const :tag "Record CLOSED timestamp" time)
2908 (const :tag "Record CLOSED timestamp with note." note)))
2910 ;; Normalize old uses of org-log-done.
2911 (cond
2912 ((eq org-log-done t) (setq org-log-done 'time))
2913 ((and (listp org-log-done) (memq 'done org-log-done))
2914 (setq org-log-done 'note)))
2916 (defcustom org-log-reschedule nil
2917 "Information to record when the scheduling date of a tasks is modified.
2919 Possible values are:
2921 nil Don't add anything, just change the date
2922 time Add a time stamp to the task
2923 note Prompt for a note and add it with template `org-log-note-headings'
2925 This option can also be set with on a per-file-basis with
2927 #+STARTUP: nologreschedule
2928 #+STARTUP: logreschedule
2929 #+STARTUP: lognotereschedule"
2930 :group 'org-todo
2931 :group 'org-progress
2932 :type '(choice
2933 (const :tag "No logging" nil)
2934 (const :tag "Record timestamp" time)
2935 (const :tag "Record timestamp with note." note)))
2937 (defcustom org-log-redeadline nil
2938 "Information to record when the deadline date of a tasks is modified.
2940 Possible values are:
2942 nil Don't add anything, just change the date
2943 time Add a time stamp to the task
2944 note Prompt for a note and add it with template `org-log-note-headings'
2946 This option can also be set with on a per-file-basis with
2948 #+STARTUP: nologredeadline
2949 #+STARTUP: logredeadline
2950 #+STARTUP: lognoteredeadline
2952 You can have local logging settings for a subtree by setting the LOGGING
2953 property to one or more of these keywords."
2954 :group 'org-todo
2955 :group 'org-progress
2956 :type '(choice
2957 (const :tag "No logging" nil)
2958 (const :tag "Record timestamp" time)
2959 (const :tag "Record timestamp with note." note)))
2961 (defcustom org-log-note-clock-out nil
2962 "Non-nil means record a note when clocking out of an item.
2963 This can also be configured on a per-file basis by adding one of
2964 the following lines anywhere in the buffer:
2966 #+STARTUP: lognoteclock-out
2967 #+STARTUP: nolognoteclock-out"
2968 :group 'org-todo
2969 :group 'org-progress
2970 :type 'boolean)
2972 (defcustom org-log-done-with-time t
2973 "Non-nil means the CLOSED time stamp will contain date and time.
2974 When nil, only the date will be recorded."
2975 :group 'org-progress
2976 :type 'boolean)
2978 (defcustom org-log-note-headings
2979 '((done . "CLOSING NOTE %t")
2980 (state . "State %-12s from %-12S %t")
2981 (note . "Note taken on %t")
2982 (reschedule . "Rescheduled from %S on %t")
2983 (delschedule . "Not scheduled, was %S on %t")
2984 (redeadline . "New deadline from %S on %t")
2985 (deldeadline . "Removed deadline, was %S on %t")
2986 (refile . "Refiled on %t")
2987 (clock-out . ""))
2988 "Headings for notes added to entries.
2990 The value is an alist, with the car being a symbol indicating the
2991 note context, and the cdr is the heading to be used. The heading
2992 may also be the empty string. The following placeholders can be
2993 used:
2995 %t a time stamp.
2996 %T an active time stamp instead the default inactive one
2997 %d a short-format time stamp.
2998 %D an active short-format time stamp.
2999 %s the new TODO state or time stamp (inactive), in double quotes.
3000 %S the old TODO state or time stamp (inactive), in double quotes.
3001 %u the user name.
3002 %U full user name.
3004 In fact, it is not a good idea to change the `state' entry,
3005 because Agenda Log mode depends on the format of these entries."
3006 :group 'org-todo
3007 :group 'org-progress
3008 :type '(list :greedy t
3009 (cons (const :tag "Heading when closing an item" done) string)
3010 (cons (const :tag
3011 "Heading when changing todo state (todo sequence only)"
3012 state) string)
3013 (cons (const :tag "Heading when just taking a note" note) string)
3014 (cons (const :tag "Heading when rescheduling" reschedule) string)
3015 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3016 (cons (const :tag "Heading when changing deadline" redeadline) string)
3017 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3018 (cons (const :tag "Heading when refiling" refile) string)
3019 (cons (const :tag "Heading when clocking out" clock-out) string)))
3021 (unless (assq 'note org-log-note-headings)
3022 (push '(note . "%t") org-log-note-headings))
3024 (defcustom org-log-into-drawer nil
3025 "Non-nil means insert state change notes and time stamps into a drawer.
3026 When nil, state changes notes will be inserted after the headline and
3027 any scheduling and clock lines, but not inside a drawer.
3029 The value of this variable should be the name of the drawer to use.
3030 LOGBOOK is proposed as the default drawer for this purpose, you can
3031 also set this to a string to define the drawer of your choice.
3033 A value of t is also allowed, representing \"LOGBOOK\".
3035 A value of t or nil can also be set with on a per-file-basis with
3037 #+STARTUP: logdrawer
3038 #+STARTUP: nologdrawer
3040 If this variable is set, `org-log-state-notes-insert-after-drawers'
3041 will be ignored.
3043 You can set the property LOG_INTO_DRAWER to overrule this setting for
3044 a subtree.
3046 Do not check directly this variable in a Lisp program. Call
3047 function `org-log-into-drawer' instead."
3048 :group 'org-todo
3049 :group 'org-progress
3050 :type '(choice
3051 (const :tag "Not into a drawer" nil)
3052 (const :tag "LOGBOOK" t)
3053 (string :tag "Other")))
3055 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3057 (defun org-log-into-drawer ()
3058 "Name of the log drawer, as a string, or nil.
3059 This is the value of `org-log-into-drawer'. However, if the
3060 current entry has or inherits a LOG_INTO_DRAWER property, it will
3061 be used instead of the default value."
3062 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3063 (cond ((equal p "nil") nil)
3064 ((equal p "t") "LOGBOOK")
3065 ((stringp p) p)
3066 (p "LOGBOOK")
3067 ((stringp org-log-into-drawer) org-log-into-drawer)
3068 (org-log-into-drawer "LOGBOOK"))))
3070 (defcustom org-log-state-notes-insert-after-drawers nil
3071 "Non-nil means insert state change notes after any drawers in entry.
3072 Only the drawers that *immediately* follow the headline and the
3073 deadline/scheduled line are skipped.
3074 When nil, insert notes right after the heading and perhaps the line
3075 with deadline/scheduling if present.
3077 This variable will have no effect if `org-log-into-drawer' is
3078 set."
3079 :group 'org-todo
3080 :group 'org-progress
3081 :type 'boolean)
3083 (defcustom org-log-states-order-reversed t
3084 "Non-nil means the latest state note will be directly after heading.
3085 When nil, the state change notes will be ordered according to time.
3087 This option can also be set with on a per-file-basis with
3089 #+STARTUP: logstatesreversed
3090 #+STARTUP: nologstatesreversed"
3091 :group 'org-todo
3092 :group 'org-progress
3093 :type 'boolean)
3095 (defcustom org-todo-repeat-to-state nil
3096 "The TODO state to which a repeater should return the repeating task.
3097 By default this is the first task in a TODO sequence, or the previous state
3098 in a TODO_TYP set. But you can specify another task here.
3099 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3100 :group 'org-todo
3101 :version "24.1"
3102 :type '(choice (const :tag "Head of sequence" nil)
3103 (string :tag "Specific state")))
3105 (defcustom org-log-repeat 'time
3106 "Non-nil means record moving through the DONE state when triggering repeat.
3107 An auto-repeating task is immediately switched back to TODO when
3108 marked DONE. If you are not logging state changes (by adding \"@\"
3109 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3110 record a closing note, there will be no record of the task moving
3111 through DONE. This variable forces taking a note anyway.
3113 nil Don't force a record
3114 time Record a time stamp
3115 note Prompt for a note and add it with template `org-log-note-headings'
3117 This option can also be set with on a per-file-basis with
3119 #+STARTUP: nologrepeat
3120 #+STARTUP: logrepeat
3121 #+STARTUP: lognoterepeat
3123 You can have local logging settings for a subtree by setting the LOGGING
3124 property to one or more of these keywords."
3125 :group 'org-todo
3126 :group 'org-progress
3127 :type '(choice
3128 (const :tag "Don't force a record" nil)
3129 (const :tag "Force recording the DONE state" time)
3130 (const :tag "Force recording a note with the DONE state" note)))
3133 (defgroup org-priorities nil
3134 "Priorities in Org mode."
3135 :tag "Org Priorities"
3136 :group 'org-todo)
3138 (defcustom org-enable-priority-commands t
3139 "Non-nil means priority commands are active.
3140 When nil, these commands will be disabled, so that you never accidentally
3141 set a priority."
3142 :group 'org-priorities
3143 :type 'boolean)
3145 (defcustom org-highest-priority ?A
3146 "The highest priority of TODO items. A character like ?A, ?B etc.
3147 Must have a smaller ASCII number than `org-lowest-priority'."
3148 :group 'org-priorities
3149 :type 'character)
3151 (defcustom org-lowest-priority ?C
3152 "The lowest priority of TODO items. A character like ?A, ?B etc.
3153 Must have a larger ASCII number than `org-highest-priority'."
3154 :group 'org-priorities
3155 :type 'character)
3157 (defcustom org-default-priority ?B
3158 "The default priority of TODO items.
3159 This is the priority an item gets if no explicit priority is given.
3160 When starting to cycle on an empty priority the first step in the cycle
3161 depends on `org-priority-start-cycle-with-default'. The resulting first
3162 step priority must not exceed the range from `org-highest-priority' to
3163 `org-lowest-priority' which means that `org-default-priority' has to be
3164 in this range exclusive or inclusive the range boundaries. Else the
3165 first step refuses to set the default and the second will fall back
3166 to (depending on the command used) the highest or lowest priority."
3167 :group 'org-priorities
3168 :type 'character)
3170 (defcustom org-priority-start-cycle-with-default t
3171 "Non-nil means start with default priority when starting to cycle.
3172 When this is nil, the first step in the cycle will be (depending on the
3173 command used) one higher or lower than the default priority.
3174 See also `org-default-priority'."
3175 :group 'org-priorities
3176 :type 'boolean)
3178 (defcustom org-get-priority-function nil
3179 "Function to extract the priority from a string.
3180 The string is normally the headline. If this is nil Org computes the
3181 priority from the priority cookie like [#A] in the headline. It returns
3182 an integer, increasing by 1000 for each priority level.
3183 The user can set a different function here, which should take a string
3184 as an argument and return the numeric priority."
3185 :group 'org-priorities
3186 :version "24.1"
3187 :type '(choice
3188 (const nil)
3189 (function)))
3191 (defgroup org-time nil
3192 "Options concerning time stamps and deadlines in Org mode."
3193 :tag "Org Time"
3194 :group 'org)
3196 (defcustom org-time-stamp-rounding-minutes '(0 5)
3197 "Number of minutes to round time stamps to.
3198 \\<org-mode-map>\
3199 These are two values, the first applies when first creating a time stamp.
3200 The second applies when changing it with the commands `S-up' and `S-down'.
3201 When changing the time stamp, this means that it will change in steps
3202 of N minutes, as given by the second value.
3204 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3205 numbers should be factors of 60, so for example 5, 10, 15.
3207 When this is larger than 1, you can still force an exact time stamp by using
3208 a double prefix argument to a time stamp command like \
3209 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3210 and by using a prefix arg to `S-up/down' to specify the exact number
3211 of minutes to shift."
3212 :group 'org-time
3213 :get (lambda (var) ; Make sure both elements are there
3214 (if (integerp (default-value var))
3215 (list (default-value var) 5)
3216 (default-value var)))
3217 :type '(list
3218 (integer :tag "when inserting times")
3219 (integer :tag "when modifying times")))
3221 ;; Normalize old customizations of this variable.
3222 (when (integerp org-time-stamp-rounding-minutes)
3223 (setq org-time-stamp-rounding-minutes
3224 (list org-time-stamp-rounding-minutes
3225 org-time-stamp-rounding-minutes)))
3227 (defcustom org-display-custom-times nil
3228 "Non-nil means overlay custom formats over all time stamps.
3229 The formats are defined through the variable `org-time-stamp-custom-formats'.
3230 To turn this on on a per-file basis, insert anywhere in the file:
3231 #+STARTUP: customtime"
3232 :group 'org-time
3233 :set 'set-default
3234 :type 'sexp)
3235 (make-variable-buffer-local 'org-display-custom-times)
3237 (defcustom org-time-stamp-custom-formats
3238 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3239 "Custom formats for time stamps. See `format-time-string' for the syntax.
3240 These are overlaid over the default ISO format if the variable
3241 `org-display-custom-times' is set. Time like %H:%M should be at the
3242 end of the second format. The custom formats are also honored by export
3243 commands, if custom time display is turned on at the time of export."
3244 :group 'org-time
3245 :type 'sexp)
3247 (defun org-time-stamp-format (&optional long inactive)
3248 "Get the right format for a time string."
3249 (let ((f (if long (cdr org-time-stamp-formats)
3250 (car org-time-stamp-formats))))
3251 (if inactive
3252 (concat "[" (substring f 1 -1) "]")
3253 f)))
3255 (defcustom org-time-clocksum-format
3256 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3257 "The format string used when creating CLOCKSUM lines.
3258 This is also used when Org mode generates a time duration.
3260 The value can be a single format string containing two
3261 %-sequences, which will be filled with the number of hours and
3262 minutes in that order.
3264 Alternatively, the value can be a plist associating any of the
3265 keys :years, :months, :weeks, :days, :hours or :minutes with
3266 format strings. The time duration is formatted using only the
3267 time components that are needed and concatenating the results.
3268 If a time unit in absent, it falls back to the next smallest
3269 unit.
3271 The keys :require-years, :require-months, :require-days,
3272 :require-weeks, :require-hours, :require-minutes are also
3273 meaningful. A non-nil value for these keys indicates that the
3274 corresponding time component should always be included, even if
3275 its value is 0.
3278 For example,
3280 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3281 :require-minutes t)
3283 means durations longer than a day will be expressed in days,
3284 hours and minutes, and durations less than a day will always be
3285 expressed in hours and minutes (even for durations less than an
3286 hour).
3288 The value
3290 (:days \"%dd\" :minutes \"%dm\")
3292 means durations longer than a day will be expressed in days and
3293 minutes, and durations less than a day will be expressed entirely
3294 in minutes (even for durations longer than an hour)."
3295 :group 'org-time
3296 :group 'org-clock
3297 :version "24.4"
3298 :package-version '(Org . "8.0")
3299 :type '(choice (string :tag "Format string")
3300 (set :tag "Plist"
3301 (group :inline t (const :tag "Years" :years)
3302 (string :tag "Format string"))
3303 (group :inline t
3304 (const :tag "Always show years" :require-years)
3305 (const t))
3306 (group :inline t (const :tag "Months" :months)
3307 (string :tag "Format string"))
3308 (group :inline t
3309 (const :tag "Always show months" :require-months)
3310 (const t))
3311 (group :inline t (const :tag "Weeks" :weeks)
3312 (string :tag "Format string"))
3313 (group :inline t
3314 (const :tag "Always show weeks" :require-weeks)
3315 (const t))
3316 (group :inline t (const :tag "Days" :days)
3317 (string :tag "Format string"))
3318 (group :inline t
3319 (const :tag "Always show days" :require-days)
3320 (const t))
3321 (group :inline t (const :tag "Hours" :hours)
3322 (string :tag "Format string"))
3323 (group :inline t
3324 (const :tag "Always show hours" :require-hours)
3325 (const t))
3326 (group :inline t (const :tag "Minutes" :minutes)
3327 (string :tag "Format string"))
3328 (group :inline t
3329 (const :tag "Always show minutes" :require-minutes)
3330 (const t)))))
3332 (defcustom org-time-clocksum-use-fractional nil
3333 "When non-nil, `\\[org-clock-display]' uses fractional times.
3334 See `org-time-clocksum-format' for more on time clock formats."
3335 :group 'org-time
3336 :group 'org-clock
3337 :version "24.3"
3338 :type 'boolean)
3340 (defcustom org-time-clocksum-use-effort-durations nil
3341 "When non-nil, `\\[org-clock-display]' uses effort durations.
3342 E.g. by default, one day is considered to be a 8 hours effort,
3343 so a task that has been clocked for 16 hours will be displayed
3344 as during 2 days in the clock display or in the clocktable.
3346 See `org-effort-durations' on how to set effort durations
3347 and `org-time-clocksum-format' for more on time clock formats."
3348 :group 'org-time
3349 :group 'org-clock
3350 :version "24.4"
3351 :package-version '(Org . "8.0")
3352 :type 'boolean)
3354 (defcustom org-time-clocksum-fractional-format "%.2f"
3355 "The format string used when creating CLOCKSUM lines,
3356 or when Org mode generates a time duration, if
3357 `org-time-clocksum-use-fractional' is enabled.
3359 The value can be a single format string containing one
3360 %-sequence, which will be filled with the number of hours as
3361 a float.
3363 Alternatively, the value can be a plist associating any of the
3364 keys :years, :months, :weeks, :days, :hours or :minutes with
3365 a format string. The time duration is formatted using the
3366 largest time unit which gives a non-zero integer part. If all
3367 specified formats have zero integer part, the smallest time unit
3368 is used."
3369 :group 'org-time
3370 :type '(choice (string :tag "Format string")
3371 (set (group :inline t (const :tag "Years" :years)
3372 (string :tag "Format string"))
3373 (group :inline t (const :tag "Months" :months)
3374 (string :tag "Format string"))
3375 (group :inline t (const :tag "Weeks" :weeks)
3376 (string :tag "Format string"))
3377 (group :inline t (const :tag "Days" :days)
3378 (string :tag "Format string"))
3379 (group :inline t (const :tag "Hours" :hours)
3380 (string :tag "Format string"))
3381 (group :inline t (const :tag "Minutes" :minutes)
3382 (string :tag "Format string")))))
3384 (defcustom org-deadline-warning-days 14
3385 "Number of days before expiration during which a deadline becomes active.
3386 This variable governs the display in sparse trees and in the agenda.
3387 When 0 or negative, it means use this number (the absolute value of it)
3388 even if a deadline has a different individual lead time specified.
3390 Custom commands can set this variable in the options section."
3391 :group 'org-time
3392 :group 'org-agenda-daily/weekly
3393 :type 'integer)
3395 (defcustom org-scheduled-delay-days 0
3396 "Number of days before a scheduled item becomes active.
3397 This variable governs the display in sparse trees and in the agenda.
3398 The default value (i.e. 0) means: don't delay scheduled item.
3399 When negative, it means use this number (the absolute value of it)
3400 even if a scheduled item has a different individual delay time
3401 specified.
3403 Custom commands can set this variable in the options section."
3404 :group 'org-time
3405 :group 'org-agenda-daily/weekly
3406 :version "24.4"
3407 :package-version '(Org . "8.0")
3408 :type 'integer)
3410 (defcustom org-read-date-prefer-future t
3411 "Non-nil means assume future for incomplete date input from user.
3412 This affects the following situations:
3413 1. The user gives a month but not a year.
3414 For example, if it is April and you enter \"feb 2\", this will be read
3415 as Feb 2, *next* year. \"May 5\", however, will be this year.
3416 2. The user gives a day, but no month.
3417 For example, if today is the 15th, and you enter \"3\", Org will read
3418 this as the third of *next* month. However, if you enter \"17\",
3419 it will be considered as *this* month.
3421 If you set this variable to the symbol `time', then also the following
3422 will work:
3424 3. If the user gives a time.
3425 If the time is before now, it will be interpreted as tomorrow.
3427 Currently none of this works for ISO week specifications.
3429 When this option is nil, the current day, month and year will always be
3430 used as defaults.
3432 See also `org-agenda-jump-prefer-future'."
3433 :group 'org-time
3434 :type '(choice
3435 (const :tag "Never" nil)
3436 (const :tag "Check month and day" t)
3437 (const :tag "Check month, day, and time" time)))
3439 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3440 "Should the agenda jump command prefer the future for incomplete dates?
3441 The default is to do the same as configured in `org-read-date-prefer-future'.
3442 But you can also set a deviating value here.
3443 This may t or nil, or the symbol `org-read-date-prefer-future'."
3444 :group 'org-agenda
3445 :group 'org-time
3446 :version "24.1"
3447 :type '(choice
3448 (const :tag "Use org-read-date-prefer-future"
3449 org-read-date-prefer-future)
3450 (const :tag "Never" nil)
3451 (const :tag "Always" t)))
3453 (defcustom org-read-date-force-compatible-dates t
3454 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3456 Depending on the system Emacs is running on, certain dates cannot
3457 be represented with the type used internally to represent time.
3458 Dates between 1970-1-1 and 2038-1-1 can always be represented
3459 correctly. Some systems allow for earlier dates, some for later,
3460 some for both. One way to find out it to insert any date into an
3461 Org buffer, putting the cursor on the year and hitting S-up and
3462 S-down to test the range.
3464 When this variable is set to t, the date/time prompt will not let
3465 you specify dates outside the 1970-2037 range, so it is certain that
3466 these dates will work in whatever version of Emacs you are
3467 running, and also that you can move a file from one Emacs implementation
3468 to another. WHenever Org is forcing the year for you, it will display
3469 a message and beep.
3471 When this variable is nil, Org will check if the date is
3472 representable in the specific Emacs implementation you are using.
3473 If not, it will force a year, usually the current year, and beep
3474 to remind you. Currently this setting is not recommended because
3475 the likelihood that you will open your Org files in an Emacs that
3476 has limited date range is not negligible.
3478 A workaround for this problem is to use diary sexp dates for time
3479 stamps outside of this range."
3480 :group 'org-time
3481 :version "24.1"
3482 :type 'boolean)
3484 (defcustom org-read-date-display-live t
3485 "Non-nil means display current interpretation of date prompt live.
3486 This display will be in an overlay, in the minibuffer."
3487 :group 'org-time
3488 :type 'boolean)
3490 (defcustom org-read-date-popup-calendar t
3491 "Non-nil means pop up a calendar when prompting for a date.
3492 In the calendar, the date can be selected with mouse-1. However, the
3493 minibuffer will also be active, and you can simply enter the date as well.
3494 When nil, only the minibuffer will be available."
3495 :group 'org-time
3496 :type 'boolean)
3497 (defvaralias 'org-popup-calendar-for-date-prompt
3498 'org-read-date-popup-calendar)
3500 (defcustom org-extend-today-until 0
3501 "The hour when your day really ends. Must be an integer.
3502 This has influence for the following applications:
3503 - When switching the agenda to \"today\". It it is still earlier than
3504 the time given here, the day recognized as TODAY is actually yesterday.
3505 - When a date is read from the user and it is still before the time given
3506 here, the current date and time will be assumed to be yesterday, 23:59.
3507 Also, timestamps inserted in capture templates follow this rule.
3509 IMPORTANT: This is a feature whose implementation is and likely will
3510 remain incomplete. Really, it is only here because past midnight seems to
3511 be the favorite working time of John Wiegley :-)"
3512 :group 'org-time
3513 :type 'integer)
3515 (defcustom org-use-effective-time nil
3516 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3517 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3518 \"effective time\" of any timestamps between midnight and 8am will be
3519 23:59 of the previous day."
3520 :group 'org-time
3521 :version "24.1"
3522 :type 'boolean)
3524 (defcustom org-use-last-clock-out-time-as-effective-time nil
3525 "When non-nil, use the last clock out time for `org-todo'.
3526 Note that this option has precedence over the combined use of
3527 `org-use-effective-time' and `org-extend-today-until'."
3528 :group 'org-time
3529 :version "24.4"
3530 :package-version '(Org . "8.0")
3531 :type 'boolean)
3533 (defcustom org-edit-timestamp-down-means-later nil
3534 "Non-nil means S-down will increase the time in a time stamp.
3535 When nil, S-up will increase."
3536 :group 'org-time
3537 :type 'boolean)
3539 (defcustom org-calendar-follow-timestamp-change t
3540 "Non-nil means make the calendar window follow timestamp changes.
3541 When a timestamp is modified and the calendar window is visible, it will be
3542 moved to the new date."
3543 :group 'org-time
3544 :type 'boolean)
3546 (defgroup org-tags nil
3547 "Options concerning tags in Org mode."
3548 :tag "Org Tags"
3549 :group 'org)
3551 (defcustom org-tag-alist nil
3552 "Default tags available in Org files.
3554 The value of this variable is an alist. Associations either:
3556 (TAG)
3557 (TAG . SELECT)
3558 (SPECIAL)
3560 where TAG is a tag as a string, SELECT is character, used to
3561 select that tag through the fast tag selection interface, and
3562 SPECIAL is one of the following keywords: `:startgroup',
3563 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3564 `:newline'. These keywords are used to define a hierarchy of
3565 tags. See manual for details.
3567 When this variable is nil, Org mode bases tag input on what is
3568 already in the buffer. The value can be overridden locally by
3569 using a TAGS keyword, e.g.,
3571 #+TAGS: tag1 tag2
3573 See also `org-tag-persistent-alist' to sidestep this behavior."
3574 :group 'org-tags
3575 :type '(repeat
3576 (choice
3577 (cons :tag "Tag with key"
3578 (string :tag "Tag name")
3579 (character :tag "Access char"))
3580 (list :tag "Tag" (string :tag "Tag name"))
3581 (const :tag "Start radio group" (:startgroup))
3582 (const :tag "Start tag group, non distinct" (:startgrouptag))
3583 (const :tag "Group tags delimiter" (:grouptags))
3584 (const :tag "End radio group" (:endgroup))
3585 (const :tag "End tag group, non distinct" (:endgrouptag))
3586 (const :tag "New line" (:newline)))))
3588 (defcustom org-tag-persistent-alist nil
3589 "Tags always available in Org files.
3591 The value of this variable is an alist. Associations either:
3593 (TAG)
3594 (TAG . SELECT)
3595 (SPECIAL)
3597 where TAG is a tag as a string, SELECT is a character, used to
3598 select that tag through the fast tag selection interface, and
3599 SPECIAL is one of the following keywords: `:startgroup',
3600 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3601 `:newline'. These keywords are used to define a hierarchy of
3602 tags. See manual for details.
3604 Unlike to `org-tag-alist', tags defined in this variable do not
3605 depend on a local TAGS keyword. Instead, to disable these tags
3606 on a per-file basis, insert anywhere in the file:
3608 #+STARTUP: noptag"
3609 :group 'org-tags
3610 :type '(repeat
3611 (choice
3612 (cons :tag "Tag with key"
3613 (string :tag "Tag name")
3614 (character :tag "Access char"))
3615 (list :tag "Tag" (string :tag "Tag name"))
3616 (const :tag "Start radio group" (:startgroup))
3617 (const :tag "Start tag group, non distinct" (:startgrouptag))
3618 (const :tag "Group tags delimiter" (:grouptags))
3619 (const :tag "End radio group" (:endgroup))
3620 (const :tag "End tag group, non distinct" (:endgrouptag))
3621 (const :tag "New line" (:newline)))))
3623 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3624 "If non-nil, always offer completion for all tags of all agenda files.
3625 Instead of customizing this variable directly, you might want to
3626 set it locally for capture buffers, because there no list of
3627 tags in that file can be created dynamically (there are none).
3629 (add-hook \\='org-capture-mode-hook
3630 (lambda ()
3631 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3632 :group 'org-tags
3633 :version "24.1"
3634 :type 'boolean)
3636 (defvar org-file-tags nil
3637 "List of tags that can be inherited by all entries in the file.
3638 The tags will be inherited if the variable `org-use-tag-inheritance'
3639 says they should be.
3640 This variable is populated from #+FILETAGS lines.")
3642 (defcustom org-use-fast-tag-selection 'auto
3643 "Non-nil means use fast tag selection scheme.
3644 This is a special interface to select and deselect tags with single keys.
3645 When nil, fast selection is never used.
3646 When the symbol `auto', fast selection is used if and only if selection
3647 characters for tags have been configured, either through the variable
3648 `org-tag-alist' or through a #+TAGS line in the buffer.
3649 When t, fast selection is always used and selection keys are assigned
3650 automatically if necessary."
3651 :group 'org-tags
3652 :type '(choice
3653 (const :tag "Always" t)
3654 (const :tag "Never" nil)
3655 (const :tag "When selection characters are configured" auto)))
3657 (defcustom org-fast-tag-selection-single-key nil
3658 "Non-nil means fast tag selection exits after first change.
3659 When nil, you have to press RET to exit it.
3660 During fast tag selection, you can toggle this flag with `C-c'.
3661 This variable can also have the value `expert'. In this case, the window
3662 displaying the tags menu is not even shown, until you press C-c again."
3663 :group 'org-tags
3664 :type '(choice
3665 (const :tag "No" nil)
3666 (const :tag "Yes" t)
3667 (const :tag "Expert" expert)))
3669 (defvar org-fast-tag-selection-include-todo nil
3670 "Non-nil means fast tags selection interface will also offer TODO states.
3671 This is an undocumented feature, you should not rely on it.")
3673 (defcustom org-tags-column -77
3674 "The column to which tags should be indented in a headline.
3675 If this number is positive, it specifies the column. If it is negative,
3676 it means that the tags should be flushright to that column. For example,
3677 -80 works well for a normal 80 character screen.
3678 When 0, place tags directly after headline text, with only one space in
3679 between."
3680 :group 'org-tags
3681 :type 'integer)
3683 (defcustom org-auto-align-tags t
3684 "Non-nil keeps tags aligned when modifying headlines.
3685 Some operations (i.e. demoting) change the length of a headline and
3686 therefore shift the tags around. With this option turned on, after
3687 each such operation the tags are again aligned to `org-tags-column'."
3688 :group 'org-tags
3689 :type 'boolean)
3691 (defcustom org-use-tag-inheritance t
3692 "Non-nil means tags in levels apply also for sublevels.
3693 When nil, only the tags directly given in a specific line apply there.
3694 This may also be a list of tags that should be inherited, or a regexp that
3695 matches tags that should be inherited. Additional control is possible
3696 with the variable `org-tags-exclude-from-inheritance' which gives an
3697 explicit list of tags to be excluded from inheritance, even if the value of
3698 `org-use-tag-inheritance' would select it for inheritance.
3700 If this option is t, a match early-on in a tree can lead to a large
3701 number of matches in the subtree when constructing the agenda or creating
3702 a sparse tree. If you only want to see the first match in a tree during
3703 a search, check out the variable `org-tags-match-list-sublevels'."
3704 :group 'org-tags
3705 :type '(choice
3706 (const :tag "Not" nil)
3707 (const :tag "Always" t)
3708 (repeat :tag "Specific tags" (string :tag "Tag"))
3709 (regexp :tag "Tags matched by regexp")))
3711 (defcustom org-tags-exclude-from-inheritance nil
3712 "List of tags that should never be inherited.
3713 This is a way to exclude a few tags from inheritance. For way to do
3714 the opposite, to actively allow inheritance for selected tags,
3715 see the variable `org-use-tag-inheritance'."
3716 :group 'org-tags
3717 :type '(repeat (string :tag "Tag")))
3719 (defun org-tag-inherit-p (tag)
3720 "Check if TAG is one that should be inherited."
3721 (cond
3722 ((member tag org-tags-exclude-from-inheritance) nil)
3723 ((eq org-use-tag-inheritance t) t)
3724 ((not org-use-tag-inheritance) nil)
3725 ((stringp org-use-tag-inheritance)
3726 (string-match org-use-tag-inheritance tag))
3727 ((listp org-use-tag-inheritance)
3728 (member tag org-use-tag-inheritance))
3729 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3731 (defcustom org-tags-match-list-sublevels t
3732 "Non-nil means list also sublevels of headlines matching a search.
3733 This variable applies to tags/property searches, and also to stuck
3734 projects because this search is based on a tags match as well.
3736 When set to the symbol `indented', sublevels are indented with
3737 leading dots.
3739 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3740 the sublevels of a headline matching a tag search often also match
3741 the same search. Listing all of them can create very long lists.
3742 Setting this variable to nil causes subtrees of a match to be skipped.
3744 This variable is semi-obsolete and probably should always be true. It
3745 is better to limit inheritance to certain tags using the variables
3746 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3747 :group 'org-tags
3748 :type '(choice
3749 (const :tag "No, don't list them" nil)
3750 (const :tag "Yes, do list them" t)
3751 (const :tag "List them, indented with leading dots" indented)))
3753 (defcustom org-tags-sort-function nil
3754 "When set, tags are sorted using this function as a comparator."
3755 :group 'org-tags
3756 :type '(choice
3757 (const :tag "No sorting" nil)
3758 (const :tag "Alphabetical" string<)
3759 (const :tag "Reverse alphabetical" string>)
3760 (function :tag "Custom function" nil)))
3762 (defvar org-tags-history nil
3763 "History of minibuffer reads for tags.")
3764 (defvar org-last-tags-completion-table nil
3765 "The last used completion table for tags.")
3766 (defvar org-after-tags-change-hook nil
3767 "Hook that is run after the tags in a line have changed.")
3769 (defgroup org-properties nil
3770 "Options concerning properties in Org mode."
3771 :tag "Org Properties"
3772 :group 'org)
3774 (defcustom org-property-format "%-10s %s"
3775 "How property key/value pairs should be formatted by `indent-line'.
3776 When `indent-line' hits a property definition, it will format the line
3777 according to this format, mainly to make sure that the values are
3778 lined-up with respect to each other."
3779 :group 'org-properties
3780 :type 'string)
3782 (defcustom org-properties-postprocess-alist nil
3783 "Alist of properties and functions to adjust inserted values.
3784 Elements of this alist must be of the form
3786 ([string] [function])
3788 where [string] must be a property name and [function] must be a
3789 lambda expression: this lambda expression must take one argument,
3790 the value to adjust, and return the new value as a string.
3792 For example, this element will allow the property \"Remaining\"
3793 to be updated wrt the relation between the \"Effort\" property
3794 and the clock summary:
3796 ((\"Remaining\" (lambda(value)
3797 (let ((clocksum (org-clock-sum-current-item))
3798 (effort (org-duration-string-to-minutes
3799 (org-entry-get (point) \"Effort\"))))
3800 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3801 :group 'org-properties
3802 :version "24.1"
3803 :type '(alist :key-type (string :tag "Property")
3804 :value-type (function :tag "Function")))
3806 (defcustom org-use-property-inheritance nil
3807 "Non-nil means properties apply also for sublevels.
3809 This setting is chiefly used during property searches. Turning it on can
3810 cause significant overhead when doing a search, which is why it is not
3811 on by default.
3813 When nil, only the properties directly given in the current entry count.
3814 When t, every property is inherited. The value may also be a list of
3815 properties that should have inheritance, or a regular expression matching
3816 properties that should be inherited.
3818 However, note that some special properties use inheritance under special
3819 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3820 and the properties ending in \"_ALL\" when they are used as descriptor
3821 for valid values of a property.
3823 Note for programmers:
3824 When querying an entry with `org-entry-get', you can control if inheritance
3825 should be used. By default, `org-entry-get' looks only at the local
3826 properties. You can request inheritance by setting the inherit argument
3827 to t (to force inheritance) or to `selective' (to respect the setting
3828 in this variable)."
3829 :group 'org-properties
3830 :type '(choice
3831 (const :tag "Not" nil)
3832 (const :tag "Always" t)
3833 (repeat :tag "Specific properties" (string :tag "Property"))
3834 (regexp :tag "Properties matched by regexp")))
3836 (defun org-property-inherit-p (property)
3837 "Return a non-nil value if PROPERTY should be inherited."
3838 (cond
3839 ((eq org-use-property-inheritance t) t)
3840 ((not org-use-property-inheritance) nil)
3841 ((stringp org-use-property-inheritance)
3842 (string-match org-use-property-inheritance property))
3843 ((listp org-use-property-inheritance)
3844 (member-ignore-case property org-use-property-inheritance))
3845 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3847 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3848 "The default column format, if no other format has been defined.
3849 This variable can be set on the per-file basis by inserting a line
3851 #+COLUMNS: %25ITEM ....."
3852 :group 'org-properties
3853 :type 'string)
3855 (defcustom org-columns-ellipses ".."
3856 "The ellipses to be used when a field in column view is truncated.
3857 When this is the empty string, as many characters as possible are shown,
3858 but then there will be no visual indication that the field has been truncated.
3859 When this is a string of length N, the last N characters of a truncated
3860 field are replaced by this string. If the column is narrower than the
3861 ellipses string, only part of the ellipses string will be shown."
3862 :group 'org-properties
3863 :type 'string)
3865 (defconst org-global-properties-fixed
3866 '(("VISIBILITY_ALL" . "folded children content all")
3867 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3868 "List of property/value pairs that can be inherited by any entry.
3870 These are fixed values, for the preset properties. The user variable
3871 that can be used to add to this list is `org-global-properties'.
3873 The entries in this list are cons cells where the car is a property
3874 name and cdr is a string with the value. If the value represents
3875 multiple items like an \"_ALL\" property, separate the items by
3876 spaces.")
3878 (defcustom org-global-properties nil
3879 "List of property/value pairs that can be inherited by any entry.
3881 This list will be combined with the constant `org-global-properties-fixed'.
3883 The entries in this list are cons cells where the car is a property
3884 name and cdr is a string with the value.
3886 You can set buffer-local values for the same purpose in the variable
3887 `org-file-properties' this by adding lines like
3889 #+PROPERTY: NAME VALUE"
3890 :group 'org-properties
3891 :type '(repeat
3892 (cons (string :tag "Property")
3893 (string :tag "Value"))))
3895 (defvar-local org-file-properties nil
3896 "List of property/value pairs that can be inherited by any entry.
3897 Valid for the current buffer.
3898 This variable is populated from #+PROPERTY lines.")
3900 (defgroup org-agenda nil
3901 "Options concerning agenda views in Org mode."
3902 :tag "Org Agenda"
3903 :group 'org)
3905 (defvar-local org-category nil
3906 "Variable used by org files to set a category for agenda display.
3907 Such files should use a file variable to set it, for example
3909 # -*- mode: org; org-category: \"ELisp\"
3911 or contain a special line
3913 #+CATEGORY: ELisp
3915 If the file does not specify a category, then file's base name
3916 is used instead.")
3917 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3919 (defcustom org-agenda-files nil
3920 "The files to be used for agenda display.
3922 If an entry is a directory, all files in that directory that are matched
3923 by `org-agenda-file-regexp' will be part of the file list.
3925 If the value of the variable is not a list but a single file name, then
3926 the list of agenda files is actually stored and maintained in that file,
3927 one agenda file per line. In this file paths can be given relative to
3928 `org-directory'. Tilde expansion and environment variable substitution
3929 are also made.
3931 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3932 and removed with `\\[org-remove-file]'."
3933 :group 'org-agenda
3934 :type '(choice
3935 (repeat :tag "List of files and directories" file)
3936 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3938 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3939 "Regular expression to match files for `org-agenda-files'.
3940 If any element in the list in that variable contains a directory instead
3941 of a normal file, all files in that directory that are matched by this
3942 regular expression will be included."
3943 :group 'org-agenda
3944 :type 'regexp)
3946 (defcustom org-agenda-text-search-extra-files nil
3947 "List of extra files to be searched by text search commands.
3948 These files will be searched in addition to the agenda files by the
3949 commands `org-search-view' (`\\[org-agenda] s') \
3950 and `org-occur-in-agenda-files'.
3951 Note that these files will only be searched for text search commands,
3952 not for the other agenda views like todo lists, tag searches or the weekly
3953 agenda. This variable is intended to list notes and possibly archive files
3954 that should also be searched by these two commands.
3955 In fact, if the first element in the list is the symbol `agenda-archives',
3956 then all archive files of all agenda files will be added to the search
3957 scope."
3958 :group 'org-agenda
3959 :type '(set :greedy t
3960 (const :tag "Agenda Archives" agenda-archives)
3961 (repeat :inline t (file))))
3963 (defvaralias 'org-agenda-multi-occur-extra-files
3964 'org-agenda-text-search-extra-files)
3966 (defcustom org-agenda-skip-unavailable-files nil
3967 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3968 A nil value means to remove them, after a query, from the list."
3969 :group 'org-agenda
3970 :type 'boolean)
3972 (defcustom org-calendar-to-agenda-key [?c]
3973 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3974 The command `org-calendar-goto-agenda' will be bound to this key. The
3975 default is the character `c' because then `c' can be used to switch back and
3976 forth between agenda and calendar."
3977 :group 'org-agenda
3978 :type 'sexp)
3980 (defcustom org-calendar-insert-diary-entry-key [?i]
3981 "The key to be installed in `calendar-mode-map' for adding diary entries.
3982 This option is irrelevant until `org-agenda-diary-file' has been configured
3983 to point to an Org file. When that is the case, the command
3984 `org-agenda-diary-entry' will be bound to the key given here, by default
3985 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3986 if you want to continue doing this, you need to change this to a different
3987 key."
3988 :group 'org-agenda
3989 :type 'sexp)
3991 (defcustom org-agenda-diary-file 'diary-file
3992 "File to which to add new entries with the `i' key in agenda and calendar.
3993 When this is the symbol `diary-file', the functionality in the Emacs
3994 calendar will be used to add entries to the `diary-file'. But when this
3995 points to a file, `org-agenda-diary-entry' will be used instead."
3996 :group 'org-agenda
3997 :type '(choice
3998 (const :tag "The standard Emacs diary file" diary-file)
3999 (file :tag "Special Org file diary entries")))
4001 (eval-after-load "calendar"
4002 '(progn
4003 (org-defkey calendar-mode-map org-calendar-to-agenda-key
4004 'org-calendar-goto-agenda)
4005 (add-hook 'calendar-mode-hook
4006 (lambda ()
4007 (unless (eq org-agenda-diary-file 'diary-file)
4008 (define-key calendar-mode-map
4009 org-calendar-insert-diary-entry-key
4010 'org-agenda-diary-entry))))))
4012 (defgroup org-latex nil
4013 "Options for embedding LaTeX code into Org mode."
4014 :tag "Org LaTeX"
4015 :group 'org)
4017 (defcustom org-format-latex-options
4018 '(:foreground default :background default :scale 1.0
4019 :html-foreground "Black" :html-background "Transparent"
4020 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
4021 "Options for creating images from LaTeX fragments.
4022 This is a property list with the following properties:
4023 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
4024 `default' means use the foreground of the default face.
4025 `auto' means use the foreground from the text face.
4026 :background the background color, or \"Transparent\".
4027 `default' means use the background of the default face.
4028 `auto' means use the background from the text face.
4029 :scale a scaling factor for the size of the images, to get more pixels
4030 :html-foreground, :html-background, :html-scale
4031 the same numbers for HTML export.
4032 :matchers a list indicating which matchers should be used to
4033 find LaTeX fragments. Valid members of this list are:
4034 \"begin\" find environments
4035 \"$1\" find single characters surrounded by $.$
4036 \"$\" find math expressions surrounded by $...$
4037 \"$$\" find math expressions surrounded by $$....$$
4038 \"\\(\" find math expressions surrounded by \\(...\\)
4039 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
4040 :group 'org-latex
4041 :type 'plist)
4043 (defcustom org-format-latex-signal-error t
4044 "Non-nil means signal an error when image creation of LaTeX snippets fails.
4045 When nil, just push out a message."
4046 :group 'org-latex
4047 :version "24.1"
4048 :type 'boolean)
4050 (defcustom org-latex-to-mathml-jar-file nil
4051 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
4052 Use this to specify additional executable file say a jar file.
4054 When using MathToWeb as the converter, specify the full-path to
4055 your mathtoweb.jar file."
4056 :group 'org-latex
4057 :version "24.1"
4058 :type '(choice
4059 (const :tag "None" nil)
4060 (file :tag "JAR file" :must-match t)))
4062 (defcustom org-latex-to-mathml-convert-command nil
4063 "Command to convert LaTeX fragments to MathML.
4064 Replace format-specifiers in the command as noted below and use
4065 `shell-command' to convert LaTeX to MathML.
4066 %j: Executable file in fully expanded form as specified by
4067 `org-latex-to-mathml-jar-file'.
4068 %I: Input LaTeX file in fully expanded form.
4069 %i: The latex fragment to be converted.
4070 %o: Output MathML file.
4072 This command is used by `org-create-math-formula'.
4074 When using MathToWeb as the converter, set this option to
4075 \"java -jar %j -unicode -force -df %o %I\".
4077 When using LaTeXML set this option to
4078 \"latexmlmath \"%i\" --presentationmathml=%o\"."
4079 :group 'org-latex
4080 :version "24.1"
4081 :type '(choice
4082 (const :tag "None" nil)
4083 (string :tag "\nShell command")))
4085 (defcustom org-preview-latex-default-process 'dvipng
4086 "The default process to convert LaTeX fragments to image files.
4087 All available processes and theirs documents can be found in
4088 `org-preview-latex-process-alist', which see."
4089 :group 'org-latex
4090 :version "26.1"
4091 :package-version '(Org . "9.0")
4092 :type 'symbol)
4094 (defcustom org-preview-latex-process-alist
4095 '((dvipng
4096 :programs ("latex" "dvipng")
4097 :description "dvi > png"
4098 :message "you need to install the programs: latex and dvipng."
4099 :image-input-type "dvi"
4100 :image-output-type "png"
4101 :image-size-adjust (1.0 . 1.0)
4102 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4103 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
4104 (dvisvgm
4105 :programs ("latex" "dvisvgm")
4106 :description "dvi > svg"
4107 :message "you need to install the programs: latex and dvisvgm."
4108 :use-xcolor t
4109 :image-input-type "dvi"
4110 :image-output-type "svg"
4111 :image-size-adjust (1.7 . 1.5)
4112 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4113 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
4114 (imagemagick
4115 :programs ("latex" "convert")
4116 :description "pdf > png"
4117 :message "you need to install the programs: latex and imagemagick."
4118 :use-xcolor t
4119 :image-input-type "pdf"
4120 :image-output-type "png"
4121 :image-size-adjust (1.0 . 1.0)
4122 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4123 :image-converter
4124 ("convert -density %D -trim -antialias %f -quality 100 %O")))
4125 "Definitions of external processes for LaTeX previewing.
4126 Org mode can use some external commands to generate TeX snippet's images for
4127 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4128 `org-create-formula-image' how to call them.
4130 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4131 PROPERTIES accepts the following attributes:
4133 :programs list of strings, required programs.
4134 :description string, describe the process.
4135 :message string, message it when required programs cannot be found.
4136 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4137 :image-output-type string, output file type of image converter (e.g., \"png\").
4138 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4139 deal with background and foreground color of image.
4140 Otherwise, dvipng style background and foreground color
4141 format are generated. You may then refer to them in
4142 command options with \"%F\" and \"%B\".
4143 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4144 image size showed in buffer and the cdr element is for
4145 HTML file. This option is only useful for process
4146 developers, users should use variable
4147 `org-format-latex-options' instead.
4148 :post-clean list of strings, files matched are to be cleaned up once
4149 the image is generated. When nil, the files with \".dvi\",
4150 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4151 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4152 be cleaned up.
4153 :latex-header list of strings, the LaTeX header of the snippet file.
4154 When nil, the fallback value is used instead, which is
4155 controlled by `org-format-latex-header',
4156 `org-latex-default-packages-alist' and
4157 `org-latex-packages-alist', which see.
4158 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4159 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4160 replaced with values defined below.
4161 :image-converter list of image converter commands strings. Each of them is
4162 given to the shell and supports any of the following
4163 place-holders defined below.
4165 Place-holders used by `:image-converter' and `:latex-compiler':
4167 %f input file name
4168 %b base name of input file
4169 %o base directory of input file
4170 %O absolute output file name
4172 Place-holders only used by `:image-converter':
4174 %F foreground of image
4175 %B background of image
4176 %D dpi, which is used to adjust image size by some processing commands.
4177 %S the image size scale ratio, which is used to adjust image size by some
4178 processing commands."
4179 :group 'org-latex
4180 :version "26.1"
4181 :package-version '(Org . "9.0")
4182 :type '(alist :tag "LaTeX to image backends"
4183 :value-type (plist)))
4185 (defcustom org-preview-latex-image-directory "ltximg/"
4186 "Path to store latex preview images.
4187 A relative path here creates many directories relative to the
4188 processed org files paths. An absolute path puts all preview
4189 images at the same place."
4190 :group 'org-latex
4191 :version "26.1"
4192 :package-version '(Org . "9.0")
4193 :type 'string)
4195 (defun org-format-latex-mathml-available-p ()
4196 "Return t if `org-latex-to-mathml-convert-command' is usable."
4197 (save-match-data
4198 (when (and (boundp 'org-latex-to-mathml-convert-command)
4199 org-latex-to-mathml-convert-command)
4200 (let ((executable (car (split-string
4201 org-latex-to-mathml-convert-command))))
4202 (when (executable-find executable)
4203 (if (string-match
4204 "%j" org-latex-to-mathml-convert-command)
4205 (file-readable-p org-latex-to-mathml-jar-file)
4206 t))))))
4208 (defcustom org-format-latex-header "\\documentclass{article}
4209 \\usepackage[usenames]{color}
4210 \[PACKAGES]
4211 \[DEFAULT-PACKAGES]
4212 \\pagestyle{empty} % do not remove
4213 % The settings below are copied from fullpage.sty
4214 \\setlength{\\textwidth}{\\paperwidth}
4215 \\addtolength{\\textwidth}{-3cm}
4216 \\setlength{\\oddsidemargin}{1.5cm}
4217 \\addtolength{\\oddsidemargin}{-2.54cm}
4218 \\setlength{\\evensidemargin}{\\oddsidemargin}
4219 \\setlength{\\textheight}{\\paperheight}
4220 \\addtolength{\\textheight}{-\\headheight}
4221 \\addtolength{\\textheight}{-\\headsep}
4222 \\addtolength{\\textheight}{-\\footskip}
4223 \\addtolength{\\textheight}{-3cm}
4224 \\setlength{\\topmargin}{1.5cm}
4225 \\addtolength{\\topmargin}{-2.54cm}"
4226 "The document header used for processing LaTeX fragments.
4227 It is imperative that this header make sure that no page number
4228 appears on the page. The package defined in the variables
4229 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4230 will either replace the placeholder \"[PACKAGES]\" in this
4231 header, or they will be appended."
4232 :group 'org-latex
4233 :type 'string)
4235 (defun org-set-packages-alist (var val)
4236 "Set the packages alist and make sure it has 3 elements per entry."
4237 (set var (mapcar (lambda (x)
4238 (if (and (consp x) (= (length x) 2))
4239 (list (car x) (nth 1 x) t)
4241 val)))
4243 (defun org-get-packages-alist (var)
4244 "Get the packages alist and make sure it has 3 elements per entry."
4245 (mapcar (lambda (x)
4246 (if (and (consp x) (= (length x) 2))
4247 (list (car x) (nth 1 x) t)
4249 (default-value var)))
4251 (defcustom org-latex-default-packages-alist
4252 '(("AUTO" "inputenc" t ("pdflatex"))
4253 ("T1" "fontenc" t ("pdflatex"))
4254 ("" "graphicx" t)
4255 ("" "grffile" t)
4256 ("" "longtable" nil)
4257 ("" "wrapfig" nil)
4258 ("" "rotating" nil)
4259 ("normalem" "ulem" t)
4260 ("" "amsmath" t)
4261 ("" "textcomp" t)
4262 ("" "amssymb" t)
4263 ("" "capt-of" nil)
4264 ("" "hyperref" nil))
4265 "Alist of default packages to be inserted in the header.
4267 Change this only if one of the packages here causes an
4268 incompatibility with another package you are using.
4270 The packages in this list are needed by one part or another of
4271 Org mode to function properly:
4273 - inputenc, fontenc: for basic font and character selection
4274 - graphicx: for including images
4275 - grffile: allow periods and spaces in graphics file names
4276 - longtable: For multipage tables
4277 - wrapfig: for figure placement
4278 - rotating: for sideways figures and tables
4279 - ulem: for underline and strike-through
4280 - amsmath: for subscript and superscript and math environments
4281 - textcomp, amssymb: for various symbols used
4282 for interpreting the entities in `org-entities'. You can skip
4283 some of these packages if you don't use any of their symbols.
4284 - capt-of: for captions outside of floats
4285 - hyperref: for cross references
4287 Therefore you should not modify this variable unless you know
4288 what you are doing. The one reason to change it anyway is that
4289 you might be loading some other package that conflicts with one
4290 of the default packages. Each element is either a cell or
4291 a string.
4293 A cell is of the format
4295 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4297 If SNIPPET-FLAG is non-nil, the package also needs to be included
4298 when compiling LaTeX snippets into images for inclusion into
4299 non-LaTeX output. COMPILERS is a list of compilers that should
4300 include the package, see `org-latex-compiler'. If the document
4301 compiler is not in the list, and the list is non-nil, the package
4302 will not be inserted in the final document.
4304 A string will be inserted as-is in the header of the document."
4305 :group 'org-latex
4306 :group 'org-export-latex
4307 :set 'org-set-packages-alist
4308 :get 'org-get-packages-alist
4309 :version "26.1"
4310 :package-version '(Org . "8.3")
4311 :type '(repeat
4312 (choice
4313 (list :tag "options/package pair"
4314 (string :tag "options")
4315 (string :tag "package")
4316 (boolean :tag "Snippet"))
4317 (string :tag "A line of LaTeX"))))
4319 (defcustom org-latex-packages-alist nil
4320 "Alist of packages to be inserted in every LaTeX header.
4322 These will be inserted after `org-latex-default-packages-alist'.
4323 Each element is either a cell or a string.
4325 A cell is of the format:
4327 (\"options\" \"package\" SNIPPET-FLAG)
4329 SNIPPET-FLAG, when non-nil, indicates that this package is also
4330 needed when turning LaTeX snippets into images for inclusion into
4331 non-LaTeX output.
4333 A string will be inserted as-is in the header of the document.
4335 Make sure that you only list packages here which:
4337 - you want in every file;
4338 - do not conflict with the setup in `org-format-latex-header';
4339 - do not conflict with the default packages in
4340 `org-latex-default-packages-alist'."
4341 :group 'org-latex
4342 :group 'org-export-latex
4343 :set 'org-set-packages-alist
4344 :get 'org-get-packages-alist
4345 :type '(repeat
4346 (choice
4347 (list :tag "options/package pair"
4348 (string :tag "options")
4349 (string :tag "package")
4350 (boolean :tag "Snippet"))
4351 (string :tag "A line of LaTeX"))))
4353 (defgroup org-appearance nil
4354 "Settings for Org mode appearance."
4355 :tag "Org Appearance"
4356 :group 'org)
4358 (defcustom org-level-color-stars-only nil
4359 "Non-nil means fontify only the stars in each headline.
4360 When nil, the entire headline is fontified.
4361 Changing it requires restart of `font-lock-mode' to become effective
4362 also in regions already fontified."
4363 :group 'org-appearance
4364 :type 'boolean)
4366 (defcustom org-hide-leading-stars nil
4367 "Non-nil means hide the first N-1 stars in a headline.
4368 This works by using the face `org-hide' for these stars. This
4369 face is white for a light background, and black for a dark
4370 background. You may have to customize the face `org-hide' to
4371 make this work.
4372 Changing it requires restart of `font-lock-mode' to become effective
4373 also in regions already fontified.
4374 You may also set this on a per-file basis by adding one of the following
4375 lines to the buffer:
4377 #+STARTUP: hidestars
4378 #+STARTUP: showstars"
4379 :group 'org-appearance
4380 :type 'boolean)
4382 (defcustom org-hidden-keywords nil
4383 "List of symbols corresponding to keywords to be hidden the org buffer.
4384 For example, a value \\='(title) for this list will make the document's title
4385 appear in the buffer without the initial #+TITLE: keyword."
4386 :group 'org-appearance
4387 :version "24.1"
4388 :type '(set (const :tag "#+AUTHOR" author)
4389 (const :tag "#+DATE" date)
4390 (const :tag "#+EMAIL" email)
4391 (const :tag "#+TITLE" title)))
4393 (defcustom org-custom-properties nil
4394 "List of properties (as strings) with a special meaning.
4395 The default use of these custom properties is to let the user
4396 hide them with `org-toggle-custom-properties-visibility'."
4397 :group 'org-properties
4398 :group 'org-appearance
4399 :version "24.3"
4400 :type '(repeat (string :tag "Property Name")))
4402 (defcustom org-fontify-done-headline nil
4403 "Non-nil means change the face of a headline if it is marked DONE.
4404 Normally, only the TODO/DONE keyword indicates the state of a headline.
4405 When this is non-nil, the headline after the keyword is set to the
4406 `org-headline-done' as an additional indication."
4407 :group 'org-appearance
4408 :type 'boolean)
4410 (defcustom org-fontify-emphasized-text t
4411 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4412 Changing this variable requires a restart of Emacs to take effect."
4413 :group 'org-appearance
4414 :type 'boolean)
4416 (defcustom org-fontify-whole-heading-line nil
4417 "Non-nil means fontify the whole line for headings.
4418 This is useful when setting a background color for the
4419 org-level-* faces."
4420 :group 'org-appearance
4421 :type 'boolean)
4423 (defcustom org-highlight-latex-and-related nil
4424 "Non-nil means highlight LaTeX related syntax in the buffer.
4425 When non nil, the value should be a list containing any of the
4426 following symbols:
4427 `latex' Highlight LaTeX snippets and environments.
4428 `script' Highlight subscript and superscript.
4429 `entities' Highlight entities."
4430 :group 'org-appearance
4431 :version "24.4"
4432 :package-version '(Org . "8.0")
4433 :type '(choice
4434 (const :tag "No highlighting" nil)
4435 (set :greedy t :tag "Highlight"
4436 (const :tag "LaTeX snippets and environments" latex)
4437 (const :tag "Subscript and superscript" script)
4438 (const :tag "Entities" entities))))
4440 (defcustom org-hide-emphasis-markers nil
4441 "Non-nil mean font-lock should hide the emphasis marker characters."
4442 :group 'org-appearance
4443 :type 'boolean)
4445 (defcustom org-hide-macro-markers nil
4446 "Non-nil mean font-lock should hide the brackets marking macro calls."
4447 :group 'org-appearance
4448 :type 'boolean)
4450 (defcustom org-pretty-entities nil
4451 "Non-nil means show entities as UTF8 characters.
4452 When nil, the \\name form remains in the buffer."
4453 :group 'org-appearance
4454 :version "24.1"
4455 :type 'boolean)
4457 (defcustom org-pretty-entities-include-sub-superscripts t
4458 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4459 :group 'org-appearance
4460 :version "24.1"
4461 :type 'boolean)
4463 (defvar org-emph-re nil
4464 "Regular expression for matching emphasis.
4465 After a match, the match groups contain these elements:
4466 0 The match of the full regular expression, including the characters
4467 before and after the proper match
4468 1 The character before the proper match, or empty at beginning of line
4469 2 The proper match, including the leading and trailing markers
4470 3 The leading marker like * or /, indicating the type of highlighting
4471 4 The text between the emphasis markers, not including the markers
4472 5 The character after the match, empty at the end of a line")
4473 (defvar org-verbatim-re nil
4474 "Regular expression for matching verbatim text.")
4475 (defvar org-emphasis-regexp-components) ; defined just below
4476 (defvar org-emphasis-alist) ; defined just below
4477 (defun org-set-emph-re (var val)
4478 "Set variable and compute the emphasis regular expression."
4479 (set var val)
4480 (when (and (boundp 'org-emphasis-alist)
4481 (boundp 'org-emphasis-regexp-components)
4482 org-emphasis-alist org-emphasis-regexp-components)
4483 (let* ((e org-emphasis-regexp-components)
4484 (pre (car e))
4485 (post (nth 1 e))
4486 (border (nth 2 e))
4487 (body (nth 3 e))
4488 (nl (nth 4 e))
4489 (body1 (concat body "*?"))
4490 (markers (mapconcat 'car org-emphasis-alist ""))
4491 (vmarkers (mapconcat
4492 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4493 org-emphasis-alist "")))
4494 ;; make sure special characters appear at the right position in the class
4495 (if (string-match "\\^" markers)
4496 (setq markers (concat (replace-match "" t t markers) "^")))
4497 (if (string-match "-" markers)
4498 (setq markers (concat (replace-match "" t t markers) "-")))
4499 (if (string-match "\\^" vmarkers)
4500 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4501 (if (string-match "-" vmarkers)
4502 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4503 (if (> nl 0)
4504 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4505 (int-to-string nl) "\\}")))
4506 ;; Make the regexp
4507 (setq org-emph-re
4508 (concat "\\([" pre "]\\|^\\)"
4509 "\\("
4510 "\\([" markers "]\\)"
4511 "\\("
4512 "[^" border "]\\|"
4513 "[^" border "]"
4514 body1
4515 "[^" border "]"
4516 "\\)"
4517 "\\3\\)"
4518 "\\([" post "]\\|$\\)"))
4519 (setq org-verbatim-re
4520 (concat "\\([" pre "]\\|^\\)"
4521 "\\("
4522 "\\([" vmarkers "]\\)"
4523 "\\("
4524 "[^" border "]\\|"
4525 "[^" border "]"
4526 body1
4527 "[^" border "]"
4528 "\\)"
4529 "\\3\\)"
4530 "\\([" post "]\\|$\\)")))))
4532 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4533 ;; set this option proved cumbersome. See this message/thread:
4534 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4535 (defvar org-emphasis-regexp-components
4536 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4537 "Components used to build the regular expression for emphasis.
4538 This is a list with five entries. Terminology: In an emphasis string
4539 like \" *strong word* \", we call the initial space PREMATCH, the final
4540 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4541 and \"trong wor\" is the body. The different components in this variable
4542 specify what is allowed/forbidden in each part:
4544 pre Chars allowed as prematch. Beginning of line will be allowed too.
4545 post Chars allowed as postmatch. End of line will be allowed too.
4546 border The chars *forbidden* as border characters.
4547 body-regexp A regexp like \".\" to match a body character. Don't use
4548 non-shy groups here, and don't allow newline here.
4549 newline The maximum number of newlines allowed in an emphasis exp.
4551 You need to reload Org or to restart Emacs after customizing this.")
4553 (defcustom org-emphasis-alist
4554 '(("*" bold)
4555 ("/" italic)
4556 ("_" underline)
4557 ("=" org-verbatim verbatim)
4558 ("~" org-code verbatim)
4559 ("+" (:strike-through t)))
4560 "Alist of characters and faces to emphasize text.
4561 Text starting and ending with a special character will be emphasized,
4562 for example *bold*, _underlined_ and /italic/. This variable sets the
4563 marker characters and the face to be used by font-lock for highlighting
4564 in Org buffers.
4566 You need to reload Org or to restart Emacs after customizing this."
4567 :group 'org-appearance
4568 :set 'org-set-emph-re
4569 :version "24.4"
4570 :package-version '(Org . "8.0")
4571 :type '(repeat
4572 (list
4573 (string :tag "Marker character")
4574 (choice
4575 (face :tag "Font-lock-face")
4576 (plist :tag "Face property list"))
4577 (option (const verbatim)))))
4579 (defvar org-protecting-blocks '("src" "example" "export")
4580 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4581 This is needed for font-lock setup.")
4583 ;;; Functions and variables from their packages
4584 ;; Declared here to avoid compiler warnings
4585 (defvar mark-active)
4587 ;; Various packages
4588 (declare-function calc-eval "calc" (str &optional separator &rest args))
4589 (declare-function calendar-forward-day "cal-move" (arg))
4590 (declare-function calendar-goto-date "cal-move" (date))
4591 (declare-function calendar-goto-today "cal-move" ())
4592 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4593 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4594 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4595 (declare-function cdlatex-tab "ext:cdlatex" ())
4596 (declare-function dired-get-filename
4597 "dired"
4598 (&optional localp no-error-if-not-filep))
4599 (declare-function iswitchb-read-buffer
4600 "iswitchb"
4601 (prompt &optional
4602 default require-match _predicate start matches-set))
4603 (declare-function org-agenda-change-all-lines
4604 "org-agenda"
4605 (newhead hdmarker &optional fixface just-this))
4606 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4607 "org-agenda"
4608 (&optional end))
4609 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4610 (declare-function org-agenda-format-item
4611 "org-agenda"
4612 (extra txt &optional level category tags dotime
4613 remove-re habitp))
4614 (declare-function org-agenda-maybe-redo "org-agenda" ())
4615 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4616 (declare-function org-agenda-save-markers-for-cut-and-paste
4617 "org-agenda"
4618 (beg end))
4619 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4620 (declare-function org-agenda-skip "org-agenda" ())
4621 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4622 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4623 (declare-function org-indent-mode "org-indent" (&optional arg))
4624 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4625 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4626 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4627 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4628 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4629 (declare-function parse-time-string "parse-time" (string))
4630 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4632 (defvar align-mode-rules-list)
4633 (defvar calc-embedded-close-formula)
4634 (defvar calc-embedded-open-formula)
4635 (defvar calc-embedded-open-mode)
4636 (defvar font-lock-unfontify-region-function)
4637 (defvar iswitchb-temp-buflist)
4638 (defvar org-agenda-tags-todo-honor-ignore-options)
4639 (defvar remember-data-file)
4640 (defvar texmathp-why)
4642 ;;;###autoload
4643 (defun turn-on-orgtbl ()
4644 "Unconditionally turn on `orgtbl-mode'."
4645 (require 'org-table)
4646 (orgtbl-mode 1))
4648 (defun org-at-table-p (&optional table-type)
4649 "Non-nil if the cursor is inside an Org table.
4650 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4651 If `org-enable-table-editor' is nil, return nil unconditionally."
4652 (and
4653 org-enable-table-editor
4654 (save-excursion
4655 (beginning-of-line)
4656 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4657 (or (not (derived-mode-p 'org-mode))
4658 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4659 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4661 (defun org-at-table.el-p ()
4662 "Non-nil when point is at a table.el table."
4663 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4664 (let ((element (org-element-at-point)))
4665 (and (eq (org-element-type element) 'table)
4666 (eq (org-element-property :type element) 'table.el)))))
4668 (defun org-at-table-hline-p ()
4669 "Non-nil when point is inside a hline in a table.
4670 Assume point is already in a table. If `org-enable-table-editor'
4671 is nil, return nil unconditionally."
4672 (and org-enable-table-editor
4673 (save-excursion
4674 (beginning-of-line)
4675 (looking-at org-table-hline-regexp))))
4677 (defun org-table-map-tables (function &optional quietly)
4678 "Apply FUNCTION to the start of all tables in the buffer."
4679 (org-with-wide-buffer
4680 (goto-char (point-min))
4681 (while (re-search-forward org-table-any-line-regexp nil t)
4682 (unless quietly
4683 (message "Mapping tables: %d%%"
4684 (floor (* 100.0 (point)) (buffer-size))))
4685 (beginning-of-line 1)
4686 (when (and (looking-at org-table-line-regexp)
4687 ;; Exclude tables in src/example/verbatim/clocktable blocks
4688 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4689 (save-excursion (funcall function))
4690 (or (looking-at org-table-line-regexp)
4691 (forward-char 1)))
4692 (re-search-forward org-table-any-border-regexp nil 1)))
4693 (unless quietly (message "Mapping tables: done")))
4695 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4696 (declare-function org-clock-update-mode-line "org-clock" ())
4697 (declare-function org-resolve-clocks "org-clock"
4698 (&optional also-non-dangling-p prompt last-valid))
4700 (defun org-at-TBLFM-p (&optional pos)
4701 "Non-nil when point (or POS) is in #+TBLFM line."
4702 (save-excursion
4703 (goto-char (or pos (point)))
4704 (beginning-of-line)
4705 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4706 (eq (org-element-type (org-element-at-point)) 'table))))
4708 (defvar org-clock-start-time)
4709 (defvar org-clock-marker (make-marker)
4710 "Marker recording the last clock-in.")
4711 (defvar org-clock-hd-marker (make-marker)
4712 "Marker recording the last clock-in, but the headline position.")
4713 (defvar org-clock-heading ""
4714 "The heading of the current clock entry.")
4715 (defun org-clock-is-active ()
4716 "Return the buffer where the clock is currently running.
4717 Return nil if no clock is running."
4718 (marker-buffer org-clock-marker))
4720 (defun org-check-running-clock ()
4721 "Check if the current buffer contains the running clock.
4722 If yes, offer to stop it and to save the buffer with the changes."
4723 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4724 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4725 (buffer-name))))
4726 (org-clock-out)
4727 (when (y-or-n-p "Save changed buffer?")
4728 (save-buffer))))
4730 (defun org-clocktable-try-shift (dir n)
4731 "Check if this line starts a clock table, if yes, shift the time block."
4732 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4733 (org-clocktable-shift dir n)))
4735 ;;;###autoload
4736 (defun org-clock-persistence-insinuate ()
4737 "Set up hooks for clock persistence."
4738 (require 'org-clock)
4739 (add-hook 'org-mode-hook 'org-clock-load)
4740 (add-hook 'kill-emacs-hook 'org-clock-save))
4742 (defgroup org-archive nil
4743 "Options concerning archiving in Org mode."
4744 :tag "Org Archive"
4745 :group 'org-structure)
4747 (defcustom org-archive-location "%s_archive::"
4748 "The location where subtrees should be archived.
4750 The value of this variable is a string, consisting of two parts,
4751 separated by a double-colon. The first part is a filename and
4752 the second part is a headline.
4754 When the filename is omitted, archiving happens in the same file.
4755 %s in the filename will be replaced by the current file
4756 name (without the directory part). Archiving to a different file
4757 is useful to keep archived entries from contributing to the
4758 Org Agenda.
4760 The archived entries will be filed as subtrees of the specified
4761 headline. When the headline is omitted, the subtrees are simply
4762 filed away at the end of the file, as top-level entries. Also in
4763 the heading you can use %s to represent the file name, this can be
4764 useful when using the same archive for a number of different files.
4766 Here are a few examples:
4767 \"%s_archive::\"
4768 If the current file is Projects.org, archive in file
4769 Projects.org_archive, as top-level trees. This is the default.
4771 \"::* Archived Tasks\"
4772 Archive in the current file, under the top-level headline
4773 \"* Archived Tasks\".
4775 \"~/org/archive.org::\"
4776 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4778 \"~/org/archive.org::* From %s\"
4779 Archive in file ~/org/archive.org (absolute path), under headlines
4780 \"From FILENAME\" where file name is the current file name.
4782 \"~/org/datetree.org::datetree/* Finished Tasks\"
4783 The \"datetree/\" string is special, signifying to archive
4784 items to the datetree. Items are placed in either the CLOSED
4785 date of the item, or the current date if there is no CLOSED date.
4786 The heading will be a subentry to the current date. There doesn't
4787 need to be a heading, but there always needs to be a slash after
4788 datetree. For example, to store archived items directly in the
4789 datetree, use \"~/org/datetree.org::datetree/\".
4791 \"basement::** Finished Tasks\"
4792 Archive in file ./basement (relative path), as level 3 trees
4793 below the level 2 heading \"** Finished Tasks\".
4795 You may set this option on a per-file basis by adding to the buffer a
4796 line like
4798 #+ARCHIVE: basement::** Finished Tasks
4800 You may also define it locally for a subtree by setting an ARCHIVE property
4801 in the entry. If such a property is found in an entry, or anywhere up
4802 the hierarchy, it will be used."
4803 :group 'org-archive
4804 :type 'string)
4806 (defcustom org-agenda-skip-archived-trees t
4807 "Non-nil means the agenda will skip any items located in archived trees.
4808 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4809 variable is no longer recommended, you should leave it at the value t.
4810 Instead, use the key `v' to cycle the archives-mode in the agenda."
4811 :group 'org-archive
4812 :group 'org-agenda-skip
4813 :type 'boolean)
4815 (defcustom org-columns-skip-archived-trees t
4816 "Non-nil means ignore archived trees when creating column view."
4817 :group 'org-archive
4818 :group 'org-properties
4819 :type 'boolean)
4821 (defcustom org-cycle-open-archived-trees nil
4822 "Non-nil means `org-cycle' will open archived trees.
4823 An archived tree is a tree marked with the tag ARCHIVE.
4824 When nil, archived trees will stay folded. You can still open them with
4825 normal outline commands like `show-all', but not with the cycling commands."
4826 :group 'org-archive
4827 :group 'org-cycle
4828 :type 'boolean)
4830 (defcustom org-sparse-tree-open-archived-trees nil
4831 "Non-nil means sparse tree construction shows matches in archived trees.
4832 When nil, matches in these trees are highlighted, but the trees are kept in
4833 collapsed state."
4834 :group 'org-archive
4835 :group 'org-sparse-trees
4836 :type 'boolean)
4838 (defcustom org-sparse-tree-default-date-type nil
4839 "The default date type when building a sparse tree.
4840 When this is nil, a date is a scheduled or a deadline timestamp.
4841 Otherwise, these types are allowed:
4843 all: all timestamps
4844 active: only active timestamps (<...>)
4845 inactive: only inactive timestamps ([...])
4846 scheduled: only scheduled timestamps
4847 deadline: only deadline timestamps"
4848 :type '(choice (const :tag "Scheduled or deadline" nil)
4849 (const :tag "All timestamps" all)
4850 (const :tag "Only active timestamps" active)
4851 (const :tag "Only inactive timestamps" inactive)
4852 (const :tag "Only scheduled timestamps" scheduled)
4853 (const :tag "Only deadline timestamps" deadline)
4854 (const :tag "Only closed timestamps" closed))
4855 :version "26.1"
4856 :package-version '(Org . "8.3")
4857 :group 'org-sparse-trees)
4859 (defun org-cycle-hide-archived-subtrees (state)
4860 "Re-hide all archived subtrees after a visibility state change.
4861 STATE should be one of the symbols listed in the docstring of
4862 `org-cycle-hook'."
4863 (when (and (not org-cycle-open-archived-trees)
4864 (not (memq state '(overview folded))))
4865 (save-excursion
4866 (let* ((globalp (memq state '(contents all)))
4867 (beg (if globalp (point-min) (point)))
4868 (end (if globalp (point-max) (org-end-of-subtree t))))
4869 (org-hide-archived-subtrees beg end)
4870 (goto-char beg)
4871 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4872 (message "%s" (substitute-command-keys
4873 "Subtree is archived and stays closed. Use \
4874 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4876 (defun org-force-cycle-archived ()
4877 "Cycle subtree even if it is archived."
4878 (interactive)
4879 (setq this-command 'org-cycle)
4880 (let ((org-cycle-open-archived-trees t))
4881 (call-interactively 'org-cycle)))
4883 (defun org-hide-archived-subtrees (beg end)
4884 "Re-hide all archived subtrees after a visibility state change."
4885 (org-with-wide-buffer
4886 (let ((case-fold-search nil)
4887 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4888 (goto-char beg)
4889 ;; Include headline point is currently on.
4890 (beginning-of-line)
4891 (while (and (< (point) end) (re-search-forward re end t))
4892 (when (member org-archive-tag (org-get-tags))
4893 (org-flag-subtree t)
4894 (org-end-of-subtree t))))))
4896 (declare-function outline-end-of-heading "outline" ())
4897 (declare-function outline-flag-region "outline" (from to flag))
4898 (defun org-flag-subtree (flag)
4899 (save-excursion
4900 (org-back-to-heading t)
4901 (outline-end-of-heading)
4902 (outline-flag-region (point)
4903 (progn (org-end-of-subtree t) (point))
4904 flag)))
4906 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4908 ;; Declare Column View Code
4910 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4911 (declare-function org-columns-compute "org-colview" (property))
4913 ;; Declare ID code
4915 (declare-function org-id-store-link "org-id")
4916 (declare-function org-id-locations-load "org-id")
4917 (declare-function org-id-locations-save "org-id")
4918 (defvar org-id-track-globally)
4920 ;;; Variables for pre-computed regular expressions, all buffer local
4922 (defvar-local org-todo-regexp nil
4923 "Matches any of the TODO state keywords.
4924 Since TODO keywords are case-sensitive, `case-fold-search' is
4925 expected to be bound to nil when matching against this regexp.")
4927 (defvar-local org-not-done-regexp nil
4928 "Matches any of the TODO state keywords except the last one.
4929 Since TODO keywords are case-sensitive, `case-fold-search' is
4930 expected to be bound to nil when matching against this regexp.")
4932 (defvar-local org-not-done-heading-regexp nil
4933 "Matches a TODO headline that is not done.
4934 Since TODO keywords are case-sensitive, `case-fold-search' is
4935 expected to be bound to nil when matching against this regexp.")
4937 (defvar-local org-todo-line-regexp nil
4938 "Matches a headline and puts TODO state into group 2 if present.
4939 Since TODO keywords are case-sensitive, `case-fold-search' is
4940 expected to be bound to nil when matching against this regexp.")
4942 (defvar-local org-complex-heading-regexp nil
4943 "Matches a headline and puts everything into groups:
4945 group 1: Stars
4946 group 2: The TODO keyword, maybe
4947 group 3: Priority cookie
4948 group 4: True headline
4949 group 5: Tags
4951 Since TODO keywords are case-sensitive, `case-fold-search' is
4952 expected to be bound to nil when matching against this regexp.")
4954 (defvar-local org-complex-heading-regexp-format nil
4955 "Printf format to make regexp to match an exact headline.
4956 This regexp will match the headline of any node which has the
4957 exact headline text that is put into the format, but may have any
4958 TODO state, priority and tags.")
4960 (defvar-local org-todo-line-tags-regexp nil
4961 "Matches a headline and puts TODO state into group 2 if present.
4962 Also put tags into group 4 if tags are present.")
4964 (defconst org-plain-time-of-day-regexp
4965 (concat
4966 "\\(\\<[012]?[0-9]"
4967 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4968 "\\(--?"
4969 "\\(\\<[012]?[0-9]"
4970 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4971 "\\)?")
4972 "Regular expression to match a plain time or time range.
4973 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4974 groups carry important information:
4975 0 the full match
4976 1 the first time, range or not
4977 8 the second time, if it is a range.")
4979 (defconst org-plain-time-extension-regexp
4980 (concat
4981 "\\(\\<[012]?[0-9]"
4982 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4983 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4984 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4985 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4986 groups carry important information:
4987 0 the full match
4988 7 hours of duration
4989 9 minutes of duration")
4991 (defconst org-stamp-time-of-day-regexp
4992 (concat
4993 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4994 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4995 "\\(--?"
4996 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4997 "Regular expression to match a timestamp time or time range.
4998 After a match, the following groups carry important information:
4999 0 the full match
5000 1 date plus weekday, for back referencing to make sure both times are on the same day
5001 2 the first time, range or not
5002 4 the second time, if it is a range.")
5004 (defconst org-startup-options
5005 '(("fold" org-startup-folded t)
5006 ("overview" org-startup-folded t)
5007 ("nofold" org-startup-folded nil)
5008 ("showall" org-startup-folded nil)
5009 ("showeverything" org-startup-folded showeverything)
5010 ("content" org-startup-folded content)
5011 ("indent" org-startup-indented t)
5012 ("noindent" org-startup-indented nil)
5013 ("hidestars" org-hide-leading-stars t)
5014 ("showstars" org-hide-leading-stars nil)
5015 ("odd" org-odd-levels-only t)
5016 ("oddeven" org-odd-levels-only nil)
5017 ("align" org-startup-align-all-tables t)
5018 ("noalign" org-startup-align-all-tables nil)
5019 ("inlineimages" org-startup-with-inline-images t)
5020 ("noinlineimages" org-startup-with-inline-images nil)
5021 ("latexpreview" org-startup-with-latex-preview t)
5022 ("nolatexpreview" org-startup-with-latex-preview nil)
5023 ("customtime" org-display-custom-times t)
5024 ("logdone" org-log-done time)
5025 ("lognotedone" org-log-done note)
5026 ("nologdone" org-log-done nil)
5027 ("lognoteclock-out" org-log-note-clock-out t)
5028 ("nolognoteclock-out" org-log-note-clock-out nil)
5029 ("logrepeat" org-log-repeat state)
5030 ("lognoterepeat" org-log-repeat note)
5031 ("logdrawer" org-log-into-drawer t)
5032 ("nologdrawer" org-log-into-drawer nil)
5033 ("logstatesreversed" org-log-states-order-reversed t)
5034 ("nologstatesreversed" org-log-states-order-reversed nil)
5035 ("nologrepeat" org-log-repeat nil)
5036 ("logreschedule" org-log-reschedule time)
5037 ("lognotereschedule" org-log-reschedule note)
5038 ("nologreschedule" org-log-reschedule nil)
5039 ("logredeadline" org-log-redeadline time)
5040 ("lognoteredeadline" org-log-redeadline note)
5041 ("nologredeadline" org-log-redeadline nil)
5042 ("logrefile" org-log-refile time)
5043 ("lognoterefile" org-log-refile note)
5044 ("nologrefile" org-log-refile nil)
5045 ("fninline" org-footnote-define-inline t)
5046 ("nofninline" org-footnote-define-inline nil)
5047 ("fnlocal" org-footnote-section nil)
5048 ("fnauto" org-footnote-auto-label t)
5049 ("fnprompt" org-footnote-auto-label nil)
5050 ("fnconfirm" org-footnote-auto-label confirm)
5051 ("fnplain" org-footnote-auto-label plain)
5052 ("fnadjust" org-footnote-auto-adjust t)
5053 ("nofnadjust" org-footnote-auto-adjust nil)
5054 ("constcgs" constants-unit-system cgs)
5055 ("constSI" constants-unit-system SI)
5056 ("noptag" org-tag-persistent-alist nil)
5057 ("hideblocks" org-hide-block-startup t)
5058 ("nohideblocks" org-hide-block-startup nil)
5059 ("beamer" org-startup-with-beamer-mode t)
5060 ("entitiespretty" org-pretty-entities t)
5061 ("entitiesplain" org-pretty-entities nil))
5062 "Variable associated with STARTUP options for org-mode.
5063 Each element is a list of three items: the startup options (as written
5064 in the #+STARTUP line), the corresponding variable, and the value to set
5065 this variable to if the option is found. An optional forth element PUSH
5066 means to push this value onto the list in the variable.")
5068 (defcustom org-group-tags t
5069 "When non-nil (the default), use group tags.
5070 This can be turned on/off through `org-toggle-tags-groups'."
5071 :group 'org-tags
5072 :group 'org-startup
5073 :type 'boolean)
5075 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5077 (defun org-toggle-tags-groups ()
5078 "Toggle support for group tags.
5079 Support for group tags is controlled by the option
5080 `org-group-tags', which is non-nil by default."
5081 (interactive)
5082 (setq org-group-tags (not org-group-tags))
5083 (cond ((and (derived-mode-p 'org-agenda-mode)
5084 org-group-tags)
5085 (org-agenda-redo))
5086 ((derived-mode-p 'org-mode)
5087 (let ((org-inhibit-startup t)) (org-mode))))
5088 (message "Groups tags support has been turned %s"
5089 (if org-group-tags "on" "off")))
5091 (defun org-set-regexps-and-options (&optional tags-only)
5092 "Precompute regular expressions used in the current buffer.
5093 When optional argument TAGS-ONLY is non-nil, only compute tags
5094 related expressions."
5095 (when (derived-mode-p 'org-mode)
5096 (let ((alist (org--setup-collect-keywords
5097 (org-make-options-regexp
5098 (append '("FILETAGS" "TAGS" "SETUPFILE")
5099 (and (not tags-only)
5100 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
5101 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
5102 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
5103 ;; Startup options. Get this early since it does change
5104 ;; behavior for other options (e.g., tags).
5105 (let ((startup (cdr (assq 'startup alist))))
5106 (dolist (option startup)
5107 (let ((entry (assoc-string option org-startup-options t)))
5108 (when entry
5109 (let ((var (nth 1 entry))
5110 (val (nth 2 entry)))
5111 (if (not (nth 3 entry)) (set (make-local-variable var) val)
5112 (unless (listp (symbol-value var))
5113 (set (make-local-variable var) nil))
5114 (add-to-list var val)))))))
5115 (setq-local org-file-tags
5116 (mapcar #'org-add-prop-inherited
5117 (cdr (assq 'filetags alist))))
5118 (setq org-current-tag-alist
5119 (append org-tag-persistent-alist
5120 (let ((tags (cdr (assq 'tags alist))))
5121 (if tags (org-tag-string-to-alist tags)
5122 org-tag-alist))))
5123 (setq org-tag-groups-alist
5124 (org-tag-alist-to-groups org-current-tag-alist))
5125 (unless tags-only
5126 ;; File properties.
5127 (setq-local org-file-properties (cdr (assq 'property alist)))
5128 ;; Archive location.
5129 (let ((archive (cdr (assq 'archive alist))))
5130 (when archive (setq-local org-archive-location archive)))
5131 ;; Category.
5132 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
5133 (when cat
5134 (setq-local org-category (intern cat))
5135 (setq-local org-file-properties
5136 (org--update-property-plist
5137 "CATEGORY" cat org-file-properties))))
5138 ;; Columns.
5139 (let ((column (cdr (assq 'columns alist))))
5140 (when column (setq-local org-columns-default-format column)))
5141 ;; Constants.
5142 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
5143 ;; Link abbreviations.
5144 (let ((links (cdr (assq 'link alist))))
5145 (when links (setq org-link-abbrev-alist-local (nreverse links))))
5146 ;; Priorities.
5147 (let ((priorities (cdr (assq 'priorities alist))))
5148 (when priorities
5149 (setq-local org-highest-priority (nth 0 priorities))
5150 (setq-local org-lowest-priority (nth 1 priorities))
5151 (setq-local org-default-priority (nth 2 priorities))))
5152 ;; Scripts.
5153 (let ((scripts (assq 'scripts alist)))
5154 (when scripts
5155 (setq-local org-use-sub-superscripts (cdr scripts))))
5156 ;; TODO keywords.
5157 (setq-local org-todo-kwd-alist nil)
5158 (setq-local org-todo-key-alist nil)
5159 (setq-local org-todo-key-trigger nil)
5160 (setq-local org-todo-keywords-1 nil)
5161 (setq-local org-done-keywords nil)
5162 (setq-local org-todo-heads nil)
5163 (setq-local org-todo-sets nil)
5164 (setq-local org-todo-log-states nil)
5165 (let ((todo-sequences
5166 (or (nreverse (cdr (assq 'todo alist)))
5167 (let ((d (default-value 'org-todo-keywords)))
5168 (if (not (stringp (car d))) d
5169 ;; XXX: Backward compatibility code.
5170 (list (cons org-todo-interpretation d)))))))
5171 (dolist (sequence todo-sequences)
5172 (let* ((sequence (or (run-hook-with-args-until-success
5173 'org-todo-setup-filter-hook sequence)
5174 sequence))
5175 (sequence-type (car sequence))
5176 (keywords (cdr sequence))
5177 (sep (member "|" keywords))
5178 names alist)
5179 (dolist (k (remove "|" keywords))
5180 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5182 (error "Invalid TODO keyword %s" k))
5183 (let ((name (match-string 1 k))
5184 (key (match-string 2 k))
5185 (log (org-extract-log-state-settings k)))
5186 (push name names)
5187 (push (cons name (and key (string-to-char key))) alist)
5188 (when log (push log org-todo-log-states))))
5189 (let* ((names (nreverse names))
5190 (done (if sep (org-remove-keyword-keys (cdr sep))
5191 (last names)))
5192 (head (car names))
5193 (tail (list sequence-type head (car done) (org-last done))))
5194 (add-to-list 'org-todo-heads head 'append)
5195 (push names org-todo-sets)
5196 (setq org-done-keywords (append org-done-keywords done nil))
5197 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5198 (setq org-todo-key-alist
5199 (append org-todo-key-alist
5200 (and alist
5201 (append '((:startgroup))
5202 (nreverse alist)
5203 '((:endgroup))))))
5204 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5205 (setq org-todo-sets (nreverse org-todo-sets)
5206 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5207 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5208 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5209 ;; Compute the regular expressions and other local variables.
5210 ;; Using `org-outline-regexp-bol' would complicate them much,
5211 ;; because of the fixed white space at the end of that string.
5212 (unless org-done-keywords
5213 (setq org-done-keywords
5214 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5215 (setq org-not-done-keywords
5216 (org-delete-all org-done-keywords
5217 (copy-sequence org-todo-keywords-1))
5218 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5219 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5220 org-not-done-heading-regexp
5221 (format org-heading-keyword-regexp-format org-not-done-regexp)
5222 org-todo-line-regexp
5223 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5224 org-complex-heading-regexp
5225 (concat "^\\(\\*+\\)"
5226 "\\(?: +" org-todo-regexp "\\)?"
5227 "\\(?: +\\(\\[#.\\]\\)\\)?"
5228 "\\(?: +\\(.*?\\)\\)??"
5229 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5230 "[ \t]*$")
5231 org-complex-heading-regexp-format
5232 (concat "^\\(\\*+\\)"
5233 "\\(?: +" org-todo-regexp "\\)?"
5234 "\\(?: +\\(\\[#.\\]\\)\\)?"
5235 "\\(?: +"
5236 ;; Stats cookies can be stuck to body.
5237 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5238 "\\(%s\\)"
5239 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5240 "\\)"
5241 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5242 "[ \t]*$")
5243 org-todo-line-tags-regexp
5244 (concat "^\\(\\*+\\)"
5245 "\\(?: +" org-todo-regexp "\\)?"
5246 "\\(?: +\\(.*?\\)\\)??"
5247 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5248 "[ \t]*$"))
5249 (org-compute-latex-and-related-regexp)))))
5251 (defun org--setup-collect-keywords (regexp &optional files alist)
5252 "Return setup keywords values as an alist.
5254 REGEXP matches a subset of setup keywords. FILES is a list of
5255 file names already visited. It is used to avoid circular setup
5256 files. ALIST, when non-nil, is the alist computed so far.
5258 Return value contains the following keys: `archive', `category',
5259 `columns', `constants', `filetags', `link', `priorities',
5260 `property', `scripts', `startup', `tags' and `todo'."
5261 (org-with-wide-buffer
5262 (goto-char (point-min))
5263 (let ((case-fold-search t))
5264 (while (re-search-forward regexp nil t)
5265 (let ((element (org-element-at-point)))
5266 (when (eq (org-element-type element) 'keyword)
5267 (let ((key (org-element-property :key element))
5268 (value (org-element-property :value element)))
5269 (cond
5270 ((equal key "ARCHIVE")
5271 (when (org-string-nw-p value)
5272 (push (cons 'archive value) alist)))
5273 ((equal key "CATEGORY") (push (cons 'category value) alist))
5274 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5275 ((equal key "CONSTANTS")
5276 (let* ((constants (assq 'constants alist))
5277 (store (cdr constants)))
5278 (dolist (pair (org-split-string value))
5279 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5280 pair)
5281 (let* ((name (match-string 1 pair))
5282 (value (match-string 2 pair))
5283 (old (assoc name store)))
5284 (if old (setcdr old value)
5285 (push (cons name value) store)))))
5286 (if constants (setcdr constants store)
5287 (push (cons 'constants store) alist))))
5288 ((equal key "FILETAGS")
5289 (when (org-string-nw-p value)
5290 (let ((old (assq 'filetags alist))
5291 (new (apply #'nconc
5292 (mapcar (lambda (x) (org-split-string x ":"))
5293 (org-split-string value)))))
5294 (if old (setcdr old (append new (cdr old)))
5295 (push (cons 'filetags new) alist)))))
5296 ((equal key "LINK")
5297 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5298 (let ((links (assq 'link alist))
5299 (pair (cons (match-string-no-properties 1 value)
5300 (match-string-no-properties 2 value))))
5301 (if links (push pair (cdr links))
5302 (push (list 'link pair) alist)))))
5303 ((equal key "OPTIONS")
5304 (when (and (org-string-nw-p value)
5305 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5306 (push (cons 'scripts (read (match-string 1 value))) alist)))
5307 ((equal key "PRIORITIES")
5308 (push (cons 'priorities
5309 (let ((prio (org-split-string value)))
5310 (if (< (length prio) 3) '(?A ?C ?B)
5311 (mapcar #'string-to-char prio))))
5312 alist))
5313 ((equal key "PROPERTY")
5314 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5315 (let* ((property (assq 'property alist))
5316 (value (org--update-property-plist
5317 (match-string-no-properties 1 value)
5318 (match-string-no-properties 2 value)
5319 (cdr property))))
5320 (if property (setcdr property value)
5321 (push (cons 'property value) alist)))))
5322 ((equal key "STARTUP")
5323 (let ((startup (assq 'startup alist)))
5324 (if startup
5325 (setcdr startup
5326 (append (cdr startup) (org-split-string value)))
5327 (push (cons 'startup (org-split-string value)) alist))))
5328 ((equal key "TAGS")
5329 (let ((tag-cell (assq 'tags alist)))
5330 (if tag-cell
5331 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5332 (push (cons 'tags value) alist))))
5333 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5334 (let ((todo (assq 'todo alist))
5335 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5336 (org-split-string value))))
5337 (if todo (push value (cdr todo))
5338 (push (list 'todo value) alist))))
5339 ((equal key "SETUPFILE")
5340 (unless buffer-read-only ; Do not check in Gnus messages.
5341 (let ((f (and (org-string-nw-p value)
5342 (expand-file-name
5343 (org-unbracket-string "\"" "\"" value)))))
5344 (when (and f (file-readable-p f) (not (member f files)))
5345 (with-temp-buffer
5346 (setq default-directory (file-name-directory f))
5347 (insert-file-contents f)
5348 (setq alist
5349 ;; Fake Org mode to benefit from cache
5350 ;; without recurring needlessly.
5351 (let ((major-mode 'org-mode))
5352 (org--setup-collect-keywords
5353 regexp (cons f files) alist)))))))))))))))
5354 alist)
5356 (defun org-tag-string-to-alist (s)
5357 "Return tag alist associated to string S.
5358 S is a value for TAGS keyword or produced with
5359 `org-tag-alist-to-string'. Return value is an alist suitable for
5360 `org-tag-alist' or `org-tag-persistent-alist'."
5361 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5362 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5363 "\\|{.+?}\\)" ; regular expression
5364 "\\(?:(\\(.\\))\\)?\\'"))
5365 alist group-flag)
5366 (dolist (tokens lines (cdr (nreverse alist)))
5367 (push '(:newline) alist)
5368 (while tokens
5369 (let ((token (pop tokens)))
5370 (pcase token
5371 ("{"
5372 (push '(:startgroup) alist)
5373 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5374 ("}"
5375 (push '(:endgroup) alist)
5376 (setq group-flag nil))
5377 ("["
5378 (push '(:startgrouptag) alist)
5379 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5380 ("]"
5381 (push '(:endgrouptag) alist)
5382 (setq group-flag nil))
5383 (":"
5384 (push '(:grouptags) alist))
5385 ((guard (string-match tag-re token))
5386 (let ((tag (match-string 1 token))
5387 (key (and (match-beginning 2)
5388 (string-to-char (match-string 2 token)))))
5389 ;; Push all tags in groups, no matter if they already
5390 ;; appear somewhere else in the list.
5391 (when (or group-flag (not (assoc tag alist)))
5392 (push (cons tag key) alist))))))))))
5394 (defun org-tag-alist-to-string (alist &optional skip-key)
5395 "Return tag string associated to ALIST.
5397 ALIST is an alist, as defined in `org-tag-alist' or
5398 `org-tag-persistent-alist', or produced with
5399 `org-tag-string-to-alist'.
5401 Return value is a string suitable as a value for \"TAGS\"
5402 keyword.
5404 When optional argument SKIP-KEY is non-nil, skip selection keys
5405 next to tags."
5406 (mapconcat (lambda (token)
5407 (pcase token
5408 (`(:startgroup) "{")
5409 (`(:endgroup) "}")
5410 (`(:startgrouptag) "[")
5411 (`(:endgrouptag) "]")
5412 (`(:grouptags) ":")
5413 (`(:newline) "\\n")
5414 ((and
5415 (guard (not skip-key))
5416 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5417 (format "%s(%c)" tag key))
5418 (`(,(and tag (pred stringp)) . ,_) tag)
5419 (_ (user-error "Invalid tag token: %S" token))))
5420 alist
5421 " "))
5423 (defun org-tag-alist-to-groups (alist)
5424 "Return group alist from tag ALIST.
5425 ALIST is an alist, as defined in `org-tag-alist' or
5426 `org-tag-persistent-alist', or produced with
5427 `org-tag-string-to-alist'. Return value is an alist following
5428 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5429 a string, summarizing TAGS, as a list of strings."
5430 (let (groups group-status current-group)
5431 (dolist (token alist (nreverse groups))
5432 (pcase token
5433 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5434 (`(,(or :endgroup :endgrouptag))
5435 (when (eq group-status 'append)
5436 (push (nreverse current-group) groups))
5437 (setq group-status nil))
5438 (`(:grouptags) (setq group-status 'append))
5439 ((and `(,tag . ,_) (guard group-status))
5440 (if (eq group-status 'append) (push tag current-group)
5441 (setq current-group (list tag))))
5442 (_ nil)))))
5444 (defun org-file-contents (file &optional noerror)
5445 "Return the contents of FILE, as a string."
5446 (if (and file (file-readable-p file))
5447 (with-temp-buffer
5448 (insert-file-contents file)
5449 (buffer-string))
5450 (funcall (if noerror 'message 'error)
5451 "Cannot read file \"%s\"%s"
5452 file
5453 (let ((from (buffer-file-name (buffer-base-buffer))))
5454 (if from (concat " (referenced in file \"" from "\")") "")))))
5456 (defun org-extract-log-state-settings (x)
5457 "Extract the log state setting from a TODO keyword string.
5458 This will extract info from a string like \"WAIT(w@/!)\"."
5459 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5460 (let ((kw (match-string 1 x))
5461 (log1 (and (match-end 3) (match-string 3 x)))
5462 (log2 (and (match-end 4) (match-string 4 x))))
5463 (and (or log1 log2)
5464 (list kw
5465 (and log1 (if (equal log1 "!") 'time 'note))
5466 (and log2 (if (equal log2 "!") 'time 'note)))))))
5468 (defun org-remove-keyword-keys (list)
5469 "Remove a pair of parenthesis at the end of each string in LIST."
5470 (mapcar (lambda (x)
5471 (if (string-match "(.*)$" x)
5472 (substring x 0 (match-beginning 0))
5474 list))
5476 (defun org-assign-fast-keys (alist)
5477 "Assign fast keys to a keyword-key alist.
5478 Respect keys that are already there."
5479 (let (new e (alt ?0))
5480 (while (setq e (pop alist))
5481 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5482 (cdr e)) ;; Key already assigned.
5483 (push e new)
5484 (let ((clist (string-to-list (downcase (car e))))
5485 (used (append new alist)))
5486 (when (= (car clist) ?@)
5487 (pop clist))
5488 (while (and clist (rassoc (car clist) used))
5489 (pop clist))
5490 (unless clist
5491 (while (rassoc alt used)
5492 (cl-incf alt)))
5493 (push (cons (car e) (or (car clist) alt)) new))))
5494 (nreverse new)))
5496 ;;; Some variables used in various places
5498 (defvar org-window-configuration nil
5499 "Used in various places to store a window configuration.")
5500 (defvar org-selected-window nil
5501 "Used in various places to store a window configuration.")
5502 (defvar org-finish-function nil
5503 "Function to be called when `C-c C-c' is used.
5504 This is for getting out of special buffers like capture.")
5505 (defvar org-last-state)
5507 ;; Defined somewhere in this file, but used before definition.
5508 (defvar org-entities) ;; defined in org-entities.el
5509 (defvar org-struct-menu)
5510 (defvar org-org-menu)
5511 (defvar org-tbl-menu)
5513 ;;;; Define the Org mode
5515 ;; We use a before-change function to check if a table might need
5516 ;; an update.
5517 (defvar org-table-may-need-update t
5518 "Indicates that a table might need an update.
5519 This variable is set by `org-before-change-function'.
5520 `org-table-align' sets it back to nil.")
5521 (defun org-before-change-function (_beg _end)
5522 "Every change indicates that a table might need an update."
5523 (setq org-table-may-need-update t))
5524 (defvar org-mode-map)
5525 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5526 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5527 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5528 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5529 (defvar org-table-buffer-is-an nil)
5531 (defvar bidi-paragraph-direction)
5532 (defvar buffer-face-mode-face)
5534 (require 'outline)
5536 ;; Other stuff we need.
5537 (require 'time-date)
5538 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5539 (require 'easymenu)
5540 (autoload 'easy-menu-add "easymenu")
5541 (require 'overlay)
5543 ;; (require 'org-macs) moved higher up in the file before it is first used
5544 (require 'org-entities)
5545 ;; (require 'org-compat) moved higher up in the file before it is first used
5546 (require 'org-faces)
5547 (require 'org-list)
5548 (require 'org-pcomplete)
5549 (require 'org-src)
5550 (require 'org-footnote)
5551 (require 'org-macro)
5553 ;; babel
5554 (require 'ob)
5556 ;;;###autoload
5557 (define-derived-mode org-mode outline-mode "Org"
5558 "Outline-based notes management and organizer, alias
5559 \"Carsten's outline-mode for keeping track of everything.\"
5561 Org mode develops organizational tasks around a NOTES file which
5562 contains information about projects as plain text. Org mode is
5563 implemented on top of Outline mode, which is ideal to keep the content
5564 of large files well structured. It supports ToDo items, deadlines and
5565 time stamps, which magically appear in the diary listing of the Emacs
5566 calendar. Tables are easily created with a built-in table editor.
5567 Plain text URL-like links connect to websites, emails (VM), Usenet
5568 messages (Gnus), BBDB entries, and any files related to the project.
5569 For printing and sharing of notes, an Org file (or a part of it)
5570 can be exported as a structured ASCII or HTML file.
5572 The following commands are available:
5574 \\{org-mode-map}"
5576 ;; Get rid of Outline menus, they are not needed
5577 ;; Need to do this here because define-derived-mode sets up
5578 ;; the keymap so late. Still, it is a waste to call this each time
5579 ;; we switch another buffer into Org mode.
5580 (define-key org-mode-map [menu-bar headings] 'undefined)
5581 (define-key org-mode-map [menu-bar hide] 'undefined)
5582 (define-key org-mode-map [menu-bar show] 'undefined)
5584 (org-load-modules-maybe)
5585 (org-install-agenda-files-menu)
5586 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5587 (add-to-invisibility-spec '(org-cwidth))
5588 (add-to-invisibility-spec '(org-hide-block . t))
5589 (setq-local outline-regexp org-outline-regexp)
5590 (setq-local outline-level 'org-outline-level)
5591 (setq bidi-paragraph-direction 'left-to-right)
5592 (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
5593 (unless org-display-table
5594 (setq org-display-table (make-display-table)))
5595 (set-display-table-slot
5596 org-display-table 4
5597 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5598 org-ellipsis)))
5599 (setq buffer-display-table org-display-table))
5600 (org-set-regexps-and-options)
5601 (org-set-font-lock-defaults)
5602 (when (and org-tag-faces (not org-tags-special-faces-re))
5603 ;; tag faces set outside customize.... force initialization.
5604 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5605 ;; Calc embedded
5606 (setq-local calc-embedded-open-mode "# ")
5607 ;; Modify a few syntax entries
5608 (modify-syntax-entry ?@ "w")
5609 (modify-syntax-entry ?\" "\"")
5610 (modify-syntax-entry ?\\ "_")
5611 (modify-syntax-entry ?~ "_")
5612 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5613 ;; Activate before-change-function
5614 (setq-local org-table-may-need-update t)
5615 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5616 ;; Check for running clock before killing a buffer
5617 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5618 ;; Initialize macros templates.
5619 (org-macro-initialize-templates)
5620 ;; Initialize radio targets.
5621 (org-update-radio-target-regexp)
5622 ;; Indentation.
5623 (setq-local indent-line-function 'org-indent-line)
5624 (setq-local indent-region-function 'org-indent-region)
5625 ;; Filling and auto-filling.
5626 (org-setup-filling)
5627 ;; Comments.
5628 (org-setup-comments-handling)
5629 ;; Initialize cache.
5630 (org-element-cache-reset)
5631 ;; Beginning/end of defun
5632 (setq-local beginning-of-defun-function 'org-backward-element)
5633 (setq-local end-of-defun-function
5634 (lambda ()
5635 (if (not (org-at-heading-p))
5636 (org-forward-element)
5637 (org-forward-element)
5638 (forward-char -1))))
5639 ;; Next error for sparse trees
5640 (setq-local next-error-function 'org-occur-next-match)
5641 ;; Make sure dependence stuff works reliably, even for users who set it
5642 ;; too late :-(
5643 (if org-enforce-todo-dependencies
5644 (add-hook 'org-blocker-hook
5645 'org-block-todo-from-children-or-siblings-or-parent)
5646 (remove-hook 'org-blocker-hook
5647 'org-block-todo-from-children-or-siblings-or-parent))
5648 (if org-enforce-todo-checkbox-dependencies
5649 (add-hook 'org-blocker-hook
5650 'org-block-todo-from-checkboxes)
5651 (remove-hook 'org-blocker-hook
5652 'org-block-todo-from-checkboxes))
5654 ;; Align options lines
5655 (setq-local
5656 align-mode-rules-list
5657 '((org-in-buffer-settings
5658 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5659 (modes . '(org-mode)))))
5661 ;; Imenu
5662 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5664 ;; Make isearch reveal context
5665 (setq-local outline-isearch-open-invisible-function
5666 (lambda (&rest _) (org-show-context 'isearch)))
5668 ;; Setup the pcomplete hooks
5669 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5670 (setq-local pcomplete-command-name-function 'org-command-at-point)
5671 (setq-local pcomplete-default-completion-function 'ignore)
5672 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5673 (setq-local pcomplete-termination-string "")
5674 (setq-local buffer-face-mode-face 'org-default)
5676 ;; If empty file that did not turn on Org mode automatically, make
5677 ;; it to.
5678 (when (and org-insert-mode-line-in-empty-file
5679 (called-interactively-p 'any)
5680 (= (point-min) (point-max)))
5681 (insert "# -*- mode: org -*-\n\n"))
5682 (unless org-inhibit-startup
5683 (org-unmodified
5684 (when org-startup-with-beamer-mode (org-beamer-mode))
5685 (when org-startup-align-all-tables
5686 (org-table-map-tables #'org-table-align t))
5687 (when org-startup-with-inline-images (org-display-inline-images))
5688 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5689 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5690 (when org-startup-truncated (setq truncate-lines t))
5691 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5692 (org-refresh-effort-properties)))
5693 ;; Try to set `org-hide' face correctly.
5694 (let ((foreground (org-find-invisible-foreground)))
5695 (when foreground
5696 (set-face-foreground 'org-hide foreground))))
5698 ;; Update `customize-package-emacs-version-alist'
5699 (add-to-list 'customize-package-emacs-version-alist
5700 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5701 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5702 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5703 ("9.0" . "26.1")))
5705 (defvar org-mode-transpose-word-syntax-table
5706 (let ((st (make-syntax-table text-mode-syntax-table)))
5707 (dolist (c org-emphasis-alist st)
5708 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5710 (when (fboundp 'abbrev-table-put)
5711 (abbrev-table-put org-mode-abbrev-table
5712 :parents (list text-mode-abbrev-table)))
5714 (defun org-find-invisible-foreground ()
5715 (let ((candidates (remove
5716 "unspecified-bg"
5717 (nconc
5718 (list (face-background 'default)
5719 (face-background 'org-default))
5720 (mapcar
5721 (lambda (alist)
5722 (when (boundp alist)
5723 (cdr (assq 'background-color (symbol-value alist)))))
5724 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5725 (list (face-foreground 'org-hide))))))
5726 (car (remove nil candidates))))
5728 (defun org-current-time (&optional rounding-minutes past)
5729 "Current time, possibly rounded to ROUNDING-MINUTES.
5730 When ROUNDING-MINUTES is not an integer, fall back on the car of
5731 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5732 the rounding returns a past time."
5733 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5734 (car org-time-stamp-rounding-minutes)))
5735 (time (decode-time)) res)
5736 (if (< r 1)
5737 (current-time)
5738 (setq res
5739 (apply 'encode-time
5740 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5741 (nthcdr 2 time))))
5742 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5743 (seconds-to-time (- (float-time res) (* r 60)))
5744 res))))
5746 (defun org-today ()
5747 "Return today date, considering `org-extend-today-until'."
5748 (time-to-days
5749 (time-subtract (current-time)
5750 (list 0 (* 3600 org-extend-today-until) 0))))
5752 ;;;; Font-Lock stuff, including the activators
5754 (defvar org-mouse-map (make-sparse-keymap))
5755 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5756 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5757 (when org-mouse-1-follows-link
5758 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5759 (when org-tab-follows-link
5760 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5761 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5763 (require 'font-lock)
5765 (defconst org-non-link-chars "]\t\n\r<>")
5766 (defvar org-link-types-re nil
5767 "Matches a link that has a url-like prefix like \"http:\"")
5768 (defvar org-link-re-with-space nil
5769 "Matches a link with spaces, optional angular brackets around it.")
5770 (defvar org-link-re-with-space2 nil
5771 "Matches a link with spaces, optional angular brackets around it.")
5772 (defvar org-link-re-with-space3 nil
5773 "Matches a link with spaces, only for internal part in bracket links.")
5774 (defvar org-angle-link-re nil
5775 "Matches link with angular brackets, spaces are allowed.")
5776 (defvar org-plain-link-re nil
5777 "Matches plain link, without spaces.")
5778 (defvar org-bracket-link-regexp nil
5779 "Matches a link in double brackets.")
5780 (defvar org-bracket-link-analytic-regexp nil
5781 "Regular expression used to analyze links.
5782 Here is what the match groups contain after a match:
5783 1: http:
5784 2: http
5785 3: path
5786 4: [desc]
5787 5: desc")
5788 (defvar org-bracket-link-analytic-regexp++ nil
5789 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5790 (defvar org-any-link-re nil
5791 "Regular expression matching any link.")
5793 (defconst org-match-sexp-depth 3
5794 "Number of stacked braces for sub/superscript matching.")
5796 (defun org-create-multibrace-regexp (left right n)
5797 "Create a regular expression which will match a balanced sexp.
5798 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5799 as single character strings.
5800 The regexp returned will match the entire expression including the
5801 delimiters. It will also define a single group which contains the
5802 match except for the outermost delimiters. The maximum depth of
5803 stacked delimiters is N. Escaping delimiters is not possible."
5804 (let* ((nothing (concat "[^" left right "]*?"))
5805 (or "\\|")
5806 (re nothing)
5807 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5808 (while (> n 1)
5809 (setq n (1- n)
5810 re (concat re or next)
5811 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5812 (concat left "\\(" re "\\)" right)))
5814 (defconst org-match-substring-regexp
5815 (concat
5816 "\\(\\S-\\)\\([_^]\\)\\("
5817 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5818 "\\|"
5819 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5820 "\\|"
5821 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5822 "The regular expression matching a sub- or superscript.")
5824 (defconst org-match-substring-with-braces-regexp
5825 (concat
5826 "\\(\\S-\\)\\([_^]\\)"
5827 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5828 "The regular expression matching a sub- or superscript, forcing braces.")
5830 (defun org-make-link-regexps ()
5831 "Update the link regular expressions.
5832 This should be called after the variable `org-link-parameters' has changed."
5833 (let ((types-re (regexp-opt (org-link-types) t)))
5834 (setq org-link-types-re
5835 (concat "\\`" types-re ":")
5836 org-link-re-with-space
5837 (concat "<?" types-re ":"
5838 "\\([^" org-non-link-chars " ]"
5839 "[^" org-non-link-chars "]*"
5840 "[^" org-non-link-chars " ]\\)>?")
5841 org-link-re-with-space2
5842 (concat "<?" types-re ":"
5843 "\\([^" org-non-link-chars " ]"
5844 "[^\t\n\r]*"
5845 "[^" org-non-link-chars " ]\\)>?")
5846 org-link-re-with-space3
5847 (concat "<?" types-re ":"
5848 "\\([^" org-non-link-chars " ]"
5849 "[^\t\n\r]*\\)")
5850 org-angle-link-re
5851 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5852 types-re)
5853 org-plain-link-re
5854 (concat
5855 "\\<" types-re ":"
5856 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5857 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5858 org-bracket-link-regexp
5859 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5860 org-bracket-link-analytic-regexp
5861 (concat
5862 "\\[\\["
5863 "\\(" types-re ":\\)?"
5864 "\\([^]]+\\)"
5865 "\\]"
5866 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5867 "\\]")
5868 org-bracket-link-analytic-regexp++
5869 (concat
5870 "\\[\\["
5871 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5872 "\\([^]]+\\)"
5873 "\\]"
5874 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5875 "\\]")
5876 org-any-link-re
5877 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5878 org-angle-link-re "\\)\\|\\("
5879 org-plain-link-re "\\)"))))
5881 (org-make-link-regexps)
5883 (defvar org-emph-face nil)
5885 (defun org-do-emphasis-faces (limit)
5886 "Run through the buffer and emphasize strings."
5887 (let (rtn a)
5888 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5889 (let* ((border (char-after (match-beginning 3)))
5890 (bre (regexp-quote (char-to-string border))))
5891 (when (and (not (= border (char-after (match-beginning 4))))
5892 (not (string-match-p (concat bre ".*" bre)
5893 (replace-regexp-in-string
5894 "\n" " "
5895 (substring (match-string 2) 1 -1)))))
5896 (setq rtn t)
5897 (setq a (assoc (match-string 3) org-emphasis-alist))
5898 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5899 'face
5900 (nth 1 a))
5901 (and (nth 2 a)
5902 (org-remove-flyspell-overlays-in
5903 (match-beginning 0) (match-end 0)))
5904 (add-text-properties (match-beginning 2) (match-end 2)
5905 '(font-lock-multiline t org-emphasis t))
5906 (when org-hide-emphasis-markers
5907 (add-text-properties (match-end 4) (match-beginning 5)
5908 '(invisible org-link))
5909 (add-text-properties (match-beginning 3) (match-end 3)
5910 '(invisible org-link)))))
5911 (goto-char (1+ (match-beginning 0))))
5912 rtn))
5914 (defun org-emphasize (&optional char)
5915 "Insert or change an emphasis, i.e. a font like bold or italic.
5916 If there is an active region, change that region to a new emphasis.
5917 If there is no region, just insert the marker characters and position
5918 the cursor between them.
5919 CHAR should be the marker character. If it is a space, it means to
5920 remove the emphasis of the selected region.
5921 If CHAR is not given (for example in an interactive call) it will be
5922 prompted for."
5923 (interactive)
5924 (let ((erc org-emphasis-regexp-components)
5925 (string "") beg end move s)
5926 (if (org-region-active-p)
5927 (setq beg (region-beginning)
5928 end (region-end)
5929 string (buffer-substring beg end))
5930 (setq move t))
5932 (unless char
5933 (message "Emphasis marker or tag: [%s]"
5934 (mapconcat #'car org-emphasis-alist ""))
5935 (setq char (read-char-exclusive)))
5936 (if (equal char ?\s)
5937 (setq s ""
5938 move nil)
5939 (unless (assoc (char-to-string char) org-emphasis-alist)
5940 (user-error "No such emphasis marker: \"%c\"" char))
5941 (setq s (char-to-string char)))
5942 (while (and (> (length string) 1)
5943 (equal (substring string 0 1) (substring string -1))
5944 (assoc (substring string 0 1) org-emphasis-alist))
5945 (setq string (substring string 1 -1)))
5946 (setq string (concat s string s))
5947 (when beg (delete-region beg end))
5948 (unless (or (bolp)
5949 (string-match (concat "[" (nth 0 erc) "\n]")
5950 (char-to-string (char-before (point)))))
5951 (insert " "))
5952 (unless (or (eobp)
5953 (string-match (concat "[" (nth 1 erc) "\n]")
5954 (char-to-string (char-after (point)))))
5955 (insert " ") (backward-char 1))
5956 (insert string)
5957 (and move (backward-char 1))))
5959 (defconst org-nonsticky-props
5960 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5962 (defsubst org-rear-nonsticky-at (pos)
5963 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5965 (defun org-activate-links (limit)
5966 "Add link properties to links.
5967 This includes angle, plain, and bracket links."
5968 (catch :exit
5969 (while (re-search-forward org-any-link-re limit t)
5970 (let* ((start (match-beginning 0))
5971 (end (match-end 0))
5972 (style (cond ((eq ?< (char-after start)) 'angle)
5973 ((eq ?\[ (char-after (1+ start))) 'bracket)
5974 (t 'plain))))
5975 (when (and (memq style org-highlight-links)
5976 ;; Do not confuse plain links with tags.
5977 (not (and (eq style 'plain)
5978 (let ((face (get-text-property
5979 (max (1- start) (point-min)) 'face)))
5980 (if (consp face) (memq 'org-tag face)
5981 (eq 'org-tag face))))))
5982 (let* ((link-object (save-excursion
5983 (goto-char start)
5984 (save-match-data (org-element-link-parser))))
5985 (link (org-element-property :raw-link link-object))
5986 (type (org-element-property :type link-object))
5987 (path (org-element-property :path link-object))
5988 (properties ;for link's visible part
5989 (list
5990 'face (pcase (org-link-get-parameter type :face)
5991 ((and (pred functionp) face) (funcall face path))
5992 ((and (pred facep) face) face)
5993 ((and (pred consp) face) face) ;anonymous
5994 (_ 'org-link))
5995 'mouse-face (or (org-link-get-parameter type :mouse-face)
5996 'highlight)
5997 'keymap (or (org-link-get-parameter type :keymap)
5998 org-mouse-map)
5999 'help-echo (pcase (org-link-get-parameter type :help-echo)
6000 ((and (pred stringp) echo) echo)
6001 ((and (pred functionp) echo) echo)
6002 (_ (concat "LINK: " link)))
6003 'htmlize-link (pcase (org-link-get-parameter type
6004 :htmlize-link)
6005 ((and (pred functionp) f) (funcall f))
6006 (_ `(:uri ,link)))
6007 'font-lock-multiline t)))
6008 (org-remove-flyspell-overlays-in start end)
6009 (org-rear-nonsticky-at end)
6010 (if (not (eq 'bracket style))
6011 (add-text-properties start end properties)
6012 ;; Handle invisible parts in bracket links.
6013 (remove-text-properties start end '(invisible nil))
6014 (let ((hidden
6015 (append `(invisible
6016 ,(or (org-link-get-parameter type :display)
6017 'org-link))
6018 properties))
6019 (visible-start (or (match-beginning 4) (match-beginning 2)))
6020 (visible-end (or (match-end 4) (match-end 2))))
6021 (add-text-properties start visible-start hidden)
6022 (add-text-properties visible-start visible-end properties)
6023 (add-text-properties visible-end end hidden)
6024 (org-rear-nonsticky-at visible-start)
6025 (org-rear-nonsticky-at visible-end)))
6026 (let ((f (org-link-get-parameter type :activate-func)))
6027 (when (functionp f)
6028 (funcall f start end path (eq style 'bracket))))
6029 (throw :exit t))))) ;signal success
6030 nil))
6032 (defun org-activate-code (limit)
6033 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
6034 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6035 (remove-text-properties (match-beginning 0) (match-end 0)
6036 '(display t invisible t intangible t))
6039 (defcustom org-src-fontify-natively t
6040 "When non-nil, fontify code in code blocks.
6041 See also the `org-block' face."
6042 :type 'boolean
6043 :version "24.4"
6044 :package-version '(Org . "8.3")
6045 :group 'org-appearance
6046 :group 'org-babel)
6048 (defcustom org-allow-promoting-top-level-subtree nil
6049 "When non-nil, allow promoting a top level subtree.
6050 The leading star of the top level headline will be replaced
6051 by a #."
6052 :type 'boolean
6053 :version "24.1"
6054 :group 'org-appearance)
6056 (defun org-fontify-meta-lines-and-blocks (limit)
6057 (condition-case nil
6058 (org-fontify-meta-lines-and-blocks-1 limit)
6059 (error (message "org-mode fontification error in %S at %d"
6060 (current-buffer)
6061 (line-number-at-pos)))))
6063 (defun org-fontify-meta-lines-and-blocks-1 (limit)
6064 "Fontify #+ lines and blocks."
6065 (let ((case-fold-search t))
6066 (when (re-search-forward
6067 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
6068 limit t)
6069 (let ((beg (match-beginning 0))
6070 (block-start (match-end 0))
6071 (block-end nil)
6072 (lang (match-string 7))
6073 (beg1 (line-beginning-position 2))
6074 (dc1 (downcase (match-string 2)))
6075 (dc3 (downcase (match-string 3)))
6076 end end1 quoting block-type)
6077 (cond
6078 ((and (match-end 4) (equal dc3 "+begin"))
6079 ;; Truly a block
6080 (setq block-type (downcase (match-string 5))
6081 quoting (member block-type org-protecting-blocks))
6082 (when (re-search-forward
6083 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
6084 nil t) ;; on purpose, we look further than LIMIT
6085 (setq end (min (point-max) (match-end 0))
6086 end1 (min (point-max) (1- (match-beginning 0))))
6087 (setq block-end (match-beginning 0))
6088 (when quoting
6089 (org-remove-flyspell-overlays-in beg1 end1)
6090 (remove-text-properties beg end
6091 '(display t invisible t intangible t)))
6092 (add-text-properties
6093 beg end '(font-lock-fontified t font-lock-multiline t))
6094 (add-text-properties beg beg1 '(face org-meta-line))
6095 (org-remove-flyspell-overlays-in beg beg1)
6096 (add-text-properties ; For end_src
6097 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6098 (org-remove-flyspell-overlays-in end1 end)
6099 (cond
6100 ((and lang (not (string= lang "")) org-src-fontify-natively)
6101 (org-src-font-lock-fontify-block lang block-start block-end)
6102 (add-text-properties beg1 block-end '(src-block t)))
6103 (quoting
6104 (add-text-properties beg1 (min (point-max) (1+ end1))
6105 (list 'face
6106 (list :inherit
6107 (let ((face-name
6108 (intern (format "org-block-%s" lang))))
6109 (append (and (facep face-name) (list face-name))
6110 '(org-block))))))) ; end of source block
6111 ((not org-fontify-quote-and-verse-blocks))
6112 ((string= block-type "quote")
6113 (add-face-text-property
6114 beg1 (min (point-max) (1+ end1)) 'org-quote t))
6115 ((string= block-type "verse")
6116 (add-face-text-property
6117 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
6118 (add-text-properties beg beg1 '(face org-block-begin-line))
6119 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6120 '(face org-block-end-line))
6122 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6123 (org-remove-flyspell-overlays-in
6124 (match-beginning 0)
6125 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6126 (add-text-properties
6127 beg (match-end 3)
6128 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6129 '(font-lock-fontified t invisible t)
6130 '(font-lock-fontified t face org-document-info-keyword)))
6131 (add-text-properties
6132 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6133 (if (string-equal dc1 "+title:")
6134 '(font-lock-fontified t face org-document-title)
6135 '(font-lock-fontified t face org-document-info))))
6136 ((string-prefix-p "+caption" dc1)
6137 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6138 (remove-text-properties (match-beginning 0) (match-end 0)
6139 '(display t invisible t intangible t))
6140 ;; Handle short captions.
6141 (save-excursion
6142 (beginning-of-line)
6143 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6144 (add-text-properties (line-beginning-position) (match-end 1)
6145 '(font-lock-fontified t face org-meta-line))
6146 (add-text-properties (match-end 0) (line-end-position)
6147 '(font-lock-fontified t face org-block))
6149 ((member dc3 '(" " ""))
6150 (org-remove-flyspell-overlays-in beg (match-end 0))
6151 (add-text-properties
6152 beg (match-end 0)
6153 '(font-lock-fontified t face font-lock-comment-face)))
6154 (t ;; just any other in-buffer setting, but not indented
6155 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6156 (remove-text-properties (match-beginning 0) (match-end 0)
6157 '(display t invisible t intangible t))
6158 (add-text-properties beg (match-end 0)
6159 '(font-lock-fontified t face org-meta-line))
6160 t))))))
6162 (defun org-fontify-drawers (limit)
6163 "Fontify drawers."
6164 (when (re-search-forward org-drawer-regexp limit t)
6165 (add-text-properties
6166 (match-beginning 0) (match-end 0)
6167 '(font-lock-fontified t face org-special-keyword))
6168 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6171 (defun org-fontify-macros (limit)
6172 "Fontify macros."
6173 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6174 (add-text-properties
6175 (match-beginning 0) (match-end 0)
6176 '(font-lock-fontified t face org-macro))
6177 (when org-hide-macro-markers
6178 (add-text-properties (match-end 2) (match-beginning 2)
6179 '(invisible t))
6180 (add-text-properties (match-beginning 1) (match-end 1)
6181 '(invisible t)))
6182 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6185 (defun org-activate-footnote-links (limit)
6186 "Add text properties for footnotes."
6187 (let ((fn (org-footnote-next-reference-or-definition limit)))
6188 (when fn
6189 (let* ((beg (nth 1 fn))
6190 (end (nth 2 fn))
6191 (label (car fn))
6192 (referencep (/= (line-beginning-position) beg)))
6193 (when (and referencep (nth 3 fn))
6194 (save-excursion
6195 (goto-char beg)
6196 (search-forward (or label "fn:"))
6197 (org-remove-flyspell-overlays-in beg (match-end 0))))
6198 (add-text-properties beg end
6199 (list 'mouse-face 'highlight
6200 'keymap org-mouse-map
6201 'help-echo
6202 (if referencep "Footnote reference"
6203 "Footnote definition")
6204 'font-lock-fontified t
6205 'font-lock-multiline t
6206 'face 'org-footnote))))))
6208 (defun org-activate-dates (limit)
6209 "Add text properties for dates."
6210 (when (and (re-search-forward org-tsr-regexp-both limit t)
6211 (not (equal (char-before (match-beginning 0)) 91)))
6212 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6213 (add-text-properties (match-beginning 0) (match-end 0)
6214 (list 'mouse-face 'highlight
6215 'keymap org-mouse-map))
6216 (org-rear-nonsticky-at (match-end 0))
6217 (when org-display-custom-times
6218 ;; If it's a date range, activate custom time for second date.
6219 (when (match-end 3)
6220 (org-display-custom-time (match-beginning 3) (match-end 3)))
6221 (org-display-custom-time (match-beginning 1) (match-end 1)))
6224 (defvar-local org-target-link-regexp nil
6225 "Regular expression matching radio targets in plain text.")
6227 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6228 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6229 border border border))
6230 "Regular expression matching a link target.")
6232 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6233 "Regular expression matching a radio target.")
6235 (defconst org-any-target-regexp
6236 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6237 "Regular expression matching any target.")
6239 (defun org-activate-target-links (limit)
6240 "Add text properties for target matches."
6241 (when org-target-link-regexp
6242 (let ((case-fold-search t))
6243 (when (re-search-forward org-target-link-regexp limit t)
6244 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6245 (add-text-properties (match-beginning 1) (match-end 1)
6246 (list 'mouse-face 'highlight
6247 'keymap org-mouse-map
6248 'help-echo "Radio target link"
6249 'org-linked-text t))
6250 (org-rear-nonsticky-at (match-end 1))
6251 t))))
6253 (defun org-update-radio-target-regexp ()
6254 "Find all radio targets in this file and update the regular expression.
6255 Also refresh fontification if needed."
6256 (interactive)
6257 (let ((old-regexp org-target-link-regexp)
6258 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6259 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6260 (targets
6261 (org-with-wide-buffer
6262 (goto-char (point-min))
6263 (let (rtn)
6264 (while (re-search-forward org-radio-target-regexp nil t)
6265 ;; Make sure point is really within the object.
6266 (backward-char)
6267 (let ((obj (org-element-context)))
6268 (when (eq (org-element-type obj) 'radio-target)
6269 (cl-pushnew (org-element-property :value obj) rtn
6270 :test #'equal))))
6271 rtn))))
6272 (setq org-target-link-regexp
6273 (and targets
6274 (concat before-re
6275 (mapconcat
6276 (lambda (x)
6277 (replace-regexp-in-string
6278 " +" "\\s-+" (regexp-quote x) t t))
6279 targets
6280 "\\|")
6281 after-re)))
6282 (unless (equal old-regexp org-target-link-regexp)
6283 ;; Clean-up cache.
6284 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6285 ((not org-target-link-regexp) old-regexp)
6287 (concat before-re
6288 (mapconcat
6289 (lambda (re)
6290 (substring re (length before-re)
6291 (- (length after-re))))
6292 (list old-regexp org-target-link-regexp)
6293 "\\|")
6294 after-re)))))
6295 (org-with-wide-buffer
6296 (goto-char (point-min))
6297 (while (re-search-forward regexp nil t)
6298 (org-element-cache-refresh (match-beginning 1)))))
6299 ;; Re fontify buffer.
6300 (when (memq 'radio org-highlight-links)
6301 (org-restart-font-lock)))))
6303 (defun org-hide-wide-columns (limit)
6304 (let (s e)
6305 (setq s (text-property-any (point) (or limit (point-max))
6306 'org-cwidth t))
6307 (when s
6308 (setq e (next-single-property-change s 'org-cwidth))
6309 (add-text-properties s e '(invisible org-cwidth))
6310 (goto-char e)
6311 t)))
6313 (defvar org-latex-and-related-regexp nil
6314 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6316 (defun org-compute-latex-and-related-regexp ()
6317 "Compute regular expression for LaTeX, entities and sub/superscript.
6318 Result depends on variable `org-highlight-latex-and-related'."
6319 (setq-local
6320 org-latex-and-related-regexp
6321 (let* ((re-sub
6322 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6323 ((eq org-use-sub-superscripts '{})
6324 (list org-match-substring-with-braces-regexp))
6325 (org-use-sub-superscripts (list org-match-substring-regexp))))
6326 (re-latex
6327 (when (memq 'latex org-highlight-latex-and-related)
6328 (let ((matchers (plist-get org-format-latex-options :matchers)))
6329 (delq nil
6330 (mapcar (lambda (x)
6331 (and (member (car x) matchers) (nth 1 x)))
6332 org-latex-regexps)))))
6333 (re-entities
6334 (when (memq 'entities org-highlight-latex-and-related)
6335 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6336 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6338 (defun org-do-latex-and-related (limit)
6339 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6340 LIMIT bounds the search for syntax to highlight. Stop at first
6341 highlighted object, if any. Return t if some highlighting was
6342 done, nil otherwise."
6343 (when (org-string-nw-p org-latex-and-related-regexp)
6344 (catch 'found
6345 (while (re-search-forward org-latex-and-related-regexp limit t)
6346 (unless
6347 (cl-some
6348 (lambda (f)
6349 (memq f '(org-code org-verbatim underline org-special-keyword)))
6350 (save-excursion
6351 (goto-char (1+ (match-beginning 0)))
6352 (face-at-point nil t)))
6353 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6354 '(?_ ?^))
6356 0)))
6357 (font-lock-prepend-text-property
6358 (+ offset (match-beginning 0)) (match-end 0)
6359 'face 'org-latex-and-related)
6360 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6361 '(font-lock-multiline t)))
6362 (throw 'found t)))
6363 nil)))
6365 (defun org-restart-font-lock ()
6366 "Restart `font-lock-mode', to force refontification."
6367 (when (and (boundp 'font-lock-mode) font-lock-mode)
6368 (font-lock-mode -1)
6369 (font-lock-mode 1)))
6371 (defun org-activate-tags (limit)
6372 (when (re-search-forward
6373 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6374 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6375 (add-text-properties (match-beginning 1) (match-end 1)
6376 (list 'mouse-face 'highlight
6377 'keymap org-mouse-map))
6378 (org-rear-nonsticky-at (match-end 1))
6381 (defun org-outline-level ()
6382 "Compute the outline level of the heading at point.
6384 If this is called at a normal headline, the level is the number
6385 of stars. Use `org-reduced-level' to remove the effect of
6386 `org-odd-levels'. Unlike to `org-current-level', this function
6387 takes into consideration inlinetasks."
6388 (org-with-wide-buffer
6389 (end-of-line)
6390 (if (re-search-backward org-outline-regexp-bol nil t)
6391 (1- (- (match-end 0) (match-beginning 0)))
6392 0)))
6394 (defvar org-font-lock-keywords nil)
6396 (defsubst org-re-property (property &optional literal allow-null value)
6397 "Return a regexp matching a PROPERTY line.
6399 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6400 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6401 non-nil, match properties even without a value.
6403 Match group 3 is set to the value when it exists. If there is no
6404 value and ALLOW-NULL is non-nil, it is set to the empty string.
6406 With optional argument VALUE, match only property lines with
6407 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6408 unless LITERAL is non-nil."
6409 (concat
6410 "^\\(?4:[ \t]*\\)"
6411 (format "\\(?1::\\(?2:%s\\):\\)"
6412 (if literal property (regexp-quote property)))
6413 (cond (value
6414 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6415 (if literal value (regexp-quote value))))
6416 (allow-null
6417 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6419 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6421 (defconst org-property-re
6422 (org-re-property "\\S-+" 'literal t)
6423 "Regular expression matching a property line.
6424 There are four matching groups:
6425 1: :PROPKEY: including the leading and trailing colon,
6426 2: PROPKEY without the leading and trailing colon,
6427 3: PROPVAL without leading or trailing spaces,
6428 4: the indentation of the current line,
6429 5: trailing whitespace.")
6431 (defvar org-font-lock-hook nil
6432 "Functions to be called for special font lock stuff.")
6434 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6436 (defvar org-font-lock-set-keywords-hook nil
6437 "Functions that can manipulate `org-font-lock-extra-keywords'.
6438 This is called after `org-font-lock-extra-keywords' is defined, but before
6439 it is installed to be used by font lock. This can be useful if something
6440 needs to be inserted at a specific position in the font-lock sequence.")
6442 (defun org-font-lock-hook (limit)
6443 "Run `org-font-lock-hook' within LIMIT."
6444 (run-hook-with-args 'org-font-lock-hook limit))
6446 (defun org-set-font-lock-defaults ()
6447 "Set font lock defaults for the current buffer."
6448 (let* ((em org-fontify-emphasized-text)
6449 (lk org-highlight-links)
6450 (org-font-lock-extra-keywords
6451 (list
6452 ;; Call the hook
6453 '(org-font-lock-hook)
6454 ;; Headlines
6455 `(,(if org-fontify-whole-heading-line
6456 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6457 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6458 (1 (org-get-level-face 1))
6459 (2 (org-get-level-face 2))
6460 (3 (org-get-level-face 3)))
6461 ;; Table lines
6462 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6463 (1 'org-table t))
6464 ;; Table internals
6465 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6466 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6467 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6468 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6469 ;; Drawers
6470 '(org-fontify-drawers)
6471 ;; Properties
6472 (list org-property-re
6473 '(1 'org-special-keyword t)
6474 '(3 'org-property-value t))
6475 ;; Link related fontification.
6476 '(org-activate-links)
6477 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6478 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6479 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6480 (when (memq 'footnote lk) '(org-activate-footnote-links))
6481 ;; Targets.
6482 (list org-any-target-regexp '(0 'org-target t))
6483 ;; Diary sexps.
6484 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6485 ;; Macro
6486 '(org-fontify-macros)
6487 '(org-hide-wide-columns (0 nil append))
6488 ;; TODO keyword
6489 (list (format org-heading-keyword-regexp-format
6490 org-todo-regexp)
6491 '(2 (org-get-todo-face 2) t))
6492 ;; DONE
6493 (if org-fontify-done-headline
6494 (list (format org-heading-keyword-regexp-format
6495 (concat
6496 "\\(?:"
6497 (mapconcat 'regexp-quote org-done-keywords "\\|")
6498 "\\)"))
6499 '(2 'org-headline-done t))
6500 nil)
6501 ;; Priorities
6502 '(org-font-lock-add-priority-faces)
6503 ;; Tags
6504 '(org-font-lock-add-tag-faces)
6505 ;; Tags groups
6506 (when (and org-group-tags org-tag-groups-alist)
6507 (list (concat org-outline-regexp-bol ".+\\(:"
6508 (regexp-opt (mapcar 'car org-tag-groups-alist))
6509 ":\\).*$")
6510 '(1 'org-tag-group prepend)))
6511 ;; Special keywords
6512 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6513 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6514 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6515 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6516 ;; Emphasis
6517 (when em '(org-do-emphasis-faces))
6518 ;; Checkboxes
6519 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6520 1 'org-checkbox prepend)
6521 (when (cdr (assq 'checkbox org-list-automatic-rules))
6522 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6523 (0 (org-get-checkbox-statistics-face) t)))
6524 ;; Description list items
6525 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6526 1 'org-list-dt prepend)
6527 ;; ARCHIVEd headings
6528 (list (concat
6529 org-outline-regexp-bol
6530 "\\(.*:" org-archive-tag ":.*\\)")
6531 '(1 'org-archived prepend))
6532 ;; Specials
6533 '(org-do-latex-and-related)
6534 '(org-fontify-entities)
6535 '(org-raise-scripts)
6536 ;; Code
6537 '(org-activate-code (1 'org-code t))
6538 ;; COMMENT
6539 (list (format
6540 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6541 org-todo-regexp
6542 org-comment-string)
6543 '(9 'org-special-keyword t))
6544 ;; Blocks and meta lines
6545 '(org-fontify-meta-lines-and-blocks))))
6546 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6547 (run-hooks 'org-font-lock-set-keywords-hook)
6548 ;; Now set the full font-lock-keywords
6549 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6550 (setq-local font-lock-defaults
6551 '(org-font-lock-keywords t nil nil backward-paragraph))
6552 (kill-local-variable 'font-lock-keywords)
6553 nil))
6555 (defun org-toggle-pretty-entities ()
6556 "Toggle the composition display of entities as UTF8 characters."
6557 (interactive)
6558 (setq-local org-pretty-entities (not org-pretty-entities))
6559 (org-restart-font-lock)
6560 (if org-pretty-entities
6561 (message "Entities are now displayed as UTF8 characters")
6562 (save-restriction
6563 (widen)
6564 (decompose-region (point-min) (point-max))
6565 (message "Entities are now displayed as plain text"))))
6567 (defvar-local org-custom-properties-overlays nil
6568 "List of overlays used for custom properties.")
6570 (defun org-toggle-custom-properties-visibility ()
6571 "Display or hide properties in `org-custom-properties'."
6572 (interactive)
6573 (if org-custom-properties-overlays
6574 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6575 (setq org-custom-properties-overlays nil))
6576 (when org-custom-properties
6577 (org-with-wide-buffer
6578 (goto-char (point-min))
6579 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6580 (while (re-search-forward regexp nil t)
6581 (let ((end (cdr (save-match-data (org-get-property-block)))))
6582 (when (and end (< (point) end))
6583 ;; Hide first custom property in current drawer.
6584 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6585 (overlay-put o 'invisible t)
6586 (overlay-put o 'org-custom-property t)
6587 (push o org-custom-properties-overlays))
6588 ;; Hide additional custom properties in the same drawer.
6589 (while (re-search-forward regexp end t)
6590 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6591 (overlay-put o 'invisible t)
6592 (overlay-put o 'org-custom-property t)
6593 (push o org-custom-properties-overlays)))))
6594 ;; Each entry is limited to a single property drawer.
6595 (outline-next-heading)))))))
6597 (defun org-fontify-entities (limit)
6598 "Find an entity to fontify."
6599 (let (ee)
6600 (when org-pretty-entities
6601 (catch 'match
6602 ;; "\_ "-family is left out on purpose. Only the first one,
6603 ;; i.e., "\_ ", could be fontified anyway, and it would be
6604 ;; confusing when adding a second white space character.
6605 (while (re-search-forward
6606 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6607 limit t)
6608 (when (and (not (org-at-comment-p))
6609 (setq ee (org-entity-get (match-string 1)))
6610 (= (length (nth 6 ee)) 1))
6611 (let* ((end (if (equal (match-string 2) "{}")
6612 (match-end 2)
6613 (match-end 1))))
6614 (add-text-properties
6615 (match-beginning 0) end
6616 (list 'font-lock-fontified t))
6617 (compose-region (match-beginning 0) end
6618 (nth 6 ee) nil)
6619 (backward-char 1)
6620 (throw 'match t))))
6621 nil))))
6623 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6624 "Fontify string S like in Org mode."
6625 (with-temp-buffer
6626 (insert s)
6627 (let ((org-odd-levels-only odd-levels))
6628 (org-mode)
6629 (org-font-lock-ensure)
6630 (buffer-string))))
6632 (defvar org-m nil)
6633 (defvar org-l nil)
6634 (defvar org-f nil)
6635 (defun org-get-level-face (n)
6636 "Get the right face for match N in font-lock matching of headlines."
6637 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6638 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6639 (if org-cycle-level-faces
6640 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6641 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6642 (cond
6643 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6644 ((eq n 2) org-f)
6645 (t (unless org-level-color-stars-only org-f))))
6647 (defun org-face-from-face-or-color (context inherit face-or-color)
6648 "Create a face list that inherits INHERIT, but sets the foreground color.
6649 When FACE-OR-COLOR is not a string, just return it."
6650 (if (stringp face-or-color)
6651 (list :inherit inherit
6652 (cdr (assoc context org-faces-easy-properties))
6653 face-or-color)
6654 face-or-color))
6656 (defun org-get-todo-face (kwd)
6657 "Get the right face for a TODO keyword KWD.
6658 If KWD is a number, get the corresponding match group."
6659 (when (numberp kwd) (setq kwd (match-string kwd)))
6660 (or (org-face-from-face-or-color
6661 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6662 (and (member kwd org-done-keywords) 'org-done)
6663 'org-todo))
6665 (defun org-get-priority-face (priority)
6666 "Get the right face for PRIORITY.
6667 PRIORITY is a character."
6668 (or (org-face-from-face-or-color
6669 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6670 'org-priority))
6672 (defun org-get-tag-face (tag)
6673 "Get the right face for TAG.
6674 If TAG is a number, get the corresponding match group."
6675 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6676 (or (org-face-from-face-or-color
6677 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6678 'org-tag)))
6680 (defun org-font-lock-add-priority-faces (limit)
6681 "Add the special priority faces."
6682 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6683 (add-text-properties
6684 (match-beginning 1) (match-end 1)
6685 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6686 'font-lock-fontified t))))
6688 (defun org-font-lock-add-tag-faces (limit)
6689 "Add the special tag faces."
6690 (when (and org-tag-faces org-tags-special-faces-re)
6691 (while (re-search-forward org-tags-special-faces-re limit t)
6692 (add-text-properties (match-beginning 1) (match-end 1)
6693 (list 'face (org-get-tag-face 1)
6694 'font-lock-fontified t))
6695 (backward-char 1))))
6697 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6698 "Remove fontification and activation overlays from links."
6699 (font-lock-default-unfontify-region beg end)
6700 (let* ((buffer-undo-list t)
6701 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6702 (inhibit-modification-hooks t)
6703 deactivate-mark buffer-file-name buffer-file-truename)
6704 (decompose-region beg end)
6705 (remove-text-properties beg end
6706 '(mouse-face t keymap t org-linked-text t
6707 invisible t intangible t
6708 org-emphasis t))
6709 (org-remove-font-lock-display-properties beg end)))
6711 (defconst org-script-display '(((raise -0.3) (height 0.7))
6712 ((raise 0.3) (height 0.7))
6713 ((raise -0.5))
6714 ((raise 0.5)))
6715 "Display properties for showing superscripts and subscripts.")
6717 (defun org-remove-font-lock-display-properties (beg end)
6718 "Remove specific display properties that have been added by font lock.
6719 The will remove the raise properties that are used to show superscripts
6720 and subscripts."
6721 (let (next prop)
6722 (while (< beg end)
6723 (setq next (next-single-property-change beg 'display nil end)
6724 prop (get-text-property beg 'display))
6725 (when (member prop org-script-display)
6726 (put-text-property beg next 'display nil))
6727 (setq beg next))))
6729 (defun org-raise-scripts (limit)
6730 "Add raise properties to sub/superscripts."
6731 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6732 (re-search-forward
6733 (if (eq org-use-sub-superscripts t)
6734 org-match-substring-regexp
6735 org-match-substring-with-braces-regexp)
6736 limit t))
6737 (let* ((pos (point)) table-p comment-p
6738 (mpos (match-beginning 3))
6739 (emph-p (get-text-property mpos 'org-emphasis))
6740 (link-p (get-text-property mpos 'mouse-face))
6741 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6742 (goto-char (point-at-bol))
6743 (setq table-p (looking-at-p org-table-dataline-regexp)
6744 comment-p (looking-at-p "^[ \t]*#[ +]"))
6745 (goto-char pos)
6746 ;; Handle a_b^c
6747 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6748 (unless (or comment-p emph-p link-p keyw-p)
6749 (put-text-property (match-beginning 3) (match-end 0)
6750 'display
6751 (if (equal (char-after (match-beginning 2)) ?^)
6752 (nth (if table-p 3 1) org-script-display)
6753 (nth (if table-p 2 0) org-script-display)))
6754 (add-text-properties (match-beginning 2) (match-end 2)
6755 (list 'invisible t
6756 'org-dwidth t 'org-dwidth-n 1))
6757 (if (and (eq (char-after (match-beginning 3)) ?{)
6758 (eq (char-before (match-end 3)) ?}))
6759 (progn
6760 (add-text-properties
6761 (match-beginning 3) (1+ (match-beginning 3))
6762 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6763 (add-text-properties
6764 (1- (match-end 3)) (match-end 3)
6765 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6766 t)))
6768 ;;;; Visibility cycling, including org-goto and indirect buffer
6770 ;;; Cycling
6772 (defvar-local org-cycle-global-status nil)
6773 (put 'org-cycle-global-status 'org-state t)
6774 (defvar-local org-cycle-subtree-status nil)
6775 (put 'org-cycle-subtree-status 'org-state t)
6777 (defvar org-inlinetask-min-level)
6779 (defun org-unlogged-message (&rest args)
6780 "Display a message, but avoid logging it in the *Messages* buffer."
6781 (let ((message-log-max nil))
6782 (apply 'message args)))
6784 ;;;###autoload
6785 (defun org-cycle (&optional arg)
6786 "TAB-action and visibility cycling for Org mode.
6788 This is the command invoked in Org mode by the `TAB' key. Its main
6789 purpose is outline visibility cycling, but it also invokes other actions
6790 in special contexts.
6792 When this function is called with a `\\[universal-argument]' prefix, rotate \
6793 the entire
6794 buffer through 3 states (global cycling)
6795 1. OVERVIEW: Show only top-level headlines.
6796 2. CONTENTS: Show all headlines of all levels, but no body text.
6797 3. SHOW ALL: Show everything.
6799 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6800 switch to the startup visibility,
6801 determined by the variable `org-startup-folded', and by any VISIBILITY
6802 properties in the buffer.
6804 With a `\\[universal-argument] \\[universal-argument] \
6805 \\[universal-argument]' prefix argument, show the entire buffer, including
6806 any drawers.
6808 When inside a table, re-align the table and move to the next field.
6810 When point is at the beginning of a headline, rotate the subtree started
6811 by this line through 3 different states (local cycling)
6812 1. FOLDED: Only the main headline is shown.
6813 2. CHILDREN: The main headline and the direct children are shown.
6814 From this state, you can move to one of the children
6815 and zoom in further.
6816 3. SUBTREE: Show the entire subtree, including body text.
6817 If there is no subtree, switch directly from CHILDREN to FOLDED.
6819 When point is at the beginning of an empty headline and the variable
6820 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6821 of the headline by demoting and promoting it to likely levels. This
6822 speeds up creation document structure by pressing `TAB' once or several
6823 times right after creating a new headline.
6825 When there is a numeric prefix, go up to a heading with level ARG, do
6826 a `show-subtree' and return to the previous cursor position. If ARG
6827 is negative, go up that many levels.
6829 When point is not at the beginning of a headline, execute the global
6830 binding for `TAB', which is re-indenting the line. See the option
6831 `org-cycle-emulate-tab' for details.
6833 As a special case, if point is at the beginning of the buffer and there is
6834 no headline in line 1, this function will act as if called with prefix arg
6835 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6836 prefix arg, but only
6837 if the variable `org-cycle-global-at-bob' is t."
6838 (interactive "P")
6839 (org-load-modules-maybe)
6840 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6841 (and org-cycle-level-after-item/entry-creation
6842 (or (org-cycle-level)
6843 (org-cycle-item-indentation))))
6844 (let* ((limit-level
6845 (or org-cycle-max-level
6846 (and (boundp 'org-inlinetask-min-level)
6847 org-inlinetask-min-level
6848 (1- org-inlinetask-min-level))))
6849 (nstars (and limit-level
6850 (if org-odd-levels-only
6851 (and limit-level (1- (* limit-level 2)))
6852 limit-level)))
6853 (org-outline-regexp
6854 (if (not (derived-mode-p 'org-mode))
6855 outline-regexp
6856 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6857 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6858 (not (looking-at org-outline-regexp))))
6859 (org-cycle-hook
6860 (if bob-special
6861 (delq 'org-optimize-window-after-visibility-change
6862 (copy-sequence org-cycle-hook))
6863 org-cycle-hook))
6864 (pos (point)))
6866 (cond
6868 ((equal arg '(16))
6869 (setq last-command 'dummy)
6870 (org-set-startup-visibility)
6871 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6873 ((equal arg '(64))
6874 (outline-show-all)
6875 (org-unlogged-message "Entire buffer visible, including drawers"))
6877 ((equal arg '(4)) (org-cycle-internal-global))
6879 ;; Try hiding block at point.
6880 ((org-hide-block-toggle-maybe))
6882 ;; Try cdlatex TAB completion
6883 ((org-try-cdlatex-tab))
6885 ;; Table: enter it or move to the next field.
6886 ((org-at-table-p 'any)
6887 (if (org-at-table.el-p)
6888 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6889 Use `\\[org-edit-special]' to edit table.el tables"))
6890 (if arg (org-table-edit-field t)
6891 (org-table-justify-field-maybe)
6892 (call-interactively 'org-table-next-field))))
6894 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6896 ;; Global cycling: delegate to `org-cycle-internal-global'.
6897 (bob-special (org-cycle-internal-global))
6899 ;; Drawers: delegate to `org-flag-drawer'.
6900 ((save-excursion
6901 (beginning-of-line 1)
6902 (looking-at org-drawer-regexp))
6903 (org-flag-drawer ; toggle block visibility
6904 (not (get-char-property (match-end 0) 'invisible))))
6906 ;; Show-subtree, ARG levels up from here.
6907 ((integerp arg)
6908 (save-excursion
6909 (org-back-to-heading)
6910 (outline-up-heading (if (< arg 0) (- arg)
6911 (- (funcall outline-level) arg)))
6912 (org-show-subtree)))
6914 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6915 ((and (featurep 'org-inlinetask)
6916 (org-inlinetask-at-task-p)
6917 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6918 (org-inlinetask-toggle-visibility))
6920 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6921 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6922 (save-excursion (move-beginning-of-line 1)
6923 (looking-at org-outline-regexp)))
6924 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6925 (org-cycle-internal-local))
6927 ;; From there: TAB emulation and template completion.
6928 (buffer-read-only (org-back-to-heading))
6930 ((run-hook-with-args-until-success
6931 'org-tab-after-check-for-cycling-hook))
6933 ((org-try-structure-completion))
6935 ((run-hook-with-args-until-success
6936 'org-tab-before-tab-emulation-hook))
6938 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6939 (or (not (bolp))
6940 (not (looking-at org-outline-regexp))))
6941 (call-interactively (global-key-binding "\t")))
6943 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6944 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6945 (or (and (eq org-cycle-emulate-tab 'white)
6946 (= (match-end 0) (point-at-eol)))
6947 (and (eq org-cycle-emulate-tab 'whitestart)
6948 (>= (match-end 0) pos))))
6950 (eq org-cycle-emulate-tab t))
6951 (call-interactively (global-key-binding "\t")))
6953 (t (save-excursion
6954 (org-back-to-heading)
6955 (org-cycle)))))))
6957 (defun org-cycle-internal-global ()
6958 "Do the global cycling action."
6959 ;; Hack to avoid display of messages for .org attachments in Gnus
6960 (let ((ga (string-match "\\*fontification" (buffer-name))))
6961 (cond
6962 ((and (eq last-command this-command)
6963 (eq org-cycle-global-status 'overview))
6964 ;; We just created the overview - now do table of contents
6965 ;; This can be slow in very large buffers, so indicate action
6966 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6967 (unless ga (org-unlogged-message "CONTENTS..."))
6968 (org-content)
6969 (unless ga (org-unlogged-message "CONTENTS...done"))
6970 (setq org-cycle-global-status 'contents)
6971 (run-hook-with-args 'org-cycle-hook 'contents))
6973 ((and (eq last-command this-command)
6974 (eq org-cycle-global-status 'contents))
6975 ;; We just showed the table of contents - now show everything
6976 (run-hook-with-args 'org-pre-cycle-hook 'all)
6977 (outline-show-all)
6978 (unless ga (org-unlogged-message "SHOW ALL"))
6979 (setq org-cycle-global-status 'all)
6980 (run-hook-with-args 'org-cycle-hook 'all))
6983 ;; Default action: go to overview
6984 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6985 (org-overview)
6986 (unless ga (org-unlogged-message "OVERVIEW"))
6987 (setq org-cycle-global-status 'overview)
6988 (run-hook-with-args 'org-cycle-hook 'overview)))))
6990 (defvar org-called-with-limited-levels nil
6991 "Non-nil when `org-with-limited-levels' is currently active.")
6993 (defun org-invisible-p (&optional pos)
6994 "Non-nil if the character after POS is invisible.
6995 If POS is nil, use `point' instead."
6996 (get-char-property (or pos (point)) 'invisible))
6998 (defun org-cycle-internal-local ()
6999 "Do the local cycling action."
7000 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7001 ;; First, determine end of headline (EOH), end of subtree or item
7002 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7003 (save-excursion
7004 (if (org-at-item-p)
7005 (progn
7006 (beginning-of-line)
7007 (setq struct (org-list-struct))
7008 (setq eoh (point-at-eol))
7009 (setq eos (org-list-get-item-end-before-blank (point) struct))
7010 (setq has-children (org-list-has-child-p (point) struct)))
7011 (org-back-to-heading)
7012 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7013 (setq eos (save-excursion (org-end-of-subtree t t)
7014 (when (bolp) (backward-char)) (point)))
7015 (setq has-children
7016 (or (save-excursion
7017 (let ((level (funcall outline-level)))
7018 (outline-next-heading)
7019 (and (org-at-heading-p t)
7020 (> (funcall outline-level) level))))
7021 (save-excursion
7022 (org-list-search-forward (org-item-beginning-re) eos t)))))
7023 ;; Determine end invisible part of buffer (EOL)
7024 (beginning-of-line 2)
7025 (while (and (not (eobp)) ;This is like `next-line'.
7026 (get-char-property (1- (point)) 'invisible))
7027 (goto-char (next-single-char-property-change (point) 'invisible))
7028 (and (eolp) (beginning-of-line 2)))
7029 (setq eol (point)))
7030 ;; Find out what to do next and set `this-command'
7031 (cond
7032 ((= eos eoh)
7033 ;; Nothing is hidden behind this heading
7034 (unless (org-before-first-heading-p)
7035 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7036 (org-unlogged-message "EMPTY ENTRY")
7037 (setq org-cycle-subtree-status nil)
7038 (save-excursion
7039 (goto-char eos)
7040 (outline-next-heading)
7041 (when (org-invisible-p) (org-flag-heading nil))))
7042 ((and (or (>= eol eos)
7043 (not (string-match "\\S-" (buffer-substring eol eos))))
7044 (or has-children
7045 (not (setq children-skipped
7046 org-cycle-skip-children-state-if-no-children))))
7047 ;; Entire subtree is hidden in one line: children view
7048 (unless (org-before-first-heading-p)
7049 (run-hook-with-args 'org-pre-cycle-hook 'children))
7050 (if (org-at-item-p)
7051 (org-list-set-item-visibility (point-at-bol) struct 'children)
7052 (org-show-entry)
7053 (org-with-limited-levels (org-show-children))
7054 ;; FIXME: This slows down the func way too much.
7055 ;; How keep drawers hidden in subtree anyway?
7056 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
7057 ;; (org-cycle-hide-drawers 'subtree))
7059 ;; Fold every list in subtree to top-level items.
7060 (when (eq org-cycle-include-plain-lists 'integrate)
7061 (save-excursion
7062 (org-back-to-heading)
7063 (while (org-list-search-forward (org-item-beginning-re) eos t)
7064 (beginning-of-line 1)
7065 (let* ((struct (org-list-struct))
7066 (prevs (org-list-prevs-alist struct))
7067 (end (org-list-get-bottom-point struct)))
7068 (dolist (e (org-list-get-all-items (point) struct prevs))
7069 (org-list-set-item-visibility e struct 'folded))
7070 (goto-char (if (< end eos) end eos)))))))
7071 (org-unlogged-message "CHILDREN")
7072 (save-excursion
7073 (goto-char eos)
7074 (outline-next-heading)
7075 (when (org-invisible-p) (org-flag-heading nil)))
7076 (setq org-cycle-subtree-status 'children)
7077 (unless (org-before-first-heading-p)
7078 (run-hook-with-args 'org-cycle-hook 'children)))
7079 ((or children-skipped
7080 (and (eq last-command this-command)
7081 (eq org-cycle-subtree-status 'children)))
7082 ;; We just showed the children, or no children are there,
7083 ;; now show everything.
7084 (unless (org-before-first-heading-p)
7085 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7086 (outline-flag-region eoh eos nil)
7087 (org-unlogged-message
7088 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7089 (setq org-cycle-subtree-status 'subtree)
7090 (unless (org-before-first-heading-p)
7091 (run-hook-with-args 'org-cycle-hook 'subtree)))
7093 ;; Default action: hide the subtree.
7094 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7095 (outline-flag-region eoh eos t)
7096 (org-unlogged-message "FOLDED")
7097 (setq org-cycle-subtree-status 'folded)
7098 (unless (org-before-first-heading-p)
7099 (run-hook-with-args 'org-cycle-hook 'folded))))))
7101 ;;;###autoload
7102 (defun org-global-cycle (&optional arg)
7103 "Cycle the global visibility. For details see `org-cycle'.
7104 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7105 With a numeric prefix, show all headlines up to that level."
7106 (interactive "P")
7107 (let ((org-cycle-include-plain-lists
7108 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7109 (cond
7110 ((integerp arg)
7111 (outline-show-all)
7112 (outline-hide-sublevels arg)
7113 (setq org-cycle-global-status 'contents))
7114 ((equal arg '(4))
7115 (org-set-startup-visibility)
7116 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7118 (org-cycle '(4))))))
7120 (defun org-set-startup-visibility ()
7121 "Set the visibility required by startup options and properties."
7122 (cond
7123 ((eq org-startup-folded t)
7124 (org-overview))
7125 ((eq org-startup-folded 'content)
7126 (org-content))
7127 ((or (eq org-startup-folded 'showeverything)
7128 (eq org-startup-folded nil))
7129 (outline-show-all)))
7130 (unless (eq org-startup-folded 'showeverything)
7131 (when org-hide-block-startup (org-hide-block-all))
7132 (org-set-visibility-according-to-property 'no-cleanup)
7133 (org-cycle-hide-archived-subtrees 'all)
7134 (org-cycle-hide-drawers 'all)
7135 (org-cycle-show-empty-lines t)))
7137 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7138 "Switch subtree visibilities according to :VISIBILITY: property."
7139 (interactive)
7140 (org-with-wide-buffer
7141 (goto-char (point-min))
7142 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7143 (if (not (org-at-property-p)) (outline-next-heading)
7144 (let ((state (match-string 3)))
7145 (save-excursion
7146 (org-back-to-heading t)
7147 (outline-hide-subtree)
7148 (org-reveal)
7149 (cond
7150 ((equal state "folded")
7151 (outline-hide-subtree))
7152 ((equal state "children")
7153 (org-show-hidden-entry)
7154 (org-show-children))
7155 ((equal state "content")
7156 (save-excursion
7157 (save-restriction
7158 (org-narrow-to-subtree)
7159 (org-content))))
7160 ((member state '("all" "showall"))
7161 (outline-show-subtree)))))))
7162 (unless no-cleanup
7163 (org-cycle-hide-archived-subtrees 'all)
7164 (org-cycle-hide-drawers 'all)
7165 (org-cycle-show-empty-lines 'all))))
7167 ;; This function uses outline-regexp instead of the more fundamental
7168 ;; org-outline-regexp so that org-cycle-global works outside of Org
7169 ;; buffers, where outline-regexp is needed.
7170 (defun org-overview ()
7171 "Switch to overview mode, showing only top-level headlines.
7172 This shows all headlines with a level equal or greater than the level
7173 of the first headline in the buffer. This is important, because if the
7174 first headline is not level one, then (hide-sublevels 1) gives confusing
7175 results."
7176 (interactive)
7177 (save-excursion
7178 (let ((level
7179 (save-excursion
7180 (goto-char (point-min))
7181 (when (re-search-forward (concat "^" outline-regexp) nil t)
7182 (goto-char (match-beginning 0))
7183 (funcall outline-level)))))
7184 (and level (outline-hide-sublevels level)))))
7186 (defun org-content (&optional arg)
7187 "Show all headlines in the buffer, like a table of contents.
7188 With numerical argument N, show content up to level N."
7189 (interactive "P")
7190 (org-overview)
7191 (save-excursion
7192 ;; Visit all headings and show their offspring
7193 (and (integerp arg) (org-overview))
7194 (goto-char (point-max))
7195 (catch 'exit
7196 (while (and (progn (condition-case nil
7197 (outline-previous-visible-heading 1)
7198 (error (goto-char (point-min))))
7200 (looking-at org-outline-regexp))
7201 (if (integerp arg)
7202 (org-show-children (1- arg))
7203 (outline-show-branches))
7204 (when (bobp) (throw 'exit nil))))))
7206 (defun org-optimize-window-after-visibility-change (state)
7207 "Adjust the window after a change in outline visibility.
7208 This function is the default value of the hook `org-cycle-hook'."
7209 (when (get-buffer-window (current-buffer))
7210 (cond
7211 ((eq state 'content) nil)
7212 ((eq state 'all) nil)
7213 ((eq state 'folded) nil)
7214 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7215 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7217 (defun org-remove-empty-overlays-at (pos)
7218 "Remove outline overlays that do not contain non-white stuff."
7219 (dolist (o (overlays-at pos))
7220 (and (eq 'outline (overlay-get o 'invisible))
7221 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7222 (overlay-end o))))
7223 (delete-overlay o))))
7225 (defun org-clean-visibility-after-subtree-move ()
7226 "Fix visibility issues after moving a subtree."
7227 ;; First, find a reasonable region to look at:
7228 ;; Start two siblings above, end three below
7229 (let* ((beg (save-excursion
7230 (and (org-get-last-sibling)
7231 (org-get-last-sibling))
7232 (point)))
7233 (end (save-excursion
7234 (and (org-get-next-sibling)
7235 (org-get-next-sibling)
7236 (org-get-next-sibling))
7237 (if (org-at-heading-p)
7238 (point-at-eol)
7239 (point))))
7240 (level (looking-at "\\*+"))
7241 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7242 (save-excursion
7243 (save-restriction
7244 (narrow-to-region beg end)
7245 (when re
7246 ;; Properly fold already folded siblings
7247 (goto-char (point-min))
7248 (while (re-search-forward re nil t)
7249 (when (and (not (org-invisible-p))
7250 (save-excursion
7251 (goto-char (point-at-eol)) (org-invisible-p)))
7252 (outline-hide-entry))))
7253 (org-cycle-show-empty-lines 'overview)
7254 (org-cycle-hide-drawers 'overview)))))
7256 (defun org-cycle-show-empty-lines (state)
7257 "Show empty lines above all visible headlines.
7258 The region to be covered depends on STATE when called through
7259 `org-cycle-hook'. Lisp program can use t for STATE to get the
7260 entire buffer covered. Note that an empty line is only shown if there
7261 are at least `org-cycle-separator-lines' empty lines before the headline."
7262 (when (/= org-cycle-separator-lines 0)
7263 (save-excursion
7264 (let* ((n (abs org-cycle-separator-lines))
7265 (re (cond
7266 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7267 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7268 (t (let ((ns (number-to-string (- n 2))))
7269 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7270 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7271 beg end)
7272 (cond
7273 ((memq state '(overview contents t))
7274 (setq beg (point-min) end (point-max)))
7275 ((memq state '(children folded))
7276 (setq beg (point)
7277 end (progn (org-end-of-subtree t t)
7278 (line-beginning-position 2)))))
7279 (when beg
7280 (goto-char beg)
7281 (while (re-search-forward re end t)
7282 (unless (get-char-property (match-end 1) 'invisible)
7283 (let ((e (match-end 1))
7284 (b (if (>= org-cycle-separator-lines 0)
7285 (match-beginning 1)
7286 (save-excursion
7287 (goto-char (match-beginning 0))
7288 (skip-chars-backward " \t\n")
7289 (line-end-position)))))
7290 (outline-flag-region b e nil))))))))
7291 ;; Never hide empty lines at the end of the file.
7292 (save-excursion
7293 (goto-char (point-max))
7294 (outline-previous-heading)
7295 (outline-end-of-heading)
7296 (when (and (looking-at "[ \t\n]+")
7297 (= (match-end 0) (point-max)))
7298 (outline-flag-region (point) (match-end 0) nil))))
7300 (defun org-show-empty-lines-in-parent ()
7301 "Move to the parent and re-show empty lines before visible headlines."
7302 (save-excursion
7303 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7304 (org-cycle-show-empty-lines context))))
7306 (defun org-files-list ()
7307 "Return `org-agenda-files' list, plus all open Org files.
7308 This is useful for operations that need to scan all of a user's
7309 open and agenda-wise Org files."
7310 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7311 (dolist (buf (buffer-list))
7312 (with-current-buffer buf
7313 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7314 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7315 files))
7317 (defsubst org-entry-beginning-position ()
7318 "Return the beginning position of the current entry."
7319 (save-excursion (org-back-to-heading t) (point)))
7321 (defsubst org-entry-end-position ()
7322 "Return the end position of the current entry."
7323 (save-excursion (outline-next-heading) (point)))
7325 (defun org-cycle-hide-drawers (state &optional exceptions)
7326 "Re-hide all drawers after a visibility state change.
7327 STATE should be one of the symbols listed in the docstring of
7328 `org-cycle-hook'. When non-nil, optional argument EXCEPTIONS is
7329 a list of strings specifying which drawers should not be hidden."
7330 (when (and (derived-mode-p 'org-mode)
7331 (not (memq state '(overview folded contents))))
7332 (save-excursion
7333 (let* ((globalp (eq state 'all))
7334 (beg (if globalp (point-min) (point)))
7335 (end (if globalp (point-max)
7336 (if (eq state 'children)
7337 (save-excursion (outline-next-heading) (point))
7338 (org-end-of-subtree t)))))
7339 (goto-char beg)
7340 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7341 (unless (member-ignore-case (match-string 1) exceptions)
7342 (let ((drawer (org-element-at-point)))
7343 (when (memq (org-element-type drawer) '(drawer property-drawer))
7344 (org-flag-drawer t drawer)
7345 ;; Make sure to skip drawer entirely or we might flag
7346 ;; it another time when matching its ending line with
7347 ;; `org-drawer-regexp'.
7348 (goto-char (org-element-property :end drawer))))))))))
7350 (defun org-flag-drawer (flag &optional element)
7351 "When FLAG is non-nil, hide the drawer we are at.
7352 Otherwise make it visible. When optional argument ELEMENT is
7353 a parsed drawer, as returned by `org-element-at-point', hide or
7354 show that drawer instead."
7355 (let ((drawer (or element
7356 (and (save-excursion
7357 (beginning-of-line)
7358 (looking-at-p org-drawer-regexp))
7359 (org-element-at-point)))))
7360 (when (memq (org-element-type drawer) '(drawer property-drawer))
7361 (let ((post (org-element-property :post-affiliated drawer)))
7362 (save-excursion
7363 (outline-flag-region
7364 (progn (goto-char post) (line-end-position))
7365 (progn (goto-char (org-element-property :end drawer))
7366 (skip-chars-backward " \r\t\n")
7367 (line-end-position))
7368 flag))
7369 ;; When the drawer is hidden away, make sure point lies in
7370 ;; a visible part of the buffer.
7371 (when (and flag (> (line-beginning-position) post))
7372 (goto-char post))))))
7374 (defun org-subtree-end-visible-p ()
7375 "Is the end of the current subtree visible?"
7376 (pos-visible-in-window-p
7377 (save-excursion (org-end-of-subtree t) (point))))
7379 (defun org-first-headline-recenter ()
7380 "Move cursor to the first headline and recenter the headline."
7381 (let ((window (get-buffer-window)))
7382 (when window
7383 (goto-char (point-min))
7384 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7385 (set-window-start window (line-beginning-position))))))
7387 ;;; Saving and restoring visibility
7389 (defun org-outline-overlay-data (&optional use-markers)
7390 "Return a list of the locations of all outline overlays.
7391 These are overlays with the `invisible' property value `outline'.
7392 The return value is a list of cons cells, with start and stop
7393 positions for each overlay.
7394 If USE-MARKERS is set, return the positions as markers."
7395 (let (beg end)
7396 (org-with-wide-buffer
7397 (delq nil
7398 (mapcar (lambda (o)
7399 (when (eq (overlay-get o 'invisible) 'outline)
7400 (setq beg (overlay-start o)
7401 end (overlay-end o))
7402 (and beg end (> end beg)
7403 (if use-markers
7404 (cons (copy-marker beg)
7405 (copy-marker end t))
7406 (cons beg end)))))
7407 (overlays-in (point-min) (point-max)))))))
7409 (defun org-set-outline-overlay-data (data)
7410 "Create visibility overlays for all positions in DATA.
7411 DATA should have been made by `org-outline-overlay-data'."
7412 (org-with-wide-buffer
7413 (outline-show-all)
7414 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7416 ;;; Folding of blocks
7418 (defvar-local org-hide-block-overlays nil
7419 "Overlays hiding blocks.")
7421 (defun org-block-map (function &optional start end)
7422 "Call FUNCTION at the head of all source blocks in the current buffer.
7423 Optional arguments START and END can be used to limit the range."
7424 (let ((start (or start (point-min)))
7425 (end (or end (point-max))))
7426 (save-excursion
7427 (goto-char start)
7428 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7429 (save-excursion
7430 (save-match-data
7431 (goto-char (match-beginning 0))
7432 (funcall function)))))))
7434 (defun org-hide-block-toggle-all ()
7435 "Toggle the visibility of all blocks in the current buffer."
7436 (org-block-map 'org-hide-block-toggle))
7438 (defun org-hide-block-all ()
7439 "Fold all blocks in the current buffer."
7440 (interactive)
7441 (org-show-block-all)
7442 (org-block-map 'org-hide-block-toggle-maybe))
7444 (defun org-show-block-all ()
7445 "Unfold all blocks in the current buffer."
7446 (interactive)
7447 (mapc #'delete-overlay org-hide-block-overlays)
7448 (setq org-hide-block-overlays nil))
7450 (defun org-hide-block-toggle-maybe ()
7451 "Toggle visibility of block at point.
7452 Unlike to `org-hide-block-toggle', this function does not throw
7453 an error. Return a non-nil value when toggling is successful."
7454 (interactive)
7455 (ignore-errors (org-hide-block-toggle)))
7457 (defun org-hide-block-toggle (&optional force)
7458 "Toggle the visibility of the current block.
7459 When optional argument FORCE is `off', make block visible. If it
7460 is non-nil, hide it unconditionally. Throw an error when not at
7461 a block. Return a non-nil value when toggling is successful."
7462 (interactive)
7463 (let ((element (org-element-at-point)))
7464 (unless (memq (org-element-type element)
7465 '(center-block comment-block dynamic-block example-block
7466 export-block quote-block special-block
7467 src-block verse-block))
7468 (user-error "Not at a block"))
7469 (let* ((start (save-excursion
7470 (goto-char (org-element-property :post-affiliated element))
7471 (line-end-position)))
7472 (end (save-excursion
7473 (goto-char (org-element-property :end element))
7474 (skip-chars-backward " \r\t\n")
7475 (line-end-position)))
7476 (overlays (overlays-at start)))
7477 (cond
7478 ;; Do nothing when not before or at the block opening line or
7479 ;; at the block closing line.
7480 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7481 ((and (not (eq force 'off))
7482 (not (memq t (mapcar
7483 (lambda (o)
7484 (eq (overlay-get o 'invisible) 'org-hide-block))
7485 overlays))))
7486 (let ((ov (make-overlay start end)))
7487 (overlay-put ov 'invisible 'org-hide-block)
7488 ;; Make the block accessible to `isearch'.
7489 (overlay-put
7490 ov 'isearch-open-invisible
7491 (lambda (ov)
7492 (when (memq ov org-hide-block-overlays)
7493 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7494 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7495 (delete-overlay ov))))
7496 (push ov org-hide-block-overlays)
7497 ;; When the block is hidden away, make sure point is left in
7498 ;; a visible part of the buffer.
7499 (when (> (line-beginning-position) start)
7500 (goto-char start)
7501 (beginning-of-line))
7502 ;; Signal successful toggling.
7504 ((or (not force) (eq force 'off))
7505 (dolist (ov overlays t)
7506 (when (memq ov org-hide-block-overlays)
7507 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7508 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7509 (delete-overlay ov))))))))
7511 ;; Remove overlays when changing major mode
7512 (add-hook 'org-mode-hook
7513 (lambda () (add-hook 'change-major-mode-hook
7514 'org-show-block-all 'append 'local)))
7516 ;;; Org-goto
7518 (defvar org-goto-window-configuration nil)
7519 (defvar org-goto-marker nil)
7520 (defvar org-goto-map)
7521 (defun org-goto-map ()
7522 "Set the keymap `org-goto'."
7523 (setq org-goto-map
7524 (let ((map (make-sparse-keymap)))
7525 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7526 mouse-drag-region universal-argument org-occur)))
7527 (dolist (cmd cmds)
7528 (substitute-key-definition cmd cmd map global-map)))
7529 (suppress-keymap map)
7530 (org-defkey map "\C-m" 'org-goto-ret)
7531 (org-defkey map [(return)] 'org-goto-ret)
7532 (org-defkey map [(left)] 'org-goto-left)
7533 (org-defkey map [(right)] 'org-goto-right)
7534 (org-defkey map [(control ?g)] 'org-goto-quit)
7535 (org-defkey map "\C-i" 'org-cycle)
7536 (org-defkey map [(tab)] 'org-cycle)
7537 (org-defkey map [(down)] 'outline-next-visible-heading)
7538 (org-defkey map [(up)] 'outline-previous-visible-heading)
7539 (if org-goto-auto-isearch
7540 (if (fboundp 'define-key-after)
7541 (define-key-after map [t] 'org-goto-local-auto-isearch)
7542 nil)
7543 (org-defkey map "q" 'org-goto-quit)
7544 (org-defkey map "n" 'outline-next-visible-heading)
7545 (org-defkey map "p" 'outline-previous-visible-heading)
7546 (org-defkey map "f" 'outline-forward-same-level)
7547 (org-defkey map "b" 'outline-backward-same-level)
7548 (org-defkey map "u" 'outline-up-heading))
7549 (org-defkey map "/" 'org-occur)
7550 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7551 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7552 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7553 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7554 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7555 map)))
7557 (defconst org-goto-help
7558 "Browse buffer copy, to find location or copy text.%s
7559 RET=jump to location C-g=quit and return to previous location
7560 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7562 (defvar org-goto-start-pos) ; dynamically scoped parameter
7564 (defun org-goto (&optional alternative-interface)
7565 "Look up a different location in the current file, keeping current visibility.
7567 When you want look-up or go to a different location in a
7568 document, the fastest way is often to fold the entire buffer and
7569 then dive into the tree. This method has the disadvantage, that
7570 the previous location will be folded, which may not be what you
7571 want.
7573 This command works around this by showing a copy of the current
7574 buffer in an indirect buffer, in overview mode. You can dive
7575 into the tree in that copy, use org-occur and incremental search
7576 to find a location. When pressing RET or `Q', the command
7577 returns to the original buffer in which the visibility is still
7578 unchanged. After RET it will also jump to the location selected
7579 in the indirect buffer and expose the headline hierarchy above.
7581 With a prefix argument, use the alternative interface: e.g., if
7582 `org-goto-interface' is `outline' use `outline-path-completion'."
7583 (interactive "P")
7584 (org-goto-map)
7585 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7586 (org-refile-use-outline-path t)
7587 (org-refile-target-verify-function nil)
7588 (interface
7589 (if (not alternative-interface)
7590 org-goto-interface
7591 (if (eq org-goto-interface 'outline)
7592 'outline-path-completion
7593 'outline)))
7594 (org-goto-start-pos (point))
7595 (selected-point
7596 (if (eq interface 'outline)
7597 (car (org-get-location (current-buffer) org-goto-help))
7598 (let ((pa (org-refile-get-location "Goto")))
7599 (org-refile-check-position pa)
7600 (nth 3 pa)))))
7601 (if selected-point
7602 (progn
7603 (org-mark-ring-push org-goto-start-pos)
7604 (goto-char selected-point)
7605 (when (or (org-invisible-p) (org-invisible-p2))
7606 (org-show-context 'org-goto)))
7607 (message "Quit"))))
7609 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7610 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7611 (defvar org-goto-local-auto-isearch-map) ; defined below
7613 (defun org-get-location (_buf help)
7614 "Let the user select a location in current buffer.
7615 This function uses a recursive edit. It returns the selected position
7616 or nil."
7617 (org-no-popups
7618 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7619 (isearch-hide-immediately nil)
7620 (isearch-search-fun-function
7621 (lambda () 'org-goto-local-search-headings))
7622 (org-goto-selected-point org-goto-exit-command))
7623 (save-excursion
7624 (save-window-excursion
7625 (delete-other-windows)
7626 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7627 (pop-to-buffer-same-window
7628 (condition-case nil
7629 (make-indirect-buffer (current-buffer) "*org-goto*")
7630 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7631 (with-output-to-temp-buffer "*Org Help*"
7632 (princ (format help (if org-goto-auto-isearch
7633 " Just type for auto-isearch."
7634 " n/p/f/b/u to navigate, q to quit."))))
7635 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7636 (setq buffer-read-only nil)
7637 (let ((org-startup-truncated t)
7638 (org-startup-folded nil)
7639 (org-startup-align-all-tables nil))
7640 (org-mode)
7641 (org-overview))
7642 (setq buffer-read-only t)
7643 (if (and (boundp 'org-goto-start-pos)
7644 (integer-or-marker-p org-goto-start-pos))
7645 (progn (goto-char org-goto-start-pos)
7646 (when (org-invisible-p)
7647 (org-show-set-visibility 'lineage)))
7648 (goto-char (point-min)))
7649 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7650 (message "Select location and press RET")
7651 (use-local-map org-goto-map)
7652 (recursive-edit)))
7653 (kill-buffer "*org-goto*")
7654 (cons org-goto-selected-point org-goto-exit-command))))
7656 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7657 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7658 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7659 (if (fboundp 'isearch-other-control-char)
7660 (progn
7661 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7662 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7663 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7664 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7665 (define-key org-goto-local-auto-isearch-map [return] nil))
7667 (defun org-goto-local-search-headings (string bound noerror)
7668 "Search and make sure that any matches are in headlines."
7669 (catch 'return
7670 (while (if isearch-forward
7671 (search-forward string bound noerror)
7672 (search-backward string bound noerror))
7673 (when (save-match-data
7674 (and (save-excursion
7675 (beginning-of-line)
7676 (looking-at org-complex-heading-regexp))
7677 (or (not (match-beginning 5))
7678 (< (point) (match-beginning 5)))))
7679 (throw 'return (point))))))
7681 (defun org-goto-local-auto-isearch ()
7682 "Start isearch."
7683 (interactive)
7684 (goto-char (point-min))
7685 (let ((keys (this-command-keys)))
7686 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7687 (isearch-mode t)
7688 (isearch-process-search-char (string-to-char keys)))))
7690 (defun org-goto-ret (&optional _arg)
7691 "Finish `org-goto' by going to the new location."
7692 (interactive "P")
7693 (setq org-goto-selected-point (point))
7694 (setq org-goto-exit-command 'return)
7695 (throw 'exit nil))
7697 (defun org-goto-left ()
7698 "Finish `org-goto' by going to the new location."
7699 (interactive)
7700 (if (org-at-heading-p)
7701 (progn
7702 (beginning-of-line 1)
7703 (setq org-goto-selected-point (point)
7704 org-goto-exit-command 'left)
7705 (throw 'exit nil))
7706 (user-error "Not on a heading")))
7708 (defun org-goto-right ()
7709 "Finish `org-goto' by going to the new location."
7710 (interactive)
7711 (if (org-at-heading-p)
7712 (progn
7713 (setq org-goto-selected-point (point)
7714 org-goto-exit-command 'right)
7715 (throw 'exit nil))
7716 (user-error "Not on a heading")))
7718 (defun org-goto-quit ()
7719 "Finish `org-goto' without cursor motion."
7720 (interactive)
7721 (setq org-goto-selected-point nil)
7722 (setq org-goto-exit-command 'quit)
7723 (throw 'exit nil))
7725 ;;; Indirect buffer display of subtrees
7727 (defvar org-indirect-dedicated-frame nil
7728 "This is the frame being used for indirect tree display.")
7729 (defvar org-last-indirect-buffer nil)
7731 (defun org-tree-to-indirect-buffer (&optional arg)
7732 "Create indirect buffer and narrow it to current subtree.
7734 With a numerical prefix ARG, go up to this level and then take that tree.
7735 If ARG is negative, go up that many levels.
7737 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7738 indirect buffer previously made with this command, to avoid proliferation of
7739 indirect buffers. However, when you call the command with a \
7740 `\\[universal-argument]' prefix, or
7741 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7742 so that you can work with several indirect buffers at the same time. If
7743 `org-indirect-buffer-display' is `dedicated-frame', the \
7744 `\\[universal-argument]' prefix also
7745 requests that a new frame be made for the new buffer, so that the dedicated
7746 frame is not changed."
7747 (interactive "P")
7748 (let ((cbuf (current-buffer))
7749 (cwin (selected-window))
7750 (pos (point))
7751 beg end level heading ibuf)
7752 (save-excursion
7753 (org-back-to-heading t)
7754 (when (numberp arg)
7755 (setq level (org-outline-level))
7756 (when (< arg 0) (setq arg (+ level arg)))
7757 (while (> (setq level (org-outline-level)) arg)
7758 (org-up-heading-safe)))
7759 (setq beg (point)
7760 heading (org-get-heading 'no-tags))
7761 (org-end-of-subtree t t)
7762 (when (org-at-heading-p) (backward-char 1))
7763 (setq end (point)))
7764 (when (and (buffer-live-p org-last-indirect-buffer)
7765 (not (eq org-indirect-buffer-display 'new-frame))
7766 (not arg))
7767 (kill-buffer org-last-indirect-buffer))
7768 (setq ibuf (org-get-indirect-buffer cbuf heading)
7769 org-last-indirect-buffer ibuf)
7770 (cond
7771 ((or (eq org-indirect-buffer-display 'new-frame)
7772 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7773 (select-frame (make-frame))
7774 (delete-other-windows)
7775 (pop-to-buffer-same-window ibuf)
7776 (org-set-frame-title heading))
7777 ((eq org-indirect-buffer-display 'dedicated-frame)
7778 (raise-frame
7779 (select-frame (or (and org-indirect-dedicated-frame
7780 (frame-live-p org-indirect-dedicated-frame)
7781 org-indirect-dedicated-frame)
7782 (setq org-indirect-dedicated-frame (make-frame)))))
7783 (delete-other-windows)
7784 (pop-to-buffer-same-window ibuf)
7785 (org-set-frame-title (concat "Indirect: " heading)))
7786 ((eq org-indirect-buffer-display 'current-window)
7787 (pop-to-buffer-same-window ibuf))
7788 ((eq org-indirect-buffer-display 'other-window)
7789 (pop-to-buffer ibuf))
7790 (t (error "Invalid value")))
7791 (narrow-to-region beg end)
7792 (outline-show-all)
7793 (goto-char pos)
7794 (run-hook-with-args 'org-cycle-hook 'all)
7795 (and (window-live-p cwin) (select-window cwin))))
7797 (defun org-get-indirect-buffer (&optional buffer heading)
7798 (setq buffer (or buffer (current-buffer)))
7799 (let ((n 1) (base (buffer-name buffer)) bname)
7800 (while (buffer-live-p
7801 (get-buffer
7802 (setq bname
7803 (concat base "-"
7804 (if heading (concat heading "-" (number-to-string n))
7805 (number-to-string n))))))
7806 (setq n (1+ n)))
7807 (condition-case nil
7808 (make-indirect-buffer buffer bname 'clone)
7809 (error (make-indirect-buffer buffer bname)))))
7811 (defun org-set-frame-title (title)
7812 "Set the title of the current frame to the string TITLE."
7813 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7815 ;;;; Structure editing
7817 ;;; Inserting headlines
7819 (defun org--line-empty-p (n)
7820 "Is the Nth next line empty?
7822 Counts the current line as N = 1 and the previous line as N = 0;
7823 see `beginning-of-line'."
7824 (save-excursion
7825 (and (not (bobp))
7826 (or (beginning-of-line n) t)
7827 (save-match-data
7828 (looking-at "[ \t]*$")))))
7830 (defun org-previous-line-empty-p ()
7831 "Is the previous line a blank line?
7832 When NEXT is non-nil, check the next line instead."
7833 (org--line-empty-p 0))
7835 (defun org-next-line-empty-p ()
7836 "Is the previous line a blank line?
7837 When NEXT is non-nil, check the next line instead."
7838 (org--line-empty-p 2))
7840 (defun org-insert-heading (&optional arg invisible-ok top)
7841 "Insert a new heading or an item with the same depth at point.
7843 If point is at the beginning of a heading or a list item, insert
7844 a new heading or a new item above the current one. When at the
7845 beginning of a regular line of text, turn it into a heading.
7847 If point is in the middle of a line, split it and create a new
7848 headline/item with the text in the current line after point (see
7849 `org-M-RET-may-split-line' on how to modify this behavior). As
7850 a special case, on a headline, splitting can only happen on the
7851 title itself. E.g., this excludes breaking stars or tags.
7853 With a `\\[universal-argument]' prefix, set \
7854 `org-insert-heading-respect-content' to
7855 a non-nil value for the duration of the command. This forces the
7856 insertion of a heading after the current subtree, independently
7857 on the location of point.
7859 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7860 insert the heading at the end of the tree
7861 above the current heading. For example, if point is within a
7862 2nd-level heading, then it will insert a 2nd-level heading at
7863 the end of the 1st-level parent subtree.
7865 When INVISIBLE-OK is set, stop at invisible headlines when going
7866 back. This is important for non-interactive uses of the
7867 command.
7869 When optional argument TOP is non-nil, insert a level 1 heading,
7870 unconditionally."
7871 (interactive "P")
7872 (let ((itemp (and (not top) (org-in-item-p)))
7873 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7874 (respect-content (or org-insert-heading-respect-content
7875 (equal arg '(4))))
7876 (initial-content ""))
7878 (cond
7880 ((or (= (buffer-size) 0)
7881 (and (not (save-excursion
7882 (and (ignore-errors (org-back-to-heading invisible-ok))
7883 (org-at-heading-p))))
7884 (or arg (not itemp))))
7885 ;; At beginning of buffer or so high up that only a heading
7886 ;; makes sense.
7887 (cond ((and (bolp) (not respect-content)) (insert "* "))
7888 ((not respect-content)
7889 (unless may-split (end-of-line))
7890 (insert "\n* "))
7891 ((re-search-forward org-outline-regexp-bol nil t)
7892 (beginning-of-line)
7893 (insert "* \n")
7894 (backward-char))
7895 (t (goto-char (point-max))
7896 (insert "\n* ")))
7897 (run-hooks 'org-insert-heading-hook))
7899 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7902 ;; Maybe move at the end of the subtree
7903 (when (equal arg '(16))
7904 (org-up-heading-safe)
7905 (org-end-of-subtree t))
7906 ;; Insert a heading
7907 (save-restriction
7908 (widen)
7909 (let* ((level nil)
7910 (on-heading (org-at-heading-p))
7911 (empty-line-p (if on-heading
7912 (org-previous-line-empty-p)
7913 ;; We will decide later
7914 nil))
7915 ;; Get a level string to fall back on.
7916 (fix-level
7917 (if (org-before-first-heading-p) "*"
7918 (save-excursion
7919 (org-back-to-heading t)
7920 (when (org-previous-line-empty-p) (setq empty-line-p t))
7921 (looking-at org-outline-regexp)
7922 (make-string (1- (length (match-string 0))) ?*))))
7923 (stars
7924 (save-excursion
7925 (condition-case nil
7926 (if top "* "
7927 (org-back-to-heading invisible-ok)
7928 (when (and (not on-heading)
7929 (featurep 'org-inlinetask)
7930 (integerp org-inlinetask-min-level)
7931 (>= (length (match-string 0))
7932 org-inlinetask-min-level))
7933 ;; Find a heading level before the inline
7934 ;; task.
7935 (while (and (setq level (org-up-heading-safe))
7936 (>= level org-inlinetask-min-level)))
7937 (if (org-at-heading-p)
7938 (org-back-to-heading invisible-ok)
7939 (error "This should not happen")))
7940 (unless (and (save-excursion
7941 (save-match-data
7942 (org-backward-heading-same-level
7943 1 invisible-ok))
7944 (= (point) (match-beginning 0)))
7945 (not (org-next-line-empty-p)))
7946 (setq empty-line-p (or empty-line-p
7947 (org-previous-line-empty-p))))
7948 (match-string 0))
7949 (error (or fix-level "* ")))))
7950 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7951 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7953 ;; If we insert after content, move there and clean up
7954 ;; whitespace.
7955 (when respect-content
7956 (if (not (org-before-first-heading-p))
7957 (org-end-of-subtree nil t)
7958 (re-search-forward org-outline-regexp-bol)
7959 (beginning-of-line 0))
7960 (skip-chars-backward " \r\t\n")
7961 (and (not (looking-back "^\\*+" (line-beginning-position)))
7962 (looking-at "[ \t]+") (replace-match ""))
7963 (unless (eobp) (forward-char 1))
7964 (when (looking-at "^\\*")
7965 (unless (bobp) (backward-char 1))
7966 (insert "\n")))
7968 ;; If we are splitting, grab the text that should be moved
7969 ;; to the new headline.
7970 (when may-split
7971 (if (org-at-heading-p)
7972 ;; This is a heading: split intelligently (keeping
7973 ;; tags).
7974 (let ((pos (point)))
7975 (beginning-of-line)
7976 (let ((case-fold-search nil))
7977 (unless (looking-at org-complex-heading-regexp)
7978 (error "This should not happen")))
7979 (when (and (match-beginning 4)
7980 (> pos (match-beginning 4))
7981 (< pos (match-end 4)))
7982 (setq initial-content (buffer-substring pos (match-end 4)))
7983 (goto-char pos)
7984 (delete-region (point) (match-end 4))
7985 (if (looking-at "[ \t]*$")
7986 (replace-match "")
7987 (insert (make-string (length initial-content) ?\s)))
7988 (setq initial-content (org-trim initial-content)))
7989 (goto-char pos))
7990 ;; A normal line.
7991 (setq initial-content
7992 (org-trim
7993 (delete-and-extract-region (point) (line-end-position))))))
7995 ;; If we are at the beginning of the line, insert before it.
7996 ;; Otherwise, after it.
7997 (cond
7998 ((and (bolp) (looking-at "[ \t]*$")))
7999 ((bolp) (save-excursion (insert "\n")))
8000 (t (end-of-line)
8001 (insert "\n")))
8003 ;; Insert the new heading
8004 (insert stars)
8005 (just-one-space)
8006 (insert initial-content)
8007 (unless (and blank (org-previous-line-empty-p))
8008 (org-N-empty-lines-before-current (if blank 1 0)))
8009 ;; Adjust visibility, which may be messed up if we removed
8010 ;; blank lines while previous entry was hidden.
8011 (let ((bol (line-beginning-position)))
8012 (dolist (o (overlays-at (1- bol)))
8013 (when (and (eq (overlay-get o 'invisible) 'outline)
8014 (eq (overlay-end o) bol))
8015 (move-overlay o (overlay-start o) (1- bol)))))
8016 (run-hooks 'org-insert-heading-hook)))))))
8018 (defun org-N-empty-lines-before-current (N)
8019 "Make the number of empty lines before current exactly N.
8020 So this will delete or add empty lines."
8021 (save-excursion
8022 (beginning-of-line)
8023 (let ((p (point)))
8024 (skip-chars-backward " \r\t\n")
8025 (unless (bolp) (forward-line))
8026 (delete-region (point) p))
8027 (when (> N 0) (insert (make-string N ?\n)))))
8029 (defun org-get-heading (&optional no-tags no-todo)
8030 "Return the heading of the current entry, without the stars.
8031 When NO-TAGS is non-nil, don't include tags.
8032 When NO-TODO is non-nil, don't include TODO keywords."
8033 (save-excursion
8034 (org-back-to-heading t)
8035 (let ((case-fold-search nil))
8036 (cond
8037 ((and no-tags no-todo)
8038 (looking-at org-complex-heading-regexp)
8039 ;; Return value has to be a string, but match group 4 is
8040 ;; optional.
8041 (or (match-string 4) ""))
8042 (no-tags
8043 (looking-at (concat org-outline-regexp
8044 "\\(.*?\\)"
8045 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8046 (match-string 1))
8047 (no-todo
8048 (looking-at org-todo-line-regexp)
8049 (match-string 3))
8050 (t (looking-at org-heading-regexp)
8051 (match-string 2))))))
8053 (defvar orgstruct-mode) ; defined below
8055 (defun org-heading-components ()
8056 "Return the components of the current heading.
8057 This is a list with the following elements:
8058 - the level as an integer
8059 - the reduced level, different if `org-odd-levels-only' is set.
8060 - the TODO keyword, or nil
8061 - the priority character, like ?A, or nil if no priority is given
8062 - the headline text itself, or the tags string if no headline text
8063 - the tags string, or nil."
8064 (save-excursion
8065 (org-back-to-heading t)
8066 (when (let (case-fold-search)
8067 (looking-at
8068 (if orgstruct-mode
8069 org-heading-regexp
8070 org-complex-heading-regexp)))
8071 (if orgstruct-mode
8072 (list (length (match-string 1))
8073 (org-reduced-level (length (match-string 1)))
8076 (match-string 2)
8077 nil)
8078 (list (length (match-string 1))
8079 (org-reduced-level (length (match-string 1)))
8080 (match-string-no-properties 2)
8081 (and (match-end 3) (aref (match-string 3) 2))
8082 (match-string-no-properties 4)
8083 (match-string-no-properties 5))))))
8085 (defun org-get-entry ()
8086 "Get the entry text, after heading, entire subtree."
8087 (save-excursion
8088 (org-back-to-heading t)
8089 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8091 (defun org-edit-headline (&optional heading)
8092 "Edit the current headline.
8093 Set it to HEADING when provided."
8094 (interactive)
8095 (org-with-wide-buffer
8096 (org-back-to-heading t)
8097 (let ((case-fold-search nil))
8098 (when (looking-at org-complex-heading-regexp)
8099 (let* ((old (match-string-no-properties 4))
8100 (new (save-match-data
8101 (org-trim (or heading (read-string "Edit: " old))))))
8102 (unless (equal old new)
8103 (if old (replace-match new t t nil 4)
8104 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8105 (insert " " new))
8106 (org-set-tags nil t)
8107 (when (looking-at "[ \t]*$") (replace-match ""))))))))
8109 (defun org-insert-heading-after-current ()
8110 "Insert a new heading with same level as current, after current subtree."
8111 (interactive)
8112 (org-back-to-heading)
8113 (org-insert-heading)
8114 (org-move-subtree-down)
8115 (end-of-line 1))
8117 (defun org-insert-heading-respect-content (&optional invisible-ok)
8118 "Insert heading with `org-insert-heading-respect-content' set to t."
8119 (interactive)
8120 (org-insert-heading '(4) invisible-ok))
8122 (defun org-insert-todo-heading-respect-content (&optional force-state)
8123 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8124 (interactive)
8125 (org-insert-todo-heading force-state '(4)))
8127 (defun org-insert-todo-heading (arg &optional force-heading)
8128 "Insert a new heading with the same level and TODO state as current heading.
8130 If the heading has no TODO state, or if the state is DONE, use
8131 the first state (TODO by default). Also with one prefix arg,
8132 force first state. With two prefix args, force inserting at the
8133 end of the parent subtree.
8135 When called at a plain list item, insert a new item with an
8136 unchecked check box."
8137 (interactive "P")
8138 (when (or force-heading (not (org-insert-item 'checkbox)))
8139 (org-insert-heading (or (and (equal arg '(16)) '(16))
8140 force-heading))
8141 (save-excursion
8142 (org-back-to-heading)
8143 (outline-previous-heading)
8144 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
8145 (let* ((new-mark-x
8146 (if (or (equal arg '(4))
8147 (not (match-beginning 2))
8148 (member (match-string 2) org-done-keywords))
8149 (car org-todo-keywords-1)
8150 (match-string 2)))
8151 (new-mark
8153 (run-hook-with-args-until-success
8154 'org-todo-get-default-hook new-mark-x nil)
8155 new-mark-x)))
8156 (beginning-of-line 1)
8157 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8158 (if org-treat-insert-todo-heading-as-state-change
8159 (org-todo new-mark)
8160 (insert new-mark " "))))
8161 (when org-provide-todo-statistics
8162 (org-update-parent-todo-statistics))))
8164 (defun org-insert-subheading (arg)
8165 "Insert a new subheading and demote it.
8166 Works for outline headings and for plain lists alike."
8167 (interactive "P")
8168 (org-insert-heading arg)
8169 (cond
8170 ((org-at-heading-p) (org-do-demote))
8171 ((org-at-item-p) (org-indent-item))))
8173 (defun org-insert-todo-subheading (arg)
8174 "Insert a new subheading with TODO keyword or checkbox and demote it.
8175 Works for outline headings and for plain lists alike."
8176 (interactive "P")
8177 (org-insert-todo-heading arg)
8178 (cond
8179 ((org-at-heading-p) (org-do-demote))
8180 ((org-at-item-p) (org-indent-item))))
8182 ;;; Promotion and Demotion
8184 (defvar org-after-demote-entry-hook nil
8185 "Hook run after an entry has been demoted.
8186 The cursor will be at the beginning of the entry.
8187 When a subtree is being demoted, the hook will be called for each node.")
8189 (defvar org-after-promote-entry-hook nil
8190 "Hook run after an entry has been promoted.
8191 The cursor will be at the beginning of the entry.
8192 When a subtree is being promoted, the hook will be called for each node.")
8194 (defun org-promote-subtree ()
8195 "Promote the entire subtree.
8196 See also `org-promote'."
8197 (interactive)
8198 (save-excursion
8199 (org-with-limited-levels (org-map-tree 'org-promote)))
8200 (org-fix-position-after-promote))
8202 (defun org-demote-subtree ()
8203 "Demote the entire subtree.
8204 See `org-demote' and `org-promote'."
8205 (interactive)
8206 (save-excursion
8207 (org-with-limited-levels (org-map-tree 'org-demote)))
8208 (org-fix-position-after-promote))
8210 (defun org-do-promote ()
8211 "Promote the current heading higher up the tree.
8212 If the region is active in `transient-mark-mode', promote all
8213 headings in the region."
8214 (interactive)
8215 (save-excursion
8216 (if (org-region-active-p)
8217 (org-map-region 'org-promote (region-beginning) (region-end))
8218 (org-promote)))
8219 (org-fix-position-after-promote))
8221 (defun org-do-demote ()
8222 "Demote the current heading lower down the tree.
8223 If the region is active in `transient-mark-mode', demote all
8224 headings in the region."
8225 (interactive)
8226 (save-excursion
8227 (if (org-region-active-p)
8228 (org-map-region 'org-demote (region-beginning) (region-end))
8229 (org-demote)))
8230 (org-fix-position-after-promote))
8232 (defun org-fix-position-after-promote ()
8233 "Fix cursor position and indentation after demoting/promoting."
8234 (let ((pos (point)))
8235 (when (save-excursion
8236 (beginning-of-line)
8237 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8238 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8239 (cond ((eobp) (insert " "))
8240 ((eolp) (insert " "))
8241 ((equal (char-after) ?\s) (forward-char 1))))))
8243 (defun org-current-level ()
8244 "Return the level of the current entry, or nil if before the first headline.
8245 The level is the number of stars at the beginning of the
8246 headline. Use `org-reduced-level' to remove the effect of
8247 `org-odd-levels'. Unlike to `org-outline-level', this function
8248 ignores inlinetasks."
8249 (let ((level (org-with-limited-levels (org-outline-level))))
8250 (and (> level 0) level)))
8252 (defun org-get-previous-line-level ()
8253 "Return the outline depth of the last headline before the current line.
8254 Returns 0 for the first headline in the buffer, and nil if before the
8255 first headline."
8256 (and (org-current-level)
8257 (or (and (/= (line-beginning-position) (point-min))
8258 (save-excursion (beginning-of-line 0) (org-current-level)))
8259 0)))
8261 (defun org-reduced-level (l)
8262 "Compute the effective level of a heading.
8263 This takes into account the setting of `org-odd-levels-only'."
8264 (cond
8265 ((zerop l) 0)
8266 (org-odd-levels-only (1+ (floor (/ l 2))))
8267 (t l)))
8269 (defun org-level-increment ()
8270 "Return the number of stars that will be added or removed at a
8271 time to headlines when structure editing, based on the value of
8272 `org-odd-levels-only'."
8273 (if org-odd-levels-only 2 1))
8275 (defun org-get-valid-level (level &optional change)
8276 "Rectify a level change under the influence of `org-odd-levels-only'
8277 LEVEL is a current level, CHANGE is by how much the level should be
8278 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8279 even level numbers will become the next higher odd number."
8280 (if org-odd-levels-only
8281 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8282 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8283 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8284 (max 1 (+ level (or change 0)))))
8286 (defun org-promote ()
8287 "Promote the current heading higher up the tree."
8288 (org-with-wide-buffer
8289 (org-back-to-heading t)
8290 (let* ((after-change-functions (remq 'flyspell-after-change-function
8291 after-change-functions))
8292 (level (save-match-data (funcall outline-level)))
8293 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8294 (diff (abs (- level (length up-head) -1))))
8295 (cond
8296 ((and (= level 1) org-allow-promoting-top-level-subtree)
8297 (replace-match "# " nil t))
8298 ((= level 1)
8299 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8300 (t (replace-match up-head nil t)))
8301 (unless (= level 1)
8302 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8303 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8304 (run-hooks 'org-after-promote-entry-hook))))
8306 (defun org-demote ()
8307 "Demote the current heading lower down the tree."
8308 (org-with-wide-buffer
8309 (org-back-to-heading t)
8310 (let* ((after-change-functions (remq 'flyspell-after-change-function
8311 after-change-functions))
8312 (level (save-match-data (funcall outline-level)))
8313 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8314 (diff (abs (- level (length down-head) -1))))
8315 (replace-match down-head nil t)
8316 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8317 (when org-adapt-indentation (org-fixup-indentation diff))
8318 (run-hooks 'org-after-demote-entry-hook))))
8320 (defun org-cycle-level ()
8321 "Cycle the level of an empty headline through possible states.
8322 This goes first to child, then to parent, level, then up the hierarchy.
8323 After top level, it switches back to sibling level."
8324 (interactive)
8325 (let ((org-adapt-indentation nil))
8326 (when (org-point-at-end-of-empty-headline)
8327 (setq this-command 'org-cycle-level) ; Only needed for caching
8328 (let ((cur-level (org-current-level))
8329 (prev-level (org-get-previous-line-level)))
8330 (cond
8331 ;; If first headline in file, promote to top-level.
8332 ((= prev-level 0)
8333 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8334 do (org-do-promote)))
8335 ;; If same level as prev, demote one.
8336 ((= prev-level cur-level)
8337 (org-do-demote))
8338 ;; If parent is top-level, promote to top level if not already.
8339 ((= prev-level 1)
8340 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8341 do (org-do-promote)))
8342 ;; If top-level, return to prev-level.
8343 ((= cur-level 1)
8344 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8345 do (org-do-demote)))
8346 ;; If less than prev-level, promote one.
8347 ((< cur-level prev-level)
8348 (org-do-promote))
8349 ;; If deeper than prev-level, promote until higher than
8350 ;; prev-level.
8351 ((> cur-level prev-level)
8352 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8353 do (org-do-promote))))
8354 t))))
8356 (defun org-map-tree (fun)
8357 "Call FUN for every heading underneath the current one."
8358 (org-back-to-heading t)
8359 (let ((level (funcall outline-level)))
8360 (save-excursion
8361 (funcall fun)
8362 (while (and (progn
8363 (outline-next-heading)
8364 (> (funcall outline-level) level))
8365 (not (eobp)))
8366 (funcall fun)))))
8368 (defun org-map-region (fun beg end)
8369 "Call FUN for every heading between BEG and END."
8370 (let ((org-ignore-region t))
8371 (save-excursion
8372 (setq end (copy-marker end))
8373 (goto-char beg)
8374 (when (and (re-search-forward org-outline-regexp-bol nil t)
8375 (< (point) end))
8376 (funcall fun))
8377 (while (and (progn
8378 (outline-next-heading)
8379 (< (point) end))
8380 (not (eobp)))
8381 (funcall fun)))))
8383 (defun org-fixup-indentation (diff)
8384 "Change the indentation in the current entry by DIFF.
8386 DIFF is an integer. Indentation is done according to the
8387 following rules:
8389 - Planning information and property drawers are always indented
8390 according to the new level of the headline;
8392 - Footnote definitions and their contents are ignored;
8394 - Inlinetasks' boundaries are not shifted;
8396 - Empty lines are ignored;
8398 - Other lines' indentation are shifted by DIFF columns, unless
8399 it would introduce a structural change in the document, in
8400 which case no shifting is done at all.
8402 Assume point is at a heading or an inlinetask beginning."
8403 (org-with-wide-buffer
8404 (narrow-to-region (line-beginning-position)
8405 (save-excursion
8406 (if (org-with-limited-levels (org-at-heading-p))
8407 (org-with-limited-levels (outline-next-heading))
8408 (org-inlinetask-goto-end))
8409 (point)))
8410 (forward-line)
8411 ;; Indent properly planning info and property drawer.
8412 (when (looking-at-p org-planning-line-re)
8413 (org-indent-line)
8414 (forward-line))
8415 (when (looking-at org-property-drawer-re)
8416 (goto-char (match-end 0))
8417 (forward-line)
8418 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8419 (catch 'no-shift
8420 (when (zerop diff) (throw 'no-shift nil))
8421 ;; If DIFF is negative, first check if a shift is possible at all
8422 ;; (e.g., it doesn't break structure). This can only happen if
8423 ;; some contents are not properly indented.
8424 (let ((case-fold-search t))
8425 (when (< diff 0)
8426 (let ((diff (- diff))
8427 (forbidden-re (concat org-outline-regexp
8428 "\\|"
8429 (substring org-footnote-definition-re 1))))
8430 (save-excursion
8431 (while (not (eobp))
8432 (cond
8433 ((looking-at-p "[ \t]*$") (forward-line))
8434 ((and (looking-at-p org-footnote-definition-re)
8435 (let ((e (org-element-at-point)))
8436 (and (eq (org-element-type e) 'footnote-definition)
8437 (goto-char (org-element-property :end e))))))
8438 ((looking-at-p org-outline-regexp) (forward-line))
8439 ;; Give up if shifting would move before column 0 or
8440 ;; if it would introduce a headline or a footnote
8441 ;; definition.
8443 (skip-chars-forward " \t")
8444 (let ((ind (current-column)))
8445 (when (or (< ind diff)
8446 (and (= ind diff) (looking-at-p forbidden-re)))
8447 (throw 'no-shift nil)))
8448 ;; Ignore contents of example blocks and source
8449 ;; blocks if their indentation is meant to be
8450 ;; preserved. Jump to block's closing line.
8451 (beginning-of-line)
8452 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8453 (let ((e (org-element-at-point)))
8454 (and (memq (org-element-type e)
8455 '(example-block src-block))
8456 (or org-src-preserve-indentation
8457 (org-element-property :preserve-indent e))
8458 (goto-char (org-element-property :end e))
8459 (progn (skip-chars-backward " \r\t\n")
8460 (beginning-of-line)
8461 t))))
8462 (forward-line))))))))
8463 ;; Shift lines but footnote definitions, inlinetasks boundaries
8464 ;; by DIFF. Also skip contents of source or example blocks
8465 ;; when indentation is meant to be preserved.
8466 (while (not (eobp))
8467 (cond
8468 ((and (looking-at-p org-footnote-definition-re)
8469 (let ((e (org-element-at-point)))
8470 (and (eq (org-element-type e) 'footnote-definition)
8471 (goto-char (org-element-property :end e))))))
8472 ((looking-at-p org-outline-regexp) (forward-line))
8473 ((looking-at-p "[ \t]*$") (forward-line))
8475 (indent-line-to (+ (org-get-indentation) diff))
8476 (beginning-of-line)
8477 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8478 (let ((e (org-element-at-point)))
8479 (and (memq (org-element-type e)
8480 '(example-block src-block))
8481 (or org-src-preserve-indentation
8482 (org-element-property :preserve-indent e))
8483 (goto-char (org-element-property :end e))
8484 (progn (skip-chars-backward " \r\t\n")
8485 (beginning-of-line)
8486 t))))
8487 (forward-line)))))))))
8489 (defun org-convert-to-odd-levels ()
8490 "Convert an Org file with all levels allowed to one with odd levels.
8491 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8492 level 5 etc."
8493 (interactive)
8494 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8495 (let ((outline-level 'org-outline-level)
8496 (org-odd-levels-only nil) n)
8497 (save-excursion
8498 (goto-char (point-min))
8499 (while (re-search-forward "^\\*\\*+ " nil t)
8500 (setq n (- (length (match-string 0)) 2))
8501 (while (>= (setq n (1- n)) 0)
8502 (org-demote))
8503 (end-of-line 1))))))
8505 (defun org-convert-to-oddeven-levels ()
8506 "Convert an Org file with only odd levels to one with odd/even levels.
8507 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8508 file contains a section with an even level, conversion would
8509 destroy the structure of the file. An error is signaled in this
8510 case."
8511 (interactive)
8512 (goto-char (point-min))
8513 ;; First check if there are no even levels
8514 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8515 (org-show-set-visibility 'canonical)
8516 (error "Not all levels are odd in this file. Conversion not possible"))
8517 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8518 (let ((outline-regexp org-outline-regexp)
8519 (outline-level 'org-outline-level)
8520 (org-odd-levels-only nil) n)
8521 (save-excursion
8522 (goto-char (point-min))
8523 (while (re-search-forward "^\\*\\*+ " nil t)
8524 (setq n (/ (1- (length (match-string 0))) 2))
8525 (while (>= (setq n (1- n)) 0)
8526 (org-promote))
8527 (end-of-line 1))))))
8529 (defun org-tr-level (n)
8530 "Make N odd if required."
8531 (if org-odd-levels-only (1+ (/ n 2)) n))
8533 ;;; Vertical tree motion, cutting and pasting of subtrees
8535 (defun org-move-subtree-up (&optional arg)
8536 "Move the current subtree up past ARG headlines of the same level."
8537 (interactive "p")
8538 (org-move-subtree-down (- (prefix-numeric-value arg))))
8540 (defun org-move-subtree-down (&optional arg)
8541 "Move the current subtree down past ARG headlines of the same level."
8542 (interactive "p")
8543 (setq arg (prefix-numeric-value arg))
8544 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8545 'org-get-last-sibling))
8546 (ins-point (make-marker))
8547 (cnt (abs arg))
8548 (col (current-column))
8549 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8550 ;; Select the tree
8551 (org-back-to-heading)
8552 (setq beg0 (point))
8553 (save-excursion
8554 (setq ne-beg (org-back-over-empty-lines))
8555 (setq beg (point)))
8556 (save-match-data
8557 (save-excursion (outline-end-of-heading)
8558 (setq folded (org-invisible-p)))
8559 (progn (org-end-of-subtree nil t)
8560 (unless (eobp) (backward-char))))
8561 (outline-next-heading)
8562 (setq ne-end (org-back-over-empty-lines))
8563 (setq end (point))
8564 (goto-char beg0)
8565 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8566 ;; include less whitespace
8567 (save-excursion
8568 (goto-char beg)
8569 (forward-line (- ne-beg ne-end))
8570 (setq beg (point))))
8571 ;; Find insertion point, with error handling
8572 (while (> cnt 0)
8573 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8574 (progn (goto-char beg0)
8575 (user-error "Cannot move past superior level or buffer limit")))
8576 (setq cnt (1- cnt)))
8577 (when (> arg 0)
8578 ;; Moving forward - still need to move over subtree
8579 (org-end-of-subtree t t)
8580 (save-excursion
8581 (org-back-over-empty-lines)
8582 (or (bolp) (newline))))
8583 (setq ne-ins (org-back-over-empty-lines))
8584 (move-marker ins-point (point))
8585 (setq txt (buffer-substring beg end))
8586 (org-save-markers-in-region beg end)
8587 (delete-region beg end)
8588 (org-remove-empty-overlays-at beg)
8589 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8590 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8591 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8592 (let ((bbb (point)))
8593 (insert-before-markers txt)
8594 (org-reinstall-markers-in-region bbb)
8595 (move-marker ins-point bbb))
8596 (or (bolp) (insert "\n"))
8597 (setq ins-end (point))
8598 (goto-char ins-point)
8599 (org-skip-whitespace)
8600 (when (and (< arg 0)
8601 (org-first-sibling-p)
8602 (> ne-ins ne-beg))
8603 ;; Move whitespace back to beginning
8604 (save-excursion
8605 (goto-char ins-end)
8606 (let ((kill-whole-line t))
8607 (kill-line (- ne-ins ne-beg)) (point)))
8608 (insert (make-string (- ne-ins ne-beg) ?\n)))
8609 (move-marker ins-point nil)
8610 (if folded
8611 (outline-hide-subtree)
8612 (org-show-entry)
8613 (org-show-children)
8614 (org-cycle-hide-drawers 'children))
8615 (org-clean-visibility-after-subtree-move)
8616 ;; move back to the initial column we were at
8617 (move-to-column col)))
8619 (defvar org-subtree-clip ""
8620 "Clipboard for cut and paste of subtrees.
8621 This is actually only a copy of the kill, because we use the normal kill
8622 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8624 (defvar org-subtree-clip-folded nil
8625 "Was the last copied subtree folded?
8626 This is used to fold the tree back after pasting.")
8628 (defun org-cut-subtree (&optional n)
8629 "Cut the current subtree into the clipboard.
8630 With prefix arg N, cut this many sequential subtrees.
8631 This is a short-hand for marking the subtree and then cutting it."
8632 (interactive "p")
8633 (org-copy-subtree n 'cut))
8635 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8636 "Copy the current subtree it in the clipboard.
8637 With prefix arg N, copy this many sequential subtrees.
8638 This is a short-hand for marking the subtree and then copying it.
8639 If CUT is non-nil, actually cut the subtree.
8640 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8641 of some markers in the region, even if CUT is non-nil. This is
8642 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8643 (interactive "p")
8644 (let (beg end folded (beg0 (point)))
8645 (if (called-interactively-p 'any)
8646 (org-back-to-heading nil) ; take what looks like a subtree
8647 (org-back-to-heading t)) ; take what is really there
8648 (setq beg (point))
8649 (skip-chars-forward " \t\r\n")
8650 (save-match-data
8651 (if nosubtrees
8652 (outline-next-heading)
8653 (save-excursion (outline-end-of-heading)
8654 (setq folded (org-invisible-p)))
8655 (ignore-errors (org-forward-heading-same-level (1- n) t))
8656 (org-end-of-subtree t t)))
8657 ;; Include the end of an inlinetask
8658 (when (and (featurep 'org-inlinetask)
8659 (looking-at-p (concat (org-inlinetask-outline-regexp)
8660 "END[ \t]*$")))
8661 (end-of-line))
8662 (setq end (point))
8663 (goto-char beg0)
8664 (when (> end beg)
8665 (setq org-subtree-clip-folded folded)
8666 (when (or cut force-store-markers)
8667 (org-save-markers-in-region beg end))
8668 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8669 (setq org-subtree-clip (current-kill 0))
8670 (message "%s: Subtree(s) with %d characters"
8671 (if cut "Cut" "Copied")
8672 (length org-subtree-clip)))))
8674 (defun org-paste-subtree (&optional level tree for-yank remove)
8675 "Paste the clipboard as a subtree, with modification of headline level.
8676 The entire subtree is promoted or demoted in order to match a new headline
8677 level.
8679 If the cursor is at the beginning of a headline, the same level as
8680 that headline is used to paste the tree.
8682 If not, the new level is derived from the *visible* headings
8683 before and after the insertion point, and taken to be the inferior headline
8684 level of the two. So if the previous visible heading is level 3 and the
8685 next is level 4 (or vice versa), level 4 will be used for insertion.
8686 This makes sure that the subtree remains an independent subtree and does
8687 not swallow low level entries.
8689 You can also force a different level, either by using a numeric prefix
8690 argument, or by inserting the heading marker by hand. For example, if the
8691 cursor is after \"*****\", then the tree will be shifted to level 5.
8693 If optional TREE is given, use this text instead of the kill ring.
8695 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8696 move back over whitespace before inserting, and move point to the end of
8697 the inserted text when done.
8699 When REMOVE is non-nil, remove the subtree from the clipboard."
8700 (interactive "P")
8701 (setq tree (or tree (and kill-ring (current-kill 0))))
8702 (unless (org-kill-is-subtree-p tree)
8703 (user-error "%s"
8704 (substitute-command-keys
8705 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8706 (org-with-limited-levels
8707 (let* ((visp (not (org-invisible-p)))
8708 (txt tree)
8709 (^re_ "\\(\\*+\\)[ \t]*")
8710 (old-level (if (string-match org-outline-regexp-bol txt)
8711 (- (match-end 0) (match-beginning 0) 1)
8712 -1))
8713 (force-level (cond (level (prefix-numeric-value level))
8714 ((and (looking-at "[ \t]*$")
8715 (string-match
8716 "^\\*+$" (buffer-substring
8717 (point-at-bol) (point))))
8718 (- (match-end 0) (match-beginning 0)))
8719 ((and (bolp)
8720 (looking-at org-outline-regexp))
8721 (- (match-end 0) (point) 1))))
8722 (previous-level (save-excursion
8723 (condition-case nil
8724 (progn
8725 (outline-previous-visible-heading 1)
8726 (if (looking-at ^re_)
8727 (- (match-end 0) (match-beginning 0) 1)
8729 (error 1))))
8730 (next-level (save-excursion
8731 (condition-case nil
8732 (progn
8733 (or (looking-at org-outline-regexp)
8734 (outline-next-visible-heading 1))
8735 (if (looking-at ^re_)
8736 (- (match-end 0) (match-beginning 0) 1)
8738 (error 1))))
8739 (new-level (or force-level (max previous-level next-level)))
8740 (shift (if (or (= old-level -1)
8741 (= new-level -1)
8742 (= old-level new-level))
8744 (- new-level old-level)))
8745 (delta (if (> shift 0) -1 1))
8746 (func (if (> shift 0) 'org-demote 'org-promote))
8747 (org-odd-levels-only nil)
8748 beg end newend)
8749 ;; Remove the forced level indicator
8750 (when force-level
8751 (delete-region (point-at-bol) (point)))
8752 ;; Paste
8753 (beginning-of-line (if (bolp) 1 2))
8754 (setq beg (point))
8755 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8756 (insert-before-markers txt)
8757 (unless (string-suffix-p "\n" txt) (insert "\n"))
8758 (setq newend (point))
8759 (org-reinstall-markers-in-region beg)
8760 (setq end (point))
8761 (goto-char beg)
8762 (skip-chars-forward " \t\n\r")
8763 (setq beg (point))
8764 (when (and (org-invisible-p) visp)
8765 (save-excursion (outline-show-heading)))
8766 ;; Shift if necessary
8767 (unless (= shift 0)
8768 (save-restriction
8769 (narrow-to-region beg end)
8770 (while (not (= shift 0))
8771 (org-map-region func (point-min) (point-max))
8772 (setq shift (+ delta shift)))
8773 (goto-char (point-min))
8774 (setq newend (point-max))))
8775 (when (or (called-interactively-p 'interactive) for-yank)
8776 (message "Clipboard pasted as level %d subtree" new-level))
8777 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8778 kill-ring
8779 (eq org-subtree-clip (current-kill 0))
8780 org-subtree-clip-folded)
8781 ;; The tree was folded before it was killed/copied
8782 (outline-hide-subtree))
8783 (and for-yank (goto-char newend))
8784 (and remove (setq kill-ring (cdr kill-ring))))))
8786 (defun org-kill-is-subtree-p (&optional txt)
8787 "Check if the current kill is an outline subtree, or a set of trees.
8788 Returns nil if kill does not start with a headline, or if the first
8789 headline level is not the largest headline level in the tree.
8790 So this will actually accept several entries of equal levels as well,
8791 which is OK for `org-paste-subtree'.
8792 If optional TXT is given, check this string instead of the current kill."
8793 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8794 (re (org-get-limited-outline-regexp))
8795 (^re (concat "^" re))
8796 (start-level (and kill
8797 (string-match
8798 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8799 kill)
8800 (- (match-end 2) (match-beginning 2) 1)))
8801 (start (1+ (or (match-beginning 2) -1))))
8802 (if (not start-level)
8803 (progn
8804 nil) ;; does not even start with a heading
8805 (catch 'exit
8806 (while (setq start (string-match ^re kill (1+ start)))
8807 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8808 (throw 'exit nil)))
8809 t))))
8811 (defvar org-markers-to-move nil
8812 "Markers that should be moved with a cut-and-paste operation.
8813 Those markers are stored together with their positions relative to
8814 the start of the region.")
8816 (defun org-save-markers-in-region (beg end)
8817 "Check markers in region.
8818 If these markers are between BEG and END, record their position relative
8819 to BEG, so that after moving the block of text, we can put the markers back
8820 into place.
8821 This function gets called just before an entry or tree gets cut from the
8822 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8823 called immediately, to move the markers with the entries."
8824 (setq org-markers-to-move nil)
8825 (when (featurep 'org-clock)
8826 (org-clock-save-markers-for-cut-and-paste beg end))
8827 (when (featurep 'org-agenda)
8828 (org-agenda-save-markers-for-cut-and-paste beg end)))
8830 (defun org-check-and-save-marker (marker beg end)
8831 "Check if MARKER is between BEG and END.
8832 If yes, remember the marker and the distance to BEG."
8833 (when (and (marker-buffer marker)
8834 (equal (marker-buffer marker) (current-buffer))
8835 (>= marker beg) (< marker end))
8836 (push (cons marker (- marker beg)) org-markers-to-move)))
8838 (defun org-reinstall-markers-in-region (beg)
8839 "Move all remembered markers to their position relative to BEG."
8840 (dolist (x org-markers-to-move)
8841 (move-marker (car x) (+ beg (cdr x))))
8842 (setq org-markers-to-move nil))
8844 (defun org-narrow-to-subtree ()
8845 "Narrow buffer to the current subtree."
8846 (interactive)
8847 (save-excursion
8848 (save-match-data
8849 (org-with-limited-levels
8850 (narrow-to-region
8851 (progn (org-back-to-heading t) (point))
8852 (progn (org-end-of-subtree t t)
8853 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8854 (point)))))))
8856 (defun org-narrow-to-block ()
8857 "Narrow buffer to the current block."
8858 (interactive)
8859 (let* ((case-fold-search t)
8860 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8861 "^[ \t]*#\\+end_.*")))
8862 (if blockp
8863 (narrow-to-region (car blockp) (cdr blockp))
8864 (user-error "Not in a block"))))
8866 (defun org-clone-subtree-with-time-shift (n &optional shift)
8867 "Clone the task (subtree) at point N times.
8868 The clones will be inserted as siblings.
8870 In interactive use, the user will be prompted for the number of
8871 clones to be produced. If the entry has a timestamp, the user
8872 will also be prompted for a time shift, which may be a repeater
8873 as used in time stamps, for example `+3d'. To disable this,
8874 you can call the function with a universal prefix argument.
8876 When a valid repeater is given and the entry contains any time
8877 stamps, the clones will become a sequence in time, with time
8878 stamps in the subtree shifted for each clone produced. If SHIFT
8879 is nil or the empty string, time stamps will be left alone. The
8880 ID property of the original subtree is removed.
8882 In each clone, all the CLOCK entries will be removed. This
8883 prevents Org from considering that the clocked times overlap.
8885 If the original subtree did contain time stamps with a repeater,
8886 the following will happen:
8887 - the repeater will be removed in each clone
8888 - an additional clone will be produced, with the current, unshifted
8889 date(s) in the entry.
8890 - the original entry will be placed *after* all the clones, with
8891 repeater intact.
8892 - the start days in the repeater in the original entry will be shifted
8893 to past the last clone.
8894 In this way you can spell out a number of instances of a repeating task,
8895 and still retain the repeater to cover future instances of the task.
8897 As described above, N+1 clones are produced when the original
8898 subtree has a repeater. Setting N to 0, then, can be used to
8899 remove the repeater from a subtree and create a shifted clone
8900 with the original repeater."
8901 (interactive "nNumber of clones to produce: ")
8902 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8903 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8904 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8905 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8906 (shift
8907 (or shift
8908 (if (and (not (equal current-prefix-arg '(4)))
8909 (save-excursion
8910 (goto-char beg)
8911 (re-search-forward org-ts-regexp-both end-of-tree t)))
8912 (read-from-minibuffer
8913 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8914 ""))) ;No time shift
8915 (doshift
8916 (and (org-string-nw-p shift)
8917 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8918 shift)
8919 (user-error "Invalid shift specification %s" shift)))))
8920 (goto-char end-of-tree)
8921 (unless (bolp) (insert "\n"))
8922 (let* ((end (point))
8923 (template (buffer-substring beg end))
8924 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8925 (shift-what (pcase (and doshift (match-string 2 shift))
8926 (`nil nil)
8927 ("d" 'day)
8928 ("w" (setq shift-n (* 7 shift-n)) 'day)
8929 ("m" 'month)
8930 ("y" 'year)
8931 (_ (error "Unsupported time unit"))))
8932 (nmin 1)
8933 (nmax n)
8934 (n-no-remove -1)
8935 (idprop (org-entry-get nil "ID")))
8936 (when (and doshift
8937 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8938 template))
8939 (delete-region beg end)
8940 (setq end beg)
8941 (setq nmin 0)
8942 (setq nmax (1+ nmax))
8943 (setq n-no-remove nmax))
8944 (goto-char end)
8945 (cl-loop for n from nmin to nmax do
8946 (insert
8947 ;; Prepare clone.
8948 (with-temp-buffer
8949 (insert template)
8950 (org-mode)
8951 (goto-char (point-min))
8952 (org-show-subtree)
8953 (and idprop (if org-clone-delete-id
8954 (org-entry-delete nil "ID")
8955 (org-id-get-create t)))
8956 (unless (= n 0)
8957 (while (re-search-forward org-clock-line-re nil t)
8958 (delete-region (line-beginning-position)
8959 (line-beginning-position 2)))
8960 (goto-char (point-min))
8961 (while (re-search-forward org-drawer-regexp nil t)
8962 (org-remove-empty-drawer-at (point))))
8963 (goto-char (point-min))
8964 (when doshift
8965 (while (re-search-forward org-ts-regexp-both nil t)
8966 (org-timestamp-change (* n shift-n) shift-what))
8967 (unless (= n n-no-remove)
8968 (goto-char (point-min))
8969 (while (re-search-forward org-ts-regexp nil t)
8970 (save-excursion
8971 (goto-char (match-beginning 0))
8972 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8973 (delete-region (match-beginning 1) (match-end 1)))))))
8974 (buffer-string)))))
8975 (goto-char beg)))
8977 ;;; Outline Sorting
8979 (defun org-sort (with-case)
8980 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8981 Optional argument WITH-CASE means sort case-sensitively."
8982 (interactive "P")
8983 (cond
8984 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8985 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8987 (org-call-with-arg 'org-sort-entries with-case))))
8989 (defun org-sort-remove-invisible (s)
8990 "Remove invisible links from string S."
8991 (remove-text-properties 0 (length s) org-rm-props s)
8992 (while (string-match org-bracket-link-regexp s)
8993 (setq s (replace-match (if (match-end 2)
8994 (match-string 3 s)
8995 (match-string 1 s))
8996 t t s)))
8997 (let ((st (format " %s " s)))
8998 (while (string-match org-emph-re st)
8999 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
9000 (setq s (substring st 1 -1)))
9003 (defvar org-priority-regexp) ; defined later in the file
9005 (defvar org-after-sorting-entries-or-items-hook nil
9006 "Hook that is run after a bunch of entries or items have been sorted.
9007 When children are sorted, the cursor is in the parent line when this
9008 hook gets called. When a region or a plain list is sorted, the cursor
9009 will be in the first entry of the sorted region/list.")
9011 (defun org-sort-entries
9012 (&optional with-case sorting-type getkey-func compare-func property
9013 interactive?)
9014 "Sort entries on a certain level of an outline tree.
9015 If there is an active region, the entries in the region are sorted.
9016 Else, if the cursor is before the first entry, sort the top-level items.
9017 Else, the children of the entry at point are sorted.
9019 Sorting can be alphabetically, numerically, by date/time as given by
9020 a time stamp, by a property, by priority order, or by a custom function.
9022 The command prompts for the sorting type unless it has been given to the
9023 function through the SORTING-TYPE argument, which needs to be a character,
9024 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9025 the precise meaning of each character:
9027 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9028 c By creation time, which is assumed to be the first inactive time stamp
9029 at the beginning of a line.
9030 d By deadline date/time.
9031 k By clocking time.
9032 n Numerically, by converting the beginning of the entry/item to a number.
9033 o By order of TODO keywords.
9034 p By priority according to the cookie.
9035 r By the value of a property.
9036 s By scheduled date/time.
9037 t By date/time, either the first active time stamp in the entry, or, if
9038 none exist, by the first inactive one.
9040 Capital letters will reverse the sort order.
9042 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9043 called with point at the beginning of the record. It must return a
9044 value that is compatible with COMPARE-FUNC, the function used to
9045 compare entries.
9047 Comparing entries ignores case by default. However, with an optional argument
9048 WITH-CASE, the sorting considers case as well.
9050 Sorting is done against the visible part of the headlines, it ignores hidden
9051 links.
9053 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
9055 A non-nil value for INTERACTIVE? is used to signal that this
9056 function is being called interactively."
9057 (interactive (list current-prefix-arg nil nil nil nil t))
9058 (let ((case-func (if with-case 'identity 'downcase))
9059 start beg end stars re re2
9060 txt what tmp)
9061 ;; Find beginning and end of region to sort
9062 (cond
9063 ((org-region-active-p)
9064 ;; we will sort the region
9065 (setq end (region-end)
9066 what "region")
9067 (goto-char (region-beginning))
9068 (unless (org-at-heading-p) (outline-next-heading))
9069 (setq start (point)))
9070 ((or (org-at-heading-p)
9071 (ignore-errors (progn (org-back-to-heading) t)))
9072 ;; we will sort the children of the current headline
9073 (org-back-to-heading)
9074 (setq start (point)
9075 end (progn (org-end-of-subtree t t)
9076 (or (bolp) (insert "\n"))
9077 (when (>= (org-back-over-empty-lines) 1)
9078 (forward-line 1))
9079 (point))
9080 what "children")
9081 (goto-char start)
9082 (outline-show-subtree)
9083 (outline-next-heading))
9085 ;; we will sort the top-level entries in this file
9086 (goto-char (point-min))
9087 (or (org-at-heading-p) (outline-next-heading))
9088 (setq start (point))
9089 (goto-char (point-max))
9090 (beginning-of-line 1)
9091 (when (looking-at ".*?\\S-")
9092 ;; File ends in a non-white line
9093 (end-of-line 1)
9094 (insert "\n"))
9095 (setq end (point-max))
9096 (setq what "top-level")
9097 (goto-char start)
9098 (outline-show-all)))
9100 (setq beg (point))
9101 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9103 (looking-at "\\(\\*+\\)")
9104 (setq stars (match-string 1)
9105 re (concat "^" (regexp-quote stars) " +")
9106 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9107 txt (buffer-substring beg end))
9108 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9109 (when (and (not (equal stars "*")) (string-match re2 txt))
9110 (user-error "Region to sort contains a level above the first entry"))
9112 (unless sorting-type
9113 (message
9114 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9115 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9116 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9117 what)
9118 (setq sorting-type (read-char-exclusive)))
9120 (unless getkey-func
9121 (and (= (downcase sorting-type) ?f)
9122 (setq getkey-func
9123 (or (and interactive?
9124 (org-read-function
9125 "Function for extracting keys: "))
9126 (error "Missing key extractor")))))
9128 (and (= (downcase sorting-type) ?r)
9129 (not property)
9130 (setq property
9131 (completing-read "Property: "
9132 (mapcar #'list (org-buffer-property-keys t))
9133 nil t)))
9135 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9136 (message "Sorting entries...")
9138 (save-restriction
9139 (narrow-to-region start end)
9140 (let ((restore-clock?
9141 ;; The clock marker is lost when using `sort-subr'; mark
9142 ;; the clock with temporary `:org-clock-marker-backup'
9143 ;; text property.
9144 (when (and (eq (org-clocking-buffer) (current-buffer))
9145 (<= start (marker-position org-clock-marker))
9146 (>= end (marker-position org-clock-marker)))
9147 (org-with-silent-modifications
9148 (put-text-property (1- org-clock-marker) org-clock-marker
9149 :org-clock-marker-backup t))
9151 (dcst (downcase sorting-type))
9152 (case-fold-search nil)
9153 (now (current-time)))
9154 (sort-subr
9155 (/= dcst sorting-type)
9156 ;; This function moves to the beginning character of the "record" to
9157 ;; be sorted.
9158 (lambda nil
9159 (if (re-search-forward re nil t)
9160 (goto-char (match-beginning 0))
9161 (goto-char (point-max))))
9162 ;; This function moves to the last character of the "record" being
9163 ;; sorted.
9164 (lambda nil
9165 (save-match-data
9166 (condition-case nil
9167 (outline-forward-same-level 1)
9168 (error
9169 (goto-char (point-max))))))
9170 ;; This function returns the value that gets sorted against.
9171 (lambda nil
9172 (cond
9173 ((= dcst ?n)
9174 (if (looking-at org-complex-heading-regexp)
9175 (string-to-number (org-sort-remove-invisible (match-string 4)))
9176 nil))
9177 ((= dcst ?a)
9178 (if (looking-at org-complex-heading-regexp)
9179 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9180 nil))
9181 ((= dcst ?k)
9182 (or (get-text-property (point) :org-clock-minutes) 0))
9183 ((= dcst ?t)
9184 (let ((end (save-excursion (outline-next-heading) (point))))
9185 (if (or (re-search-forward org-ts-regexp end t)
9186 (re-search-forward org-ts-regexp-both end t))
9187 (org-time-string-to-seconds (match-string 0))
9188 (float-time now))))
9189 ((= dcst ?c)
9190 (let ((end (save-excursion (outline-next-heading) (point))))
9191 (if (re-search-forward
9192 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9193 end t)
9194 (org-time-string-to-seconds (match-string 0))
9195 (float-time now))))
9196 ((= dcst ?s)
9197 (let ((end (save-excursion (outline-next-heading) (point))))
9198 (if (re-search-forward org-scheduled-time-regexp end t)
9199 (org-time-string-to-seconds (match-string 1))
9200 (float-time now))))
9201 ((= dcst ?d)
9202 (let ((end (save-excursion (outline-next-heading) (point))))
9203 (if (re-search-forward org-deadline-time-regexp end t)
9204 (org-time-string-to-seconds (match-string 1))
9205 (float-time now))))
9206 ((= dcst ?p)
9207 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9208 (string-to-char (match-string 2))
9209 org-default-priority))
9210 ((= dcst ?r)
9211 (or (org-entry-get nil property) ""))
9212 ((= dcst ?o)
9213 (when (looking-at org-complex-heading-regexp)
9214 (let* ((m (match-string 2))
9215 (s (if (member m org-done-keywords) '- '+)))
9216 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9217 ((= dcst ?f)
9218 (if getkey-func
9219 (progn
9220 (setq tmp (funcall getkey-func))
9221 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9222 tmp)
9223 (error "Invalid key function `%s'" getkey-func)))
9224 (t (error "Invalid sorting type `%c'" sorting-type))))
9226 (cond
9227 ((= dcst ?a) 'string<)
9228 ((= dcst ?f)
9229 (or compare-func
9230 (and interactive?
9231 (org-read-function
9232 (concat "Function for comparing keys "
9233 "(empty for default `sort-subr' predicate): ")
9234 'allow-empty))))
9235 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))
9236 (when restore-clock?
9237 (move-marker org-clock-marker
9238 (1+ (next-single-property-change
9239 start :org-clock-marker-backup)))
9240 (remove-text-properties (1- org-clock-marker) org-clock-marker
9241 '(:org-clock-marker-backup t)))))
9242 (run-hooks 'org-after-sorting-entries-or-items-hook)
9243 (message "Sorting entries...done")))
9245 ;;; The orgstruct minor mode
9247 ;; Define a minor mode which can be used in other modes in order to
9248 ;; integrate the Org mode structure editing commands.
9250 ;; This is really a hack, because the Org mode structure commands use
9251 ;; keys which normally belong to the major mode. Here is how it
9252 ;; works: The minor mode defines all the keys necessary to operate the
9253 ;; structure commands, but wraps the commands into a function which
9254 ;; tests if the cursor is currently at a headline or a plain list
9255 ;; item. If that is the case, the structure command is used,
9256 ;; temporarily setting many Org mode variables like regular
9257 ;; expressions for filling etc. However, when any of those keys is
9258 ;; used at a different location, function uses `key-binding' to look
9259 ;; up if the key has an associated command in another currently active
9260 ;; keymap (minor modes, major mode, global), and executes that
9261 ;; command. There might be problems if any of the keys is otherwise
9262 ;; used as a prefix key.
9264 (defcustom orgstruct-heading-prefix-regexp ""
9265 "Regexp that matches the custom prefix of Org headlines in
9266 orgstruct(++)-mode."
9267 :group 'org
9268 :version "24.4"
9269 :package-version '(Org . "8.3")
9270 :type 'regexp)
9271 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9273 (defcustom orgstruct-setup-hook nil
9274 "Hook run after orgstruct-mode-map is filled."
9275 :group 'org
9276 :version "24.4"
9277 :package-version '(Org . "8.0")
9278 :type 'hook)
9280 (defvar orgstruct-initialized nil)
9282 (defvar org-local-vars nil
9283 "List of local variables, for use by `orgstruct-mode'.")
9285 ;;;###autoload
9286 (define-minor-mode orgstruct-mode
9287 "Toggle the minor mode `orgstruct-mode'.
9288 This mode is for using Org mode structure commands in other
9289 modes. The following keys behave as if Org mode were active, if
9290 the cursor is on a headline, or on a plain list item (both as
9291 defined by Org mode)."
9292 nil " OrgStruct" (make-sparse-keymap)
9293 (funcall (if orgstruct-mode
9294 'add-to-invisibility-spec
9295 'remove-from-invisibility-spec)
9296 '(outline . t))
9297 (when orgstruct-mode
9298 (org-load-modules-maybe)
9299 (unless orgstruct-initialized
9300 (orgstruct-setup)
9301 (setq orgstruct-initialized t))))
9303 ;;;###autoload
9304 (defun turn-on-orgstruct ()
9305 "Unconditionally turn on `orgstruct-mode'."
9306 (orgstruct-mode 1))
9308 (defvar-local orgstruct-is-++ nil
9309 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9310 (defvar-local org-fb-vars nil)
9311 (defun orgstruct++-mode (&optional arg)
9312 "Toggle `orgstruct-mode', the enhanced version of it.
9313 In addition to setting orgstruct-mode, this also exports all
9314 indentation and autofilling variables from Org mode into the
9315 buffer. It will also recognize item context in multiline items."
9316 (interactive "P")
9317 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9318 (if (< arg 1)
9319 (progn (orgstruct-mode -1)
9320 (dolist (v org-fb-vars)
9321 (set (make-local-variable (car v))
9322 (if (eq (car-safe (cadr v)) 'quote)
9323 (cl-cadadr v)
9324 (nth 1 v)))))
9325 (orgstruct-mode 1)
9326 (setq org-fb-vars nil)
9327 (unless org-local-vars
9328 (setq org-local-vars (org-get-local-variables)))
9329 (let (var val)
9330 (dolist (x org-local-vars)
9331 (when (string-match
9332 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9333 \\|fill-prefix\\|indent-\\)"
9334 (symbol-name (car x)))
9335 (setq var (car x) val (nth 1 x))
9336 (push (list var `(quote ,(eval var))) org-fb-vars)
9337 (set (make-local-variable var)
9338 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9339 (setq-local orgstruct-is-++ t))))
9341 ;;;###autoload
9342 (defun turn-on-orgstruct++ ()
9343 "Unconditionally turn on `orgstruct++-mode'."
9344 (orgstruct++-mode 1))
9346 (defun orgstruct-error ()
9347 "Error when there is no default binding for a structure key."
9348 (interactive)
9349 (funcall (if (fboundp 'user-error)
9350 'user-error
9351 'error)
9352 "This key has no function outside structure elements"))
9354 (defun orgstruct-setup ()
9355 "Setup orgstruct keymap."
9356 (dolist (cell '((org-demote . t)
9357 (org-metaleft . t)
9358 (org-metaright . t)
9359 (org-promote . t)
9360 (org-shiftmetaleft . t)
9361 (org-shiftmetaright . t)
9362 org-backward-element
9363 org-backward-heading-same-level
9364 org-ctrl-c-ret
9365 org-ctrl-c-minus
9366 org-ctrl-c-star
9367 org-cycle
9368 org-force-cycle-archived
9369 org-forward-heading-same-level
9370 org-insert-heading
9371 org-insert-heading-respect-content
9372 org-kill-note-or-show-branches
9373 org-mark-subtree
9374 org-meta-return
9375 org-metadown
9376 org-metaup
9377 org-narrow-to-subtree
9378 org-promote-subtree
9379 org-reveal
9380 org-shiftdown
9381 org-shiftleft
9382 org-shiftmetadown
9383 org-shiftmetaup
9384 org-shiftright
9385 org-shifttab
9386 org-shifttab
9387 org-shiftup
9388 org-show-children
9389 org-show-subtree
9390 org-sort
9391 org-up-element
9392 outline-demote
9393 outline-next-visible-heading
9394 outline-previous-visible-heading
9395 outline-promote
9396 outline-up-heading))
9397 (let ((f (or (car-safe cell) cell))
9398 (disable-when-heading-prefix (cdr-safe cell)))
9399 (when (fboundp f)
9400 (let ((new-bindings))
9401 (dolist (binding (nconc (where-is-internal f org-mode-map)
9402 (where-is-internal f outline-mode-map)))
9403 (push binding new-bindings)
9404 ;; TODO use local-function-key-map
9405 (dolist (rep '(("<tab>" . "TAB")
9406 ("<return>" . "RET")
9407 ("<escape>" . "ESC")
9408 ("<delete>" . "DEL")))
9409 (setq binding (read-kbd-macro
9410 (let ((case-fold-search))
9411 (replace-regexp-in-string
9412 (regexp-quote (cdr rep))
9413 (car rep)
9414 (key-description binding)))))
9415 (cl-pushnew binding new-bindings :test 'equal)))
9416 (dolist (binding new-bindings)
9417 (let ((key (lookup-key orgstruct-mode-map binding)))
9418 (when (or (not key) (numberp key))
9419 (ignore-errors
9420 (org-defkey orgstruct-mode-map
9421 binding
9422 (orgstruct-make-binding
9423 f binding disable-when-heading-prefix))))))))))
9424 (run-hooks 'orgstruct-setup-hook))
9426 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9427 "Create a function for binding in the structure minor mode.
9428 FUN is the command to call inside a table. KEY is the key that
9429 should be checked in for a command to execute outside of tables.
9430 Non-nil `disable-when-heading-prefix' means to disable the command
9431 if `orgstruct-heading-prefix-regexp' is not empty."
9432 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9433 (let ((nname name)
9434 (i 0))
9435 (while (fboundp (intern nname))
9436 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9437 (setq name (intern nname)))
9438 (eval
9439 (let ((bindings '((org-heading-regexp
9440 (concat "^"
9441 orgstruct-heading-prefix-regexp
9442 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9443 (org-outline-regexp
9444 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9445 (org-outline-regexp-bol
9446 (concat "^" org-outline-regexp))
9447 (outline-regexp org-outline-regexp)
9448 (outline-heading-end-regexp "\n")
9449 (outline-level 'org-outline-level)
9450 (outline-heading-alist))))
9451 `(defun ,name (arg)
9452 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9453 "Outside of structure, run the binding of `"
9454 (key-description key) "'."
9455 (when disable-when-heading-prefix
9456 (concat
9457 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9458 "back to the default binding due to limitations of Org's implementation of\n"
9459 "`" (symbol-name fun) "'.")))
9460 (interactive "p")
9461 (let* ((disable
9462 ,(and disable-when-heading-prefix
9463 '(not (string= orgstruct-heading-prefix-regexp ""))))
9464 (fallback
9465 (or disable
9466 (not
9467 (let* ,bindings
9468 (org-context-p 'headline 'item
9469 ,(when (memq fun
9470 '(org-insert-heading
9471 org-insert-heading-respect-content
9472 org-meta-return))
9473 '(when orgstruct-is-++
9474 'item-body))))))))
9475 (if fallback
9476 (let* ((orgstruct-mode)
9477 (binding
9478 (let ((key ,key))
9479 (catch 'exit
9480 (dolist
9481 (rep
9482 '(nil
9483 ("<\\([^>]*\\)tab>" . "\\1TAB")
9484 ("<\\([^>]*\\)return>" . "\\1RET")
9485 ("<\\([^>]*\\)escape>" . "\\1ESC")
9486 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9487 nil)
9488 (when rep
9489 (setq key (read-kbd-macro
9490 (let ((case-fold-search))
9491 (replace-regexp-in-string
9492 (car rep)
9493 (cdr rep)
9494 (key-description key))))))
9495 (when (key-binding key)
9496 (throw 'exit (key-binding key))))))))
9497 (if (keymapp binding)
9498 (org-set-transient-map binding)
9499 (let ((func (or binding
9500 (unless disable
9501 'orgstruct-error))))
9502 (when func
9503 (call-interactively func)))))
9504 (org-run-like-in-org-mode
9505 (lambda ()
9506 (interactive)
9507 (let* ,bindings
9508 (call-interactively ',fun)))))))))
9509 name))
9511 (defun org-contextualize-keys (alist contexts)
9512 "Return valid elements in ALIST depending on CONTEXTS.
9514 `org-agenda-custom-commands' or `org-capture-templates' are the
9515 values used for ALIST, and `org-agenda-custom-commands-contexts'
9516 or `org-capture-templates-contexts' are the associated contexts
9517 definitions."
9518 (let ((contexts
9519 ;; normalize contexts
9520 (mapcar
9521 (lambda(c) (cond ((listp (cadr c))
9522 (list (car c) (car c) (nth 1 c)))
9523 ((string= "" (cadr c))
9524 (list (car c) (car c) (nth 2 c)))
9525 (t c)))
9526 contexts))
9527 (a alist) r s)
9528 ;; loop over all commands or templates
9529 (dolist (c a)
9530 (let (vrules repl)
9531 (cond
9532 ((not (assoc (car c) contexts))
9533 (push c r))
9534 ((and (assoc (car c) contexts)
9535 (setq vrules (org-contextualize-validate-key
9536 (car c) contexts)))
9537 (mapc (lambda (vr)
9538 (unless (equal (car vr) (cadr vr))
9539 (setq repl vr)))
9540 vrules)
9541 (if (not repl) (push c r)
9542 (push (cadr repl) s)
9543 (push
9544 (cons (car c)
9545 (cdr (or (assoc (cadr repl) alist)
9546 (error "Undefined key `%s' as contextual replacement for `%s'"
9547 (cadr repl) (car c)))))
9548 r))))))
9549 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9550 (delq
9552 (delete-dups
9553 (mapcar (lambda (x)
9554 (let ((tpl (car x)))
9555 (unless (delq
9557 (mapcar (lambda (y)
9558 (equal y tpl))
9560 x)))
9561 (reverse r))))))
9563 (defun org-contextualize-validate-key (key contexts)
9564 "Check CONTEXTS for agenda or capture KEY."
9565 (let (res)
9566 (dolist (r contexts)
9567 (dolist (rr (car (last r)))
9568 (when
9569 (and (equal key (car r))
9570 (if (functionp rr) (funcall rr)
9571 (or (and (eq (car rr) 'in-file)
9572 (buffer-file-name)
9573 (string-match (cdr rr) (buffer-file-name)))
9574 (and (eq (car rr) 'in-mode)
9575 (string-match (cdr rr) (symbol-name major-mode)))
9576 (and (eq (car rr) 'in-buffer)
9577 (string-match (cdr rr) (buffer-name)))
9578 (when (and (eq (car rr) 'not-in-file)
9579 (buffer-file-name))
9580 (not (string-match (cdr rr) (buffer-file-name))))
9581 (when (eq (car rr) 'not-in-mode)
9582 (not (string-match (cdr rr) (symbol-name major-mode))))
9583 (when (eq (car rr) 'not-in-buffer)
9584 (not (string-match (cdr rr) (buffer-name)))))))
9585 (push r res))))
9586 (delete-dups (delq nil res))))
9588 (defun org-context-p (&rest contexts)
9589 "Check if local context is any of CONTEXTS.
9590 Possible values in the list of contexts are `table', `headline', and `item'."
9591 (let ((pos (point)))
9592 (goto-char (point-at-bol))
9593 (prog1 (or (and (memq 'table contexts)
9594 (looking-at "[ \t]*|"))
9595 (and (memq 'headline contexts)
9596 (looking-at org-outline-regexp))
9597 (and (memq 'item contexts)
9598 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9599 (and (memq 'item-body contexts)
9600 (org-in-item-p)))
9601 (goto-char pos))))
9603 ;;;###autoload
9604 (defun org-run-like-in-org-mode (cmd)
9605 "Run a command, pretending that the current buffer is in Org mode.
9606 This will temporarily bind local variables that are typically bound in
9607 Org mode to the values they have in Org mode, and then interactively
9608 call CMD."
9609 (org-load-modules-maybe)
9610 (unless org-local-vars
9611 (setq org-local-vars (org-get-local-variables)))
9612 (let (binds)
9613 (dolist (var org-local-vars)
9614 (when (or (not (boundp (car var)))
9615 (eq (symbol-value (car var))
9616 (default-value (car var))))
9617 (push (list (car var) `(quote ,(cadr var))) binds)))
9618 (eval `(let ,binds
9619 (call-interactively (quote ,cmd))))))
9621 (defun org-get-category (&optional pos force-refresh)
9622 "Get the category applying to position POS."
9623 (save-match-data
9624 (when force-refresh (org-refresh-category-properties))
9625 (let ((pos (or pos (point))))
9626 (or (get-text-property pos 'org-category)
9627 (progn (org-refresh-category-properties)
9628 (get-text-property pos 'org-category))))))
9630 ;;; Refresh properties
9632 (defun org-refresh-properties (dprop tprop)
9633 "Refresh buffer text properties.
9634 DPROP is the drawer property and TPROP is either the
9635 corresponding text property to set, or an alist with each element
9636 being a text property (as a symbol) and a function to apply to
9637 the value of the drawer property."
9638 (let* ((case-fold-search t)
9639 (inhibit-read-only t)
9640 (inherit? (org-property-inherit-p dprop))
9641 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9642 (global (and inherit? (org--property-global-value dprop nil))))
9643 (org-with-silent-modifications
9644 (org-with-point-at 1
9645 ;; Set global values (e.g., values defined through
9646 ;; "#+PROPERTY:" keywords) to the whole buffer.
9647 (when global (put-text-property (point-min) (point-max) tprop global))
9648 ;; Set local values.
9649 (while (re-search-forward property-re nil t)
9650 (when (org-at-property-p)
9651 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9652 (outline-next-heading))))))
9654 (defun org-refresh-property (tprop p &optional inherit)
9655 "Refresh the buffer text property TPROP from the drawer property P.
9656 The refresh happens only for the current headline, or the whole
9657 sub-tree if optional argument INHERIT is non-nil."
9658 (unless (org-before-first-heading-p)
9659 (save-excursion
9660 (org-back-to-heading t)
9661 (let ((start (point))
9662 (end (save-excursion
9663 (if inherit (org-end-of-subtree t t)
9664 (or (outline-next-heading) (point-max))))))
9665 (if (symbolp tprop)
9666 ;; TPROP is a text property symbol.
9667 (put-text-property start end tprop p)
9668 ;; TPROP is an alist with (property . function) elements.
9669 (pcase-dolist (`(,prop . ,f) tprop)
9670 (put-text-property start end prop (funcall f p))))))))
9672 (defun org-refresh-category-properties ()
9673 "Refresh category text properties in the buffer."
9674 (let ((case-fold-search t)
9675 (inhibit-read-only t)
9676 (default-category
9677 (cond ((null org-category)
9678 (if buffer-file-name
9679 (file-name-sans-extension
9680 (file-name-nondirectory buffer-file-name))
9681 "???"))
9682 ((symbolp org-category) (symbol-name org-category))
9683 (t org-category))))
9684 (org-with-silent-modifications
9685 (org-with-wide-buffer
9686 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9687 ;; This is the default category for the buffer. If none is
9688 ;; found, fall-back to `org-category' or buffer file name.
9689 (put-text-property
9690 (point-min) (point-max)
9691 'org-category
9692 (catch 'buffer-category
9693 (goto-char (point-max))
9694 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9695 (let ((element (org-element-at-point)))
9696 (when (eq (org-element-type element) 'keyword)
9697 (throw 'buffer-category
9698 (org-element-property :value element)))))
9699 default-category))
9700 ;; Set sub-tree specific categories.
9701 (goto-char (point-min))
9702 (let ((regexp (org-re-property "CATEGORY")))
9703 (while (re-search-forward regexp nil t)
9704 (let ((value (match-string-no-properties 3)))
9705 (when (org-at-property-p)
9706 (put-text-property
9707 (save-excursion (org-back-to-heading t) (point))
9708 (save-excursion (org-end-of-subtree t t) (point))
9709 'org-category
9710 value)))))))))
9712 (defun org-refresh-stats-properties ()
9713 "Refresh stats text properties in the buffer."
9714 (org-with-silent-modifications
9715 (org-with-point-at 1
9716 (let ((regexp (concat org-outline-regexp-bol
9717 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9718 (while (re-search-forward regexp nil t)
9719 (let* ((numerator (string-to-number (match-string 1)))
9720 (denominator (and (match-end 2)
9721 (string-to-number (match-string 2))))
9722 (stats (cond ((not denominator) numerator) ;percent
9723 ((= denominator 0) 0)
9724 (t (/ (* numerator 100) denominator)))))
9725 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9726 'org-stats stats)))))))
9728 (defun org-refresh-effort-properties ()
9729 "Refresh effort properties"
9730 (org-refresh-properties
9731 org-effort-property
9732 '((effort . identity)
9733 (effort-minutes . org-duration-string-to-minutes))))
9735 ;;;; Link Stuff
9737 ;;; Link abbreviations
9739 (defun org-link-expand-abbrev (link)
9740 "Apply replacements as defined in `org-link-abbrev-alist'."
9741 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9742 (let* ((key (match-string 1 link))
9743 (as (or (assoc key org-link-abbrev-alist-local)
9744 (assoc key org-link-abbrev-alist)))
9745 (tag (and (match-end 2) (match-string 3 link)))
9746 rpl)
9747 (if (not as)
9748 link
9749 (setq rpl (cdr as))
9750 (cond
9751 ((symbolp rpl) (funcall rpl tag))
9752 ((string-match "%(\\([^)]+\\))" rpl)
9753 (replace-match
9754 (save-match-data
9755 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9756 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9757 ((string-match "%h" rpl)
9758 (replace-match (url-hexify-string (or tag "")) t t rpl))
9759 (t (concat rpl tag)))))
9760 link))
9762 ;;; Storing and inserting links
9764 (defvar org-insert-link-history nil
9765 "Minibuffer history for links inserted with `org-insert-link'.")
9767 (defvar org-stored-links nil
9768 "Contains the links stored with `org-store-link'.")
9770 (defvar org-store-link-plist nil
9771 "Plist with info about the most recently link created with `org-store-link'.")
9773 (defun org-store-link-functions ()
9774 "Return a list of functions that are called to create and store a link.
9775 The functions defined in the :store property of
9776 `org-link-parameters'.
9778 Each function will be called in turn until one returns a non-nil
9779 value. Each function should check if it is responsible for
9780 creating this link (for example by looking at the major mode).
9781 If not, it must exit and return nil. If yes, it should return
9782 a non-nil value after calling `org-store-link-props' with a list
9783 of properties and values. Special properties are:
9785 :type The link prefix, like \"http\". This must be given.
9786 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9787 This is obligatory as well.
9788 :description Optional default description for the second pair
9789 of brackets in an Org mode link. The user can still change
9790 this when inserting this link into an Org mode buffer.
9792 In addition to these, any additional properties can be specified
9793 and then used in capture templates."
9794 (cl-loop for link in org-link-parameters
9795 with store-func
9796 do (setq store-func (org-link-get-parameter (car link) :store))
9797 if store-func
9798 collect store-func))
9800 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9801 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9803 ;;;###autoload
9804 (defun org-store-link (arg)
9805 "Store an org-link to the current location.
9806 \\<org-mode-map>
9807 This link is added to `org-stored-links' and can later be inserted
9808 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9810 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9811 A single
9812 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9813 `org-gnus-prefer-web-links' for links to Usenet articles.
9815 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9816 skipping storing functions that are not
9817 part of Org core.
9819 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9820 prefix ARG forces storing a link for each line in the
9821 active region."
9822 (interactive "P")
9823 (org-load-modules-maybe)
9824 (if (and (equal arg '(64)) (org-region-active-p))
9825 (save-excursion
9826 (let ((end (region-end)))
9827 (goto-char (region-beginning))
9828 (set-mark (point))
9829 (while (< (point-at-eol) end)
9830 (move-end-of-line 1) (activate-mark)
9831 (let (current-prefix-arg)
9832 (call-interactively 'org-store-link))
9833 (move-beginning-of-line 2)
9834 (set-mark (point)))))
9835 (setq org-store-link-plist nil)
9836 (let (link cpltxt desc description search
9837 txt custom-id agenda-link sfuns sfunsn)
9838 (cond
9840 ;; Store a link using an external link type
9841 ((and (not (equal arg '(16)))
9842 (setq sfuns
9843 (delq
9844 nil (mapcar (lambda (f)
9845 (let (fs) (if (funcall f) (push f fs))))
9846 (org-store-link-functions)))
9847 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9848 (or (and (cdr sfuns)
9849 (funcall (intern
9850 (completing-read
9851 "Which function for creating the link? "
9852 sfunsn nil t (car sfunsn)))))
9853 (funcall (caar sfuns)))
9854 (setq link (plist-get org-store-link-plist :link)
9855 desc (or (plist-get org-store-link-plist
9856 :description)
9857 link))))
9859 ;; Store a link from a source code buffer.
9860 ((org-src-edit-buffer-p)
9861 (let ((coderef-format (org-src-coderef-format)))
9862 (cond ((save-excursion
9863 (beginning-of-line)
9864 (looking-at (org-src-coderef-regexp coderef-format)))
9865 (setq link (format "(%s)" (match-string-no-properties 3))))
9866 ((called-interactively-p 'any)
9867 (let ((label (read-string "Code line label: ")))
9868 (end-of-line)
9869 (setq link (format coderef-format label))
9870 (let ((gc (- 79 (length link))))
9871 (if (< (current-column) gc)
9872 (org-move-to-column gc t)
9873 (insert " ")))
9874 (insert link)
9875 (setq link (concat "(" label ")"))
9876 (setq desc nil)))
9877 (t (setq link nil)))))
9879 ;; We are in the agenda, link to referenced location
9880 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9881 (let ((m (or (get-text-property (point) 'org-hd-marker)
9882 (get-text-property (point) 'org-marker))))
9883 (when m
9884 (org-with-point-at m
9885 (setq agenda-link
9886 (if (called-interactively-p 'any)
9887 (call-interactively 'org-store-link)
9888 (org-store-link nil)))))))
9890 ((eq major-mode 'calendar-mode)
9891 (let ((cd (calendar-cursor-to-date)))
9892 (setq link
9893 (format-time-string
9894 (car org-time-stamp-formats)
9895 (apply 'encode-time
9896 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9897 nil nil nil))))
9898 (org-store-link-props :type "calendar" :date cd)))
9900 ((eq major-mode 'help-mode)
9901 (setq link (concat "help:" (save-excursion
9902 (goto-char (point-min))
9903 (looking-at "^[^ ]+")
9904 (match-string 0))))
9905 (org-store-link-props :type "help"))
9907 ((eq major-mode 'w3-mode)
9908 (setq cpltxt (if (and (buffer-name)
9909 (not (string-match "Untitled" (buffer-name))))
9910 (buffer-name)
9911 (url-view-url t))
9912 link (url-view-url t))
9913 (org-store-link-props :type "w3" :url (url-view-url t)))
9915 ((eq major-mode 'image-mode)
9916 (setq cpltxt (concat "file:"
9917 (abbreviate-file-name buffer-file-name))
9918 link cpltxt)
9919 (org-store-link-props :type "image" :file buffer-file-name))
9921 ;; In dired, store a link to the file of the current line
9922 ((derived-mode-p 'dired-mode)
9923 (let ((file (dired-get-filename nil t)))
9924 (setq file (if file
9925 (abbreviate-file-name
9926 (expand-file-name (dired-get-filename nil t)))
9927 ;; otherwise, no file so use current directory.
9928 default-directory))
9929 (setq cpltxt (concat "file:" file)
9930 link cpltxt)))
9932 ((setq search (run-hook-with-args-until-success
9933 'org-create-file-search-functions))
9934 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9935 "::" search))
9936 (setq cpltxt (or description link)))
9938 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9939 (org-with-limited-levels
9940 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9941 (cond
9942 ;; Store a link using the target at point
9943 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9944 (setq cpltxt
9945 (concat "file:"
9946 (abbreviate-file-name
9947 (buffer-file-name (buffer-base-buffer)))
9948 "::" (match-string 1))
9949 link cpltxt))
9950 ((and (featurep 'org-id)
9951 (or (eq org-id-link-to-org-use-id t)
9952 (and (called-interactively-p 'any)
9953 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9954 (and (eq org-id-link-to-org-use-id
9955 'create-if-interactive-and-no-custom-id)
9956 (not custom-id))))
9957 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9958 ;; Store a link using the ID at point
9959 (setq link (condition-case nil
9960 (prog1 (org-id-store-link)
9961 (setq desc (or (plist-get org-store-link-plist
9962 :description)
9963 "")))
9964 (error
9965 ;; Probably before first headline, link only to file
9966 (concat "file:"
9967 (abbreviate-file-name
9968 (buffer-file-name (buffer-base-buffer))))))))
9970 ;; Just link to current headline
9971 (setq cpltxt (concat "file:"
9972 (abbreviate-file-name
9973 (buffer-file-name (buffer-base-buffer)))))
9974 ;; Add a context search string
9975 (when (org-xor org-context-in-file-links
9976 (equal arg '(4)))
9977 (let* ((element (org-element-at-point))
9978 (name (org-element-property :name element)))
9979 (setq txt (cond
9980 ((org-at-heading-p) nil)
9981 (name)
9982 ((org-region-active-p)
9983 (buffer-substring (region-beginning) (region-end)))))
9984 (when (or (null txt) (string-match "\\S-" txt))
9985 (setq cpltxt
9986 (concat cpltxt "::"
9987 (condition-case nil
9988 (org-make-org-heading-search-string txt)
9989 (error "")))
9990 desc (or name
9991 (nth 4 (ignore-errors (org-heading-components)))
9992 "NONE")))))
9993 (when (string-match "::\\'" cpltxt)
9994 (setq cpltxt (substring cpltxt 0 -2)))
9995 (setq link cpltxt)))))
9997 ((buffer-file-name (buffer-base-buffer))
9998 ;; Just link to this file here.
9999 (setq cpltxt (concat "file:"
10000 (abbreviate-file-name
10001 (buffer-file-name (buffer-base-buffer)))))
10002 ;; Add a context string.
10003 (when (org-xor org-context-in-file-links
10004 (equal arg '(4)))
10005 (setq txt (if (org-region-active-p)
10006 (buffer-substring (region-beginning) (region-end))
10007 (buffer-substring (point-at-bol) (point-at-eol))))
10008 ;; Only use search option if there is some text.
10009 (when (string-match "\\S-" txt)
10010 (setq cpltxt
10011 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10012 desc "NONE")))
10013 (setq link cpltxt))
10015 ((called-interactively-p 'interactive)
10016 (user-error "No method for storing a link from this buffer"))
10018 (t (setq link nil)))
10020 ;; We're done setting link and desc, clean up
10021 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10022 (setq link (or link cpltxt)
10023 desc (or desc cpltxt))
10024 (cond ((not desc))
10025 ((equal desc "NONE") (setq desc nil))
10026 (t (setq desc
10027 (replace-regexp-in-string
10028 org-bracket-link-analytic-regexp
10029 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10030 desc))))
10031 ;; Return the link
10032 (if (not (and (or (called-interactively-p 'any)
10033 executing-kbd-macro)
10034 link))
10035 (or agenda-link (and link (org-make-link-string link desc)))
10036 (push (list link desc) org-stored-links)
10037 (message "Stored: %s" (or desc link))
10038 (when custom-id
10039 (setq link (concat "file:" (abbreviate-file-name
10040 (buffer-file-name)) "::#" custom-id))
10041 (push (list link desc) org-stored-links))
10042 (car org-stored-links)))))
10044 (defun org-store-link-props (&rest plist)
10045 "Store link properties, extract names, addresses and dates."
10046 (let ((x (plist-get plist :from)))
10047 (when x
10048 (let ((adr (mail-extract-address-components x)))
10049 (setq plist (plist-put plist :fromname (car adr)))
10050 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10051 (let ((x (plist-get plist :to)))
10052 (when x
10053 (let ((adr (mail-extract-address-components x)))
10054 (setq plist (plist-put plist :toname (car adr)))
10055 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10056 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10057 (when x
10058 (setq plist (plist-put plist :date-timestamp
10059 (format-time-string
10060 (org-time-stamp-format t) x)))
10061 (setq plist (plist-put plist :date-timestamp-inactive
10062 (format-time-string
10063 (org-time-stamp-format t t) x)))))
10064 (let ((from (plist-get plist :from))
10065 (to (plist-get plist :to)))
10066 (when (and from to org-from-is-user-regexp)
10067 (setq plist
10068 (plist-put plist :fromto
10069 (if (string-match org-from-is-user-regexp from)
10070 (concat "to %t")
10071 (concat "from %f"))))))
10072 (setq org-store-link-plist plist))
10074 (defun org-add-link-props (&rest plist)
10075 "Add these properties to the link property list."
10076 (let (key value)
10077 (while plist
10078 (setq key (pop plist) value (pop plist))
10079 (setq org-store-link-plist
10080 (plist-put org-store-link-plist key value)))))
10082 (defun org-email-link-description (&optional fmt)
10083 "Return the description part of an email link.
10084 This takes information from `org-store-link-plist' and formats it
10085 according to FMT (default from `org-email-link-description-format')."
10086 (setq fmt (or fmt org-email-link-description-format))
10087 (let* ((p org-store-link-plist)
10088 (to (plist-get p :toaddress))
10089 (from (plist-get p :fromaddress))
10090 (table
10091 (list
10092 (cons "%c" (plist-get p :fromto))
10093 (cons "%F" (plist-get p :from))
10094 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10095 (cons "%T" (plist-get p :to))
10096 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10097 (cons "%s" (plist-get p :subject))
10098 (cons "%d" (plist-get p :date))
10099 (cons "%m" (plist-get p :message-id)))))
10100 (when (string-match "%c" fmt)
10101 ;; Check if the user wrote this message
10102 (if (and org-from-is-user-regexp from to
10103 (save-match-data (string-match org-from-is-user-regexp from)))
10104 (setq fmt (replace-match "to %t" t t fmt))
10105 (setq fmt (replace-match "from %f" t t fmt))))
10106 (org-replace-escapes fmt table)))
10108 (defun org-make-org-heading-search-string (&optional string)
10109 "Make search string for the current headline or STRING."
10110 (let ((s (or string
10111 (and (derived-mode-p 'org-mode)
10112 (save-excursion
10113 (org-back-to-heading t)
10114 (org-element-property :raw-value (org-element-at-point))))))
10115 (lines org-context-in-file-links))
10116 (or string (setq s (concat "*" s))) ; Add * for headlines
10117 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10118 (when (and string (integerp lines) (> lines 0))
10119 (let ((slines (org-split-string s "\n")))
10120 (when (< lines (length slines))
10121 (setq s (mapconcat
10122 'identity
10123 (reverse (nthcdr (- (length slines) lines)
10124 (reverse slines))) "\n")))))
10125 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10127 (defun org-make-link-string (link &optional description)
10128 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10129 (unless (org-string-nw-p link) (error "Empty link"))
10130 (let ((uri (cond ((string-match org-link-types-re link)
10131 (concat (match-string 1 link)
10132 (org-link-escape (substring link (match-end 1)))))
10133 ;; For readability, url-encode internal links only
10134 ;; when absolutely needed (i.e, when they contain
10135 ;; square brackets). File links however, are
10136 ;; encoded since, e.g., spaces are significant.
10137 ((or (file-name-absolute-p link)
10138 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10139 (org-link-escape link))
10140 (t link)))
10141 (description
10142 (and (org-string-nw-p description)
10143 ;; Remove brackets from description, as they are fatal.
10144 (replace-regexp-in-string
10145 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10146 (org-trim description)))))
10147 (format "[[%s]%s]"
10149 (if description (format "[%s]" description) ""))))
10151 (defconst org-link-escape-chars
10152 ;;%20 %5B %5D %25
10153 '(?\s ?\[ ?\] ?%)
10154 "List of characters that should be escaped in a link when stored to Org.
10155 This is the list that is used for internal purposes.")
10157 (defun org-link-escape (text &optional table merge)
10158 "Return percent escaped representation of TEXT.
10159 TEXT is a string with the text to escape.
10160 Optional argument TABLE is a list with characters that should be
10161 escaped. When nil, `org-link-escape-chars' is used.
10162 If optional argument MERGE is set, merge TABLE into
10163 `org-link-escape-chars'."
10164 (let ((characters-to-encode
10165 (cond ((null table) org-link-escape-chars)
10166 (merge (append org-link-escape-chars table))
10167 (t table))))
10168 (mapconcat
10169 (lambda (c)
10170 (if (or (memq c characters-to-encode)
10171 (and org-url-hexify-p (or (< c 32) (> c 126))))
10172 (mapconcat (lambda (e) (format "%%%.2X" e))
10173 (or (encode-coding-char c 'utf-8)
10174 (error "Unable to percent escape character: %c" c))
10176 (char-to-string c)))
10177 text "")))
10179 (defun org-link-unescape (str)
10180 "Unhex hexified Unicode parts in string STR.
10181 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10182 reciprocal of `org-link-escape', which see."
10183 (if (org-string-nw-p str)
10184 (replace-regexp-in-string
10185 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10186 str))
10188 (defun org-link-unescape-compound (hex)
10189 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10190 Note: this function also decodes single byte encodings like
10191 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10192 (save-match-data
10193 (let* ((bytes (cdr (split-string hex "%")))
10194 (ret "")
10195 (eat 0)
10196 (sum 0))
10197 (while bytes
10198 (let* ((val (string-to-number (pop bytes) 16))
10199 (shift-xor
10200 (if (= 0 eat)
10201 (cond
10202 ((>= val 252) (cons 6 252))
10203 ((>= val 248) (cons 5 248))
10204 ((>= val 240) (cons 4 240))
10205 ((>= val 224) (cons 3 224))
10206 ((>= val 192) (cons 2 192))
10207 (t (cons 0 0)))
10208 (cons 6 128))))
10209 (when (>= val 192) (setq eat (car shift-xor)))
10210 (setq val (logxor val (cdr shift-xor)))
10211 (setq sum (+ (lsh sum (car shift-xor)) val))
10212 (when (> eat 0) (setq eat (- eat 1)))
10213 (cond
10214 ((= 0 eat) ;multi byte
10215 (setq ret (concat ret (char-to-string sum)))
10216 (setq sum 0))
10217 ((not bytes) ; single byte(s)
10218 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10219 ret)))
10221 (defun org-link-unescape-single-byte-sequence (hex)
10222 "Unhexify hex-encoded single byte character sequences."
10223 (mapconcat (lambda (byte)
10224 (char-to-string (string-to-number byte 16)))
10225 (cdr (split-string hex "%")) ""))
10227 (defun org-xor (a b)
10228 "Exclusive or."
10229 (if a (not b) b))
10231 (defun org-fixup-message-id-for-http (s)
10232 "Replace special characters in a message id, so it can be used in an http query."
10233 (when (string-match "%" s)
10234 (setq s (mapconcat (lambda (c)
10235 (if (eq c ?%)
10236 "%25"
10237 (char-to-string c)))
10238 s "")))
10239 (while (string-match "<" s)
10240 (setq s (replace-match "%3C" t t s)))
10241 (while (string-match ">" s)
10242 (setq s (replace-match "%3E" t t s)))
10243 (while (string-match "@" s)
10244 (setq s (replace-match "%40" t t s)))
10247 (defun org-link-prettify (link)
10248 "Return a human-readable representation of LINK.
10249 The car of LINK must be a raw link.
10250 The cdr of LINK must be either a link description or nil."
10251 (let ((desc (or (cadr link) "<no description>")))
10252 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10253 "<" (car link) ">")))
10255 ;;;###autoload
10256 (defun org-insert-link-global ()
10257 "Insert a link like Org mode does.
10258 This command can be called in any mode to insert a link in Org syntax."
10259 (interactive)
10260 (org-load-modules-maybe)
10261 (org-run-like-in-org-mode 'org-insert-link))
10263 (defun org-insert-all-links (arg &optional pre post)
10264 "Insert all links in `org-stored-links'.
10265 When a universal prefix, do not delete the links from `org-stored-links'.
10266 When `ARG' is a number, insert the last N link(s).
10267 `PRE' and `POST' are optional arguments to define a string to
10268 prepend or to append."
10269 (interactive "P")
10270 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10271 (links (copy-sequence org-stored-links))
10272 (pr (or pre "- "))
10273 (po (or post "\n"))
10274 (cnt 1) l)
10275 (if (null org-stored-links)
10276 (message "No link to insert")
10277 (while (and (or (listp arg) (>= arg cnt))
10278 (setq l (if (listp arg)
10279 (pop links)
10280 (pop org-stored-links))))
10281 (setq cnt (1+ cnt))
10282 (insert pr)
10283 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10284 (insert po)))))
10286 (defun org-insert-last-stored-link (arg)
10287 "Insert the last link stored in `org-stored-links'."
10288 (interactive "p")
10289 (org-insert-all-links arg "" "\n"))
10291 (defun org-link-fontify-links-to-this-file ()
10292 "Fontify links to the current file in `org-stored-links'."
10293 (let ((f (buffer-file-name)) a b)
10294 (setq a (mapcar (lambda(l)
10295 (let ((ll (car l)))
10296 (when (and (string-match "^file:\\(.+\\)::" ll)
10297 (equal f (expand-file-name (match-string 1 ll))))
10298 ll)))
10299 org-stored-links))
10300 (when (featurep 'org-id)
10301 (setq b (mapcar (lambda(l)
10302 (let ((ll (car l)))
10303 (when (and (string-match "^id:\\(.+\\)$" ll)
10304 (equal f (expand-file-name
10305 (or (org-id-find-id-file
10306 (match-string 1 ll)) ""))))
10307 ll)))
10308 org-stored-links)))
10309 (mapcar (lambda(l)
10310 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10311 (delq nil (append a b)))))
10313 (defvar org--links-history nil)
10314 (defun org-insert-link (&optional complete-file link-location default-description)
10315 "Insert a link. At the prompt, enter the link.
10317 Completion can be used to insert any of the link protocol prefixes in use.
10319 The history can be used to select a link previously stored with
10320 `org-store-link'. When the empty string is entered (i.e. if you just
10321 press `RET' at the prompt), the link defaults to the most recently
10322 stored link. As `SPC' triggers completion in the minibuffer, you need to
10323 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10325 You will also be prompted for a description, and if one is given, it will
10326 be displayed in the buffer instead of the link.
10328 If there is already a link at point, this command will allow you to edit
10329 link and description parts.
10331 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10332 file name can be
10333 selected using completion. The path to the file will be relative to the
10334 current directory if the file is in the current directory or a subdirectory.
10335 Otherwise, the link will be the absolute path as completed in the minibuffer
10336 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10337 option `org-link-file-path-type'.
10339 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10340 absolute path even if the file is in
10341 the current directory or below.
10343 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10344 prefix negates `org-keep-stored-link-after-insertion'.
10346 If `org-make-link-description-function' is non-nil, this function will be
10347 called with the link target, and the result will be the default
10348 link description.
10350 If the LINK-LOCATION parameter is non-nil, this value will be used as
10351 the link location instead of reading one interactively.
10353 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10354 as the default description."
10355 (interactive "P")
10356 (let* ((wcf (current-window-configuration))
10357 (origbuf (current-buffer))
10358 (region (when (org-region-active-p)
10359 (buffer-substring (region-beginning) (region-end))))
10360 (remove (and region (list (region-beginning) (region-end))))
10361 (desc region)
10362 (link link-location)
10363 (abbrevs org-link-abbrev-alist-local)
10364 entry all-prefixes auto-desc)
10365 (cond
10366 (link-location) ; specified by arg, just use it.
10367 ((org-in-regexp org-bracket-link-regexp 1)
10368 ;; We do have a link at point, and we are going to edit it.
10369 (setq remove (list (match-beginning 0) (match-end 0)))
10370 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10371 (setq link (read-string "Link: "
10372 (org-link-unescape
10373 (match-string-no-properties 1)))))
10374 ((or (org-in-regexp org-angle-link-re)
10375 (org-in-regexp org-plain-link-re))
10376 ;; Convert to bracket link
10377 (setq remove (list (match-beginning 0) (match-end 0))
10378 link (read-string "Link: "
10379 (org-unbracket-string "<" ">" (match-string 0)))))
10380 ((member complete-file '((4) (16)))
10381 ;; Completing read for file names.
10382 (setq link (org-file-complete-link complete-file)))
10384 ;; Read link, with completion for stored links.
10385 (org-link-fontify-links-to-this-file)
10386 (org-switch-to-buffer-other-window "*Org Links*")
10387 (with-current-buffer "*Org Links*"
10388 (erase-buffer)
10389 (insert "Insert a link.
10390 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10391 (when org-stored-links
10392 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10393 (insert (mapconcat 'org-link-prettify
10394 (reverse org-stored-links) "\n")))
10395 (goto-char (point-min)))
10396 (let ((cw (selected-window)))
10397 (select-window (get-buffer-window "*Org Links*" 'visible))
10398 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10399 (unless (pos-visible-in-window-p (point-max))
10400 (org-fit-window-to-buffer))
10401 (and (window-live-p cw) (select-window cw)))
10402 (setq all-prefixes (append (mapcar 'car abbrevs)
10403 (mapcar 'car org-link-abbrev-alist)
10404 (org-link-types)))
10405 (unwind-protect
10406 ;; Fake a link history, containing the stored links.
10407 (let ((org--links-history
10408 (append (mapcar #'car org-stored-links)
10409 org-insert-link-history)))
10410 (setq link
10411 (org-completing-read
10412 "Link: "
10413 (append
10414 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10415 (mapcar #'car org-stored-links))
10416 nil nil nil
10417 'org--links-history
10418 (caar org-stored-links)))
10419 (unless (org-string-nw-p link) (user-error "No link selected"))
10420 (dolist (l org-stored-links)
10421 (when (equal link (cadr l))
10422 (setq link (car l))
10423 (setq auto-desc t)))
10424 (when (or (member link all-prefixes)
10425 (and (equal ":" (substring link -1))
10426 (member (substring link 0 -1) all-prefixes)
10427 (setq link (substring link 0 -1))))
10428 (setq link (with-current-buffer origbuf
10429 (org-link-try-special-completion link)))))
10430 (set-window-configuration wcf)
10431 (kill-buffer "*Org Links*"))
10432 (setq entry (assoc link org-stored-links))
10433 (or entry (push link org-insert-link-history))
10434 (setq desc (or desc (nth 1 entry)))))
10436 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10437 (not org-keep-stored-link-after-insertion))
10438 (setq org-stored-links (delq (assoc link org-stored-links)
10439 org-stored-links)))
10441 (when (and (string-match org-plain-link-re link)
10442 (not (string-match org-ts-regexp link)))
10443 ;; URL-like link, normalize the use of angular brackets.
10444 (setq link (org-unbracket-string "<" ">" link)))
10446 ;; Check if we are linking to the current file with a search
10447 ;; option If yes, simplify the link by using only the search
10448 ;; option.
10449 (when (and buffer-file-name
10450 (let ((case-fold-search nil))
10451 (string-match "\\`file:\\(.+?\\)::" link)))
10452 (let ((path (match-string-no-properties 1 link))
10453 (search (substring-no-properties link (match-end 0))))
10454 (save-match-data
10455 (when (equal (file-truename buffer-file-name) (file-truename path))
10456 ;; We are linking to this same file, with a search option
10457 (setq link search)))))
10459 ;; Check if we can/should use a relative path. If yes, simplify the link
10460 (let ((case-fold-search nil))
10461 (when (string-match "\\`\\(file\\|docview\\):" link)
10462 (let* ((type (match-string-no-properties 0 link))
10463 (path (substring-no-properties link (match-end 0)))
10464 (origpath path))
10465 (cond
10466 ((or (eq org-link-file-path-type 'absolute)
10467 (equal complete-file '(16)))
10468 (setq path (abbreviate-file-name (expand-file-name path))))
10469 ((eq org-link-file-path-type 'noabbrev)
10470 (setq path (expand-file-name path)))
10471 ((eq org-link-file-path-type 'relative)
10472 (setq path (file-relative-name path)))
10474 (save-match-data
10475 (if (string-match (concat "^" (regexp-quote
10476 (expand-file-name
10477 (file-name-as-directory
10478 default-directory))))
10479 (expand-file-name path))
10480 ;; We are linking a file with relative path name.
10481 (setq path (substring (expand-file-name path)
10482 (match-end 0)))
10483 (setq path (abbreviate-file-name (expand-file-name path)))))))
10484 (setq link (concat type path))
10485 (when (equal desc origpath)
10486 (setq desc path)))))
10488 (if org-make-link-description-function
10489 (setq desc
10490 (or (condition-case nil
10491 (funcall org-make-link-description-function link desc)
10492 (error (progn (message "Can't get link description from `%s'"
10493 (symbol-name org-make-link-description-function))
10494 (sit-for 2) nil)))
10495 (read-string "Description: " default-description)))
10496 (if default-description (setq desc default-description)
10497 (setq desc (or (and auto-desc desc)
10498 (read-string "Description: " desc)))))
10500 (unless (string-match "\\S-" desc) (setq desc nil))
10501 (when remove (apply 'delete-region remove))
10502 (insert (org-make-link-string link desc))
10503 ;; Redisplay so as the new link has proper invisible characters.
10504 (sit-for 0)))
10506 (defun org-link-try-special-completion (type)
10507 "If there is completion support for link type TYPE, offer it."
10508 (let ((fun (org-link-get-parameter type :complete)))
10509 (if (functionp fun)
10510 (funcall fun)
10511 (read-string "Link (no completion support): " (concat type ":")))))
10513 (defun org-file-complete-link (&optional arg)
10514 "Create a file link using completion."
10515 (let ((file (read-file-name "File: "))
10516 (pwd (file-name-as-directory (expand-file-name ".")))
10517 (pwd1 (file-name-as-directory (abbreviate-file-name
10518 (expand-file-name ".")))))
10519 (cond ((equal arg '(16))
10520 (concat "file:"
10521 (abbreviate-file-name (expand-file-name file))))
10522 ((string-match
10523 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10524 (concat "file:" (match-string 1 file)))
10525 ((string-match
10526 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10527 (expand-file-name file))
10528 (concat "file:"
10529 (match-string 1 (expand-file-name file))))
10530 (t (concat "file:" file)))))
10532 (defun org-completing-read (&rest args)
10533 "Completing-read with SPACE being a normal character."
10534 (let ((enable-recursive-minibuffers t)
10535 (minibuffer-local-completion-map
10536 (copy-keymap minibuffer-local-completion-map)))
10537 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10538 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10539 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10540 'org-time-stamp-inactive)
10541 (apply #'completing-read args)))
10543 ;;; Opening/following a link
10545 (defvar org-link-search-failed nil)
10547 (defvar org-open-link-functions nil
10548 "Hook for functions finding a plain text link.
10549 These functions must take a single argument, the link content.
10550 They will be called for links that look like [[link text][description]]
10551 when LINK TEXT does not have a protocol like \"http:\" and does not look
10552 like a filename (e.g. \"./blue.png\").
10554 These functions will be called *before* Org attempts to resolve the
10555 link by doing text searches in the current buffer - so if you want a
10556 link \"[[target]]\" to still find \"<<target>>\", your function should
10557 handle this as a special case.
10559 When the function does handle the link, it must return a non-nil value.
10560 If it decides that it is not responsible for this link, it must return
10561 nil to indicate that that Org can continue with other options like
10562 exact and fuzzy text search.")
10564 (defun org-next-link (&optional search-backward)
10565 "Move forward to the next link.
10566 If the link is in hidden text, expose it."
10567 (interactive "P")
10568 (when (and org-link-search-failed (eq this-command last-command))
10569 (goto-char (point-min))
10570 (message "Link search wrapped back to beginning of buffer"))
10571 (setq org-link-search-failed nil)
10572 (let* ((pos (point))
10573 (ct (org-context))
10574 (a (assq :link ct))
10575 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10576 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10577 ((looking-at org-any-link-re)
10578 ;; Don't stay stuck at link without an org-link face
10579 (forward-char (if search-backward -1 1))))
10580 (if (funcall srch-fun org-any-link-re nil t)
10581 (progn
10582 (goto-char (match-beginning 0))
10583 (when (org-invisible-p) (org-show-context)))
10584 (goto-char pos)
10585 (setq org-link-search-failed t)
10586 (message "No further link found"))))
10588 (defun org-previous-link ()
10589 "Move backward to the previous link.
10590 If the link is in hidden text, expose it."
10591 (interactive)
10592 (funcall 'org-next-link t))
10594 (defun org-translate-link (s)
10595 "Translate a link string if a translation function has been defined."
10596 (with-temp-buffer
10597 (insert (org-trim s))
10598 (org-trim (org-element-interpret-data (org-element-context)))))
10600 (defun org-translate-link-from-planner (type path)
10601 "Translate a link from Emacs Planner syntax so that Org can follow it.
10602 This is still an experimental function, your mileage may vary."
10603 (cond
10604 ((member type '("http" "https" "news" "ftp"))
10605 ;; standard Internet links are the same.
10606 nil)
10607 ((and (equal type "irc") (string-match "^//" path))
10608 ;; Planner has two / at the beginning of an irc link, we have 1.
10609 ;; We should have zero, actually....
10610 (setq path (substring path 1)))
10611 ((and (equal type "lisp") (string-match "^/" path))
10612 ;; Planner has a slash, we do not.
10613 (setq type "elisp" path (substring path 1)))
10614 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10615 ;; A typical message link. Planner has the id after the final slash,
10616 ;; we separate it with a hash mark
10617 (setq path (concat (match-string 1 path) "#"
10618 (org-unbracket-string "<" ">" (match-string 2 path))))))
10619 (cons type path))
10621 (defun org-find-file-at-mouse (ev)
10622 "Open file link or URL at mouse."
10623 (interactive "e")
10624 (mouse-set-point ev)
10625 (org-open-at-point 'in-emacs))
10627 (defun org-open-at-mouse (ev)
10628 "Open file link or URL at mouse.
10629 See the docstring of `org-open-file' for details."
10630 (interactive "e")
10631 (mouse-set-point ev)
10632 (when (eq major-mode 'org-agenda-mode)
10633 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10634 (org-open-at-point))
10636 (defvar org-window-config-before-follow-link nil
10637 "The window configuration before following a link.
10638 This is saved in case the need arises to restore it.")
10640 ;;;###autoload
10641 (defun org-open-at-point-global ()
10642 "Follow a link or time-stamp like Org mode does.
10643 This command can be called in any mode to follow an external link
10644 or a time-stamp that has Org mode syntax. Its behavior is
10645 undefined when called on internal links (e.g., fuzzy links).
10646 Raise an error when there is nothing to follow. "
10647 (interactive)
10648 (cond ((org-in-regexp org-any-link-re)
10649 (org-open-link-from-string (match-string-no-properties 0)))
10650 ((or (org-in-regexp org-ts-regexp-both nil t)
10651 (org-in-regexp org-tsr-regexp-both nil t))
10652 (org-follow-timestamp-link))
10653 (t (user-error "No link found"))))
10655 ;;;###autoload
10656 (defun org-open-link-from-string (s &optional arg reference-buffer)
10657 "Open a link in the string S, as if it was in Org mode."
10658 (interactive "sLink: \nP")
10659 (let ((reference-buffer (or reference-buffer (current-buffer))))
10660 (with-temp-buffer
10661 (let ((org-inhibit-startup (not reference-buffer)))
10662 (org-mode)
10663 (insert s)
10664 (goto-char (point-min))
10665 (when reference-buffer
10666 (setq org-link-abbrev-alist-local
10667 (with-current-buffer reference-buffer
10668 org-link-abbrev-alist-local)))
10669 (org-open-at-point arg reference-buffer)))))
10671 (defvar org-open-at-point-functions nil
10672 "Hook that is run when following a link at point.
10674 Functions in this hook must return t if they identify and follow
10675 a link at point. If they don't find anything interesting at point,
10676 they must return nil.")
10678 (defvar org-link-search-inhibit-query nil)
10679 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10680 (defun org--open-doi-link (path)
10681 "Open a \"doi\" type link.
10682 PATH is a the path to search for, as a string."
10683 (browse-url (url-encode-url (concat org-doi-server-url path))))
10685 (defun org--open-elisp-link (path)
10686 "Open a \"elisp\" type link.
10687 PATH is the sexp to evaluate, as a string."
10688 (let ((cmd path))
10689 (if (or (and (org-string-nw-p
10690 org-confirm-elisp-link-not-regexp)
10691 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10692 (not org-confirm-elisp-link-function)
10693 (funcall org-confirm-elisp-link-function
10694 (format "Execute \"%s\" as elisp? "
10695 (org-add-props cmd nil 'face 'org-warning))))
10696 (message "%s => %s" cmd
10697 (if (eq (string-to-char cmd) ?\()
10698 (eval (read cmd))
10699 (call-interactively (read cmd))))
10700 (user-error "Abort"))))
10702 (defun org--open-help-link (path)
10703 "Open a \"help\" type link.
10704 PATH is a symbol name, as a string."
10705 (pcase (intern path)
10706 ((and (pred fboundp) variable) (describe-function variable))
10707 ((and (pred boundp) function) (describe-variable function))
10708 (name (user-error "Unknown function or variable: %s" name))))
10710 (defun org--open-shell-link (path)
10711 "Open a \"shell\" type link.
10712 PATH is the command to execute, as a string."
10713 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10714 (cmd path))
10715 (if (or (and (org-string-nw-p
10716 org-confirm-shell-link-not-regexp)
10717 (string-match
10718 org-confirm-shell-link-not-regexp cmd))
10719 (not org-confirm-shell-link-function)
10720 (funcall org-confirm-shell-link-function
10721 (format "Execute \"%s\" in shell? "
10722 (org-add-props cmd nil
10723 'face 'org-warning))))
10724 (progn
10725 (message "Executing %s" cmd)
10726 (shell-command cmd buf)
10727 (when (featurep 'midnight)
10728 (setq clean-buffer-list-kill-buffer-names
10729 (cons (buffer-name buf)
10730 clean-buffer-list-kill-buffer-names))))
10731 (user-error "Abort"))))
10733 (defun org-open-at-point (&optional arg reference-buffer)
10734 "Open link, timestamp, footnote or tags at point.
10736 When point is on a link, follow it. Normally, files will be
10737 opened by an appropriate application. If the optional prefix
10738 argument ARG is non-nil, Emacs will visit the file. With
10739 a double prefix argument, try to open outside of Emacs, in the
10740 application the system uses for this file type.
10742 When point is on a timestamp, open the agenda at the day
10743 specified.
10745 When point is a footnote definition, move to the first reference
10746 found. If it is on a reference, move to the associated
10747 definition.
10749 When point is on a headline, display a list of every link in the
10750 entry, so it is possible to pick one, or all, of them. If point
10751 is on a tag, call `org-tags-view' instead.
10753 When optional argument REFERENCE-BUFFER is non-nil, it should
10754 specify a buffer from where the link search should happen. This
10755 is used internally by `org-open-link-from-string'.
10757 On top of syntactically correct links, this function will also
10758 try to open links and time-stamps in comments, example
10759 blocks... i.e., whenever point is on something looking like
10760 a timestamp or a link."
10761 (interactive "P")
10762 ;; On a code block, open block's results.
10763 (unless (call-interactively 'org-babel-open-src-block-result)
10764 (org-load-modules-maybe)
10765 (setq org-window-config-before-follow-link (current-window-configuration))
10766 (org-remove-occur-highlights nil nil t)
10767 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10768 (let* ((context
10769 ;; Only consider supported types, even if they are not
10770 ;; the closest one.
10771 (org-element-lineage
10772 (org-element-context)
10773 '(clock footnote-definition footnote-reference headline
10774 inlinetask link timestamp)
10776 (type (org-element-type context))
10777 (value (org-element-property :value context)))
10778 (cond
10779 ;; On a headline or an inlinetask, but not on a timestamp,
10780 ;; a link, a footnote reference.
10781 ((memq type '(headline inlinetask))
10782 (org-match-line org-complex-heading-regexp)
10783 (if (and (match-beginning 5)
10784 (>= (point) (match-beginning 5))
10785 (< (point) (match-end 5)))
10786 ;; On tags.
10787 (org-tags-view arg (substring (match-string 5) 0 -1))
10788 ;; Not on tags.
10789 (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
10790 (`(nil . ,_)
10791 (require 'org-attach)
10792 (org-attach-reveal 'if-exists))
10793 (`(,links . ,links-end)
10794 (dolist (link (if (stringp links) (list links) links))
10795 (search-forward link nil links-end)
10796 (goto-char (match-beginning 0))
10797 (org-open-at-point))))))
10798 ;; On a footnote reference or at definition's label.
10799 ((or (eq type 'footnote-reference)
10800 (and (eq type 'footnote-definition)
10801 (save-excursion
10802 ;; Do not validate action when point is on the
10803 ;; spaces right after the footnote label, in
10804 ;; order to be on par with behaviour on links.
10805 (skip-chars-forward " \t")
10806 (let ((begin
10807 (org-element-property :contents-begin context)))
10808 (if begin (< (point) begin)
10809 (= (org-element-property :post-affiliated context)
10810 (line-beginning-position)))))))
10811 (org-footnote-action))
10812 ;; No valid context. Ignore catch-all types like `headline'.
10813 ;; If point is on something looking like a link or
10814 ;; a time-stamp, try opening it. It may be useful in
10815 ;; comments, example blocks...
10816 ((memq type '(footnote-definition headline inlinetask nil))
10817 (call-interactively #'org-open-at-point-global))
10818 ;; On a clock line, make sure point is on the timestamp
10819 ;; before opening it.
10820 ((and (eq type 'clock)
10821 value
10822 (>= (point) (org-element-property :begin value))
10823 (<= (point) (org-element-property :end value)))
10824 (org-follow-timestamp-link))
10825 ;; Do nothing on white spaces after an object.
10826 ((>= (point)
10827 (save-excursion
10828 (goto-char (org-element-property :end context))
10829 (skip-chars-backward " \t")
10830 (point)))
10831 (user-error "No link found"))
10832 ((eq type 'timestamp) (org-follow-timestamp-link))
10833 ((eq type 'link)
10834 ;; When link is located within the description of another
10835 ;; link (e.g., an inline image), always open the parent
10836 ;; link.
10837 (let* ((link (let ((up (org-element-property :parent context)))
10838 (if (eq (org-element-type up) 'link) up context)))
10839 (type (org-element-property :type link))
10840 (path (org-link-unescape (org-element-property :path link))))
10841 ;; Switch back to REFERENCE-BUFFER needed when called in
10842 ;; a temporary buffer through `org-open-link-from-string'.
10843 (with-current-buffer (or reference-buffer (current-buffer))
10844 (cond
10845 ((equal type "file")
10846 (if (string-match "[*?{]" (file-name-nondirectory path))
10847 (dired path)
10848 ;; Look into `org-link-parameters' in order to find
10849 ;; a DEDICATED-FUNCTION to open file. The function
10850 ;; will be applied on raw link instead of parsed
10851 ;; link due to the limitation in `org-add-link-type'
10852 ;; ("open" function called with a single argument).
10853 ;; If no such function is found, fallback to
10854 ;; `org-open-file'.
10855 (let* ((option (org-element-property :search-option link))
10856 (app (org-element-property :application link))
10857 (dedicated-function
10858 (org-link-get-parameter
10859 (if app (concat type "+" app) type)
10860 :follow)))
10861 (if dedicated-function
10862 (funcall dedicated-function
10863 (concat path
10864 (and option (concat "::" option))))
10865 (apply #'org-open-file
10866 path
10867 (cond (arg)
10868 ((equal app "emacs") 'emacs)
10869 ((equal app "sys") 'system))
10870 (cond ((not option) nil)
10871 ((string-match-p "\\`[0-9]+\\'" option)
10872 (list (string-to-number option)))
10873 (t (list nil
10874 (org-link-unescape option)))))))))
10875 ((functionp (org-link-get-parameter type :follow))
10876 (funcall (org-link-get-parameter type :follow) path))
10877 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10878 (unless (run-hook-with-args-until-success
10879 'org-open-link-functions path)
10880 (if (not arg) (org-mark-ring-push)
10881 (switch-to-buffer-other-window
10882 (org-get-buffer-for-internal-link (current-buffer))))
10883 (let ((destination
10884 (org-with-wide-buffer
10885 (if (equal type "radio")
10886 (org-search-radio-target
10887 (org-element-property :path link))
10888 (org-link-search
10889 (if (member type '("custom-id" "coderef"))
10890 (org-element-property :raw-link link)
10891 path)
10892 ;; Prevent fuzzy links from matching
10893 ;; themselves.
10894 (and (equal type "fuzzy")
10895 (+ 2 (org-element-property :begin link)))))
10896 (point))))
10897 (unless (and (<= (point-min) destination)
10898 (>= (point-max) destination))
10899 (widen))
10900 (goto-char destination))))
10901 (t (browse-url-at-point))))))
10902 (t (user-error "No link found")))))
10903 (run-hook-with-args 'org-follow-link-hook)))
10905 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10906 "Offer links in the current entry and return the selected link.
10907 If there is only one link, return it.
10908 If NTH is an integer, return the NTH link found.
10909 If ZERO is a string, check also this string for a link, and if
10910 there is one, return it."
10911 (with-current-buffer buffer
10912 (org-with-wide-buffer
10913 (goto-char marker)
10914 (let ((cnt ?0)
10915 have-zero end links link c)
10916 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10917 (push (match-string 0 zero) links)
10918 (setq cnt (1- cnt) have-zero t))
10919 (save-excursion
10920 (org-back-to-heading t)
10921 (setq end (save-excursion (outline-next-heading) (point)))
10922 (while (re-search-forward org-any-link-re end t)
10923 (push (match-string 0) links))
10924 (setq links (org-uniquify (reverse links))))
10925 (cond
10926 ((null links)
10927 (message "No links"))
10928 ((equal (length links) 1)
10929 (setq link (car links)))
10930 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10931 (setq link (nth (if have-zero nth (1- nth)) links)))
10932 (t ; we have to select a link
10933 (save-excursion
10934 (save-window-excursion
10935 (delete-other-windows)
10936 (with-output-to-temp-buffer "*Select Link*"
10937 (dolist (l links)
10938 (cond
10939 ((not (string-match org-bracket-link-regexp l))
10940 (princ (format "[%c] %s\n" (cl-incf cnt)
10941 (org-unbracket-string "<" ">" l))))
10942 ((match-end 3)
10943 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10944 (match-string 3 l) (match-string 1 l))))
10945 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10946 (match-string 1 l)))))))
10947 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10948 (message "Select link to open, RET to open all:")
10949 (setq c (read-char-exclusive))
10950 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10951 (when (equal c ?q) (user-error "Abort"))
10952 (if (equal c ?\C-m)
10953 (setq link links)
10954 (setq nth (- c ?0))
10955 (when have-zero (setq nth (1+ nth)))
10956 (unless (and (integerp nth) (>= (length links) nth))
10957 (user-error "Invalid link selection"))
10958 (setq link (nth (1- nth) links)))))
10959 (cons link end)))))
10961 ;; TODO: These functions are deprecated since `org-open-at-point'
10962 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10963 (defun org-open-file-with-system (path)
10964 "Open file at PATH using the system way of opening it."
10965 (org-open-file path 'system))
10966 (defun org-open-file-with-emacs (path)
10967 "Open file at PATH in Emacs."
10968 (org-open-file path 'emacs))
10971 ;;; File search
10973 (defvar org-create-file-search-functions nil
10974 "List of functions to construct the right search string for a file link.
10975 These functions are called in turn with point at the location to
10976 which the link should point.
10978 A function in the hook should first test if it would like to
10979 handle this file type, for example by checking the `major-mode'
10980 or the file extension. If it decides not to handle this file, it
10981 should just return nil to give other functions a chance. If it
10982 does handle the file, it must return the search string to be used
10983 when following the link. The search string will be part of the
10984 file link, given after a double colon, and `org-open-at-point'
10985 will automatically search for it. If special measures must be
10986 taken to make the search successful, another function should be
10987 added to the companion hook `org-execute-file-search-functions',
10988 which see.
10990 A function in this hook may also use `setq' to set the variable
10991 `description' to provide a suggestion for the descriptive text to
10992 be used for this link when it gets inserted into an Org buffer
10993 with \\[org-insert-link].")
10995 (defvar org-execute-file-search-functions nil
10996 "List of functions to execute a file search triggered by a link.
10998 Functions added to this hook must accept a single argument, the
10999 search string that was part of the file link, the part after the
11000 double colon. The function must first check if it would like to
11001 handle this search, for example by checking the `major-mode' or
11002 the file extension. If it decides not to handle this search, it
11003 should just return nil to give other functions a chance. If it
11004 does handle the search, it must return a non-nil value to keep
11005 other functions from trying.
11007 Each function can access the current prefix argument through the
11008 variable `current-prefix-arg'. Note that a single prefix is used
11009 to force opening a link in Emacs, so it may be good to only use a
11010 numeric or double prefix to guide the search function.
11012 In case this is needed, a function in this hook can also restore
11013 the window configuration before `org-open-at-point' was called using:
11015 (set-window-configuration org-window-config-before-follow-link)")
11017 (defun org-search-radio-target (target)
11018 "Search a radio target matching TARGET in current buffer.
11019 White spaces are not significant."
11020 (let ((re (format "<<<%s>>>"
11021 (mapconcat #'regexp-quote
11022 (org-split-string target "[ \t\n]+")
11023 "[ \t]+\\(?:\n[ \t]*\\)?")))
11024 (origin (point)))
11025 (goto-char (point-min))
11026 (catch :radio-match
11027 (while (re-search-forward re nil t)
11028 (backward-char)
11029 (let ((object (org-element-context)))
11030 (when (eq (org-element-type object) 'radio-target)
11031 (goto-char (org-element-property :begin object))
11032 (org-show-context 'link-search)
11033 (throw :radio-match nil))))
11034 (goto-char origin)
11035 (user-error "No match for radio target: %s" target))))
11037 (defun org-link-search (s &optional avoid-pos stealth)
11038 "Search for a search string S.
11040 If S starts with \"#\", it triggers a custom ID search.
11042 If S is enclosed within parenthesis, it initiates a coderef
11043 search.
11045 If S is surrounded by forward slashes, it is interpreted as
11046 a regular expression. In Org mode files, this will create an
11047 `org-occur' sparse tree. In ordinary files, `occur' will be used
11048 to list matches. If the current buffer is in `dired-mode', grep
11049 will be used to search in all files.
11051 When AVOID-POS is given, ignore matches near that position.
11053 When optional argument STEALTH is non-nil, do not modify
11054 visibility around point, thus ignoring `org-show-context-detail'
11055 variable.
11057 Search is case-insensitive and ignores white spaces. Return type
11058 of matched result, which is either `dedicated' or `fuzzy'."
11059 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11060 (let* ((case-fold-search t)
11061 (origin (point))
11062 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11063 (starred (eq (string-to-char normalized) ?*))
11064 (words (split-string (if starred (substring s 1) s)))
11065 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
11066 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11067 type)
11068 (cond
11069 ;; Check if there are any special search functions.
11070 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11071 ((eq (string-to-char s) ?#)
11072 ;; Look for a custom ID S if S starts with "#".
11073 (let* ((id (substring normalized 1))
11074 (match (org-find-property "CUSTOM_ID" id)))
11075 (if match (progn (goto-char match) (setf type 'dedicated))
11076 (error "No match for custom ID: %s" id))))
11077 ((string-match "\\`(\\(.*\\))\\'" normalized)
11078 ;; Look for coderef targets if S is enclosed within parenthesis.
11079 (let ((coderef (match-string-no-properties 1 normalized))
11080 (re (substring s-single-re 1 -1)))
11081 (goto-char (point-min))
11082 (catch :coderef-match
11083 (while (re-search-forward re nil t)
11084 (let ((element (org-element-at-point)))
11085 (when (and (memq (org-element-type element)
11086 '(example-block src-block))
11087 ;; Build proper regexp according to current
11088 ;; block's label format.
11089 (let ((label-fmt
11090 (regexp-quote
11091 (or (org-element-property :label-fmt element)
11092 org-coderef-label-format))))
11093 (save-excursion
11094 (beginning-of-line)
11095 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11096 (format label-fmt coderef))))))
11097 (setq type 'dedicated)
11098 (goto-char (match-beginning 1))
11099 (throw :coderef-match nil))))
11100 (goto-char origin)
11101 (error "No match for coderef: %s" coderef))))
11102 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11103 ;; Look for a regular expression.
11104 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11105 (match-string 1 s)))
11106 ;; From here, we handle fuzzy links.
11108 ;; Look for targets, only if not in a headline search.
11109 ((and (not starred)
11110 (let ((target (format "<<%s>>" s-multi-re)))
11111 (catch :target-match
11112 (goto-char (point-min))
11113 (while (re-search-forward target nil t)
11114 (backward-char)
11115 (let ((context (org-element-context)))
11116 (when (eq (org-element-type context) 'target)
11117 (setq type 'dedicated)
11118 (goto-char (org-element-property :begin context))
11119 (throw :target-match t))))
11120 nil))))
11121 ;; Look for elements named after S, only if not in a headline
11122 ;; search.
11123 ((and (not starred)
11124 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11125 (catch :name-match
11126 (goto-char (point-min))
11127 (while (re-search-forward name nil t)
11128 (let ((element (org-element-at-point)))
11129 (when (equal words
11130 (split-string
11131 (org-element-property :name element)))
11132 (setq type 'dedicated)
11133 (beginning-of-line)
11134 (throw :name-match t))))
11135 nil))))
11136 ;; Regular text search. Prefer headlines in Org mode buffers.
11137 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
11138 ;; statistics cookies and tags.
11139 ((and (derived-mode-p 'org-mode)
11140 (let ((title-re
11141 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
11142 org-outline-regexp-bol
11143 org-comment-string
11144 (mapconcat #'regexp-quote words ".+")))
11145 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
11146 (comment-re (format "\\`%s[ \t]+" org-comment-string)))
11147 (goto-char (point-min))
11148 (catch :found
11149 (while (re-search-forward title-re nil t)
11150 (when (equal words
11151 (split-string
11152 (replace-regexp-in-string
11153 cookie-re ""
11154 (replace-regexp-in-string
11155 comment-re "" (org-get-heading t t)))))
11156 (throw :found t)))
11157 nil)))
11158 (beginning-of-line)
11159 (setq type 'dedicated))
11160 ;; Offer to create non-existent headline depending on
11161 ;; `org-link-search-must-match-exact-headline'.
11162 ((and (derived-mode-p 'org-mode)
11163 (not org-link-search-inhibit-query)
11164 (eq org-link-search-must-match-exact-headline 'query-to-create)
11165 (yes-or-no-p "No match - create this as a new heading? "))
11166 (goto-char (point-max))
11167 (unless (bolp) (newline))
11168 (org-insert-heading nil t t)
11169 (insert s "\n")
11170 (beginning-of-line 0))
11171 ;; Only headlines are looked after. No need to process
11172 ;; further: throw an error.
11173 ((and (derived-mode-p 'org-mode)
11174 (or starred org-link-search-must-match-exact-headline))
11175 (goto-char origin)
11176 (error "No match for fuzzy expression: %s" normalized))
11177 ;; Regular text search.
11178 ((catch :fuzzy-match
11179 (goto-char (point-min))
11180 (while (re-search-forward s-multi-re nil t)
11181 ;; Skip match if it contains AVOID-POS or it is included in
11182 ;; a link with a description but outside the description.
11183 (unless (or (and avoid-pos
11184 (<= (match-beginning 0) avoid-pos)
11185 (> (match-end 0) avoid-pos))
11186 (and (save-match-data
11187 (org-in-regexp org-bracket-link-regexp))
11188 (match-beginning 3)
11189 (or (> (match-beginning 3) (point))
11190 (<= (match-end 3) (point)))
11191 (org-element-lineage
11192 (save-match-data (org-element-context))
11193 '(link) t)))
11194 (goto-char (match-beginning 0))
11195 (setq type 'fuzzy)
11196 (throw :fuzzy-match t)))
11197 nil))
11198 ;; All failed. Throw an error.
11199 (t (goto-char origin)
11200 (error "No match for fuzzy expression: %s" normalized)))
11201 ;; Disclose surroundings of match, if appropriate.
11202 (when (and (derived-mode-p 'org-mode) (not stealth))
11203 (org-show-context 'link-search))
11204 type))
11206 (defun org-get-buffer-for-internal-link (buffer)
11207 "Return a buffer to be used for displaying the link target of internal links."
11208 (cond
11209 ((not org-display-internal-link-with-indirect-buffer)
11210 buffer)
11211 ((string-suffix-p "(Clone)" (buffer-name buffer))
11212 (message "Buffer is already a clone, not making another one")
11213 ;; we also do not modify visibility in this case
11214 buffer)
11215 (t ; make a new indirect buffer for displaying the link
11216 (let* ((bn (buffer-name buffer))
11217 (ibn (concat bn "(Clone)"))
11218 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11219 (with-current-buffer ib (org-overview))
11220 ib))))
11222 (defun org-do-occur (regexp &optional cleanup)
11223 "Call the Emacs command `occur'.
11224 If CLEANUP is non-nil, remove the printout of the regular expression
11225 in the *Occur* buffer. This is useful if the regex is long and not useful
11226 to read."
11227 (occur regexp)
11228 (when cleanup
11229 (let ((cwin (selected-window)) win beg end)
11230 (when (setq win (get-buffer-window "*Occur*"))
11231 (select-window win))
11232 (goto-char (point-min))
11233 (when (re-search-forward "match[a-z]+" nil t)
11234 (setq beg (match-end 0))
11235 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11236 (setq end (1- (match-beginning 0)))))
11237 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11238 (goto-char (point-min))
11239 (select-window cwin))))
11241 ;;; The mark ring for links jumps
11243 (defvar org-mark-ring nil
11244 "Mark ring for positions before jumps in Org mode.")
11245 (defvar org-mark-ring-last-goto nil
11246 "Last position in the mark ring used to go back.")
11247 ;; Fill and close the ring
11248 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11249 (dotimes (_ org-mark-ring-length)
11250 (push (make-marker) org-mark-ring))
11251 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11252 org-mark-ring)
11254 (defun org-mark-ring-push (&optional pos buffer)
11255 "Put the current position or POS into the mark ring and rotate it."
11256 (interactive)
11257 (setq pos (or pos (point)))
11258 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11259 (move-marker (car org-mark-ring)
11260 (or pos (point))
11261 (or buffer (current-buffer)))
11262 (message "%s"
11263 (substitute-command-keys
11264 "Position saved to mark ring, go back with \
11265 `\\[org-mark-ring-goto]'.")))
11267 (defun org-mark-ring-goto (&optional n)
11268 "Jump to the previous position in the mark ring.
11269 With prefix arg N, jump back that many stored positions. When
11270 called several times in succession, walk through the entire ring.
11271 Org mode commands jumping to a different position in the current file,
11272 or to another Org file, automatically push the old position onto the ring."
11273 (interactive "p")
11274 (let (p m)
11275 (if (eq last-command this-command)
11276 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11277 (setq p org-mark-ring))
11278 (setq org-mark-ring-last-goto p)
11279 (setq m (car p))
11280 (pop-to-buffer-same-window (marker-buffer m))
11281 (goto-char m)
11282 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11284 (defun org-add-angle-brackets (s)
11285 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11286 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11289 ;;; Following specific links
11291 (defvar org-agenda-buffer-tmp-name)
11292 (defvar org-agenda-start-on-weekday)
11293 (defun org-follow-timestamp-link ()
11294 "Open an agenda view for the time-stamp date/range at point."
11295 (cond
11296 ((org-at-date-range-p t)
11297 (let ((org-agenda-start-on-weekday)
11298 (t1 (match-string 1))
11299 (t2 (match-string 2)) tt1 tt2)
11300 (setq tt1 (time-to-days (org-time-string-to-time t1))
11301 tt2 (time-to-days (org-time-string-to-time t2)))
11302 (let ((org-agenda-buffer-tmp-name
11303 (format "*Org Agenda(a:%s)"
11304 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11305 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11306 ((org-at-timestamp-p t)
11307 (let ((org-agenda-buffer-tmp-name
11308 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11309 (org-agenda-list nil (time-to-days (org-time-string-to-time
11310 (substring (match-string 1) 0 10)))
11311 1)))
11312 (t (error "This should not happen"))))
11315 ;;; Following file links
11316 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11317 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11318 (declare-function mailcap-mime-info
11319 "mailcap" (string &optional request no-decode))
11320 (defvar org-wait nil)
11321 (defun org-open-file (path &optional in-emacs line search)
11322 "Open the file at PATH.
11323 First, this expands any special file name abbreviations. Then the
11324 configuration variable `org-file-apps' is checked if it contains an
11325 entry for this file type, and if yes, the corresponding command is launched.
11327 If no application is found, Emacs simply visits the file.
11329 With optional prefix argument IN-EMACS, Emacs will visit the file.
11330 With a double \\[universal-argument] \\[universal-argument] \
11331 prefix arg, Org tries to avoid opening in Emacs
11332 and to use an external application to visit the file.
11334 Optional LINE specifies a line to go to, optional SEARCH a string
11335 to search for. If LINE or SEARCH is given, the file will be
11336 opened in Emacs, unless an entry from org-file-apps that makes
11337 use of groups in a regexp matches.
11339 If you want to change the way frames are used when following a
11340 link, please customize `org-link-frame-setup'.
11342 If the file does not exist, an error is thrown."
11343 (let* ((file (if (equal path "")
11344 buffer-file-name
11345 (substitute-in-file-name (expand-file-name path))))
11346 (file-apps (append org-file-apps (org-default-apps)))
11347 (apps (cl-remove-if
11348 'org-file-apps-entry-match-against-dlink-p file-apps))
11349 (apps-dlink (cl-remove-if-not
11350 'org-file-apps-entry-match-against-dlink-p file-apps))
11351 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11352 (dirp (unless remp (file-directory-p file)))
11353 (file (if (and dirp org-open-directory-means-index-dot-org)
11354 (concat (file-name-as-directory file) "index.org")
11355 file))
11356 (a-m-a-p (assq 'auto-mode apps))
11357 (dfile (downcase file))
11358 ;; Reconstruct the original link from the PATH, LINE and
11359 ;; SEARCH args.
11360 (link (cond (line (concat file "::" (number-to-string line)))
11361 (search (concat file "::" search))
11362 (t file)))
11363 (dlink (downcase link))
11364 (old-buffer (current-buffer))
11365 (old-pos (point))
11366 (old-mode major-mode)
11367 (ext
11368 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11369 (match-string 1 dfile)))
11370 cmd link-match-data)
11371 (cond
11372 ((member in-emacs '((16) system))
11373 (setq cmd (cdr (assq 'system apps))))
11374 (in-emacs (setq cmd 'emacs))
11376 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11377 (and dirp (cdr (assq 'directory apps)))
11378 ;; First, try matching against apps-dlink if we
11379 ;; get a match here, store the match data for
11380 ;; later.
11381 (let ((match (assoc-default dlink apps-dlink
11382 'string-match)))
11383 (if match
11384 (progn (setq link-match-data (match-data))
11385 match)
11386 (progn (setq in-emacs (or in-emacs line search))
11387 nil))) ; if we have no match in apps-dlink,
11388 ; always open the file in emacs if line or search
11389 ; is given (for backwards compatibility)
11390 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11391 'string-match)
11392 (cdr (assoc ext apps))
11393 (cdr (assq t apps))))))
11394 (when (eq cmd 'system)
11395 (setq cmd (cdr (assq 'system apps))))
11396 (when (eq cmd 'default)
11397 (setq cmd (cdr (assoc t apps))))
11398 (when (eq cmd 'mailcap)
11399 (require 'mailcap)
11400 (mailcap-parse-mailcaps)
11401 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11402 (command (mailcap-mime-info mime-type)))
11403 (if (stringp command)
11404 (setq cmd command)
11405 (setq cmd 'emacs))))
11406 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11407 (not (file-exists-p file))
11408 (not org-open-non-existing-files))
11409 (user-error "No such file: %s" file))
11410 (cond
11411 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11412 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11413 (while (string-match "['\"]%s['\"]" cmd)
11414 (setq cmd (replace-match "%s" t t cmd)))
11415 (setq cmd (replace-regexp-in-string
11416 "%s"
11417 (shell-quote-argument (convert-standard-filename file))
11419 nil t))
11421 ;; Replace "%1", "%2" etc. in command with group matches from regex
11422 (save-match-data
11423 (let ((match-index 1)
11424 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11425 (set-match-data link-match-data)
11426 (while (<= match-index number-of-groups)
11427 (let ((regex (concat "%" (number-to-string match-index)))
11428 (replace-with (match-string match-index dlink)))
11429 (while (string-match regex cmd)
11430 (setq cmd (replace-match replace-with t t cmd))))
11431 (setq match-index (+ match-index 1)))))
11433 (save-window-excursion
11434 (message "Running %s...done" cmd)
11435 (start-process-shell-command cmd nil cmd)
11436 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11437 ((or (stringp cmd)
11438 (eq cmd 'emacs))
11439 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11440 (widen)
11441 (cond (line (org-goto-line line)
11442 (when (derived-mode-p 'org-mode) (org-reveal)))
11443 (search (org-link-search search))))
11444 ((functionp cmd)
11445 (save-match-data
11446 (set-match-data link-match-data)
11447 (condition-case nil
11448 (funcall cmd file link)
11449 ;; FIXME: Remove this check when most default installations
11450 ;; of Emacs have at least Org 9.0.
11451 ((debug wrong-number-of-arguments wrong-type-argument
11452 invalid-function)
11453 (user-error "Please see Org News for version 9.0 about \
11454 `org-file-apps'--Lisp error: %S" cmd)))))
11455 ((consp cmd)
11456 ;; FIXME: Remove this check when most default installations of
11457 ;; Emacs have at least Org 9.0.
11458 ;; Heads-up instead of silently fall back to
11459 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11460 ;; with sexp instead of a function for `cmd'.
11461 (user-error "Please see Org News for version 9.0 about \
11462 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11463 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11464 (and (derived-mode-p 'org-mode)
11465 (eq old-mode 'org-mode)
11466 (or (not (eq old-buffer (current-buffer)))
11467 (not (eq old-pos (point))))
11468 (org-mark-ring-push old-pos old-buffer))))
11470 (defun org-file-apps-entry-match-against-dlink-p (entry)
11471 "This function returns non-nil if `entry' uses a regular
11472 expression which should be matched against the whole link by
11473 org-open-file.
11475 It assumes that is the case when the entry uses a regular
11476 expression which has at least one grouping construct and the
11477 action is either a lisp form or a command string containing
11478 `%1', i.e. using at least one subexpression match as a
11479 parameter."
11480 (let ((selector (car entry))
11481 (action (cdr entry)))
11482 (if (stringp selector)
11483 (and (> (regexp-opt-depth selector) 0)
11484 (or (and (stringp action)
11485 (string-match "%[0-9]" action))
11486 (consp action)))
11487 nil)))
11489 (defun org-default-apps ()
11490 "Return the default applications for this operating system."
11491 (cond
11492 ((eq system-type 'darwin)
11493 org-file-apps-defaults-macosx)
11494 ((eq system-type 'windows-nt)
11495 org-file-apps-defaults-windowsnt)
11496 (t org-file-apps-defaults-gnu)))
11498 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11499 "Convert extensions to regular expressions in the cars of LIST.
11500 Also, weed out any non-string entries, because the return value is used
11501 only for regexp matching.
11502 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11503 point to the symbol `emacs', indicating that the file should
11504 be opened in Emacs."
11505 (append
11506 (delq nil
11507 (mapcar (lambda (x)
11508 (unless (not (stringp (car x)))
11509 (if (string-match "\\W" (car x))
11511 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11512 list))
11513 (when add-auto-mode
11514 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11516 (defvar ange-ftp-name-format)
11517 (defun org-file-remote-p (file)
11518 "Test whether FILE specifies a location on a remote system.
11519 Return non-nil if the location is indeed remote.
11521 For example, the filename \"/user@host:/foo\" specifies a location
11522 on the system \"/user@host:\"."
11523 (cond ((fboundp 'file-remote-p)
11524 (file-remote-p file))
11525 ((fboundp 'tramp-handle-file-remote-p)
11526 (tramp-handle-file-remote-p file))
11527 ((and (boundp 'ange-ftp-name-format)
11528 (string-match (car ange-ftp-name-format) file))
11529 t)))
11532 ;;;; Refiling
11534 (defun org-get-org-file ()
11535 "Read a filename, with default directory `org-directory'."
11536 (let ((default (or org-default-notes-file remember-data-file)))
11537 (read-file-name (format "File name [%s]: " default)
11538 (file-name-as-directory org-directory)
11539 default)))
11541 (defun org-notes-order-reversed-p ()
11542 "Check if the current file should receive notes in reversed order."
11543 (cond
11544 ((not org-reverse-note-order) nil)
11545 ((eq t org-reverse-note-order) t)
11546 ((not (listp org-reverse-note-order)) nil)
11547 (t (catch 'exit
11548 (dolist (entry org-reverse-note-order)
11549 (when (string-match (car entry) buffer-file-name)
11550 (throw 'exit (cdr entry))))))))
11552 (defvar org-refile-target-table nil
11553 "The list of refile targets, created by `org-refile'.")
11555 (defvar org-agenda-new-buffers nil
11556 "Buffers created to visit agenda files.")
11558 (defvar org-refile-cache nil
11559 "Cache for refile targets.")
11561 (defvar org-refile-markers nil
11562 "All the markers used for caching refile locations.")
11564 (defun org-refile-marker (pos)
11565 "Get a new refile marker, but only if caching is in use."
11566 (if (not org-refile-use-cache)
11568 (let ((m (make-marker)))
11569 (move-marker m pos)
11570 (push m org-refile-markers)
11571 m)))
11573 (defun org-refile-cache-clear ()
11574 "Clear the refile cache and disable all the markers."
11575 (dolist (m org-refile-markers) (move-marker m nil))
11576 (setq org-refile-markers nil)
11577 (setq org-refile-cache nil)
11578 (message "Refile cache has been cleared"))
11580 (defun org-refile-cache-check-set (set)
11581 "Check if all the markers in the cache still have live buffers."
11582 (let (marker)
11583 (catch 'exit
11584 (while (and set (setq marker (nth 3 (pop set))))
11585 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11586 (when (and marker (null (marker-buffer marker)))
11587 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11588 (sit-for 3)
11589 (throw 'exit nil)))
11590 t)))
11592 (defun org-refile-cache-put (set &rest identifiers)
11593 "Push the refile targets SET into the cache, under IDENTIFIERS."
11594 (let* ((key (sha1 (prin1-to-string identifiers)))
11595 (entry (assoc key org-refile-cache)))
11596 (if entry
11597 (setcdr entry set)
11598 (push (cons key set) org-refile-cache))))
11600 (defun org-refile-cache-get (&rest identifiers)
11601 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11602 (cond
11603 ((not org-refile-cache) nil)
11604 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11606 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11607 org-refile-cache))))
11608 (and set (org-refile-cache-check-set set) set)))))
11610 (defvar org-outline-path-cache nil
11611 "Alist between buffer positions and outline paths.
11612 It value is an alist (POSITION . PATH) where POSITION is the
11613 buffer position at the beginning of an entry and PATH is a list
11614 of strings describing the outline path for that entry, in reverse
11615 order.")
11617 (defun org-refile-get-targets (&optional default-buffer)
11618 "Produce a table with refile targets."
11619 (let ((case-fold-search nil)
11620 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11621 (entries (or org-refile-targets '((nil . (:level . 1)))))
11622 targets tgs files desc descre)
11623 (message "Getting targets...")
11624 (with-current-buffer (or default-buffer (current-buffer))
11625 (dolist (entry entries)
11626 (setq files (car entry) desc (cdr entry))
11627 (cond
11628 ((null files) (setq files (list (current-buffer))))
11629 ((eq files 'org-agenda-files)
11630 (setq files (org-agenda-files 'unrestricted)))
11631 ((and (symbolp files) (fboundp files))
11632 (setq files (funcall files)))
11633 ((and (symbolp files) (boundp files))
11634 (setq files (symbol-value files))))
11635 (when (stringp files) (setq files (list files)))
11636 (cond
11637 ((eq (car desc) :tag)
11638 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11639 ((eq (car desc) :todo)
11640 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11641 ((eq (car desc) :regexp)
11642 (setq descre (cdr desc)))
11643 ((eq (car desc) :level)
11644 (setq descre (concat "^\\*\\{" (number-to-string
11645 (if org-odd-levels-only
11646 (1- (* 2 (cdr desc)))
11647 (cdr desc)))
11648 "\\}[ \t]")))
11649 ((eq (car desc) :maxlevel)
11650 (setq descre (concat "^\\*\\{1," (number-to-string
11651 (if org-odd-levels-only
11652 (1- (* 2 (cdr desc)))
11653 (cdr desc)))
11654 "\\}[ \t]")))
11655 (t (error "Bad refiling target description %s" desc)))
11656 (dolist (f files)
11657 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11659 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11660 (progn
11661 (when (bufferp f)
11662 (setq f (buffer-file-name (buffer-base-buffer f))))
11663 (setq f (and f (expand-file-name f)))
11664 (when (eq org-refile-use-outline-path 'file)
11665 (push (list (file-name-nondirectory f) f nil nil) tgs))
11666 (org-with-wide-buffer
11667 (goto-char (point-min))
11668 (setq org-outline-path-cache nil)
11669 (while (re-search-forward descre nil t)
11670 (beginning-of-line)
11671 (let ((case-fold-search nil))
11672 (looking-at org-complex-heading-regexp))
11673 (let ((begin (point))
11674 (heading (match-string-no-properties 4)))
11675 (unless (or (and
11676 org-refile-target-verify-function
11677 (not
11678 (funcall org-refile-target-verify-function)))
11679 (not heading))
11680 (let ((re (format org-complex-heading-regexp-format
11681 (regexp-quote heading)))
11682 (target
11683 (if (not org-refile-use-outline-path) heading
11684 (mapconcat
11685 #'org-protect-slash
11686 (append
11687 (pcase org-refile-use-outline-path
11688 (`file (list (file-name-nondirectory
11689 (buffer-file-name
11690 (buffer-base-buffer)))))
11691 (`full-file-path
11692 (list (buffer-file-name
11693 (buffer-base-buffer))))
11694 (_ nil))
11695 (org-get-outline-path t t))
11696 "/"))))
11697 (push (list target f re (org-refile-marker (point)))
11698 tgs)))
11699 (when (= (point) begin)
11700 ;; Verification function has not moved point.
11701 (end-of-line)))))))
11702 (when org-refile-use-cache
11703 (org-refile-cache-put tgs (buffer-file-name) descre))
11704 (setq targets (append tgs targets))))))
11705 (message "Getting targets...done")
11706 (delete-dups (nreverse targets))))
11708 (defun org-protect-slash (s)
11709 (replace-regexp-in-string "/" "\\/" s nil t))
11711 (defun org--get-outline-path-1 (&optional use-cache)
11712 "Return outline path to current headline.
11714 Outline path is a list of strings, in reverse order. When
11715 optional argument USE-CACHE is non-nil, make use of a cache. See
11716 `org-get-outline-path' for details.
11718 Assume buffer is widened and point is on a headline."
11719 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11720 (let ((p (point))
11721 (heading (let ((case-fold-search nil))
11722 (looking-at org-complex-heading-regexp)
11723 (if (not (match-end 4)) ""
11724 ;; Remove statistics cookies.
11725 (org-trim
11726 (org-link-display-format
11727 (replace-regexp-in-string
11728 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11729 (match-string-no-properties 4))))))))
11730 (if (org-up-heading-safe)
11731 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11732 (when use-cache
11733 (push (cons p path) org-outline-path-cache))
11734 path)
11735 ;; This is a new root node. Since we assume we are moving
11736 ;; forward, we can drop previous cache so as to limit number
11737 ;; of associations there.
11738 (let ((path (list heading)))
11739 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11740 path)))))
11742 (defun org-get-outline-path (&optional with-self use-cache)
11743 "Return the outline path to the current entry.
11745 An outline path is a list of ancestors for current headline, as
11746 a list of strings. Statistics cookies are removed and links are
11747 replaced with their description, if any, or their path otherwise.
11749 When optional argument WITH-SELF is non-nil, the path also
11750 includes the current headline.
11752 When optional argument USE-CACHE is non-nil, cache outline paths
11753 between calls to this function so as to avoid backtracking. This
11754 argument is useful when planning to find more than one outline
11755 path in the same document. In that case, there are two
11756 conditions to satisfy:
11757 - `org-outline-path-cache' is set to nil before starting the
11758 process;
11759 - outline paths are computed by increasing buffer positions."
11760 (org-with-wide-buffer
11761 (and (or (and with-self (org-back-to-heading t))
11762 (org-up-heading-safe))
11763 (reverse (org--get-outline-path-1 use-cache)))))
11765 (defun org-format-outline-path (path &optional width prefix separator)
11766 "Format the outline path PATH for display.
11767 WIDTH is the maximum number of characters that is available.
11768 PREFIX is a prefix to be included in the returned string,
11769 such as the file name.
11770 SEPARATOR is inserted between the different parts of the path,
11771 the default is \"/\"."
11772 (setq width (or width 79))
11773 (setq path (delq nil path))
11774 (unless (> width 0)
11775 (user-error "Argument `width' must be positive"))
11776 (setq separator (or separator "/"))
11777 (let* ((org-odd-levels-only nil)
11778 (fpath (concat
11779 prefix (and prefix path separator)
11780 (mapconcat
11781 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11782 (cl-loop for head in path
11783 for n from 0
11784 collect (org-add-props
11785 head nil 'face
11786 (nth (% n org-n-level-faces) org-level-faces)))
11787 separator))))
11788 (when (> (length fpath) width)
11789 (if (< width 7)
11790 ;; It's unlikely that `width' will be this small, but don't
11791 ;; waste characters by adding ".." if it is.
11792 (setq fpath (substring fpath 0 width))
11793 (setf (substring fpath (- width 2)) "..")))
11794 fpath))
11796 (defun org-display-outline-path (&optional file current separator just-return-string)
11797 "Display the current outline path in the echo area.
11799 If FILE is non-nil, prepend the output with the file name.
11800 If CURRENT is non-nil, append the current heading to the output.
11801 SEPARATOR is passed through to `org-format-outline-path'. It separates
11802 the different parts of the path and defaults to \"/\".
11803 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11804 (interactive "P")
11805 (let* (case-fold-search
11806 (bfn (buffer-file-name (buffer-base-buffer)))
11807 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11808 res)
11809 (when current (setq path (append path
11810 (save-excursion
11811 (org-back-to-heading t)
11812 (when (looking-at org-complex-heading-regexp)
11813 (list (match-string 4)))))))
11814 (setq res
11815 (org-format-outline-path
11816 path
11817 (1- (frame-width))
11818 (and file bfn (concat (file-name-nondirectory bfn) separator))
11819 separator))
11820 (if just-return-string
11821 (org-no-properties res)
11822 (org-unlogged-message "%s" res))))
11824 (defvar org-refile-history nil
11825 "History for refiling operations.")
11827 (defvar org-after-refile-insert-hook nil
11828 "Hook run after `org-refile' has inserted its stuff at the new location.
11829 Note that this is still *before* the stuff will be removed from
11830 the *old* location.")
11832 (defvar org-capture-last-stored-marker)
11833 (defvar org-refile-keep nil
11834 "Non-nil means `org-refile' will copy instead of refile.")
11836 (defun org-copy ()
11837 "Like `org-refile', but copy."
11838 (interactive)
11839 (let ((org-refile-keep t))
11840 (funcall 'org-refile nil nil nil "Copy")))
11842 (defun org-refile (&optional arg default-buffer rfloc msg)
11843 "Move the entry or entries at point to another heading.
11845 The list of target headings is compiled using the information in
11846 `org-refile-targets', which see.
11848 At the target location, the entry is filed as a subitem of the
11849 target heading. Depending on `org-reverse-note-order', the new
11850 subitem will either be the first or the last subitem.
11852 If there is an active region, all entries in that region will be
11853 refiled. However, the region must fulfill the requirement that
11854 the first heading sets the top-level of the moved text.
11856 With a `\\[universal-argument]' ARG, the command will only visit the target \
11857 location
11858 and not actually move anything.
11860 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11861 location where the last
11862 refiling operation has put the subtree.
11864 With a numeric prefix argument of `2', refile to the running clock.
11866 With a numeric prefix argument of `3', emulate `org-refile-keep'
11867 being set to t and copy to the target location, don't move it.
11868 Beware that keeping refiled entries may result in duplicated ID
11869 properties.
11871 RFLOC can be a refile location obtained in a different way.
11873 MSG is a string to replace \"Refile\" in the default prompt with
11874 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11876 See also `org-refile-use-outline-path'.
11878 If you are using target caching (see `org-refile-use-cache'), you
11879 have to clear the target cache in order to find new targets.
11880 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11881 prefix argument (`C-u C-u C-u C-c C-w')."
11882 (interactive "P")
11883 (if (member arg '(0 (64)))
11884 (org-refile-cache-clear)
11885 (let* ((actionmsg (cond (msg msg)
11886 ((equal arg 3) "Refile (and keep)")
11887 (t "Refile")))
11888 (regionp (org-region-active-p))
11889 (region-start (and regionp (region-beginning)))
11890 (region-end (and regionp (region-end)))
11891 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11892 pos it nbuf file level reversed)
11893 (setq last-command nil)
11894 (when regionp
11895 (goto-char region-start)
11896 (or (bolp) (goto-char (point-at-bol)))
11897 (setq region-start (point))
11898 (unless (or (org-kill-is-subtree-p
11899 (buffer-substring region-start region-end))
11900 (prog1 org-refile-active-region-within-subtree
11901 (let ((s (point-at-eol)))
11902 (org-toggle-heading)
11903 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11904 (user-error "The region is not a (sequence of) subtree(s)")))
11905 (if (equal arg '(16))
11906 (org-refile-goto-last-stored)
11907 (when (or
11908 (and (equal arg 2)
11909 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11910 (prog1
11911 (setq it (list (or org-clock-heading "running clock")
11912 (buffer-file-name
11913 (marker-buffer org-clock-hd-marker))
11915 (marker-position org-clock-hd-marker)))
11916 (setq arg nil)))
11917 (setq it
11918 (or rfloc
11919 (let (heading-text)
11920 (save-excursion
11921 (unless (and arg (listp arg))
11922 (org-back-to-heading t)
11923 (setq heading-text
11924 (replace-regexp-in-string
11925 org-bracket-link-regexp
11926 "\\3"
11927 (or (nth 4 (org-heading-components))
11928 ""))))
11929 (org-refile-get-location
11930 (cond ((and arg (listp arg)) "Goto")
11931 (regionp (concat actionmsg " region to"))
11932 (t (concat actionmsg " subtree \""
11933 heading-text "\" to")))
11934 default-buffer
11935 (and (not (equal '(4) arg))
11936 org-refile-allow-creating-parent-nodes)))))))
11937 (setq file (nth 1 it)
11938 pos (nth 3 it))
11939 (when (and (not arg)
11941 (equal (buffer-file-name) file)
11942 (if regionp
11943 (and (>= pos region-start)
11944 (<= pos region-end))
11945 (and (>= pos (point))
11946 (< pos (save-excursion
11947 (org-end-of-subtree t t))))))
11948 (error "Cannot refile to position inside the tree or region"))
11949 (setq nbuf (or (find-buffer-visiting file)
11950 (find-file-noselect file)))
11951 (if (and arg (not (equal arg 3)))
11952 (progn
11953 (pop-to-buffer-same-window nbuf)
11954 (goto-char (cond (pos)
11955 ((org-notes-order-reversed-p) (point-min))
11956 (t (point-max))))
11957 (org-show-context 'org-goto))
11958 (if regionp
11959 (progn
11960 (org-kill-new (buffer-substring region-start region-end))
11961 (org-save-markers-in-region region-start region-end))
11962 (org-copy-subtree 1 nil t))
11963 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11964 (find-file-noselect file)))
11965 (setq reversed (org-notes-order-reversed-p))
11966 (org-with-wide-buffer
11967 (if pos
11968 (progn
11969 (goto-char pos)
11970 (looking-at org-outline-regexp)
11971 (setq level (org-get-valid-level (funcall outline-level) 1))
11972 (goto-char
11973 (if reversed
11974 (or (outline-next-heading) (point-max))
11975 (or (save-excursion (org-get-next-sibling))
11976 (org-end-of-subtree t t)
11977 (point-max)))))
11978 (setq level 1)
11979 (if (not reversed)
11980 (goto-char (point-max))
11981 (goto-char (point-min))
11982 (or (outline-next-heading) (goto-char (point-max)))))
11983 (unless (bolp) (newline))
11984 (org-paste-subtree level nil nil t)
11985 (when org-log-refile
11986 (org-add-log-setup 'refile nil nil org-log-refile)
11987 (unless (eq org-log-refile 'note)
11988 (save-excursion (org-add-log-note))))
11989 (and org-auto-align-tags
11990 (let ((org-loop-over-headlines-in-active-region nil))
11991 (org-set-tags nil t)))
11992 (let ((bookmark-name (plist-get org-bookmark-names-plist
11993 :last-refile)))
11994 (when bookmark-name
11995 (with-demoted-errors
11996 (bookmark-set bookmark-name))))
11997 ;; If we are refiling for capture, make sure that the
11998 ;; last-capture pointers point here
11999 (when (bound-and-true-p org-capture-is-refiling)
12000 (let ((bookmark-name (plist-get org-bookmark-names-plist
12001 :last-capture-marker)))
12002 (when bookmark-name
12003 (with-demoted-errors
12004 (bookmark-set bookmark-name))))
12005 (move-marker org-capture-last-stored-marker (point)))
12006 (when (fboundp 'deactivate-mark) (deactivate-mark))
12007 (run-hooks 'org-after-refile-insert-hook)))
12008 (unless org-refile-keep
12009 (if regionp
12010 (delete-region (point) (+ (point) (- region-end region-start)))
12011 (delete-region
12012 (and (org-back-to-heading t) (point))
12013 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12014 (when (featurep 'org-inlinetask)
12015 (org-inlinetask-remove-END-maybe))
12016 (setq org-markers-to-move nil)
12017 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12019 (defun org-refile-goto-last-stored ()
12020 "Go to the location where the last refile was stored."
12021 (interactive)
12022 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12023 (message "This is the location of the last refile"))
12025 (defun org-refile--get-location (refloc tbl)
12026 "When user refile to REFLOC, find the associated target in TBL.
12027 Also check `org-refile-target-table'."
12028 (car (delq
12030 (mapcar
12031 (lambda (r) (or (assoc r tbl)
12032 (assoc r org-refile-target-table)))
12033 (list (replace-regexp-in-string "/$" "" refloc)
12034 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12036 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12037 "Prompt the user for a refile location, using PROMPT.
12038 PROMPT should not be suffixed with a colon and a space, because
12039 this function appends the default value from
12040 `org-refile-history' automatically, if that is not empty."
12041 (let ((org-refile-targets org-refile-targets)
12042 (org-refile-use-outline-path org-refile-use-outline-path))
12043 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12044 (unless org-refile-target-table
12045 (user-error "No refile targets"))
12046 (let* ((cbuf (current-buffer))
12047 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12048 (cfunc (if (and org-refile-use-outline-path
12049 org-outline-path-complete-in-steps)
12050 #'org-olpath-completing-read
12051 #'completing-read))
12052 (extra (if org-refile-use-outline-path "/" ""))
12053 (cbnex (concat (buffer-name) extra))
12054 (filename (and cfn (expand-file-name cfn)))
12055 (tbl (mapcar
12056 (lambda (x)
12057 (if (and (not (member org-refile-use-outline-path
12058 '(file full-file-path)))
12059 (not (equal filename (nth 1 x))))
12060 (cons (concat (car x) extra " ("
12061 (file-name-nondirectory (nth 1 x)) ")")
12062 (cdr x))
12063 (cons (concat (car x) extra) (cdr x))))
12064 org-refile-target-table))
12065 (completion-ignore-case t)
12066 cdef
12067 (prompt (concat prompt
12068 (or (and (car org-refile-history)
12069 (concat " (default " (car org-refile-history) ")"))
12070 (and (assoc cbnex tbl) (setq cdef cbnex)
12071 (concat " (default " cbnex ")"))) ": "))
12072 pa answ parent-target child parent old-hist)
12073 (setq old-hist org-refile-history)
12074 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12075 nil 'org-refile-history (or cdef (car org-refile-history))))
12076 (if (setq pa (org-refile--get-location answ tbl))
12077 (progn
12078 (org-refile-check-position pa)
12079 (when (or (not org-refile-history)
12080 (not (eq old-hist org-refile-history))
12081 (not (equal (car pa) (car org-refile-history))))
12082 (setq org-refile-history
12083 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12084 org-refile-history
12085 (cdr org-refile-history))))
12086 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12087 (pop org-refile-history)))
12089 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12090 (progn
12091 (setq parent (match-string 1 answ)
12092 child (match-string 2 answ))
12093 (setq parent-target (org-refile--get-location parent tbl))
12094 (when (and parent-target
12095 (or (eq new-nodes t)
12096 (and (eq new-nodes 'confirm)
12097 (y-or-n-p (format "Create new node \"%s\"? "
12098 child)))))
12099 (org-refile-new-child parent-target child)))
12100 (user-error "Invalid target location")))))
12102 (declare-function org-string-nw-p "org-macs" (s))
12103 (defun org-refile-check-position (refile-pointer)
12104 "Check if the refile pointer matches the headline to which it points."
12105 (let* ((file (nth 1 refile-pointer))
12106 (re (nth 2 refile-pointer))
12107 (pos (nth 3 refile-pointer))
12108 buffer)
12109 (if (and (not (markerp pos)) (not file))
12110 (user-error "Please indicate a target file in the refile path")
12111 (when (org-string-nw-p re)
12112 (setq buffer (if (markerp pos)
12113 (marker-buffer pos)
12114 (or (find-buffer-visiting file)
12115 (find-file-noselect file))))
12116 (with-current-buffer buffer
12117 (org-with-wide-buffer
12118 (goto-char pos)
12119 (beginning-of-line 1)
12120 (unless (looking-at-p re)
12121 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12123 (defun org-refile-new-child (parent-target child)
12124 "Use refile target PARENT-TARGET to add new CHILD below it."
12125 (unless parent-target
12126 (error "Cannot find parent for new node"))
12127 (let ((file (nth 1 parent-target))
12128 (pos (nth 3 parent-target))
12129 level)
12130 (with-current-buffer (or (find-buffer-visiting file)
12131 (find-file-noselect file))
12132 (org-with-wide-buffer
12133 (if pos
12134 (goto-char pos)
12135 (goto-char (point-max))
12136 (unless (bolp) (newline)))
12137 (when (looking-at org-outline-regexp)
12138 (setq level (funcall outline-level))
12139 (org-end-of-subtree t t))
12140 (org-back-over-empty-lines)
12141 (insert "\n" (make-string
12142 (if pos (org-get-valid-level level 1) 1) ?*)
12143 " " child "\n")
12144 (beginning-of-line 0)
12145 (list (concat (car parent-target) "/" child) file "" (point))))))
12147 (defun org-olpath-completing-read (prompt collection &rest args)
12148 "Read an outline path like a file name."
12149 (let ((thetable collection))
12150 (apply #'completing-read
12151 prompt
12152 (lambda (string predicate &optional flag)
12153 (cond
12154 ((eq flag nil) (try-completion string thetable))
12155 ((eq flag t)
12156 (let ((l (length string)))
12157 (mapcar (lambda (x)
12158 (let ((r (substring x l))
12159 (f (if (string-match " ([^)]*)$" x)
12160 (match-string 0 x)
12161 "")))
12162 (if (string-match "/" r)
12163 (concat string (substring r 0 (match-end 0)) f)
12164 x)))
12165 (all-completions string thetable predicate))))
12166 ;; Exact match?
12167 ((eq flag 'lambda) (assoc string thetable))))
12168 args)))
12170 ;;;; Dynamic blocks
12172 (defun org-find-dblock (name)
12173 "Find the first dynamic block with name NAME in the buffer.
12174 If not found, stay at current position and return nil."
12175 (let ((case-fold-search t) pos)
12176 (save-excursion
12177 (goto-char (point-min))
12178 (setq pos (and (re-search-forward
12179 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12180 (match-beginning 0))))
12181 (when pos (goto-char pos))
12182 pos))
12184 (defun org-create-dblock (plist)
12185 "Create a dynamic block section, with parameters taken from PLIST.
12186 PLIST must contain a :name entry which is used as the name of the block."
12187 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12188 (end-of-line 1)
12189 (newline))
12190 (let ((col (current-column))
12191 (name (plist-get plist :name)))
12192 (insert "#+BEGIN: " name)
12193 (while plist
12194 (if (eq (car plist) :name)
12195 (setq plist (cddr plist))
12196 (insert " " (prin1-to-string (pop plist)))))
12197 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12198 (beginning-of-line -2)))
12200 (defun org-prepare-dblock ()
12201 "Prepare dynamic block for refresh.
12202 This empties the block, puts the cursor at the insert position and returns
12203 the property list including an extra property :name with the block name."
12204 (unless (looking-at org-dblock-start-re)
12205 (user-error "Not at a dynamic block"))
12206 (let* ((begdel (1+ (match-end 0)))
12207 (name (org-no-properties (match-string 1)))
12208 (params (append (list :name name)
12209 (read (concat "(" (match-string 3) ")")))))
12210 (save-excursion
12211 (beginning-of-line 1)
12212 (skip-chars-forward " \t")
12213 (setq params (plist-put params :indentation-column (current-column))))
12214 (unless (re-search-forward org-dblock-end-re nil t)
12215 (error "Dynamic block not terminated"))
12216 (setq params
12217 (append params
12218 (list :content (buffer-substring
12219 begdel (match-beginning 0)))))
12220 (delete-region begdel (match-beginning 0))
12221 (goto-char begdel)
12222 (open-line 1)
12223 params))
12225 (defun org-map-dblocks (&optional command)
12226 "Apply COMMAND to all dynamic blocks in the current buffer.
12227 If COMMAND is not given, use `org-update-dblock'."
12228 (let ((cmd (or command 'org-update-dblock)))
12229 (save-excursion
12230 (goto-char (point-min))
12231 (while (re-search-forward org-dblock-start-re nil t)
12232 (goto-char (match-beginning 0))
12233 (save-excursion
12234 (condition-case nil
12235 (funcall cmd)
12236 (error (message "Error during update of dynamic block"))))
12237 (unless (re-search-forward org-dblock-end-re nil t)
12238 (error "Dynamic block not terminated"))))))
12240 (defun org-dblock-update (&optional arg)
12241 "User command for updating dynamic blocks.
12242 Update the dynamic block at point. With prefix ARG, update all dynamic
12243 blocks in the buffer."
12244 (interactive "P")
12245 (if arg
12246 (org-update-all-dblocks)
12247 (or (looking-at org-dblock-start-re)
12248 (org-beginning-of-dblock))
12249 (org-update-dblock)))
12251 (defun org-update-dblock ()
12252 "Update the dynamic block at point.
12253 This means to empty the block, parse for parameters and then call
12254 the correct writing function."
12255 (interactive)
12256 (save-excursion
12257 (let* ((win (selected-window))
12258 (pos (point))
12259 (line (org-current-line))
12260 (params (org-prepare-dblock))
12261 (name (plist-get params :name))
12262 (indent (plist-get params :indentation-column))
12263 (cmd (intern (concat "org-dblock-write:" name))))
12264 (message "Updating dynamic block `%s' at line %d..." name line)
12265 (funcall cmd params)
12266 (message "Updating dynamic block `%s' at line %d...done" name line)
12267 (goto-char pos)
12268 (when (and indent (> indent 0))
12269 (setq indent (make-string indent ?\ ))
12270 (save-excursion
12271 (select-window win)
12272 (org-beginning-of-dblock)
12273 (forward-line 1)
12274 (while (not (looking-at org-dblock-end-re))
12275 (insert indent)
12276 (beginning-of-line 2))
12277 (when (looking-at org-dblock-end-re)
12278 (and (looking-at "[ \t]+")
12279 (replace-match ""))
12280 (insert indent)))))))
12282 (defun org-beginning-of-dblock ()
12283 "Find the beginning of the dynamic block at point.
12284 Error if there is no such block at point."
12285 (let ((pos (point))
12286 beg)
12287 (end-of-line 1)
12288 (if (and (re-search-backward org-dblock-start-re nil t)
12289 (setq beg (match-beginning 0))
12290 (re-search-forward org-dblock-end-re nil t)
12291 (> (match-end 0) pos))
12292 (goto-char beg)
12293 (goto-char pos)
12294 (error "Not in a dynamic block"))))
12296 (defun org-update-all-dblocks ()
12297 "Update all dynamic blocks in the buffer.
12298 This function can be used in a hook."
12299 (interactive)
12300 (when (derived-mode-p 'org-mode)
12301 (org-map-dblocks 'org-update-dblock)))
12304 ;;;; Completion
12306 (declare-function org-export-backend-options "ox" (cl-x) t)
12307 (defun org-get-export-keywords ()
12308 "Return a list of all currently understood export keywords.
12309 Export keywords include options, block names, attributes and
12310 keywords relative to each registered export back-end."
12311 (let (keywords)
12312 (dolist (backend
12313 (bound-and-true-p org-export-registered-backends)
12314 (delq nil keywords))
12315 ;; Back-end name (for keywords, like #+LATEX:)
12316 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12317 (dolist (option-entry (org-export-backend-options backend))
12318 ;; Back-end options.
12319 (push (nth 1 option-entry) keywords)))))
12321 (defconst org-options-keywords
12322 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12323 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12324 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12325 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12326 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12328 (defcustom org-structure-template-alist
12329 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12330 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12331 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12332 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12333 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12334 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12335 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12336 ("L" "#+LaTeX: ")
12337 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12338 ("H" "#+HTML: ")
12339 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12340 ("A" "#+ASCII: ")
12341 ("i" "#+INDEX: ?")
12342 ("I" "#+INCLUDE: %file ?"))
12343 "Structure completion elements.
12344 This is a list of abbreviation keys and values. The value gets inserted
12345 if you type `<' followed by the key and then press the completion key,
12346 usually `TAB'. %file will be replaced by a file name after prompting
12347 for the file using completion. The cursor will be placed at the position
12348 of the `?' in the template.
12349 There are two templates for each key, the first uses the original Org syntax,
12350 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12351 the default when the /org-mtags.el/ module has been loaded. See also the
12352 variable `org-mtags-prefer-muse-templates'."
12353 :group 'org-completion
12354 :type '(repeat
12355 (list
12356 (string :tag "Key")
12357 (string :tag "Template")))
12358 :version "26.1"
12359 :package-version '(Org . "8.3"))
12361 (defun org-try-structure-completion ()
12362 "Try to complete a structure template before point.
12363 This looks for strings like \"<e\" on an otherwise empty line and
12364 expands them."
12365 (let ((l (buffer-substring (point-at-bol) (point)))
12367 (when (and (looking-at "[ \t]*$")
12368 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12369 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12370 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12371 (match-beginning 1)) a)
12372 t)))
12374 (defun org-complete-expand-structure-template (start cell)
12375 "Expand a structure template."
12376 (let ((rpl (nth 1 cell))
12377 (ind ""))
12378 (delete-region start (point))
12379 (when (string-match "\\`[ \t]*#\\+" rpl)
12380 (cond
12381 ((bolp))
12382 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12383 (setq ind (buffer-substring (point-at-bol) (point))))
12384 (t (newline))))
12385 (setq start (point))
12386 (when (string-match "%file" rpl)
12387 (setq rpl (replace-match
12388 (concat
12389 "\""
12390 (save-match-data
12391 (abbreviate-file-name (read-file-name "Include file: ")))
12392 "\"")
12393 t t rpl)))
12394 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12395 (concat "\n" ind)))
12396 (insert rpl)
12397 (when (re-search-backward "\\?" start t) (delete-char 1))))
12399 ;;;; TODO, DEADLINE, Comments
12401 (defun org-toggle-comment ()
12402 "Change the COMMENT state of an entry."
12403 (interactive)
12404 (save-excursion
12405 (org-back-to-heading)
12406 (let ((case-fold-search nil))
12407 (looking-at org-complex-heading-regexp))
12408 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12409 (skip-chars-forward " \t")
12410 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12411 (if (org-in-commented-heading-p t)
12412 (delete-region (point)
12413 (progn (search-forward " " (line-end-position) 'move)
12414 (skip-chars-forward " \t")
12415 (point)))
12416 (insert org-comment-string)
12417 (unless (eolp) (insert " ")))))
12419 (defvar org-last-todo-state-is-todo nil
12420 "This is non-nil when the last TODO state change led to a TODO state.
12421 If the last change removed the TODO tag or switched to DONE, then
12422 this is nil.")
12424 (defvar org-setting-tags nil) ; dynamically skipped
12426 (defvar org-todo-setup-filter-hook nil
12427 "Hook for functions that pre-filter todo specs.
12428 Each function takes a todo spec and returns either nil or the spec
12429 transformed into canonical form." )
12431 (defvar org-todo-get-default-hook nil
12432 "Hook for functions that get a default item for todo.
12433 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12434 nil or a string to be used for the todo mark." )
12436 (defvar org-agenda-headline-snapshot-before-repeat)
12438 (defun org-current-effective-time ()
12439 "Return current time adjusted for `org-extend-today-until' variable."
12440 (let* ((ct (org-current-time))
12441 (dct (decode-time ct))
12442 (ct1
12443 (cond
12444 (org-use-last-clock-out-time-as-effective-time
12445 (or (org-clock-get-last-clock-out-time) ct))
12446 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12447 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12448 (t ct))))
12449 ct1))
12451 (defun org-todo-yesterday (&optional arg)
12452 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12453 (interactive "P")
12454 (if (eq major-mode 'org-agenda-mode)
12455 (apply 'org-agenda-todo-yesterday arg)
12456 (let* ((org-use-effective-time t)
12457 (hour (nth 2 (decode-time (org-current-time))))
12458 (org-extend-today-until (1+ hour)))
12459 (org-todo arg))))
12461 (defvar org-block-entry-blocking ""
12462 "First entry preventing the TODO state change.")
12464 (defun org-cancel-repeater ()
12465 "Cancel a repeater by setting its numeric value to zero."
12466 (interactive)
12467 (save-excursion
12468 (org-back-to-heading t)
12469 (let ((bound1 (point))
12470 (bound0 (save-excursion (outline-next-heading) (point))))
12471 (when (and (re-search-forward
12472 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12473 org-deadline-time-regexp "\\)\\|\\("
12474 org-ts-regexp "\\)")
12475 bound0 t)
12476 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12477 bound1 t))
12478 (replace-match "0" t nil nil 1)))))
12480 (defvar org-state)
12481 (defvar org-blocked-by-checkboxes)
12482 (defun org-todo (&optional arg)
12483 "Change the TODO state of an item.
12485 The state of an item is given by a keyword at the start of the heading,
12486 like
12487 *** TODO Write paper
12488 *** DONE Call mom
12490 The different keywords are specified in the variable `org-todo-keywords'.
12491 By default the available states are \"TODO\" and \"DONE\". So, for this
12492 example: when the item starts with TODO, it is changed to DONE.
12493 When it starts with DONE, the DONE is removed. And when neither TODO nor
12494 DONE are present, add TODO at the beginning of the heading.
12496 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12497 state.
12498 With numeric prefix ARG, switch to that state.
12499 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12500 next set of TODO \
12501 keywords (nextset).
12502 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12503 prefix, circumvent any state blocking.
12504 With a numeric prefix arg of 0, inhibit note taking for the change.
12505 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12507 When called through ELisp, arg is also interpreted in the following way:
12508 `none' -> empty state
12509 \"\" -> switch to empty state
12510 `done' -> switch to DONE
12511 `nextset' -> switch to the next set of keywords
12512 `previousset' -> switch to the previous set of keywords
12513 \"WAITING\" -> switch to the specified keyword, but only if it
12514 really is a member of `org-todo-keywords'."
12515 (interactive "P")
12516 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12517 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12518 'region-start-level 'region))
12519 org-loop-over-headlines-in-active-region)
12520 (org-map-entries
12521 `(org-todo ,arg)
12522 org-loop-over-headlines-in-active-region
12523 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12524 (when (equal arg '(16)) (setq arg 'nextset))
12525 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12526 (let ((org-blocker-hook org-blocker-hook)
12527 commentp
12528 case-fold-search)
12529 (when (equal arg '(64))
12530 (setq arg nil org-blocker-hook nil))
12531 (when (and org-blocker-hook
12532 (or org-inhibit-blocking
12533 (org-entry-get nil "NOBLOCKING")))
12534 (setq org-blocker-hook nil))
12535 (save-excursion
12536 (catch 'exit
12537 (org-back-to-heading t)
12538 (when (org-in-commented-heading-p t)
12539 (org-toggle-comment)
12540 (setq commentp t))
12541 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12542 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12543 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12544 (let* ((match-data (match-data))
12545 (startpos (point-at-bol))
12546 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12547 (org-log-done org-log-done)
12548 (org-log-repeat org-log-repeat)
12549 (org-todo-log-states org-todo-log-states)
12550 (org-inhibit-logging
12551 (if (equal arg 0)
12552 (progn (setq arg nil) 'note) org-inhibit-logging))
12553 (this (match-string 1))
12554 (hl-pos (match-beginning 0))
12555 (head (org-get-todo-sequence-head this))
12556 (ass (assoc head org-todo-kwd-alist))
12557 (interpret (nth 1 ass))
12558 (done-word (nth 3 ass))
12559 (final-done-word (nth 4 ass))
12560 (org-last-state (or this ""))
12561 (completion-ignore-case t)
12562 (member (member this org-todo-keywords-1))
12563 (tail (cdr member))
12564 (org-state (cond
12565 ((and org-todo-key-trigger
12566 (or (and (equal arg '(4))
12567 (eq org-use-fast-todo-selection 'prefix))
12568 (and (not arg) org-use-fast-todo-selection
12569 (not (eq org-use-fast-todo-selection
12570 'prefix)))))
12571 ;; Use fast selection.
12572 (org-fast-todo-selection))
12573 ((and (equal arg '(4))
12574 (or (not org-use-fast-todo-selection)
12575 (not org-todo-key-trigger)))
12576 ;; Read a state with completion.
12577 (completing-read
12578 "State: " (mapcar #'list org-todo-keywords-1)
12579 nil t))
12580 ((eq arg 'right)
12581 (if this
12582 (if tail (car tail) nil)
12583 (car org-todo-keywords-1)))
12584 ((eq arg 'left)
12585 (unless (equal member org-todo-keywords-1)
12586 (if this
12587 (nth (- (length org-todo-keywords-1)
12588 (length tail) 2)
12589 org-todo-keywords-1)
12590 (org-last org-todo-keywords-1))))
12591 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12592 (setq arg nil))) ;hack to fall back to cycling
12593 (arg
12594 ;; User or caller requests a specific state.
12595 (cond
12596 ((equal arg "") nil)
12597 ((eq arg 'none) nil)
12598 ((eq arg 'done) (or done-word (car org-done-keywords)))
12599 ((eq arg 'nextset)
12600 (or (car (cdr (member head org-todo-heads)))
12601 (car org-todo-heads)))
12602 ((eq arg 'previousset)
12603 (let ((org-todo-heads (reverse org-todo-heads)))
12604 (or (car (cdr (member head org-todo-heads)))
12605 (car org-todo-heads))))
12606 ((car (member arg org-todo-keywords-1)))
12607 ((stringp arg)
12608 (user-error "State `%s' not valid in this file" arg))
12609 ((nth (1- (prefix-numeric-value arg))
12610 org-todo-keywords-1))))
12611 ((null member) (or head (car org-todo-keywords-1)))
12612 ((equal this final-done-word) nil) ;-> make empty
12613 ((null tail) nil) ;-> first entry
12614 ((memq interpret '(type priority))
12615 (if (eq this-command last-command)
12616 (car tail)
12617 (if (> (length tail) 0)
12618 (or done-word (car org-done-keywords))
12619 nil)))
12621 (car tail))))
12622 (org-state (or
12623 (run-hook-with-args-until-success
12624 'org-todo-get-default-hook org-state org-last-state)
12625 org-state))
12626 (next (if org-state (concat " " org-state " ") " "))
12627 (change-plist (list :type 'todo-state-change :from this :to org-state
12628 :position startpos))
12629 dolog now-done-p)
12630 (when org-blocker-hook
12631 (let (org-blocked-by-checkboxes block-reason)
12632 (setq org-last-todo-state-is-todo
12633 (not (member this org-done-keywords)))
12634 (unless (save-excursion
12635 (save-match-data
12636 (org-with-wide-buffer
12637 (run-hook-with-args-until-failure
12638 'org-blocker-hook change-plist))))
12639 (setq block-reason (if org-blocked-by-checkboxes
12640 "contained checkboxes"
12641 (format "\"%s\"" org-block-entry-blocking)))
12642 (if (called-interactively-p 'interactive)
12643 (user-error "TODO state change from %s to %s blocked (by %s)"
12644 this org-state block-reason)
12645 ;; Fail silently.
12646 (message "TODO state change from %s to %s blocked (by %s)"
12647 this org-state block-reason)
12648 (throw 'exit nil)))))
12649 (store-match-data match-data)
12650 (replace-match next t t)
12651 (cond ((equal this org-state)
12652 (message "TODO state was already %s" (org-trim next)))
12653 ((not (pos-visible-in-window-p hl-pos))
12654 (message "TODO state changed to %s" (org-trim next))))
12655 (unless head
12656 (setq head (org-get-todo-sequence-head org-state)
12657 ass (assoc head org-todo-kwd-alist)
12658 interpret (nth 1 ass)
12659 done-word (nth 3 ass)
12660 final-done-word (nth 4 ass)))
12661 (when (memq arg '(nextset previousset))
12662 (message "Keyword-Set %d/%d: %s"
12663 (- (length org-todo-sets) -1
12664 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12665 (length org-todo-sets)
12666 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12667 (setq org-last-todo-state-is-todo
12668 (not (member org-state org-done-keywords)))
12669 (setq now-done-p (and (member org-state org-done-keywords)
12670 (not (member this org-done-keywords))))
12671 (and logging (org-local-logging logging))
12672 (when (and (or org-todo-log-states org-log-done)
12673 (not (eq org-inhibit-logging t))
12674 (not (memq arg '(nextset previousset))))
12675 ;; We need to look at recording a time and note.
12676 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12677 (nth 2 (assoc this org-todo-log-states))))
12678 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12679 (setq dolog 'time))
12680 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12681 (and org-state
12682 (member org-state org-not-done-keywords)
12683 (not (member this org-not-done-keywords))))
12684 ;; This is now a todo state and was not one before
12685 ;; If there was a CLOSED time stamp, get rid of it.
12686 (org-add-planning-info nil nil 'closed))
12687 (when (and now-done-p org-log-done)
12688 ;; It is now done, and it was not done before.
12689 (org-add-planning-info 'closed (org-current-effective-time))
12690 (when (and (not dolog) (eq 'note org-log-done))
12691 (org-add-log-setup 'done org-state this 'note)))
12692 (when (and org-state dolog)
12693 ;; This is a non-nil state, and we need to log it.
12694 (org-add-log-setup 'state org-state this dolog)))
12695 ;; Fixup tag positioning.
12696 (org-todo-trigger-tag-changes org-state)
12697 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12698 (when org-provide-todo-statistics
12699 (org-update-parent-todo-statistics))
12700 (run-hooks 'org-after-todo-state-change-hook)
12701 (when (and arg (not (member org-state org-done-keywords)))
12702 (setq head (org-get-todo-sequence-head org-state)))
12703 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12704 ;; Do we need to trigger a repeat?
12705 (when now-done-p
12706 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12707 ;; This is for the agenda, take a snapshot of the headline.
12708 (save-match-data
12709 (setq org-agenda-headline-snapshot-before-repeat
12710 (org-get-heading))))
12711 (org-auto-repeat-maybe org-state))
12712 ;; Fixup cursor location if close to the keyword.
12713 (when (and (outline-on-heading-p)
12714 (not (bolp))
12715 (save-excursion (beginning-of-line 1)
12716 (looking-at org-todo-line-regexp))
12717 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12718 (goto-char (or (match-end 2) (match-end 1)))
12719 (and (looking-at " ") (just-one-space)))
12720 (when org-trigger-hook
12721 (save-excursion
12722 (run-hook-with-args 'org-trigger-hook change-plist)))
12723 (when commentp (org-toggle-comment))))))))
12725 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12726 "Block turning an entry into a TODO, using the hierarchy.
12727 This checks whether the current task should be blocked from state
12728 changes. Such blocking occurs when:
12730 1. The task has children which are not all in a completed state.
12732 2. A task has a parent with the property :ORDERED:, and there
12733 are siblings prior to the current task with incomplete
12734 status.
12736 3. The parent of the task is blocked because it has siblings that should
12737 be done first, or is child of a block grandparent TODO entry."
12739 (if (not org-enforce-todo-dependencies)
12740 t ; if locally turned off don't block
12741 (catch 'dont-block
12742 ;; If this is not a todo state change, or if this entry is already DONE,
12743 ;; do not block
12744 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12745 (member (plist-get change-plist :from)
12746 (cons 'done org-done-keywords))
12747 (member (plist-get change-plist :to)
12748 (cons 'todo org-not-done-keywords))
12749 (not (plist-get change-plist :to)))
12750 (throw 'dont-block t))
12751 ;; If this task has children, and any are undone, it's blocked
12752 (save-excursion
12753 (org-back-to-heading t)
12754 (let ((this-level (funcall outline-level)))
12755 (outline-next-heading)
12756 (let ((child-level (funcall outline-level)))
12757 (while (and (not (eobp))
12758 (> child-level this-level))
12759 ;; this todo has children, check whether they are all
12760 ;; completed
12761 (when (and (not (org-entry-is-done-p))
12762 (org-entry-is-todo-p))
12763 (setq org-block-entry-blocking (org-get-heading))
12764 (throw 'dont-block nil))
12765 (outline-next-heading)
12766 (setq child-level (funcall outline-level))))))
12767 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12768 ;; any previous siblings are undone, it's blocked
12769 (save-excursion
12770 (org-back-to-heading t)
12771 (let* ((pos (point))
12772 (parent-pos (and (org-up-heading-safe) (point)))
12773 (case-fold-search nil))
12774 (unless parent-pos (throw 'dont-block t)) ; no parent
12775 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12776 (forward-line 1)
12777 (re-search-forward org-not-done-heading-regexp pos t))
12778 (setq org-block-entry-blocking (match-string 0))
12779 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12780 ;; Search further up the hierarchy, to see if an ancestor is blocked
12781 (while t
12782 (goto-char parent-pos)
12783 (unless (looking-at org-not-done-heading-regexp)
12784 (throw 'dont-block t)) ; do not block, parent is not a TODO
12785 (setq pos (point))
12786 (setq parent-pos (and (org-up-heading-safe) (point)))
12787 (unless parent-pos (throw 'dont-block t)) ; no parent
12788 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12789 (forward-line 1)
12790 (re-search-forward org-not-done-heading-regexp pos t)
12791 (setq org-block-entry-blocking (org-get-heading)))
12792 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12794 (defcustom org-track-ordered-property-with-tag nil
12795 "Should the ORDERED property also be shown as a tag?
12796 The ORDERED property decides if an entry should require subtasks to be
12797 completed in sequence. Since a property is not very visible, setting
12798 this option means that toggling the ORDERED property with the command
12799 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12800 not relevant for the behavior, but it makes things more visible.
12802 Note that toggling the tag with tags commands will not change the property
12803 and therefore not influence behavior!
12805 This can be t, meaning the tag ORDERED should be used, It can also be a
12806 string to select a different tag for this task."
12807 :group 'org-todo
12808 :type '(choice
12809 (const :tag "No tracking" nil)
12810 (const :tag "Track with ORDERED tag" t)
12811 (string :tag "Use other tag")))
12813 (defun org-toggle-ordered-property ()
12814 "Toggle the ORDERED property of the current entry.
12815 For better visibility, you can track the value of this property with a tag.
12816 See variable `org-track-ordered-property-with-tag'."
12817 (interactive)
12818 (let* ((t1 org-track-ordered-property-with-tag)
12819 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12820 (save-excursion
12821 (org-back-to-heading)
12822 (if (org-entry-get nil "ORDERED")
12823 (progn
12824 (org-delete-property "ORDERED")
12825 (and tag (org-toggle-tag tag 'off))
12826 (message "Subtasks can be completed in arbitrary order"))
12827 (org-entry-put nil "ORDERED" "t")
12828 (and tag (org-toggle-tag tag 'on))
12829 (message "Subtasks must be completed in sequence")))))
12831 (defun org-block-todo-from-checkboxes (change-plist)
12832 "Block turning an entry into a TODO, using checkboxes.
12833 This checks whether the current task should be blocked from state
12834 changes because there are unchecked boxes in this entry."
12835 (if (not org-enforce-todo-checkbox-dependencies)
12836 t ; if locally turned off don't block
12837 (catch 'dont-block
12838 ;; If this is not a todo state change, or if this entry is already DONE,
12839 ;; do not block
12840 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12841 (member (plist-get change-plist :from)
12842 (cons 'done org-done-keywords))
12843 (member (plist-get change-plist :to)
12844 (cons 'todo org-not-done-keywords))
12845 (not (plist-get change-plist :to)))
12846 (throw 'dont-block t))
12847 ;; If this task has checkboxes that are not checked, it's blocked
12848 (save-excursion
12849 (org-back-to-heading t)
12850 (let ((beg (point)) end)
12851 (outline-next-heading)
12852 (setq end (point))
12853 (goto-char beg)
12854 (when (org-list-search-forward
12855 (concat (org-item-beginning-re)
12856 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12857 "\\[[- ]\\]")
12858 end t)
12859 (when (boundp 'org-blocked-by-checkboxes)
12860 (setq org-blocked-by-checkboxes t))
12861 (throw 'dont-block nil))))
12862 t))) ; do not block
12864 (defun org-entry-blocked-p ()
12865 "Non-nil if entry at point is blocked."
12866 (and (not (org-entry-get nil "NOBLOCKING"))
12867 (member (org-entry-get nil "TODO") org-not-done-keywords)
12868 (not (run-hook-with-args-until-failure
12869 'org-blocker-hook
12870 (list :type 'todo-state-change
12871 :position (point)
12872 :from 'todo
12873 :to 'done)))))
12875 (defun org-update-statistics-cookies (all)
12876 "Update the statistics cookie, either from TODO or from checkboxes.
12877 This should be called with the cursor in a line with a statistics
12878 cookie. When called with a \\[universal-argument] prefix, update
12879 all statistics cookies in the buffer."
12880 (interactive "P")
12881 (if all
12882 (progn
12883 (org-update-checkbox-count 'all)
12884 (org-map-entries 'org-update-parent-todo-statistics))
12885 (if (not (org-at-heading-p))
12886 (org-update-checkbox-count)
12887 (let ((pos (point-marker))
12888 end l1 l2)
12889 (ignore-errors (org-back-to-heading t))
12890 (if (not (org-at-heading-p))
12891 (org-update-checkbox-count)
12892 (setq l1 (org-outline-level))
12893 (setq end (save-excursion
12894 (outline-next-heading)
12895 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12896 (point)))
12897 (if (and (save-excursion
12898 (re-search-forward
12899 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12900 (not (save-excursion (re-search-forward
12901 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12902 (org-update-checkbox-count)
12903 (if (and l2 (> l2 l1))
12904 (progn
12905 (goto-char end)
12906 (org-update-parent-todo-statistics))
12907 (goto-char pos)
12908 (beginning-of-line 1)
12909 (while (re-search-forward
12910 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12911 (point-at-eol) t)
12912 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12913 (goto-char pos)
12914 (move-marker pos nil)))))
12916 (defvar org-entry-property-inherited-from) ;; defined below
12917 (defun org-update-parent-todo-statistics ()
12918 "Update any statistics cookie in the parent of the current headline.
12919 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12920 the entire subtree and this will travel up the hierarchy and update
12921 statistics everywhere."
12922 (let* ((prop (save-excursion (org-up-heading-safe)
12923 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12924 (recursive (or (not org-hierarchical-todo-statistics)
12925 (and prop (string-match "\\<recursive\\>" prop))))
12926 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12928 (first t)
12929 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12930 level ltoggle l1 new ndel
12931 (cnt-all 0) (cnt-done 0) is-percent kwd
12932 checkbox-beg cookie-present)
12933 (catch 'exit
12934 (save-excursion
12935 (beginning-of-line 1)
12936 (setq ltoggle (funcall outline-level))
12937 ;; Three situations are to consider:
12939 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12940 ;; to the top-level ancestor on the headline;
12942 ;; 2. If parent has "recursive" property, repeat up to the
12943 ;; headline setting that property, taking inheritance into
12944 ;; account;
12946 ;; 3. Else, move up to direct parent and proceed only once.
12947 (while (and (setq level (org-up-heading-safe))
12948 (or recursive first)
12949 (>= (point) lim))
12950 (setq first nil cookie-present nil)
12951 (unless (and level
12952 (not (string-match
12953 "\\<checkbox\\>"
12954 (downcase (or (org-entry-get nil "COOKIE_DATA")
12955 "")))))
12956 (throw 'exit nil))
12957 (while (re-search-forward box-re (point-at-eol) t)
12958 (setq cnt-all 0 cnt-done 0 cookie-present t)
12959 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12960 (save-match-data
12961 (unless (outline-next-heading) (throw 'exit nil))
12962 (while (and (looking-at org-complex-heading-regexp)
12963 (> (setq l1 (length (match-string 1))) level))
12964 (setq kwd (and (or recursive (= l1 ltoggle))
12965 (match-string 2)))
12966 (if (or (eq org-provide-todo-statistics 'all-headlines)
12967 (and (eq org-provide-todo-statistics t)
12968 (or (member kwd org-done-keywords)))
12969 (and (listp org-provide-todo-statistics)
12970 (stringp (car org-provide-todo-statistics))
12971 (or (member kwd org-provide-todo-statistics)
12972 (member kwd org-done-keywords)))
12973 (and (listp org-provide-todo-statistics)
12974 (listp (car org-provide-todo-statistics))
12975 (or (member kwd (car org-provide-todo-statistics))
12976 (and (member kwd org-done-keywords)
12977 (member kwd (cadr org-provide-todo-statistics))))))
12978 (setq cnt-all (1+ cnt-all))
12979 (and (eq org-provide-todo-statistics t)
12981 (setq cnt-all (1+ cnt-all))))
12982 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12983 (member kwd org-done-keywords))
12984 (and (listp org-provide-todo-statistics)
12985 (listp (car org-provide-todo-statistics))
12986 (member kwd org-done-keywords)
12987 (member kwd (cadr org-provide-todo-statistics)))
12988 (and (listp org-provide-todo-statistics)
12989 (stringp (car org-provide-todo-statistics))
12990 (member kwd org-done-keywords)))
12991 (setq cnt-done (1+ cnt-done)))
12992 (outline-next-heading)))
12993 (setq new
12994 (if is-percent
12995 (format "[%d%%]" (floor (* 100.0 cnt-done)
12996 (max 1 cnt-all)))
12997 (format "[%d/%d]" cnt-done cnt-all))
12998 ndel (- (match-end 0) checkbox-beg))
12999 (goto-char checkbox-beg)
13000 (insert new)
13001 (delete-region (point) (+ (point) ndel))
13002 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
13003 (when cookie-present
13004 (run-hook-with-args 'org-after-todo-statistics-hook
13005 cnt-done (- cnt-all cnt-done))))))
13006 (run-hooks 'org-todo-statistics-hook)))
13008 (defvar org-after-todo-statistics-hook nil
13009 "Hook that is called after a TODO statistics cookie has been updated.
13010 Each function is called with two arguments: the number of not-done entries
13011 and the number of done entries.
13013 For example, the following function, when added to this hook, will switch
13014 an entry to DONE when all children are done, and back to TODO when new
13015 entries are set to a TODO status. Note that this hook is only called
13016 when there is a statistics cookie in the headline!
13018 (defun org-summary-todo (n-done n-not-done)
13019 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13020 (let (org-log-done org-log-states) ; turn off logging
13021 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13024 (defvar org-todo-statistics-hook nil
13025 "Hook that is run whenever Org thinks TODO statistics should be updated.
13026 This hook runs even if there is no statistics cookie present, in which case
13027 `org-after-todo-statistics-hook' would not run.")
13029 (defun org-todo-trigger-tag-changes (state)
13030 "Apply the changes defined in `org-todo-state-tags-triggers'."
13031 (let ((l org-todo-state-tags-triggers)
13032 changes)
13033 (when (or (not state) (equal state ""))
13034 (setq changes (append changes (cdr (assoc "" l)))))
13035 (when (and (stringp state) (> (length state) 0))
13036 (setq changes (append changes (cdr (assoc state l)))))
13037 (when (member state org-not-done-keywords)
13038 (setq changes (append changes (cdr (assq 'todo l)))))
13039 (when (member state org-done-keywords)
13040 (setq changes (append changes (cdr (assq 'done l)))))
13041 (dolist (c changes)
13042 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13044 (defun org-local-logging (value)
13045 "Get logging settings from a property VALUE."
13046 ;; Directly set the variables, they are already local.
13047 (setq org-log-done nil
13048 org-log-repeat nil
13049 org-todo-log-states nil)
13050 (dolist (w (org-split-string value))
13051 (let (a)
13052 (cond
13053 ((setq a (assoc w org-startup-options))
13054 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13055 (set (nth 1 a) (nth 2 a))))
13056 ((setq a (org-extract-log-state-settings w))
13057 (and (member (car a) org-todo-keywords-1)
13058 (push a org-todo-log-states)))))))
13060 (defun org-get-todo-sequence-head (kwd)
13061 "Return the head of the TODO sequence to which KWD belongs.
13062 If KWD is not set, check if there is a text property remembering the
13063 right sequence."
13064 (let (p)
13065 (cond
13066 ((not kwd)
13067 (or (get-text-property (point-at-bol) 'org-todo-head)
13068 (progn
13069 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13070 nil (point-at-eol)))
13071 (get-text-property p 'org-todo-head))))
13072 ((not (member kwd org-todo-keywords-1))
13073 (car org-todo-keywords-1))
13074 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13076 (defun org-fast-todo-selection ()
13077 "Fast TODO keyword selection with single keys.
13078 Returns the new TODO keyword, or nil if no state change should occur."
13079 (let* ((fulltable org-todo-key-alist)
13080 (done-keywords org-done-keywords) ;; needed for the faces.
13081 (maxlen (apply 'max (mapcar
13082 (lambda (x)
13083 (if (stringp (car x)) (string-width (car x)) 0))
13084 fulltable)))
13085 (expert nil)
13086 (fwidth (+ maxlen 3 1 3))
13087 (ncol (/ (- (window-width) 4) fwidth))
13088 tg cnt e c tbl
13089 groups ingroup)
13090 (save-excursion
13091 (save-window-excursion
13092 (if expert
13093 (set-buffer (get-buffer-create " *Org todo*"))
13094 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13095 (erase-buffer)
13096 (setq-local org-done-keywords done-keywords)
13097 (setq tbl fulltable cnt 0)
13098 (while (setq e (pop tbl))
13099 (cond
13100 ((equal e '(:startgroup))
13101 (push '() groups) (setq ingroup t)
13102 (unless (= cnt 0)
13103 (setq cnt 0)
13104 (insert "\n"))
13105 (insert "{ "))
13106 ((equal e '(:endgroup))
13107 (setq ingroup nil cnt 0)
13108 (insert "}\n"))
13109 ((equal e '(:newline))
13110 (unless (= cnt 0)
13111 (setq cnt 0)
13112 (insert "\n")
13113 (setq e (car tbl))
13114 (while (equal (car tbl) '(:newline))
13115 (insert "\n")
13116 (setq tbl (cdr tbl)))))
13118 (setq tg (car e) c (cdr e))
13119 (when ingroup (push tg (car groups)))
13120 (setq tg (org-add-props tg nil 'face
13121 (org-get-todo-face tg)))
13122 (when (and (= cnt 0) (not ingroup)) (insert " "))
13123 (insert "[" c "] " tg (make-string
13124 (- fwidth 4 (length tg)) ?\ ))
13125 (when (= (setq cnt (1+ cnt)) ncol)
13126 (insert "\n")
13127 (when ingroup (insert " "))
13128 (setq cnt 0)))))
13129 (insert "\n")
13130 (goto-char (point-min))
13131 (unless expert (org-fit-window-to-buffer))
13132 (message "[a-z..]:Set [SPC]:clear")
13133 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13134 (cond
13135 ((or (= c ?\C-g)
13136 (and (= c ?q) (not (rassoc c fulltable))))
13137 (setq quit-flag t))
13138 ((= c ?\ ) nil)
13139 ((setq e (rassoc c fulltable) tg (car e))
13141 (t (setq quit-flag t)))))))
13143 (defun org-entry-is-todo-p ()
13144 (member (org-get-todo-state) org-not-done-keywords))
13146 (defun org-entry-is-done-p ()
13147 (member (org-get-todo-state) org-done-keywords))
13149 (defun org-get-todo-state ()
13150 "Return the TODO keyword of the current subtree."
13151 (save-excursion
13152 (org-back-to-heading t)
13153 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13154 (match-end 2)
13155 (match-string 2))))
13157 (defun org-at-date-range-p (&optional inactive-ok)
13158 "Non-nil if point is inside a date range.
13160 When optional argument INACTIVE-OK is non-nil, also consider
13161 inactive time ranges.
13163 When this function returns a non-nil value, match data is set
13164 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13165 on INACTIVE-OK."
13166 (interactive)
13167 (save-excursion
13168 (catch 'exit
13169 (let ((pos (point)))
13170 (skip-chars-backward "^[<\r\n")
13171 (skip-chars-backward "<[")
13172 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13173 (>= (match-end 0) pos)
13174 (throw 'exit t))
13175 (skip-chars-backward "^<[\r\n")
13176 (skip-chars-backward "<[")
13177 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13178 (>= (match-end 0) pos)
13179 (throw 'exit t)))
13180 nil)))
13182 (defun org-get-repeat (&optional tagline)
13183 "Check if there is a deadline/schedule with repeater in this entry."
13184 (save-match-data
13185 (save-excursion
13186 (org-back-to-heading t)
13187 (and (re-search-forward (if tagline
13188 (concat tagline "\\s-*" org-repeat-re)
13189 org-repeat-re)
13190 (org-entry-end-position) t)
13191 (match-string-no-properties 1)))))
13193 (defvar org-last-changed-timestamp)
13194 (defvar org-last-inserted-timestamp)
13195 (defvar org-log-post-message)
13196 (defvar org-log-note-purpose)
13197 (defvar org-log-note-how nil)
13198 (defvar org-log-note-extra)
13199 (defun org-auto-repeat-maybe (done-word)
13200 "Check if the current headline contains a repeated time-stamp.
13202 If yes, set TODO state back to what it was and change the base date
13203 of repeating deadline/scheduled time stamps to new date.
13205 This function is run automatically after each state change to a DONE state."
13206 (let* ((repeat (org-get-repeat))
13207 (aa (assoc org-last-state org-todo-kwd-alist))
13208 (interpret (nth 1 aa))
13209 (head (nth 2 aa))
13210 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13211 (msg "Entry repeats: ")
13212 (org-log-done nil)
13213 (org-todo-log-states nil))
13214 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13215 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13216 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13217 org-todo-repeat-to-state)))
13218 (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
13219 to-state)
13220 ((eq interpret 'type) org-last-state)
13221 (head)
13222 (t 'none))))
13223 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13224 (org-entry-put nil "LAST_REPEAT" (format-time-string
13225 (org-time-stamp-format t t))))
13226 (when org-log-repeat
13227 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13228 (memq 'org-add-log-note post-command-hook))
13229 ;; We are already setup for some record.
13230 (when (eq org-log-repeat 'note)
13231 ;; Make sure we take a note, not only a time stamp.
13232 (setq org-log-note-how 'note))
13233 ;; Set up for taking a record.
13234 (org-add-log-setup 'state
13235 (or done-word (car org-done-keywords))
13236 org-last-state
13237 org-log-repeat)))
13238 (org-back-to-heading t)
13239 (org-add-planning-info nil nil 'closed)
13240 (let ((end (save-excursion (outline-next-heading) (point)))
13241 (planning-re (regexp-opt
13242 (list org-scheduled-string org-deadline-string))))
13243 (while (re-search-forward org-ts-regexp end t)
13244 (let* ((ts (match-string 0))
13245 (planning? (org-at-planning-p))
13246 (type (if (not planning?) "Plain:"
13247 (save-excursion
13248 (re-search-backward
13249 planning-re (line-beginning-position) t)
13250 (match-string 0)))))
13251 (cond
13252 ;; Ignore fake time-stamps (e.g., within comments).
13253 ((and (not planning?)
13254 (not (org-at-property-p))
13255 (not (eq 'timestamp
13256 (org-element-type (save-excursion
13257 (backward-char)
13258 (org-element-context)))))))
13259 ;; Time-stamps without a repeater are usually skipped.
13260 ;; However, a SCHEDULED time-stamp without one is
13261 ;; removed, as it is considered as no longer relevant.
13262 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13263 (when (equal type org-scheduled-string)
13264 (org-remove-timestamp-with-keyword type)))
13266 (let ((n (string-to-number (match-string 2 ts)))
13267 (what (match-string 3 ts)))
13268 (when (equal what "w") (setq n (* n 7) what "d"))
13269 (when (and (equal what "h")
13270 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13271 ts)))
13272 (user-error
13273 "Cannot repeat in Repeat in %d hour(s) because no hour \
13274 has been set"
13276 ;; Preparation, see if we need to modify the start
13277 ;; date for the change.
13278 (when (match-end 1)
13279 (let ((time (save-match-data (org-time-string-to-time ts))))
13280 (cond
13281 ((equal (match-string 1 ts) ".")
13282 ;; Shift starting date to today
13283 (org-timestamp-change
13284 (- (org-today) (time-to-days time))
13285 'day))
13286 ((equal (match-string 1 ts) "+")
13287 (let ((nshiftmax 10)
13288 (nshift 0))
13289 (while (or (= nshift 0)
13290 (not (time-less-p (current-time) time)))
13291 (when (= (cl-incf nshift) nshiftmax)
13292 (or (y-or-n-p
13293 (format "%d repeater intervals were not \
13294 enough to shift date past today. Continue? "
13295 nshift))
13296 (user-error "Abort")))
13297 (org-timestamp-change n (cdr (assoc what whata)))
13298 (org-at-timestamp-p t)
13299 (setq ts (match-string 1))
13300 (setq time
13301 (save-match-data
13302 (org-time-string-to-time ts)))))
13303 (org-timestamp-change (- n) (cdr (assoc what whata)))
13304 ;; Rematch, so that we have everything in place
13305 ;; for the real shift.
13306 (org-at-timestamp-p t)
13307 (setq ts (match-string 1))
13308 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13309 ts)))))
13310 (save-excursion
13311 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13312 (setq msg
13313 (concat
13314 msg type " " org-last-changed-timestamp " "))))))))
13315 (setq org-log-post-message msg)
13316 (message "%s" msg))))
13318 (defun org-show-todo-tree (arg)
13319 "Make a compact tree which shows all headlines marked with TODO.
13320 The tree will show the lines where the regexp matches, and all higher
13321 headlines above the match.
13322 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13323 With a numeric prefix N, construct a sparse tree for the Nth element
13324 of `org-todo-keywords-1'."
13325 (interactive "P")
13326 (let ((case-fold-search nil)
13327 (kwd-re
13328 (cond ((null arg) org-not-done-regexp)
13329 ((equal arg '(4))
13330 (let ((kwd
13331 (completing-read "Keyword (or KWD1|KWD2|...): "
13332 (mapcar #'list org-todo-keywords-1))))
13333 (concat "\\("
13334 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13335 "\\)\\>")))
13336 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13337 (regexp-quote (nth (1- (prefix-numeric-value arg))
13338 org-todo-keywords-1)))
13339 (t (user-error "Invalid prefix argument: %s" arg)))))
13340 (message "%d TODO entries found"
13341 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13343 (defun org--deadline-or-schedule (arg type time)
13344 "Insert DEADLINE or SCHEDULE information in current entry.
13345 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13346 `org-schedule' for information about ARG and TIME arguments."
13347 (let* ((deadline? (eq type 'deadline))
13348 (keyword (if deadline? org-deadline-string org-scheduled-string))
13349 (log (if deadline? org-log-redeadline org-log-reschedule))
13350 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13351 (old-date-time (and old-date (org-time-string-to-time old-date)))
13352 ;; Save repeater cookie from either TIME or current scheduled
13353 ;; time stamp. We are going to insert it back at the end of
13354 ;; the process.
13355 (repeater (or (and (org-string-nw-p time)
13356 ;; We use `org-repeat-re' because we need
13357 ;; to tell the difference between a real
13358 ;; repeater and a time delta, e.g. "+2d".
13359 (string-match org-repeat-re time)
13360 (match-string 1 time))
13361 (and (org-string-nw-p old-date)
13362 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13363 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13364 old-date)
13365 (match-string 1 old-date)))))
13366 (pcase arg
13367 (`(4)
13368 (when (and old-date log)
13369 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13370 nil old-date log))
13371 (org-remove-timestamp-with-keyword keyword)
13372 (message (if deadline? "Item no longer has a deadline."
13373 "Item is no longer scheduled.")))
13374 (`(16)
13375 (save-excursion
13376 (org-back-to-heading t)
13377 (let ((regexp (if deadline? org-deadline-time-regexp
13378 org-scheduled-time-regexp)))
13379 (if (not (re-search-forward regexp (line-end-position 2) t))
13380 (user-error (if deadline? "No deadline information to update"
13381 "No scheduled information to update"))
13382 (let* ((rpl0 (match-string 1))
13383 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13384 (msg (if deadline? "Warn starting from" "Delay until")))
13385 (replace-match
13386 (concat keyword
13387 " <" rpl
13388 (format " -%dd"
13389 (abs (- (time-to-days
13390 (save-match-data
13391 (org-read-date
13392 nil t nil msg old-date-time)))
13393 (time-to-days old-date-time))))
13394 ">") t t))))))
13396 (org-add-planning-info type time 'closed)
13397 (when (and old-date
13399 (not (equal old-date org-last-inserted-timestamp)))
13400 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13401 org-last-inserted-timestamp
13402 old-date
13403 log))
13404 (when repeater
13405 (save-excursion
13406 (org-back-to-heading t)
13407 (when (re-search-forward
13408 (concat keyword " " org-last-inserted-timestamp)
13409 (line-end-position 2)
13411 (goto-char (1- (match-end 0)))
13412 (insert " " repeater)
13413 (setq org-last-inserted-timestamp
13414 (concat (substring org-last-inserted-timestamp 0 -1)
13415 " " repeater
13416 (substring org-last-inserted-timestamp -1))))))
13417 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13418 org-last-inserted-timestamp)))))
13420 (defun org-deadline (arg &optional time)
13421 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13422 With one universal prefix argument, remove any deadline from the item.
13423 With two universal prefix arguments, prompt for a warning delay.
13424 With argument TIME, set the deadline at the corresponding date. TIME
13425 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13426 (interactive "P")
13427 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13428 (org-map-entries
13429 (lambda () (org--deadline-or-schedule arg 'deadline time))
13431 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13432 'region-start-level
13433 'region)
13434 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13435 (org--deadline-or-schedule arg 'deadline time)))
13437 (defun org-schedule (arg &optional time)
13438 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13439 With one universal prefix argument, remove any scheduling date from the item.
13440 With two universal prefix arguments, prompt for a delay cookie.
13441 With argument TIME, scheduled at the corresponding date. TIME can
13442 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13443 (interactive "P")
13444 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13445 (org-map-entries
13446 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13448 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13449 'region-start-level
13450 'region)
13451 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13452 (org--deadline-or-schedule arg 'scheduled time)))
13454 (defun org-get-scheduled-time (pom &optional inherit)
13455 "Get the scheduled time as a time tuple, of a format suitable
13456 for calling org-schedule with, or if there is no scheduling,
13457 returns nil."
13458 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13459 (when time
13460 (apply 'encode-time (org-parse-time-string time)))))
13462 (defun org-get-deadline-time (pom &optional inherit)
13463 "Get the deadline as a time tuple, of a format suitable for
13464 calling org-deadline with, or if there is no scheduling, returns
13465 nil."
13466 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13467 (when time
13468 (apply 'encode-time (org-parse-time-string time)))))
13470 (defun org-remove-timestamp-with-keyword (keyword)
13471 "Remove all time stamps with KEYWORD in the current entry."
13472 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13473 beg)
13474 (save-excursion
13475 (org-back-to-heading t)
13476 (setq beg (point))
13477 (outline-next-heading)
13478 (while (re-search-backward re beg t)
13479 (replace-match "")
13480 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13481 (equal (char-before) ?\ ))
13482 (backward-delete-char 1)
13483 (when (string-match "^[ \t]*$" (buffer-substring
13484 (point-at-bol) (point-at-eol)))
13485 (delete-region (point-at-bol)
13486 (min (point-max) (1+ (point-at-eol))))))))))
13488 (defvar org-time-was-given) ; dynamically scoped parameter
13489 (defvar org-end-time-was-given) ; dynamically scoped parameter
13491 (defun org-at-planning-p ()
13492 "Non-nil when point is on a planning info line."
13493 ;; This is as accurate and faster than `org-element-at-point' since
13494 ;; planning info location is fixed in the section.
13495 (org-with-wide-buffer
13496 (beginning-of-line)
13497 (and (looking-at-p org-planning-line-re)
13498 (eq (point)
13499 (ignore-errors
13500 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13501 (org-back-to-heading t)
13502 (org-with-limited-levels (org-back-to-heading t)))
13503 (line-beginning-position 2))))))
13505 (defun org-add-planning-info (what &optional time &rest remove)
13506 "Insert new timestamp with keyword in the planning line.
13507 WHAT indicates what kind of time stamp to add. It is a symbol
13508 among `closed', `deadline', `scheduled' and nil. TIME indicates
13509 the time to use. If none is given, the user is prompted for
13510 a date. REMOVE indicates what kind of entries to remove. An old
13511 WHAT entry will also be removed."
13512 (let (org-time-was-given org-end-time-was-given default-time default-input)
13513 (catch 'exit
13514 (when (and (memq what '(scheduled deadline))
13515 (or (not time)
13516 (and (stringp time)
13517 (string-match "^[-+]+[0-9]" time))))
13518 ;; Try to get a default date/time from existing timestamp
13519 (save-excursion
13520 (org-back-to-heading t)
13521 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13522 (when (re-search-forward (if (eq what 'scheduled)
13523 org-scheduled-time-regexp
13524 org-deadline-time-regexp)
13525 end t)
13526 (setq ts (match-string 1)
13527 default-time (apply 'encode-time (org-parse-time-string ts))
13528 default-input (and ts (org-get-compact-tod ts)))))))
13529 (when what
13530 (setq time
13531 (if (stringp time)
13532 ;; This is a string (relative or absolute), set
13533 ;; proper date.
13534 (apply #'encode-time
13535 (org-read-date-analyze
13536 time default-time (decode-time default-time)))
13537 ;; If necessary, get the time from the user
13538 (or time (org-read-date nil 'to-time nil nil
13539 default-time default-input)))))
13541 (org-with-wide-buffer
13542 (org-back-to-heading t)
13543 (forward-line)
13544 (unless (bolp) (insert "\n"))
13545 (cond ((looking-at-p org-planning-line-re)
13546 ;; Move to current indentation.
13547 (skip-chars-forward " \t")
13548 ;; Check if we have to remove something.
13549 (dolist (type (if what (cons what remove) remove))
13550 (save-excursion
13551 (when (re-search-forward
13552 (cl-case type
13553 (closed org-closed-time-regexp)
13554 (deadline org-deadline-time-regexp)
13555 (scheduled org-scheduled-time-regexp)
13556 (otherwise
13557 (error "Invalid planning type: %s" type)))
13558 (line-end-position) t)
13559 ;; Delete until next keyword or end of line.
13560 (delete-region
13561 (match-beginning 0)
13562 (if (re-search-forward org-keyword-time-not-clock-regexp
13563 (line-end-position)
13565 (match-beginning 0)
13566 (line-end-position))))))
13567 ;; If there is nothing more to add and no more keyword
13568 ;; is left, remove the line completely.
13569 (if (and (looking-at-p "[ \t]*$") (not what))
13570 (delete-region (line-beginning-position)
13571 (line-beginning-position 2))
13572 ;; If we removed last keyword, do not leave trailing
13573 ;; white space at the end of line.
13574 (let ((p (point)))
13575 (save-excursion
13576 (end-of-line)
13577 (unless (= (skip-chars-backward " \t" p) 0)
13578 (delete-region (point) (line-end-position)))))))
13579 ((not what) (throw 'exit nil)) ; Nothing to do.
13580 (t (insert-before-markers "\n")
13581 (backward-char 1)
13582 (when org-adapt-indentation
13583 (indent-to-column (1+ (org-outline-level))))))
13584 (when what
13585 ;; Insert planning keyword.
13586 (insert (cl-case what
13587 (closed org-closed-string)
13588 (deadline org-deadline-string)
13589 (scheduled org-scheduled-string)
13590 (otherwise (error "Invalid planning type: %s" what)))
13591 " ")
13592 ;; Insert associated timestamp.
13593 (let ((ts (org-insert-time-stamp
13594 time
13595 (or org-time-was-given
13596 (and (eq what 'closed) org-log-done-with-time))
13597 (eq what 'closed)
13598 nil nil (list org-end-time-was-given))))
13599 (unless (eolp) (insert " "))
13600 ts))))))
13602 (defvar org-log-note-marker (make-marker)
13603 "Marker pointing at the entry where the note is to be inserted.")
13604 (defvar org-log-note-purpose nil)
13605 (defvar org-log-note-state nil)
13606 (defvar org-log-note-previous-state nil)
13607 (defvar org-log-note-extra nil)
13608 (defvar org-log-note-window-configuration nil)
13609 (defvar org-log-note-return-to (make-marker))
13610 (defvar org-log-note-effective-time nil
13611 "Remembered current time so that dynamically scoped
13612 `org-extend-today-until' affects timestamps in state change log")
13614 (defvar org-log-post-message nil
13615 "Message to be displayed after a log note has been stored.
13616 The auto-repeater uses this.")
13618 (defun org-add-note ()
13619 "Add a note to the current entry.
13620 This is done in the same way as adding a state change note."
13621 (interactive)
13622 (org-add-log-setup 'note))
13624 (defun org-log-beginning (&optional create)
13625 "Return expected start of log notes in current entry.
13626 When optional argument CREATE is non-nil, the function creates
13627 a drawer to store notes, if necessary. Returned position ignores
13628 narrowing."
13629 (org-with-wide-buffer
13630 (let ((drawer (org-log-into-drawer)))
13631 (cond
13632 (drawer
13633 (org-end-of-meta-data)
13634 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13635 (end (if (org-at-heading-p) (point)
13636 (save-excursion (outline-next-heading) (point))))
13637 (case-fold-search t))
13638 (catch 'exit
13639 ;; Try to find existing drawer.
13640 (while (re-search-forward regexp end t)
13641 (let ((element (org-element-at-point)))
13642 (when (eq (org-element-type element) 'drawer)
13643 (let ((cend (org-element-property :contents-end element)))
13644 (when (and (not org-log-states-order-reversed) cend)
13645 (goto-char cend)))
13646 (throw 'exit nil))))
13647 ;; No drawer found. Create one, if permitted.
13648 (when create
13649 (unless (bolp) (insert "\n"))
13650 (let ((beg (point)))
13651 (insert ":" drawer ":\n:END:\n")
13652 (org-indent-region beg (point)))
13653 (end-of-line -1)))))
13655 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13656 (skip-chars-forward " \t\n")
13657 (beginning-of-line)
13658 (unless org-log-states-order-reversed
13659 (org-skip-over-state-notes)
13660 (skip-chars-backward " \t\n")
13661 (forward-line)))))
13662 (if (bolp) (point) (line-beginning-position 2))))
13664 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13665 "Set up the post command hook to take a note.
13666 If this is about to TODO state change, the new state is expected in STATE.
13667 HOW is an indicator what kind of note should be created.
13668 EXTRA is additional text that will be inserted into the notes buffer."
13669 (move-marker org-log-note-marker (point))
13670 (setq org-log-note-purpose purpose
13671 org-log-note-state state
13672 org-log-note-previous-state prev-state
13673 org-log-note-how how
13674 org-log-note-extra extra
13675 org-log-note-effective-time (org-current-effective-time))
13676 (add-hook 'post-command-hook 'org-add-log-note 'append))
13678 (defun org-skip-over-state-notes ()
13679 "Skip past the list of State notes in an entry."
13680 (when (ignore-errors (goto-char (org-in-item-p)))
13681 (let* ((struct (org-list-struct))
13682 (prevs (org-list-prevs-alist struct))
13683 (regexp
13684 (concat "[ \t]*- +"
13685 (replace-regexp-in-string
13686 " +" " +"
13687 (org-replace-escapes
13688 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13689 `(("%d" . ,org-ts-regexp-inactive)
13690 ("%D" . ,org-ts-regexp)
13691 ("%s" . "\"\\S-+\"")
13692 ("%S" . "\"\\S-+\"")
13693 ("%t" . ,org-ts-regexp-inactive)
13694 ("%T" . ,org-ts-regexp)
13695 ("%u" . ".*?")
13696 ("%U" . ".*?")))))))
13697 (while (looking-at-p regexp)
13698 (goto-char (or (org-list-get-next-item (point) struct prevs)
13699 (org-list-get-item-end (point) struct)))))))
13701 (defun org-add-log-note (&optional _purpose)
13702 "Pop up a window for taking a note, and add this note later."
13703 (remove-hook 'post-command-hook 'org-add-log-note)
13704 (setq org-log-note-window-configuration (current-window-configuration))
13705 (delete-other-windows)
13706 (move-marker org-log-note-return-to (point))
13707 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13708 (goto-char org-log-note-marker)
13709 (org-switch-to-buffer-other-window "*Org Note*")
13710 (erase-buffer)
13711 (if (memq org-log-note-how '(time state))
13712 (org-store-log-note)
13713 (let ((org-inhibit-startup t)) (org-mode))
13714 (insert (format "# Insert note for %s.
13715 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13716 (cond
13717 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13718 ((eq org-log-note-purpose 'done) "closed todo item")
13719 ((eq org-log-note-purpose 'state)
13720 (format "state change from \"%s\" to \"%s\""
13721 (or org-log-note-previous-state "")
13722 (or org-log-note-state "")))
13723 ((eq org-log-note-purpose 'reschedule)
13724 "rescheduling")
13725 ((eq org-log-note-purpose 'delschedule)
13726 "no longer scheduled")
13727 ((eq org-log-note-purpose 'redeadline)
13728 "changing deadline")
13729 ((eq org-log-note-purpose 'deldeadline)
13730 "removing deadline")
13731 ((eq org-log-note-purpose 'refile)
13732 "refiling")
13733 ((eq org-log-note-purpose 'note)
13734 "this entry")
13735 (t (error "This should not happen")))))
13736 (when org-log-note-extra (insert org-log-note-extra))
13737 (setq-local org-finish-function 'org-store-log-note)
13738 (run-hooks 'org-log-buffer-setup-hook)))
13740 (defvar org-note-abort nil) ; dynamically scoped
13741 (defun org-store-log-note ()
13742 "Finish taking a log note, and insert it to where it belongs."
13743 (let ((txt (prog1 (buffer-string)
13744 (kill-buffer)))
13745 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13746 lines)
13747 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13748 (setq txt (replace-match "" t t txt)))
13749 (when (string-match "\\s-+\\'" txt)
13750 (setq txt (replace-match "" t t txt)))
13751 (setq lines (org-split-string txt "\n"))
13752 (when (org-string-nw-p note)
13753 (setq note
13754 (org-replace-escapes
13755 note
13756 (list (cons "%u" (user-login-name))
13757 (cons "%U" user-full-name)
13758 (cons "%t" (format-time-string
13759 (org-time-stamp-format 'long 'inactive)
13760 org-log-note-effective-time))
13761 (cons "%T" (format-time-string
13762 (org-time-stamp-format 'long nil)
13763 org-log-note-effective-time))
13764 (cons "%d" (format-time-string
13765 (org-time-stamp-format nil 'inactive)
13766 org-log-note-effective-time))
13767 (cons "%D" (format-time-string
13768 (org-time-stamp-format nil nil)
13769 org-log-note-effective-time))
13770 (cons "%s" (cond
13771 ((not org-log-note-state) "")
13772 ((string-match-p org-ts-regexp
13773 org-log-note-state)
13774 (format "\"[%s]\""
13775 (substring org-log-note-state 1 -1)))
13776 (t (format "\"%s\"" org-log-note-state))))
13777 (cons "%S"
13778 (cond
13779 ((not org-log-note-previous-state) "")
13780 ((string-match-p org-ts-regexp
13781 org-log-note-previous-state)
13782 (format "\"[%s]\""
13783 (substring
13784 org-log-note-previous-state 1 -1)))
13785 (t (format "\"%s\""
13786 org-log-note-previous-state)))))))
13787 (when lines (setq note (concat note " \\\\")))
13788 (push note lines))
13789 (when (and lines (not org-note-abort))
13790 (with-current-buffer (marker-buffer org-log-note-marker)
13791 (org-with-wide-buffer
13792 ;; Find location for the new note.
13793 (goto-char org-log-note-marker)
13794 (set-marker org-log-note-marker nil)
13795 ;; Note associated to a clock is to be located right after
13796 ;; the clock. Do not move point.
13797 (unless (eq org-log-note-purpose 'clock-out)
13798 (goto-char (org-log-beginning t)))
13799 ;; Make sure point is at the beginning of an empty line.
13800 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13801 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13802 ;; In an existing list, add a new item at the top level.
13803 ;; Otherwise, indent line like a regular one.
13804 (let ((itemp (org-in-item-p)))
13805 (if itemp
13806 (indent-line-to
13807 (let ((struct (save-excursion
13808 (goto-char itemp) (org-list-struct))))
13809 (org-list-get-ind (org-list-get-top-point struct) struct)))
13810 (org-indent-line)))
13811 (insert (org-list-bullet-string "-") (pop lines))
13812 (let ((ind (org-list-item-body-column (line-beginning-position))))
13813 (dolist (line lines)
13814 (insert "\n")
13815 (indent-line-to ind)
13816 (insert line)))
13817 (message "Note stored")
13818 (org-back-to-heading t)
13819 (org-cycle-hide-drawers 'children))
13820 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13821 ;; from within `org-add-log-note' because `buffer-undo-list'
13822 ;; is then modified outside of `org-with-remote-undo'.
13823 (when (eq this-command 'org-agenda-todo)
13824 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13825 ;; Don't add undo information when called from `org-agenda-todo'.
13826 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13827 (set-window-configuration org-log-note-window-configuration)
13828 (with-current-buffer (marker-buffer org-log-note-return-to)
13829 (goto-char org-log-note-return-to))
13830 (move-marker org-log-note-return-to nil)
13831 (when org-log-post-message (message "%s" org-log-post-message))))
13833 (defun org-remove-empty-drawer-at (pos)
13834 "Remove an empty drawer at position POS.
13835 POS may also be a marker."
13836 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13837 (org-with-wide-buffer
13838 (goto-char pos)
13839 (let ((drawer (org-element-at-point)))
13840 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13841 (not (org-element-property :contents-begin drawer)))
13842 (delete-region (org-element-property :begin drawer)
13843 (progn (goto-char (org-element-property :end drawer))
13844 (skip-chars-backward " \r\t\n")
13845 (forward-line)
13846 (point))))))))
13848 (defvar org-ts-type nil)
13849 (defun org-sparse-tree (&optional arg type)
13850 "Create a sparse tree, prompt for the details.
13851 This command can create sparse trees. You first need to select the type
13852 of match used to create the tree:
13854 t Show all TODO entries.
13855 T Show entries with a specific TODO keyword.
13856 m Show entries selected by a tags/property match.
13857 p Enter a property name and its value (both with completion on existing
13858 names/values) and show entries with that property.
13859 r Show entries matching a regular expression (`/' can be used as well).
13860 b Show deadlines and scheduled items before a date.
13861 a Show deadlines and scheduled items after a date.
13862 d Show deadlines due within `org-deadline-warning-days'.
13863 D Show deadlines and scheduled items between a date range."
13864 (interactive "P")
13865 (setq type (or type org-sparse-tree-default-date-type))
13866 (setq org-ts-type type)
13867 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13868 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13869 \[c]ycle through date types: %s"
13870 (cl-case type
13871 (all "all timestamps")
13872 (scheduled "only scheduled")
13873 (deadline "only deadline")
13874 (active "only active timestamps")
13875 (inactive "only inactive timestamps")
13876 (closed "with a closed time-stamp")
13877 (otherwise "scheduled/deadline")))
13878 (let ((answer (read-char-exclusive)))
13879 (cl-case answer
13881 (org-sparse-tree
13883 (cadr
13884 (memq type '(nil all scheduled deadline active inactive closed)))))
13885 (?d (call-interactively 'org-check-deadlines))
13886 (?b (call-interactively 'org-check-before-date))
13887 (?a (call-interactively 'org-check-after-date))
13888 (?D (call-interactively 'org-check-dates-range))
13889 (?t (call-interactively 'org-show-todo-tree))
13890 (?T (org-show-todo-tree '(4)))
13891 (?m (call-interactively 'org-match-sparse-tree))
13892 ((?p ?P)
13893 (let* ((kwd (completing-read
13894 "Property: " (mapcar #'list (org-buffer-property-keys))))
13895 (value (completing-read
13896 "Value: " (mapcar #'list (org-property-values kwd)))))
13897 (unless (string-match "\\`{.*}\\'" value)
13898 (setq value (concat "\"" value "\"")))
13899 (org-match-sparse-tree arg (concat kwd "=" value))))
13900 ((?r ?R ?/) (call-interactively 'org-occur))
13901 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13903 (defvar-local org-occur-highlights nil
13904 "List of overlays used for occur matches.")
13905 (defvar-local org-occur-parameters nil
13906 "Parameters of the active org-occur calls.
13907 This is a list, each call to org-occur pushes as cons cell,
13908 containing the regular expression and the callback, onto the list.
13909 The list can contain several entries if `org-occur' has been called
13910 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13911 will only contain one set of parameters. When the highlights are
13912 removed (for example with `C-c C-c', or with the next edit (depending
13913 on `org-remove-highlights-with-change'), this variable is emptied
13914 as well.")
13916 (defun org-occur (regexp &optional keep-previous callback)
13917 "Make a compact tree which shows all matches of REGEXP.
13919 The tree will show the lines where the regexp matches, and any other context
13920 defined in `org-show-context-detail', which see.
13922 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13923 done by a previous call to `org-occur' will be kept, to allow stacking of
13924 calls to this command.
13926 Optional argument CALLBACK can be a function of no argument. In this case,
13927 it is called with point at the end of the match, match data being set
13928 accordingly. Current match is shown only if the return value is non-nil.
13929 The function must neither move point nor alter narrowing."
13930 (interactive "sRegexp: \nP")
13931 (when (equal regexp "")
13932 (user-error "Regexp cannot be empty"))
13933 (unless keep-previous
13934 (org-remove-occur-highlights nil nil t))
13935 (push (cons regexp callback) org-occur-parameters)
13936 (let ((cnt 0))
13937 (save-excursion
13938 (goto-char (point-min))
13939 (when (or (not keep-previous) ; do not want to keep
13940 (not org-occur-highlights)) ; no previous matches
13941 ;; hide everything
13942 (org-overview))
13943 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13944 (isearch-no-upper-case-p regexp t)
13945 org-occur-case-fold-search)))
13946 (while (re-search-forward regexp nil t)
13947 (when (or (not callback)
13948 (save-match-data (funcall callback)))
13949 (setq cnt (1+ cnt))
13950 (when org-highlight-sparse-tree-matches
13951 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13952 (org-show-context 'occur-tree)))))
13953 (when org-remove-highlights-with-change
13954 (add-hook 'before-change-functions 'org-remove-occur-highlights
13955 nil 'local))
13956 (unless org-sparse-tree-open-archived-trees
13957 (org-hide-archived-subtrees (point-min) (point-max)))
13958 (run-hooks 'org-occur-hook)
13959 (when (called-interactively-p 'interactive)
13960 (message "%d match(es) for regexp %s" cnt regexp))
13961 cnt))
13963 (defun org-occur-next-match (&optional n _reset)
13964 "Function for `next-error-function' to find sparse tree matches.
13965 N is the number of matches to move, when negative move backwards.
13966 This function always goes back to the starting point when no
13967 match is found."
13968 (let* ((limit (if (< n 0) (point-min) (point-max)))
13969 (search-func (if (< n 0)
13970 'previous-single-char-property-change
13971 'next-single-char-property-change))
13972 (n (abs n))
13973 (pos (point))
13975 (catch 'exit
13976 (while (setq p1 (funcall search-func (point) 'org-type))
13977 (when (equal p1 limit)
13978 (goto-char pos)
13979 (user-error "No more matches"))
13980 (when (equal (get-char-property p1 'org-type) 'org-occur)
13981 (setq n (1- n))
13982 (when (= n 0)
13983 (goto-char p1)
13984 (throw 'exit (point))))
13985 (goto-char p1))
13986 (goto-char p1)
13987 (user-error "No more matches"))))
13989 (defun org-show-context (&optional key)
13990 "Make sure point and context are visible.
13991 Optional argument KEY, when non-nil, is a symbol. See
13992 `org-show-context-detail' for allowed values and how much is to
13993 be shown."
13994 (org-show-set-visibility
13995 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13996 ((cdr (assq key org-show-context-detail)))
13997 (t (cdr (assq 'default org-show-context-detail))))))
13999 (defun org-show-set-visibility (detail)
14000 "Set visibility around point according to DETAIL.
14001 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14002 `tree', `canonical' or t. See `org-show-context-detail' for more
14003 information."
14004 ;; Show current heading and possibly its entry, following headline
14005 ;; or all children.
14006 (if (and (org-at-heading-p) (not (eq detail 'local)))
14007 (org-flag-heading nil)
14008 (org-show-entry)
14009 ;; If point is hidden within a drawer or a block, make sure to
14010 ;; expose it.
14011 (dolist (o (overlays-at (point)))
14012 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14013 (delete-overlay o)))
14014 (unless (org-before-first-heading-p)
14015 (org-with-limited-levels
14016 (cl-case detail
14017 ((tree canonical t) (org-show-children))
14018 ((nil minimal ancestors))
14019 (t (save-excursion
14020 (outline-next-heading)
14021 (org-flag-heading nil)))))))
14022 ;; Show all siblings.
14023 (when (eq detail 'lineage) (org-show-siblings))
14024 ;; Show ancestors, possibly with their children.
14025 (when (memq detail '(ancestors lineage tree canonical t))
14026 (save-excursion
14027 (while (org-up-heading-safe)
14028 (org-flag-heading nil)
14029 (when (memq detail '(canonical t)) (org-show-entry))
14030 (when (memq detail '(tree canonical t)) (org-show-children))))))
14032 (defvar org-reveal-start-hook nil
14033 "Hook run before revealing a location.")
14035 (defun org-reveal (&optional siblings)
14036 "Show current entry, hierarchy above it, and the following headline.
14038 This can be used to show a consistent set of context around
14039 locations exposed with `org-show-context'.
14041 With optional argument SIBLINGS, on each level of the hierarchy all
14042 siblings are shown. This repairs the tree structure to what it would
14043 look like when opened with hierarchical calls to `org-cycle'.
14045 With a \\[universal-argument] \\[universal-argument] prefix, \
14046 go to the parent and show the entire tree."
14047 (interactive "P")
14048 (run-hooks 'org-reveal-start-hook)
14049 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14050 ((equal siblings '(16))
14051 (save-excursion
14052 (when (org-up-heading-safe)
14053 (org-show-subtree)
14054 (run-hook-with-args 'org-cycle-hook 'subtree))))
14055 (t (org-show-set-visibility 'lineage))))
14057 (defun org-highlight-new-match (beg end)
14058 "Highlight from BEG to END and mark the highlight is an occur headline."
14059 (let ((ov (make-overlay beg end)))
14060 (overlay-put ov 'face 'secondary-selection)
14061 (overlay-put ov 'org-type 'org-occur)
14062 (push ov org-occur-highlights)))
14064 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14065 "Remove the occur highlights from the buffer.
14066 BEG and END are ignored. If NOREMOVE is nil, remove this function
14067 from the `before-change-functions' in the current buffer."
14068 (interactive)
14069 (unless org-inhibit-highlight-removal
14070 (mapc #'delete-overlay org-occur-highlights)
14071 (setq org-occur-highlights nil)
14072 (setq org-occur-parameters nil)
14073 (unless noremove
14074 (remove-hook 'before-change-functions
14075 'org-remove-occur-highlights 'local))))
14077 ;;;; Priorities
14079 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14080 "Regular expression matching the priority indicator.")
14082 (defvar org-remove-priority-next-time nil)
14084 (defun org-priority-up ()
14085 "Increase the priority of the current item."
14086 (interactive)
14087 (org-priority 'up))
14089 (defun org-priority-down ()
14090 "Decrease the priority of the current item."
14091 (interactive)
14092 (org-priority 'down))
14094 (defun org-priority (&optional action _show)
14095 "Change the priority of an item.
14096 ACTION can be `set', `up', `down', or a character."
14097 (interactive "P")
14098 (if (equal action '(4))
14099 (org-show-priority)
14100 (unless org-enable-priority-commands
14101 (user-error "Priority commands are disabled"))
14102 (setq action (or action 'set))
14103 (let (current new news have remove)
14104 (save-excursion
14105 (org-back-to-heading t)
14106 (when (looking-at org-priority-regexp)
14107 (setq current (string-to-char (match-string 2))
14108 have t))
14109 (cond
14110 ((eq action 'remove)
14111 (setq remove t new ?\ ))
14112 ((or (eq action 'set)
14113 (integerp action))
14114 (if (not (eq action 'set))
14115 (setq new action)
14116 (message "Priority %c-%c, SPC to remove: "
14117 org-highest-priority org-lowest-priority)
14118 (save-match-data
14119 (setq new (read-char-exclusive))))
14120 (when (and (= (upcase org-highest-priority) org-highest-priority)
14121 (= (upcase org-lowest-priority) org-lowest-priority))
14122 (setq new (upcase new)))
14123 (cond ((equal new ?\ ) (setq remove t))
14124 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14125 (user-error "Priority must be between `%c' and `%c'"
14126 org-highest-priority org-lowest-priority))))
14127 ((eq action 'up)
14128 (setq new (if have
14129 (1- current) ; normal cycling
14130 ;; last priority was empty
14131 (if (eq last-command this-command)
14132 org-lowest-priority ; wrap around empty to lowest
14133 ;; default
14134 (if org-priority-start-cycle-with-default
14135 org-default-priority
14136 (1- org-default-priority))))))
14137 ((eq action 'down)
14138 (setq new (if have
14139 (1+ current) ; normal cycling
14140 ;; last priority was empty
14141 (if (eq last-command this-command)
14142 org-highest-priority ; wrap around empty to highest
14143 ;; default
14144 (if org-priority-start-cycle-with-default
14145 org-default-priority
14146 (1+ org-default-priority))))))
14147 (t (user-error "Invalid action")))
14148 (when (or (< (upcase new) org-highest-priority)
14149 (> (upcase new) org-lowest-priority))
14150 (if (and (memq action '(up down))
14151 (not have) (not (eq last-command this-command)))
14152 ;; `new' is from default priority
14153 (error
14154 "The default can not be set, see `org-default-priority' why")
14155 ;; normal cycling: `new' is beyond highest/lowest priority
14156 ;; and is wrapped around to the empty priority
14157 (setq remove t)))
14158 (setq news (format "%c" new))
14159 (if have
14160 (if remove
14161 (replace-match "" t t nil 1)
14162 (replace-match news t t nil 2))
14163 (if remove
14164 (user-error "No priority cookie found in line")
14165 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14166 (if (match-end 2)
14167 (progn
14168 (goto-char (match-end 2))
14169 (insert " [#" news "]"))
14170 (goto-char (match-beginning 3))
14171 (insert "[#" news "] "))))
14172 (org-set-tags nil 'align))
14173 (if remove
14174 (message "Priority removed")
14175 (message "Priority of current item set to %s" news)))))
14177 (defun org-show-priority ()
14178 "Show the priority of the current item.
14179 This priority is composed of the main priority given with the [#A] cookies,
14180 and by additional input from the age of a schedules or deadline entry."
14181 (interactive)
14182 (let ((pri (if (eq major-mode 'org-agenda-mode)
14183 (org-get-at-bol 'priority)
14184 (save-excursion
14185 (save-match-data
14186 (beginning-of-line)
14187 (and (looking-at org-heading-regexp)
14188 (org-get-priority (match-string 0))))))))
14189 (message "Priority is %d" (if pri pri -1000))))
14191 (defun org-get-priority (s)
14192 "Find priority cookie and return priority."
14193 (save-match-data
14194 (if (functionp org-get-priority-function)
14195 (funcall org-get-priority-function)
14196 (if (not (string-match org-priority-regexp s))
14197 (* 1000 (- org-lowest-priority org-default-priority))
14198 (* 1000 (- org-lowest-priority
14199 (string-to-char (match-string 2 s))))))))
14201 ;;;; Tags
14203 (defvar org-agenda-archives-mode)
14204 (defvar org-map-continue-from nil
14205 "Position from where mapping should continue.
14206 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14208 (defvar org-scanner-tags nil
14209 "The current tag list while the tags scanner is running.")
14211 (defvar org-trust-scanner-tags nil
14212 "Should `org-get-tags-at' use the tags for the scanner.
14213 This is for internal dynamical scoping only.
14214 When this is non-nil, the function `org-get-tags-at' will return the value
14215 of `org-scanner-tags' instead of building the list by itself. This
14216 can lead to large speed-ups when the tags scanner is used in a file with
14217 many entries, and when the list of tags is retrieved, for example to
14218 obtain a list of properties. Building the tags list for each entry in such
14219 a file becomes an N^2 operation - but with this variable set, it scales
14220 as N.")
14222 (defvar org--matcher-tags-todo-only nil)
14224 (defun org-scan-tags (action matcher todo-only &optional start-level)
14225 "Scan headline tags with inheritance and produce output ACTION.
14227 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14228 or `agenda' to produce an entry list for an agenda view. It can also be
14229 a Lisp form or a function that should be called at each matched headline, in
14230 this case the return value is a list of all return values from these calls.
14232 MATCHER is a function accepting three arguments, returning
14233 a non-nil value whenever a given set of tags qualifies a headline
14234 for inclusion. See `org-make-tags-matcher' for more information.
14235 As a special case, it can also be set to t (respectively nil) in
14236 order to match all (respectively none) headline.
14238 When TODO-ONLY is non-nil, only lines with a not-done TODO
14239 keyword are included in the output.
14241 START-LEVEL can be a string with asterisks, reducing the scope to
14242 headlines matching this string."
14243 (require 'org-agenda)
14244 (let* ((re (concat "^"
14245 (if start-level
14246 ;; Get the correct level to match
14247 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14248 org-outline-regexp)
14249 " *\\(\\<\\("
14250 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14251 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14252 (props (list 'face 'default
14253 'done-face 'org-agenda-done
14254 'undone-face 'default
14255 'mouse-face 'highlight
14256 'org-not-done-regexp org-not-done-regexp
14257 'org-todo-regexp org-todo-regexp
14258 'org-complex-heading-regexp org-complex-heading-regexp
14259 'help-echo
14260 (format "mouse-2 or RET jump to org file %s"
14261 (abbreviate-file-name
14262 (or (buffer-file-name (buffer-base-buffer))
14263 (buffer-name (buffer-base-buffer)))))))
14264 (org-map-continue-from nil)
14265 lspos tags tags-list
14266 (tags-alist (list (cons 0 org-file-tags)))
14267 (llast 0) rtn rtn1 level category i txt
14268 todo marker entry priority
14269 ts-date ts-date-type ts-date-pair)
14270 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14271 (setq action (list 'lambda nil action)))
14272 (save-excursion
14273 (goto-char (point-min))
14274 (when (eq action 'sparse-tree)
14275 (org-overview)
14276 (org-remove-occur-highlights))
14277 (while (let (case-fold-search)
14278 (re-search-forward re nil t))
14279 (setq org-map-continue-from nil)
14280 (catch :skip
14281 (setq todo
14282 ;; TODO: is the 1-2 difference a bug?
14283 (when (match-end 1) (match-string-no-properties 2))
14284 tags (when (match-end 4) (match-string-no-properties 4)))
14285 (goto-char (setq lspos (match-beginning 0)))
14286 (setq level (org-reduced-level (org-outline-level))
14287 category (org-get-category))
14288 (when (eq action 'agenda)
14289 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14290 ts-date (car ts-date-pair)
14291 ts-date-type (cdr ts-date-pair)))
14292 (setq i llast llast level)
14293 ;; remove tag lists from same and sublevels
14294 (while (>= i level)
14295 (when (setq entry (assoc i tags-alist))
14296 (setq tags-alist (delete entry tags-alist)))
14297 (setq i (1- i)))
14298 ;; add the next tags
14299 (when tags
14300 (setq tags (org-split-string tags ":")
14301 tags-alist
14302 (cons (cons level tags) tags-alist)))
14303 ;; compile tags for current headline
14304 (setq tags-list
14305 (if org-use-tag-inheritance
14306 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14307 tags)
14308 org-scanner-tags tags-list)
14309 (when org-use-tag-inheritance
14310 (setcdr (car tags-alist)
14311 (mapcar (lambda (x)
14312 (setq x (copy-sequence x))
14313 (org-add-prop-inherited x))
14314 (cdar tags-alist))))
14315 (when (and tags org-use-tag-inheritance
14316 (or (not (eq t org-use-tag-inheritance))
14317 org-tags-exclude-from-inheritance))
14318 ;; Selective inheritance, remove uninherited ones.
14319 (setcdr (car tags-alist)
14320 (org-remove-uninherited-tags (cdar tags-alist))))
14321 (when (and
14323 ;; eval matcher only when the todo condition is OK
14324 (and (or (not todo-only) (member todo org-not-done-keywords))
14325 (if (functionp matcher)
14326 (let ((case-fold-search t) (org-trust-scanner-tags t))
14327 (funcall matcher todo tags-list level))
14328 matcher))
14330 ;; Call the skipper, but return t if it does not
14331 ;; skip, so that the `and' form continues evaluating.
14332 (progn
14333 (unless (eq action 'sparse-tree) (org-agenda-skip))
14336 ;; Check if timestamps are deselecting this entry
14337 (or (not todo-only)
14338 (and (member todo org-not-done-keywords)
14339 (or (not org-agenda-tags-todo-honor-ignore-options)
14340 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14342 ;; select this headline
14343 (cond
14344 ((eq action 'sparse-tree)
14345 (and org-highlight-sparse-tree-matches
14346 (org-get-heading) (match-end 0)
14347 (org-highlight-new-match
14348 (match-beginning 1) (match-end 1)))
14349 (org-show-context 'tags-tree))
14350 ((eq action 'agenda)
14351 (setq txt (org-agenda-format-item
14353 (concat
14354 (if (eq org-tags-match-list-sublevels 'indented)
14355 (make-string (1- level) ?.) "")
14356 (org-get-heading))
14357 (make-string level ?\s)
14358 category
14359 tags-list)
14360 priority (org-get-priority txt))
14361 (goto-char lspos)
14362 (setq marker (org-agenda-new-marker))
14363 (org-add-props txt props
14364 'org-marker marker 'org-hd-marker marker 'org-category category
14365 'todo-state todo
14366 'ts-date ts-date
14367 'priority priority
14368 'type (concat "tagsmatch" ts-date-type))
14369 (push txt rtn))
14370 ((functionp action)
14371 (setq org-map-continue-from nil)
14372 (save-excursion
14373 (setq rtn1 (funcall action))
14374 (push rtn1 rtn)))
14375 (t (user-error "Invalid action")))
14377 ;; if we are to skip sublevels, jump to end of subtree
14378 (unless org-tags-match-list-sublevels
14379 (org-end-of-subtree t)
14380 (backward-char 1))))
14381 ;; Get the correct position from where to continue
14382 (if org-map-continue-from
14383 (goto-char org-map-continue-from)
14384 (and (= (point) lspos) (end-of-line 1)))))
14385 (when (and (eq action 'sparse-tree)
14386 (not org-sparse-tree-open-archived-trees))
14387 (org-hide-archived-subtrees (point-min) (point-max)))
14388 (nreverse rtn)))
14390 (defun org-remove-uninherited-tags (tags)
14391 "Remove all tags that are not inherited from the list TAGS."
14392 (cond
14393 ((eq org-use-tag-inheritance t)
14394 (if org-tags-exclude-from-inheritance
14395 (org-delete-all org-tags-exclude-from-inheritance tags)
14396 tags))
14397 ((not org-use-tag-inheritance) nil)
14398 ((stringp org-use-tag-inheritance)
14399 (delq nil (mapcar
14400 (lambda (x)
14401 (if (and (string-match org-use-tag-inheritance x)
14402 (not (member x org-tags-exclude-from-inheritance)))
14403 x nil))
14404 tags)))
14405 ((listp org-use-tag-inheritance)
14406 (delq nil (mapcar
14407 (lambda (x)
14408 (if (member x org-use-tag-inheritance) x nil))
14409 tags)))))
14411 (defun org-match-sparse-tree (&optional todo-only match)
14412 "Create a sparse tree according to tags string MATCH.
14414 MATCH is a string with match syntax. It can contain a selection
14415 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14416 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14417 those. See the manual for details.
14419 If optional argument TODO-ONLY is non-nil, only select lines that
14420 are also TODO tasks."
14421 (interactive "P")
14422 (org-agenda-prepare-buffers (list (current-buffer)))
14423 (let ((org--matcher-tags-todo-only todo-only))
14424 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14425 org--matcher-tags-todo-only)))
14427 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14429 (defvar org-cached-props nil)
14430 (defun org-cached-entry-get (pom property)
14431 (if (or (eq t org-use-property-inheritance)
14432 (and (stringp org-use-property-inheritance)
14433 (let ((case-fold-search t))
14434 (string-match-p org-use-property-inheritance property)))
14435 (and (listp org-use-property-inheritance)
14436 (member-ignore-case property org-use-property-inheritance)))
14437 ;; Caching is not possible, check it directly.
14438 (org-entry-get pom property 'inherit)
14439 ;; Get all properties, so we can do complicated checks easily.
14440 (cdr (assoc-string property
14441 (or org-cached-props
14442 (setq org-cached-props (org-entry-properties pom)))
14443 t))))
14445 (defun org-global-tags-completion-table (&optional files)
14446 "Return the list of all tags in all agenda buffer/files.
14447 Optional FILES argument is a list of files which can be used
14448 instead of the agenda files."
14449 (save-excursion
14450 (org-uniquify
14451 (delq nil
14452 (apply #'append
14453 (mapcar
14454 (lambda (file)
14455 (set-buffer (find-file-noselect file))
14456 (mapcar (lambda (x)
14457 (and (stringp (car-safe x))
14458 (list (car-safe x))))
14459 (or org-current-tag-alist (org-get-buffer-tags))))
14460 (if (car-safe files) files
14461 (org-agenda-files))))))))
14463 (defun org-make-tags-matcher (match)
14464 "Create the TAGS/TODO matcher form for the selection string MATCH.
14466 Returns a cons of the selection string MATCH and a function
14467 implementing the matcher.
14469 The matcher is to be called at an Org entry, with point on the
14470 headline, and returns non-nil if the entry matches the selection
14471 string MATCH. It must be called with three arguments: the TODO
14472 keyword at the entry (or nil if none), the list of all tags at
14473 the entry including inherited ones and the reduced level of the
14474 headline. Additionally, the category of the entry, if any, must
14475 be specified as the text property `org-category' on the headline.
14477 This function sets the variable `org--matcher-tags-todo-only' to
14478 a non-nil value if the matcher restricts matching to TODO
14479 entries, otherwise it is not touched.
14481 See also `org-scan-tags'."
14482 (unless match
14483 ;; Get a new match request, with completion against the global
14484 ;; tags table and the local tags in current buffer.
14485 (let ((org-last-tags-completion-table
14486 (org-uniquify
14487 (delq nil (append (org-get-buffer-tags)
14488 (org-global-tags-completion-table))))))
14489 (setq match
14490 (completing-read
14491 "Match: "
14492 'org-tags-completion-function nil nil nil 'org-tags-history))))
14494 (let ((match0 match)
14495 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14496 (start 0)
14497 tagsmatch todomatch tagsmatcher todomatcher)
14499 ;; Expand group tags.
14500 (setq match (org-tags-expand match))
14502 ;; Check if there is a TODO part of this match, which would be the
14503 ;; part after a "/". To make sure that this slash is not part of
14504 ;; a property value to be matched against, we also check that
14505 ;; there is no / after that slash. First, find the last slash.
14506 (let ((s 0))
14507 (while (string-match "/+" match s)
14508 (setq start (match-beginning 0))
14509 (setq s (match-end 0))))
14510 (if (and (string-match "/+" match start)
14511 (not (string-match-p "\"" match start)))
14512 ;; Match contains also a TODO-matching request.
14513 (progn
14514 (setq tagsmatch (substring match 0 (match-beginning 0)))
14515 (setq todomatch (substring match (match-end 0)))
14516 (when (string-prefix-p "!" todomatch)
14517 (setq org--matcher-tags-todo-only t)
14518 (setq todomatch (substring todomatch 1)))
14519 (when (string-match "\\`\\s-*\\'" todomatch)
14520 (setq todomatch nil)))
14521 ;; Only matching tags.
14522 (setq tagsmatch match)
14523 (setq todomatch nil))
14525 ;; Make the tags matcher.
14526 (when (org-string-nw-p tagsmatch)
14527 (let ((orlist nil)
14528 (orterms (org-split-string tagsmatch "|"))
14529 term)
14530 (while (setq term (pop orterms))
14531 (while (and (equal (substring term -1) "\\") orterms)
14532 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14533 (while (string-match re term)
14534 (let* ((rest (substring term (match-end 0)))
14535 (minus (and (match-end 1)
14536 (equal (match-string 1 term) "-")))
14537 (tag (save-match-data
14538 (replace-regexp-in-string
14539 "\\\\-" "-" (match-string 2 term))))
14540 (regexp (eq (string-to-char tag) ?{))
14541 (levelp (match-end 4))
14542 (propp (match-end 5))
14544 (cond
14545 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14546 (levelp
14547 `(,(org-op-to-function (match-string 3 term))
14548 level
14549 ,(string-to-number (match-string 4 term))))
14550 (propp
14551 (let* ((gv (pcase (upcase (match-string 5 term))
14552 ("CATEGORY"
14553 '(get-text-property (point) 'org-category))
14554 ("TODO" 'todo)
14555 (p `(org-cached-entry-get nil ,p))))
14556 (pv (match-string 7 term))
14557 (regexp (eq (string-to-char pv) ?{))
14558 (strp (eq (string-to-char pv) ?\"))
14559 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14560 (po (org-op-to-function (match-string 6 term)
14561 (if timep 'time strp))))
14562 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14563 (when timep (setq pv (org-matcher-time pv)))
14564 (cond ((and regexp (eq po 'org<>))
14565 `(not (string-match ,pv (or ,gv ""))))
14566 (regexp `(string-match ,pv (or ,gv "")))
14567 (strp `(,po (or ,gv "") ,pv))
14569 `(,po
14570 (string-to-number (or ,gv ""))
14571 ,(string-to-number pv))))))
14572 (t `(member ,tag tags-list)))))
14573 (push (if minus `(not ,mm) mm) tagsmatcher)
14574 (setq term rest)))
14575 (push `(and ,@tagsmatcher) orlist)
14576 (setq tagsmatcher nil))
14577 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14579 ;; Make the TODO matcher.
14580 (when (org-string-nw-p todomatch)
14581 (let ((orlist nil))
14582 (dolist (term (org-split-string todomatch "|"))
14583 (while (string-match re term)
14584 (let* ((minus (and (match-end 1)
14585 (equal (match-string 1 term) "-")))
14586 (kwd (match-string 2 term))
14587 (regexp (eq (string-to-char kwd) ?{))
14588 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14589 `(equal todo ,kwd))))
14590 (push (if minus `(not ,mm) mm) todomatcher))
14591 (setq term (substring term (match-end 0))))
14592 (push (if (> (length todomatcher) 1)
14593 (cons 'and todomatcher)
14594 (car todomatcher))
14595 orlist)
14596 (setq todomatcher nil))
14597 (setq todomatcher (cons 'or orlist))))
14599 ;; Return the string and function of the matcher. If no
14600 ;; tags-specific or todo-specific matcher exists, match
14601 ;; everything.
14602 (let ((matcher (if (and tagsmatcher todomatcher)
14603 `(and ,tagsmatcher ,todomatcher)
14604 (or tagsmatcher todomatcher t))))
14605 (when org--matcher-tags-todo-only
14606 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14607 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14609 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14610 "Expand group tags in MATCH.
14612 This replaces every group tag in MATCH with a regexp tag search.
14613 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14614 will be replaced like this:
14616 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14617 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14618 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14620 Replacing by a regexp preserves the structure of the match.
14621 E.g., this expansion
14623 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14625 will match anything tagged with \"Lab\" and \"Home\", or tagged
14626 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14628 A group tag in MATCH can contain regular expressions of its own.
14629 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14630 will be replaced like this:
14632 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14634 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14635 assumed to be a single group tag, and the function will return
14636 the list of tags in this group.
14638 When DOWNCASE is non-nil, expand downcased TAGS."
14639 (if org-group-tags
14640 (let* ((case-fold-search t)
14641 (stable org-mode-syntax-table)
14642 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14643 (taggroups (if downcased
14644 (mapcar (lambda (tg) (mapcar #'downcase tg))
14645 taggroups)
14646 taggroups))
14647 (taggroups-keys (mapcar #'car taggroups))
14648 (return-match (if downcased (downcase match) match))
14649 (count 0)
14650 (work-already-expanded tags-already-expanded)
14651 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14652 ;; @ and _ are allowed as word-components in tags.
14653 (modify-syntax-entry ?@ "w" stable)
14654 (modify-syntax-entry ?_ "w" stable)
14655 ;; Temporarily replace regexp-expressions in the match-expression.
14656 (while (string-match "{.+?}" return-match)
14657 (cl-incf count)
14658 (push (match-string 0 return-match) regexps-in-match)
14659 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14660 (while (and taggroups-keys
14661 (with-syntax-table stable
14662 (string-match
14663 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14664 (regexp-opt taggroups-keys) "\\>\\)")
14665 return-match)))
14666 (let* ((dir (match-string 1 return-match))
14667 (tag (match-string 2 return-match))
14668 (tag (if downcased (downcase tag) tag)))
14669 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14670 (member tag work-already-expanded))
14671 (setq tags-in-group (assoc tag taggroups))
14672 (push tag work-already-expanded)
14673 ;; Recursively expand each tag in the group, if the tag hasn't
14674 ;; already been expanded. Restore the match-data after all recursive calls.
14675 (save-match-data
14676 (let (tags-expanded)
14677 (dolist (x (cdr tags-in-group))
14678 (if (and (member x taggroups-keys)
14679 (not (member x work-already-expanded)))
14680 (setq tags-expanded
14681 (delete-dups
14682 (append
14683 (org-tags-expand x t downcased
14684 work-already-expanded)
14685 tags-expanded)))
14686 (setq tags-expanded
14687 (append (list x) tags-expanded)))
14688 (setq work-already-expanded
14689 (delete-dups
14690 (append tags-expanded
14691 work-already-expanded))))
14692 (setq tags-in-group
14693 (delete-dups (cons (car tags-in-group)
14694 tags-expanded)))))
14695 ;; Filter tag-regexps from tags.
14696 (setq regexp-in-group-escaped
14697 (delq nil (mapcar (lambda (x)
14698 (if (stringp x)
14699 (and (equal "{" (substring x 0 1))
14700 (equal "}" (substring x -1))
14703 tags-in-group))
14704 regexp-in-group
14705 (mapcar (lambda (x)
14706 (substring x 1 -1))
14707 regexp-in-group-escaped)
14708 tags-in-group
14709 (delq nil (mapcar (lambda (x)
14710 (if (stringp x)
14711 (and (not (equal "{" (substring x 0 1)))
14712 (not (equal "}" (substring x -1)))
14715 tags-in-group)))
14716 ;; If single-as-list, do no more in the while-loop.
14717 (if (not single-as-list)
14718 (progn
14719 (when regexp-in-group
14720 (setq regexp-in-group
14721 (concat "\\|"
14722 (mapconcat 'identity regexp-in-group
14723 "\\|"))))
14724 (setq tags-in-group
14725 (concat dir
14726 "{\\<"
14727 (regexp-opt tags-in-group)
14728 "\\>"
14729 regexp-in-group
14730 "}"))
14731 (when (stringp tags-in-group)
14732 (org-add-props tags-in-group '(grouptag t)))
14733 (setq return-match
14734 (replace-match tags-in-group t t return-match)))
14735 (setq tags-in-group
14736 (append regexp-in-group-escaped tags-in-group))))
14737 (setq taggroups-keys (delete tag taggroups-keys))))
14738 ;; Add the regular expressions back into the match-expression again.
14739 (while regexps-in-match
14740 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14741 (pop regexps-in-match)
14742 return-match t t))
14743 (cl-decf count))
14744 (if single-as-list
14745 (if tags-in-group tags-in-group (list return-match))
14746 return-match))
14747 (if single-as-list
14748 (list (if downcased (downcase match) match))
14749 match)))
14751 (defun org-op-to-function (op &optional stringp)
14752 "Turn an operator into the appropriate function."
14753 (setq op
14754 (cond
14755 ((equal op "<" ) '(< string< org-time<))
14756 ((equal op ">" ) '(> org-string> org-time>))
14757 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14758 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14759 ((member op '("=" "==")) '(= string= org-time=))
14760 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14761 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14763 (defun org<> (a b) (not (= a b)))
14764 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14765 (defun org-string>= (a b) (not (string< a b)))
14766 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14767 (defun org-string<> (a b) (not (string= a b)))
14768 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14769 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14770 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14771 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14772 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14773 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14774 (defun org-2ft (s)
14775 "Convert S to a floating point time.
14776 If S is already a number, just return it. If it is a string, parse
14777 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14778 (cond
14779 ((numberp s) s)
14780 ((stringp s)
14781 (condition-case nil
14782 (float-time (apply #'encode-time (org-parse-time-string s nil t)))
14783 (error 0.)))
14784 (t 0.)))
14786 (defun org-time-today ()
14787 "Time in seconds today at 0:00.
14788 Returns the float number of seconds since the beginning of the
14789 epoch to the beginning of today (00:00)."
14790 (float-time (apply 'encode-time
14791 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14793 (defun org-matcher-time (s)
14794 "Interpret a time comparison value."
14795 (save-match-data
14796 (cond
14797 ((string= s "<now>") (float-time))
14798 ((string= s "<today>") (org-time-today))
14799 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14800 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14801 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14802 (+ (org-time-today)
14803 (* (string-to-number (match-string 1 s))
14804 (cdr (assoc (match-string 2 s)
14805 '(("d" . 86400.0) ("w" . 604800.0)
14806 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14807 (t (org-2ft s)))))
14809 (defun org-match-any-p (re list)
14810 "Does re match any element of list?"
14811 (setq list (mapcar (lambda (x) (string-match re x)) list))
14812 (delq nil list))
14814 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14815 (defvar org-tags-overlay (make-overlay 1 1))
14816 (delete-overlay org-tags-overlay)
14818 (defun org-get-local-tags-at (&optional pos)
14819 "Get a list of tags defined in the current headline."
14820 (org-get-tags-at pos 'local))
14822 (defun org-get-local-tags ()
14823 "Get a list of tags defined in the current headline."
14824 (org-get-tags-at nil 'local))
14826 (defun org-get-tags-at (&optional pos local)
14827 "Get a list of all headline tags applicable at POS.
14828 POS defaults to point. If tags are inherited, the list contains
14829 the targets in the same sequence as the headlines appear, i.e.
14830 the tags of the current headline come last.
14831 When LOCAL is non-nil, only return tags from the current headline,
14832 ignore inherited ones."
14833 (interactive)
14834 (if (and org-trust-scanner-tags
14835 (or (not pos) (equal pos (point)))
14836 (not local))
14837 org-scanner-tags
14838 (let (tags ltags lastpos parent)
14839 (save-excursion
14840 (save-restriction
14841 (widen)
14842 (goto-char (or pos (point)))
14843 (save-match-data
14844 (catch 'done
14845 (condition-case nil
14846 (progn
14847 (org-back-to-heading t)
14848 (while (not (equal lastpos (point)))
14849 (setq lastpos (point))
14850 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14851 (setq ltags (org-split-string
14852 (match-string-no-properties 1) ":"))
14853 (when parent
14854 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14855 (setq tags (append
14856 (if parent
14857 (org-remove-uninherited-tags ltags)
14858 ltags)
14859 tags)))
14860 (or org-use-tag-inheritance (throw 'done t))
14861 (when local (throw 'done t))
14862 (or (org-up-heading-safe) (error nil))
14863 (setq parent t)))
14864 (error nil)))))
14865 (if local
14866 tags
14867 (reverse (delete-dups
14868 (reverse (append
14869 (org-remove-uninherited-tags
14870 org-file-tags)
14871 tags)))))))))
14873 (defun org-add-prop-inherited (s)
14874 (add-text-properties 0 (length s) '(inherited t) s)
14877 (defun org-toggle-tag (tag &optional onoff)
14878 "Toggle the tag TAG for the current line.
14879 If ONOFF is `on' or `off', don't toggle but set to this state."
14880 (let (res current)
14881 (save-excursion
14882 (org-back-to-heading t)
14883 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14884 (point-at-eol) t)
14885 (progn
14886 (setq current (match-string 1))
14887 (replace-match ""))
14888 (setq current ""))
14889 (setq current (nreverse (org-split-string current ":")))
14890 (cond
14891 ((eq onoff 'on)
14892 (setq res t)
14893 (or (member tag current) (push tag current)))
14894 ((eq onoff 'off)
14895 (or (not (member tag current)) (setq current (delete tag current))))
14896 (t (if (member tag current)
14897 (setq current (delete tag current))
14898 (setq res t)
14899 (push tag current))))
14900 (end-of-line 1)
14901 (if current
14902 (progn
14903 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14904 (org-set-tags nil t))
14905 (delete-horizontal-space))
14906 (run-hooks 'org-after-tags-change-hook))
14907 res))
14909 (defun org--align-tags-here (to-col)
14910 "Align tags on the current headline to TO-COL.
14911 Assume point is on a headline."
14912 (let ((pos (point)))
14913 (beginning-of-line)
14914 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14915 (>= pos (match-beginning 2)))
14916 ;; No tags or point within tags: do not align.
14917 (goto-char pos)
14918 (goto-char (match-beginning 1))
14919 (let ((shift (max (- (if (>= to-col 0) to-col
14920 (- (abs to-col) (string-width (match-string 2))))
14921 (current-column))
14922 1)))
14923 (replace-match (make-string shift ?\s) nil nil nil 1)
14924 ;; Preserve initial position, if possible. In any case, stop
14925 ;; before tags.
14926 (when (< pos (point)) (goto-char pos))))))
14928 (defun org-set-tags-command (&optional arg just-align)
14929 "Call the set-tags command for the current entry."
14930 (interactive "P")
14931 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14932 (org-set-tags arg just-align)
14933 (save-excursion
14934 (unless (and (org-region-active-p)
14935 org-loop-over-headlines-in-active-region)
14936 (org-back-to-heading t))
14937 (org-set-tags arg just-align))))
14939 (defun org-set-tags-to (data)
14940 "Set the tags of the current entry to DATA, replacing the current tags.
14941 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14942 If DATA is nil or the empty string, any tags will be removed."
14943 (interactive "sTags: ")
14944 (setq data
14945 (cond
14946 ((eq data nil) "")
14947 ((equal data "") "")
14948 ((stringp data)
14949 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14950 ":"))
14951 ((listp data)
14952 (concat ":" (mapconcat 'identity data ":") ":"))))
14953 (when data
14954 (save-excursion
14955 (org-back-to-heading t)
14956 (when (let ((case-fold-search nil))
14957 (looking-at org-complex-heading-regexp))
14958 (if (match-end 5)
14959 (progn
14960 (goto-char (match-beginning 5))
14961 (insert data)
14962 (delete-region (point) (point-at-eol))
14963 (org-set-tags nil 'align))
14964 (goto-char (point-at-eol))
14965 (insert " " data)
14966 (org-set-tags nil 'align)))
14967 (beginning-of-line 1)
14968 (when (looking-at ".*?\\([ \t]+\\)$")
14969 (delete-region (match-beginning 1) (match-end 1))))))
14971 (defun org-align-all-tags ()
14972 "Align the tags in all headings."
14973 (interactive)
14974 (save-excursion
14975 (or (ignore-errors (org-back-to-heading t))
14976 (outline-next-heading))
14977 (if (org-at-heading-p)
14978 (org-set-tags t)
14979 (message "No headings"))))
14981 (defvar org-indent-indentation-per-level)
14982 (defun org-set-tags (&optional arg just-align)
14983 "Set the tags for the current headline.
14984 With prefix ARG, realign all tags in headings in the current buffer.
14985 When JUST-ALIGN is non-nil, only align tags."
14986 (interactive "P")
14987 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14988 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14989 'region-start-level
14990 'region))
14991 org-loop-over-headlines-in-active-region)
14992 (org-map-entries
14993 ;; We don't use ARG and JUST-ALIGN here because these args
14994 ;; are not useful when looping over headlines.
14995 #'org-set-tags
14996 org-loop-over-headlines-in-active-region
14998 '(when (org-invisible-p) (org-end-of-subtree nil t))))
14999 (let ((org-setting-tags t))
15000 (if arg
15001 (save-excursion
15002 (goto-char (point-min))
15003 (while (re-search-forward org-outline-regexp-bol nil t)
15004 (org-set-tags nil t)
15005 (end-of-line))
15006 (message "All tags realigned to column %d" org-tags-column))
15007 (let* ((current (org-get-tags-string))
15008 (tags
15009 (if just-align current
15010 ;; Get a new set of tags from the user.
15011 (save-excursion
15012 (let* ((seen)
15013 (table
15014 (setq
15015 org-last-tags-completion-table
15016 ;; Uniquify tags in alists, yet preserve
15017 ;; structure (i.e., keywords).
15018 (delq nil
15019 (mapcar
15020 (lambda (pair)
15021 (let ((head (car pair)))
15022 (cond ((symbolp head) pair)
15023 ((member head seen) nil)
15024 (t (push head seen)
15025 pair))))
15026 (append
15027 (or org-current-tag-alist
15028 (org-get-buffer-tags))
15029 (and
15030 org-complete-tags-always-offer-all-agenda-tags
15031 (org-global-tags-completion-table
15032 (org-agenda-files))))))))
15033 (current-tags (org-split-string current ":"))
15034 (inherited-tags
15035 (nreverse (nthcdr (length current-tags)
15036 (nreverse (org-get-tags-at))))))
15037 (replace-regexp-in-string
15038 "\\([-+&]+\\|,\\)"
15040 (if (or (eq t org-use-fast-tag-selection)
15041 (and org-use-fast-tag-selection
15042 (delq nil (mapcar #'cdr table))))
15043 (org-fast-tag-selection
15044 current-tags inherited-tags table
15045 (and org-fast-tag-selection-include-todo
15046 org-todo-key-alist))
15047 (let ((org-add-colon-after-tag-completion
15048 (< 1 (length table))))
15049 (org-trim
15050 (completing-read
15051 "Tags: "
15052 #'org-tags-completion-function
15053 nil nil current 'org-tags-history))))))))))
15055 (when org-tags-sort-function
15056 (setq tags
15057 (mapconcat
15058 #'identity
15059 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15060 org-tags-sort-function)
15061 ":")))
15063 (if (or (string= ":" tags)
15064 (string= "::" tags))
15065 (setq tags ""))
15066 (if (not (org-string-nw-p tags)) (setq tags "")
15067 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
15068 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
15070 ;; Insert new tags at the correct column.
15071 (unless (equal current tags)
15072 (save-excursion
15073 (beginning-of-line)
15074 (let ((case-fold-search nil))
15075 (looking-at org-complex-heading-regexp))
15076 ;; Remove current tags, if any.
15077 (when (match-end 5) (replace-match "" nil nil nil 5))
15078 ;; Insert new tags, if any. Otherwise, remove trailing
15079 ;; white spaces.
15080 (end-of-line)
15081 (if (not (equal tags ""))
15082 ;; When text is being inserted on an invisible
15083 ;; region boundary, it can be inadvertently sucked
15084 ;; into invisibility.
15085 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
15086 (skip-chars-backward " \t")
15087 (delete-region (point) (line-end-position)))))
15088 ;; Align tags, if any. Fix tags column if `org-indent-mode'
15089 ;; is on.
15090 (unless (equal tags "")
15091 (let* ((level (save-excursion
15092 (beginning-of-line)
15093 (skip-chars-forward "\\*")))
15094 (offset (if (bound-and-true-p org-indent-mode)
15095 (* (1- org-indent-indentation-per-level)
15096 (1- level))
15098 (tags-column
15099 (+ org-tags-column
15100 (if (> org-tags-column 0) (- offset) offset))))
15101 (org--align-tags-here tags-column))))
15102 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15104 (defun org-change-tag-in-region (beg end tag off)
15105 "Add or remove TAG for each entry in the region.
15106 This works in the agenda, and also in an Org buffer."
15107 (interactive
15108 (list (region-beginning) (region-end)
15109 (let ((org-last-tags-completion-table
15110 (if (derived-mode-p 'org-mode)
15111 (org-uniquify
15112 (delq nil (append (org-get-buffer-tags)
15113 (org-global-tags-completion-table))))
15114 (org-global-tags-completion-table))))
15115 (completing-read
15116 "Tag: " 'org-tags-completion-function nil nil nil
15117 'org-tags-history))
15118 (progn
15119 (message "[s]et or [r]emove? ")
15120 (equal (read-char-exclusive) ?r))))
15121 (when (fboundp 'deactivate-mark) (deactivate-mark))
15122 (let ((agendap (equal major-mode 'org-agenda-mode))
15123 l1 l2 m buf pos newhead (cnt 0))
15124 (goto-char end)
15125 (setq l2 (1- (org-current-line)))
15126 (goto-char beg)
15127 (setq l1 (org-current-line))
15128 (cl-loop for l from l1 to l2 do
15129 (org-goto-line l)
15130 (setq m (get-text-property (point) 'org-hd-marker))
15131 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15132 (and agendap m))
15133 (setq buf (if agendap (marker-buffer m) (current-buffer))
15134 pos (if agendap m (point)))
15135 (with-current-buffer buf
15136 (save-excursion
15137 (save-restriction
15138 (goto-char pos)
15139 (setq cnt (1+ cnt))
15140 (org-toggle-tag tag (if off 'off 'on))
15141 (setq newhead (org-get-heading)))))
15142 (and agendap (org-agenda-change-all-lines newhead m))))
15143 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15145 (defun org-tags-completion-function (string _predicate &optional flag)
15146 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15147 (confirm (lambda (x) (stringp (car x)))))
15148 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15149 (setq s1 (match-string 1 string)
15150 s2 (match-string 2 string))
15151 (setq s1 "" s2 string))
15152 (cond
15153 ((eq flag nil)
15154 ;; try completion
15155 (setq rtn (try-completion s2 ctable confirm))
15156 (when (stringp rtn)
15157 (setq rtn
15158 (concat s1 s2 (substring rtn (length s2))
15159 (if (and org-add-colon-after-tag-completion
15160 (assoc rtn ctable))
15161 ":" ""))))
15162 rtn)
15163 ((eq flag t)
15164 ;; all-completions
15165 (all-completions s2 ctable confirm))
15166 ((eq flag 'lambda)
15167 ;; exact match?
15168 (assoc s2 ctable)))))
15170 (defun org-fast-tag-insert (kwd tags face &optional end)
15171 "Insert KDW, and the TAGS, the latter with face FACE.
15172 Also insert END."
15173 (insert (format "%-12s" (concat kwd ":"))
15174 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15175 (or end "")))
15177 (defun org-fast-tag-show-exit (flag)
15178 (save-excursion
15179 (org-goto-line 3)
15180 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15181 (replace-match ""))
15182 (when flag
15183 (end-of-line 1)
15184 (org-move-to-column (- (window-width) 19) t)
15185 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15187 (defun org-set-current-tags-overlay (current prefix)
15188 "Add an overlay to CURRENT tag with PREFIX."
15189 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15190 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15191 (org-overlay-display org-tags-overlay (concat prefix s))))
15193 (defvar org-last-tag-selection-key nil)
15194 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15195 "Fast tag selection with single keys.
15196 CURRENT is the current list of tags in the headline, INHERITED is the
15197 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15198 possibly with grouping information. TODO-TABLE is a similar table with
15199 TODO keywords, should these have keys assigned to them.
15200 If the keys are nil, a-z are automatically assigned.
15201 Returns the new tags string, or nil to not change the current settings."
15202 (let* ((fulltable (append table todo-table))
15203 (maxlen (apply 'max (mapcar
15204 (lambda (x)
15205 (if (stringp (car x)) (string-width (car x)) 0))
15206 fulltable)))
15207 (buf (current-buffer))
15208 (expert (eq org-fast-tag-selection-single-key 'expert))
15209 (buffer-tags nil)
15210 (fwidth (+ maxlen 3 1 3))
15211 (ncol (/ (- (window-width) 4) fwidth))
15212 (i-face 'org-done)
15213 (c-face 'org-todo)
15214 tg cnt e c char c1 c2 ntable tbl rtn
15215 ov-start ov-end ov-prefix
15216 (exit-after-next org-fast-tag-selection-single-key)
15217 (done-keywords org-done-keywords)
15218 groups ingroup intaggroup)
15219 (save-excursion
15220 (beginning-of-line 1)
15221 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15222 (setq ov-start (match-beginning 1)
15223 ov-end (match-end 1)
15224 ov-prefix "")
15225 (setq ov-start (1- (point-at-eol))
15226 ov-end (1+ ov-start))
15227 (skip-chars-forward "^\n\r")
15228 (setq ov-prefix
15229 (concat
15230 (buffer-substring (1- (point)) (point))
15231 (if (> (current-column) org-tags-column)
15233 (make-string (- org-tags-column (current-column)) ?\ ))))))
15234 (move-overlay org-tags-overlay ov-start ov-end)
15235 (save-window-excursion
15236 (if expert
15237 (set-buffer (get-buffer-create " *Org tags*"))
15238 (delete-other-windows)
15239 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15240 (org-switch-to-buffer-other-window " *Org tags*"))
15241 (erase-buffer)
15242 (setq-local org-done-keywords done-keywords)
15243 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15244 (org-fast-tag-insert "Current" current c-face "\n\n")
15245 (org-fast-tag-show-exit exit-after-next)
15246 (org-set-current-tags-overlay current ov-prefix)
15247 (setq tbl fulltable char ?a cnt 0)
15248 (while (setq e (pop tbl))
15249 (cond
15250 ((eq (car e) :startgroup)
15251 (push '() groups) (setq ingroup t)
15252 (unless (zerop cnt)
15253 (setq cnt 0)
15254 (insert "\n"))
15255 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15256 ((eq (car e) :endgroup)
15257 (setq ingroup nil cnt 0)
15258 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15259 ((eq (car e) :startgrouptag)
15260 (setq intaggroup t)
15261 (unless (zerop cnt)
15262 (setq cnt 0)
15263 (insert "\n"))
15264 (insert "[ "))
15265 ((eq (car e) :endgrouptag)
15266 (setq intaggroup nil cnt 0)
15267 (insert "]\n"))
15268 ((equal e '(:newline))
15269 (unless (zerop cnt)
15270 (setq cnt 0)
15271 (insert "\n")
15272 (setq e (car tbl))
15273 (while (equal (car tbl) '(:newline))
15274 (insert "\n")
15275 (setq tbl (cdr tbl)))))
15276 ((equal e '(:grouptags)) (insert " : "))
15278 (setq tg (copy-sequence (car e)) c2 nil)
15279 (if (cdr e)
15280 (setq c (cdr e))
15281 ;; automatically assign a character.
15282 (setq c1 (string-to-char
15283 (downcase (substring
15284 tg (if (= (string-to-char tg) ?@) 1 0)))))
15285 (if (or (rassoc c1 ntable) (rassoc c1 table))
15286 (while (or (rassoc char ntable) (rassoc char table))
15287 (setq char (1+ char)))
15288 (setq c2 c1))
15289 (setq c (or c2 char)))
15290 (when ingroup (push tg (car groups)))
15291 (setq tg (org-add-props tg nil 'face
15292 (cond
15293 ((not (assoc tg table))
15294 (org-get-todo-face tg))
15295 ((member tg current) c-face)
15296 ((member tg inherited) i-face))))
15297 (when (equal (caar tbl) :grouptags)
15298 (org-add-props tg nil 'face 'org-tag-group))
15299 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15300 (insert "[" c "] " tg (make-string
15301 (- fwidth 4 (length tg)) ?\ ))
15302 (push (cons tg c) ntable)
15303 (when (= (cl-incf cnt) ncol)
15304 (insert "\n")
15305 (when (or ingroup intaggroup) (insert " "))
15306 (setq cnt 0)))))
15307 (setq ntable (nreverse ntable))
15308 (insert "\n")
15309 (goto-char (point-min))
15310 (unless expert (org-fit-window-to-buffer))
15311 (setq rtn
15312 (catch 'exit
15313 (while t
15314 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15315 (if (not groups) "no " "")
15316 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15317 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15318 (setq org-last-tag-selection-key c)
15319 (cond
15320 ((= c ?\r) (throw 'exit t))
15321 ((= c ?!)
15322 (setq groups (not groups))
15323 (goto-char (point-min))
15324 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15325 ((= c ?\C-c)
15326 (if (not expert)
15327 (org-fast-tag-show-exit
15328 (setq exit-after-next (not exit-after-next)))
15329 (setq expert nil)
15330 (delete-other-windows)
15331 (set-window-buffer (split-window-vertically) " *Org tags*")
15332 (org-switch-to-buffer-other-window " *Org tags*")
15333 (org-fit-window-to-buffer)))
15334 ((or (= c ?\C-g)
15335 (and (= c ?q) (not (rassoc c ntable))))
15336 (delete-overlay org-tags-overlay)
15337 (setq quit-flag t))
15338 ((= c ?\ )
15339 (setq current nil)
15340 (when exit-after-next (setq exit-after-next 'now)))
15341 ((= c ?\t)
15342 (condition-case nil
15343 (setq tg (completing-read
15344 "Tag: "
15345 (or buffer-tags
15346 (with-current-buffer buf
15347 (setq buffer-tags
15348 (org-get-buffer-tags))))))
15349 (quit (setq tg "")))
15350 (when (string-match "\\S-" tg)
15351 (cl-pushnew (list tg) buffer-tags :test #'equal)
15352 (if (member tg current)
15353 (setq current (delete tg current))
15354 (push tg current)))
15355 (when exit-after-next (setq exit-after-next 'now)))
15356 ((setq e (rassoc c todo-table) tg (car e))
15357 (with-current-buffer buf
15358 (save-excursion (org-todo tg)))
15359 (when exit-after-next (setq exit-after-next 'now)))
15360 ((setq e (rassoc c ntable) tg (car e))
15361 (if (member tg current)
15362 (setq current (delete tg current))
15363 (cl-loop for g in groups do
15364 (when (member tg g)
15365 (dolist (x g) (setq current (delete x current)))))
15366 (push tg current))
15367 (when exit-after-next (setq exit-after-next 'now))))
15369 ;; Create a sorted list
15370 (setq current
15371 (sort current
15372 (lambda (a b)
15373 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15374 (when (eq exit-after-next 'now) (throw 'exit t))
15375 (goto-char (point-min))
15376 (beginning-of-line 2)
15377 (delete-region (point) (point-at-eol))
15378 (org-fast-tag-insert "Current" current c-face)
15379 (org-set-current-tags-overlay current ov-prefix)
15380 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15381 (setq tg (match-string 1))
15382 (add-text-properties
15383 (match-beginning 1) (match-end 1)
15384 (list 'face
15385 (cond
15386 ((member tg current) c-face)
15387 ((member tg inherited) i-face)
15388 (t (get-text-property (match-beginning 1) 'face))))))
15389 (goto-char (point-min)))))
15390 (delete-overlay org-tags-overlay)
15391 (if rtn
15392 (mapconcat 'identity current ":")
15393 nil))))
15395 (defun org-get-tags-string ()
15396 "Get the TAGS string in the current headline."
15397 (unless (org-at-heading-p t)
15398 (user-error "Not on a heading"))
15399 (save-excursion
15400 (beginning-of-line 1)
15401 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15402 (match-string-no-properties 1)
15403 "")))
15405 (defun org-get-tags ()
15406 "Get the list of tags specified in the current headline."
15407 (org-split-string (org-get-tags-string) ":"))
15409 (defun org-get-buffer-tags ()
15410 "Get a table of all tags used in the buffer, for completion."
15411 (org-with-wide-buffer
15412 (goto-char (point-min))
15413 (let ((tag-re (concat org-outline-regexp-bol
15414 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15415 tags)
15416 (while (re-search-forward tag-re nil t)
15417 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15418 (push tag tags)))
15419 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15421 ;;;; The mapping API
15423 (defvar org-agenda-skip-comment-trees)
15424 (defvar org-agenda-skip-function)
15425 (defun org-map-entries (func &optional match scope &rest skip)
15426 "Call FUNC at each headline selected by MATCH in SCOPE.
15428 FUNC is a function or a lisp form. The function will be called without
15429 arguments, with the cursor positioned at the beginning of the headline.
15430 The return values of all calls to the function will be collected and
15431 returned as a list.
15433 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15434 does not need to preserve point. After evaluation, the cursor will be
15435 moved to the end of the line (presumably of the headline of the
15436 processed entry) and search continues from there. Under some
15437 circumstances, this may not produce the wanted results. For example,
15438 if you have removed (e.g. archived) the current (sub)tree it could
15439 mean that the next entry will be skipped entirely. In such cases, you
15440 can specify the position from where search should continue by making
15441 FUNC set the variable `org-map-continue-from' to the desired buffer
15442 position.
15444 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15445 Only headlines that are matched by this query will be considered during
15446 the iteration. When MATCH is nil or t, all headlines will be
15447 visited by the iteration.
15449 SCOPE determines the scope of this command. It can be any of:
15451 nil The current buffer, respecting the restriction if any
15452 tree The subtree started with the entry at point
15453 region The entries within the active region, if any
15454 region-start-level
15455 The entries within the active region, but only those at
15456 the same level than the first one.
15457 file The current buffer, without restriction
15458 file-with-archives
15459 The current buffer, and any archives associated with it
15460 agenda All agenda files
15461 agenda-with-archives
15462 All agenda files with any archive files associated with them
15463 \(file1 file2 ...)
15464 If this is a list, all files in the list will be scanned
15466 The remaining args are treated as settings for the skipping facilities of
15467 the scanner. The following items can be given here:
15469 archive skip trees with the archive tag
15470 comment skip trees with the COMMENT keyword
15471 function or Emacs Lisp form:
15472 will be used as value for `org-agenda-skip-function', so
15473 whenever the function returns a position, FUNC will not be
15474 called for that entry and search will continue from the
15475 position returned
15477 If your function needs to retrieve the tags including inherited tags
15478 at the *current* entry, you can use the value of the variable
15479 `org-scanner-tags' which will be much faster than getting the value
15480 with `org-get-tags-at'. If your function gets properties with
15481 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15482 to t around the call to `org-entry-properties' to get the same speedup.
15483 Note that if your function moves around to retrieve tags and properties at
15484 a *different* entry, you cannot use these techniques."
15485 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15486 (not (org-region-active-p)))
15487 (let* ((org-agenda-archives-mode nil) ; just to make sure
15488 (org-agenda-skip-archived-trees (memq 'archive skip))
15489 (org-agenda-skip-comment-trees (memq 'comment skip))
15490 (org-agenda-skip-function
15491 (car (org-delete-all '(comment archive) skip)))
15492 (org-tags-match-list-sublevels t)
15493 (start-level (eq scope 'region-start-level))
15494 matcher res
15495 org-todo-keywords-for-agenda
15496 org-done-keywords-for-agenda
15497 org-todo-keyword-alist-for-agenda
15498 org-tag-alist-for-agenda
15499 org--matcher-tags-todo-only)
15501 (cond
15502 ((eq match t) (setq matcher t))
15503 ((eq match nil) (setq matcher t))
15504 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15506 (save-excursion
15507 (save-restriction
15508 (cond ((eq scope 'tree)
15509 (org-back-to-heading t)
15510 (org-narrow-to-subtree)
15511 (setq scope nil))
15512 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15513 (org-region-active-p))
15514 ;; If needed, set start-level to a string like "2"
15515 (when start-level
15516 (save-excursion
15517 (goto-char (region-beginning))
15518 (unless (org-at-heading-p) (outline-next-heading))
15519 (setq start-level (org-current-level))))
15520 (narrow-to-region (region-beginning)
15521 (save-excursion
15522 (goto-char (region-end))
15523 (unless (and (bolp) (org-at-heading-p))
15524 (outline-next-heading))
15525 (point)))
15526 (setq scope nil)))
15528 (if (not scope)
15529 (progn
15530 (org-agenda-prepare-buffers
15531 (and buffer-file-name (list buffer-file-name)))
15532 (setq res
15533 (org-scan-tags
15534 func matcher org--matcher-tags-todo-only start-level)))
15535 ;; Get the right scope
15536 (cond
15537 ((and scope (listp scope) (symbolp (car scope)))
15538 (setq scope (eval scope)))
15539 ((eq scope 'agenda)
15540 (setq scope (org-agenda-files t)))
15541 ((eq scope 'agenda-with-archives)
15542 (setq scope (org-agenda-files t))
15543 (setq scope (org-add-archive-files scope)))
15544 ((eq scope 'file)
15545 (setq scope (and buffer-file-name (list buffer-file-name))))
15546 ((eq scope 'file-with-archives)
15547 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15548 (org-agenda-prepare-buffers scope)
15549 (dolist (file scope)
15550 (with-current-buffer (org-find-base-buffer-visiting file)
15551 (org-with-wide-buffer
15552 (goto-char (point-min))
15553 (setq res
15554 (append
15556 (org-scan-tags
15557 func matcher org--matcher-tags-todo-only)))))))))
15558 res)))
15560 ;;; Properties API
15562 (defconst org-special-properties
15563 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15564 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15565 "The special properties valid in Org mode.
15566 These are properties that are not defined in the property drawer,
15567 but in some other way.")
15569 (defconst org-default-properties
15570 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15571 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15572 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15573 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15574 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15575 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15576 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15577 "Some properties that are used by Org mode for various purposes.
15578 Being in this list makes sure that they are offered for completion.")
15580 (defun org--valid-property-p (property)
15581 "Non nil when string PROPERTY is a valid property name."
15582 (not
15583 (or (equal property "")
15584 (string-match-p "\\s-" property))))
15586 (defun org--update-property-plist (key val props)
15587 "Associate KEY to VAL in alist PROPS.
15588 Modifications are made by side-effect. Return new alist."
15589 (let* ((appending (string= (substring key -1) "+"))
15590 (key (if appending (substring key 0 -1) key))
15591 (old (assoc-string key props t)))
15592 (if (not old) (cons (cons key val) props)
15593 (setcdr old (if appending (concat (cdr old) " " val) val))
15594 props)))
15596 (defun org-get-property-block (&optional beg force)
15597 "Return the (beg . end) range of the body of the property drawer.
15598 BEG is the beginning of the current subtree, or of the part
15599 before the first headline. If it is not given, it will be found.
15600 If the drawer does not exist, create it if FORCE is non-nil, or
15601 return nil."
15602 (org-with-wide-buffer
15603 (when beg (goto-char beg))
15604 (unless (org-before-first-heading-p)
15605 (let ((beg (cond (beg)
15606 ((or (not (featurep 'org-inlinetask))
15607 (org-inlinetask-in-task-p))
15608 (org-back-to-heading t))
15609 (t (org-with-limited-levels (org-back-to-heading t))))))
15610 (forward-line)
15611 (when (looking-at-p org-planning-line-re) (forward-line))
15612 (cond ((looking-at org-property-drawer-re)
15613 (forward-line)
15614 (cons (point) (progn (goto-char (match-end 0))
15615 (line-beginning-position))))
15616 (force
15617 (goto-char beg)
15618 (org-insert-property-drawer)
15619 (let ((pos (save-excursion (search-forward ":END:")
15620 (line-beginning-position))))
15621 (cons pos pos))))))))
15623 (defun org-at-property-p ()
15624 "Non-nil when point is inside a property drawer.
15625 See `org-property-re' for match data, if applicable."
15626 (save-excursion
15627 (beginning-of-line)
15628 (and (looking-at org-property-re)
15629 (let ((property-drawer (save-match-data (org-get-property-block))))
15630 (and property-drawer
15631 (>= (point) (car property-drawer))
15632 (< (point) (cdr property-drawer)))))))
15634 (defun org-property-action ()
15635 "Do an action on properties."
15636 (interactive)
15637 (unless (org-at-property-p) (user-error "Not at a property"))
15638 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15639 (let ((c (read-char-exclusive)))
15640 (cl-case c
15641 (?s (call-interactively #'org-set-property))
15642 (?d (call-interactively #'org-delete-property))
15643 (?D (call-interactively #'org-delete-property-globally))
15644 (?c (call-interactively #'org-compute-property-at-point))
15645 (otherwise (user-error "No such property action %c" c)))))
15647 (defun org-inc-effort ()
15648 "Increment the value of the effort property in the current entry."
15649 (interactive)
15650 (org-set-effort nil t))
15652 (defvar org-clock-effort) ; Defined in org-clock.el.
15653 (defvar org-clock-current-task) ; Defined in org-clock.el.
15654 (defun org-set-effort (&optional value increment)
15655 "Set the effort property of the current entry.
15656 With numerical prefix arg, use the nth allowed value, 0 stands for the
15657 10th allowed value.
15659 When INCREMENT is non-nil, set the property to the next allowed value."
15660 (interactive "P")
15661 (when (equal value 0) (setq value 10))
15662 (let* ((completion-ignore-case t)
15663 (prop org-effort-property)
15664 (cur (org-entry-get nil prop))
15665 (allowed (org-property-get-allowed-values nil prop 'table))
15666 (existing (mapcar 'list (org-property-values prop)))
15667 (heading (nth 4 (org-heading-components)))
15669 (val (cond
15670 ((stringp value) value)
15671 ((and allowed (integerp value))
15672 (or (car (nth (1- value) allowed))
15673 (car (org-last allowed))))
15674 ((and allowed increment)
15675 (or (cl-caadr (member (list cur) allowed))
15676 (user-error "Allowed effort values are not set")))
15677 (allowed
15678 (message "Select 1-9,0, [RET%s]: %s"
15679 (if cur (concat "=" cur) "")
15680 (mapconcat 'car allowed " "))
15681 (setq rpl (read-char-exclusive))
15682 (if (equal rpl ?\r)
15684 (setq rpl (- rpl ?0))
15685 (when (equal rpl 0) (setq rpl 10))
15686 (if (and (> rpl 0) (<= rpl (length allowed)))
15687 (car (nth (1- rpl) allowed))
15688 (org-completing-read "Effort: " allowed nil))))
15690 (org-completing-read
15691 (concat "Effort" (and cur (string-match "\\S-" cur)
15692 (concat " [" cur "]"))
15693 ": ")
15694 existing nil nil "" nil cur)))))
15695 (unless (equal (org-entry-get nil prop) val)
15696 (org-entry-put nil prop val))
15697 (org-refresh-property
15698 '((effort . identity)
15699 (effort-minutes . org-duration-string-to-minutes))
15700 val)
15701 (when (equal heading (bound-and-true-p org-clock-current-task))
15702 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15703 (org-clock-update-mode-line))
15704 (message "%s is now %s" prop val)))
15706 (defun org-entry-properties (&optional pom which)
15707 "Get all properties of the current entry.
15709 When POM is a buffer position, get all properties from the entry
15710 there instead.
15712 This includes the TODO keyword, the tags, time strings for
15713 deadline, scheduled, and clocking, and any additional properties
15714 defined in the entry.
15716 If WHICH is nil or `all', get all properties. If WHICH is
15717 `special' or `standard', only get that subclass. If WHICH is
15718 a string, only get that property.
15720 Return value is an alist. Keys are properties, as upcased
15721 strings."
15722 (org-with-point-at pom
15723 (when (and (derived-mode-p 'org-mode)
15724 (ignore-errors (org-back-to-heading t)))
15725 (catch 'exit
15726 (let* ((beg (point))
15727 (specific (and (stringp which) (upcase which)))
15728 (which (cond ((not specific) which)
15729 ((member specific org-special-properties) 'special)
15730 (t 'standard)))
15731 props)
15732 ;; Get the special properties, like TODO and TAGS.
15733 (when (memq which '(nil all special))
15734 (when (or (not specific) (string= specific "CLOCKSUM"))
15735 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15736 (when clocksum
15737 (push (cons "CLOCKSUM"
15738 (org-minutes-to-clocksum-string clocksum))
15739 props)))
15740 (when specific (throw 'exit props)))
15741 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15742 (let ((clocksumt (get-text-property (point)
15743 :org-clock-minutes-today)))
15744 (when clocksumt
15745 (push (cons "CLOCKSUM_T"
15746 (org-minutes-to-clocksum-string clocksumt))
15747 props)))
15748 (when specific (throw 'exit props)))
15749 (when (or (not specific) (string= specific "ITEM"))
15750 (let ((case-fold-search nil))
15751 (when (looking-at org-complex-heading-regexp)
15752 (push (cons "ITEM"
15753 (let ((title (match-string-no-properties 4)))
15754 (if (org-string-nw-p title)
15755 (org-remove-tabs title)
15756 "")))
15757 props)))
15758 (when specific (throw 'exit props)))
15759 (when (or (not specific) (string= specific "TODO"))
15760 (let ((case-fold-search nil))
15761 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15762 (push (cons "TODO" (match-string-no-properties 2)) props)))
15763 (when specific (throw 'exit props)))
15764 (when (or (not specific) (string= specific "PRIORITY"))
15765 (push (cons "PRIORITY"
15766 (if (looking-at org-priority-regexp)
15767 (match-string-no-properties 2)
15768 (char-to-string org-default-priority)))
15769 props)
15770 (when specific (throw 'exit props)))
15771 (when (or (not specific) (string= specific "FILE"))
15772 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15773 props)
15774 (when specific (throw 'exit props)))
15775 (when (or (not specific) (string= specific "TAGS"))
15776 (let ((value (org-string-nw-p (org-get-tags-string))))
15777 (when value (push (cons "TAGS" value) props)))
15778 (when specific (throw 'exit props)))
15779 (when (or (not specific) (string= specific "ALLTAGS"))
15780 (let ((value (org-get-tags-at)))
15781 (when value
15782 (push (cons "ALLTAGS"
15783 (format ":%s:" (mapconcat #'identity value ":")))
15784 props)))
15785 (when specific (throw 'exit props)))
15786 (when (or (not specific) (string= specific "BLOCKED"))
15787 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15788 (when specific (throw 'exit props)))
15789 (when (or (not specific)
15790 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15791 (forward-line)
15792 (when (looking-at-p org-planning-line-re)
15793 (end-of-line)
15794 (let ((bol (line-beginning-position))
15795 ;; Backward compatibility: time keywords used to
15796 ;; be configurable (before 8.3). Make sure we
15797 ;; get the correct keyword.
15798 (key-assoc `(("CLOSED" . ,org-closed-string)
15799 ("DEADLINE" . ,org-deadline-string)
15800 ("SCHEDULED" . ,org-scheduled-string))))
15801 (dolist (pair (if specific (list (assoc specific key-assoc))
15802 key-assoc))
15803 (save-excursion
15804 (when (search-backward (cdr pair) bol t)
15805 (goto-char (match-end 0))
15806 (skip-chars-forward " \t")
15807 (and (looking-at org-ts-regexp-both)
15808 (push (cons (car pair)
15809 (match-string-no-properties 0))
15810 props)))))))
15811 (when specific (throw 'exit props)))
15812 (when (or (not specific)
15813 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15814 (let ((find-ts
15815 (lambda (end ts)
15816 ;; Fix next time-stamp before END. TS is the
15817 ;; list of time-stamps found so far.
15818 (let ((ts ts)
15819 (regexp (cond
15820 ((string= specific "TIMESTAMP")
15821 org-ts-regexp)
15822 ((string= specific "TIMESTAMP_IA")
15823 org-ts-regexp-inactive)
15824 ((assoc "TIMESTAMP_IA" ts)
15825 org-ts-regexp)
15826 ((assoc "TIMESTAMP" ts)
15827 org-ts-regexp-inactive)
15828 (t org-ts-regexp-both))))
15829 (catch 'next
15830 (while (re-search-forward regexp end t)
15831 (backward-char)
15832 (let ((object (org-element-context)))
15833 ;; Accept to match timestamps in node
15834 ;; properties, too.
15835 (when (memq (org-element-type object)
15836 '(node-property timestamp))
15837 (let ((type
15838 (org-element-property :type object)))
15839 (cond
15840 ((and (memq type '(active active-range))
15841 (not (equal specific "TIMESTAMP_IA")))
15842 (unless (assoc "TIMESTAMP" ts)
15843 (push (cons "TIMESTAMP"
15844 (org-element-property
15845 :raw-value object))
15847 (when specific (throw 'exit ts))))
15848 ((and (memq type '(inactive inactive-range))
15849 (not (string= specific "TIMESTAMP")))
15850 (unless (assoc "TIMESTAMP_IA" ts)
15851 (push (cons "TIMESTAMP_IA"
15852 (org-element-property
15853 :raw-value object))
15855 (when specific (throw 'exit ts))))))
15856 ;; Both timestamp types are found,
15857 ;; move to next part.
15858 (when (= (length ts) 2) (throw 'next ts)))))
15859 ts)))))
15860 (goto-char beg)
15861 ;; First look for timestamps within headline.
15862 (let ((ts (funcall find-ts (line-end-position) nil)))
15863 (if (= (length ts) 2) (setq props (nconc ts props))
15864 ;; Then find timestamps in the section, skipping
15865 ;; planning line.
15866 (let ((end (save-excursion (outline-next-heading))))
15867 (forward-line)
15868 (when (looking-at-p org-planning-line-re) (forward-line))
15869 (setq props (nconc (funcall find-ts end ts) props))))))))
15870 ;; Get the standard properties, like :PROP:.
15871 (when (memq which '(nil all standard))
15872 ;; If we are looking after a specific property, delegate
15873 ;; to `org-entry-get', which is faster. However, make an
15874 ;; exception for "CATEGORY", since it can be also set
15875 ;; through keywords (i.e. #+CATEGORY).
15876 (if (and specific (not (equal specific "CATEGORY")))
15877 (let ((value (org-entry-get beg specific nil t)))
15878 (throw 'exit (and value (list (cons specific value)))))
15879 (let ((range (org-get-property-block beg)))
15880 (when range
15881 (let ((end (cdr range)) seen-base)
15882 (goto-char (car range))
15883 ;; Unlike to `org--update-property-plist', we
15884 ;; handle the case where base values is found
15885 ;; after its extension. We also forbid standard
15886 ;; properties to be named as special properties.
15887 (while (re-search-forward org-property-re end t)
15888 (let* ((key (upcase (match-string-no-properties 2)))
15889 (extendp (string-match-p "\\+\\'" key))
15890 (key-base (if extendp (substring key 0 -1) key))
15891 (value (match-string-no-properties 3)))
15892 (cond
15893 ((member-ignore-case key-base org-special-properties))
15894 (extendp
15895 (setq props
15896 (org--update-property-plist key value props)))
15897 ((member key seen-base))
15898 (t (push key seen-base)
15899 (let ((p (assoc-string key props t)))
15900 (if p (setcdr p (concat value " " (cdr p)))
15901 (push (cons key value) props))))))))))))
15902 (unless (assoc "CATEGORY" props)
15903 (push (cons "CATEGORY" (org-get-category beg)) props)
15904 (when (string= specific "CATEGORY") (throw 'exit props)))
15905 ;; Return value.
15906 props)))))
15908 (defun org--property-local-values (property literal-nil)
15909 "Return value for PROPERTY in current entry.
15910 Value is a list whose car is the base value for PROPERTY and cdr
15911 a list of accumulated values. Return nil if neither is found in
15912 the entry. Also return nil when PROPERTY is set to \"nil\",
15913 unless LITERAL-NIL is non-nil."
15914 (let ((range (org-get-property-block)))
15915 (when range
15916 (goto-char (car range))
15917 (let* ((case-fold-search t)
15918 (end (cdr range))
15919 (value
15920 ;; Base value.
15921 (save-excursion
15922 (let ((v (and (re-search-forward
15923 (org-re-property property nil t) end t)
15924 (match-string-no-properties 3))))
15925 (list (if literal-nil v (org-not-nil v)))))))
15926 ;; Find additional values.
15927 (let* ((property+ (org-re-property (concat property "+") nil t)))
15928 (while (re-search-forward property+ end t)
15929 (push (match-string-no-properties 3) value)))
15930 ;; Return final values.
15931 (and (not (equal value '(nil))) (nreverse value))))))
15933 (defun org--property-global-value (property literal-nil)
15934 "Return value for PROPERTY in current buffer.
15935 Return value is a string. Return nil if property is not set
15936 globally. Also return nil when PROPERTY is set to \"nil\",
15937 unless LITERAL-NIL is non-nil."
15938 (let ((global
15939 (cdr (or (assoc-string property org-file-properties t)
15940 (assoc-string property org-global-properties t)
15941 (assoc-string property org-global-properties-fixed t)))))
15942 (if literal-nil global (org-not-nil global))))
15944 (defun org-entry-get (pom property &optional inherit literal-nil)
15945 "Get value of PROPERTY for entry or content at point-or-marker POM.
15947 If INHERIT is non-nil and the entry does not have the property,
15948 then also check higher levels of the hierarchy. If INHERIT is
15949 the symbol `selective', use inheritance only if the setting in
15950 `org-use-property-inheritance' selects PROPERTY for inheritance.
15952 If the property is present but empty, the return value is the
15953 empty string. If the property is not present at all, nil is
15954 returned. In any other case, return the value as a string.
15955 Search is case-insensitive.
15957 If LITERAL-NIL is set, return the string value \"nil\" as
15958 a string, do not interpret it as the list atom nil. This is used
15959 for inheritance when a \"nil\" value can supersede a non-nil
15960 value higher up the hierarchy."
15961 (org-with-point-at pom
15962 (cond
15963 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15964 ;; We need a special property. Use `org-entry-properties' to
15965 ;; retrieve it, but specify the wanted property.
15966 (cdr (assoc-string property (org-entry-properties nil property))))
15967 ((and inherit
15968 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15969 (org-entry-get-with-inheritance property literal-nil))
15971 (let* ((local (org--property-local-values property literal-nil))
15972 (value (and local (mapconcat #'identity (delq nil local) " "))))
15973 (if literal-nil value (org-not-nil value)))))))
15975 (defun org-property-or-variable-value (var &optional inherit)
15976 "Check if there is a property fixing the value of VAR.
15977 If yes, return this value. If not, return the current value of the variable."
15978 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15979 (if (and prop (stringp prop) (string-match "\\S-" prop))
15980 (read prop)
15981 (symbol-value var))))
15983 (defun org-entry-delete (pom property)
15984 "Delete PROPERTY from entry at point-or-marker POM.
15985 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15986 non-nil when a property was removed."
15987 (org-with-point-at pom
15988 (pcase (org-get-property-block)
15989 (`(,begin . ,origin)
15990 (let* ((end (copy-marker origin))
15991 (re (org-re-property
15992 (concat (regexp-quote property) "\\+?") t t)))
15993 (goto-char begin)
15994 (while (re-search-forward re end t)
15995 (delete-region (match-beginning 0) (line-beginning-position 2)))
15996 ;; If drawer is empty, remove it altogether.
15997 (when (= begin end)
15998 (delete-region (line-beginning-position 0)
15999 (line-beginning-position 2)))
16000 ;; Return non-nil if some property was removed.
16001 (prog1 (/= end origin) (set-marker end nil))))
16002 (_ nil))))
16004 ;; Multi-values properties are properties that contain multiple values
16005 ;; These values are assumed to be single words, separated by whitespace.
16006 (defun org-entry-add-to-multivalued-property (pom property value)
16007 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16008 (let* ((old (org-entry-get pom property))
16009 (values (and old (org-split-string old "[ \t]"))))
16010 (setq value (org-entry-protect-space value))
16011 (unless (member value values)
16012 (setq values (append values (list value)))
16013 (org-entry-put pom property
16014 (mapconcat 'identity values " ")))))
16016 (defun org-entry-remove-from-multivalued-property (pom property value)
16017 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16018 (let* ((old (org-entry-get pom property))
16019 (values (and old (org-split-string old "[ \t]"))))
16020 (setq value (org-entry-protect-space value))
16021 (when (member value values)
16022 (setq values (delete value values))
16023 (org-entry-put pom property
16024 (mapconcat 'identity values " ")))))
16026 (defun org-entry-member-in-multivalued-property (pom property value)
16027 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16028 (let* ((old (org-entry-get pom property))
16029 (values (and old (org-split-string old "[ \t]"))))
16030 (setq value (org-entry-protect-space value))
16031 (member value values)))
16033 (defun org-entry-get-multivalued-property (pom property)
16034 "Return a list of values in a multivalued property."
16035 (let* ((value (org-entry-get pom property))
16036 (values (and value (org-split-string value "[ \t]"))))
16037 (mapcar 'org-entry-restore-space values)))
16039 (defun org-entry-put-multivalued-property (pom property &rest values)
16040 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16041 VALUES should be a list of strings. Spaces will be protected."
16042 (org-entry-put pom property
16043 (mapconcat 'org-entry-protect-space values " "))
16044 (let* ((value (org-entry-get pom property))
16045 (values (and value (org-split-string value "[ \t]"))))
16046 (mapcar 'org-entry-restore-space values)))
16048 (defun org-entry-protect-space (s)
16049 "Protect spaces and newline in string S."
16050 (while (string-match " " s)
16051 (setq s (replace-match "%20" t t s)))
16052 (while (string-match "\n" s)
16053 (setq s (replace-match "%0A" t t s)))
16056 (defun org-entry-restore-space (s)
16057 "Restore spaces and newline in string S."
16058 (while (string-match "%20" s)
16059 (setq s (replace-match " " t t s)))
16060 (while (string-match "%0A" s)
16061 (setq s (replace-match "\n" t t s)))
16064 (defvar org-entry-property-inherited-from (make-marker)
16065 "Marker pointing to the entry from where a property was inherited.
16066 Each call to `org-entry-get-with-inheritance' will set this marker to the
16067 location of the entry where the inheritance search matched. If there was
16068 no match, the marker will point nowhere.
16069 Note that also `org-entry-get' calls this function, if the INHERIT flag
16070 is set.")
16072 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16073 "Get PROPERTY of entry or content at point, search higher levels if needed.
16074 The search will stop at the first ancestor which has the property defined.
16075 If the value found is \"nil\", return nil to show that the property
16076 should be considered as undefined (this is the meaning of nil here).
16077 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16078 (move-marker org-entry-property-inherited-from nil)
16079 (org-with-wide-buffer
16080 (let (value)
16081 (catch 'exit
16082 (while t
16083 (let ((v (org--property-local-values property literal-nil)))
16084 (when v
16085 (setq value
16086 (concat (mapconcat #'identity (delq nil v) " ")
16087 (and value " ")
16088 value)))
16089 (cond
16090 ((car v)
16091 (org-back-to-heading t)
16092 (move-marker org-entry-property-inherited-from (point))
16093 (throw 'exit nil))
16094 ((org-up-heading-safe))
16096 (let ((global (org--property-global-value property literal-nil)))
16097 (cond ((not global))
16098 (value (setq value (concat global " " value)))
16099 (t (setq value global))))
16100 (throw 'exit nil))))))
16101 (if literal-nil value (org-not-nil value)))))
16103 (defvar org-property-changed-functions nil
16104 "Hook called when the value of a property has changed.
16105 Each hook function should accept two arguments, the name of the property
16106 and the new value.")
16108 (defun org-entry-put (pom property value)
16109 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16111 If the value is nil, it is converted to the empty string. If it
16112 is not a string, an error is raised. Also raise an error on
16113 invalid property names.
16115 PROPERTY can be any regular property (see
16116 `org-special-properties'). It can also be \"TODO\",
16117 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16119 For the last two properties, VALUE may have any of the special
16120 values \"earlier\" and \"later\". The function then increases or
16121 decreases scheduled or deadline date by one day."
16122 (cond ((null value) (setq value ""))
16123 ((not (stringp value)) (error "Properties values should be strings"))
16124 ((not (org--valid-property-p property))
16125 (user-error "Invalid property name: \"%s\"" property)))
16126 (org-with-point-at pom
16127 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16128 (org-back-to-heading t)
16129 (org-with-limited-levels (org-back-to-heading t)))
16130 (let ((beg (point)))
16131 (cond
16132 ((equal property "TODO")
16133 (cond ((not (org-string-nw-p value)) (setq value 'none))
16134 ((not (member value org-todo-keywords-1))
16135 (user-error "\"%s\" is not a valid TODO state" value)))
16136 (org-todo value)
16137 (org-set-tags nil 'align))
16138 ((equal property "PRIORITY")
16139 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16140 (org-set-tags nil 'align))
16141 ((equal property "SCHEDULED")
16142 (forward-line)
16143 (if (and (looking-at-p org-planning-line-re)
16144 (re-search-forward
16145 org-scheduled-time-regexp (line-end-position) t))
16146 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16147 ((string= value "later") (org-timestamp-change 1 'day))
16148 ((string= value "") (org-schedule '(4)))
16149 (t (org-schedule nil value)))
16150 (if (member value '("earlier" "later" ""))
16151 (call-interactively #'org-schedule)
16152 (org-schedule nil value))))
16153 ((equal property "DEADLINE")
16154 (forward-line)
16155 (if (and (looking-at-p org-planning-line-re)
16156 (re-search-forward
16157 org-deadline-time-regexp (line-end-position) t))
16158 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16159 ((string= value "later") (org-timestamp-change 1 'day))
16160 ((string= value "") (org-deadline '(4)))
16161 (t (org-deadline nil value)))
16162 (if (member value '("earlier" "later" ""))
16163 (call-interactively #'org-deadline)
16164 (org-deadline nil value))))
16165 ((member property org-special-properties)
16166 (error "The %s property cannot be set with `org-entry-put'" property))
16168 (let* ((range (org-get-property-block beg 'force))
16169 (end (cdr range))
16170 (case-fold-search t))
16171 (goto-char (car range))
16172 (if (re-search-forward (org-re-property property nil t) end t)
16173 (progn (delete-region (match-beginning 0) (match-end 0))
16174 (goto-char (match-beginning 0)))
16175 (goto-char end)
16176 (insert "\n")
16177 (backward-char))
16178 (insert ":" property ":")
16179 (when value (insert " " value))
16180 (org-indent-line)))))
16181 (run-hook-with-args 'org-property-changed-functions property value)))
16183 (defun org-buffer-property-keys
16184 (&optional specials defaults columns ignore-malformed)
16185 "Get all property keys in the current buffer.
16187 When SPECIALS is non-nil, also list the special properties that
16188 reflect things like tags and TODO state.
16190 When DEFAULTS is non-nil, also include properties that has
16191 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16192 DESCRIPTION, LOCATION, and LOGGING and others.
16194 When COLUMNS in non-nil, also include property names given in
16195 COLUMN formats in the current buffer.
16197 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16198 automatically performed, such drawers will be silently ignored."
16199 (let ((case-fold-search t)
16200 (props (append
16201 (and specials org-special-properties)
16202 (and defaults (cons org-effort-property org-default-properties))
16203 nil)))
16204 (org-with-wide-buffer
16205 (goto-char (point-min))
16206 (while (re-search-forward org-property-start-re nil t)
16207 (let ((range (org-get-property-block)))
16208 (catch 'skip
16209 (unless range
16210 (when (and (not ignore-malformed)
16211 (not (org-before-first-heading-p))
16212 (y-or-n-p (format "Malformed drawer at %d, repair?"
16213 (line-beginning-position))))
16214 (org-get-property-block nil t))
16215 (throw 'skip nil))
16216 (goto-char (car range))
16217 (let ((begin (car range))
16218 (end (cdr range)))
16219 ;; Make sure that found property block is not located
16220 ;; before current point, as it would generate an infloop.
16221 ;; It can happen, for example, in the following
16222 ;; situation:
16224 ;; * Headline
16225 ;; :PROPERTIES:
16226 ;; ...
16227 ;; :END:
16228 ;; *************** Inlinetask
16229 ;; #+BEGIN_EXAMPLE
16230 ;; :PROPERTIES:
16231 ;; #+END_EXAMPLE
16233 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16234 (while (< (point) end)
16235 (let ((p (progn (looking-at org-property-re)
16236 (match-string-no-properties 2))))
16237 ;; Only add true property name, not extension symbol.
16238 (push (if (not (string-match-p "\\+\\'" p)) p
16239 (substring p 0 -1))
16240 props))
16241 (forward-line))))
16242 (outline-next-heading)))
16243 (when columns
16244 (goto-char (point-min))
16245 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16246 (let ((element (org-element-at-point)))
16247 (when (memq (org-element-type element) '(keyword node-property))
16248 (let ((value (org-element-property :value element))
16249 (start 0))
16250 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16251 (setq start (match-end 0))
16252 (let ((p (match-string-no-properties 1 value)))
16253 (unless (member-ignore-case p org-special-properties)
16254 (push p props))))))))))
16255 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16257 (defun org-property-values (key)
16258 "List all non-nil values of property KEY in current buffer."
16259 (org-with-wide-buffer
16260 (goto-char (point-min))
16261 (let ((case-fold-search t)
16262 (re (org-re-property key))
16263 values)
16264 (while (re-search-forward re nil t)
16265 (push (org-entry-get (point) key) values))
16266 (delete-dups values))))
16268 (defun org-insert-property-drawer ()
16269 "Insert a property drawer into the current entry."
16270 (org-with-wide-buffer
16271 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16272 (org-back-to-heading t)
16273 (org-with-limited-levels (org-back-to-heading t)))
16274 (forward-line)
16275 (when (looking-at-p org-planning-line-re) (forward-line))
16276 (unless (looking-at-p org-property-drawer-re)
16277 ;; Make sure we start editing a line from current entry, not from
16278 ;; next one. It prevents extending text properties or overlays
16279 ;; belonging to the latter.
16280 (when (bolp) (backward-char))
16281 (let ((begin (1+ (point)))
16282 (inhibit-read-only t))
16283 (insert "\n:PROPERTIES:\n:END:")
16284 (when (eobp) (insert "\n"))
16285 (org-indent-region begin (point))))))
16287 (defun org-insert-drawer (&optional arg drawer)
16288 "Insert a drawer at point.
16290 When optional argument ARG is non-nil, insert a property drawer.
16292 Optional argument DRAWER, when non-nil, is a string representing
16293 drawer's name. Otherwise, the user is prompted for a name.
16295 If a region is active, insert the drawer around that region
16296 instead.
16298 Point is left between drawer's boundaries."
16299 (interactive "P")
16300 (let* ((drawer (if arg "PROPERTIES"
16301 (or drawer (read-from-minibuffer "Drawer: ")))))
16302 (cond
16303 ;; With C-u, fall back on `org-insert-property-drawer'
16304 (arg (org-insert-property-drawer))
16305 ;; Check validity of suggested drawer's name.
16306 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16307 (user-error "Invalid drawer name"))
16308 ;; With an active region, insert a drawer at point.
16309 ((not (org-region-active-p))
16310 (progn
16311 (unless (bolp) (insert "\n"))
16312 (insert (format ":%s:\n\n:END:\n" drawer))
16313 (forward-line -2)))
16314 ;; Otherwise, insert the drawer at point
16316 (let ((rbeg (region-beginning))
16317 (rend (copy-marker (region-end))))
16318 (unwind-protect
16319 (progn
16320 (goto-char rbeg)
16321 (beginning-of-line)
16322 (when (save-excursion
16323 (re-search-forward org-outline-regexp-bol rend t))
16324 (user-error "Drawers cannot contain headlines"))
16325 ;; Position point at the beginning of the first
16326 ;; non-blank line in region. Insert drawer's opening
16327 ;; there, then indent it.
16328 (org-skip-whitespace)
16329 (beginning-of-line)
16330 (insert ":" drawer ":\n")
16331 (forward-line -1)
16332 (indent-for-tab-command)
16333 ;; Move point to the beginning of the first blank line
16334 ;; after the last non-blank line in region. Insert
16335 ;; drawer's closing, then indent it.
16336 (goto-char rend)
16337 (skip-chars-backward " \r\t\n")
16338 (insert "\n:END:")
16339 (deactivate-mark t)
16340 (indent-for-tab-command)
16341 (unless (eolp) (insert "\n")))
16342 ;; Clear marker, whatever the outcome of insertion is.
16343 (set-marker rend nil)))))))
16345 (defvar org-property-set-functions-alist nil
16346 "Property set function alist.
16347 Each entry should have the following format:
16349 (PROPERTY . READ-FUNCTION)
16351 The read function will be called with the same argument as
16352 `org-completing-read'.")
16354 (defun org-set-property-function (property)
16355 "Get the function that should be used to set PROPERTY.
16356 This is computed according to `org-property-set-functions-alist'."
16357 (or (cdr (assoc property org-property-set-functions-alist))
16358 'org-completing-read))
16360 (defun org-read-property-value (property)
16361 "Read PROPERTY value from user."
16362 (let* ((completion-ignore-case t)
16363 (allowed (org-property-get-allowed-values nil property 'table))
16364 (cur (org-entry-get nil property))
16365 (prompt (concat property " value"
16366 (if (and cur (string-match "\\S-" cur))
16367 (concat " [" cur "]") "") ": "))
16368 (set-function (org-set-property-function property))
16369 (val (if allowed
16370 (funcall set-function prompt allowed nil
16371 (not (get-text-property 0 'org-unrestricted
16372 (caar allowed))))
16373 (funcall set-function prompt
16374 (mapcar 'list (org-property-values property))
16375 nil nil "" nil cur))))
16376 (org-trim val)))
16378 (defvar org-last-set-property nil)
16379 (defvar org-last-set-property-value nil)
16380 (defun org-read-property-name ()
16381 "Read a property name."
16382 (let ((completion-ignore-case t)
16383 (default-prop (or (and (org-at-property-p)
16384 (match-string-no-properties 2))
16385 org-last-set-property)))
16386 (org-completing-read
16387 (concat "Property"
16388 (if default-prop (concat " [" default-prop "]") "")
16389 ": ")
16390 (mapcar #'list (org-buffer-property-keys nil t t))
16391 nil nil nil nil default-prop)))
16393 (defun org-set-property-and-value (use-last)
16394 "Allow to set [PROPERTY]: [value] direction from prompt.
16395 When use-default, don't even ask, just use the last
16396 \"[PROPERTY]: [value]\" string from the history."
16397 (interactive "P")
16398 (let* ((completion-ignore-case t)
16399 (pv (or (and use-last org-last-set-property-value)
16400 (org-completing-read
16401 "Enter a \"[Property]: [value]\" pair: "
16402 nil nil nil nil nil
16403 org-last-set-property-value)))
16404 prop val)
16405 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16406 (setq prop (match-string 1 pv)
16407 val (match-string 2 pv))
16408 (org-set-property prop val))))
16410 (defun org-set-property (property value)
16411 "In the current entry, set PROPERTY to VALUE.
16413 When called interactively, this will prompt for a property name, offering
16414 completion on existing and default properties. And then it will prompt
16415 for a value, offering completion either on allowed values (via an inherited
16416 xxx_ALL property) or on existing values in other instances of this property
16417 in the current file.
16419 Throw an error when trying to set a property with an invalid name."
16420 (interactive (list nil nil))
16421 (let ((property (or property (org-read-property-name))))
16422 ;; `org-entry-put' also makes the following check, but this one
16423 ;; avoids polluting `org-last-set-property' and
16424 ;; `org-last-set-property-value' needlessly.
16425 (unless (org--valid-property-p property)
16426 (user-error "Invalid property name: \"%s\"" property))
16427 (let ((value (or value (org-read-property-value property)))
16428 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16429 (setq org-last-set-property property)
16430 (setq org-last-set-property-value (concat property ": " value))
16431 ;; Possibly postprocess the inserted value:
16432 (when fn (setq value (funcall fn value)))
16433 (unless (equal (org-entry-get nil property) value)
16434 (org-entry-put nil property value)))))
16436 (defun org-find-property (property &optional value)
16437 "Find first entry in buffer that sets PROPERTY.
16439 When optional argument VALUE is non-nil, only consider an entry
16440 if it contains PROPERTY set to this value. If PROPERTY should be
16441 explicitly set to nil, use string \"nil\" for VALUE.
16443 Return position where the entry begins, or nil if there is no
16444 such entry. If narrowing is in effect, only search the visible
16445 part of the buffer."
16446 (save-excursion
16447 (goto-char (point-min))
16448 (let ((case-fold-search t)
16449 (re (org-re-property property nil (not value) value)))
16450 (catch 'exit
16451 (while (re-search-forward re nil t)
16452 (when (if value (org-at-property-p)
16453 (org-entry-get (point) property nil t))
16454 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16456 (defun org-delete-property (property)
16457 "In the current entry, delete PROPERTY."
16458 (interactive
16459 (let* ((completion-ignore-case t)
16460 (cat (org-entry-get (point) "CATEGORY"))
16461 (props0 (org-entry-properties nil 'standard))
16462 (props (if cat props0
16463 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16464 (prop (if (< 1 (length props))
16465 (completing-read "Property: " props nil t)
16466 (caar props))))
16467 (list prop)))
16468 (if (not property)
16469 (message "No property to delete in this entry")
16470 (org-entry-delete nil property)
16471 (message "Property \"%s\" deleted" property)))
16473 (defun org-delete-property-globally (property)
16474 "Remove PROPERTY globally, from all entries.
16475 This function ignores narrowing, if any."
16476 (interactive
16477 (let* ((completion-ignore-case t)
16478 (prop (completing-read
16479 "Globally remove property: "
16480 (mapcar #'list (org-buffer-property-keys)))))
16481 (list prop)))
16482 (org-with-wide-buffer
16483 (goto-char (point-min))
16484 (let ((count 0)
16485 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16486 (while (re-search-forward re nil t)
16487 (when (org-entry-delete (point) property) (cl-incf count)))
16488 (message "Property \"%s\" removed from %d entries" property count))))
16490 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16492 (defun org-compute-property-at-point ()
16493 "Compute the property at point.
16494 This looks for an enclosing column format, extracts the operator and
16495 then applies it to the property in the column format's scope."
16496 (interactive)
16497 (unless (org-at-property-p)
16498 (user-error "Not at a property"))
16499 (let ((prop (match-string-no-properties 2)))
16500 (org-columns-get-format-and-top-level)
16501 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16502 (user-error "No operator defined for property %s" prop))
16503 (org-columns-compute prop)))
16505 (defvar org-property-allowed-value-functions nil
16506 "Hook for functions supplying allowed values for a specific property.
16507 The functions must take a single argument, the name of the property, and
16508 return a flat list of allowed values. If \":ETC\" is one of
16509 the values, this means that these values are intended as defaults for
16510 completion, but that other values should be allowed too.
16511 The functions must return nil if they are not responsible for this
16512 property.")
16514 (defun org-property-get-allowed-values (pom property &optional table)
16515 "Get allowed values for the property PROPERTY.
16516 When TABLE is non-nil, return an alist that can directly be used for
16517 completion."
16518 (let (vals)
16519 (cond
16520 ((equal property "TODO")
16521 (setq vals (org-with-point-at pom
16522 (append org-todo-keywords-1 '("")))))
16523 ((equal property "PRIORITY")
16524 (let ((n org-lowest-priority))
16525 (while (>= n org-highest-priority)
16526 (push (char-to-string n) vals)
16527 (setq n (1- n)))))
16528 ((equal property "CATEGORY"))
16529 ((member property org-special-properties))
16530 ((setq vals (run-hook-with-args-until-success
16531 'org-property-allowed-value-functions property)))
16533 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16534 (when (and vals (string-match "\\S-" vals))
16535 (setq vals (car (read-from-string (concat "(" vals ")"))))
16536 (setq vals (mapcar (lambda (x)
16537 (cond ((stringp x) x)
16538 ((numberp x) (number-to-string x))
16539 ((symbolp x) (symbol-name x))
16540 (t "???")))
16541 vals)))))
16542 (when (member ":ETC" vals)
16543 (setq vals (remove ":ETC" vals))
16544 (org-add-props (car vals) '(org-unrestricted t)))
16545 (if table (mapcar 'list vals) vals)))
16547 (defun org-property-previous-allowed-value (&optional _previous)
16548 "Switch to the next allowed value for this property."
16549 (interactive)
16550 (org-property-next-allowed-value t))
16552 (defun org-property-next-allowed-value (&optional previous)
16553 "Switch to the next allowed value for this property."
16554 (interactive)
16555 (unless (org-at-property-p)
16556 (user-error "Not at a property"))
16557 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16558 (key (match-string 2))
16559 (value (match-string 3))
16560 (allowed (or (org-property-get-allowed-values (point) key)
16561 (and (member value '("[ ]" "[-]" "[X]"))
16562 '("[ ]" "[X]"))))
16563 (heading (save-match-data (nth 4 (org-heading-components))))
16564 nval)
16565 (unless allowed
16566 (user-error "Allowed values for this property have not been defined"))
16567 (when previous (setq allowed (reverse allowed)))
16568 (when (member value allowed)
16569 (setq nval (car (cdr (member value allowed)))))
16570 (setq nval (or nval (car allowed)))
16571 (when (equal nval value)
16572 (user-error "Only one allowed value for this property"))
16573 (org-at-property-p)
16574 (replace-match (concat " :" key ": " nval) t t)
16575 (org-indent-line)
16576 (beginning-of-line 1)
16577 (skip-chars-forward " \t")
16578 (when (equal prop org-effort-property)
16579 (org-refresh-property
16580 '((effort . identity)
16581 (effort-minutes . org-duration-string-to-minutes))
16582 nval)
16583 (when (string= org-clock-current-task heading)
16584 (setq org-clock-effort nval)
16585 (org-clock-update-mode-line)))
16586 (run-hook-with-args 'org-property-changed-functions key nval)))
16588 (defun org-find-olp (path &optional this-buffer)
16589 "Return a marker pointing to the entry at outline path OLP.
16590 If anything goes wrong, throw an error.
16591 You can wrap this call to catch the error like this:
16593 (condition-case msg
16594 (org-mobile-locate-entry (match-string 4))
16595 (error (nth 1 msg)))
16597 The return value will then be either a string with the error message,
16598 or a marker if everything is OK.
16600 If THIS-BUFFER is set, the outline path does not contain a file,
16601 only headings."
16602 (let* ((file (if this-buffer buffer-file-name (pop path)))
16603 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16604 (level 1)
16605 (lmin 1)
16606 (lmax 1)
16607 end found flevel)
16608 (unless buffer (error "File not found :%s" file))
16609 (with-current-buffer buffer
16610 (org-with-wide-buffer
16611 (goto-char (point-min))
16612 (dolist (heading path)
16613 (let ((re (format org-complex-heading-regexp-format
16614 (regexp-quote heading)))
16615 (cnt 0))
16616 (while (re-search-forward re end t)
16617 (setq level (- (match-end 1) (match-beginning 1)))
16618 (when (and (>= level lmin) (<= level lmax))
16619 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16620 (when (= cnt 0)
16621 (error "Heading not found on level %d: %s" lmax heading))
16622 (when (> cnt 1)
16623 (error "Heading not unique on level %d: %s" lmax heading))
16624 (goto-char found)
16625 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16626 (setq end (save-excursion (org-end-of-subtree t t)))))
16627 (when (org-at-heading-p)
16628 (point-marker))))))
16630 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16631 "Find node HEADING in BUFFER.
16632 Return a marker to the heading if it was found, or nil if not.
16633 If POS-ONLY is set, return just the position instead of a marker.
16635 The heading text must match exact, but it may have a TODO keyword,
16636 a priority cookie and tags in the standard locations."
16637 (with-current-buffer (or buffer (current-buffer))
16638 (org-with-wide-buffer
16639 (goto-char (point-min))
16640 (let (case-fold-search)
16641 (when (re-search-forward
16642 (format org-complex-heading-regexp-format
16643 (regexp-quote heading)) nil t)
16644 (if pos-only
16645 (match-beginning 0)
16646 (move-marker (make-marker) (match-beginning 0))))))))
16648 (defun org-find-exact-heading-in-directory (heading &optional dir)
16649 "Find Org node headline HEADING in all .org files in directory DIR.
16650 When the target headline is found, return a marker to this location."
16651 (let ((files (directory-files (or dir default-directory)
16652 t "\\`[^.#].*\\.org\\'"))
16653 visiting m buffer)
16654 (catch 'found
16655 (dolist (file files)
16656 (message "trying %s" file)
16657 (setq visiting (org-find-base-buffer-visiting file))
16658 (setq buffer (or visiting (find-file-noselect file)))
16659 (setq m (org-find-exact-headline-in-buffer
16660 heading buffer))
16661 (when (and (not m) (not visiting)) (kill-buffer buffer))
16662 (and m (throw 'found m))))))
16664 (defun org-find-entry-with-id (ident)
16665 "Locate the entry that contains the ID property with exact value IDENT.
16666 IDENT can be a string, a symbol or a number, this function will search for
16667 the string representation of it.
16668 Return the position where this entry starts, or nil if there is no such entry."
16669 (interactive "sID: ")
16670 (let ((id (cond
16671 ((stringp ident) ident)
16672 ((symbolp ident) (symbol-name ident))
16673 ((numberp ident) (number-to-string ident))
16674 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16675 (org-with-wide-buffer (org-find-property "ID" id))))
16677 ;;;; Timestamps
16679 (defvar org-last-changed-timestamp nil)
16680 (defvar org-last-inserted-timestamp nil
16681 "The last time stamp inserted with `org-insert-time-stamp'.")
16682 (defvar org-ts-what) ; dynamically scoped parameter
16684 (defun org-time-stamp (arg &optional inactive)
16685 "Prompt for a date/time and insert a time stamp.
16687 If the user specifies a time like HH:MM or if this command is
16688 called with at least one prefix argument, the time stamp contains
16689 the date and the time. Otherwise, only the date is included.
16691 All parts of a date not specified by the user are filled in from
16692 the timestamp at point, if any, or the current date/time
16693 otherwise.
16695 If there is already a timestamp at the cursor, it is replaced.
16697 With two universal prefix arguments, insert an active timestamp
16698 with the current time without prompting the user.
16700 When called from lisp, the timestamp is inactive if INACTIVE is
16701 non-nil."
16702 (interactive "P")
16703 (let* ((ts (cond
16704 ((org-at-date-range-p t)
16705 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16706 ((org-at-timestamp-p t) (match-string 0))))
16707 ;; Default time is either the timestamp at point or today.
16708 ;; When entering a range, only the range start is considered.
16709 (default-time (if (not ts) (current-time)
16710 (apply #'encode-time (org-parse-time-string ts))))
16711 (default-input (and ts (org-get-compact-tod ts)))
16712 (repeater (and ts
16713 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16714 (match-string 0 ts)))
16715 org-time-was-given
16716 org-end-time-was-given
16717 (time
16718 (and (if (equal arg '(16)) (current-time)
16719 ;; Preserve `this-command' and `last-command'.
16720 (let ((this-command this-command)
16721 (last-command last-command))
16722 (org-read-date
16723 arg 'totime nil nil default-time default-input
16724 inactive))))))
16725 (cond
16726 ((and ts
16727 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16728 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16729 (insert "--")
16730 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16732 ;; Make sure we're on a timestamp. When in the middle of a date
16733 ;; range, move arbitrarily to range end.
16734 (unless (org-at-timestamp-p t)
16735 (skip-chars-forward "-")
16736 (org-at-timestamp-p t))
16737 (replace-match "")
16738 (setq org-last-changed-timestamp
16739 (org-insert-time-stamp
16740 time (or org-time-was-given arg)
16741 inactive nil nil (list org-end-time-was-given)))
16742 (when repeater
16743 (backward-char)
16744 (insert " " repeater)
16745 (setq org-last-changed-timestamp
16746 (concat (substring org-last-inserted-timestamp 0 -1)
16747 " " repeater ">")))
16748 (message "Timestamp updated"))
16749 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16750 (t (org-insert-time-stamp
16751 time (or org-time-was-given arg) inactive nil nil
16752 (list org-end-time-was-given))))))
16754 ;; FIXME: can we use this for something else, like computing time differences?
16755 (defun org-get-compact-tod (s)
16756 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16757 (let* ((t1 (match-string 1 s))
16758 (h1 (string-to-number (match-string 2 s)))
16759 (m1 (string-to-number (match-string 3 s)))
16760 (t2 (and (match-end 4) (match-string 5 s)))
16761 (h2 (and t2 (string-to-number (match-string 6 s))))
16762 (m2 (and t2 (string-to-number (match-string 7 s))))
16763 dh dm)
16764 (if (not t2)
16766 (setq dh (- h2 h1) dm (- m2 m1))
16767 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16768 (concat t1 "+" (number-to-string dh)
16769 (and (/= 0 dm) (format ":%02d" dm)))))))
16771 (defun org-time-stamp-inactive (&optional arg)
16772 "Insert an inactive time stamp.
16773 An inactive time stamp is enclosed in square brackets instead of angle
16774 brackets. It is inactive in the sense that it does not trigger agenda entries,
16775 does not link to the calendar and cannot be changed with the S-cursor keys.
16776 So these are more for recording a certain time/date."
16777 (interactive "P")
16778 (org-time-stamp arg 'inactive))
16780 (defvar org-date-ovl (make-overlay 1 1))
16781 (overlay-put org-date-ovl 'face 'org-date-selected)
16782 (delete-overlay org-date-ovl)
16784 (defvar org-ans1) ; dynamically scoped parameter
16785 (defvar org-ans2) ; dynamically scoped parameter
16787 (defvar org-plain-time-of-day-regexp) ; defined below
16789 (defvar org-overriding-default-time nil) ; dynamically scoped
16790 (defvar org-read-date-overlay nil)
16791 (defvar org-dcst nil) ; dynamically scoped
16792 (defvar org-read-date-history nil)
16793 (defvar org-read-date-final-answer nil)
16794 (defvar org-read-date-analyze-futurep nil)
16795 (defvar org-read-date-analyze-forced-year nil)
16796 (defvar org-read-date-inactive)
16798 (defvar org-read-date-minibuffer-local-map
16799 (let* ((map (make-sparse-keymap)))
16800 (set-keymap-parent map minibuffer-local-map)
16801 (org-defkey map (kbd ".")
16802 (lambda () (interactive)
16803 ;; Are we at the beginning of the prompt?
16804 (if (looking-back "^[^:]+: "
16805 (let ((inhibit-field-text-motion t))
16806 (line-beginning-position)))
16807 (org-eval-in-calendar '(calendar-goto-today))
16808 (insert "."))))
16809 (org-defkey map (kbd "C-.")
16810 (lambda () (interactive)
16811 (org-eval-in-calendar '(calendar-goto-today))))
16812 (org-defkey map [(meta shift left)]
16813 (lambda () (interactive)
16814 (org-eval-in-calendar '(calendar-backward-month 1))))
16815 (org-defkey map [(meta shift right)]
16816 (lambda () (interactive)
16817 (org-eval-in-calendar '(calendar-forward-month 1))))
16818 (org-defkey map [(meta shift up)]
16819 (lambda () (interactive)
16820 (org-eval-in-calendar '(calendar-backward-year 1))))
16821 (org-defkey map [(meta shift down)]
16822 (lambda () (interactive)
16823 (org-eval-in-calendar '(calendar-forward-year 1))))
16824 (org-defkey map [?\e (shift left)]
16825 (lambda () (interactive)
16826 (org-eval-in-calendar '(calendar-backward-month 1))))
16827 (org-defkey map [?\e (shift right)]
16828 (lambda () (interactive)
16829 (org-eval-in-calendar '(calendar-forward-month 1))))
16830 (org-defkey map [?\e (shift up)]
16831 (lambda () (interactive)
16832 (org-eval-in-calendar '(calendar-backward-year 1))))
16833 (org-defkey map [?\e (shift down)]
16834 (lambda () (interactive)
16835 (org-eval-in-calendar '(calendar-forward-year 1))))
16836 (org-defkey map [(shift up)]
16837 (lambda () (interactive)
16838 (org-eval-in-calendar '(calendar-backward-week 1))))
16839 (org-defkey map [(shift down)]
16840 (lambda () (interactive)
16841 (org-eval-in-calendar '(calendar-forward-week 1))))
16842 (org-defkey map [(shift left)]
16843 (lambda () (interactive)
16844 (org-eval-in-calendar '(calendar-backward-day 1))))
16845 (org-defkey map [(shift right)]
16846 (lambda () (interactive)
16847 (org-eval-in-calendar '(calendar-forward-day 1))))
16848 (org-defkey map "!"
16849 (lambda () (interactive)
16850 (org-eval-in-calendar '(diary-view-entries))
16851 (message "")))
16852 (org-defkey map ">"
16853 (lambda () (interactive)
16854 (org-eval-in-calendar '(calendar-scroll-left 1))))
16855 (org-defkey map "<"
16856 (lambda () (interactive)
16857 (org-eval-in-calendar '(calendar-scroll-right 1))))
16858 (org-defkey map "\C-v"
16859 (lambda () (interactive)
16860 (org-eval-in-calendar
16861 '(calendar-scroll-left-three-months 1))))
16862 (org-defkey map "\M-v"
16863 (lambda () (interactive)
16864 (org-eval-in-calendar
16865 '(calendar-scroll-right-three-months 1))))
16866 map)
16867 "Keymap for minibuffer commands when using `org-read-date'.")
16869 (defvar org-def)
16870 (defvar org-defdecode)
16871 (defvar org-with-time)
16873 (defvar calendar-setup) ; Dynamically scoped.
16874 (defun org-read-date (&optional with-time to-time from-string prompt
16875 default-time default-input inactive)
16876 "Read a date, possibly a time, and make things smooth for the user.
16877 The prompt will suggest to enter an ISO date, but you can also enter anything
16878 which will at least partially be understood by `parse-time-string'.
16879 Unrecognized parts of the date will default to the current day, month, year,
16880 hour and minute. If this command is called to replace a timestamp at point,
16881 or to enter the second timestamp of a range, the default time is taken
16882 from the existing stamp. Furthermore, the command prefers the future,
16883 so if you are giving a date where the year is not given, and the day-month
16884 combination is already past in the current year, it will assume you
16885 mean next year. For details, see the manual. A few examples:
16887 3-2-5 --> 2003-02-05
16888 feb 15 --> currentyear-02-15
16889 2/15 --> currentyear-02-15
16890 sep 12 9 --> 2009-09-12
16891 12:45 --> today 12:45
16892 22 sept 0:34 --> currentyear-09-22 0:34
16893 12 --> currentyear-currentmonth-12
16894 Fri --> nearest Friday after today
16895 -Tue --> last Tuesday
16896 etc.
16898 Furthermore you can specify a relative date by giving, as the *first* thing
16899 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16900 change in days weeks, months, years.
16901 With a single plus or minus, the date is relative to today. With a double
16902 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16903 +4d --> four days from today
16904 +4 --> same as above
16905 +2w --> two weeks from today
16906 ++5 --> five days from default date
16908 The function understands only English month and weekday abbreviations.
16910 While prompting, a calendar is popped up - you can also select the
16911 date with the mouse (button 1). The calendar shows a period of three
16912 months. To scroll it to other months, use the keys `>' and `<'.
16913 If you don't like the calendar, turn it off with
16914 (setq org-read-date-popup-calendar nil)
16916 With optional argument TO-TIME, the date will immediately be converted
16917 to an internal time.
16918 With an optional argument WITH-TIME, the prompt will suggest to
16919 also insert a time. Note that when WITH-TIME is not set, you can
16920 still enter a time, and this function will inform the calling routine
16921 about this change. The calling routine may then choose to change the
16922 format used to insert the time stamp into the buffer to include the time.
16923 With optional argument FROM-STRING, read from this string instead from
16924 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16925 the time/date that is used for everything that is not specified by the
16926 user."
16927 (require 'parse-time)
16928 (let* ((org-with-time with-time)
16929 (org-time-stamp-rounding-minutes
16930 (if (equal org-with-time '(16))
16931 '(0 0)
16932 org-time-stamp-rounding-minutes))
16933 (org-dcst org-display-custom-times)
16934 (ct (org-current-time))
16935 (org-def (or org-overriding-default-time default-time ct))
16936 (org-defdecode (decode-time org-def))
16937 (cur-frame (selected-frame))
16938 (mouse-autoselect-window nil) ; Don't let the mouse jump
16939 (calendar-setup
16940 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16941 (calendar-move-hook nil)
16942 (calendar-view-diary-initially-flag nil)
16943 (calendar-view-holidays-initially-flag nil)
16944 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16945 ;; Rationalize `org-def' and `org-defdecode', if required.
16946 (when (< (nth 2 org-defdecode) org-extend-today-until)
16947 (setf (nth 2 org-defdecode) -1)
16948 (setf (nth 1 org-defdecode) 59)
16949 (setq org-def (apply #'encode-time org-defdecode))
16950 (setq org-defdecode (decode-time org-def)))
16951 (let* ((timestr (format-time-string
16952 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16953 org-def))
16954 (prompt (concat (if prompt (concat prompt " ") "")
16955 (format "Date+time [%s]: " timestr))))
16956 (cond
16957 (from-string (setq ans from-string))
16958 (org-read-date-popup-calendar
16959 (save-excursion
16960 (save-window-excursion
16961 (calendar)
16962 (when (eq calendar-setup 'calendar-only)
16963 (setq cal-frame
16964 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16965 (select-frame cal-frame))
16966 (org-eval-in-calendar '(setq cursor-type nil) t)
16967 (unwind-protect
16968 (progn
16969 (calendar-forward-day (- (time-to-days org-def)
16970 (calendar-absolute-from-gregorian
16971 (calendar-current-date))))
16972 (org-eval-in-calendar nil t)
16973 (let* ((old-map (current-local-map))
16974 (map (copy-keymap calendar-mode-map))
16975 (minibuffer-local-map
16976 (copy-keymap org-read-date-minibuffer-local-map)))
16977 (org-defkey map (kbd "RET") 'org-calendar-select)
16978 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16979 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16980 (unwind-protect
16981 (progn
16982 (use-local-map map)
16983 (setq org-read-date-inactive inactive)
16984 (add-hook 'post-command-hook 'org-read-date-display)
16985 (setq org-ans0
16986 (read-string prompt
16987 default-input
16988 'org-read-date-history
16989 nil))
16990 ;; org-ans0: from prompt
16991 ;; org-ans1: from mouse click
16992 ;; org-ans2: from calendar motion
16993 (setq ans
16994 (concat org-ans0 " " (or org-ans1 org-ans2))))
16995 (remove-hook 'post-command-hook 'org-read-date-display)
16996 (use-local-map old-map)
16997 (when org-read-date-overlay
16998 (delete-overlay org-read-date-overlay)
16999 (setq org-read-date-overlay nil)))))
17000 (bury-buffer "*Calendar*")
17001 (when cal-frame
17002 (delete-frame cal-frame)
17003 (select-frame-set-input-focus cur-frame))))))
17005 (t ; Naked prompt only
17006 (unwind-protect
17007 (setq ans (read-string prompt default-input
17008 'org-read-date-history timestr))
17009 (when org-read-date-overlay
17010 (delete-overlay org-read-date-overlay)
17011 (setq org-read-date-overlay nil))))))
17013 (setq final (org-read-date-analyze ans org-def org-defdecode))
17015 (when org-read-date-analyze-forced-year
17016 (message "Year was forced into %s"
17017 (if org-read-date-force-compatible-dates
17018 "compatible range (1970-2037)"
17019 "range representable on this machine"))
17020 (ding))
17022 ;; One round trip to get rid of 34th of August and stuff like that....
17023 (setq final (decode-time (apply 'encode-time final)))
17025 (setq org-read-date-final-answer ans)
17027 (if to-time
17028 (apply 'encode-time final)
17029 (if (and (boundp 'org-time-was-given) org-time-was-given)
17030 (format "%04d-%02d-%02d %02d:%02d"
17031 (nth 5 final) (nth 4 final) (nth 3 final)
17032 (nth 2 final) (nth 1 final))
17033 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17035 (defun org-read-date-display ()
17036 "Display the current date prompt interpretation in the minibuffer."
17037 (when org-read-date-display-live
17038 (when org-read-date-overlay
17039 (delete-overlay org-read-date-overlay))
17040 (when (minibufferp (current-buffer))
17041 (save-excursion
17042 (end-of-line 1)
17043 (while (not (equal (buffer-substring
17044 (max (point-min) (- (point) 4)) (point))
17045 " "))
17046 (insert " ")))
17047 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17048 " " (or org-ans1 org-ans2)))
17049 (org-end-time-was-given nil)
17050 (f (org-read-date-analyze ans org-def org-defdecode))
17051 (fmts (if org-dcst
17052 org-time-stamp-custom-formats
17053 org-time-stamp-formats))
17054 (fmt (if (or org-with-time
17055 (and (boundp 'org-time-was-given) org-time-was-given))
17056 (cdr fmts)
17057 (car fmts)))
17058 (txt (format-time-string fmt (apply 'encode-time f)))
17059 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17060 (txt (concat "=> " txt)))
17061 (when (and org-end-time-was-given
17062 (string-match org-plain-time-of-day-regexp txt))
17063 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17064 org-end-time-was-given
17065 (substring txt (match-end 0)))))
17066 (when org-read-date-analyze-futurep
17067 (setq txt (concat txt " (=>F)")))
17068 (setq org-read-date-overlay
17069 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17070 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17072 (defun org-read-date-analyze (ans def defdecode)
17073 "Analyze the combined answer of the date prompt."
17074 ;; FIXME: cleanup and comment
17075 ;; Pass `current-time' result to `decode-time' (instead of calling
17076 ;; without arguments) so that only `current-time' has to be
17077 ;; overridden in tests.
17078 (let ((org-def def)
17079 (org-defdecode defdecode)
17080 (nowdecode (decode-time (current-time)))
17081 delta deltan deltaw deltadef year month day
17082 hour minute second wday pm h2 m2 tl wday1
17083 iso-year iso-weekday iso-week iso-date futurep kill-year)
17084 (setq org-read-date-analyze-futurep nil
17085 org-read-date-analyze-forced-year nil)
17086 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17087 (setq ans "+0"))
17089 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17090 (setq ans (replace-match "" t t ans)
17091 deltan (car delta)
17092 deltaw (nth 1 delta)
17093 deltadef (nth 2 delta)))
17095 ;; Check if there is an iso week date in there. If yes, store the
17096 ;; info and postpone interpreting it until the rest of the parsing
17097 ;; is done.
17098 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17099 (setq iso-year (when (match-end 1)
17100 (org-small-year-to-year
17101 (string-to-number (match-string 1 ans))))
17102 iso-weekday (when (match-end 3)
17103 (string-to-number (match-string 3 ans)))
17104 iso-week (string-to-number (match-string 2 ans)))
17105 (setq ans (replace-match "" t t ans)))
17107 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17108 (when (string-match
17109 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17110 (setq year (if (match-end 2)
17111 (string-to-number (match-string 2 ans))
17112 (progn (setq kill-year t)
17113 (string-to-number (format-time-string "%Y"))))
17114 month (string-to-number (match-string 3 ans))
17115 day (string-to-number (match-string 4 ans)))
17116 (setq year (org-small-year-to-year year))
17117 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17118 t nil ans)))
17120 ;; Help matching dotted european dates
17121 (when (string-match
17122 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17123 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17124 (setq kill-year t)
17125 (string-to-number (format-time-string "%Y")))
17126 day (string-to-number (match-string 1 ans))
17127 month (string-to-number (match-string 2 ans))
17128 ans (replace-match (format "%04d-%02d-%02d" year month day)
17129 t nil ans)))
17131 ;; Help matching american dates, like 5/30 or 5/30/7
17132 (when (string-match
17133 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17134 (setq year (if (match-end 4)
17135 (string-to-number (match-string 4 ans))
17136 (progn (setq kill-year t)
17137 (string-to-number (format-time-string "%Y"))))
17138 month (string-to-number (match-string 1 ans))
17139 day (string-to-number (match-string 2 ans)))
17140 (setq year (org-small-year-to-year year))
17141 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17142 t nil ans)))
17143 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17144 ;; If there is a time with am/pm, and *no* time without it, we convert
17145 ;; so that matching will be successful.
17146 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17147 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17148 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17149 (setq hour (string-to-number (match-string 1 ans))
17150 minute (if (match-end 3)
17151 (string-to-number (match-string 3 ans))
17153 pm (equal ?p
17154 (string-to-char (downcase (match-string 4 ans)))))
17155 (if (and (= hour 12) (not pm))
17156 (setq hour 0)
17157 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17158 (setq ans (replace-match (format "%02d:%02d" hour minute)
17159 t t ans))))
17161 ;; Check if a time range is given as a duration
17162 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17163 (setq hour (string-to-number (match-string 1 ans))
17164 h2 (+ hour (string-to-number (match-string 3 ans)))
17165 minute (string-to-number (match-string 2 ans))
17166 m2 (+ minute (if (match-end 5) (string-to-number
17167 (match-string 5 ans))0)))
17168 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17169 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17170 t t ans)))
17172 ;; Check if there is a time range
17173 (when (boundp 'org-end-time-was-given)
17174 (setq org-time-was-given nil)
17175 (when (and (string-match org-plain-time-of-day-regexp ans)
17176 (match-end 8))
17177 (setq org-end-time-was-given (match-string 8 ans))
17178 (setq ans (concat (substring ans 0 (match-beginning 7))
17179 (substring ans (match-end 7))))))
17181 (setq tl (parse-time-string ans)
17182 day (or (nth 3 tl) (nth 3 org-defdecode))
17183 month
17184 (cond ((nth 4 tl))
17185 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17186 ;; Day was specified. Make sure DAY+MONTH
17187 ;; combination happens in the future.
17188 ((nth 3 tl)
17189 (setq futurep t)
17190 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17191 (nth 4 nowdecode)))
17192 (t (nth 4 org-defdecode)))
17193 year
17194 (cond ((and (not kill-year) (nth 5 tl)))
17195 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17196 ;; Month was guessed in the future and is at least
17197 ;; equal to NOWDECODE's. Fix year accordingly.
17198 (futurep
17199 (if (or (> month (nth 4 nowdecode))
17200 (>= day (nth 3 nowdecode)))
17201 (nth 5 nowdecode)
17202 (1+ (nth 5 nowdecode))))
17203 ;; Month was specified. Make sure MONTH+YEAR
17204 ;; combination happens in the future.
17205 ((nth 4 tl)
17206 (setq futurep t)
17207 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17208 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17209 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17210 (t (nth 5 nowdecode))))
17211 (t (nth 5 org-defdecode)))
17212 hour (or (nth 2 tl) (nth 2 org-defdecode))
17213 minute (or (nth 1 tl) (nth 1 org-defdecode))
17214 second (or (nth 0 tl) 0)
17215 wday (nth 6 tl))
17217 (when (and (eq org-read-date-prefer-future 'time)
17218 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17219 (equal day (nth 3 nowdecode))
17220 (equal month (nth 4 nowdecode))
17221 (equal year (nth 5 nowdecode))
17222 (nth 2 tl)
17223 (or (< (nth 2 tl) (nth 2 nowdecode))
17224 (and (= (nth 2 tl) (nth 2 nowdecode))
17225 (nth 1 tl)
17226 (< (nth 1 tl) (nth 1 nowdecode)))))
17227 (setq day (1+ day)
17228 futurep t))
17230 ;; Special date definitions below
17231 (cond
17232 (iso-week
17233 ;; There was an iso week
17234 (require 'cal-iso)
17235 (setq futurep nil)
17236 (setq year (or iso-year year)
17237 day (or iso-weekday wday 1)
17238 wday nil ; to make sure that the trigger below does not match
17239 iso-date (calendar-gregorian-from-absolute
17240 (calendar-iso-to-absolute
17241 (list iso-week day year))))
17242 ; FIXME: Should we also push ISO weeks into the future?
17243 ; (when (and org-read-date-prefer-future
17244 ; (not iso-year)
17245 ; (< (calendar-absolute-from-gregorian iso-date)
17246 ; (time-to-days (current-time))))
17247 ; (setq year (1+ year)
17248 ; iso-date (calendar-gregorian-from-absolute
17249 ; (calendar-iso-to-absolute
17250 ; (list iso-week day year)))))
17251 (setq month (car iso-date)
17252 year (nth 2 iso-date)
17253 day (nth 1 iso-date)))
17254 (deltan
17255 (setq futurep nil)
17256 (unless deltadef
17257 ;; Pass `current-time' result to `decode-time' (instead of
17258 ;; calling without arguments) so that only `current-time' has
17259 ;; to be overridden in tests.
17260 (let ((now (decode-time (current-time))))
17261 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17262 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17263 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17264 ((equal deltaw "m") (setq month (+ month deltan)))
17265 ((equal deltaw "y") (setq year (+ year deltan)))))
17266 ((and wday (not (nth 3 tl)))
17267 ;; Weekday was given, but no day, so pick that day in the week
17268 ;; on or after the derived date.
17269 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17270 (unless (equal wday wday1)
17271 (setq day (+ day (% (- wday wday1 -7) 7))))))
17272 (when (and (boundp 'org-time-was-given)
17273 (nth 2 tl))
17274 (setq org-time-was-given t))
17275 (when (< year 100) (setq year (+ 2000 year)))
17276 ;; Check of the date is representable
17277 (if org-read-date-force-compatible-dates
17278 (progn
17279 (when (< year 1970)
17280 (setq year 1970 org-read-date-analyze-forced-year t))
17281 (when (> year 2037)
17282 (setq year 2037 org-read-date-analyze-forced-year t)))
17283 (condition-case nil
17284 (ignore (encode-time second minute hour day month year))
17285 (error
17286 (setq year (nth 5 org-defdecode))
17287 (setq org-read-date-analyze-forced-year t))))
17288 (setq org-read-date-analyze-futurep futurep)
17289 (list second minute hour day month year)))
17291 (defvar parse-time-weekdays)
17292 (defun org-read-date-get-relative (s today default)
17293 "Check string S for special relative date string.
17294 TODAY and DEFAULT are internal times, for today and for a default.
17295 Return shift list (N what def-flag)
17296 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17297 N is the number of WHATs to shift.
17298 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17299 the DEFAULT date rather than TODAY."
17300 (require 'parse-time)
17301 (when (and
17302 (string-match
17303 (concat
17304 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17305 "\\([0-9]+\\)?"
17306 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17307 "\\([ \t]\\|$\\)") s)
17308 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17309 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17310 (string-to-char (substring (match-string 1 s) -1))
17311 ?+))
17312 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17313 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17314 (what (if (match-end 3) (match-string 3 s) "d"))
17315 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17316 (date (if rel default today))
17317 (wday (nth 6 (decode-time date)))
17318 delta)
17319 (if wday1
17320 (progn
17321 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17322 (when (= delta 0) (setq delta 7))
17323 (when (= dir ?-)
17324 (setq delta (- delta 7))
17325 (when (= delta 0) (setq delta -7)))
17326 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17327 (list delta "d" rel))
17328 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17330 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17331 "Turn a user-specified date into the internal representation.
17332 The internal representation needed by the calendar is (month day year).
17333 This is a wrapper to handle the brain-dead convention in calendar that
17334 user function argument order change dependent on argument order."
17335 (pcase calendar-date-style
17336 (`american (list arg1 arg2 arg3))
17337 (`european (list arg2 arg1 arg3))
17338 (`iso (list arg2 arg3 arg1))))
17340 (defun org-eval-in-calendar (form &optional keepdate)
17341 "Eval FORM in the calendar window and return to current window.
17342 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17343 (let ((sf (selected-frame))
17344 (sw (selected-window)))
17345 (select-window (get-buffer-window "*Calendar*" t))
17346 (eval form)
17347 (when (and (not keepdate) (calendar-cursor-to-date))
17348 (let* ((date (calendar-cursor-to-date))
17349 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17350 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17351 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17352 (select-window sw)
17353 (select-frame-set-input-focus sf)))
17355 (defun org-calendar-select ()
17356 "Return to `org-read-date' with the date currently selected.
17357 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17358 (interactive)
17359 (when (calendar-cursor-to-date)
17360 (let* ((date (calendar-cursor-to-date))
17361 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17362 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17363 (when (active-minibuffer-window) (exit-minibuffer))))
17365 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17366 "Insert a date stamp for the date given by the internal TIME.
17367 See `format-time-string' for the format of TIME.
17368 WITH-HM means use the stamp format that includes the time of the day.
17369 INACTIVE means use square brackets instead of angular ones, so that the
17370 stamp will not contribute to the agenda.
17371 PRE and POST are optional strings to be inserted before and after the
17372 stamp.
17373 The command returns the inserted time stamp."
17374 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17375 stamp)
17376 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17377 (insert-before-markers (or pre ""))
17378 (when (listp extra)
17379 (setq extra (car extra))
17380 (if (and (stringp extra)
17381 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17382 (setq extra (format "-%02d:%02d"
17383 (string-to-number (match-string 1 extra))
17384 (string-to-number (match-string 2 extra))))
17385 (setq extra nil)))
17386 (when extra
17387 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17388 (insert-before-markers (setq stamp (format-time-string fmt time)))
17389 (insert-before-markers (or post ""))
17390 (setq org-last-inserted-timestamp stamp)))
17392 (defun org-toggle-time-stamp-overlays ()
17393 "Toggle the use of custom time stamp formats."
17394 (interactive)
17395 (setq org-display-custom-times (not org-display-custom-times))
17396 (unless org-display-custom-times
17397 (let ((p (point-min)) (bmp (buffer-modified-p)))
17398 (while (setq p (next-single-property-change p 'display))
17399 (when (and (get-text-property p 'display)
17400 (eq (get-text-property p 'face) 'org-date))
17401 (remove-text-properties
17402 p (setq p (next-single-property-change p 'display))
17403 '(display t))))
17404 (set-buffer-modified-p bmp)))
17405 (org-restart-font-lock)
17406 (setq org-table-may-need-update t)
17407 (if org-display-custom-times
17408 (message "Time stamps are overlaid with custom format")
17409 (message "Time stamp overlays removed")))
17411 (defun org-display-custom-time (beg end)
17412 "Overlay modified time stamp format over timestamp between BEG and END."
17413 (let* ((ts (buffer-substring beg end))
17414 t1 w1 with-hm tf time str w2 (off 0))
17415 (save-match-data
17416 (setq t1 (org-parse-time-string ts t))
17417 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17418 (setq off (- (match-end 0) (match-beginning 0)))))
17419 (setq end (- end off))
17420 (setq w1 (- end beg)
17421 with-hm (and (nth 1 t1) (nth 2 t1))
17422 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17423 time (org-fix-decoded-time t1)
17424 str (org-add-props
17425 (format-time-string
17426 (substring tf 1 -1) (apply 'encode-time time))
17427 nil 'mouse-face 'highlight)
17428 w2 (length str))
17429 (unless (= w2 w1)
17430 (add-text-properties (1+ beg) (+ 2 beg)
17431 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17432 (put-text-property beg end 'display str)))
17434 (defun org-fix-decoded-time (time)
17435 "Set 0 instead of nil for the first 6 elements of time.
17436 Don't touch the rest."
17437 (let ((n 0))
17438 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17440 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17441 "Difference between TIMESTAMP-STRING and now in days.
17442 If SECONDS is non-nil, return the difference in seconds."
17443 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17444 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17445 (funcall fdiff (current-time)))))
17447 (defun org-deadline-close-p (timestamp-string &optional ndays)
17448 "Is the time in TIMESTAMP-STRING close to the current date?"
17449 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17450 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17451 (not (org-entry-is-done-p))))
17453 (defun org-get-wdays (ts &optional delay zero-delay)
17454 "Get the deadline lead time appropriate for timestring TS.
17455 When DELAY is non-nil, get the delay time for scheduled items
17456 instead of the deadline lead time. When ZERO-DELAY is non-nil
17457 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17458 don't try to find the delay cookie in the scheduled timestamp."
17459 (let ((tv (if delay org-scheduled-delay-days
17460 org-deadline-warning-days)))
17461 (cond
17462 ((or (and delay (< tv 0))
17463 (and delay zero-delay (<= tv 0))
17464 (and (not delay) (<= tv 0)))
17465 ;; Enforce this value no matter what
17466 (- tv))
17467 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17468 ;; lead time is specified.
17469 (floor (* (string-to-number (match-string 1 ts))
17470 (cdr (assoc (match-string 2 ts)
17471 '(("d" . 1) ("w" . 7)
17472 ("m" . 30.4) ("y" . 365.25)
17473 ("h" . 0.041667)))))))
17474 ;; go for the default.
17475 (t tv))))
17477 (defun org-calendar-select-mouse (ev)
17478 "Return to `org-read-date' with the date currently selected.
17479 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17480 (interactive "e")
17481 (mouse-set-point ev)
17482 (when (calendar-cursor-to-date)
17483 (let* ((date (calendar-cursor-to-date))
17484 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17485 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17486 (when (active-minibuffer-window) (exit-minibuffer))))
17488 (defun org-check-deadlines (ndays)
17489 "Check if there are any deadlines due or past due.
17490 A deadline is considered due if it happens within `org-deadline-warning-days'
17491 days from today's date. If the deadline appears in an entry marked DONE,
17492 it is not shown. A numeric prefix argument NDAYS can be used to test that
17493 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17494 are shown."
17495 (interactive "P")
17496 (let* ((org-warn-days
17497 (cond
17498 ((equal ndays '(4)) 100000)
17499 (ndays (prefix-numeric-value ndays))
17500 (t (abs org-deadline-warning-days))))
17501 (case-fold-search nil)
17502 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17503 (callback
17504 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17505 (message "%d deadlines past-due or due within %d days"
17506 (org-occur regexp nil callback)
17507 org-warn-days)))
17509 (defsubst org-re-timestamp (type)
17510 "Return a regexp for timestamp TYPE.
17511 Allowed values for TYPE are:
17513 all: all timestamps
17514 active: only active timestamps (<...>)
17515 inactive: only inactive timestamps ([...])
17516 scheduled: only scheduled timestamps
17517 deadline: only deadline timestamps
17518 closed: only closed time-stamps
17520 When TYPE is nil, fall back on returning a regexp that matches
17521 both scheduled and deadline timestamps."
17522 (cl-case type
17523 (all org-ts-regexp-both)
17524 (active org-ts-regexp)
17525 (inactive org-ts-regexp-inactive)
17526 (scheduled org-scheduled-time-regexp)
17527 (deadline org-deadline-time-regexp)
17528 (closed org-closed-time-regexp)
17529 (otherwise
17530 (concat "\\<"
17531 (regexp-opt (list org-deadline-string org-scheduled-string))
17532 " *<\\([^>]+\\)>"))))
17534 (defun org-check-before-date (d)
17535 "Check if there are deadlines or scheduled entries before date D."
17536 (interactive (list (org-read-date)))
17537 (let* ((case-fold-search nil)
17538 (regexp (org-re-timestamp org-ts-type))
17539 (ts-type org-ts-type)
17540 (callback
17541 (lambda ()
17542 (let ((match (match-string 1)))
17543 (and (if (memq ts-type '(active inactive all))
17544 (eq (org-element-type (save-excursion
17545 (backward-char)
17546 (org-element-context)))
17547 'timestamp)
17548 (org-at-planning-p))
17549 (time-less-p
17550 (org-time-string-to-time match)
17551 (org-time-string-to-time d)))))))
17552 (message "%d entries before %s"
17553 (org-occur regexp nil callback)
17554 d)))
17556 (defun org-check-after-date (d)
17557 "Check if there are deadlines or scheduled entries after date D."
17558 (interactive (list (org-read-date)))
17559 (let* ((case-fold-search nil)
17560 (regexp (org-re-timestamp org-ts-type))
17561 (ts-type org-ts-type)
17562 (callback
17563 (lambda ()
17564 (let ((match (match-string 1)))
17565 (and (if (memq ts-type '(active inactive all))
17566 (eq (org-element-type (save-excursion
17567 (backward-char)
17568 (org-element-context)))
17569 'timestamp)
17570 (org-at-planning-p))
17571 (not (time-less-p
17572 (org-time-string-to-time match)
17573 (org-time-string-to-time d))))))))
17574 (message "%d entries after %s"
17575 (org-occur regexp nil callback)
17576 d)))
17578 (defun org-check-dates-range (start-date end-date)
17579 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17580 (interactive (list (org-read-date nil nil nil "Range starts")
17581 (org-read-date nil nil nil "Range end")))
17582 (let ((case-fold-search nil)
17583 (regexp (org-re-timestamp org-ts-type))
17584 (callback
17585 (let ((type org-ts-type))
17586 (lambda ()
17587 (let ((match (match-string 1)))
17588 (and
17589 (if (memq type '(active inactive all))
17590 (eq (org-element-type (save-excursion
17591 (backward-char)
17592 (org-element-context)))
17593 'timestamp)
17594 (org-at-planning-p))
17595 (not (time-less-p
17596 (org-time-string-to-time match)
17597 (org-time-string-to-time start-date)))
17598 (time-less-p
17599 (org-time-string-to-time match)
17600 (org-time-string-to-time end-date))))))))
17601 (message "%d entries between %s and %s"
17602 (org-occur regexp nil callback) start-date end-date)))
17604 (defun org-evaluate-time-range (&optional to-buffer)
17605 "Evaluate a time range by computing the difference between start and end.
17606 Normally the result is just printed in the echo area, but with prefix arg
17607 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17608 If the time range is actually in a table, the result is inserted into the
17609 next column.
17610 For time difference computation, a year is assumed to be exactly 365
17611 days in order to avoid rounding problems."
17612 (interactive "P")
17614 (org-clock-update-time-maybe)
17615 (save-excursion
17616 (unless (org-at-date-range-p t)
17617 (goto-char (point-at-bol))
17618 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17619 (unless (org-at-date-range-p t)
17620 (user-error "Not at a time-stamp range, and none found in current line")))
17621 (let* ((ts1 (match-string 1))
17622 (ts2 (match-string 2))
17623 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17624 (match-end (match-end 0))
17625 (time1 (org-time-string-to-time ts1))
17626 (time2 (org-time-string-to-time ts2))
17627 (t1 (float-time time1))
17628 (t2 (float-time time2))
17629 (diff (abs (- t2 t1)))
17630 (negative (< (- t2 t1) 0))
17631 ;; (ys (floor (* 365 24 60 60)))
17632 (ds (* 24 60 60))
17633 (hs (* 60 60))
17634 (fy "%dy %dd %02d:%02d")
17635 (fy1 "%dy %dd")
17636 (fd "%dd %02d:%02d")
17637 (fd1 "%dd")
17638 (fh "%02d:%02d")
17639 y d h m align)
17640 (if havetime
17641 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17643 d (floor (/ diff ds)) diff (mod diff ds)
17644 h (floor (/ diff hs)) diff (mod diff hs)
17645 m (floor (/ diff 60)))
17646 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17648 d (floor (+ (/ diff ds) 0.5))
17649 h 0 m 0))
17650 (if (not to-buffer)
17651 (message "%s" (org-make-tdiff-string y d h m))
17652 (if (org-at-table-p)
17653 (progn
17654 (goto-char match-end)
17655 (setq align t)
17656 (and (looking-at " *|") (goto-char (match-end 0))))
17657 (goto-char match-end))
17658 (when (looking-at
17659 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17660 (replace-match ""))
17661 (when negative (insert " -"))
17662 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17663 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17664 (insert " " (format fh h m))))
17665 (when align (org-table-align))
17666 (message "Time difference inserted")))))
17668 (defun org-make-tdiff-string (y d h m)
17669 (let ((fmt "")
17670 (l nil))
17671 (when (> y 0)
17672 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17673 (push y l))
17674 (when (> d 0)
17675 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17676 (push d l))
17677 (when (> h 0)
17678 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17679 (push h l))
17680 (when (> m 0)
17681 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17682 (push m l))
17683 (apply 'format fmt (nreverse l))))
17685 (defun org-time-string-to-time (s &optional buffer pos)
17686 "Convert a timestamp string into internal time."
17687 (condition-case errdata
17688 (apply 'encode-time (org-parse-time-string s))
17689 (error (error "Bad timestamp `%s'%s\nError was: %s"
17690 s (if (not (and buffer pos))
17692 (format-message " at %d in buffer `%s'" pos buffer))
17693 (cdr errdata)))))
17695 (defun org-time-string-to-seconds (s)
17696 "Convert a timestamp string to a number of seconds."
17697 (float-time (org-time-string-to-time s)))
17699 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17701 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17702 "Convert time stamp S to an absolute day number.
17704 If DAYNR in non-nil, and there is a specifier for a cyclic time
17705 stamp, get the closest date to DAYNR. If PREFER is
17706 `past' (respectively `future') return a date past (respectively
17707 after) or equal to DAYNR.
17709 POS is the location of time stamp S, as a buffer position in
17710 BUFFER.
17712 Diary sexp timestamps are matched against DAYNR, when non-nil.
17713 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17714 signaled."
17715 (cond
17716 ((string-match "\\`%%\\((.*)\\)" s)
17717 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17718 ;; only able to match individual dates. If it fails, raise an
17719 ;; error.
17720 (if (and daynr
17721 (org-diary-sexp-entry
17722 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17723 daynr
17724 (signal 'org-diary-sexp-no-match (list s))))
17725 (daynr (org-closest-date s daynr prefer))
17726 (t (time-to-days
17727 (condition-case errdata
17728 (apply #'encode-time (org-parse-time-string s))
17729 (error (error "Bad timestamp `%s'%s\nError was: %s"
17731 (if (not (and buffer pos)) ""
17732 (format-message " at %d in buffer `%s'" pos buffer))
17733 (cdr errdata))))))))
17735 (defun org-days-to-iso-week (days)
17736 "Return the iso week number."
17737 (require 'cal-iso)
17738 (car (calendar-iso-from-absolute days)))
17740 (defun org-small-year-to-year (year)
17741 "Convert 2-digit years into 4-digit years.
17742 YEAR is expanded into one of the 30 next years, if possible, or
17743 into a past one. Any year larger than 99 is returned unchanged."
17744 (if (>= year 100) year
17745 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17746 (century (/ current 100))
17747 (offset (- year (% current 100))))
17748 (cond ((> offset 30) (+ (* (1- century) 100) year))
17749 ((> offset -70) (+ (* century 100) year))
17750 (t (+ (* (1+ century) 100) year))))))
17752 (defun org-time-from-absolute (d)
17753 "Return the time corresponding to date D.
17754 D may be an absolute day number, or a calendar-type list (month day year)."
17755 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17756 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17758 (defvar org-agenda-current-date)
17759 (defun org-calendar-holiday ()
17760 "List of holidays, for Diary display in Org mode."
17761 (require 'holidays)
17762 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17763 (and hl (mapconcat #'identity hl "; "))))
17765 (defun org-diary-sexp-entry (sexp entry d)
17766 "Process a SEXP diary ENTRY for date D."
17767 (require 'diary-lib)
17768 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17769 ;; dynamically.
17770 (let* ((sexp `(let ((entry ,entry)
17771 (date ',d))
17772 ,(car (read-from-string sexp))))
17773 (result (if calendar-debug-sexp (eval sexp)
17774 (condition-case nil
17775 (eval sexp)
17776 (error
17777 (beep)
17778 (message "Bad sexp at line %d in %s: %s"
17779 (org-current-line)
17780 (buffer-file-name) sexp)
17781 (sleep-for 2))))))
17782 (cond ((stringp result) (split-string result "; "))
17783 ((and (consp result)
17784 (not (consp (cdr result)))
17785 (stringp (cdr result))) (cdr result))
17786 ((and (consp result)
17787 (stringp (car result))) result)
17788 (result entry))))
17790 (defun org-diary-to-ical-string (frombuf)
17791 "Get iCalendar entries from diary entries in buffer FROMBUF.
17792 This uses the icalendar.el library."
17793 (let* ((tmpdir temporary-file-directory)
17794 (tmpfile (make-temp-name
17795 (expand-file-name "orgics" tmpdir)))
17796 buf rtn b e)
17797 (with-current-buffer frombuf
17798 (icalendar-export-region (point-min) (point-max) tmpfile)
17799 (setq buf (find-buffer-visiting tmpfile))
17800 (set-buffer buf)
17801 (goto-char (point-min))
17802 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17803 (setq b (match-beginning 0)))
17804 (goto-char (point-max))
17805 (when (re-search-backward "^END:VEVENT" nil t)
17806 (setq e (match-end 0)))
17807 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17808 (kill-buffer buf)
17809 (delete-file tmpfile)
17810 rtn))
17812 (defun org-closest-date (start current prefer)
17813 "Return closest date to CURRENT starting from START.
17815 CURRENT and START are both time stamps.
17817 When PREFER is `past', return a date that is either CURRENT or
17818 past. When PREFER is `future', return a date that is either
17819 CURRENT or future.
17821 Only time stamps with a repeater are modified. Any other time
17822 stamp stay unchanged. In any case, return value is an absolute
17823 day number."
17824 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17825 ;; No repeater. Do not shift time stamp.
17826 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17827 (let ((value (string-to-number (match-string 1 start)))
17828 (type (match-string 2 start)))
17829 (if (= 0 value)
17830 ;; Repeater with a 0-value is considered as void.
17831 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17832 (let* ((base (org-date-to-gregorian start))
17833 (target (org-date-to-gregorian current))
17834 (sday (calendar-absolute-from-gregorian base))
17835 (cday (calendar-absolute-from-gregorian target))
17836 n1 n2)
17837 ;; If START is already past CURRENT, just return START.
17838 (if (<= cday sday) sday
17839 ;; Compute closest date before (N1) and closest date past
17840 ;; (N2) CURRENT.
17841 (pcase type
17842 ("h"
17843 (let ((missing-hours
17844 (mod (+ (- (* 24 (- cday sday))
17845 (nth 2 (org-parse-time-string start)))
17846 org-extend-today-until)
17847 value)))
17848 (setf n1 (if (= missing-hours 0) cday
17849 (- cday (1+ (/ missing-hours 24)))))
17850 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17851 ((or "d" "w")
17852 (let ((value (if (equal type "w") (* 7 value) value)))
17853 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17854 (setf n2 (+ n1 value))))
17855 ("m"
17856 (let* ((add-months
17857 (lambda (d n)
17858 ;; Add N months to gregorian date D, i.e.,
17859 ;; a list (MONTH DAY YEAR). Return a valid
17860 ;; gregorian date.
17861 (let ((m (+ (nth 0 d) n)))
17862 (list (mod m 12)
17863 (nth 1 d)
17864 (+ (/ m 12) (nth 2 d))))))
17865 (months ; Complete months to TARGET.
17866 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17867 (- (nth 0 target) (nth 0 base))
17868 ;; If START's day is greater than
17869 ;; TARGET's, remove incomplete month.
17870 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17871 value)
17872 value))
17873 (before (funcall add-months base months)))
17874 (setf n1 (calendar-absolute-from-gregorian before))
17875 (setf n2
17876 (calendar-absolute-from-gregorian
17877 (funcall add-months before value)))))
17879 (let* ((d (nth 1 base))
17880 (m (nth 0 base))
17881 (y (nth 2 base))
17882 (years ; Complete years to TARGET.
17883 (* (/ (- (nth 2 target)
17885 ;; If START's month and day are
17886 ;; greater than TARGET's, remove
17887 ;; incomplete year.
17888 (if (or (> (nth 0 target) m)
17889 (and (= (nth 0 target) m)
17890 (> (nth 1 target) d)))
17893 value)
17894 value))
17895 (before (list m d (+ y years))))
17896 (setf n1 (calendar-absolute-from-gregorian before))
17897 (setf n2 (calendar-absolute-from-gregorian
17898 (list m d (+ (nth 2 before) value)))))))
17899 ;; Handle PREFER parameter, if any.
17900 (cond
17901 ((eq prefer 'past) (if (= cday n2) n2 n1))
17902 ((eq prefer 'future) (if (= cday n1) n1 n2))
17903 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17905 (defun org-date-to-gregorian (d)
17906 "Turn any specification of date D into a Gregorian date for the calendar."
17907 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17908 ((and (listp d) (= (length d) 3)) d)
17909 ((stringp d)
17910 (let ((d (org-parse-time-string d)))
17911 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17912 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17914 (defun org-parse-time-string (s &optional nodefault zone)
17915 "Parse the standard Org time string.
17917 This should be a lot faster than the normal `parse-time-string'.
17919 If time is not given, defaults to 0:00. However, with optional
17920 NODEFAULT, hour and minute fields will be nil if not given.
17922 The optional ZONE is omitted or nil for Emacs local time, t for
17923 Universal Time, ‘wall’ for system wall clock time, or a string as
17924 in the TZ environment variable."
17925 (cond ((string-match org-ts-regexp0 s)
17926 (list 0
17927 (when (or (match-beginning 8) (not nodefault))
17928 (string-to-number (or (match-string 8 s) "0")))
17929 (when (or (match-beginning 7) (not nodefault))
17930 (string-to-number (or (match-string 7 s) "0")))
17931 (string-to-number (match-string 4 s))
17932 (string-to-number (match-string 3 s))
17933 (string-to-number (match-string 2 s))
17934 nil nil zone))
17935 ((string-match "^<[^>]+>$" s)
17936 ;; FIXME: `decode-time' needs to be called with ZONE as its
17937 ;; second argument. However, this requires at least Emacs
17938 ;; 25.1. We can do it when we switch to this version as our
17939 ;; minimal requirement.
17940 (decode-time (seconds-to-time (org-matcher-time s))))
17941 (t (error "Not a standard Org time string: %s" s))))
17943 (defun org-timestamp-up (&optional arg)
17944 "Increase the date item at the cursor by one.
17945 If the cursor is on the year, change the year. If it is on the month,
17946 the day or the time, change that.
17947 With prefix ARG, change by that many units."
17948 (interactive "p")
17949 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17951 (defun org-timestamp-down (&optional arg)
17952 "Decrease the date item at the cursor by one.
17953 If the cursor is on the year, change the year. If it is on the month,
17954 the day or the time, change that.
17955 With prefix ARG, change by that many units."
17956 (interactive "p")
17957 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17959 (defun org-timestamp-up-day (&optional arg)
17960 "Increase the date in the time stamp by one day.
17961 With prefix ARG, change that many days."
17962 (interactive "p")
17963 (if (and (not (org-at-timestamp-p t))
17964 (org-at-heading-p))
17965 (org-todo 'up)
17966 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17968 (defun org-timestamp-down-day (&optional arg)
17969 "Decrease the date in the time stamp by one day.
17970 With prefix ARG, change that many days."
17971 (interactive "p")
17972 (if (and (not (org-at-timestamp-p t))
17973 (org-at-heading-p))
17974 (org-todo 'down)
17975 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17977 (defun org-at-timestamp-p (&optional inactive-ok)
17978 "Non-nil if point is inside a timestamp.
17980 When optional argument INACTIVE-OK is non-nil, also consider
17981 inactive timestamps.
17983 When this function returns a non-nil value, match data is set
17984 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17985 INACTIVE-OK."
17986 (interactive)
17987 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17988 (pos (point))
17989 (ans (or (looking-at tsr)
17990 (save-excursion
17991 (skip-chars-backward "^[<\n\r\t")
17992 (when (> (point) (point-min)) (backward-char 1))
17993 (and (looking-at tsr)
17994 (> (- (match-end 0) pos) -1))))))
17995 (and ans
17996 (boundp 'org-ts-what)
17997 (setq org-ts-what
17998 (cond
17999 ((= pos (match-beginning 0)) 'bracket)
18000 ;; Point is considered to be "on the bracket" whether
18001 ;; it's really on it or right after it.
18002 ((= pos (1- (match-end 0))) 'bracket)
18003 ((= pos (match-end 0)) 'after)
18004 ((org-pos-in-match-range pos 2) 'year)
18005 ((org-pos-in-match-range pos 3) 'month)
18006 ((org-pos-in-match-range pos 7) 'hour)
18007 ((org-pos-in-match-range pos 8) 'minute)
18008 ((or (org-pos-in-match-range pos 4)
18009 (org-pos-in-match-range pos 5)) 'day)
18010 ((and (> pos (or (match-end 8) (match-end 5)))
18011 (< pos (match-end 0)))
18012 (- pos (or (match-end 8) (match-end 5))))
18013 (t 'day))))
18014 ans))
18016 (defun org-toggle-timestamp-type ()
18017 "Toggle the type (<active> or [inactive]) of a time stamp."
18018 (interactive)
18019 (when (org-at-timestamp-p t)
18020 (let ((beg (match-beginning 0)) (end (match-end 0))
18021 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18022 (save-excursion
18023 (goto-char beg)
18024 (while (re-search-forward "[][<>]" end t)
18025 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18026 t t)))
18027 (message "Timestamp is now %sactive"
18028 (if (equal (char-after beg) ?<) "" "in")))))
18030 (defun org-at-clock-log-p nil
18031 "Is the cursor on the clock log line?"
18032 (save-excursion
18033 (beginning-of-line)
18034 (looking-at org-clock-line-re)))
18036 (defvar org-clock-history) ; defined in org-clock.el
18037 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18038 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18039 "Change the date in the time stamp at point.
18040 The date will be changed by N times WHAT. WHAT can be `day', `month',
18041 `year', `minute', `second'. If WHAT is not given, the cursor position
18042 in the timestamp determines what will be changed.
18043 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18044 (let ((origin (point)) origin-cat
18045 with-hm inactive
18046 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18047 org-ts-what
18048 extra rem
18049 ts time time0 fixnext clrgx)
18050 (unless (org-at-timestamp-p t)
18051 (user-error "Not at a timestamp"))
18052 (if (and (not what) (eq org-ts-what 'bracket))
18053 (org-toggle-timestamp-type)
18054 ;; Point isn't on brackets. Remember the part of the time-stamp
18055 ;; the point was in. Indeed, size of time-stamps may change,
18056 ;; but point must be kept in the same category nonetheless.
18057 (setq origin-cat org-ts-what)
18058 (when (and (not what) (not (eq org-ts-what 'day))
18059 org-display-custom-times
18060 (get-text-property (point) 'display)
18061 (not (get-text-property (1- (point)) 'display)))
18062 (setq org-ts-what 'day))
18063 (setq org-ts-what (or what org-ts-what)
18064 inactive (= (char-after (match-beginning 0)) ?\[)
18065 ts (match-string 0))
18066 (replace-match "")
18067 (when (string-match
18068 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18070 (setq extra (match-string 1 ts))
18071 (when suppress-tmp-delay
18072 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18073 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18074 (setq with-hm t))
18075 (setq time0 (org-parse-time-string ts))
18076 (when (and updown
18077 (eq org-ts-what 'minute)
18078 (not current-prefix-arg))
18079 ;; This looks like s-up and s-down. Change by one rounding step.
18080 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18081 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18082 (setcar (cdr time0) (+ (nth 1 time0)
18083 (if (> n 0) (- rem) (- dm rem))))))
18084 (setq time
18085 (apply #'encode-time
18086 (or (car time0) 0)
18087 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18088 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18089 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18090 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18091 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18092 (nthcdr 6 time0)))
18093 (when (and (member org-ts-what '(hour minute))
18094 extra
18095 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18096 (setq extra (org-modify-ts-extra
18097 extra
18098 (if (eq org-ts-what 'hour) 2 5)
18099 n dm)))
18100 (when (integerp org-ts-what)
18101 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18102 (when (eq what 'calendar)
18103 (let ((cal-date (org-get-date-from-calendar)))
18104 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18105 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18106 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18107 (setcar time0 (or (car time0) 0))
18108 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18109 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18110 (setq time (apply 'encode-time time0))))
18111 ;; Insert the new time-stamp, and ensure point stays in the same
18112 ;; category as before (i.e. not after the last position in that
18113 ;; category).
18114 (let ((pos (point)))
18115 ;; Stay before inserted string. `save-excursion' is of no use.
18116 (setq org-last-changed-timestamp
18117 (org-insert-time-stamp time with-hm inactive nil nil extra))
18118 (goto-char pos))
18119 (save-match-data
18120 (looking-at org-ts-regexp3)
18121 (goto-char
18122 (pcase origin-cat
18123 ;; `day' category ends before `hour' if any, or at the end
18124 ;; of the day name.
18125 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18126 (`hour (min (match-end 7) origin))
18127 (`minute (min (1- (match-end 8)) origin))
18128 ((pred integerp) (min (1- (match-end 0)) origin))
18129 ;; Point was right after the time-stamp. However, the
18130 ;; time-stamp length might have changed, so refer to
18131 ;; (match-end 0) instead.
18132 (`after (match-end 0))
18133 ;; `year' and `month' have both fixed size: point couldn't
18134 ;; have moved into another part.
18135 (_ origin))))
18136 ;; Update clock if on a CLOCK line.
18137 (org-clock-update-time-maybe)
18138 ;; Maybe adjust the closest clock in `org-clock-history'
18139 (when org-clock-adjust-closest
18140 (if (not (and (org-at-clock-log-p)
18141 (< 1 (length (delq nil (mapcar 'marker-position
18142 org-clock-history))))))
18143 (message "No clock to adjust")
18144 (cond ((save-excursion ; fix previous clock?
18145 (re-search-backward org-ts-regexp0 nil t)
18146 (looking-back (concat org-clock-string " \\[")
18147 (line-beginning-position)))
18148 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18149 ((save-excursion ; fix next clock?
18150 (re-search-backward org-ts-regexp0 nil t)
18151 (looking-at (concat org-ts-regexp0 "\\] =>")))
18152 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18153 (save-window-excursion
18154 ;; Find closest clock to point, adjust the previous/next one in history
18155 (let* ((p (save-excursion (org-back-to-heading t)))
18156 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18157 (clfixnth
18158 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18159 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18160 (if (not clfixpos)
18161 (message "No clock to adjust")
18162 (save-excursion
18163 (org-goto-marker-or-bmk clfixpos)
18164 (org-show-subtree)
18165 (when (re-search-forward clrgx nil t)
18166 (goto-char (match-beginning 1))
18167 (let (org-clock-adjust-closest)
18168 (org-timestamp-change n org-ts-what updown))
18169 (message "Clock adjusted in %s for heading: %s"
18170 (file-name-nondirectory (buffer-file-name))
18171 (org-get-heading t t)))))))))
18172 ;; Try to recenter the calendar window, if any.
18173 (when (and org-calendar-follow-timestamp-change
18174 (get-buffer-window "*Calendar*" t)
18175 (memq org-ts-what '(day month year)))
18176 (org-recenter-calendar (time-to-days time))))))
18178 (defun org-modify-ts-extra (s pos n dm)
18179 "Change the different parts of the lead-time and repeat fields in timestamp."
18180 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18181 ng h m new rem)
18182 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18183 (cond
18184 ((or (org-pos-in-match-range pos 2)
18185 (org-pos-in-match-range pos 3))
18186 (setq m (string-to-number (match-string 3 s))
18187 h (string-to-number (match-string 2 s)))
18188 (if (org-pos-in-match-range pos 2)
18189 (setq h (+ h n))
18190 (setq n (* dm (with-no-warnings (signum n))))
18191 (unless (= 0 (setq rem (% m dm)))
18192 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18193 (setq m (+ m n)))
18194 (when (< m 0) (setq m (+ m 60) h (1- h)))
18195 (when (> m 59) (setq m (- m 60) h (1+ h)))
18196 (setq h (mod h 24))
18197 (setq ng 1 new (format "-%02d:%02d" h m)))
18198 ((org-pos-in-match-range pos 6)
18199 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18200 ((org-pos-in-match-range pos 5)
18201 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18203 ((org-pos-in-match-range pos 9)
18204 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18205 ((org-pos-in-match-range pos 8)
18206 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18208 (when ng
18209 (setq s (concat
18210 (substring s 0 (match-beginning ng))
18212 (substring s (match-end ng))))))
18215 (defun org-recenter-calendar (d)
18216 "If the calendar is visible, recenter it to date D."
18217 (let ((cwin (get-buffer-window "*Calendar*" t)))
18218 (when cwin
18219 (let ((calendar-move-hook nil))
18220 (with-selected-window cwin
18221 (calendar-goto-date
18222 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18224 (defun org-goto-calendar (&optional arg)
18225 "Go to the Emacs calendar at the current date.
18226 If there is a time stamp in the current line, go to that date.
18227 A prefix ARG can be used to force the current date."
18228 (interactive "P")
18229 (let ((tsr org-ts-regexp) diff
18230 (calendar-move-hook nil)
18231 (calendar-view-holidays-initially-flag nil)
18232 (calendar-view-diary-initially-flag nil))
18233 (when (or (org-at-timestamp-p)
18234 (save-excursion
18235 (beginning-of-line 1)
18236 (looking-at (concat ".*" tsr))))
18237 (let ((d1 (time-to-days (current-time)))
18238 (d2 (time-to-days
18239 (org-time-string-to-time (match-string 1)))))
18240 (setq diff (- d2 d1))))
18241 (calendar)
18242 (calendar-goto-today)
18243 (when (and diff (not arg)) (calendar-forward-day diff))))
18245 (defun org-get-date-from-calendar ()
18246 "Return a list (month day year) of date at point in calendar."
18247 (with-current-buffer "*Calendar*"
18248 (save-match-data
18249 (calendar-cursor-to-date))))
18251 (defun org-date-from-calendar ()
18252 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18253 If there is already a time stamp at the cursor position, update it."
18254 (interactive)
18255 (if (org-at-timestamp-p t)
18256 (org-timestamp-change 0 'calendar)
18257 (let ((cal-date (org-get-date-from-calendar)))
18258 (org-insert-time-stamp
18259 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18261 (defcustom org-effort-durations
18262 `(("min" . 1)
18263 ("h" . 60)
18264 ("d" . ,(* 60 8))
18265 ("w" . ,(* 60 8 5))
18266 ("m" . ,(* 60 8 5 4))
18267 ("y" . ,(* 60 8 5 40)))
18268 "Conversion factor to minutes for an effort modifier.
18270 Each entry has the form (MODIFIER . MINUTES).
18272 In an effort string, a number followed by MODIFIER is multiplied
18273 by the specified number of MINUTES to obtain an effort in
18274 minutes.
18276 For example, if the value of this variable is ((\"hours\" . 60)), then an
18277 effort string \"2hours\" is equivalent to 120 minutes."
18278 :group 'org-agenda
18279 :version "26.1"
18280 :package-version '(Org . "8.3")
18281 :type '(alist :key-type (string :tag "Modifier")
18282 :value-type (number :tag "Minutes")))
18284 (defun org-minutes-to-clocksum-string (m)
18285 "Format number of minutes as a clocksum string.
18286 The format is determined by `org-time-clocksum-format',
18287 `org-time-clocksum-use-fractional' and
18288 `org-time-clocksum-fractional-format' and
18289 `org-time-clocksum-use-effort-durations'."
18290 (let ((clocksum "")
18291 (m (round m)) ; Don't allow fractions of minutes
18292 h d w mo y fmt n)
18293 (setq h (if org-time-clocksum-use-effort-durations
18294 (cdr (assoc "h" org-effort-durations)) 60)
18295 d (if org-time-clocksum-use-effort-durations
18296 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18297 w (if org-time-clocksum-use-effort-durations
18298 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18299 mo (if org-time-clocksum-use-effort-durations
18300 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18301 y (if org-time-clocksum-use-effort-durations
18302 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18303 ;; fractional format
18304 (if org-time-clocksum-use-fractional
18305 (cond
18306 ;; single format string
18307 ((stringp org-time-clocksum-fractional-format)
18308 (format org-time-clocksum-fractional-format (/ m (float h))))
18309 ;; choice of fractional formats for different time units
18310 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18311 (> (/ (truncate m) (* y d h)) 0))
18312 (format fmt (/ m (* y d (float h)))))
18313 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18314 (> (/ (truncate m) (* mo d h)) 0))
18315 (format fmt (/ m (* mo d (float h)))))
18316 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18317 (> (/ (truncate m) (* w d h)) 0))
18318 (format fmt (/ m (* w d (float h)))))
18319 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18320 (> (/ (truncate m) (* d h)) 0))
18321 (format fmt (/ m (* d (float h)))))
18322 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18323 (> (/ (truncate m) h) 0))
18324 (format fmt (/ m (float h))))
18325 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18326 (format fmt m))
18327 ;; fall back to smallest time unit with a format
18328 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18329 (format fmt (/ m (float h))))
18330 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18331 (format fmt (/ m (* d (float h)))))
18332 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18333 (format fmt (/ m (* w d (float h)))))
18334 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18335 (format fmt (/ m (* mo d (float h)))))
18336 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18337 (format fmt (/ m (* y d (float h))))))
18338 ;; standard (non-fractional) format, with single format string
18339 (if (stringp org-time-clocksum-format)
18340 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18341 ;; separate formats components
18342 (and (setq fmt (plist-get org-time-clocksum-format :years))
18343 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18344 (plist-get org-time-clocksum-format :require-years))
18345 (setq clocksum (concat clocksum (format fmt n))
18346 m (- m (* n y d h))))
18347 (and (setq fmt (plist-get org-time-clocksum-format :months))
18348 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18349 (plist-get org-time-clocksum-format :require-months))
18350 (setq clocksum (concat clocksum (format fmt n))
18351 m (- m (* n mo d h))))
18352 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18353 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18354 (plist-get org-time-clocksum-format :require-weeks))
18355 (setq clocksum (concat clocksum (format fmt n))
18356 m (- m (* n w d h))))
18357 (and (setq fmt (plist-get org-time-clocksum-format :days))
18358 (or (> (setq n (/ (truncate m) (* d h))) 0)
18359 (plist-get org-time-clocksum-format :require-days))
18360 (setq clocksum (concat clocksum (format fmt n))
18361 m (- m (* n d h))))
18362 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18363 (or (> (setq n (/ (truncate m) h)) 0)
18364 (plist-get org-time-clocksum-format :require-hours))
18365 (setq clocksum (concat clocksum (format fmt n))
18366 m (- m (* n h))))
18367 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18368 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18369 (setq clocksum (concat clocksum (format fmt m))))
18370 ;; return formatted time duration
18371 clocksum))))
18373 (defun org-hours-to-clocksum-string (n)
18374 (org-minutes-to-clocksum-string (* n 60)))
18376 (defun org-hh:mm-string-to-minutes (s)
18377 "Convert a string H:MM to a number of minutes.
18378 If the string is just a number, interpret it as minutes.
18379 In fact, the first hh:mm or number in the string will be taken,
18380 there can be extra stuff in the string.
18381 If no number is found, the return value is 0."
18382 (cond
18383 ((integerp s) s)
18384 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18385 (+ (* (string-to-number (match-string 1 s)) 60)
18386 (string-to-number (match-string 2 s))))
18387 ((string-match "\\([0-9]+\\)" s)
18388 (string-to-number (match-string 1 s)))
18389 (t 0)))
18391 (defcustom org-image-actual-width t
18392 "Should we use the actual width of images when inlining them?
18394 When set to t, always use the image width.
18396 When set to a number, use imagemagick (when available) to set
18397 the image's width to this value.
18399 When set to a number in a list, try to get the width from any
18400 #+ATTR.* keyword if it matches a width specification like
18402 #+ATTR_HTML: :width 300px
18404 and fall back on that number if none is found.
18406 When set to nil, try to get the width from an #+ATTR.* keyword
18407 and fall back on the original width if none is found.
18409 This requires Emacs >= 24.1, build with imagemagick support."
18410 :group 'org-appearance
18411 :version "24.4"
18412 :package-version '(Org . "8.0")
18413 :type '(choice
18414 (const :tag "Use the image width" t)
18415 (integer :tag "Use a number of pixels")
18416 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18417 (const :tag "Use #+ATTR* or don't resize" nil)))
18419 (defcustom org-agenda-inhibit-startup nil
18420 "Inhibit startup when preparing agenda buffers.
18421 When this variable is t, the initialization of the Org agenda
18422 buffers is inhibited: e.g. the visibility state is not set, the
18423 tables are not re-aligned, etc."
18424 :type 'boolean
18425 :version "24.3"
18426 :group 'org-agenda)
18428 (defcustom org-agenda-ignore-properties nil
18429 "Avoid updating text properties when building the agenda.
18430 Properties are used to prepare buffers for effort estimates,
18431 appointments, statistics and subtree-local categories.
18432 If you don't use these in the agenda, you can add them to this
18433 list and agenda building will be a bit faster.
18434 The value is a list, with zero or more of the symbols `effort', `appt',
18435 `stats' or `category'."
18436 :type '(set :greedy t
18437 (const effort)
18438 (const appt)
18439 (const stats)
18440 (const category))
18441 :version "26.1"
18442 :package-version '(Org . "8.3")
18443 :group 'org-agenda)
18445 (defun org-duration-string-to-minutes (s &optional output-to-string)
18446 "Convert a duration string S to minutes.
18448 A bare number is interpreted as minutes, modifiers can be set by
18449 customizing `org-effort-durations' (which see).
18451 Entries containing a colon are interpreted as H:MM by
18452 `org-hh:mm-string-to-minutes'."
18453 (let ((result 0)
18454 (re (concat "\\([0-9.]+\\) *\\("
18455 (regexp-opt (mapcar 'car org-effort-durations))
18456 "\\)")))
18457 (while (string-match re s)
18458 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18459 (string-to-number (match-string 1 s))))
18460 (setq s (replace-match "" nil t s)))
18461 (setq result (floor result))
18462 (cl-incf result (org-hh:mm-string-to-minutes s))
18463 (if output-to-string (number-to-string result) result)))
18465 ;;;; Files
18467 (defun org-save-all-org-buffers ()
18468 "Save all Org buffers without user confirmation."
18469 (interactive)
18470 (message "Saving all Org buffers...")
18471 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18472 (when (featurep 'org-id) (org-id-locations-save))
18473 (message "Saving all Org buffers... done"))
18475 (defun org-revert-all-org-buffers ()
18476 "Revert all Org buffers.
18477 Prompt for confirmation when there are unsaved changes.
18478 Be sure you know what you are doing before letting this function
18479 overwrite your changes.
18481 This function is useful in a setup where one tracks org files
18482 with a version control system, to revert on one machine after pulling
18483 changes from another. I believe the procedure must be like this:
18485 1. M-x org-save-all-org-buffers
18486 2. Pull changes from the other machine, resolve conflicts
18487 3. M-x org-revert-all-org-buffers"
18488 (interactive)
18489 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18490 (user-error "Abort"))
18491 (save-excursion
18492 (save-window-excursion
18493 (dolist (b (buffer-list))
18494 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18495 (with-current-buffer b buffer-file-name))
18496 (pop-to-buffer-same-window b)
18497 (revert-buffer t 'no-confirm)))
18498 (when (and (featurep 'org-id) org-id-track-globally)
18499 (org-id-locations-load)))))
18501 ;;;; Agenda files
18503 ;;;###autoload
18504 (defun org-switchb (&optional arg)
18505 "Switch between Org buffers.
18507 With `\\[universal-argument]' prefix, restrict available buffers to files.
18509 With `\\[universal-argument] \\[universal-argument]' \
18510 prefix, restrict available buffers to agenda files."
18511 (interactive "P")
18512 (let ((blist (org-buffer-list
18513 (cond ((equal arg '(4)) 'files)
18514 ((equal arg '(16)) 'agenda)))))
18515 (pop-to-buffer-same-window
18516 (completing-read "Org buffer: "
18517 (mapcar #'list (mapcar #'buffer-name blist))
18518 nil t))))
18520 (defun org-buffer-list (&optional predicate exclude-tmp)
18521 "Return a list of Org buffers.
18522 PREDICATE can be `export', `files' or `agenda'.
18524 export restrict the list to Export buffers.
18525 files restrict the list to buffers visiting Org files.
18526 agenda restrict the list to buffers visiting agenda files.
18528 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18529 (let* ((bfn nil)
18530 (agenda-files (and (eq predicate 'agenda)
18531 (mapcar 'file-truename (org-agenda-files t))))
18532 (filter
18533 (cond
18534 ((eq predicate 'files)
18535 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18536 ((eq predicate 'export)
18537 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18538 ((eq predicate 'agenda)
18539 (lambda (b)
18540 (with-current-buffer b
18541 (and (derived-mode-p 'org-mode)
18542 (setq bfn (buffer-file-name b))
18543 (member (file-truename bfn) agenda-files)))))
18544 (t (lambda (b) (with-current-buffer b
18545 (or (derived-mode-p 'org-mode)
18546 (string-match "\\*Org .*Export"
18547 (buffer-name b)))))))))
18548 (delq nil
18549 (mapcar
18550 (lambda(b)
18551 (if (and (funcall filter b)
18552 (or (not exclude-tmp)
18553 (not (string-match "tmp" (buffer-name b)))))
18555 nil))
18556 (buffer-list)))))
18558 (defun org-agenda-files (&optional unrestricted archives)
18559 "Get the list of agenda files.
18560 Optional UNRESTRICTED means return the full list even if a restriction
18561 is currently in place.
18562 When ARCHIVES is t, include all archive files that are really being
18563 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18564 `org-agenda-archives-mode' is t."
18565 (let ((files
18566 (cond
18567 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18568 ((stringp org-agenda-files) (org-read-agenda-file-list))
18569 ((listp org-agenda-files) org-agenda-files)
18570 (t (error "Invalid value of `org-agenda-files'")))))
18571 (setq files (apply 'append
18572 (mapcar (lambda (f)
18573 (if (file-directory-p f)
18574 (directory-files
18575 f t org-agenda-file-regexp)
18576 (list f)))
18577 files)))
18578 (when org-agenda-skip-unavailable-files
18579 (setq files (delq nil
18580 (mapcar (function
18581 (lambda (file)
18582 (and (file-readable-p file) file)))
18583 files))))
18584 (when (or (eq archives t)
18585 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18586 (setq files (org-add-archive-files files)))
18587 files))
18589 (defun org-agenda-file-p (&optional file)
18590 "Return non-nil, if FILE is an agenda file.
18591 If FILE is omitted, use the file associated with the current
18592 buffer."
18593 (let ((fname (or file (buffer-file-name))))
18594 (and fname
18595 (member (file-truename fname)
18596 (mapcar #'file-truename (org-agenda-files t))))))
18598 (defun org-edit-agenda-file-list ()
18599 "Edit the list of agenda files.
18600 Depending on setup, this either uses customize to edit the variable
18601 `org-agenda-files', or it visits the file that is holding the list. In the
18602 latter case, the buffer is set up in a way that saving it automatically kills
18603 the buffer and restores the previous window configuration."
18604 (interactive)
18605 (if (stringp org-agenda-files)
18606 (let ((cw (current-window-configuration)))
18607 (find-file org-agenda-files)
18608 (setq-local org-window-configuration cw)
18609 (add-hook 'after-save-hook
18610 (lambda ()
18611 (set-window-configuration
18612 (prog1 org-window-configuration
18613 (kill-buffer (current-buffer))))
18614 (org-install-agenda-files-menu)
18615 (message "New agenda file list installed"))
18616 nil 'local)
18617 (message "%s" (substitute-command-keys
18618 "Edit list and finish with \\[save-buffer]")))
18619 (customize-variable 'org-agenda-files)))
18621 (defun org-store-new-agenda-file-list (list)
18622 "Set new value for the agenda file list and save it correctly."
18623 (if (stringp org-agenda-files)
18624 (let ((fe (org-read-agenda-file-list t)) b u)
18625 (while (setq b (find-buffer-visiting org-agenda-files))
18626 (kill-buffer b))
18627 (with-temp-file org-agenda-files
18628 (insert
18629 (mapconcat
18630 (lambda (f) ;; Keep un-expanded entries.
18631 (if (setq u (assoc f fe))
18632 (cdr u)
18634 list "\n")
18635 "\n")))
18636 (let ((org-mode-hook nil) (org-inhibit-startup t)
18637 (org-insert-mode-line-in-empty-file nil))
18638 (setq org-agenda-files list)
18639 (customize-save-variable 'org-agenda-files org-agenda-files))))
18641 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18642 "Read the list of agenda files from a file.
18643 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18644 filenames, used by `org-store-new-agenda-file-list' to write back
18645 un-expanded file names."
18646 (when (file-directory-p org-agenda-files)
18647 (error "`org-agenda-files' cannot be a single directory"))
18648 (when (stringp org-agenda-files)
18649 (with-temp-buffer
18650 (insert-file-contents org-agenda-files)
18651 (mapcar
18652 (lambda (f)
18653 (let ((e (expand-file-name (substitute-in-file-name f)
18654 org-directory)))
18655 (if pair-with-expansion
18656 (cons e f)
18657 e)))
18658 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18660 ;;;###autoload
18661 (defun org-cycle-agenda-files ()
18662 "Cycle through the files in `org-agenda-files'.
18663 If the current buffer visits an agenda file, find the next one in the list.
18664 If the current buffer does not, find the first agenda file."
18665 (interactive)
18666 (let* ((fs (or (org-agenda-files t)
18667 (user-error "No agenda files")))
18668 (files (copy-sequence fs))
18669 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18670 file)
18671 (when tcf
18672 (while (and (setq file (pop files))
18673 (not (equal (file-truename file) tcf)))))
18674 (find-file (car (or files fs)))
18675 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18677 (defun org-agenda-file-to-front (&optional to-end)
18678 "Move/add the current file to the top of the agenda file list.
18679 If the file is not present in the list, it is added to the front. If it is
18680 present, it is moved there. With optional argument TO-END, add/move to the
18681 end of the list."
18682 (interactive "P")
18683 (let ((org-agenda-skip-unavailable-files nil)
18684 (file-alist (mapcar (lambda (x)
18685 (cons (file-truename x) x))
18686 (org-agenda-files t)))
18687 (ctf (file-truename
18688 (or buffer-file-name
18689 (user-error "Please save the current buffer to a file"))))
18690 x had)
18691 (setq x (assoc ctf file-alist) had x)
18693 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18694 (if to-end
18695 (setq file-alist (append (delq x file-alist) (list x)))
18696 (setq file-alist (cons x (delq x file-alist))))
18697 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18698 (org-install-agenda-files-menu)
18699 (message "File %s to %s of agenda file list"
18700 (if had "moved" "added") (if to-end "end" "front"))))
18702 (defun org-remove-file (&optional file)
18703 "Remove current file from the list of files in variable `org-agenda-files'.
18704 These are the files which are being checked for agenda entries.
18705 Optional argument FILE means use this file instead of the current."
18706 (interactive)
18707 (let* ((org-agenda-skip-unavailable-files nil)
18708 (file (or file buffer-file-name
18709 (user-error "Current buffer does not visit a file")))
18710 (true-file (file-truename file))
18711 (afile (abbreviate-file-name file))
18712 (files (delq nil (mapcar
18713 (lambda (x)
18714 (unless (equal true-file
18715 (file-truename x))
18717 (org-agenda-files t)))))
18718 (if (not (= (length files) (length (org-agenda-files t))))
18719 (progn
18720 (org-store-new-agenda-file-list files)
18721 (org-install-agenda-files-menu)
18722 (message "Removed from Org Agenda list: %s" afile))
18723 (message "File was not in list: %s (not removed)" afile))))
18725 (defun org-file-menu-entry (file)
18726 (vector file (list 'find-file file) t))
18728 (defun org-check-agenda-file (file)
18729 "Make sure FILE exists. If not, ask user what to do."
18730 (unless (file-exists-p file)
18731 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18732 (abbreviate-file-name file))
18733 (let ((r (downcase (read-char-exclusive))))
18734 (cond
18735 ((equal r ?r)
18736 (org-remove-file file)
18737 (throw 'nextfile t))
18738 (t (user-error "Abort"))))))
18740 (defun org-get-agenda-file-buffer (file)
18741 "Get an agenda buffer visiting FILE.
18742 If the buffer needs to be created, add it to the list of buffers
18743 which might be released later."
18744 (let ((buf (org-find-base-buffer-visiting file)))
18745 (if buf
18746 buf ; just return it
18747 ;; Make a new buffer and remember it
18748 (setq buf (find-file-noselect file))
18749 (when buf (push buf org-agenda-new-buffers))
18750 buf)))
18752 (defun org-release-buffers (blist)
18753 "Release all buffers in list, asking the user for confirmation when needed.
18754 When a buffer is unmodified, it is just killed. When modified, it is saved
18755 \(if the user agrees) and then killed."
18756 (let (file)
18757 (dolist (buf blist)
18758 (setq file (buffer-file-name buf))
18759 (when (and (buffer-modified-p buf)
18760 file
18761 (y-or-n-p (format "Save file %s? " file)))
18762 (with-current-buffer buf (save-buffer)))
18763 (kill-buffer buf))))
18765 (defun org-agenda-prepare-buffers (files)
18766 "Create buffers for all agenda files, protect archived trees and comments."
18767 (interactive)
18768 (let ((pa '(:org-archived t))
18769 (pc '(:org-comment t))
18770 (pall '(:org-archived t :org-comment t))
18771 (inhibit-read-only t)
18772 (org-inhibit-startup org-agenda-inhibit-startup)
18773 (rea (concat ":" org-archive-tag ":"))
18774 re pos)
18775 (setq org-tag-alist-for-agenda nil
18776 org-tag-groups-alist-for-agenda nil)
18777 (save-excursion
18778 (save-restriction
18779 (dolist (file files)
18780 (catch 'nextfile
18781 (if (bufferp file)
18782 (set-buffer file)
18783 (org-check-agenda-file file)
18784 (set-buffer (org-get-agenda-file-buffer file)))
18785 (widen)
18786 (org-set-regexps-and-options 'tags-only)
18787 (setq pos (point))
18788 (or (memq 'category org-agenda-ignore-properties)
18789 (org-refresh-category-properties))
18790 (or (memq 'stats org-agenda-ignore-properties)
18791 (org-refresh-stats-properties))
18792 (or (memq 'effort org-agenda-ignore-properties)
18793 (org-refresh-effort-properties))
18794 (or (memq 'appt org-agenda-ignore-properties)
18795 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18796 (setq org-todo-keywords-for-agenda
18797 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18798 (setq org-done-keywords-for-agenda
18799 (append org-done-keywords-for-agenda org-done-keywords))
18800 (setq org-todo-keyword-alist-for-agenda
18801 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18802 (setq org-tag-alist-for-agenda
18803 (org-uniquify
18804 (append org-tag-alist-for-agenda
18805 org-current-tag-alist)))
18806 ;; Merge current file's tag groups into global
18807 ;; `org-tag-groups-alist-for-agenda'.
18808 (when org-group-tags
18809 (dolist (alist org-tag-groups-alist)
18810 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18811 (if old
18812 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18813 (push alist org-tag-groups-alist-for-agenda)))))
18814 (org-with-silent-modifications
18815 (save-excursion
18816 (remove-text-properties (point-min) (point-max) pall)
18817 (when org-agenda-skip-archived-trees
18818 (goto-char (point-min))
18819 (while (re-search-forward rea nil t)
18820 (when (org-at-heading-p t)
18821 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18822 (goto-char (point-min))
18823 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18824 (while (re-search-forward re nil t)
18825 (when (save-match-data (org-in-commented-heading-p t))
18826 (add-text-properties
18827 (match-beginning 0) (org-end-of-subtree t) pc)))))
18828 (goto-char pos)))))
18829 (setq org-todo-keywords-for-agenda
18830 (org-uniquify org-todo-keywords-for-agenda))
18831 (setq org-todo-keyword-alist-for-agenda
18832 (org-uniquify org-todo-keyword-alist-for-agenda))))
18835 ;;;; CDLaTeX minor mode
18837 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18838 "Keymap for the minor `org-cdlatex-mode'.")
18840 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18841 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18842 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18843 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18844 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18846 (defvar org-cdlatex-texmathp-advice-is-done nil
18847 "Flag remembering if we have applied the advice to texmathp already.")
18849 (define-minor-mode org-cdlatex-mode
18850 "Toggle the minor `org-cdlatex-mode'.
18851 This mode supports entering LaTeX environment and math in LaTeX fragments
18852 in Org mode.
18853 \\{org-cdlatex-mode-map}"
18854 nil " OCDL" nil
18855 (when org-cdlatex-mode
18856 (require 'cdlatex)
18857 (run-hooks 'cdlatex-mode-hook)
18858 (cdlatex-compute-tables))
18859 (unless org-cdlatex-texmathp-advice-is-done
18860 (setq org-cdlatex-texmathp-advice-is-done t)
18861 (defadvice texmathp (around org-math-always-on activate)
18862 "Always return t in Org buffers.
18863 This is because we want to insert math symbols without dollars even outside
18864 the LaTeX math segments. If Org mode thinks that point is actually inside
18865 an embedded LaTeX fragment, let `texmathp' do its job.
18866 `\\[org-cdlatex-mode-map]'"
18867 (interactive)
18868 (let (p)
18869 (cond
18870 ((not (derived-mode-p 'org-mode)) ad-do-it)
18871 ((eq this-command 'cdlatex-math-symbol)
18872 (setq ad-return-value t
18873 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18875 (let ((p (org-inside-LaTeX-fragment-p)))
18876 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18877 (setq ad-return-value t
18878 texmathp-why '("Org mode embedded math" . 0))
18879 (when p ad-do-it)))))))))
18881 (defun turn-on-org-cdlatex ()
18882 "Unconditionally turn on `org-cdlatex-mode'."
18883 (org-cdlatex-mode 1))
18885 (defun org-try-cdlatex-tab ()
18886 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18887 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18888 - inside a LaTeX fragment, or
18889 - after the first word in a line, where an abbreviation expansion could
18890 insert a LaTeX environment."
18891 (when org-cdlatex-mode
18892 (cond
18893 ;; Before any word on the line: No expansion possible.
18894 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18895 ;; Just after first word on the line: Expand it. Make sure it
18896 ;; cannot happen on headlines, though.
18897 ((save-excursion
18898 (skip-chars-backward "a-zA-Z0-9*")
18899 (skip-chars-backward " \t")
18900 (and (bolp) (not (org-at-heading-p))))
18901 (cdlatex-tab) t)
18902 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18904 (defun org-cdlatex-underscore-caret (&optional _arg)
18905 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18906 Revert to the normal definition outside of these fragments."
18907 (interactive "P")
18908 (if (org-inside-LaTeX-fragment-p)
18909 (call-interactively 'cdlatex-sub-superscript)
18910 (let (org-cdlatex-mode)
18911 (call-interactively (key-binding (vector last-input-event))))))
18913 (defun org-cdlatex-math-modify (&optional _arg)
18914 "Execute `cdlatex-math-modify' in LaTeX fragments.
18915 Revert to the normal definition outside of these fragments."
18916 (interactive "P")
18917 (if (org-inside-LaTeX-fragment-p)
18918 (call-interactively 'cdlatex-math-modify)
18919 (let (org-cdlatex-mode)
18920 (call-interactively (key-binding (vector last-input-event))))))
18922 (defun org-cdlatex-environment-indent (&optional environment item)
18923 "Execute `cdlatex-environment' and indent the inserted environment.
18925 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18927 The inserted environment is indented to current indentation
18928 unless point is at the beginning of the line, in which the
18929 environment remains unintended."
18930 (interactive)
18931 ;; cdlatex-environment always return nil. Therefore, capture output
18932 ;; first and determine if an environment was selected.
18933 (let* ((beg (point-marker))
18934 (end (copy-marker (point) t))
18935 (inserted (progn
18936 (ignore-errors (cdlatex-environment environment item))
18937 (< beg end)))
18938 ;; Figure out how many lines to move forward after the
18939 ;; environment has been inserted.
18940 (lines (when inserted
18941 (save-excursion
18942 (- (cl-loop while (< beg (point))
18943 with x = 0
18944 do (forward-line -1)
18945 (cl-incf x)
18946 finally return x)
18947 (if (progn (goto-char beg)
18948 (and (progn (skip-chars-forward " \t") (eolp))
18949 (progn (skip-chars-backward " \t") (bolp))))
18950 1 0)))))
18951 (env (org-trim (delete-and-extract-region beg end))))
18952 (when inserted
18953 ;; Get indentation of next line unless at column 0.
18954 (let ((ind (if (bolp) 0
18955 (save-excursion
18956 (org-return-indent)
18957 (prog1 (org-get-indentation)
18958 (when (progn (skip-chars-forward " \t") (eolp))
18959 (delete-region beg (point)))))))
18960 (bol (progn (skip-chars-backward " \t") (bolp))))
18961 ;; Insert a newline before environment unless at column zero
18962 ;; to "escape" the current line. Insert a newline if
18963 ;; something is one the same line as \end{ENVIRONMENT}.
18964 (insert
18965 (concat (unless bol "\n") env
18966 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18967 (unless (zerop ind)
18968 (save-excursion
18969 (goto-char beg)
18970 (while (< (point) end)
18971 (unless (eolp) (indent-line-to ind))
18972 (forward-line))))
18973 (goto-char beg)
18974 (forward-line lines)
18975 (indent-line-to ind)))
18976 (set-marker beg nil)
18977 (set-marker end nil)))
18980 ;;;; LaTeX fragments
18982 (defun org-inside-LaTeX-fragment-p ()
18983 "Test if point is inside a LaTeX fragment.
18984 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18985 sequence appearing also before point.
18986 Even though the matchers for math are configurable, this function assumes
18987 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18988 delimiters are skipped when they have been removed by customization.
18989 The return value is nil, or a cons cell with the delimiter and the
18990 position of this delimiter.
18992 This function does a reasonably good job, but can locally be fooled by
18993 for example currency specifications. For example it will assume being in
18994 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18995 fragments that are properly closed, but during editing, we have to live
18996 with the uncertainty caused by missing closing delimiters. This function
18997 looks only before point, not after."
18998 (catch 'exit
18999 (let ((pos (point))
19000 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19001 (lim (save-excursion (org-backward-paragraph) (point)))
19002 dd-on str (start 0) m re)
19003 (goto-char pos)
19004 (when dodollar
19005 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19006 re (nth 1 (assoc "$" org-latex-regexps)))
19007 (while (string-match re str start)
19008 (cond
19009 ((= (match-end 0) (length str))
19010 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19011 ((= (match-end 0) (- (length str) 5))
19012 (throw 'exit nil))
19013 (t (setq start (match-end 0))))))
19014 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19015 (goto-char pos)
19016 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19017 (and (match-beginning 2) (throw 'exit nil))
19018 ;; count $$
19019 (while (re-search-backward "\\$\\$" lim t)
19020 (setq dd-on (not dd-on)))
19021 (goto-char pos)
19022 (when dd-on (cons "$$" m))))))
19024 (defun org-inside-latex-macro-p ()
19025 "Is point inside a LaTeX macro or its arguments?"
19026 (save-match-data
19027 (org-in-regexp
19028 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19030 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19031 "Build an overlay between BEG and END using IMAGE file.
19032 Argument IMAGETYPE is the extension of the displayed image,
19033 as a string. It defaults to \"png\"."
19034 (let ((ov (make-overlay beg end))
19035 (imagetype (or (intern imagetype) 'png)))
19036 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19037 (overlay-put ov 'evaporate t)
19038 (overlay-put ov
19039 'modification-hooks
19040 (list (lambda (o _flag _beg _end &optional _l)
19041 (delete-overlay o))))
19042 (overlay-put ov
19043 'display
19044 (list 'image :type imagetype :file image :ascent 'center))))
19046 (defun org--list-latex-overlays (&optional beg end)
19047 "List all Org LaTeX overlays in current buffer.
19048 Limit to overlays between BEG and END when those are provided."
19049 (cl-remove-if-not
19050 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19051 (overlays-in (or beg (point-min)) (or end (point-max)))))
19053 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19054 "Remove all overlays with LaTeX fragment images in current buffer.
19055 When optional arguments BEG and END are non-nil, remove all
19056 overlays between them instead. Return a non-nil value when some
19057 overlays were removed, nil otherwise."
19058 (let ((overlays (org--list-latex-overlays beg end)))
19059 (mapc #'delete-overlay overlays)
19060 overlays))
19062 (defun org-toggle-latex-fragment (&optional arg)
19063 "Preview the LaTeX fragment at point, or all locally or globally.
19065 If the cursor is on a LaTeX fragment, create the image and overlay
19066 it over the source code, if there is none. Remove it otherwise.
19067 If there is no fragment at point, display all fragments in the
19068 current section.
19070 With prefix ARG, preview or clear image for all fragments in the
19071 current subtree or in the whole buffer when used before the first
19072 headline. With a prefix ARG `\\[universal-argument] \
19073 \\[universal-argument]' preview or clear images
19074 for all fragments in the buffer."
19075 (interactive "P")
19076 (when (display-graphic-p)
19077 (catch 'exit
19078 (save-excursion
19079 (let (beg end msg)
19080 (cond
19081 ((or (equal arg '(16))
19082 (and (equal arg '(4))
19083 (org-with-limited-levels (org-before-first-heading-p))))
19084 (if (org-remove-latex-fragment-image-overlays)
19085 (progn (message "LaTeX fragments images removed from buffer")
19086 (throw 'exit nil))
19087 (setq msg "Creating images for buffer...")))
19088 ((equal arg '(4))
19089 (org-with-limited-levels (org-back-to-heading t))
19090 (setq beg (point))
19091 (setq end (progn (org-end-of-subtree t) (point)))
19092 (if (org-remove-latex-fragment-image-overlays beg end)
19093 (progn
19094 (message "LaTeX fragment images removed from subtree")
19095 (throw 'exit nil))
19096 (setq msg "Creating images for subtree...")))
19097 ((let ((datum (org-element-context)))
19098 (when (memq (org-element-type datum)
19099 '(latex-environment latex-fragment))
19100 (setq beg (org-element-property :begin datum))
19101 (setq end (org-element-property :end datum))
19102 (if (org-remove-latex-fragment-image-overlays beg end)
19103 (progn (message "LaTeX fragment image removed")
19104 (throw 'exit nil))
19105 (setq msg "Creating image...")))))
19107 (org-with-limited-levels
19108 (setq beg (if (org-at-heading-p) (line-beginning-position)
19109 (outline-previous-heading)
19110 (point)))
19111 (setq end (progn (outline-next-heading) (point)))
19112 (if (org-remove-latex-fragment-image-overlays beg end)
19113 (progn
19114 (message "LaTeX fragment images removed from section")
19115 (throw 'exit nil))
19116 (setq msg "Creating images for section...")))))
19117 (let ((file (buffer-file-name (buffer-base-buffer))))
19118 (org-format-latex
19119 (concat org-preview-latex-image-directory "org-ltximg")
19120 beg end
19121 ;; Emacs cannot overlay images from remote hosts. Create
19122 ;; it in `temporary-file-directory' instead.
19123 (if (or (not file) (file-remote-p file))
19124 temporary-file-directory
19125 default-directory)
19126 'overlays msg 'forbuffer org-preview-latex-default-process))
19127 (message (concat msg "done")))))))
19129 (defun org-format-latex
19130 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19131 "Replace LaTeX fragments with links to an image.
19133 The function takes care of creating the replacement image.
19135 Only consider fragments between BEG and END when those are
19136 provided.
19138 When optional argument OVERLAYS is non-nil, display the image on
19139 top of the fragment instead of replacing it.
19141 PROCESSING-TYPE is the conversion method to use, as a symbol.
19143 Some of the options can be changed using the variable
19144 `org-format-latex-options', which see."
19145 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19146 (unless (eq processing-type 'verbatim)
19147 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19148 (cnt 0)
19149 checkdir-flag)
19150 (goto-char (or beg (point-min)))
19151 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19152 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19153 (overlay-recenter (or end (point-max))))
19154 (while (re-search-forward math-regexp end t)
19155 (unless (and overlays
19156 (eq (get-char-property (point) 'org-overlay-type)
19157 'org-latex-overlay))
19158 (let* ((context (org-element-context))
19159 (type (org-element-type context)))
19160 (when (memq type '(latex-environment latex-fragment))
19161 (let ((block-type (eq type 'latex-environment))
19162 (value (org-element-property :value context))
19163 (beg (org-element-property :begin context))
19164 (end (save-excursion
19165 (goto-char (org-element-property :end context))
19166 (skip-chars-backward " \r\t\n")
19167 (point))))
19168 (cond
19169 ((eq processing-type 'mathjax)
19170 ;; Prepare for MathJax processing.
19171 (if (not (string-match "\\`\\$\\$?" value))
19172 (goto-char end)
19173 (delete-region beg end)
19174 (if (string= (match-string 0 value) "$$")
19175 (insert "\\[" (substring value 2 -2) "\\]")
19176 (insert "\\(" (substring value 1 -1) "\\)"))))
19177 ((assq processing-type org-preview-latex-process-alist)
19178 ;; Process to an image.
19179 (cl-incf cnt)
19180 (goto-char beg)
19181 (let* ((processing-info
19182 (cdr (assq processing-type org-preview-latex-process-alist)))
19183 (face (face-at-point))
19184 ;; Get the colors from the face at point.
19186 (let ((color (plist-get org-format-latex-options
19187 :foreground)))
19188 (if (and forbuffer (eq color 'auto))
19189 (face-attribute face :foreground nil 'default)
19190 color)))
19192 (let ((color (plist-get org-format-latex-options
19193 :background)))
19194 (if (and forbuffer (eq color 'auto))
19195 (face-attribute face :background nil 'default)
19196 color)))
19197 (hash (sha1 (prin1-to-string
19198 (list org-format-latex-header
19199 org-latex-default-packages-alist
19200 org-latex-packages-alist
19201 org-format-latex-options
19202 forbuffer value fg bg))))
19203 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19204 (absprefix (expand-file-name prefix dir))
19205 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19206 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19207 (sep (and block-type "\n\n"))
19208 (link (concat sep "[[file:" linkfile "]]" sep))
19209 (options
19210 (org-combine-plists
19211 org-format-latex-options
19212 `(:foreground ,fg :background ,bg))))
19213 (when msg (message msg cnt))
19214 (unless checkdir-flag ; Ensure the directory exists.
19215 (setq checkdir-flag t)
19216 (let ((todir (file-name-directory absprefix)))
19217 (unless (file-directory-p todir)
19218 (make-directory todir t))))
19219 (unless (file-exists-p movefile)
19220 (org-create-formula-image
19221 value movefile options forbuffer processing-type))
19222 (if overlays
19223 (progn
19224 (dolist (o (overlays-in beg end))
19225 (when (eq (overlay-get o 'org-overlay-type)
19226 'org-latex-overlay)
19227 (delete-overlay o)))
19228 (org--format-latex-make-overlay beg end movefile imagetype)
19229 (goto-char end))
19230 (delete-region beg end)
19231 (insert
19232 (org-add-props link
19233 (list 'org-latex-src
19234 (replace-regexp-in-string "\"" "" value)
19235 'org-latex-src-embed-type
19236 (if block-type 'paragraph 'character)))))))
19237 ((eq processing-type 'mathml)
19238 ;; Process to MathML.
19239 (unless (org-format-latex-mathml-available-p)
19240 (user-error "LaTeX to MathML converter not configured"))
19241 (cl-incf cnt)
19242 (when msg (message msg cnt))
19243 (goto-char beg)
19244 (delete-region beg end)
19245 (insert (org-format-latex-as-mathml
19246 value block-type prefix dir)))
19248 (error "Unknown conversion process %s for LaTeX fragments"
19249 processing-type)))))))))))
19251 (defun org-create-math-formula (latex-frag &optional mathml-file)
19252 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19253 Use `org-latex-to-mathml-convert-command'. If the conversion is
19254 sucessful, return the portion between \"<math...> </math>\"
19255 elements otherwise return nil. When MATHML-FILE is specified,
19256 write the results in to that file. When invoked as an
19257 interactive command, prompt for LATEX-FRAG, with initial value
19258 set to the current active region and echo the results for user
19259 inspection."
19260 (interactive (list (let ((frag (when (org-region-active-p)
19261 (buffer-substring-no-properties
19262 (region-beginning) (region-end)))))
19263 (read-string "LaTeX Fragment: " frag nil frag))))
19264 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19265 (let* ((tmp-in-file
19266 (let ((file (file-relative-name
19267 (make-temp-name (expand-file-name "ltxmathml-in")))))
19268 (write-region latex-frag nil file)
19269 file))
19270 (tmp-out-file (file-relative-name
19271 (make-temp-name (expand-file-name "ltxmathml-out"))))
19272 (cmd (format-spec
19273 org-latex-to-mathml-convert-command
19274 `((?j . ,(and org-latex-to-mathml-jar-file
19275 (shell-quote-argument
19276 (expand-file-name
19277 org-latex-to-mathml-jar-file))))
19278 (?I . ,(shell-quote-argument tmp-in-file))
19279 (?i . ,latex-frag)
19280 (?o . ,(shell-quote-argument tmp-out-file)))))
19281 mathml shell-command-output)
19282 (when (called-interactively-p 'any)
19283 (unless (org-format-latex-mathml-available-p)
19284 (user-error "LaTeX to MathML converter not configured")))
19285 (message "Running %s" cmd)
19286 (setq shell-command-output (shell-command-to-string cmd))
19287 (setq mathml
19288 (when (file-readable-p tmp-out-file)
19289 (with-current-buffer (find-file-noselect tmp-out-file t)
19290 (goto-char (point-min))
19291 (when (re-search-forward
19292 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19293 (regexp-quote
19294 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19295 nil t)
19296 (prog1 (match-string 0) (kill-buffer))))))
19297 (cond
19298 (mathml
19299 (setq mathml
19300 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19301 (when mathml-file
19302 (write-region mathml nil mathml-file))
19303 (when (called-interactively-p 'any)
19304 (message mathml)))
19305 ((message "LaTeX to MathML conversion failed")
19306 (message shell-command-output)))
19307 (delete-file tmp-in-file)
19308 (when (file-exists-p tmp-out-file)
19309 (delete-file tmp-out-file))
19310 mathml))
19312 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19313 prefix &optional dir)
19314 "Use `org-create-math-formula' but check local cache first."
19315 (let* ((absprefix (expand-file-name prefix dir))
19316 (print-length nil) (print-level nil)
19317 (formula-id (concat
19318 "formula-"
19319 (sha1
19320 (prin1-to-string
19321 (list latex-frag
19322 org-latex-to-mathml-convert-command)))))
19323 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19324 (formula-cache-dir (file-name-directory formula-cache)))
19326 (unless (file-directory-p formula-cache-dir)
19327 (make-directory formula-cache-dir t))
19329 (unless (file-exists-p formula-cache)
19330 (org-create-math-formula latex-frag formula-cache))
19332 (if (file-exists-p formula-cache)
19333 ;; Successful conversion. Return the link to MathML file.
19334 (org-add-props
19335 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19336 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19337 'org-latex-src-embed-type (if latex-frag-type
19338 'paragraph 'character)))
19339 ;; Failed conversion. Return the LaTeX fragment verbatim
19340 latex-frag)))
19342 (defun org--get-display-dpi ()
19343 "Get the DPI of the display.
19344 The function assumes that the display has the same pixel width in
19345 the horizontal and vertical directions."
19346 (if (display-graphic-p)
19347 (round (/ (display-pixel-height)
19348 (/ (display-mm-height) 25.4)))
19349 (error "Attempt to calculate the dpi of a non-graphic display")))
19351 (defun org-create-formula-image
19352 (string tofile options buffer &optional processing-type)
19353 "Create an image from LaTeX source using external processes.
19355 The LaTeX STRING is saved to a temporary LaTeX file, then
19356 converted to an image file by process PROCESSING-TYPE defined in
19357 `org-preview-latex-process-alist'. A nil value defaults to
19358 `org-preview-latex-default-process'.
19360 The generated image file is eventually moved to TOFILE.
19362 The OPTIONS argument controls the size, foreground color and
19363 background color of the generated image.
19365 When BUFFER non-nil, this function is used for LaTeX previewing.
19366 Otherwise, it is used to deal with LaTeX snippets showed in
19367 a HTML file."
19368 (let* ((processing-type (or processing-type
19369 org-preview-latex-default-process))
19370 (processing-info
19371 (cdr (assq processing-type org-preview-latex-process-alist)))
19372 (programs (plist-get processing-info :programs))
19373 (error-message (or (plist-get processing-info :message) ""))
19374 (use-xcolor (plist-get processing-info :use-xcolor))
19375 (image-input-type (plist-get processing-info :image-input-type))
19376 (image-output-type (plist-get processing-info :image-output-type))
19377 (post-clean (or (plist-get processing-info :post-clean)
19378 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19379 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19380 (latex-header
19381 (or (plist-get processing-info :latex-header)
19382 (org-latex-make-preamble
19383 (org-export-get-environment (org-export-get-backend 'latex))
19384 org-format-latex-header
19385 'snippet)))
19386 (latex-compiler (plist-get processing-info :latex-compiler))
19387 (image-converter (plist-get processing-info :image-converter))
19388 (tmpdir temporary-file-directory)
19389 (texfilebase (make-temp-name
19390 (expand-file-name "orgtex" tmpdir)))
19391 (texfile (concat texfilebase ".tex"))
19392 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19393 '(1.0 . 1.0)))
19394 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19395 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19396 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19397 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19398 "Black"))
19399 (bg (or (plist-get options (if buffer :background :html-background))
19400 "Transparent"))
19401 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19402 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19403 (dolist (program programs)
19404 (org-check-external-command program error-message))
19405 (if use-xcolor
19406 (progn (if (eq fg 'default)
19407 (setq fg (org-latex-color :foreground))
19408 (setq fg (org-latex-color-format fg)))
19409 (if (eq bg 'default)
19410 (setq bg (org-latex-color :background))
19411 (setq bg (org-latex-color-format
19412 (if (string= bg "Transparent") "white" bg))))
19413 (with-temp-file texfile
19414 (insert latex-header)
19415 (insert "\n\\begin{document}\n"
19416 "\\definecolor{fg}{rgb}{" fg "}\n"
19417 "\\definecolor{bg}{rgb}{" bg "}\n"
19418 "\n\\pagecolor{bg}\n"
19419 "\n{\\color{fg}\n"
19420 string
19421 "\n}\n"
19422 "\n\\end{document}\n")))
19423 (if (eq fg 'default)
19424 (setq fg (org-dvipng-color :foreground))
19425 (unless (string= fg "Transparent")
19426 (setq fg (org-dvipng-color-format fg))))
19427 (if (eq bg 'default)
19428 (setq bg (org-dvipng-color :background))
19429 (unless (string= bg "Transparent")
19430 (setq bg (org-dvipng-color-format bg))))
19431 (with-temp-file texfile
19432 (insert latex-header)
19433 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19435 (let* ((err-msg (format "Please adjust `%s' part of \
19436 `org-preview-latex-process-alist'."
19437 processing-type))
19438 (image-input-file
19439 (org-compile-file
19440 texfile latex-compiler image-input-type err-msg log-buf))
19441 (image-output-file
19442 (org-compile-file
19443 image-input-file image-converter image-output-type err-msg log-buf
19444 `((?F . ,(shell-quote-argument fg))
19445 (?B . ,(shell-quote-argument bg))
19446 (?D . ,(shell-quote-argument (format "%s" dpi)))
19447 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19448 (copy-file image-output-file tofile 'replace)
19449 (dolist (e post-clean)
19450 (when (file-exists-p (concat texfilebase e))
19451 (delete-file (concat texfilebase e))))
19452 image-output-file)))
19454 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19455 "Fill a LaTeX header template TPL.
19456 In the template, the following place holders will be recognized:
19458 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19459 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19460 [PACKAGES] \\usepackage statements for PKG
19461 [NO-PACKAGES] do not include PKG
19462 [EXTRA] the string EXTRA
19463 [NO-EXTRA] do not include EXTRA
19465 For backward compatibility, if both the positive and the negative place
19466 holder is missing, the positive one (without the \"NO-\") will be
19467 assumed to be present at the end of the template.
19468 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19469 EXTRA is a string.
19470 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19471 (let (rpl (end ""))
19472 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19473 (setq rpl (if (or (match-end 1) (not def-pkg))
19474 "" (org-latex-packages-to-string def-pkg snippets-p t))
19475 tpl (replace-match rpl t t tpl))
19476 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19478 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19479 (setq rpl (if (or (match-end 1) (not pkg))
19480 "" (org-latex-packages-to-string pkg snippets-p t))
19481 tpl (replace-match rpl t t tpl))
19482 (when pkg (setq end
19483 (concat end "\n"
19484 (org-latex-packages-to-string pkg snippets-p)))))
19486 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19487 (setq rpl (if (or (match-end 1) (not extra))
19488 "" (concat extra "\n"))
19489 tpl (replace-match rpl t t tpl))
19490 (when (and extra (string-match "\\S-" extra))
19491 (setq end (concat end "\n" extra))))
19493 (if (string-match "\\S-" end)
19494 (concat tpl "\n" end)
19495 tpl)))
19497 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19498 "Turn an alist of packages into a string with the \\usepackage macros."
19499 (setq pkg (mapconcat (lambda(p)
19500 (cond
19501 ((stringp p) p)
19502 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19503 (format "%% Package %s omitted" (cadr p)))
19504 ((equal "" (car p))
19505 (format "\\usepackage{%s}" (cadr p)))
19507 (format "\\usepackage[%s]{%s}"
19508 (car p) (cadr p)))))
19510 "\n"))
19511 (if newline (concat pkg "\n") pkg))
19513 (defun org-dvipng-color (attr)
19514 "Return a RGB color specification for dvipng."
19515 (org-dvipng-color-format (face-attribute 'default attr nil)))
19517 (defun org-dvipng-color-format (color-name)
19518 "Convert COLOR-NAME to a RGB color value for dvipng."
19519 (apply #'format "rgb %s %s %s"
19520 (mapcar 'org-normalize-color
19521 (color-values color-name))))
19523 (defun org-latex-color (attr)
19524 "Return a RGB color for the LaTeX color package."
19525 (org-latex-color-format (face-attribute 'default attr nil)))
19527 (defun org-latex-color-format (color-name)
19528 "Convert COLOR-NAME to a RGB color value."
19529 (apply #'format "%s,%s,%s"
19530 (mapcar 'org-normalize-color
19531 (color-values color-name))))
19533 (defun org-normalize-color (value)
19534 "Return string to be used as color value for an RGB component."
19535 (format "%g" (/ value 65535.0)))
19539 ;; Image display
19541 (defvar-local org-inline-image-overlays nil)
19543 (defun org-toggle-inline-images (&optional include-linked)
19544 "Toggle the display of inline images.
19545 INCLUDE-LINKED is passed to `org-display-inline-images'."
19546 (interactive "P")
19547 (if org-inline-image-overlays
19548 (progn
19549 (org-remove-inline-images)
19550 (when (called-interactively-p 'interactive)
19551 (message "Inline image display turned off")))
19552 (org-display-inline-images include-linked)
19553 (when (called-interactively-p 'interactive)
19554 (message (if org-inline-image-overlays
19555 (format "%d images displayed inline"
19556 (length org-inline-image-overlays))
19557 "No images to display inline")))))
19559 (defun org-redisplay-inline-images ()
19560 "Refresh the display of inline images."
19561 (interactive)
19562 (if (not org-inline-image-overlays)
19563 (org-toggle-inline-images)
19564 (org-toggle-inline-images)
19565 (org-toggle-inline-images)))
19567 (defun org-display-inline-images (&optional include-linked refresh beg end)
19568 "Display inline images.
19570 An inline image is a link which follows either of these
19571 conventions:
19573 1. Its path is a file with an extension matching return value
19574 from `image-file-name-regexp' and it has no contents.
19576 2. Its description consists in a single link of the previous
19577 type.
19579 When optional argument INCLUDE-LINKED is non-nil, also links with
19580 a text description part will be inlined. This can be nice for
19581 a quick look at those images, but it does not reflect what
19582 exported files will look like.
19584 When optional argument REFRESH is non-nil, refresh existing
19585 images between BEG and END. This will create new image displays
19586 only if necessary. BEG and END default to the buffer
19587 boundaries."
19588 (interactive "P")
19589 (when (display-graphic-p)
19590 (unless refresh
19591 (org-remove-inline-images)
19592 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19593 (org-with-wide-buffer
19594 (goto-char (or beg (point-min)))
19595 (let ((case-fold-search t)
19596 (file-extension-re (image-file-name-regexp)))
19597 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19598 (let ((link (save-match-data (org-element-context))))
19599 ;; Check if we're at an inline image.
19600 (when (and (equal (org-element-property :type link) "file")
19601 (or include-linked
19602 (not (org-element-property :contents-begin link)))
19603 (let ((parent (org-element-property :parent link)))
19604 (or (not (eq (org-element-type parent) 'link))
19605 (not (cdr (org-element-contents parent)))))
19606 (string-match-p file-extension-re
19607 (org-element-property :path link)))
19608 (let ((file (expand-file-name
19609 (org-link-unescape
19610 (org-element-property :path link)))))
19611 (when (file-exists-p file)
19612 (let ((width
19613 ;; Apply `org-image-actual-width' specifications.
19614 (cond
19615 ((not (image-type-available-p 'imagemagick)) nil)
19616 ((eq org-image-actual-width t) nil)
19617 ((listp org-image-actual-width)
19619 ;; First try to find a width among
19620 ;; attributes associated to the paragraph
19621 ;; containing link.
19622 (let ((paragraph
19623 (let ((e link))
19624 (while (and (setq e (org-element-property
19625 :parent e))
19626 (not (eq (org-element-type e)
19627 'paragraph))))
19628 e)))
19629 (when paragraph
19630 (save-excursion
19631 (goto-char (org-element-property :begin paragraph))
19632 (when
19633 (re-search-forward
19634 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19635 (org-element-property
19636 :post-affiliated paragraph)
19638 (string-to-number (match-string 1))))))
19639 ;; Otherwise, fall-back to provided number.
19640 (car org-image-actual-width)))
19641 ((numberp org-image-actual-width)
19642 org-image-actual-width)))
19643 (old (get-char-property-and-overlay
19644 (org-element-property :begin link)
19645 'org-image-overlay)))
19646 (if (and (car-safe old) refresh)
19647 (image-refresh (overlay-get (cdr old) 'display))
19648 (let ((image (create-image file
19649 (and width 'imagemagick)
19651 :width width)))
19652 (when image
19653 (let* ((link
19654 ;; If inline image is the description
19655 ;; of another link, be sure to
19656 ;; consider the latter as the one to
19657 ;; apply the overlay on.
19658 (let ((parent
19659 (org-element-property :parent link)))
19660 (if (eq (org-element-type parent) 'link)
19661 parent
19662 link)))
19663 (ov (make-overlay
19664 (org-element-property :begin link)
19665 (progn
19666 (goto-char
19667 (org-element-property :end link))
19668 (skip-chars-backward " \t")
19669 (point)))))
19670 (overlay-put ov 'display image)
19671 (overlay-put ov 'face 'default)
19672 (overlay-put ov 'org-image-overlay t)
19673 (overlay-put
19674 ov 'modification-hooks
19675 (list 'org-display-inline-remove-overlay))
19676 (push ov org-inline-image-overlays)))))))))))))))
19678 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19679 "Remove inline-display overlay if a corresponding region is modified."
19680 (let ((inhibit-modification-hooks t))
19681 (when (and ov after)
19682 (delete ov org-inline-image-overlays)
19683 (delete-overlay ov))))
19685 (defun org-remove-inline-images ()
19686 "Remove inline display of images."
19687 (interactive)
19688 (mapc #'delete-overlay org-inline-image-overlays)
19689 (setq org-inline-image-overlays nil))
19691 ;;;; Key bindings
19693 ;; Outline functions from `outline-mode-prefix-map'
19694 ;; that can be remapped in Org:
19695 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19696 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19697 (define-key org-mode-map [remap outline-forward-same-level]
19698 'org-forward-heading-same-level)
19699 (define-key org-mode-map [remap outline-backward-same-level]
19700 'org-backward-heading-same-level)
19701 (define-key org-mode-map [remap outline-show-branches]
19702 'org-kill-note-or-show-branches)
19703 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19704 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19705 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19706 (define-key org-mode-map [remap outline-next-visible-heading]
19707 'org-next-visible-heading)
19708 (define-key org-mode-map [remap outline-previous-visible-heading]
19709 'org-previous-visible-heading)
19710 (define-key org-mode-map [remap show-children] 'org-show-children)
19712 ;; Outline functions from `outline-mode-prefix-map' that can not
19713 ;; be remapped in Org:
19715 ;; - the column "key binding" shows whether the Outline function is still
19716 ;; available in Org mode on the same key that it has been bound to in
19717 ;; Outline mode:
19718 ;; - "overridden": key used for a different functionality in Org mode
19719 ;; - else: key still bound to the same Outline function in Org mode
19721 ;; | Outline function | key binding | Org replacement |
19722 ;; |------------------------------------+-------------+--------------------------|
19723 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19724 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19725 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19726 ;; | `show-entry' | overridden | no replacement |
19727 ;; | `show-branches' | `C-c C-k' | still same function |
19728 ;; | `show-subtree' | overridden | visibility cycling |
19729 ;; | `show-all' | overridden | no replacement |
19730 ;; | `hide-subtree' | overridden | visibility cycling |
19731 ;; | `hide-body' | overridden | no replacement |
19732 ;; | `hide-entry' | overridden | visibility cycling |
19733 ;; | `hide-leaves' | overridden | no replacement |
19734 ;; | `hide-sublevels' | overridden | no replacement |
19735 ;; | `hide-other' | overridden | no replacement |
19737 ;; Make `C-c C-x' a prefix key
19738 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19740 ;; TAB key with modifiers
19741 (org-defkey org-mode-map "\C-i" 'org-cycle)
19742 (org-defkey org-mode-map [(tab)] 'org-cycle)
19743 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19744 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19745 ;; The following line is necessary under Suse GNU/Linux
19746 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19747 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19748 (define-key org-mode-map [backtab] 'org-shifttab)
19750 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19751 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19752 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19754 ;; Cursor keys with modifiers
19755 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19756 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19757 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19758 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19760 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19761 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19762 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19763 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19764 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19765 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19767 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19768 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19769 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19770 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19772 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19773 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19774 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19775 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19777 ;; Babel keys
19778 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19779 (dolist (pair org-babel-key-bindings)
19780 (define-key org-babel-map (car pair) (cdr pair)))
19782 ;;; Extra keys for tty access.
19783 ;; We only set them when really needed because otherwise the
19784 ;; menus don't show the simple keys
19786 (when (or org-use-extra-keys (not window-system))
19787 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19788 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19789 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19790 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19791 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19792 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19793 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19794 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19795 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19796 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19797 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19798 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19799 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19800 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19801 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19802 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19803 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19804 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19805 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19806 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19807 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19808 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19809 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19810 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19811 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19812 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19813 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19814 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19816 ;; All the other keys
19818 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19819 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19820 (if (boundp 'narrow-map)
19821 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19822 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19823 (if (boundp 'narrow-map)
19824 (org-defkey narrow-map "b" 'org-narrow-to-block)
19825 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19826 (if (boundp 'narrow-map)
19827 (org-defkey narrow-map "e" 'org-narrow-to-element)
19828 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19829 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19830 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19831 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19832 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19833 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19834 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19835 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19836 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19837 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19838 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19839 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19840 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19841 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19842 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19843 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19844 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19845 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19846 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19847 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19848 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19849 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19850 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19851 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19852 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19853 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19854 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19855 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19856 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19857 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19858 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19859 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19860 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19861 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19862 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19863 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19864 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19865 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19866 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19867 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19868 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19869 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19870 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19871 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19872 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19873 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19874 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19875 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19876 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19877 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19878 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19879 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19880 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19881 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19882 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19883 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19884 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19885 (org-defkey org-mode-map "\C-c^" 'org-sort)
19886 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19887 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19888 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19889 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19890 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19891 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19892 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19893 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19894 (org-defkey org-mode-map "\C-m" 'org-return)
19895 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19896 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19897 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19898 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19899 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19900 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19901 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19902 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19903 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19904 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19905 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19906 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19907 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19908 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19909 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19910 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19911 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19912 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19913 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19914 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19915 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19916 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19917 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19918 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19919 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19921 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19922 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19923 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19925 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19926 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19927 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19928 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19929 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19930 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19931 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19932 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19933 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19934 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19935 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19936 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19937 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19938 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19939 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19940 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19941 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19942 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19943 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19944 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19945 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19946 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19948 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19949 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19950 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19951 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19952 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19954 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19956 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19958 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19959 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19961 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19964 (defconst org-speed-commands-default
19966 ("Outline Navigation")
19967 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19968 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19969 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19970 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19971 ("F" . org-next-block)
19972 ("B" . org-previous-block)
19973 ("u" . (org-speed-move-safe 'outline-up-heading))
19974 ("j" . org-goto)
19975 ("g" . (org-refile t))
19976 ("Outline Visibility")
19977 ("c" . org-cycle)
19978 ("C" . org-shifttab)
19979 (" " . org-display-outline-path)
19980 ("s" . org-narrow-to-subtree)
19981 ("=" . org-columns)
19982 ("Outline Structure Editing")
19983 ("U" . org-metaup)
19984 ("D" . org-metadown)
19985 ("r" . org-metaright)
19986 ("l" . org-metaleft)
19987 ("R" . org-shiftmetaright)
19988 ("L" . org-shiftmetaleft)
19989 ("i" . (progn (forward-char 1) (call-interactively
19990 'org-insert-heading-respect-content)))
19991 ("^" . org-sort)
19992 ("w" . org-refile)
19993 ("a" . org-archive-subtree-default-with-confirmation)
19994 ("@" . org-mark-subtree)
19995 ("#" . org-toggle-comment)
19996 ("Clock Commands")
19997 ("I" . org-clock-in)
19998 ("O" . org-clock-out)
19999 ("Meta Data Editing")
20000 ("t" . org-todo)
20001 ("," . (org-priority))
20002 ("0" . (org-priority ?\ ))
20003 ("1" . (org-priority ?A))
20004 ("2" . (org-priority ?B))
20005 ("3" . (org-priority ?C))
20006 (":" . org-set-tags-command)
20007 ("e" . org-set-effort)
20008 ("E" . org-inc-effort)
20009 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20010 (org-entry-put (point) "APPT_WARNTIME" m)))
20011 ("Agenda Views etc")
20012 ("v" . org-agenda)
20013 ("/" . org-sparse-tree)
20014 ("Misc")
20015 ("o" . org-open-at-point)
20016 ("?" . org-speed-command-help)
20017 ("<" . (org-agenda-set-restriction-lock 'subtree))
20018 (">" . (org-agenda-remove-restriction-lock))
20020 "The default speed commands.")
20022 (defun org-print-speed-command (e)
20023 (if (> (length (car e)) 1)
20024 (progn
20025 (princ "\n")
20026 (princ (car e))
20027 (princ "\n")
20028 (princ (make-string (length (car e)) ?-))
20029 (princ "\n"))
20030 (princ (car e))
20031 (princ " ")
20032 (if (symbolp (cdr e))
20033 (princ (symbol-name (cdr e)))
20034 (prin1 (cdr e)))
20035 (princ "\n")))
20037 (defun org-speed-command-help ()
20038 "Show the available speed commands."
20039 (interactive)
20040 (if (not org-use-speed-commands)
20041 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20042 (with-output-to-temp-buffer "*Help*"
20043 (princ "User-defined Speed commands\n===========================\n")
20044 (mapc #'org-print-speed-command org-speed-commands-user)
20045 (princ "\n")
20046 (princ "Built-in Speed commands\n=======================\n")
20047 (mapc #'org-print-speed-command org-speed-commands-default))
20048 (with-current-buffer "*Help*"
20049 (setq truncate-lines t))))
20051 (defun org-speed-move-safe (cmd)
20052 "Execute CMD, but make sure that the cursor always ends up in a headline.
20053 If not, return to the original position and throw an error."
20054 (interactive)
20055 (let ((pos (point)))
20056 (call-interactively cmd)
20057 (unless (and (bolp) (org-at-heading-p))
20058 (goto-char pos)
20059 (error "Boundary reached while executing %s" cmd))))
20061 (defvar org-self-insert-command-undo-counter 0)
20063 (defvar org-table-auto-blank-field) ; defined in org-table.el
20064 (defvar org-speed-command nil)
20066 (defun org-speed-command-activate (keys)
20067 "Hook for activating single-letter speed commands.
20068 `org-speed-commands-default' specifies a minimal command set.
20069 Use `org-speed-commands-user' for further customization."
20070 (when (or (and (bolp) (looking-at org-outline-regexp))
20071 (and (functionp org-use-speed-commands)
20072 (funcall org-use-speed-commands)))
20073 (cdr (assoc keys (append org-speed-commands-user
20074 org-speed-commands-default)))))
20076 (defun org-babel-speed-command-activate (keys)
20077 "Hook for activating single-letter code block commands."
20078 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20079 (cdr (assoc keys org-babel-key-bindings))))
20081 (defcustom org-speed-command-hook
20082 '(org-speed-command-default-hook org-babel-speed-command-hook)
20083 "Hook for activating speed commands at strategic locations.
20084 Hook functions are called in sequence until a valid handler is
20085 found.
20087 Each hook takes a single argument, a user-pressed command key
20088 which is also a `self-insert-command' from the global map.
20090 Within the hook, examine the cursor position and the command key
20091 and return nil or a valid handler as appropriate. Handler could
20092 be one of an interactive command, a function, or a form.
20094 Set `org-use-speed-commands' to non-nil value to enable this
20095 hook. The default setting is `org-speed-command-activate'."
20096 :group 'org-structure
20097 :version "24.1"
20098 :type 'hook)
20100 (defun org-self-insert-command (N)
20101 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20102 If the cursor is in a table looking at whitespace, the whitespace is
20103 overwritten, and the table is not marked as requiring realignment."
20104 (interactive "p")
20105 (org-check-before-invisible-edit 'insert)
20106 (cond
20107 ((and org-use-speed-commands
20108 (let ((kv (this-command-keys-vector)))
20109 (setq org-speed-command
20110 (run-hook-with-args-until-success
20111 'org-speed-command-hook
20112 (make-string 1 (aref kv (1- (length kv))))))))
20113 (cond
20114 ((commandp org-speed-command)
20115 (setq this-command org-speed-command)
20116 (call-interactively org-speed-command))
20117 ((functionp org-speed-command)
20118 (funcall org-speed-command))
20119 ((and org-speed-command (listp org-speed-command))
20120 (eval org-speed-command))
20121 (t (let (org-use-speed-commands)
20122 (call-interactively 'org-self-insert-command)))))
20123 ((and
20124 (org-at-table-p)
20125 (eq N 1)
20126 (not (org-region-active-p))
20127 (progn
20128 ;; Check if we blank the field, and if that triggers align.
20129 (and (featurep 'org-table) org-table-auto-blank-field
20130 (memq last-command
20131 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20132 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20133 ;; Got extra space, this field does not determine
20134 ;; column width.
20135 (let (org-table-may-need-update) (org-table-blank-field))
20136 ;; No extra space, this field may determine column
20137 ;; width.
20138 (org-table-blank-field)))
20140 (looking-at "[^|\n]* \\( \\)|"))
20141 ;; There is room for insertion without re-aligning the table.
20142 (delete-region (match-beginning 1) (match-end 1))
20143 (self-insert-command N))
20145 (setq org-table-may-need-update t)
20146 (self-insert-command N)
20147 (org-fix-tags-on-the-fly)
20148 (when org-self-insert-cluster-for-undo
20149 (if (not (eq last-command 'org-self-insert-command))
20150 (setq org-self-insert-command-undo-counter 1)
20151 (if (>= org-self-insert-command-undo-counter 20)
20152 (setq org-self-insert-command-undo-counter 1)
20153 (and (> org-self-insert-command-undo-counter 0)
20154 buffer-undo-list (listp buffer-undo-list)
20155 (not (cadr buffer-undo-list)) ; remove nil entry
20156 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20157 (setq org-self-insert-command-undo-counter
20158 (1+ org-self-insert-command-undo-counter))))))))
20160 (defun org-check-before-invisible-edit (kind)
20161 "Check is editing if kind KIND would be dangerous with invisible text around.
20162 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20163 ;; First, try to get out of here as quickly as possible, to reduce overhead
20164 (when (and org-catch-invisible-edits
20165 (or (not (boundp 'visible-mode)) (not visible-mode))
20166 (or (get-char-property (point) 'invisible)
20167 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20168 ;; OK, we need to take a closer look. Do not consider
20169 ;; invisibility obtained through text properties (e.g., link
20170 ;; fontification), as it cannot be toggled.
20171 (let* ((invisible-at-point
20172 (pcase (get-char-property-and-overlay (point) 'invisible)
20173 (`(,_ . ,(and (pred overlayp) o)) o)))
20174 ;; Assume that point cannot land in the middle of an
20175 ;; overlay, or between two overlays.
20176 (invisible-before-point
20177 (and (not invisible-at-point)
20178 (not (bobp))
20179 (pcase (get-char-property-and-overlay (1- (point)) 'invisible)
20180 (`(,_ . ,(and (pred overlayp) o)) o))))
20181 (border-and-ok-direction
20183 ;; Check if we are acting predictably before invisible
20184 ;; text.
20185 (and invisible-at-point
20186 (memq kind '(insert delete-backward)))
20187 ;; Check if we are acting predictably after invisible text
20188 ;; This works not well, and I have turned it off. It seems
20189 ;; better to always show and stop after invisible text.
20190 ;; (and (not invisible-at-point) invisible-before-point
20191 ;; (memq kind '(insert delete)))
20193 (when (or invisible-at-point invisible-before-point)
20194 (when (eq org-catch-invisible-edits 'error)
20195 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20196 (if (and org-custom-properties-overlays
20197 (y-or-n-p "Display invisible properties in this buffer? "))
20198 (org-toggle-custom-properties-visibility)
20199 ;; Make the area visible
20200 (save-excursion
20201 (when invisible-before-point
20202 (goto-char
20203 (previous-single-char-property-change (point) 'invisible)))
20204 ;; Remove whatever overlay is currently making yet-to-be
20205 ;; edited text invisible. Also remove nested invisibility
20206 ;; related overlays.
20207 (delete-overlay (or invisible-at-point invisible-before-point))
20208 (let ((origin (if invisible-at-point (point) (1- (point)))))
20209 (while (pcase (get-char-property-and-overlay origin 'invisible)
20210 (`(,_ . ,(and (pred overlayp) o))
20211 (delete-overlay o)
20212 t)))))
20213 (cond
20214 ((eq org-catch-invisible-edits 'show)
20215 ;; That's it, we do the edit after showing
20216 (message
20217 "Unfolding invisible region around point before editing")
20218 (sit-for 1))
20219 ((and (eq org-catch-invisible-edits 'smart)
20220 border-and-ok-direction)
20221 (message "Unfolding invisible region around point before editing"))
20223 ;; Don't do the edit, make the user repeat it in full visibility
20224 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20226 (defun org-fix-tags-on-the-fly ()
20227 "Align tags in headline at point.
20228 Unlike to `org-set-tags', it ignores region and sorting."
20229 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
20230 (org-at-heading-p))
20231 (let ((org-ignore-region t)
20232 (org-tags-sort-function nil))
20233 (org-set-tags nil t))))
20235 (defun org-delete-backward-char (N)
20236 "Like `delete-backward-char', insert whitespace at field end in tables.
20237 When deleting backwards, in tables this function will insert whitespace in
20238 front of the next \"|\" separator, to keep the table aligned. The table will
20239 still be marked for re-alignment if the field did fill the entire column,
20240 because, in this case the deletion might narrow the column."
20241 (interactive "p")
20242 (save-match-data
20243 (org-check-before-invisible-edit 'delete-backward)
20244 (if (and (org-at-table-p)
20245 (eq N 1)
20246 (string-match "|" (buffer-substring (point-at-bol) (point)))
20247 (looking-at ".*?|"))
20248 (let ((pos (point))
20249 (noalign (looking-at "[^|\n\r]* |"))
20250 (c org-table-may-need-update))
20251 (backward-delete-char N)
20252 (unless overwrite-mode
20253 (skip-chars-forward "^|")
20254 (insert " ")
20255 (goto-char (1- pos)))
20256 ;; noalign: if there were two spaces at the end, this field
20257 ;; does not determine the width of the column.
20258 (when noalign (setq org-table-may-need-update c)))
20259 (backward-delete-char N)
20260 (org-fix-tags-on-the-fly))))
20262 (defun org-delete-char (N)
20263 "Like `delete-char', but insert whitespace at field end in tables.
20264 When deleting characters, in tables this function will insert whitespace in
20265 front of the next \"|\" separator, to keep the table aligned. The table will
20266 still be marked for re-alignment if the field did fill the entire column,
20267 because, in this case the deletion might narrow the column."
20268 (interactive "p")
20269 (save-match-data
20270 (org-check-before-invisible-edit 'delete)
20271 (if (and (org-at-table-p)
20272 (not (bolp))
20273 (not (= (char-after) ?|))
20274 (eq N 1))
20275 (if (looking-at ".*?|")
20276 (let ((pos (point))
20277 (noalign (looking-at "[^|\n\r]* |"))
20278 (c org-table-may-need-update))
20279 (replace-match
20280 (concat (substring (match-string 0) 1 -1) " |") nil t)
20281 (goto-char pos)
20282 ;; noalign: if there were two spaces at the end, this field
20283 ;; does not determine the width of the column.
20284 (when noalign (setq org-table-may-need-update c)))
20285 (delete-char N))
20286 (delete-char N)
20287 (org-fix-tags-on-the-fly))))
20289 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20290 (put 'org-self-insert-command 'delete-selection
20291 (lambda ()
20292 (not (run-hook-with-args-until-success
20293 'self-insert-uses-region-functions))))
20294 (put 'orgtbl-self-insert-command 'delete-selection
20295 (lambda ()
20296 (not (run-hook-with-args-until-success
20297 'self-insert-uses-region-functions))))
20298 (put 'org-delete-char 'delete-selection 'supersede)
20299 (put 'org-delete-backward-char 'delete-selection 'supersede)
20300 (put 'org-yank 'delete-selection 'yank)
20302 ;; Make `flyspell-mode' delay after some commands
20303 (put 'org-self-insert-command 'flyspell-delayed t)
20304 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20305 (put 'org-delete-char 'flyspell-delayed t)
20306 (put 'org-delete-backward-char 'flyspell-delayed t)
20308 ;; Make pabbrev-mode expand after Org mode commands
20309 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20310 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20312 (defun org-remap (map &rest commands)
20313 "In MAP, remap the functions given in COMMANDS.
20314 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20315 (let (new old)
20316 (while commands
20317 (setq old (pop commands) new (pop commands))
20318 (org-defkey map (vector 'remap old) new))))
20320 (defun org-transpose-words ()
20321 "Transpose words for Org.
20322 This uses the `org-mode-transpose-word-syntax-table' syntax
20323 table, which interprets characters in `org-emphasis-alist' as
20324 word constituents."
20325 (interactive)
20326 (with-syntax-table org-mode-transpose-word-syntax-table
20327 (call-interactively 'transpose-words)))
20328 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20330 (when (eq org-enable-table-editor 'optimized)
20331 ;; If the user wants maximum table support, we need to hijack
20332 ;; some standard editing functions
20333 (org-remap org-mode-map
20334 'self-insert-command 'org-self-insert-command
20335 'delete-char 'org-delete-char
20336 'delete-backward-char 'org-delete-backward-char)
20337 (org-defkey org-mode-map "|" 'org-force-self-insert))
20339 (defvar org-ctrl-c-ctrl-c-hook nil
20340 "Hook for functions attaching themselves to `C-c C-c'.
20342 This can be used to add additional functionality to the C-c C-c
20343 key which executes context-dependent commands. This hook is run
20344 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20345 run after the last test.
20347 Each function will be called with no arguments. The function
20348 must check if the context is appropriate for it to act. If yes,
20349 it should do its thing and then return a non-nil value. If the
20350 context is wrong, just do nothing and return nil.")
20352 (defvar org-ctrl-c-ctrl-c-final-hook nil
20353 "Hook for functions attaching themselves to `C-c C-c'.
20355 This can be used to add additional functionality to the C-c C-c
20356 key which executes context-dependent commands. This hook is run
20357 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20358 before the first test.
20360 Each function will be called with no arguments. The function
20361 must check if the context is appropriate for it to act. If yes,
20362 it should do its thing and then return a non-nil value. If the
20363 context is wrong, just do nothing and return nil.")
20365 (defvar org-tab-first-hook nil
20366 "Hook for functions to attach themselves to TAB.
20367 See `org-ctrl-c-ctrl-c-hook' for more information.
20368 This hook runs as the first action when TAB is pressed, even before
20369 `org-cycle' messes around with the `outline-regexp' to cater for
20370 inline tasks and plain list item folding.
20371 If any function in this hook returns t, any other actions that
20372 would have been caused by TAB (such as table field motion or visibility
20373 cycling) will not occur.")
20375 (defvar org-tab-after-check-for-table-hook nil
20376 "Hook for functions to attach themselves to TAB.
20377 See `org-ctrl-c-ctrl-c-hook' for more information.
20378 This hook runs after it has been established that the cursor is not in a
20379 table, but before checking if the cursor is in a headline or if global cycling
20380 should be done.
20381 If any function in this hook returns t, not other actions like visibility
20382 cycling will be done.")
20384 (defvar org-tab-after-check-for-cycling-hook nil
20385 "Hook for functions to attach themselves to TAB.
20386 See `org-ctrl-c-ctrl-c-hook' for more information.
20387 This hook runs after it has been established that not table field motion and
20388 not visibility should be done because of current context. This is probably
20389 the place where a package like yasnippets can hook in.")
20391 (defvar org-tab-before-tab-emulation-hook nil
20392 "Hook for functions to attach themselves to TAB.
20393 See `org-ctrl-c-ctrl-c-hook' for more information.
20394 This hook runs after every other options for TAB have been exhausted, but
20395 before indentation and \t insertion takes place.")
20397 (defvar org-metaleft-hook nil
20398 "Hook for functions attaching themselves to `M-left'.
20399 See `org-ctrl-c-ctrl-c-hook' for more information.")
20400 (defvar org-metaright-hook nil
20401 "Hook for functions attaching themselves to `M-right'.
20402 See `org-ctrl-c-ctrl-c-hook' for more information.")
20403 (defvar org-metaup-hook nil
20404 "Hook for functions attaching themselves to `M-up'.
20405 See `org-ctrl-c-ctrl-c-hook' for more information.")
20406 (defvar org-metadown-hook nil
20407 "Hook for functions attaching themselves to `M-down'.
20408 See `org-ctrl-c-ctrl-c-hook' for more information.")
20409 (defvar org-shiftmetaleft-hook nil
20410 "Hook for functions attaching themselves to `M-S-left'.
20411 See `org-ctrl-c-ctrl-c-hook' for more information.")
20412 (defvar org-shiftmetaright-hook nil
20413 "Hook for functions attaching themselves to `M-S-right'.
20414 See `org-ctrl-c-ctrl-c-hook' for more information.")
20415 (defvar org-shiftmetaup-hook nil
20416 "Hook for functions attaching themselves to `M-S-up'.
20417 See `org-ctrl-c-ctrl-c-hook' for more information.")
20418 (defvar org-shiftmetadown-hook nil
20419 "Hook for functions attaching themselves to `M-S-down'.
20420 See `org-ctrl-c-ctrl-c-hook' for more information.")
20421 (defvar org-metareturn-hook nil
20422 "Hook for functions attaching themselves to `M-RET'.
20423 See `org-ctrl-c-ctrl-c-hook' for more information.")
20424 (defvar org-shiftup-hook nil
20425 "Hook for functions attaching themselves to `S-up'.
20426 See `org-ctrl-c-ctrl-c-hook' for more information.")
20427 (defvar org-shiftup-final-hook nil
20428 "Hook for functions attaching themselves to `S-up'.
20429 This one runs after all other options except shift-select have been excluded.
20430 See `org-ctrl-c-ctrl-c-hook' for more information.")
20431 (defvar org-shiftdown-hook nil
20432 "Hook for functions attaching themselves to `S-down'.
20433 See `org-ctrl-c-ctrl-c-hook' for more information.")
20434 (defvar org-shiftdown-final-hook nil
20435 "Hook for functions attaching themselves to `S-down'.
20436 This one runs after all other options except shift-select have been excluded.
20437 See `org-ctrl-c-ctrl-c-hook' for more information.")
20438 (defvar org-shiftleft-hook nil
20439 "Hook for functions attaching themselves to `S-left'.
20440 See `org-ctrl-c-ctrl-c-hook' for more information.")
20441 (defvar org-shiftleft-final-hook nil
20442 "Hook for functions attaching themselves to `S-left'.
20443 This one runs after all other options except shift-select have been excluded.
20444 See `org-ctrl-c-ctrl-c-hook' for more information.")
20445 (defvar org-shiftright-hook nil
20446 "Hook for functions attaching themselves to `S-right'.
20447 See `org-ctrl-c-ctrl-c-hook' for more information.")
20448 (defvar org-shiftright-final-hook nil
20449 "Hook for functions attaching themselves to `S-right'.
20450 This one runs after all other options except shift-select have been excluded.
20451 See `org-ctrl-c-ctrl-c-hook' for more information.")
20453 (defun org-modifier-cursor-error ()
20454 "Throw an error, a modified cursor command was applied in wrong context."
20455 (user-error "This command is active in special context like tables, headlines or items"))
20457 (defun org-shiftselect-error ()
20458 "Throw an error because Shift-Cursor command was applied in wrong context."
20459 (if (and (boundp 'shift-select-mode) shift-select-mode)
20460 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20461 (user-error "This command works only in special context like headlines or timestamps")))
20463 (defun org-call-for-shift-select (cmd)
20464 (let ((this-command-keys-shift-translated t))
20465 (call-interactively cmd)))
20467 (defun org-shifttab (&optional arg)
20468 "Global visibility cycling or move to previous table field.
20469 Call `org-table-previous-field' within a table.
20470 When ARG is nil, cycle globally through visibility states.
20471 When ARG is a numeric prefix, show contents of this level."
20472 (interactive "P")
20473 (cond
20474 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20475 ((integerp arg)
20476 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20477 (message "Content view to level: %d" arg)
20478 (org-content (prefix-numeric-value arg2))
20479 (org-cycle-show-empty-lines t)
20480 (setq org-cycle-global-status 'overview)))
20481 (t (call-interactively 'org-global-cycle))))
20483 (defun org-shiftmetaleft ()
20484 "Promote subtree or delete table column.
20485 Calls `org-promote-subtree', `org-outdent-item-tree', or
20486 `org-table-delete-column', depending on context. See the
20487 individual commands for more information."
20488 (interactive)
20489 (cond
20490 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20491 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20492 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20493 ((if (not (org-region-active-p)) (org-at-item-p)
20494 (save-excursion (goto-char (region-beginning))
20495 (org-at-item-p)))
20496 (call-interactively 'org-outdent-item-tree))
20497 (t (org-modifier-cursor-error))))
20499 (defun org-shiftmetaright ()
20500 "Demote subtree or insert table column.
20501 Calls `org-demote-subtree', `org-indent-item-tree', or
20502 `org-table-insert-column', depending on context. See the
20503 individual commands for more information."
20504 (interactive)
20505 (cond
20506 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20507 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20508 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20509 ((if (not (org-region-active-p)) (org-at-item-p)
20510 (save-excursion (goto-char (region-beginning))
20511 (org-at-item-p)))
20512 (call-interactively 'org-indent-item-tree))
20513 (t (org-modifier-cursor-error))))
20515 (defun org-shiftmetaup (&optional _arg)
20516 "Drag the line at point up.
20517 In a table, kill the current row.
20518 On a clock timestamp, update the value of the timestamp like `S-<up>'
20519 but also adjust the previous clocked item in the clock history.
20520 Everywhere else, drag the line at point up."
20521 (interactive "P")
20522 (cond
20523 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20524 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20525 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20526 (call-interactively 'org-timestamp-up)))
20527 (t (call-interactively 'org-drag-line-backward))))
20529 (defun org-shiftmetadown (&optional _arg)
20530 "Drag the line at point down.
20531 In a table, insert an empty row at the current line.
20532 On a clock timestamp, update the value of the timestamp like `S-<down>'
20533 but also adjust the previous clocked item in the clock history.
20534 Everywhere else, drag the line at point down."
20535 (interactive "P")
20536 (cond
20537 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20538 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20539 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20540 (call-interactively 'org-timestamp-down)))
20541 (t (call-interactively 'org-drag-line-forward))))
20543 (defsubst org-hidden-tree-error ()
20544 (user-error
20545 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20547 (defun org-metaleft (&optional _arg)
20548 "Promote heading, list item at point or move table column left.
20550 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20551 depending on context. With no specific context, calls the Emacs
20552 default `backward-word'. See the individual commands for more
20553 information.
20555 This function runs the hook `org-metaleft-hook' as a first step,
20556 and returns at first non-nil value."
20557 (interactive "P")
20558 (cond
20559 ((run-hook-with-args-until-success 'org-metaleft-hook))
20560 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20561 ((org-with-limited-levels
20562 (or (org-at-heading-p)
20563 (and (org-region-active-p)
20564 (save-excursion
20565 (goto-char (region-beginning))
20566 (org-at-heading-p)))))
20567 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20568 (call-interactively 'org-do-promote))
20569 ;; At an inline task.
20570 ((org-at-heading-p)
20571 (call-interactively 'org-inlinetask-promote))
20572 ((or (org-at-item-p)
20573 (and (org-region-active-p)
20574 (save-excursion
20575 (goto-char (region-beginning))
20576 (org-at-item-p))))
20577 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20578 (call-interactively 'org-outdent-item))
20579 (t (call-interactively 'backward-word))))
20581 (defun org-metaright (&optional _arg)
20582 "Demote heading, list item at point or move table column right.
20584 In front of a drawer or a block keyword, indent it correctly.
20586 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20587 `org-indent-drawer' or `org-indent-block' depending on context.
20588 With no specific context, calls the Emacs default `forward-word'.
20589 See the individual commands for more information.
20591 This function runs the hook `org-metaright-hook' as a first step,
20592 and returns at first non-nil value."
20593 (interactive "P")
20594 (cond
20595 ((run-hook-with-args-until-success 'org-metaright-hook))
20596 ((org-at-table-p) (call-interactively 'org-table-move-column))
20597 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20598 ((org-at-block-p) (call-interactively 'org-indent-block))
20599 ((org-with-limited-levels
20600 (or (org-at-heading-p)
20601 (and (org-region-active-p)
20602 (save-excursion
20603 (goto-char (region-beginning))
20604 (org-at-heading-p)))))
20605 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20606 (call-interactively 'org-do-demote))
20607 ;; At an inline task.
20608 ((org-at-heading-p)
20609 (call-interactively 'org-inlinetask-demote))
20610 ((or (org-at-item-p)
20611 (and (org-region-active-p)
20612 (save-excursion
20613 (goto-char (region-beginning))
20614 (org-at-item-p))))
20615 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20616 (call-interactively 'org-indent-item))
20617 (t (call-interactively 'forward-word))))
20619 (defun org-check-for-hidden (what)
20620 "Check if there are hidden headlines/items in the current visual line.
20621 WHAT can be either `headlines' or `items'. If the current line is
20622 an outline or item heading and it has a folded subtree below it,
20623 this function returns t, nil otherwise."
20624 (let ((re (cond
20625 ((eq what 'headlines) org-outline-regexp-bol)
20626 ((eq what 'items) (org-item-beginning-re))
20627 (t (error "This should not happen"))))
20628 beg end)
20629 (save-excursion
20630 (catch 'exit
20631 (unless (org-region-active-p)
20632 (setq beg (point-at-bol))
20633 (beginning-of-line 2)
20634 (while (and (not (eobp)) ;; this is like `next-line'
20635 (get-char-property (1- (point)) 'invisible))
20636 (beginning-of-line 2))
20637 (setq end (point))
20638 (goto-char beg)
20639 (goto-char (point-at-eol))
20640 (setq end (max end (point)))
20641 (while (re-search-forward re end t)
20642 (when (get-char-property (match-beginning 0) 'invisible)
20643 (throw 'exit t))))
20644 nil))))
20646 (defun org-metaup (&optional _arg)
20647 "Move subtree up or move table row up.
20648 Calls `org-move-subtree-up' or `org-table-move-row' or
20649 `org-move-item-up', depending on context. See the individual commands
20650 for more information."
20651 (interactive "P")
20652 (cond
20653 ((run-hook-with-args-until-success 'org-metaup-hook))
20654 ((org-region-active-p)
20655 (let* ((a (min (region-beginning) (region-end)))
20656 (b (1- (max (region-beginning) (region-end))))
20657 (c (save-excursion (goto-char a)
20658 (move-beginning-of-line 0)))
20659 (d (save-excursion (goto-char a)
20660 (move-end-of-line 0) (point))))
20661 (transpose-regions a b c d)
20662 (goto-char c)))
20663 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20664 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20665 ((org-at-item-p) (call-interactively 'org-move-item-up))
20666 (t (org-drag-element-backward))))
20668 (defun org-metadown (&optional _arg)
20669 "Move subtree down or move table row down.
20670 Calls `org-move-subtree-down' or `org-table-move-row' or
20671 `org-move-item-down', depending on context. See the individual
20672 commands for more information."
20673 (interactive "P")
20674 (cond
20675 ((run-hook-with-args-until-success 'org-metadown-hook))
20676 ((org-region-active-p)
20677 (let* ((a (min (region-beginning) (region-end)))
20678 (b (max (region-beginning) (region-end)))
20679 (c (save-excursion (goto-char b)
20680 (move-beginning-of-line 1)))
20681 (d (save-excursion (goto-char b)
20682 (move-end-of-line 1) (1+ (point)))))
20683 (transpose-regions a b c d)
20684 (goto-char d)))
20685 ((org-at-table-p) (call-interactively 'org-table-move-row))
20686 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20687 ((org-at-item-p) (call-interactively 'org-move-item-down))
20688 (t (org-drag-element-forward))))
20690 (defun org-shiftup (&optional arg)
20691 "Increase item in timestamp or increase priority of current headline.
20692 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20693 depending on context. See the individual commands for more information."
20694 (interactive "P")
20695 (cond
20696 ((run-hook-with-args-until-success 'org-shiftup-hook))
20697 ((and org-support-shift-select (org-region-active-p))
20698 (org-call-for-shift-select 'previous-line))
20699 ((org-at-timestamp-p t)
20700 (call-interactively (if org-edit-timestamp-down-means-later
20701 'org-timestamp-down 'org-timestamp-up)))
20702 ((and (not (eq org-support-shift-select 'always))
20703 org-enable-priority-commands
20704 (org-at-heading-p))
20705 (call-interactively 'org-priority-up))
20706 ((and (not org-support-shift-select) (org-at-item-p))
20707 (call-interactively 'org-previous-item))
20708 ((org-clocktable-try-shift 'up arg))
20709 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20710 (org-support-shift-select
20711 (org-call-for-shift-select 'previous-line))
20712 (t (org-shiftselect-error))))
20714 (defun org-shiftdown (&optional arg)
20715 "Decrease item in timestamp or decrease priority of current headline.
20716 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20717 depending on context. See the individual commands for more information."
20718 (interactive "P")
20719 (cond
20720 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20721 ((and org-support-shift-select (org-region-active-p))
20722 (org-call-for-shift-select 'next-line))
20723 ((org-at-timestamp-p t)
20724 (call-interactively (if org-edit-timestamp-down-means-later
20725 'org-timestamp-up 'org-timestamp-down)))
20726 ((and (not (eq org-support-shift-select 'always))
20727 org-enable-priority-commands
20728 (org-at-heading-p))
20729 (call-interactively 'org-priority-down))
20730 ((and (not org-support-shift-select) (org-at-item-p))
20731 (call-interactively 'org-next-item))
20732 ((org-clocktable-try-shift 'down arg))
20733 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20734 (org-support-shift-select
20735 (org-call-for-shift-select 'next-line))
20736 (t (org-shiftselect-error))))
20738 (defun org-shiftright (&optional arg)
20739 "Cycle the thing at point or in the current line, depending on context.
20740 Depending on context, this does one of the following:
20742 - switch a timestamp at point one day into the future
20743 - on a headline, switch to the next TODO keyword.
20744 - on an item, switch entire list to the next bullet type
20745 - on a property line, switch to the next allowed value
20746 - on a clocktable definition line, move time block into the future"
20747 (interactive "P")
20748 (cond
20749 ((run-hook-with-args-until-success 'org-shiftright-hook))
20750 ((and org-support-shift-select (org-region-active-p))
20751 (org-call-for-shift-select 'forward-char))
20752 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20753 ((and (not (eq org-support-shift-select 'always))
20754 (org-at-heading-p))
20755 (let ((org-inhibit-logging
20756 (not org-treat-S-cursor-todo-selection-as-state-change))
20757 (org-inhibit-blocking
20758 (not org-treat-S-cursor-todo-selection-as-state-change)))
20759 (org-call-with-arg 'org-todo 'right)))
20760 ((or (and org-support-shift-select
20761 (not (eq org-support-shift-select 'always))
20762 (org-at-item-bullet-p))
20763 (and (not org-support-shift-select) (org-at-item-p)))
20764 (org-call-with-arg 'org-cycle-list-bullet nil))
20765 ((and (not (eq org-support-shift-select 'always))
20766 (org-at-property-p))
20767 (call-interactively 'org-property-next-allowed-value))
20768 ((org-clocktable-try-shift 'right arg))
20769 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20770 (org-support-shift-select
20771 (org-call-for-shift-select 'forward-char))
20772 (t (org-shiftselect-error))))
20774 (defun org-shiftleft (&optional arg)
20775 "Cycle the thing at point or in the current line, depending on context.
20776 Depending on context, this does one of the following:
20778 - switch a timestamp at point one day into the past
20779 - on a headline, switch to the previous TODO keyword.
20780 - on an item, switch entire list to the previous bullet type
20781 - on a property line, switch to the previous allowed value
20782 - on a clocktable definition line, move time block into the past"
20783 (interactive "P")
20784 (cond
20785 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20786 ((and org-support-shift-select (org-region-active-p))
20787 (org-call-for-shift-select 'backward-char))
20788 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20789 ((and (not (eq org-support-shift-select 'always))
20790 (org-at-heading-p))
20791 (let ((org-inhibit-logging
20792 (not org-treat-S-cursor-todo-selection-as-state-change))
20793 (org-inhibit-blocking
20794 (not org-treat-S-cursor-todo-selection-as-state-change)))
20795 (org-call-with-arg 'org-todo 'left)))
20796 ((or (and org-support-shift-select
20797 (not (eq org-support-shift-select 'always))
20798 (org-at-item-bullet-p))
20799 (and (not org-support-shift-select) (org-at-item-p)))
20800 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20801 ((and (not (eq org-support-shift-select 'always))
20802 (org-at-property-p))
20803 (call-interactively 'org-property-previous-allowed-value))
20804 ((org-clocktable-try-shift 'left arg))
20805 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20806 (org-support-shift-select
20807 (org-call-for-shift-select 'backward-char))
20808 (t (org-shiftselect-error))))
20810 (defun org-shiftcontrolright ()
20811 "Switch to next TODO set."
20812 (interactive)
20813 (cond
20814 ((and org-support-shift-select (org-region-active-p))
20815 (org-call-for-shift-select 'forward-word))
20816 ((and (not (eq org-support-shift-select 'always))
20817 (org-at-heading-p))
20818 (org-call-with-arg 'org-todo 'nextset))
20819 (org-support-shift-select
20820 (org-call-for-shift-select 'forward-word))
20821 (t (org-shiftselect-error))))
20823 (defun org-shiftcontrolleft ()
20824 "Switch to previous TODO set."
20825 (interactive)
20826 (cond
20827 ((and org-support-shift-select (org-region-active-p))
20828 (org-call-for-shift-select 'backward-word))
20829 ((and (not (eq org-support-shift-select 'always))
20830 (org-at-heading-p))
20831 (org-call-with-arg 'org-todo 'previousset))
20832 (org-support-shift-select
20833 (org-call-for-shift-select 'backward-word))
20834 (t (org-shiftselect-error))))
20836 (defun org-shiftcontrolup (&optional n)
20837 "Change timestamps synchronously up in CLOCK log lines.
20838 Optional argument N tells to change by that many units."
20839 (interactive "P")
20840 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20841 (let (org-support-shift-select)
20842 (org-clock-timestamps-up n))
20843 (user-error "Not at a clock log")))
20845 (defun org-shiftcontroldown (&optional n)
20846 "Change timestamps synchronously down in CLOCK log lines.
20847 Optional argument N tells to change by that many units."
20848 (interactive "P")
20849 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20850 (let (org-support-shift-select)
20851 (org-clock-timestamps-down n))
20852 (user-error "Not at a clock log")))
20854 (defun org-increase-number-at-point (&optional inc)
20855 "Increment the number at point.
20856 With an optional prefix numeric argument INC, increment using
20857 this numeric value."
20858 (interactive "p")
20859 (if (not (number-at-point))
20860 (user-error "Not on a number")
20861 (unless inc (setq inc 1))
20862 (let ((pos (point))
20863 (beg (skip-chars-backward "-+^/*0-9eE."))
20864 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20865 (setq nap (buffer-substring-no-properties
20866 (+ pos beg) (+ pos beg end)))
20867 (delete-region (+ pos beg) (+ pos beg end))
20868 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20869 (when (org-at-table-p)
20870 (org-table-align)
20871 (org-table-end-of-field 1))))
20873 (defun org-decrease-number-at-point (&optional inc)
20874 "Decrement the number at point.
20875 With an optional prefix numeric argument INC, decrement using
20876 this numeric value."
20877 (interactive "p")
20878 (org-increase-number-at-point (- (or inc 1))))
20880 (defun org-ctrl-c-ret ()
20881 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20882 (interactive)
20883 (cond
20884 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20885 (t (call-interactively 'org-insert-heading))))
20887 (defun org-find-visible ()
20888 (let ((s (point)))
20889 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20890 (get-char-property s 'invisible)))
20892 (defun org-find-invisible ()
20893 (let ((s (point)))
20894 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20895 (not (get-char-property s 'invisible))))
20898 (defun org-copy-visible (beg end)
20899 "Copy the visible parts of the region."
20900 (interactive "r")
20901 (let ((result ""))
20902 (while (/= beg end)
20903 (when (get-char-property beg 'invisible)
20904 (setq beg (next-single-char-property-change beg 'invisible nil end)))
20905 (let ((next (next-single-char-property-change beg 'invisible nil end)))
20906 (setq result (concat result (buffer-substring beg next)))
20907 (setq beg next)))
20908 (kill-new result)))
20910 (defun org-copy-special ()
20911 "Copy region in table or copy current subtree.
20912 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20913 context. See the individual commands for more information."
20914 (interactive)
20915 (call-interactively
20916 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20918 (defun org-cut-special ()
20919 "Cut region in table or cut current subtree.
20920 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20921 context. See the individual commands for more information."
20922 (interactive)
20923 (call-interactively
20924 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20926 (defun org-paste-special (arg)
20927 "Paste rectangular region into table, or past subtree relative to level.
20928 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20929 See the individual commands for more information."
20930 (interactive "P")
20931 (if (org-at-table-p)
20932 (org-table-paste-rectangle)
20933 (org-paste-subtree arg)))
20935 (defun org-edit-special (&optional arg)
20936 "Call a special editor for the element at point.
20937 When at a table, call the formula editor with `org-table-edit-formulas'.
20938 When in a source code block, call `org-edit-src-code'.
20939 When in a fixed-width region, call `org-edit-fixed-width-region'.
20940 When in an export block, call `org-edit-export-block'.
20941 When at an #+INCLUDE keyword, visit the included file.
20942 When at a footnote reference, call `org-edit-footnote-reference'
20943 On a link, call `ffap' to visit the link at point.
20944 Otherwise, return a user error."
20945 (interactive "P")
20946 (let ((element (org-element-at-point)))
20947 (barf-if-buffer-read-only)
20948 (pcase (org-element-type element)
20949 (`src-block
20950 (if (not arg) (org-edit-src-code)
20951 (let* ((info (org-babel-get-src-block-info))
20952 (lang (nth 0 info))
20953 (params (nth 2 info))
20954 (session (cdr (assq :session params))))
20955 (if (not session) (org-edit-src-code)
20956 ;; At a src-block with a session and function called with
20957 ;; an ARG: switch to the buffer related to the inferior
20958 ;; process.
20959 (switch-to-buffer
20960 (funcall (intern (concat "org-babel-prep-session:" lang))
20961 session params))))))
20962 (`keyword
20963 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20964 (org-open-link-from-string
20965 (format "[[%s]]"
20966 (expand-file-name
20967 (let ((value (org-element-property :value element)))
20968 (cond ((not (org-string-nw-p value))
20969 (user-error "No file to edit"))
20970 ((string-match "\\`\"\\(.*?\\)\"" value)
20971 (match-string 1 value))
20972 ((string-match "\\`[^ \t\"]\\S-*" value)
20973 (match-string 0 value))
20974 (t (user-error "No valid file specified")))))))
20975 (user-error "No special environment to edit here")))
20976 (`table
20977 (if (eq (org-element-property :type element) 'table.el)
20978 (org-edit-table.el)
20979 (call-interactively 'org-table-edit-formulas)))
20980 ;; Only Org tables contain `table-row' type elements.
20981 (`table-row (call-interactively 'org-table-edit-formulas))
20982 (`example-block (org-edit-src-code))
20983 (`export-block (org-edit-export-block))
20984 (`fixed-width (org-edit-fixed-width-region))
20986 ;; No notable element at point. Though, we may be at a link or
20987 ;; a footnote reference, which are objects. Thus, scan deeper.
20988 (let ((context (org-element-context element)))
20989 (pcase (org-element-type context)
20990 (`footnote-reference (org-edit-footnote-reference))
20991 (`inline-src-block (org-edit-inline-src-code))
20992 (`link (call-interactively #'ffap))
20993 (_ (user-error "No special environment to edit here"))))))))
20995 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20996 (defun org-ctrl-c-ctrl-c (&optional arg)
20997 "Set tags in headline, or update according to changed information at point.
20999 This command does many different things, depending on context:
21001 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21002 this is what we do.
21004 - If the cursor is on a statistics cookie, update it.
21006 - If the cursor is in a headline, prompt for tags and insert them
21007 into the current line, aligned to `org-tags-column'. When called
21008 with prefix arg, realign all tags in the current buffer.
21010 - If the cursor is in one of the special #+KEYWORD lines, this
21011 triggers scanning the buffer for these lines and updating the
21012 information.
21014 - If the cursor is inside a table, realign the table. This command
21015 works even if the automatic table editor has been turned off.
21017 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21018 the entire table.
21020 - If the cursor is at a footnote reference or definition, jump to
21021 the corresponding definition or references, respectively.
21023 - If the cursor is a the beginning of a dynamic block, update it.
21025 - If the current buffer is a capture buffer, close note and file it.
21027 - If the cursor is on a <<<target>>>, update radio targets and
21028 corresponding links in this buffer.
21030 - If the cursor is on a numbered item in a plain list, renumber the
21031 ordered list.
21033 - If the cursor is on a checkbox, toggle it.
21035 - If the cursor is on a code block, evaluate it. The variable
21036 `org-confirm-babel-evaluate' can be used to control prompting
21037 before code block evaluation, by default every code block
21038 evaluation requires confirmation. Code block evaluation can be
21039 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21040 (interactive "P")
21041 (cond
21042 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
21043 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21044 (org-remove-occur-highlights)
21045 (message "Temporary highlights/overlays removed from current buffer"))
21046 ((and (local-variable-p 'org-finish-function)
21047 (fboundp org-finish-function))
21048 (funcall org-finish-function))
21049 ((org-babel-hash-at-point))
21050 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21052 (let* ((context
21053 (org-element-lineage
21054 (org-element-context)
21055 ;; Limit to supported contexts.
21056 '(babel-call clock dynamic-block footnote-definition
21057 footnote-reference inline-babel-call inline-src-block
21058 inlinetask item keyword node-property paragraph
21059 plain-list property-drawer radio-target src-block
21060 statistics-cookie table table-cell table-row
21061 timestamp)
21063 (type (org-element-type context)))
21064 ;; For convenience: at the first line of a paragraph on the same
21065 ;; line as an item, apply function on that item instead.
21066 (when (eq type 'paragraph)
21067 (let ((parent (org-element-property :parent context)))
21068 (when (and (eq (org-element-type parent) 'item)
21069 (= (line-beginning-position)
21070 (org-element-property :begin parent)))
21071 (setq context parent)
21072 (setq type 'item))))
21073 ;; Act according to type of element or object at point.
21075 ;; Do nothing on a blank line, except if it is contained in
21076 ;; a src block. Hence, we first check if point is in such
21077 ;; a block and then if it is at a blank line.
21078 (pcase type
21079 ((or `inline-src-block `src-block)
21080 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
21081 (org-babel-eval-wipe-error-buffer)
21082 (org-babel-execute-src-block
21083 current-prefix-arg (org-babel-get-src-block-info nil context))))
21084 ((guard (org-match-line "[ \t]*$"))
21085 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21086 (user-error
21087 (substitute-command-keys
21088 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
21089 ((or `babel-call `inline-babel-call)
21090 (let ((info (org-babel-lob-get-info context)))
21091 (when info (org-babel-execute-src-block nil info))))
21092 (`clock (org-clock-update-time-maybe))
21093 (`dynamic-block
21094 (save-excursion
21095 (goto-char (org-element-property :post-affiliated context))
21096 (org-update-dblock)))
21097 (`footnote-definition
21098 (goto-char (org-element-property :post-affiliated context))
21099 (call-interactively 'org-footnote-action))
21100 (`footnote-reference (call-interactively #'org-footnote-action))
21101 ((or `headline `inlinetask)
21102 (save-excursion (goto-char (org-element-property :begin context))
21103 (call-interactively #'org-set-tags)))
21104 (`item
21105 ;; At an item: `C-u C-u' sets checkbox to "[-]"
21106 ;; unconditionally, whereas `C-u' will toggle its presence.
21107 ;; Without a universal argument, if the item has a checkbox,
21108 ;; toggle it. Otherwise repair the list.
21109 (let* ((box (org-element-property :checkbox context))
21110 (struct (org-element-property :structure context))
21111 (old-struct (copy-tree struct))
21112 (parents (org-list-parents-alist struct))
21113 (prevs (org-list-prevs-alist struct))
21114 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21115 (org-list-set-checkbox
21116 (org-element-property :begin context) struct
21117 (cond ((equal arg '(16)) "[-]")
21118 ((and (not box) (equal arg '(4))) "[ ]")
21119 ((or (not box) (equal arg '(4))) nil)
21120 ((eq box 'on) "[ ]")
21121 (t "[X]")))
21122 ;; Mimic `org-list-write-struct' but with grabbing a return
21123 ;; value from `org-list-struct-fix-box'.
21124 (org-list-struct-fix-ind struct parents 2)
21125 (org-list-struct-fix-item-end struct)
21126 (org-list-struct-fix-bul struct prevs)
21127 (org-list-struct-fix-ind struct parents)
21128 (let ((block-item
21129 (org-list-struct-fix-box struct parents prevs orderedp)))
21130 (if (and box (equal struct old-struct))
21131 (if (equal arg '(16))
21132 (message "Checkboxes already reset")
21133 (user-error "Cannot toggle this checkbox: %s"
21134 (if (eq box 'on)
21135 "all subitems checked"
21136 "unchecked subitems")))
21137 (org-list-struct-apply-struct struct old-struct)
21138 (org-update-checkbox-count-maybe))
21139 (when block-item
21140 (message "Checkboxes were removed due to empty box at line %d"
21141 (org-current-line block-item))))))
21142 (`keyword
21143 (let ((org-inhibit-startup-visibility-stuff t)
21144 (org-startup-align-all-tables nil))
21145 (when (boundp 'org-table-coordinate-overlays)
21146 (mapc #'delete-overlay org-table-coordinate-overlays)
21147 (setq org-table-coordinate-overlays nil))
21148 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21149 (message "Local setup has been refreshed"))
21150 (`plain-list
21151 ;; At a plain list, with a double C-u argument, set
21152 ;; checkboxes of each item to "[-]", whereas a single one
21153 ;; will toggle their presence according to the state of the
21154 ;; first item in the list. Without an argument, repair the
21155 ;; list.
21156 (let* ((begin (org-element-property :contents-begin context))
21157 (beginm (move-marker (make-marker) begin))
21158 (struct (org-element-property :structure context))
21159 (old-struct (copy-tree struct))
21160 (first-box (save-excursion
21161 (goto-char begin)
21162 (looking-at org-list-full-item-re)
21163 (match-string-no-properties 3)))
21164 (new-box (cond ((equal arg '(16)) "[-]")
21165 ((equal arg '(4)) (unless first-box "[ ]"))
21166 ((equal first-box "[X]") "[ ]")
21167 (t "[X]"))))
21168 (cond
21169 (arg
21170 (dolist (pos
21171 (org-list-get-all-items
21172 begin struct (org-list-prevs-alist struct)))
21173 (org-list-set-checkbox pos struct new-box)))
21174 ((and first-box (eq (point) begin))
21175 ;; For convenience, when point is at bol on the first
21176 ;; item of the list and no argument is provided, simply
21177 ;; toggle checkbox of that item, if any.
21178 (org-list-set-checkbox begin struct new-box)))
21179 (org-list-write-struct
21180 struct (org-list-parents-alist struct) old-struct)
21181 (org-update-checkbox-count-maybe)
21182 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21183 ((or `property-drawer `node-property)
21184 (call-interactively #'org-property-action))
21185 (`radio-target
21186 (call-interactively #'org-update-radio-target-regexp))
21187 (`statistics-cookie
21188 (call-interactively #'org-update-statistics-cookies))
21189 ((or `table `table-cell `table-row)
21190 ;; At a table, recalculate every field and align it. Also
21191 ;; send the table if necessary. If the table has
21192 ;; a `table.el' type, just give up. At a table row or cell,
21193 ;; maybe recalculate line but always align table.
21194 (if (eq (org-element-property :type context) 'table.el)
21195 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21196 Use `\\[org-edit-special]' to edit table.el tables"))
21197 (let ((org-enable-table-editor t))
21198 (if (or (eq type 'table)
21199 ;; Check if point is at a TBLFM line.
21200 (and (eq type 'table-row)
21201 (= (point) (org-element-property :end context))))
21202 (save-excursion
21203 (if (org-at-TBLFM-p)
21204 (progn (require 'org-table)
21205 (org-table-calc-current-TBLFM))
21206 (goto-char (org-element-property :contents-begin context))
21207 (org-call-with-arg 'org-table-recalculate (or arg t))
21208 (orgtbl-send-table 'maybe)))
21209 (org-table-maybe-eval-formula)
21210 (cond (arg (call-interactively #'org-table-recalculate))
21211 ((org-table-maybe-recalculate-line))
21212 (t (org-table-align)))))))
21213 (`timestamp (org-timestamp-change 0 'day))
21214 ((and `nil (guard (org-at-heading-p)))
21215 ;; When point is on an unsupported object type, we can miss
21216 ;; the fact that it also is at a heading. Handle it here.
21217 (call-interactively #'org-set-tags))
21218 ((guard
21219 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
21221 (user-error
21222 (substitute-command-keys
21223 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
21225 (defun org-mode-restart ()
21226 (interactive)
21227 (let ((indent-status (bound-and-true-p org-indent-mode)))
21228 (funcall major-mode)
21229 (hack-local-variables)
21230 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21231 (org-indent-mode -1)))
21232 (message "%s restarted" major-mode))
21234 (defun org-kill-note-or-show-branches ()
21235 "Abort storing current note, or call `outline-show-branches'."
21236 (interactive)
21237 (if (not org-finish-function)
21238 (progn
21239 (outline-hide-subtree)
21240 (call-interactively 'outline-show-branches))
21241 (let ((org-note-abort t))
21242 (funcall org-finish-function))))
21244 (defun org-delete-indentation (&optional arg)
21245 "Join current line to previous and fix whitespace at join.
21247 If previous line is a headline add to headline title. Otherwise
21248 the function calls `delete-indentation'.
21250 With a non-nil optional argument, join it to the following one."
21251 (interactive "*P")
21252 (if (save-excursion
21253 (beginning-of-line (if arg 1 0))
21254 (let ((case-fold-search nil))
21255 (looking-at org-complex-heading-regexp)))
21256 ;; At headline.
21257 (let ((tags-column (when (match-beginning 5)
21258 (save-excursion (goto-char (match-beginning 5))
21259 (current-column))))
21260 (string (concat " " (progn (when arg (forward-line 1))
21261 (org-trim (delete-and-extract-region
21262 (line-beginning-position)
21263 (line-end-position)))))))
21264 (unless (bobp) (delete-region (point) (1- (point))))
21265 (goto-char (or (match-end 4)
21266 (match-beginning 5)
21267 (match-end 0)))
21268 (skip-chars-backward " \t")
21269 (save-excursion (insert string))
21270 ;; Adjust alignment of tags.
21271 (cond
21272 ((not tags-column)) ;no tags
21273 (org-auto-align-tags (org-set-tags nil t))
21274 (t (org--align-tags-here tags-column)))) ;preserve tags column
21275 (delete-indentation arg)))
21277 (defun org-open-line (n)
21278 "Insert a new row in tables, call `open-line' elsewhere.
21279 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21280 As a special case, when a document starts with a table, allow to
21281 call `open-line' on the very first character."
21282 (interactive "*p")
21283 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21284 (org-table-insert-row)
21285 (open-line n)))
21287 (defun org-return (&optional indent)
21288 "Goto next table row or insert a newline.
21290 Calls `org-table-next-row' or `newline', depending on context.
21292 When optional INDENT argument is non-nil, call
21293 `newline-and-indent' instead of `newline'.
21295 When `org-return-follows-link' is non-nil and point is on
21296 a timestamp or a link, call `org-open-at-point'. However, it
21297 will not happen if point is in a table or on a \"dead\"
21298 object (e.g., within a comment). In these case, you need to use
21299 `org-open-at-point' directly."
21300 (interactive)
21301 (let ((context (if org-return-follows-link (org-element-context)
21302 (org-element-at-point))))
21303 (cond
21304 ;; In a table, call `org-table-next-row'.
21305 ((or (and (eq (org-element-type context) 'table)
21306 (>= (point) (org-element-property :contents-begin context))
21307 (< (point) (org-element-property :contents-end context)))
21308 (org-element-lineage context '(table-row table-cell) t))
21309 (org-table-justify-field-maybe)
21310 (call-interactively #'org-table-next-row))
21311 ;; On a link or a timestamp, call `org-open-at-point' if
21312 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21313 ;; locations, e.g., in a comment, as `org-open-at-point'.
21314 ((and org-return-follows-link
21315 (or (org-in-regexp org-ts-regexp-both nil t)
21316 (org-in-regexp org-tsr-regexp-both nil t)
21317 (org-in-regexp org-any-link-re nil t)))
21318 (call-interactively #'org-open-at-point))
21319 ;; Insert newline in heading, but preserve tags.
21320 ((and (not (bolp))
21321 (save-excursion (beginning-of-line)
21322 (let ((case-fold-search nil))
21323 (looking-at org-complex-heading-regexp))))
21324 ;; At headline. Split line. However, if point is on keyword,
21325 ;; priority cookie or tags, do not break any of them: add
21326 ;; a newline after the headline instead.
21327 (let ((tags-column (and (match-beginning 5)
21328 (save-excursion (goto-char (match-beginning 5))
21329 (current-column))))
21330 (string
21331 (when (and (match-end 4) (org-point-in-group (point) 4))
21332 (delete-and-extract-region (point) (match-end 4)))))
21333 ;; Adjust tag alignment.
21334 (cond
21335 ((not (and tags-column string)))
21336 (org-auto-align-tags (org-set-tags nil t))
21337 (t (org--align-tags-here tags-column))) ;preserve tags column
21338 (end-of-line)
21339 (org-show-entry)
21340 (if indent (newline-and-indent) (newline))
21341 (when string (save-excursion (insert (org-trim string))))))
21342 ;; In a list, make sure indenting keeps trailing text within.
21343 ((and indent
21344 (not (eolp))
21345 (org-element-lineage context '(item)))
21346 (let ((trailing-data
21347 (delete-and-extract-region (point) (line-end-position))))
21348 (newline-and-indent)
21349 (save-excursion (insert trailing-data))))
21350 (t (if indent (newline-and-indent) (newline))))))
21352 (defun org-return-indent ()
21353 "Goto next table row or insert a newline and indent.
21354 Calls `org-table-next-row' or `newline-and-indent', depending on
21355 context. See the individual commands for more information."
21356 (interactive)
21357 (org-return t))
21359 (defun org-ctrl-c-star ()
21360 "Compute table, or change heading status of lines.
21361 Calls `org-table-recalculate' or `org-toggle-heading',
21362 depending on context."
21363 (interactive)
21364 (cond
21365 ((org-at-table-p)
21366 (call-interactively 'org-table-recalculate))
21368 ;; Convert all lines in region to list items
21369 (call-interactively 'org-toggle-heading))))
21371 (defun org-ctrl-c-minus ()
21372 "Insert separator line in table or modify bullet status of line.
21373 Also turns a plain line or a region of lines into list items.
21374 Calls `org-table-insert-hline', `org-toggle-item', or
21375 `org-cycle-list-bullet', depending on context."
21376 (interactive)
21377 (cond
21378 ((org-at-table-p)
21379 (call-interactively 'org-table-insert-hline))
21380 ((org-region-active-p)
21381 (call-interactively 'org-toggle-item))
21382 ((org-in-item-p)
21383 (call-interactively 'org-cycle-list-bullet))
21385 (call-interactively 'org-toggle-item))))
21387 (defun org-toggle-heading (&optional nstars)
21388 "Convert headings to normal text, or items or text to headings.
21389 If there is no active region, only convert the current line.
21391 With a `\\[universal-argument]' prefix, convert the whole list at
21392 point into heading.
21394 In a region:
21396 - If the first non blank line is a headline, remove the stars
21397 from all headlines in the region.
21399 - If it is a normal line, turn each and every normal line (i.e.,
21400 not an heading or an item) in the region into headings. If you
21401 want to convert only the first line of this region, use one
21402 universal prefix argument.
21404 - If it is a plain list item, turn all plain list items into headings.
21406 When converting a line into a heading, the number of stars is chosen
21407 such that the lines become children of the current entry. However,
21408 when a numeric prefix argument is given, its value determines the
21409 number of stars to add."
21410 (interactive "P")
21411 (let ((skip-blanks
21412 (function
21413 ;; Return beginning of first non-blank line, starting from
21414 ;; line at POS.
21415 (lambda (pos)
21416 (save-excursion
21417 (goto-char pos)
21418 (while (org-at-comment-p) (forward-line))
21419 (skip-chars-forward " \r\t\n")
21420 (point-at-bol)))))
21421 beg end toggled)
21422 ;; Determine boundaries of changes. If a universal prefix has
21423 ;; been given, put the list in a region. If region ends at a bol,
21424 ;; do not consider the last line to be in the region.
21426 (when (and current-prefix-arg (org-at-item-p))
21427 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21428 (org-mark-element))
21430 (if (org-region-active-p)
21431 (setq beg (funcall skip-blanks (region-beginning))
21432 end (copy-marker (save-excursion
21433 (goto-char (region-end))
21434 (if (bolp) (point) (point-at-eol)))))
21435 (setq beg (funcall skip-blanks (point-at-bol))
21436 end (copy-marker (point-at-eol))))
21437 ;; Ensure inline tasks don't count as headings.
21438 (org-with-limited-levels
21439 (save-excursion
21440 (goto-char beg)
21441 (cond
21442 ;; Case 1. Started at an heading: de-star headings.
21443 ((org-at-heading-p)
21444 (while (< (point) end)
21445 (when (org-at-heading-p t)
21446 (looking-at org-outline-regexp) (replace-match "")
21447 (setq toggled t))
21448 (forward-line)))
21449 ;; Case 2. Started at an item: change items into headlines.
21450 ;; One star will be added by `org-list-to-subtree'.
21451 ((org-at-item-p)
21452 (while (< (point) end)
21453 (when (org-at-item-p)
21454 ;; Pay attention to cases when region ends before list.
21455 (let* ((struct (org-list-struct))
21456 (list-end
21457 (min (org-list-get-bottom-point struct) (1+ end))))
21458 (save-restriction
21459 (narrow-to-region (point) list-end)
21460 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21461 (setq toggled t))
21462 (forward-line)))
21463 ;; Case 3. Started at normal text: make every line an heading,
21464 ;; skipping headlines and items.
21465 (t (let* ((stars
21466 (make-string
21467 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21468 (add-stars
21469 (cond (nstars "") ; stars from prefix only
21470 ((equal stars "") "*") ; before first heading
21471 (org-odd-levels-only "**") ; inside heading, odd
21472 (t "*"))) ; inside heading, oddeven
21473 (rpl (concat stars add-stars " "))
21474 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21475 (while (< (point) (if (equal nstars '(4)) lend end))
21476 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21477 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21478 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21479 (forward-line)))))))
21480 (unless toggled (message "Cannot toggle heading from here"))))
21482 (defun org-meta-return (&optional _arg)
21483 "Insert a new heading or wrap a region in a table.
21484 Calls `org-insert-heading' or `org-table-wrap-region', depending
21485 on context. See the individual commands for more information."
21486 (interactive)
21487 (org-check-before-invisible-edit 'insert)
21488 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21489 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21490 #'org-insert-heading))))
21492 ;;; Menu entries
21494 (defsubst org-in-subtree-not-table-p ()
21495 "Are we in a subtree and not in a table?"
21496 (and (not (org-before-first-heading-p))
21497 (not (org-at-table-p))))
21499 ;; Define the Org mode menus
21500 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21501 '("Tbl"
21502 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21503 ["Next Field" org-cycle (org-at-table-p)]
21504 ["Previous Field" org-shifttab (org-at-table-p)]
21505 ["Next Row" org-return (org-at-table-p)]
21506 "--"
21507 ["Blank Field" org-table-blank-field (org-at-table-p)]
21508 ["Edit Field" org-table-edit-field (org-at-table-p)]
21509 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21510 "--"
21511 ("Column"
21512 ["Move Column Left" org-metaleft (org-at-table-p)]
21513 ["Move Column Right" org-metaright (org-at-table-p)]
21514 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21515 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21516 ("Row"
21517 ["Move Row Up" org-metaup (org-at-table-p)]
21518 ["Move Row Down" org-metadown (org-at-table-p)]
21519 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21520 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21521 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21522 "--"
21523 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21524 ("Rectangle"
21525 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21526 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21527 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21528 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21529 "--"
21530 ("Calculate"
21531 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21532 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21533 ["Edit Formulas" org-edit-special (org-at-table-p)]
21534 "--"
21535 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21536 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21537 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21538 "--"
21539 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21540 "--"
21541 ["Sum Column/Rectangle" org-table-sum
21542 (or (org-at-table-p) (org-region-active-p))]
21543 ["Which Column?" org-table-current-column (org-at-table-p)])
21544 ["Debug Formulas"
21545 org-table-toggle-formula-debugger
21546 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21547 ["Show Col/Row Numbers"
21548 org-table-toggle-coordinate-overlays
21549 :style toggle
21550 :selected (bound-and-true-p org-table-overlay-coordinates)]
21551 "--"
21552 ["Create" org-table-create (and (not (org-at-table-p))
21553 org-enable-table-editor)]
21554 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21555 ["Import from File" org-table-import (not (org-at-table-p))]
21556 ["Export to File" org-table-export (org-at-table-p)]
21557 "--"
21558 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21559 "--"
21560 ("Plot"
21561 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21562 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21564 (easy-menu-define org-org-menu org-mode-map "Org menu"
21565 '("Org"
21566 ("Show/Hide"
21567 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21568 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21569 ["Sparse Tree..." org-sparse-tree t]
21570 ["Reveal Context" org-reveal t]
21571 ["Show All" outline-show-all t]
21572 "--"
21573 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21574 "--"
21575 ["New Heading" org-insert-heading t]
21576 ("Navigate Headings"
21577 ["Up" outline-up-heading t]
21578 ["Next" outline-next-visible-heading t]
21579 ["Previous" outline-previous-visible-heading t]
21580 ["Next Same Level" outline-forward-same-level t]
21581 ["Previous Same Level" outline-backward-same-level t]
21582 "--"
21583 ["Jump" org-goto t])
21584 ("Edit Structure"
21585 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21586 "--"
21587 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21588 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21589 "--"
21590 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21591 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21592 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21593 "--"
21594 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21595 "--"
21596 ["Copy visible text" org-copy-visible t]
21597 "--"
21598 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21599 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21600 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21601 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21602 "--"
21603 ["Sort Region/Children" org-sort t]
21604 "--"
21605 ["Convert to odd levels" org-convert-to-odd-levels t]
21606 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21607 ("Editing"
21608 ["Emphasis..." org-emphasize t]
21609 ["Edit Source Example" org-edit-special t]
21610 "--"
21611 ["Footnote new/jump" org-footnote-action t]
21612 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21613 ("Archive"
21614 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21615 "--"
21616 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21617 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21618 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21620 "--"
21621 ("Hyperlinks"
21622 ["Store Link (Global)" org-store-link t]
21623 ["Find existing link to here" org-occur-link-in-agenda-files t]
21624 ["Insert Link" org-insert-link t]
21625 ["Follow Link" org-open-at-point t]
21626 "--"
21627 ["Next link" org-next-link t]
21628 ["Previous link" org-previous-link t]
21629 "--"
21630 ["Descriptive Links"
21631 org-toggle-link-display
21632 :style radio
21633 :selected org-descriptive-links
21635 ["Literal Links"
21636 org-toggle-link-display
21637 :style radio
21638 :selected (not org-descriptive-links)])
21639 "--"
21640 ("TODO Lists"
21641 ["TODO/DONE/-" org-todo t]
21642 ("Select keyword"
21643 ["Next keyword" org-shiftright (org-at-heading-p)]
21644 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21645 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21646 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21647 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21648 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21649 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21650 "--"
21651 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21652 :selected org-enforce-todo-dependencies :style toggle :active t]
21653 "Settings for tree at point"
21654 ["Do Children sequentially" org-toggle-ordered-property :style radio
21655 :selected (org-entry-get nil "ORDERED")
21656 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21657 ["Do Children parallel" org-toggle-ordered-property :style radio
21658 :selected (not (org-entry-get nil "ORDERED"))
21659 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21660 "--"
21661 ["Set Priority" org-priority t]
21662 ["Priority Up" org-shiftup t]
21663 ["Priority Down" org-shiftdown t]
21664 "--"
21665 ["Get news from all feeds" org-feed-update-all t]
21666 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21667 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21668 ("TAGS and Properties"
21669 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21670 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21671 "--"
21672 ["Set property" org-set-property (not (org-before-first-heading-p))]
21673 ["Column view of properties" org-columns t]
21674 ["Insert Column View DBlock" org-columns-insert-dblock t])
21675 ("Dates and Scheduling"
21676 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21677 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21678 ("Change Date"
21679 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21680 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21681 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21682 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21683 ["Compute Time Range" org-evaluate-time-range t]
21684 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21685 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21686 "--"
21687 ["Custom time format" org-toggle-time-stamp-overlays
21688 :style radio :selected org-display-custom-times]
21689 "--"
21690 ["Goto Calendar" org-goto-calendar t]
21691 ["Date from Calendar" org-date-from-calendar t]
21692 "--"
21693 ["Start/Restart Timer" org-timer-start t]
21694 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21695 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21696 ["Insert Timer String" org-timer t]
21697 ["Insert Timer Item" org-timer-item t])
21698 ("Logging work"
21699 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21700 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21701 ["Clock out" org-clock-out t]
21702 ["Clock cancel" org-clock-cancel t]
21703 "--"
21704 ["Mark as default task" org-clock-mark-default-task t]
21705 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21706 ["Goto running clock" org-clock-goto t]
21707 "--"
21708 ["Display times" org-clock-display t]
21709 ["Create clock table" org-clock-report t]
21710 "--"
21711 ["Record DONE time"
21712 (progn (setq org-log-done (not org-log-done))
21713 (message "Switching to %s will %s record a timestamp"
21714 (car org-done-keywords)
21715 (if org-log-done "automatically" "not")))
21716 :style toggle :selected org-log-done])
21717 "--"
21718 ["Agenda Command..." org-agenda t]
21719 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21720 ("File List for Agenda")
21721 ("Special views current file"
21722 ["TODO Tree" org-show-todo-tree t]
21723 ["Check Deadlines" org-check-deadlines t]
21724 ["Timeline" org-timeline t]
21725 ["Tags/Property tree" org-match-sparse-tree t])
21726 "--"
21727 ["Export/Publish..." org-export-dispatch t]
21728 ("LaTeX"
21729 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21730 :selected org-cdlatex-mode]
21731 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21732 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21733 ["Modify math symbol" org-cdlatex-math-modify
21734 (org-inside-LaTeX-fragment-p)]
21735 ["Insert citation" org-reftex-citation t])
21736 "--"
21737 ("MobileOrg"
21738 ["Push Files and Views" org-mobile-push t]
21739 ["Get Captured and Flagged" org-mobile-pull t]
21740 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21741 "--"
21742 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21743 "--"
21744 ("Documentation"
21745 ["Show Version" org-version t]
21746 ["Info Documentation" org-info t])
21747 ("Customize"
21748 ["Browse Org Group" org-customize t]
21749 "--"
21750 ["Expand This Menu" org-create-customize-menu
21751 (fboundp 'customize-menu-create)])
21752 ["Send bug report" org-submit-bug-report t]
21753 "--"
21754 ("Refresh/Reload"
21755 ["Refresh setup current buffer" org-mode-restart t]
21756 ["Reload Org (after update)" org-reload t]
21757 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21760 (defun org-info (&optional node)
21761 "Read documentation for Org in the info system.
21762 With optional NODE, go directly to that node."
21763 (interactive)
21764 (info (format "(org)%s" (or node ""))))
21766 ;;;###autoload
21767 (defun org-submit-bug-report ()
21768 "Submit a bug report on Org via mail.
21770 Don't hesitate to report any problems or inaccurate documentation.
21772 If you don't have setup sending mail from (X)Emacs, please copy the
21773 output buffer into your mail program, as it gives us important
21774 information about your Org version and configuration."
21775 (interactive)
21776 (require 'reporter)
21777 (defvar reporter-prompt-for-summary-p)
21778 (org-load-modules-maybe)
21779 (org-require-autoloaded-modules)
21780 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21781 (reporter-submit-bug-report
21782 "emacs-orgmode@gnu.org"
21783 (org-version nil 'full)
21784 (let (list)
21785 (save-window-excursion
21786 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21787 (delete-other-windows)
21788 (erase-buffer)
21789 (insert "You are about to submit a bug report to the Org mailing list.
21791 We would like to add your full Org and Outline configuration to the
21792 bug report. This greatly simplifies the work of the maintainer and
21793 other experts on the mailing list.
21795 HOWEVER, some variables you have customized may contain private
21796 information. The names of customers, colleagues, or friends, might
21797 appear in the form of file names, tags, todo states, or search strings.
21798 If you answer yes to the prompt, you might want to check and remove
21799 such private information before sending the email.")
21800 (add-text-properties (point-min) (point-max) '(face org-warning))
21801 (when (yes-or-no-p "Include your Org configuration ")
21802 (mapatoms
21803 (lambda (v)
21804 (and (boundp v)
21805 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21806 (or (and (symbol-value v)
21807 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21808 (and
21809 (get v 'custom-type) (get v 'standard-value)
21810 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21811 (push v list)))))
21812 (kill-buffer (get-buffer "*Warn about privacy*"))
21813 list))
21814 nil nil
21815 "Remember to cover the basics, that is, what you expected to happen and
21816 what in fact did happen. You don't know how to make a good report? See
21818 http://orgmode.org/manual/Feedback.html#Feedback
21820 Your bug report will be posted to the Org mailing list.
21821 ------------------------------------------------------------------------")
21822 (save-excursion
21823 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21824 (replace-match "\\1Bug: \\3 [\\2]")))))
21827 (defun org-install-agenda-files-menu ()
21828 (let ((bl (buffer-list)))
21829 (save-excursion
21830 (while bl
21831 (set-buffer (pop bl))
21832 (when (derived-mode-p 'org-mode) (setq bl nil)))
21833 (when (derived-mode-p 'org-mode)
21834 (easy-menu-change
21835 '("Org") "File List for Agenda"
21836 (append
21837 (list
21838 ["Edit File List" (org-edit-agenda-file-list) t]
21839 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21840 ["Remove Current File from List" org-remove-file t]
21841 ["Cycle through agenda files" org-cycle-agenda-files t]
21842 ["Occur in all agenda files" org-occur-in-agenda-files t]
21843 "--")
21844 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21846 ;;;; Documentation
21848 (defun org-require-autoloaded-modules ()
21849 (interactive)
21850 (mapc #'require
21851 '(org-agenda org-archive org-attach org-clock org-colview org-id
21852 org-table org-timer)))
21854 ;;;###autoload
21855 (defun org-reload (&optional uncompiled)
21856 "Reload all org lisp files.
21857 With prefix arg UNCOMPILED, load the uncompiled versions."
21858 (interactive "P")
21859 (require 'loadhist)
21860 (let* ((org-dir (org-find-library-dir "org"))
21861 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21862 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21863 (remove-re (format "\\`%s\\'"
21864 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21865 (feats (delete-dups
21866 (mapcar 'file-name-sans-extension
21867 (mapcar 'file-name-nondirectory
21868 (delq nil
21869 (mapcar 'feature-file
21870 features))))))
21871 (lfeat (append
21872 (sort
21873 (setq feats
21874 (delq nil (mapcar
21875 (lambda (f)
21876 (if (and (string-match feature-re f)
21877 (not (string-match remove-re f)))
21878 f nil))
21879 feats)))
21880 'string-lessp)
21881 (list "org-version" "org")))
21882 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21883 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21884 load-uncore load-misses)
21885 (setq load-misses
21886 (delq 't
21887 (mapcar (lambda (f)
21888 (or (org-load-noerror-mustsuffix (concat org-dir f))
21889 (and (string= org-dir contrib-dir)
21890 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21891 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21892 (add-to-list 'load-uncore f 'append)
21895 lfeat)))
21896 (when load-uncore
21897 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21898 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21899 (if load-misses
21900 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21901 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21902 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21904 ;;;###autoload
21905 (defun org-customize ()
21906 "Call the customize function with org as argument."
21907 (interactive)
21908 (org-load-modules-maybe)
21909 (org-require-autoloaded-modules)
21910 (customize-browse 'org))
21912 (defun org-create-customize-menu ()
21913 "Create a full customization menu for Org mode, insert it into the menu."
21914 (interactive)
21915 (org-load-modules-maybe)
21916 (org-require-autoloaded-modules)
21917 (if (fboundp 'customize-menu-create)
21918 (progn
21919 (easy-menu-change
21920 '("Org") "Customize"
21921 `(["Browse Org group" org-customize t]
21922 "--"
21923 ,(customize-menu-create 'org)
21924 ["Set" Custom-set t]
21925 ["Save" Custom-save t]
21926 ["Reset to Current" Custom-reset-current t]
21927 ["Reset to Saved" Custom-reset-saved t]
21928 ["Reset to Standard Settings" Custom-reset-standard t]))
21929 (message "\"Org\"-menu now contains full customization menu"))
21930 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21932 ;;;; Miscellaneous stuff
21934 ;;; Generally useful functions
21936 (defun org-get-at-eol (property n)
21937 "Get text property PROPERTY at the end of line less N characters."
21938 (get-text-property (- (point-at-eol) n) property))
21940 (defun org-find-text-property-in-string (prop s)
21941 "Return the first non-nil value of property PROP in string S."
21942 (or (get-text-property 0 prop s)
21943 (get-text-property (or (next-single-property-change 0 prop s) 0)
21944 prop s)))
21946 (defun org-display-warning (message)
21947 "Display the given MESSAGE as a warning."
21948 (display-warning 'org message :warning))
21950 (defun org-eval (form)
21951 "Eval FORM and return result."
21952 (condition-case error
21953 (eval form)
21954 (error (format "%%![Error: %s]" error))))
21956 (defun org-in-clocktable-p ()
21957 "Check if the cursor is in a clocktable."
21958 (let ((pos (point)) start)
21959 (save-excursion
21960 (end-of-line 1)
21961 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21962 (setq start (match-beginning 0))
21963 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21964 (>= (match-end 0) pos)
21965 start))))
21967 (defun org-in-verbatim-emphasis ()
21968 (save-match-data
21969 (and (org-in-regexp org-emph-re 2)
21970 (>= (point) (match-beginning 3))
21971 (<= (point) (match-end 4))
21972 (member (match-string 3) '("=" "~")))))
21974 (defun org-overlay-display (ovl text &optional face evap)
21975 "Make overlay OVL display TEXT with face FACE."
21976 (overlay-put ovl 'display text)
21977 (if face (overlay-put ovl 'face face))
21978 (if evap (overlay-put ovl 'evaporate t)))
21980 (defun org-overlay-before-string (ovl text &optional face evap)
21981 "Make overlay OVL display TEXT with face FACE."
21982 (if face (org-add-props text nil 'face face))
21983 (overlay-put ovl 'before-string text)
21984 (if evap (overlay-put ovl 'evaporate t)))
21986 (defun org-find-overlays (prop &optional pos delete)
21987 "Find all overlays specifying PROP at POS or point.
21988 If DELETE is non-nil, delete all those overlays."
21989 (let (found)
21990 (dolist (ov (overlays-at (or pos (point))) found)
21991 (cond ((not (overlay-get ov prop)))
21992 (delete (delete-overlay ov))
21993 (t (push ov found))))))
21995 (defun org-goto-marker-or-bmk (marker &optional bookmark)
21996 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
21997 (if (and marker (marker-buffer marker)
21998 (buffer-live-p (marker-buffer marker)))
21999 (progn
22000 (pop-to-buffer-same-window (marker-buffer marker))
22001 (when (or (> marker (point-max)) (< marker (point-min)))
22002 (widen))
22003 (goto-char marker)
22004 (org-show-context 'org-goto))
22005 (if bookmark
22006 (bookmark-jump bookmark)
22007 (error "Cannot find location"))))
22009 (defun org-quote-csv-field (s)
22010 "Quote field for inclusion in CSV material."
22011 (if (string-match "[\",]" s)
22012 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22015 (defun org-force-self-insert (N)
22016 "Needed to enforce self-insert under remapping."
22017 (interactive "p")
22018 (self-insert-command N))
22020 (defun org-string-width (s)
22021 "Compute width of string, ignoring invisible characters.
22022 This ignores character with invisibility property `org-link', and also
22023 characters with property `org-cwidth', because these will become invisible
22024 upon the next fontification round."
22025 (let (b l)
22026 (when (or (eq t buffer-invisibility-spec)
22027 (assq 'org-link buffer-invisibility-spec))
22028 (while (setq b (text-property-any 0 (length s)
22029 'invisible 'org-link s))
22030 (setq s (concat (substring s 0 b)
22031 (substring s (or (next-single-property-change
22032 b 'invisible s)
22033 (length s)))))))
22034 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22035 (setq s (concat (substring s 0 b)
22036 (substring s (or (next-single-property-change
22037 b 'org-cwidth s)
22038 (length s))))))
22039 (setq l (string-width s) b -1)
22040 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22041 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22044 (defun org-shorten-string (s maxlength)
22045 "Shorten string S so that it is no longer than MAXLENGTH characters.
22046 If the string is shorter or has length MAXLENGTH, just return the
22047 original string. If it is longer, the functions finds a space in the
22048 string, breaks this string off at that locations and adds three dots
22049 as ellipsis. Including the ellipsis, the string will not be longer
22050 than MAXLENGTH. If finding a good breaking point in the string does
22051 not work, the string is just chopped off in the middle of a word
22052 if necessary."
22053 (if (<= (length s) maxlength)
22055 (let* ((n (max (- maxlength 4) 1))
22056 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22057 (if (string-match re s)
22058 (concat (match-string 1 s) "...")
22059 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22061 (defun org-get-indentation (&optional line)
22062 "Get the indentation of the current line, interpreting tabs.
22063 When LINE is given, assume it represents a line and compute its indentation."
22064 (if line
22065 (when (string-match "^ *" (org-remove-tabs line))
22066 (match-end 0))
22067 (save-excursion
22068 (beginning-of-line 1)
22069 (skip-chars-forward " \t")
22070 (current-column))))
22072 (defun org-get-string-indentation (s)
22073 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22074 (let ((n -1) (i 0) (w tab-width) c)
22075 (catch 'exit
22076 (while (< (setq n (1+ n)) (length s))
22077 (setq c (aref s n))
22078 (cond ((= c ?\ ) (setq i (1+ i)))
22079 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22080 (t (throw 'exit t)))))
22083 (defun org-remove-tabs (s &optional width)
22084 "Replace tabulators in S with spaces.
22085 Assumes that s is a single line, starting in column 0."
22086 (setq width (or width tab-width))
22087 (while (string-match "\t" s)
22088 (setq s (replace-match
22089 (make-string
22090 (- (* width (/ (+ (match-beginning 0) width) width))
22091 (match-beginning 0)) ?\ )
22092 t t s)))
22095 (defun org-fix-indentation (line ind)
22096 "Fix indentation in LINE.
22097 IND is a cons cell with target and minimum indentation.
22098 If the current indentation in LINE is smaller than the minimum,
22099 leave it alone. If it is larger than ind, set it to the target."
22100 (let* ((l (org-remove-tabs line))
22101 (i (org-get-indentation l))
22102 (i1 (car ind)) (i2 (cdr ind)))
22103 (when (>= i i2) (setq l (substring line i2)))
22104 (if (> i1 0)
22105 (concat (make-string i1 ?\ ) l)
22106 l)))
22108 (defun org-remove-indentation (code &optional n)
22109 "Remove maximum common indentation in string CODE and return it.
22110 N may optionally be the number of columns to remove. Return CODE
22111 as-is if removal failed."
22112 (with-temp-buffer
22113 (insert code)
22114 (if (org-do-remove-indentation n) (buffer-string) code)))
22116 (defun org-do-remove-indentation (&optional n)
22117 "Remove the maximum common indentation from the buffer.
22118 When optional argument N is a positive integer, remove exactly
22119 that much characters from indentation, if possible. Return nil
22120 if it fails."
22121 (catch :exit
22122 (goto-char (point-min))
22123 ;; Find maximum common indentation, if not specified.
22124 (let ((n (or n
22125 (let ((min-ind (point-max)))
22126 (save-excursion
22127 (while (re-search-forward "^[ \t]*\\S-" nil t)
22128 (let ((ind (1- (current-column))))
22129 (if (zerop ind) (throw :exit nil)
22130 (setq min-ind (min min-ind ind))))))
22131 min-ind))))
22132 (if (zerop n) (throw :exit nil)
22133 ;; Remove exactly N indentation, but give up if not possible.
22134 (while (not (eobp))
22135 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22136 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22137 ((< ind n) (throw :exit nil))
22138 (t (indent-line-to (- ind n))))
22139 (forward-line)))
22140 ;; Signal success.
22141 t))))
22143 (defun org-fill-template (template alist)
22144 "Find each %key of ALIST in TEMPLATE and replace it."
22145 (let ((case-fold-search nil))
22146 (dolist (entry (sort (copy-sequence alist)
22147 (lambda (a b) (< (length (car a)) (length (car b))))))
22148 (setq template
22149 (replace-regexp-in-string
22150 (concat "%" (regexp-quote (car entry)))
22151 (or (cdr entry) "") template t t)))
22152 template))
22154 (defun org-base-buffer (buffer)
22155 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22156 (if (not buffer)
22157 buffer
22158 (or (buffer-base-buffer buffer)
22159 buffer)))
22161 (defun org-wrap (string &optional width lines)
22162 "Wrap string to either a number of lines, or a width in characters.
22163 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22164 that costs. If there is a word longer than WIDTH, the text is actually
22165 wrapped to the length of that word.
22166 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22167 many lines, whatever width that takes.
22168 The return value is a list of lines, without newlines at the end."
22169 (let* ((words (org-split-string string "[ \t\n]+"))
22170 (maxword (apply 'max (mapcar 'org-string-width words)))
22171 w ll)
22172 (cond (width
22173 (org-do-wrap words (max maxword width)))
22174 (lines
22175 (setq w maxword)
22176 (setq ll (org-do-wrap words maxword))
22177 (if (<= (length ll) lines)
22179 (setq ll words)
22180 (while (> (length ll) lines)
22181 (setq w (1+ w))
22182 (setq ll (org-do-wrap words w)))
22183 ll))
22184 (t (error "Cannot wrap this")))))
22186 (defun org-do-wrap (words width)
22187 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22188 (let (lines line)
22189 (while words
22190 (setq line (pop words))
22191 (while (and words (< (+ (length line) (length (car words))) width))
22192 (setq line (concat line " " (pop words))))
22193 (setq lines (push line lines)))
22194 (nreverse lines)))
22196 (defun org-split-string (string &optional separators)
22197 "Splits STRING into substrings at SEPARATORS.
22198 SEPARATORS is a regular expression.
22199 No empty strings are returned if there are matches at the beginning
22200 and end of string."
22201 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22202 (let ((start 0) notfirst list)
22203 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22204 (if (and notfirst
22205 (= start (match-beginning 0))
22206 (< start (length string)))
22207 (1+ start) start))
22208 (< (match-beginning 0) (length string)))
22209 (setq notfirst t)
22210 (or (eq (match-beginning 0) 0)
22211 (and (eq (match-beginning 0) (match-end 0))
22212 (eq (match-beginning 0) start))
22213 (push (substring string start (match-beginning 0)) list))
22214 (setq start (match-end 0)))
22215 (or (eq start (length string))
22216 (push (substring string start) list))
22217 (nreverse list)))
22219 (defun org-quote-vert (s)
22220 "Replace \"|\" with \"\\vert\"."
22221 (while (string-match "|" s)
22222 (setq s (replace-match "\\vert" t t s)))
22225 (defun org-uuidgen-p (s)
22226 "Is S an ID created by UUIDGEN?"
22227 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22229 (defun org-in-src-block-p (&optional inside)
22230 "Whether point is in a code source block.
22231 When INSIDE is non-nil, don't consider we are within a src block
22232 when point is at #+BEGIN_SRC or #+END_SRC."
22233 (let ((case-fold-search t))
22234 (or (and (eq (get-char-property (point) 'src-block) t))
22235 (and (not inside)
22236 (save-match-data
22237 (save-excursion
22238 (beginning-of-line)
22239 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22241 (defun org-context ()
22242 "Return a list of contexts of the current cursor position.
22243 If several contexts apply, all are returned.
22244 Each context entry is a list with a symbol naming the context, and
22245 two positions indicating start and end of the context. Possible
22246 contexts are:
22248 :headline anywhere in a headline
22249 :headline-stars on the leading stars in a headline
22250 :todo-keyword on a TODO keyword (including DONE) in a headline
22251 :tags on the TAGS in a headline
22252 :priority on the priority cookie in a headline
22253 :item on the first line of a plain list item
22254 :item-bullet on the bullet/number of a plain list item
22255 :checkbox on the checkbox in a plain list item
22256 :table in an Org table
22257 :table-special on a special filed in a table
22258 :table-table in a table.el table
22259 :clocktable in a clocktable
22260 :src-block in a source block
22261 :link on a hyperlink
22262 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22263 :target on a <<target>>
22264 :radio-target on a <<<radio-target>>>
22265 :latex-fragment on a LaTeX fragment
22266 :latex-preview on a LaTeX fragment with overlaid preview image
22268 This function expects the position to be visible because it uses font-lock
22269 faces as a help to recognize the following contexts: :table-special, :link,
22270 and :keyword."
22271 (let* ((f (get-text-property (point) 'face))
22272 (faces (if (listp f) f (list f)))
22273 (case-fold-search t)
22274 (p (point)) clist o)
22275 ;; First the large context
22276 (cond
22277 ((org-at-heading-p t)
22278 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22279 (when (progn
22280 (beginning-of-line 1)
22281 (looking-at org-todo-line-tags-regexp))
22282 (push (org-point-in-group p 1 :headline-stars) clist)
22283 (push (org-point-in-group p 2 :todo-keyword) clist)
22284 (push (org-point-in-group p 4 :tags) clist))
22285 (goto-char p)
22286 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22287 (when (looking-at "\\[#[A-Z0-9]\\]")
22288 (push (org-point-in-group p 0 :priority) clist)))
22290 ((org-at-item-p)
22291 (push (org-point-in-group p 2 :item-bullet) clist)
22292 (push (list :item (point-at-bol)
22293 (save-excursion (org-end-of-item) (point)))
22294 clist)
22295 (and (org-at-item-checkbox-p)
22296 (push (org-point-in-group p 0 :checkbox) clist)))
22298 ((org-at-table-p)
22299 (push (list :table (org-table-begin) (org-table-end)) clist)
22300 (when (memq 'org-formula faces)
22301 (push (list :table-special
22302 (previous-single-property-change p 'face)
22303 (next-single-property-change p 'face)) clist)))
22304 ((org-at-table-p 'any)
22305 (push (list :table-table) clist)))
22306 (goto-char p)
22308 (let ((case-fold-search t))
22309 ;; New the "medium" contexts: clocktables, source blocks
22310 (cond ((org-in-clocktable-p)
22311 (push (list :clocktable
22312 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22313 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22314 (match-beginning 1))
22315 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22316 (match-end 0))) clist))
22317 ((org-in-src-block-p)
22318 (push (list :src-block
22319 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22320 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22321 (match-beginning 1))
22322 (and (search-forward "#+END_SRC" nil t)
22323 (match-beginning 0))) clist))))
22324 (goto-char p)
22326 ;; Now the small context
22327 (cond
22328 ((org-at-timestamp-p)
22329 (push (org-point-in-group p 0 :timestamp) clist))
22330 ((memq 'org-link faces)
22331 (push (list :link
22332 (previous-single-property-change p 'face)
22333 (next-single-property-change p 'face)) clist))
22334 ((memq 'org-special-keyword faces)
22335 (push (list :keyword
22336 (previous-single-property-change p 'face)
22337 (next-single-property-change p 'face)) clist))
22338 ((org-at-target-p)
22339 (push (org-point-in-group p 0 :target) clist)
22340 (goto-char (1- (match-beginning 0)))
22341 (when (looking-at org-radio-target-regexp)
22342 (push (org-point-in-group p 0 :radio-target) clist))
22343 (goto-char p))
22344 ((setq o (cl-some
22345 (lambda (o)
22346 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22348 (overlays-at (point))))
22349 (push (list :latex-fragment
22350 (overlay-start o) (overlay-end o)) clist)
22351 (push (list :latex-preview
22352 (overlay-start o) (overlay-end o)) clist))
22353 ((org-inside-LaTeX-fragment-p)
22354 ;; FIXME: positions wrong.
22355 (push (list :latex-fragment (point) (point)) clist)))
22357 (setq clist (nreverse (delq nil clist)))
22358 clist))
22360 (defun org-in-regexp (regexp &optional nlines visually)
22361 "Check if point is inside a match of REGEXP.
22363 Normally only the current line is checked, but you can include
22364 NLINES extra lines around point into the search. If VISUALLY is
22365 set, require that the cursor is not after the match but really
22366 on, so that the block visually is on the match.
22368 Return nil or a cons cell (BEG . END) where BEG and END are,
22369 respectively, the positions at the beginning and the end of the
22370 match."
22371 (catch :exit
22372 (let ((pos (point))
22373 (eol (line-end-position (if nlines (1+ nlines) 1))))
22374 (save-excursion
22375 (beginning-of-line (- 1 (or nlines 0)))
22376 (while (and (re-search-forward regexp eol t)
22377 (<= (match-beginning 0) pos))
22378 (let ((end (match-end 0)))
22379 (when (or (> end pos) (and (= end pos) (not visually)))
22380 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22382 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22383 "Non-nil when point is between matches of START-RE and END-RE.
22385 Also return a non-nil value when point is on one of the matches.
22387 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22388 buffer positions. Default values are the positions of headlines
22389 surrounding the point.
22391 The functions returns a cons cell whose car (resp. cdr) is the
22392 position before START-RE (resp. after END-RE)."
22393 (save-match-data
22394 (let ((pos (point))
22395 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22396 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22397 beg end)
22398 (save-excursion
22399 ;; Point is on a block when on START-RE or if START-RE can be
22400 ;; found before it...
22401 (and (or (org-in-regexp start-re)
22402 (re-search-backward start-re limit-up t))
22403 (setq beg (match-beginning 0))
22404 ;; ... and END-RE after it...
22405 (goto-char (match-end 0))
22406 (re-search-forward end-re limit-down t)
22407 (> (setq end (match-end 0)) pos)
22408 ;; ... without another START-RE in-between.
22409 (goto-char (match-beginning 0))
22410 (not (re-search-backward start-re (1+ beg) t))
22411 ;; Return value.
22412 (cons beg end))))))
22414 (defun org-in-block-p (names)
22415 "Non-nil when point belongs to a block whose name belongs to NAMES.
22417 NAMES is a list of strings containing names of blocks.
22419 Return first block name matched, or nil. Beware that in case of
22420 nested blocks, the returned name may not belong to the closest
22421 block from point."
22422 (save-match-data
22423 (catch 'exit
22424 (let ((case-fold-search t)
22425 (lim-up (save-excursion (outline-previous-heading)))
22426 (lim-down (save-excursion (outline-next-heading))))
22427 (dolist (name names)
22428 (let ((n (regexp-quote name)))
22429 (when (org-between-regexps-p
22430 (concat "^[ \t]*#\\+begin_" n)
22431 (concat "^[ \t]*#\\+end_" n)
22432 lim-up lim-down)
22433 (throw 'exit n)))))
22434 nil)))
22436 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22437 "Call `multi-occur' with buffers for all agenda files."
22438 (interactive "sOrg-files matching: ")
22439 (let* ((files (org-agenda-files))
22440 (tnames (mapcar #'file-truename files))
22441 (extra org-agenda-text-search-extra-files))
22442 (when (eq (car extra) 'agenda-archives)
22443 (setq extra (cdr extra))
22444 (setq files (org-add-archive-files files)))
22445 (dolist (f extra)
22446 (unless (member (file-truename f) tnames)
22447 (unless (member f files) (setq files (append files (list f))))
22448 (setq tnames (append tnames (list (file-truename f))))))
22449 (multi-occur
22450 (mapcar (lambda (x)
22451 (with-current-buffer
22452 ;; FIXME: Why not just (find-file-noselect x)?
22453 ;; Is it to avoid the "revert buffer" prompt?
22454 (or (get-file-buffer x) (find-file-noselect x))
22455 (widen)
22456 (current-buffer)))
22457 files)
22458 regexp)))
22460 (add-hook 'occur-mode-find-occurrence-hook
22461 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22463 (defun org-occur-link-in-agenda-files ()
22464 "Create a link and search for it in the agendas.
22465 The link is not stored in `org-stored-links', it is just created
22466 for the search purpose."
22467 (interactive)
22468 (let ((link (condition-case nil
22469 (org-store-link nil)
22470 (error "Unable to create a link to here"))))
22471 (org-occur-in-agenda-files (regexp-quote link))))
22473 (defun org-reverse-string (string)
22474 "Return the reverse of STRING."
22475 (apply 'string (reverse (string-to-list string))))
22477 ;; defsubst org-uniquify must be defined before first use
22479 (defun org-uniquify-alist (alist)
22480 "Merge elements of ALIST with the same key.
22482 For example, in this alist:
22484 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22485 => \\='((a 1 3) (b 2))
22487 merge (a 1) and (a 3) into (a 1 3).
22489 The function returns the new ALIST."
22490 (let (rtn)
22491 (dolist (e alist rtn)
22492 (let (n)
22493 (if (not (assoc (car e) rtn))
22494 (push e rtn)
22495 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22496 (setq rtn (assq-delete-all (car e) rtn))
22497 (push n rtn))))))
22499 (defun org-delete-all (elts list)
22500 "Remove all elements in ELTS from LIST.
22501 Comparison is done with `equal'. It is a destructive operation
22502 that may remove elements by altering the list structure."
22503 (while elts
22504 (setq list (delete (pop elts) list)))
22505 list)
22507 (defun org-back-over-empty-lines ()
22508 "Move backwards over whitespace, to the beginning of the first empty line.
22509 Returns the number of empty lines passed."
22510 (let ((pos (point)))
22511 (if (cdr (assq 'heading org-blank-before-new-entry))
22512 (skip-chars-backward " \t\n\r")
22513 (unless (eobp)
22514 (forward-line -1)))
22515 (beginning-of-line 2)
22516 (goto-char (min (point) pos))
22517 (count-lines (point) pos)))
22519 (defun org-skip-whitespace ()
22520 (skip-chars-forward " \t\n\r"))
22522 (defun org-point-in-group (point group &optional context)
22523 "Check if POINT is in match-group GROUP.
22524 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22525 match. If the match group does not exist or point is not inside it,
22526 return nil."
22527 (and (match-beginning group)
22528 (>= point (match-beginning group))
22529 (<= point (match-end group))
22530 (if context
22531 (list context (match-beginning group) (match-end group))
22532 t)))
22534 (defun org-switch-to-buffer-other-window (&rest args)
22535 "Switch to buffer in a second window on the current frame.
22536 In particular, do not allow pop-up frames.
22537 Returns the newly created buffer."
22538 (org-no-popups
22539 (apply 'switch-to-buffer-other-window args)))
22541 (defun org-combine-plists (&rest plists)
22542 "Create a single property list from all plists in PLISTS.
22543 The process starts by copying the first list, and then setting properties
22544 from the other lists. Settings in the last list are the most significant
22545 ones and overrule settings in the other lists."
22546 (let ((rtn (copy-sequence (pop plists)))
22547 p v ls)
22548 (while plists
22549 (setq ls (pop plists))
22550 (while ls
22551 (setq p (pop ls) v (pop ls))
22552 (setq rtn (plist-put rtn p v))))
22553 rtn))
22555 (defun org-replace-escapes (string table)
22556 "Replace %-escapes in STRING with values in TABLE.
22557 TABLE is an association list with keys like \"%a\" and string values.
22558 The sequences in STRING may contain normal field width and padding information,
22559 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22560 so values can contain further %-escapes if they are define later in TABLE."
22561 (let ((tbl (copy-alist table))
22562 (case-fold-search nil)
22563 (pchg 0)
22564 re rpl)
22565 (dolist (e tbl)
22566 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22567 (when (and (cdr e) (string-match re (cdr e)))
22568 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22569 (safe "SREF"))
22570 (add-text-properties 0 3 (list 'sref sref) safe)
22571 (setcdr e (replace-match safe t t (cdr e)))))
22572 (while (string-match re string)
22573 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22574 (cdr e)))
22575 (setq string (replace-match rpl t t string))))
22576 (while (setq pchg (next-property-change pchg string))
22577 (let ((sref (get-text-property pchg 'sref string)))
22578 (when (and sref (string-match "SREF" string pchg))
22579 (setq string (replace-match sref t t string)))))
22580 string))
22582 (defun org-find-base-buffer-visiting (file)
22583 "Like `find-buffer-visiting' but always return the base buffer and
22584 not an indirect buffer."
22585 (let ((buf (or (get-file-buffer file)
22586 (find-buffer-visiting file))))
22587 (if buf
22588 (or (buffer-base-buffer buf) buf)
22589 nil)))
22591 ;;; TODO: Only called once, from ox-odt which should probably use
22592 ;;; org-export-inline-image-p or something.
22593 (defun org-file-image-p (file)
22594 "Return non-nil if FILE is an image."
22595 (save-match-data
22596 (string-match (image-file-name-regexp) file)))
22598 (defun org-get-cursor-date (&optional with-time)
22599 "Return the date at cursor in as a time.
22600 This works in the calendar and in the agenda, anywhere else it just
22601 returns the current time.
22602 If WITH-TIME is non-nil, returns the time of the event at point (in
22603 the agenda) or the current time of the day."
22604 (let (date day defd tp hod mod)
22605 (when with-time
22606 (setq tp (get-text-property (point) 'time))
22607 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22608 (setq hod (string-to-number (match-string 1 tp))
22609 mod (string-to-number (match-string 2 tp))))
22610 (or tp (let ((now (decode-time)))
22611 (setq hod (nth 2 now)
22612 mod (nth 1 now)))))
22613 (cond
22614 ((eq major-mode 'calendar-mode)
22615 (setq date (calendar-cursor-to-date)
22616 defd (encode-time 0 (or mod 0) (or hod 0)
22617 (nth 1 date) (nth 0 date) (nth 2 date))))
22618 ((eq major-mode 'org-agenda-mode)
22619 (setq day (get-text-property (point) 'day))
22620 (when day
22621 (setq date (calendar-gregorian-from-absolute day)
22622 defd (encode-time 0 (or mod 0) (or hod 0)
22623 (nth 1 date) (nth 0 date) (nth 2 date))))))
22624 (or defd (current-time))))
22626 (defun org-mark-subtree (&optional up)
22627 "Mark the current subtree.
22628 This puts point at the start of the current subtree, and mark at
22629 the end. If a numeric prefix UP is given, move up into the
22630 hierarchy of headlines by UP levels before marking the subtree."
22631 (interactive "P")
22632 (org-with-limited-levels
22633 (cond ((org-at-heading-p) (beginning-of-line))
22634 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22635 (t (outline-previous-visible-heading 1))))
22636 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22637 (if (called-interactively-p 'any)
22638 (call-interactively 'org-mark-element)
22639 (org-mark-element)))
22641 (defun org-file-newer-than-p (file time)
22642 "Non-nil if FILE is newer than TIME.
22643 FILE is a filename, as a string, TIME is a list of integers, as
22644 returned by, e.g., `current-time'."
22645 (and (file-exists-p file)
22646 ;; Only compare times up to whole seconds as some file-systems
22647 ;; (e.g. HFS+) do not retain any finer granularity. As
22648 ;; a consequence, make sure we return non-nil when the two
22649 ;; times are equal.
22650 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22651 (cl-subseq time 0 2)))))
22653 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22654 "Compile a SOURCE file using PROCESS.
22656 PROCESS is either a function or a list of shell commands, as
22657 strings. EXT is a file extension, without the leading dot, as
22658 a string. It is used to check if the process actually succeeded.
22660 PROCESS must create a file with the same base name and directory
22661 as SOURCE, but ending with EXT. The function then returns its
22662 filename. Otherwise, it raises an error. The error message can
22663 then be refined by providing string ERR-MSG, which is appended to
22664 the standard message.
22666 If PROCESS is a function, it is called with a single argument:
22667 the SOURCE file.
22669 If it is a list of commands, each of them is called using
22670 `shell-command'. By default, in each command, %b, %f, %F, %o and
22671 %O are replaced with, respectively, SOURCE base name, name, full
22672 name, directory and absolute output file name. It is possible,
22673 however, to use more place-holders by specifying them in optional
22674 argument SPEC, as an alist following the pattern
22676 (CHARACTER . REPLACEMENT-STRING).
22678 When PROCESS is a list of commands, optional argument LOG-BUF can
22679 be set to a buffer or a buffer name. `shell-command' then uses
22680 it for output."
22681 (let* ((base-name (file-name-base source))
22682 (full-name (file-truename source))
22683 (out-dir (or (file-name-directory source) "./"))
22684 (output (expand-file-name (concat base-name "." ext) out-dir))
22685 (time (current-time))
22686 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22687 (save-window-excursion
22688 (pcase process
22689 ((pred functionp) (funcall process (shell-quote-argument source)))
22690 ((pred consp)
22691 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22692 (spec (append spec
22693 `((?b . ,(shell-quote-argument base-name))
22694 (?f . ,(shell-quote-argument source))
22695 (?F . ,(shell-quote-argument full-name))
22696 (?o . ,(shell-quote-argument out-dir))
22697 (?O . ,(shell-quote-argument output))))))
22698 (dolist (command process)
22699 (shell-command (format-spec command spec) log-buf))))
22700 (_ (error "No valid command to process %S%s" source err-msg))))
22701 ;; Check for process failure. Output file is expected to be
22702 ;; located in the same directory as SOURCE.
22703 (unless (org-file-newer-than-p output time)
22704 (error (format "File %S wasn't produced%s" output err-msg)))
22705 output))
22707 ;;; Indentation
22709 (defvar org-element-greater-elements)
22710 (defun org--get-expected-indentation (element contentsp)
22711 "Expected indentation column for current line, according to ELEMENT.
22712 ELEMENT is an element containing point. CONTENTSP is non-nil
22713 when indentation is to be computed according to contents of
22714 ELEMENT."
22715 (let ((type (org-element-type element))
22716 (start (org-element-property :begin element))
22717 (post-affiliated (org-element-property :post-affiliated element)))
22718 (org-with-wide-buffer
22719 (cond
22720 (contentsp
22721 (cl-case type
22722 ((diary-sexp footnote-definition) 0)
22723 ((headline inlinetask nil)
22724 (if (not org-adapt-indentation) 0
22725 (let ((level (org-current-level)))
22726 (if level (1+ level) 0))))
22727 ((item plain-list) (org-list-item-body-column post-affiliated))
22729 (goto-char start)
22730 (org-get-indentation))))
22731 ((memq type '(headline inlinetask nil))
22732 (if (org-match-line "[ \t]*$")
22733 (org--get-expected-indentation element t)
22735 ((memq type '(diary-sexp footnote-definition)) 0)
22736 ;; First paragraph of a footnote definition or an item.
22737 ;; Indent like parent.
22738 ((< (line-beginning-position) start)
22739 (org--get-expected-indentation
22740 (org-element-property :parent element) t))
22741 ;; At first line: indent according to previous sibling, if any,
22742 ;; ignoring footnote definitions and inline tasks, or parent's
22743 ;; contents.
22744 ((= (line-beginning-position) start)
22745 (catch 'exit
22746 (while t
22747 (if (= (point-min) start) (throw 'exit 0)
22748 (goto-char (1- start))
22749 (let* ((previous (org-element-at-point))
22750 (parent previous))
22751 (while (and parent (<= (org-element-property :end parent) start))
22752 (setq previous parent
22753 parent (org-element-property :parent parent)))
22754 (cond
22755 ((not previous) (throw 'exit 0))
22756 ((> (org-element-property :end previous) start)
22757 (throw 'exit (org--get-expected-indentation previous t)))
22758 ((memq (org-element-type previous)
22759 '(footnote-definition inlinetask))
22760 (setq start (org-element-property :begin previous)))
22761 (t (goto-char (org-element-property :begin previous))
22762 (throw 'exit
22763 (if (bolp) (org-get-indentation)
22764 ;; At first paragraph in an item or
22765 ;; a footnote definition.
22766 (org--get-expected-indentation
22767 (org-element-property :parent previous) t))))))))))
22768 ;; Otherwise, move to the first non-blank line above.
22770 (beginning-of-line)
22771 (let ((pos (point)))
22772 (skip-chars-backward " \r\t\n")
22773 (cond
22774 ;; Two blank lines end a footnote definition or a plain
22775 ;; list. When we indent an empty line after them, the
22776 ;; containing list or footnote definition is over, so it
22777 ;; qualifies as a previous sibling. Therefore, we indent
22778 ;; like its first line.
22779 ((and (memq type '(footnote-definition plain-list))
22780 (> (count-lines (point) pos) 2))
22781 (goto-char start)
22782 (org-get-indentation))
22783 ;; Line above is the first one of a paragraph at the
22784 ;; beginning of an item or a footnote definition. Indent
22785 ;; like parent.
22786 ((< (line-beginning-position) start)
22787 (org--get-expected-indentation
22788 (org-element-property :parent element) t))
22789 ;; Line above is the beginning of an element, i.e., point
22790 ;; was originally on the blank lines between element's start
22791 ;; and contents.
22792 ((= (line-beginning-position) post-affiliated)
22793 (org--get-expected-indentation element t))
22794 ;; POS is after contents in a greater element. Indent like
22795 ;; the beginning of the element.
22796 ((and (memq type org-element-greater-elements)
22797 (let ((cend (org-element-property :contents-end element)))
22798 (and cend (<= cend pos))))
22799 ;; As a special case, if point is at the end of a footnote
22800 ;; definition or an item, indent like the very last element
22801 ;; within. If that last element is an item, indent like
22802 ;; its contents.
22803 (if (memq type '(footnote-definition item plain-list))
22804 (let ((last (org-element-at-point)))
22805 (goto-char pos)
22806 (org--get-expected-indentation
22807 last (eq (org-element-type last) 'item)))
22808 (goto-char start)
22809 (org-get-indentation)))
22810 ;; In any other case, indent like the current line.
22811 (t (org-get-indentation)))))))))
22813 (defun org--align-node-property ()
22814 "Align node property at point.
22815 Alignment is done according to `org-property-format', which see."
22816 (when (save-excursion
22817 (beginning-of-line)
22818 (looking-at org-property-re))
22819 (replace-match
22820 (concat (match-string 4)
22821 (org-trim
22822 (format org-property-format (match-string 1) (match-string 3))))
22823 t t)))
22825 (defun org-indent-line ()
22826 "Indent line depending on context.
22828 Indentation is done according to the following rules:
22830 - Footnote definitions, diary sexps, headlines and inline tasks
22831 have to start at column 0.
22833 - On the very first line of an element, consider, in order, the
22834 next rules until one matches:
22836 1. If there's a sibling element before, ignoring footnote
22837 definitions and inline tasks, indent like its first line.
22839 2. If element has a parent, indent like its contents. More
22840 precisely, if parent is an item, indent after the
22841 description part, if any, or the bullet (see
22842 `org-list-description-max-indent'). Else, indent like
22843 parent's first line.
22845 3. Otherwise, indent relatively to current level, if
22846 `org-adapt-indentation' is non-nil, or to left margin.
22848 - On a blank line at the end of an element, indent according to
22849 the type of the element. More precisely
22851 1. If element is a plain list, an item, or a footnote
22852 definition, indent like the very last element within.
22854 2. If element is a paragraph, indent like its last non blank
22855 line.
22857 3. Otherwise, indent like its very first line.
22859 - In the code part of a source block, use language major mode
22860 to indent current line if `org-src-tab-acts-natively' is
22861 non-nil. If it is nil, do nothing.
22863 - Otherwise, indent like the first non-blank line above.
22865 The function doesn't indent an item as it could break the whole
22866 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22867 `\\[org-shiftmetaright]'.
22869 Also align node properties according to `org-property-format'."
22870 (interactive)
22871 (cond
22872 (orgstruct-is-++
22873 (let ((indent-line-function
22874 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22875 (indent-according-to-mode)))
22876 ((org-at-heading-p) 'noindent)
22878 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22879 (type (org-element-type element)))
22880 (cond ((and (memq type '(plain-list item))
22881 (= (line-beginning-position)
22882 (org-element-property :post-affiliated element)))
22883 'noindent)
22884 ((and (eq type 'latex-environment)
22885 (>= (point) (org-element-property :post-affiliated element))
22886 (< (point) (org-with-wide-buffer
22887 (goto-char (org-element-property :end element))
22888 (skip-chars-backward " \r\t\n")
22889 (line-beginning-position 2))))
22890 'noindent)
22891 ((and (eq type 'src-block)
22892 org-src-tab-acts-natively
22893 (> (line-beginning-position)
22894 (org-element-property :post-affiliated element))
22895 (< (line-beginning-position)
22896 (org-with-wide-buffer
22897 (goto-char (org-element-property :end element))
22898 (skip-chars-backward " \r\t\n")
22899 (line-beginning-position))))
22900 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22902 (let ((column (org--get-expected-indentation element nil)))
22903 ;; Preserve current column.
22904 (if (<= (current-column) (current-indentation))
22905 (indent-line-to column)
22906 (save-excursion (indent-line-to column))))
22907 ;; Align node property. Also preserve current column.
22908 (when (eq type 'node-property)
22909 (let ((column (current-column)))
22910 (org--align-node-property)
22911 (org-move-to-column column)))))))))
22913 (defun org-indent-region (start end)
22914 "Indent each non-blank line in the region.
22915 Called from a program, START and END specify the region to
22916 indent. The function will not indent contents of example blocks,
22917 verse blocks and export blocks as leading white spaces are
22918 assumed to be significant there."
22919 (interactive "r")
22920 (save-excursion
22921 (goto-char start)
22922 (skip-chars-forward " \r\t\n")
22923 (unless (eobp) (beginning-of-line))
22924 (let ((indent-to
22925 (lambda (ind pos)
22926 ;; Set IND as indentation for all lines between point and
22927 ;; POS. Blank lines are ignored. Leave point after POS
22928 ;; once done.
22929 (let ((limit (copy-marker pos)))
22930 (while (< (point) limit)
22931 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22932 (forward-line))
22933 (set-marker limit nil))))
22934 (end (copy-marker end)))
22935 (while (< (point) end)
22936 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22937 (let* ((element (org-element-at-point))
22938 (type (org-element-type element))
22939 (element-end (copy-marker (org-element-property :end element)))
22940 (ind (org--get-expected-indentation element nil)))
22941 (cond
22942 ;; Element indented as a single block. Example blocks
22943 ;; preserving indentation are a special case since the
22944 ;; "contents" must not be indented whereas the block
22945 ;; boundaries can.
22946 ((or (memq type '(export-block latex-environment))
22947 (and (eq type 'example-block)
22948 (not
22949 (or org-src-preserve-indentation
22950 (org-element-property :preserve-indent element)))))
22951 (let ((offset (- ind (org-get-indentation))))
22952 (unless (zerop offset)
22953 (indent-rigidly (org-element-property :begin element)
22954 (org-element-property :end element)
22955 offset)))
22956 (goto-char element-end))
22957 ;; Elements indented line wise. Be sure to exclude
22958 ;; example blocks (preserving indentation) and source
22959 ;; blocks from this category as they are treated
22960 ;; specially later.
22961 ((or (memq type '(paragraph table table-row))
22962 (not (or (org-element-property :contents-begin element)
22963 (memq type '(example-block src-block)))))
22964 (when (eq type 'node-property)
22965 (org--align-node-property)
22966 (beginning-of-line))
22967 (funcall indent-to ind (min element-end end)))
22968 ;; Elements consisting of three parts: before the
22969 ;; contents, the contents, and after the contents. The
22970 ;; contents are treated specially, according to the
22971 ;; element type, or not indented at all. Other parts are
22972 ;; indented as a single block.
22974 (let* ((post (copy-marker
22975 (org-element-property :post-affiliated element)))
22976 (cbeg
22977 (copy-marker
22978 (cond
22979 ((not (org-element-property :contents-begin element))
22980 ;; Fake contents for source blocks.
22981 (org-with-wide-buffer
22982 (goto-char post)
22983 (line-beginning-position 2)))
22984 ((memq type '(footnote-definition item plain-list))
22985 ;; Contents in these elements could start on
22986 ;; the same line as the beginning of the
22987 ;; element. Make sure we start indenting
22988 ;; from the second line.
22989 (org-with-wide-buffer
22990 (goto-char post)
22991 (end-of-line)
22992 (skip-chars-forward " \r\t\n")
22993 (if (eobp) (point) (line-beginning-position))))
22994 (t (org-element-property :contents-begin element)))))
22995 (cend (copy-marker
22996 (or (org-element-property :contents-end element)
22997 ;; Fake contents for source blocks.
22998 (org-with-wide-buffer
22999 (goto-char element-end)
23000 (skip-chars-backward " \r\t\n")
23001 (line-beginning-position)))
23002 t)))
23003 ;; Do not change items indentation individually as it
23004 ;; might break the list as a whole. On the other
23005 ;; hand, when at a plain list, indent it as a whole.
23006 (cond ((eq type 'plain-list)
23007 (let ((offset (- ind (org-get-indentation))))
23008 (unless (zerop offset)
23009 (indent-rigidly (org-element-property :begin element)
23010 (org-element-property :end element)
23011 offset))
23012 (goto-char cbeg)))
23013 ((eq type 'item) (goto-char cbeg))
23014 (t (funcall indent-to ind (min cbeg end))))
23015 (when (< (point) end)
23016 (cl-case type
23017 ((example-block verse-block))
23018 (src-block
23019 ;; In a source block, indent source code
23020 ;; according to language major mode, but only if
23021 ;; `org-src-tab-acts-natively' is non-nil.
23022 (when (and (< (point) end) org-src-tab-acts-natively)
23023 (ignore-errors
23024 (org-babel-do-in-edit-buffer
23025 (indent-region (point-min) (point-max))))))
23026 (t (org-indent-region (point) (min cend end))))
23027 (goto-char (min cend end))
23028 (when (< (point) end)
23029 (funcall indent-to ind (min element-end end))))
23030 (set-marker post nil)
23031 (set-marker cbeg nil)
23032 (set-marker cend nil))))
23033 (set-marker element-end nil))))
23034 (set-marker end nil))))
23036 (defun org-indent-drawer ()
23037 "Indent the drawer at point."
23038 (interactive)
23039 (unless (save-excursion
23040 (beginning-of-line)
23041 (looking-at-p org-drawer-regexp))
23042 (user-error "Not at a drawer"))
23043 (let ((element (org-element-at-point)))
23044 (unless (memq (org-element-type element) '(drawer property-drawer))
23045 (user-error "Not at a drawer"))
23046 (org-with-wide-buffer
23047 (org-indent-region (org-element-property :begin element)
23048 (org-element-property :end element))))
23049 (message "Drawer at point indented"))
23051 (defun org-indent-block ()
23052 "Indent the block at point."
23053 (interactive)
23054 (unless (save-excursion
23055 (beginning-of-line)
23056 (let ((case-fold-search t))
23057 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23058 (user-error "Not at a block"))
23059 (let ((element (org-element-at-point)))
23060 (unless (memq (org-element-type element)
23061 '(comment-block center-block dynamic-block example-block
23062 export-block quote-block special-block
23063 src-block verse-block))
23064 (user-error "Not at a block"))
23065 (org-with-wide-buffer
23066 (org-indent-region (org-element-property :begin element)
23067 (org-element-property :end element))))
23068 (message "Block at point indented"))
23071 ;;; Filling
23073 ;; We use our own fill-paragraph and auto-fill functions.
23075 ;; `org-fill-paragraph' relies on adaptive filling and context
23076 ;; checking. Appropriate `fill-prefix' is computed with
23077 ;; `org-adaptive-fill-function'.
23079 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23080 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23081 ;; `org-adaptive-fill-function' value. Internally,
23082 ;; `org-comment-line-break-function' breaks the line.
23084 ;; `org-setup-filling' installs filling and auto-filling related
23085 ;; variables during `org-mode' initialization.
23087 (defvar org-element-paragraph-separate) ; org-element.el
23088 (defun org-setup-filling ()
23089 (require 'org-element)
23090 ;; Prevent auto-fill from inserting unwanted new items.
23091 (when (boundp 'fill-nobreak-predicate)
23092 (setq-local
23093 fill-nobreak-predicate
23094 (org-uniquify
23095 (append fill-nobreak-predicate
23096 '(org-fill-line-break-nobreak-p
23097 org-fill-paragraph-with-timestamp-nobreak-p)))))
23098 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23099 (setq-local paragraph-start paragraph-ending)
23100 (setq-local paragraph-separate paragraph-ending))
23101 (setq-local fill-paragraph-function 'org-fill-paragraph)
23102 (setq-local auto-fill-inhibit-regexp nil)
23103 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23104 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23105 (setq-local comment-line-break-function 'org-comment-line-break-function))
23107 (defun org-fill-line-break-nobreak-p ()
23108 "Non-nil when a new line at point would create an Org line break."
23109 (save-excursion
23110 (skip-chars-backward "[ \t]")
23111 (skip-chars-backward "\\\\")
23112 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23114 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23115 "Non-nil when a new line at point would split a timestamp."
23116 (and (org-at-timestamp-p t)
23117 (not (looking-at org-ts-regexp-both))))
23119 (declare-function message-in-body-p "message" ())
23120 (defvar orgtbl-line-start-regexp) ; From org-table.el
23121 (defun org-adaptive-fill-function ()
23122 "Compute a fill prefix for the current line.
23123 Return fill prefix, as a string, or nil if current line isn't
23124 meant to be filled. For convenience, if `adaptive-fill-regexp'
23125 matches in paragraphs or comments, use it."
23126 (catch 'exit
23127 (when (derived-mode-p 'message-mode)
23128 (save-excursion
23129 (beginning-of-line)
23130 (cond ((not (message-in-body-p)) (throw 'exit nil))
23131 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23132 ((looking-at message-cite-prefix-regexp)
23133 (throw 'exit (match-string-no-properties 0)))
23134 ((looking-at org-outline-regexp)
23135 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23136 (org-with-wide-buffer
23137 (unless (org-at-heading-p)
23138 (let* ((p (line-beginning-position))
23139 (element (save-excursion
23140 (beginning-of-line)
23141 (org-element-at-point)))
23142 (type (org-element-type element))
23143 (post-affiliated (org-element-property :post-affiliated element)))
23144 (unless (< p post-affiliated)
23145 (cl-case type
23146 (comment
23147 (save-excursion
23148 (beginning-of-line)
23149 (looking-at "[ \t]*")
23150 (concat (match-string 0) "# ")))
23151 (footnote-definition "")
23152 ((item plain-list)
23153 (make-string (org-list-item-body-column post-affiliated) ?\s))
23154 (paragraph
23155 ;; Fill prefix is usually the same as the current line,
23156 ;; unless the paragraph is at the beginning of an item.
23157 (let ((parent (org-element-property :parent element)))
23158 (save-excursion
23159 (beginning-of-line)
23160 (cond ((eq (org-element-type parent) 'item)
23161 (make-string (org-list-item-body-column
23162 (org-element-property :begin parent))
23163 ?\s))
23164 ((and adaptive-fill-regexp
23165 ;; Locally disable
23166 ;; `adaptive-fill-function' to let
23167 ;; `fill-context-prefix' handle
23168 ;; `adaptive-fill-regexp' variable.
23169 (let (adaptive-fill-function)
23170 (fill-context-prefix
23171 post-affiliated
23172 (org-element-property :end element)))))
23173 ((looking-at "[ \t]+") (match-string 0))
23174 (t "")))))
23175 (comment-block
23176 ;; Only fill contents if P is within block boundaries.
23177 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23178 (forward-line)
23179 (point)))
23180 (cend (save-excursion
23181 (goto-char (org-element-property :end element))
23182 (skip-chars-backward " \r\t\n")
23183 (line-beginning-position))))
23184 (when (and (>= p cbeg) (< p cend))
23185 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23186 (match-string 0)
23187 "")))))))))))
23189 (declare-function message-goto-body "message" ())
23190 (defvar message-cite-prefix-regexp) ; From message.el
23191 (defun org-fill-paragraph (&optional justify)
23192 "Fill element at point, when applicable.
23194 This function only applies to comment blocks, comments, example
23195 blocks and paragraphs. Also, as a special case, re-align table
23196 when point is at one.
23198 If JUSTIFY is non-nil (interactively, with prefix argument),
23199 justify as well. If `sentence-end-double-space' is non-nil, then
23200 period followed by one space does not end a sentence, so don't
23201 break a line there. The variable `fill-column' controls the
23202 width for filling.
23204 For convenience, when point is at a plain list, an item or
23205 a footnote definition, try to fill the first paragraph within."
23206 (interactive)
23207 (if (and (derived-mode-p 'message-mode)
23208 (or (not (message-in-body-p))
23209 (save-excursion (move-beginning-of-line 1)
23210 (looking-at message-cite-prefix-regexp))))
23211 ;; First ensure filling is correct in message-mode.
23212 (let ((fill-paragraph-function
23213 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23214 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23215 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23216 (paragraph-separate
23217 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23218 (fill-paragraph nil))
23219 (with-syntax-table org-mode-transpose-word-syntax-table
23220 ;; Move to end of line in order to get the first paragraph
23221 ;; within a plain list or a footnote definition.
23222 (let ((element (save-excursion
23223 (end-of-line)
23224 (or (ignore-errors (org-element-at-point))
23225 (user-error "An element cannot be parsed line %d"
23226 (line-number-at-pos (point)))))))
23227 ;; First check if point is in a blank line at the beginning of
23228 ;; the buffer. In that case, ignore filling.
23229 (cl-case (org-element-type element)
23230 ;; Use major mode filling function is src blocks.
23231 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23232 ;; Align Org tables, leave table.el tables as-is.
23233 (table-row (org-table-align) t)
23234 (table
23235 (when (eq (org-element-property :type element) 'org)
23236 (save-excursion
23237 (goto-char (org-element-property :post-affiliated element))
23238 (org-table-align)))
23240 (paragraph
23241 ;; Paragraphs may contain `line-break' type objects.
23242 (let ((beg (max (point-min)
23243 (org-element-property :contents-begin element)))
23244 (end (min (point-max)
23245 (org-element-property :contents-end element))))
23246 ;; Do nothing if point is at an affiliated keyword.
23247 (if (< (line-end-position) beg) t
23248 (when (derived-mode-p 'message-mode)
23249 ;; In `message-mode', do not fill following citation
23250 ;; in current paragraph nor text before message body.
23251 (let ((body-start (save-excursion (message-goto-body))))
23252 (when body-start (setq beg (max body-start beg))))
23253 (when (save-excursion
23254 (re-search-forward
23255 (concat "^" message-cite-prefix-regexp) end t))
23256 (setq end (match-beginning 0))))
23257 ;; Fill paragraph, taking line breaks into account.
23258 (save-excursion
23259 (goto-char beg)
23260 (let ((cuts (list beg)))
23261 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23262 (when (eq 'line-break
23263 (org-element-type
23264 (save-excursion (backward-char)
23265 (org-element-context))))
23266 (push (point) cuts)))
23267 (dolist (c (delq end cuts))
23268 (fill-region-as-paragraph c end justify)
23269 (setq end c))))
23270 t)))
23271 ;; Contents of `comment-block' type elements should be
23272 ;; filled as plain text, but only if point is within block
23273 ;; markers.
23274 (comment-block
23275 (let* ((case-fold-search t)
23276 (beg (save-excursion
23277 (goto-char (org-element-property :begin element))
23278 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23279 (forward-line)
23280 (point)))
23281 (end (save-excursion
23282 (goto-char (org-element-property :end element))
23283 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23284 (line-beginning-position))))
23285 (if (or (< (point) beg) (> (point) end)) t
23286 (fill-region-as-paragraph
23287 (save-excursion (end-of-line)
23288 (re-search-backward "^[ \t]*$" beg 'move)
23289 (line-beginning-position))
23290 (save-excursion (beginning-of-line)
23291 (re-search-forward "^[ \t]*$" end 'move)
23292 (line-beginning-position))
23293 justify))))
23294 ;; Fill comments.
23295 (comment
23296 (let ((begin (org-element-property :post-affiliated element))
23297 (end (org-element-property :end element)))
23298 (when (and (>= (point) begin) (<= (point) end))
23299 (let ((begin (save-excursion
23300 (end-of-line)
23301 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23302 (progn (forward-line) (point))
23303 begin)))
23304 (end (save-excursion
23305 (end-of-line)
23306 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23307 (1- (line-beginning-position))
23308 (skip-chars-backward " \r\t\n")
23309 (line-end-position)))))
23310 ;; Do not fill comments when at a blank line.
23311 (when (> end begin)
23312 (let ((fill-prefix
23313 (save-excursion
23314 (beginning-of-line)
23315 (looking-at "[ \t]*#")
23316 (let ((comment-prefix (match-string 0)))
23317 (goto-char (match-end 0))
23318 (if (looking-at adaptive-fill-regexp)
23319 (concat comment-prefix (match-string 0))
23320 (concat comment-prefix " "))))))
23321 (save-excursion
23322 (fill-region-as-paragraph begin end justify))))))
23324 ;; Ignore every other element.
23325 (otherwise t))))))
23327 (defun org-auto-fill-function ()
23328 "Auto-fill function."
23329 ;; Check if auto-filling is meaningful.
23330 (let ((fc (current-fill-column)))
23331 (when (and fc (> (current-column) fc))
23332 (let* ((fill-prefix (org-adaptive-fill-function))
23333 ;; Enforce empty fill prefix, if required. Otherwise, it
23334 ;; will be computed again.
23335 (adaptive-fill-mode (not (equal fill-prefix ""))))
23336 (when fill-prefix (do-auto-fill))))))
23338 (defun org-comment-line-break-function (&optional soft)
23339 "Break line at point and indent, continuing comment if within one.
23340 The inserted newline is marked hard if variable
23341 `use-hard-newlines' is true, unless optional argument SOFT is
23342 non-nil."
23343 (if soft (insert-and-inherit ?\n) (newline 1))
23344 (save-excursion (forward-char -1) (delete-horizontal-space))
23345 (delete-horizontal-space)
23346 (indent-to-left-margin)
23347 (insert-before-markers-and-inherit fill-prefix))
23350 ;;; Fixed Width Areas
23352 (defun org-toggle-fixed-width ()
23353 "Toggle fixed-width markup.
23355 Add or remove fixed-width markup on current line, whenever it
23356 makes sense. Return an error otherwise.
23358 If a region is active and if it contains only fixed-width areas
23359 or blank lines, remove all fixed-width markup in it. If the
23360 region contains anything else, convert all non-fixed-width lines
23361 to fixed-width ones.
23363 Blank lines at the end of the region are ignored unless the
23364 region only contains such lines."
23365 (interactive)
23366 (if (not (org-region-active-p))
23367 ;; No region:
23369 ;; Remove fixed width marker only in a fixed-with element.
23371 ;; Add fixed width maker in paragraphs, in blank lines after
23372 ;; elements or at the beginning of a headline or an inlinetask,
23373 ;; and before any one-line elements (e.g., a clock).
23374 (progn
23375 (beginning-of-line)
23376 (let* ((element (org-element-at-point))
23377 (type (org-element-type element)))
23378 (cond
23379 ((and (eq type 'fixed-width)
23380 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23381 (replace-match
23382 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23383 ((and (memq type '(babel-call clock comment diary-sexp headline
23384 horizontal-rule keyword paragraph
23385 planning))
23386 (<= (org-element-property :post-affiliated element) (point)))
23387 (skip-chars-forward " \t")
23388 (insert ": "))
23389 ((and (looking-at-p "[ \t]*$")
23390 (or (eq type 'inlinetask)
23391 (save-excursion
23392 (skip-chars-forward " \r\t\n")
23393 (<= (org-element-property :end element) (point)))))
23394 (delete-region (point) (line-end-position))
23395 (org-indent-line)
23396 (insert ": "))
23397 (t (user-error "Cannot insert a fixed-width line here")))))
23398 ;; Region active.
23399 (let* ((begin (save-excursion
23400 (goto-char (region-beginning))
23401 (line-beginning-position)))
23402 (end (copy-marker
23403 (save-excursion
23404 (goto-char (region-end))
23405 (unless (eolp) (beginning-of-line))
23406 (if (save-excursion (re-search-backward "\\S-" begin t))
23407 (progn (skip-chars-backward " \r\t\n") (point))
23408 (point)))))
23409 (all-fixed-width-p
23410 (catch 'not-all-p
23411 (save-excursion
23412 (goto-char begin)
23413 (skip-chars-forward " \r\t\n")
23414 (when (eobp) (throw 'not-all-p nil))
23415 (while (< (point) end)
23416 (let ((element (org-element-at-point)))
23417 (if (eq (org-element-type element) 'fixed-width)
23418 (goto-char (org-element-property :end element))
23419 (throw 'not-all-p nil))))
23420 t))))
23421 (if all-fixed-width-p
23422 (save-excursion
23423 (goto-char begin)
23424 (while (< (point) end)
23425 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23426 (replace-match
23427 "" nil nil nil
23428 (if (= (line-end-position) (match-end 0)) 0 1)))
23429 (forward-line)))
23430 (let ((min-ind (point-max)))
23431 ;; Find minimum indentation across all lines.
23432 (save-excursion
23433 (goto-char begin)
23434 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23435 (setq min-ind 0)
23436 (catch 'zerop
23437 (while (< (point) end)
23438 (unless (looking-at-p "[ \t]*$")
23439 (let ((ind (org-get-indentation)))
23440 (setq min-ind (min min-ind ind))
23441 (when (zerop ind) (throw 'zerop t))))
23442 (forward-line)))))
23443 ;; Loop over all lines and add fixed-width markup everywhere
23444 ;; but in fixed-width lines.
23445 (save-excursion
23446 (goto-char begin)
23447 (while (< (point) end)
23448 (cond
23449 ((org-at-heading-p)
23450 (insert ": ")
23451 (forward-line)
23452 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23453 (insert ":")
23454 (forward-line)))
23455 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23456 (let* ((element (org-element-at-point))
23457 (element-end (org-element-property :end element)))
23458 (if (eq (org-element-type element) 'fixed-width)
23459 (progn (goto-char element-end)
23460 (skip-chars-backward " \r\t\n")
23461 (forward-line))
23462 (let ((limit (min end element-end)))
23463 (while (< (point) limit)
23464 (org-move-to-column min-ind t)
23465 (insert ": ")
23466 (forward-line))))))
23468 (org-move-to-column min-ind t)
23469 (insert ": ")
23470 (forward-line)))))))
23471 (set-marker end nil))))
23474 ;;; Comments
23476 ;; Org comments syntax is quite complex. It requires the entire line
23477 ;; to be just a comment. Also, even with the right syntax at the
23478 ;; beginning of line, some some elements (i.e. verse-block or
23479 ;; example-block) don't accept comments. Usual Emacs comment commands
23480 ;; cannot cope with those requirements. Therefore, Org replaces them.
23482 ;; Org still relies on `comment-dwim', but cannot trust
23483 ;; `comment-only-p'. So, `comment-region-function' and
23484 ;; `uncomment-region-function' both point
23485 ;; to`org-comment-or-uncomment-region'. Eventually,
23486 ;; `org-insert-comment' takes care of insertion of comments at the
23487 ;; beginning of line.
23489 ;; `org-setup-comments-handling' install comments related variables
23490 ;; during `org-mode' initialization.
23492 (defun org-setup-comments-handling ()
23493 (interactive)
23494 (setq-local comment-use-syntax nil)
23495 (setq-local comment-start "# ")
23496 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23497 (setq-local comment-insert-comment-function 'org-insert-comment)
23498 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23499 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23501 (defun org-insert-comment ()
23502 "Insert an empty comment above current line.
23503 If the line is empty, insert comment at its beginning. When
23504 point is within a source block, comment according to the related
23505 major mode."
23506 (if (let ((element (org-element-at-point)))
23507 (and (eq (org-element-type element) 'src-block)
23508 (< (save-excursion
23509 (goto-char (org-element-property :post-affiliated element))
23510 (line-end-position))
23511 (point))
23512 (> (save-excursion
23513 (goto-char (org-element-property :end element))
23514 (skip-chars-backward " \r\t\n")
23515 (line-beginning-position))
23516 (point))))
23517 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23518 (beginning-of-line)
23519 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23520 (open-line 1))
23521 (org-indent-line)
23522 (insert "# ")))
23524 (defvar comment-empty-lines) ; From newcomment.el.
23525 (defun org-comment-or-uncomment-region (beg end &rest _)
23526 "Comment or uncomment each non-blank line in the region.
23527 Uncomment each non-blank line between BEG and END if it only
23528 contains commented lines. Otherwise, comment them. If region is
23529 strictly within a source block, use appropriate comment syntax."
23530 (if (let ((element (org-element-at-point)))
23531 (and (eq (org-element-type element) 'src-block)
23532 (< (save-excursion
23533 (goto-char (org-element-property :post-affiliated element))
23534 (line-end-position))
23535 beg)
23536 (>= (save-excursion
23537 (goto-char (org-element-property :end element))
23538 (skip-chars-backward " \r\t\n")
23539 (line-beginning-position))
23540 end)))
23541 ;; Translate region boundaries for the Org buffer to the source
23542 ;; buffer.
23543 (let ((offset (- end beg)))
23544 (save-excursion
23545 (goto-char beg)
23546 (org-babel-do-in-edit-buffer
23547 (comment-or-uncomment-region (point) (+ offset (point))))))
23548 (save-restriction
23549 ;; Restrict region
23550 (narrow-to-region (save-excursion (goto-char beg)
23551 (skip-chars-forward " \r\t\n" end)
23552 (line-beginning-position))
23553 (save-excursion (goto-char end)
23554 (skip-chars-backward " \r\t\n" beg)
23555 (line-end-position)))
23556 (let ((uncommentp
23557 ;; UNCOMMENTP is non-nil when every non blank line between
23558 ;; BEG and END is a comment.
23559 (save-excursion
23560 (goto-char (point-min))
23561 (while (and (not (eobp))
23562 (let ((element (org-element-at-point)))
23563 (and (eq (org-element-type element) 'comment)
23564 (goto-char (min (point-max)
23565 (org-element-property
23566 :end element)))))))
23567 (eobp))))
23568 (if uncommentp
23569 ;; Only blank lines and comments in region: uncomment it.
23570 (save-excursion
23571 (goto-char (point-min))
23572 (while (not (eobp))
23573 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23574 (replace-match "" nil nil nil 1))
23575 (forward-line)))
23576 ;; Comment each line in region.
23577 (let ((min-indent (point-max)))
23578 ;; First find the minimum indentation across all lines.
23579 (save-excursion
23580 (goto-char (point-min))
23581 (while (and (not (eobp)) (not (zerop min-indent)))
23582 (unless (looking-at "[ \t]*$")
23583 (setq min-indent (min min-indent (current-indentation))))
23584 (forward-line)))
23585 ;; Then loop over all lines.
23586 (save-excursion
23587 (goto-char (point-min))
23588 (while (not (eobp))
23589 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23590 ;; Don't get fooled by invisible text (e.g. link path)
23591 ;; when moving to column MIN-INDENT.
23592 (let ((buffer-invisibility-spec nil))
23593 (org-move-to-column min-indent t))
23594 (insert comment-start))
23595 (forward-line)))))))))
23597 (defun org-comment-dwim (_arg)
23598 "Call `comment-dwim' within a source edit buffer if needed."
23599 (interactive "*P")
23600 (if (org-in-src-block-p)
23601 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23602 (call-interactively 'comment-dwim)))
23605 ;;; Timestamps API
23607 ;; This section contains tools to operate on timestamp objects, as
23608 ;; returned by, e.g. `org-element-context'.
23610 (defun org-timestamp--to-internal-time (timestamp &optional end)
23611 "Encode TIMESTAMP object into Emacs internal time.
23612 Use end of date range or time range when END is non-nil."
23613 (apply #'encode-time
23614 (cons 0
23615 (mapcar
23616 (lambda (prop) (or (org-element-property prop timestamp) 0))
23617 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23618 '(:minute-start :hour-start :day-start :month-start
23619 :year-start))))))
23621 (defun org-timestamp-has-time-p (timestamp)
23622 "Non-nil when TIMESTAMP has a time specified."
23623 (org-element-property :hour-start timestamp))
23625 (defun org-timestamp-format (timestamp format &optional end utc)
23626 "Format a TIMESTAMP object into a string.
23628 FORMAT is a format specifier to be passed to
23629 `format-time-string'.
23631 When optional argument END is non-nil, use end of date-range or
23632 time-range, if possible.
23634 When optional argument UTC is non-nil, time will be expressed as
23635 Universal Time."
23636 (format-time-string
23637 format (org-timestamp--to-internal-time timestamp end)
23638 (and utc t)))
23640 (defun org-timestamp-split-range (timestamp &optional end)
23641 "Extract a TIMESTAMP object from a date or time range.
23643 END, when non-nil, means extract the end of the range.
23644 Otherwise, extract its start.
23646 Return a new timestamp object."
23647 (let ((type (org-element-property :type timestamp)))
23648 (if (memq type '(active inactive diary)) timestamp
23649 (let ((split-ts (org-element-copy timestamp)))
23650 ;; Set new type.
23651 (org-element-put-property
23652 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23653 ;; Copy start properties over end properties if END is
23654 ;; non-nil. Otherwise, copy end properties over `start' ones.
23655 (let ((p-alist '((:minute-start . :minute-end)
23656 (:hour-start . :hour-end)
23657 (:day-start . :day-end)
23658 (:month-start . :month-end)
23659 (:year-start . :year-end))))
23660 (dolist (p-cell p-alist)
23661 (org-element-put-property
23662 split-ts
23663 (funcall (if end #'car #'cdr) p-cell)
23664 (org-element-property
23665 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23666 ;; Eventually refresh `:raw-value'.
23667 (org-element-put-property split-ts :raw-value nil)
23668 (org-element-put-property
23669 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23671 (defun org-timestamp-translate (timestamp &optional boundary)
23672 "Translate TIMESTAMP object to custom format.
23674 Format string is defined in `org-time-stamp-custom-formats',
23675 which see.
23677 When optional argument BOUNDARY is non-nil, it is either the
23678 symbol `start' or `end'. In this case, only translate the
23679 starting or ending part of TIMESTAMP if it is a date or time
23680 range. Otherwise, translate both parts.
23682 Return timestamp as-is if `org-display-custom-times' is nil or if
23683 it has a `diary' type."
23684 (let ((type (org-element-property :type timestamp)))
23685 (if (or (not org-display-custom-times) (eq type 'diary))
23686 (org-element-interpret-data timestamp)
23687 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23688 org-time-stamp-custom-formats)))
23689 (if (and (not boundary) (memq type '(active-range inactive-range)))
23690 (concat (org-timestamp-format timestamp fmt)
23691 "--"
23692 (org-timestamp-format timestamp fmt t))
23693 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23697 ;;; Other stuff.
23699 (defvar reftex-docstruct-symbol)
23700 (defvar org--rds)
23702 (defun org-reftex-citation ()
23703 "Use reftex-citation to insert a citation into the buffer.
23704 This looks for a line like
23706 #+BIBLIOGRAPHY: foo plain option:-d
23708 and derives from it that foo.bib is the bibliography file relevant
23709 for this document. It then installs the necessary environment for RefTeX
23710 to work in this buffer and calls `reftex-citation' to insert a citation
23711 into the buffer.
23713 Export of such citations to both LaTeX and HTML is handled by the contributed
23714 package ox-bibtex by Taru Karttunen."
23715 (interactive)
23716 (let ((reftex-docstruct-symbol 'org--rds)
23717 org--rds bib)
23718 (org-with-wide-buffer
23719 (let ((case-fold-search t)
23720 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23721 (if (not (save-excursion
23722 (or (re-search-forward re nil t)
23723 (re-search-backward re nil t))))
23724 (user-error "No bibliography defined in file")
23725 (setq bib (concat (match-string 1) ".bib")
23726 org--rds (list (list 'bib bib))))))
23727 (call-interactively 'reftex-citation)))
23729 ;;;; Functions extending outline functionality
23731 (defun org-beginning-of-line (&optional n)
23732 "Go to the beginning of the current visible line.
23734 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23735 tags on the first attempt, and only move to after the tags when
23736 the cursor is already beyond the end of the headline.
23738 With argument N not nil or 1, move forward N - 1 lines first."
23739 (interactive "^p")
23740 (let ((origin (point))
23741 (special (pcase org-special-ctrl-a/e
23742 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23743 deactivate-mark)
23744 ;; First move to a visible line.
23745 (if (bound-and-true-p visual-line-mode)
23746 (beginning-of-visual-line n)
23747 (move-beginning-of-line n)
23748 ;; `move-beginning-of-line' may leave point after invisible
23749 ;; characters if line starts with such of these (e.g., with
23750 ;; a link at column 0). Really move to the beginning of the
23751 ;; current visible line.
23752 (beginning-of-line))
23753 (cond
23754 ;; No special behavior. Point is already at the beginning of
23755 ;; a line, logical or visual.
23756 ((not special))
23757 ;; `beginning-of-visual-line' left point before logical beginning
23758 ;; of line: point is at the beginning of a visual line. Bail
23759 ;; out.
23760 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23761 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23762 ;; At a headline, special position is before the title, but
23763 ;; after any TODO keyword or priority cookie.
23764 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23765 (line-end-position)))
23766 (bol (point)))
23767 (if (eq special 'reversed)
23768 (when (and (= origin bol) (eq last-command this-command))
23769 (goto-char refpos))
23770 (when (or (> origin refpos) (= origin bol))
23771 (goto-char refpos)))))
23772 ((and (looking-at org-list-full-item-re)
23773 (memq (org-element-type (save-match-data (org-element-at-point)))
23774 '(item plain-list)))
23775 ;; Set special position at first white space character after
23776 ;; bullet, and check-box, if any.
23777 (let ((after-bullet
23778 (let ((box (match-end 3)))
23779 (cond ((not box) (match-end 1))
23780 ((eq (char-after box) ?\s) (1+ box))
23781 (t box)))))
23782 (if (eq special 'reversed)
23783 (when (and (= (point) origin) (eq last-command this-command))
23784 (goto-char after-bullet))
23785 (when (or (> origin after-bullet) (= (point) origin))
23786 (goto-char after-bullet)))))
23787 ;; No special context. Point is already at beginning of line.
23788 (t nil))))
23790 (defun org-end-of-line (&optional n)
23791 "Go to the end of the line, but before ellipsis, if any.
23793 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23794 tags on the first attempt, and only move to after the tags when
23795 the cursor is already beyond the end of the headline.
23797 With argument N not nil or 1, move forward N - 1 lines first."
23798 (interactive "^p")
23799 (let ((origin (point))
23800 (special (pcase org-special-ctrl-a/e
23801 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23802 deactivate-mark)
23803 ;; First move to a visible line.
23804 (if (bound-and-true-p visual-line-mode)
23805 (beginning-of-visual-line n)
23806 (move-beginning-of-line n))
23807 (cond
23808 ;; At a headline, with tags.
23809 ((and special
23810 (save-excursion
23811 (beginning-of-line)
23812 (let ((case-fold-search nil))
23813 (looking-at org-complex-heading-regexp)))
23814 (match-end 5))
23815 (let ((tags (save-excursion
23816 (goto-char (match-beginning 5))
23817 (skip-chars-backward " \t")
23818 (point)))
23819 (visual-end (and (bound-and-true-p visual-line-mode)
23820 (save-excursion
23821 (end-of-visual-line)
23822 (point)))))
23823 ;; If `end-of-visual-line' brings us before end of line or
23824 ;; even tags, i.e., the headline spans over multiple visual
23825 ;; lines, move there.
23826 (cond ((and visual-end
23827 (< visual-end tags)
23828 (<= origin visual-end))
23829 (goto-char visual-end))
23830 ((eq special 'reversed)
23831 (if (and (= origin (line-end-position))
23832 (eq this-command last-command))
23833 (goto-char tags)
23834 (end-of-line)))
23836 (if (or (< origin tags) (= origin (line-end-position)))
23837 (goto-char tags)
23838 (end-of-line))))))
23839 ((bound-and-true-p visual-line-mode)
23840 (let ((bol (line-beginning-position)))
23841 (end-of-visual-line)
23842 ;; If `end-of-visual-line' gets us past the ellipsis at the
23843 ;; end of a line, backtrack and use `end-of-line' instead.
23844 (when (/= bol (line-beginning-position))
23845 (goto-char bol)
23846 (end-of-line))))
23847 (t (end-of-line)))))
23849 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23850 (define-key org-mode-map "\C-e" 'org-end-of-line)
23852 (defun org-backward-sentence (&optional _arg)
23853 "Go to beginning of sentence, or beginning of table field.
23854 This will call `backward-sentence' or `org-table-beginning-of-field',
23855 depending on context."
23856 (interactive)
23857 (let* ((element (org-element-at-point))
23858 (contents-begin (org-element-property :contents-begin element))
23859 (table (org-element-lineage element '(table) t)))
23860 (if (and table
23861 (> (point) contents-begin)
23862 (<= (point) (org-element-property :contents-end table)))
23863 (call-interactively #'org-table-beginning-of-field)
23864 (save-restriction
23865 (when (and contents-begin
23866 (< (point-min) contents-begin)
23867 (> (point) contents-begin))
23868 (narrow-to-region contents-begin
23869 (org-element-property :contents-end element)))
23870 (call-interactively #'backward-sentence)))))
23872 (defun org-forward-sentence (&optional _arg)
23873 "Go to end of sentence, or end of table field.
23874 This will call `forward-sentence' or `org-table-end-of-field',
23875 depending on context."
23876 (interactive)
23877 (let* ((element (org-element-at-point))
23878 (contents-end (org-element-property :contents-end element))
23879 (table (org-element-lineage element '(table) t)))
23880 (if (and table
23881 (>= (point) (org-element-property :contents-begin table))
23882 (< (point) contents-end))
23883 (call-interactively #'org-table-end-of-field)
23884 (save-restriction
23885 (when (and contents-end
23886 (> (point-max) contents-end)
23887 ;; Skip blank lines between elements.
23888 (< (org-element-property :end element)
23889 (save-excursion (goto-char contents-end)
23890 (skip-chars-forward " \r\t\n"))))
23891 (narrow-to-region (org-element-property :contents-begin element)
23892 contents-end))
23893 (call-interactively #'forward-sentence)))))
23895 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23896 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23898 (defun org-kill-line (&optional _arg)
23899 "Kill line, to tags or end of line."
23900 (interactive)
23901 (cond
23902 ((or (not org-special-ctrl-k)
23903 (bolp)
23904 (not (org-at-heading-p)))
23905 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23906 org-ctrl-k-protect-subtree
23907 (or (eq org-ctrl-k-protect-subtree 'error)
23908 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23909 (user-error "C-k aborted as it would kill a hidden subtree"))
23910 (call-interactively
23911 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23912 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23913 (kill-region (point) (match-beginning 1))
23914 (org-set-tags nil t))
23915 (t (kill-region (point) (point-at-eol)))))
23917 (define-key org-mode-map "\C-k" 'org-kill-line)
23919 (defun org-yank (&optional arg)
23920 "Yank. If the kill is a subtree, treat it specially.
23921 This command will look at the current kill and check if is a single
23922 subtree, or a series of subtrees[1]. If it passes the test, and if the
23923 cursor is at the beginning of a line or after the stars of a currently
23924 empty headline, then the yank is handled specially. How exactly depends
23925 on the value of the following variables.
23927 `org-yank-folded-subtrees'
23928 By default, this variable is non-nil, which results in
23929 subtree(s) being folded after insertion, except if doing so
23930 would swallow text after the yanked text.
23932 `org-yank-adjusted-subtrees'
23933 When non-nil (the default value is nil), the subtree will be
23934 promoted or demoted in order to fit into the local outline tree
23935 structure, which means that the level will be adjusted so that it
23936 becomes the smaller one of the two *visible* surrounding headings.
23938 Any prefix to this command will cause `yank' to be called directly with
23939 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23940 will just
23941 plainly yank the text as it is.
23943 \[1] The test checks if the first non-white line is a heading
23944 and if there are no other headings with fewer stars."
23945 (interactive "P")
23946 (org-yank-generic 'yank arg))
23948 (defun org-yank-generic (command arg)
23949 "Perform some yank-like command.
23951 This function implements the behavior described in the `org-yank'
23952 documentation. However, it has been generalized to work for any
23953 interactive command with similar behavior."
23955 ;; pretend to be command COMMAND
23956 (setq this-command command)
23958 (if arg
23959 (call-interactively command)
23961 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23962 (and (org-kill-is-subtree-p)
23963 (or (bolp)
23964 (and (looking-at "[ \t]*$")
23965 (string-match
23966 "\\`\\*+\\'"
23967 (buffer-substring (point-at-bol) (point)))))))
23968 swallowp)
23969 (cond
23970 ((and subtreep org-yank-folded-subtrees)
23971 (let ((beg (point))
23972 end)
23973 (if (and subtreep org-yank-adjusted-subtrees)
23974 (org-paste-subtree nil nil 'for-yank)
23975 (call-interactively command))
23977 (setq end (point))
23978 (goto-char beg)
23979 (when (and (bolp) subtreep
23980 (not (setq swallowp
23981 (org-yank-folding-would-swallow-text beg end))))
23982 (org-with-limited-levels
23983 (or (looking-at org-outline-regexp)
23984 (re-search-forward org-outline-regexp-bol end t))
23985 (while (and (< (point) end) (looking-at org-outline-regexp))
23986 (outline-hide-subtree)
23987 (org-cycle-show-empty-lines 'folded)
23988 (condition-case nil
23989 (outline-forward-same-level 1)
23990 (error (goto-char end))))))
23991 (when swallowp
23992 (message
23993 "Inserted text not folded because that would swallow text"))
23995 (goto-char end)
23996 (skip-chars-forward " \t\n\r")
23997 (beginning-of-line 1)
23998 (push-mark beg 'nomsg)))
23999 ((and subtreep org-yank-adjusted-subtrees)
24000 (let ((beg (point-at-bol)))
24001 (org-paste-subtree nil nil 'for-yank)
24002 (push-mark beg 'nomsg)))
24004 (call-interactively command))))))
24006 (defun org-yank-folding-would-swallow-text (beg end)
24007 "Would hide-subtree at BEG swallow any text after END?"
24008 (let (level)
24009 (org-with-limited-levels
24010 (save-excursion
24011 (goto-char beg)
24012 (when (or (looking-at org-outline-regexp)
24013 (re-search-forward org-outline-regexp-bol end t))
24014 (setq level (org-outline-level)))
24015 (goto-char end)
24016 (skip-chars-forward " \t\r\n\v\f")
24017 (not (or (eobp)
24018 (and (bolp) (looking-at-p org-outline-regexp)
24019 (<= (org-outline-level) level))))))))
24021 (define-key org-mode-map "\C-y" 'org-yank)
24023 (defun org-truely-invisible-p ()
24024 "Check if point is at a character currently not visible.
24025 This version does not only check the character property, but also
24026 `visible-mode'."
24027 (unless (bound-and-true-p visible-mode)
24028 (org-invisible-p)))
24030 (defun org-invisible-p2 ()
24031 "Check if point is at a character currently not visible.
24033 If the point is at EOL (and not at the beginning of a buffer too),
24034 move it back by one char before doing this check."
24035 (save-excursion
24036 (when (and (eolp) (not (bobp)))
24037 (backward-char 1))
24038 (org-invisible-p)))
24040 (defun org-back-to-heading (&optional invisible-ok)
24041 "Call `outline-back-to-heading', but provide a better error message."
24042 (condition-case nil
24043 (outline-back-to-heading invisible-ok)
24044 (error (error "Before first headline at position %d in buffer %s"
24045 (point) (current-buffer)))))
24047 (defun org-before-first-heading-p ()
24048 "Before first heading?"
24049 (save-excursion
24050 (end-of-line)
24051 (null (re-search-backward org-outline-regexp-bol nil t))))
24053 (defun org-at-heading-p (&optional ignored)
24054 (outline-on-heading-p t))
24056 (defun org-in-commented-heading-p (&optional no-inheritance)
24057 "Non-nil if point is under a commented heading.
24058 This function also checks ancestors of the current headline,
24059 unless optional argument NO-INHERITANCE is non-nil."
24060 (cond
24061 ((org-before-first-heading-p) nil)
24062 ((let ((headline (nth 4 (org-heading-components))))
24063 (and headline
24064 (let ((case-fold-search nil))
24065 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24066 headline)))))
24067 (no-inheritance nil)
24069 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24071 (defun org-at-comment-p nil
24072 "Is cursor in a commented line?"
24073 (save-excursion
24074 (save-match-data
24075 (beginning-of-line)
24076 (looking-at "^[ \t]*# "))))
24078 (defun org-at-drawer-p nil
24079 "Is cursor at a drawer keyword?"
24080 (save-excursion
24081 (move-beginning-of-line 1)
24082 (looking-at org-drawer-regexp)))
24084 (defun org-at-block-p nil
24085 "Is cursor at a block keyword?"
24086 (save-excursion
24087 (move-beginning-of-line 1)
24088 (looking-at org-block-regexp)))
24090 (defun org-point-at-end-of-empty-headline ()
24091 "If point is at the end of an empty headline, return t, else nil.
24092 If the heading only contains a TODO keyword, it is still still considered
24093 empty."
24094 (let ((case-fold-search nil))
24095 (and (looking-at "[ \t]*$")
24096 org-todo-line-regexp
24097 (save-excursion
24098 (beginning-of-line)
24099 (looking-at org-todo-line-regexp)
24100 (string= (match-string 3) "")))))
24102 (defun org-at-heading-or-item-p ()
24103 (or (org-at-heading-p) (org-at-item-p)))
24105 (defun org-at-target-p ()
24106 (or (org-in-regexp org-radio-target-regexp)
24107 (org-in-regexp org-target-regexp)))
24108 ;; Compatibility alias with Org versions < 7.8.03
24109 (defalias 'org-on-target-p 'org-at-target-p)
24111 (defun org-up-heading-all (arg)
24112 "Move to the heading line of which the present line is a subheading.
24113 This function considers both visible and invisible heading lines.
24114 With argument, move up ARG levels."
24115 (outline-up-heading arg t))
24117 (defun org-up-heading-safe ()
24118 "Move to the heading line of which the present line is a subheading.
24119 This version will not throw an error. It will return the level of the
24120 headline found, or nil if no higher level is found.
24122 Also, this function will be a lot faster than `outline-up-heading',
24123 because it relies on stars being the outline starters. This can really
24124 make a significant difference in outlines with very many siblings."
24125 (when (ignore-errors (org-back-to-heading t))
24126 (let ((level-up (1- (funcall outline-level))))
24127 (and (> level-up 0)
24128 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24129 (funcall outline-level)))))
24131 (defun org-first-sibling-p ()
24132 "Is this heading the first child of its parents?"
24133 (interactive)
24134 (let ((re org-outline-regexp-bol)
24135 level l)
24136 (unless (org-at-heading-p t)
24137 (user-error "Not at a heading"))
24138 (setq level (funcall outline-level))
24139 (save-excursion
24140 (if (not (re-search-backward re nil t))
24142 (setq l (funcall outline-level))
24143 (< l level)))))
24145 (defun org-goto-sibling (&optional previous)
24146 "Goto the next sibling, even if it is invisible.
24147 When PREVIOUS is set, go to the previous sibling instead. Returns t
24148 when a sibling was found. When none is found, return nil and don't
24149 move point."
24150 (let ((fun (if previous 're-search-backward 're-search-forward))
24151 (pos (point))
24152 (re org-outline-regexp-bol)
24153 level l)
24154 (when (ignore-errors (org-back-to-heading t))
24155 (setq level (funcall outline-level))
24156 (catch 'exit
24157 (or previous (forward-char 1))
24158 (while (funcall fun re nil t)
24159 (setq l (funcall outline-level))
24160 (when (< l level) (goto-char pos) (throw 'exit nil))
24161 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24162 (goto-char pos)
24163 nil))))
24165 (defun org-show-siblings ()
24166 "Show all siblings of the current headline."
24167 (save-excursion
24168 (while (org-goto-sibling) (org-flag-heading nil)))
24169 (save-excursion
24170 (while (org-goto-sibling 'previous)
24171 (org-flag-heading nil))))
24173 (defun org-goto-first-child ()
24174 "Goto the first child, even if it is invisible.
24175 Return t when a child was found. Otherwise don't move point and
24176 return nil."
24177 (let (level (pos (point)) (re org-outline-regexp-bol))
24178 (when (ignore-errors (org-back-to-heading t))
24179 (setq level (outline-level))
24180 (forward-char 1)
24181 (if (and (re-search-forward re nil t) (> (outline-level) level))
24182 (progn (goto-char (match-beginning 0)) t)
24183 (goto-char pos) nil))))
24185 (defun org-show-hidden-entry ()
24186 "Show an entry where even the heading is hidden."
24187 (save-excursion
24188 (org-show-entry)))
24190 (defun org-flag-heading (flag &optional entry)
24191 "Flag the current heading. FLAG non-nil means make invisible.
24192 When ENTRY is non-nil, show the entire entry."
24193 (save-excursion
24194 (org-back-to-heading t)
24195 ;; Check if we should show the entire entry
24196 (if entry
24197 (progn
24198 (org-show-entry)
24199 (save-excursion
24200 (and (outline-next-heading)
24201 (org-flag-heading nil))))
24202 (outline-flag-region (max (point-min) (1- (point)))
24203 (save-excursion (outline-end-of-heading) (point))
24204 flag))))
24206 (defun org-get-next-sibling ()
24207 "Move to next heading of the same level, and return point.
24208 If there is no such heading, return nil.
24209 This is like outline-next-sibling, but invisible headings are ok."
24210 (let ((level (funcall outline-level)))
24211 (outline-next-heading)
24212 (while (and (not (eobp)) (> (funcall outline-level) level))
24213 (outline-next-heading))
24214 (unless (or (eobp) (< (funcall outline-level) level))
24215 (point))))
24217 (defun org-get-last-sibling ()
24218 "Move to previous heading of the same level, and return point.
24219 If there is no such heading, return nil."
24220 (let ((opoint (point))
24221 (level (funcall outline-level)))
24222 (outline-previous-heading)
24223 (when (and (/= (point) opoint) (outline-on-heading-p t))
24224 (while (and (> (funcall outline-level) level)
24225 (not (bobp)))
24226 (outline-previous-heading))
24227 (unless (< (funcall outline-level) level)
24228 (point)))))
24230 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24231 "Goto to the end of a subtree."
24232 ;; This contains an exact copy of the original function, but it uses
24233 ;; `org-back-to-heading', to make it work also in invisible
24234 ;; trees. And is uses an invisible-ok argument.
24235 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24236 ;; Furthermore, when used inside Org, finding the end of a large subtree
24237 ;; with many children and grandchildren etc, this can be much faster
24238 ;; than the outline version.
24239 (org-back-to-heading invisible-ok)
24240 (let ((first t)
24241 (level (funcall outline-level)))
24242 (if (and (derived-mode-p 'org-mode) (< level 1000))
24243 ;; A true heading (not a plain list item), in Org
24244 ;; This means we can easily find the end by looking
24245 ;; only for the right number of stars. Using a regexp to do
24246 ;; this is so much faster than using a Lisp loop.
24247 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24248 (forward-char 1)
24249 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24250 ;; something else, do it the slow way
24251 (while (and (not (eobp))
24252 (or first (> (funcall outline-level) level)))
24253 (setq first nil)
24254 (outline-next-heading)))
24255 (unless to-heading
24256 (when (memq (preceding-char) '(?\n ?\^M))
24257 ;; Go to end of line before heading
24258 (forward-char -1)
24259 (when (memq (preceding-char) '(?\n ?\^M))
24260 ;; leave blank line before heading
24261 (forward-char -1)))))
24262 (point))
24264 (defun org-end-of-meta-data (&optional full)
24265 "Skip planning line and properties drawer in current entry.
24266 When optional argument FULL is non-nil, also skip empty lines,
24267 clocking lines and regular drawers at the beginning of the
24268 entry."
24269 (org-back-to-heading t)
24270 (forward-line)
24271 (when (looking-at-p org-planning-line-re) (forward-line))
24272 (when (looking-at org-property-drawer-re)
24273 (goto-char (match-end 0))
24274 (forward-line))
24275 (when (and full (not (org-at-heading-p)))
24276 (catch 'exit
24277 (let ((end (save-excursion (outline-next-heading) (point)))
24278 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24279 (while (not (eobp))
24280 (cond ((looking-at-p org-drawer-regexp)
24281 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24282 (forward-line)
24283 (throw 'exit t)))
24284 ((looking-at-p re) (forward-line))
24285 (t (throw 'exit t))))))))
24287 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24288 "Move forward to the ARG'th subheading at same level as this one.
24289 Stop at the first and last subheadings of a superior heading.
24290 Normally this only looks at visible headings, but when INVISIBLE-OK is
24291 non-nil it will also look at invisible ones."
24292 (interactive "p")
24293 (let ((backward? (and arg (< arg 0))))
24294 (if (org-before-first-heading-p)
24295 (if backward? (goto-char (point-min)) (outline-next-heading))
24296 (org-back-to-heading invisible-ok)
24297 (unless backward? (end-of-line)) ;do not match current headline
24298 (let ((level (- (match-end 0) (match-beginning 0) 1))
24299 (f (if backward? #'re-search-backward #'re-search-forward))
24300 (count (if arg (abs arg) 1))
24301 (result (point)))
24302 (while (and (> count 0)
24303 (funcall f org-outline-regexp-bol nil 'move))
24304 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24305 (cond ((< l level) (setq count 0))
24306 ((and (= l level)
24307 (or invisible-ok
24308 (not (org-invisible-p
24309 (line-beginning-position)))))
24310 (cl-decf count)
24311 (when (= l level) (setq result (point)))))))
24312 (goto-char result))
24313 (beginning-of-line))))
24315 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24316 "Move backward to the ARG'th subheading at same level as this one.
24317 Stop at the first and last subheadings of a superior heading."
24318 (interactive "p")
24319 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24321 (defun org-next-visible-heading (arg)
24322 "Move to the next visible heading.
24324 This function wraps `outline-next-visible-heading' with
24325 `org-with-limited-levels' in order to skip over inline tasks and
24326 respect customization of `org-odd-levels-only'."
24327 (interactive "p")
24328 (org-with-limited-levels
24329 (outline-next-visible-heading arg)))
24331 (defun org-previous-visible-heading (arg)
24332 "Move to the previous visible heading.
24334 This function wraps `outline-previous-visible-heading' with
24335 `org-with-limited-levels' in order to skip over inline tasks and
24336 respect customization of `org-odd-levels-only'."
24337 (interactive "p")
24338 (org-with-limited-levels
24339 (outline-previous-visible-heading arg)))
24341 (defun org-next-block (arg &optional backward block-regexp)
24342 "Jump to the next block.
24344 With a prefix argument ARG, jump forward ARG many blocks.
24346 When BACKWARD is non-nil, jump to the previous block.
24348 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24349 Match data is set according to this regexp when the function
24350 returns.
24352 Return point at beginning of the opening line of found block.
24353 Throw an error if no block is found."
24354 (interactive "p")
24355 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24356 (case-fold-search t)
24357 (search-fn (if backward #'re-search-backward #'re-search-forward))
24358 (count (or arg 1))
24359 (origin (point))
24360 last-element)
24361 (if backward (beginning-of-line) (end-of-line))
24362 (while (and (> count 0) (funcall search-fn re nil t))
24363 (let ((element (save-excursion
24364 (goto-char (match-beginning 0))
24365 (save-match-data (org-element-at-point)))))
24366 (when (and (memq (org-element-type element)
24367 '(center-block comment-block dynamic-block
24368 example-block export-block quote-block
24369 special-block src-block verse-block))
24370 (<= (match-beginning 0)
24371 (org-element-property :post-affiliated element)))
24372 (setq last-element element)
24373 (cl-decf count))))
24374 (if (= count 0)
24375 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24376 (save-match-data (org-show-context)))
24377 (goto-char origin)
24378 (user-error "No %s code blocks" (if backward "previous" "further")))))
24380 (defun org-previous-block (arg &optional block-regexp)
24381 "Jump to the previous block.
24382 With a prefix argument ARG, jump backward ARG many source blocks.
24383 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24384 (interactive "p")
24385 (org-next-block arg t block-regexp))
24387 (defun org-forward-paragraph ()
24388 "Move forward to beginning of next paragraph or equivalent.
24390 The function moves point to the beginning of the next visible
24391 structural element, which can be a paragraph, a table, a list
24392 item, etc. It also provides some special moves for convenience:
24394 - On an affiliated keyword, jump to the beginning of the
24395 relative element.
24396 - On an item or a footnote definition, move to the second
24397 element inside, if any.
24398 - On a table or a property drawer, jump after it.
24399 - On a verse or source block, stop after blank lines."
24400 (interactive)
24401 (unless (eobp)
24402 (let* ((deactivate-mark nil)
24403 (element (org-element-at-point))
24404 (type (org-element-type element))
24405 (post-affiliated (org-element-property :post-affiliated element))
24406 (contents-begin (org-element-property :contents-begin element))
24407 (contents-end (org-element-property :contents-end element))
24408 (end (let ((end (org-element-property :end element)) (parent element))
24409 (while (and (setq parent (org-element-property :parent parent))
24410 (= (org-element-property :contents-end parent) end))
24411 (setq end (org-element-property :end parent)))
24412 end)))
24413 (cond ((not element)
24414 (skip-chars-forward " \r\t\n")
24415 (or (eobp) (beginning-of-line)))
24416 ;; On affiliated keywords, move to element's beginning.
24417 ((< (point) post-affiliated)
24418 (goto-char post-affiliated))
24419 ;; At a table row, move to the end of the table. Similarly,
24420 ;; at a node property, move to the end of the property
24421 ;; drawer.
24422 ((memq type '(node-property table-row))
24423 (goto-char (org-element-property
24424 :end (org-element-property :parent element))))
24425 ((memq type '(property-drawer table)) (goto-char end))
24426 ;; Consider blank lines as separators in verse and source
24427 ;; blocks to ease editing.
24428 ((memq type '(src-block verse-block))
24429 (when (eq type 'src-block)
24430 (setq contents-end
24431 (save-excursion (goto-char end)
24432 (skip-chars-backward " \r\t\n")
24433 (line-beginning-position))))
24434 (beginning-of-line)
24435 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24436 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24437 (goto-char end)
24438 (skip-chars-forward " \r\t\n")
24439 (if (= (point) contents-end) (goto-char end)
24440 (beginning-of-line))))
24441 ;; With no contents, just skip element.
24442 ((not contents-begin) (goto-char end))
24443 ;; If contents are invisible, skip the element altogether.
24444 ((org-invisible-p (line-end-position))
24445 (cl-case type
24446 (headline
24447 (org-with-limited-levels (outline-next-visible-heading 1)))
24448 ;; At a plain list, make sure we move to the next item
24449 ;; instead of skipping the whole list.
24450 (plain-list (forward-char)
24451 (org-forward-paragraph))
24452 (otherwise (goto-char end))))
24453 ((>= (point) contents-end) (goto-char end))
24454 ((>= (point) contents-begin)
24455 ;; This can only happen on paragraphs and plain lists.
24456 (cl-case type
24457 (paragraph (goto-char end))
24458 ;; At a plain list, try to move to second element in
24459 ;; first item, if possible.
24460 (plain-list (end-of-line)
24461 (org-forward-paragraph))))
24462 ;; When contents start on the middle of a line (e.g. in
24463 ;; items and footnote definitions), try to reach first
24464 ;; element starting after current line.
24465 ((> (line-end-position) contents-begin)
24466 (end-of-line)
24467 (org-forward-paragraph))
24468 (t (goto-char contents-begin))))))
24470 (defun org-backward-paragraph ()
24471 "Move backward to start of previous paragraph or equivalent.
24473 The function moves point to the beginning of the current
24474 structural element, which can be a paragraph, a table, a list
24475 item, etc., or to the beginning of the previous visible one if
24476 point is already there. It also provides some special moves for
24477 convenience:
24479 - On an affiliated keyword, jump to the first one.
24480 - On a table or a property drawer, move to its beginning.
24481 - On a verse or source block, stop before blank lines."
24482 (interactive)
24483 (unless (bobp)
24484 (let* ((deactivate-mark nil)
24485 (element (org-element-at-point))
24486 (type (org-element-type element))
24487 (contents-begin (org-element-property :contents-begin element))
24488 (contents-end (org-element-property :contents-end element))
24489 (post-affiliated (org-element-property :post-affiliated element))
24490 (begin (org-element-property :begin element)))
24491 (cond
24492 ((not element) (goto-char (point-min)))
24493 ((= (point) begin)
24494 (backward-char)
24495 (org-backward-paragraph))
24496 ((<= (point) post-affiliated) (goto-char begin))
24497 ((memq type '(node-property table-row))
24498 (goto-char (org-element-property
24499 :post-affiliated (org-element-property :parent element))))
24500 ((memq type '(property-drawer table)) (goto-char begin))
24501 ((memq type '(src-block verse-block))
24502 (when (eq type 'src-block)
24503 (setq contents-begin
24504 (save-excursion (goto-char begin) (forward-line) (point))))
24505 (if (= (point) contents-begin) (goto-char post-affiliated)
24506 ;; Inside a verse block, see blank lines as paragraph
24507 ;; separators.
24508 (let ((origin (point)))
24509 (skip-chars-backward " \r\t\n" contents-begin)
24510 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24511 (skip-chars-forward " \r\t\n" origin)
24512 (if (= (point) origin) (goto-char contents-begin)
24513 (beginning-of-line))))))
24514 ((not contents-begin) (goto-char (or post-affiliated begin)))
24515 ((eq type 'paragraph)
24516 (goto-char contents-begin)
24517 ;; When at first paragraph in an item or a footnote definition,
24518 ;; move directly to beginning of line.
24519 (let ((parent-contents
24520 (org-element-property
24521 :contents-begin (org-element-property :parent element))))
24522 (when (and parent-contents (= parent-contents contents-begin))
24523 (beginning-of-line))))
24524 ;; At the end of a greater element, move to the beginning of the
24525 ;; last element within.
24526 ((>= (point) contents-end)
24527 (goto-char (1- contents-end))
24528 (org-backward-paragraph))
24529 (t (goto-char (or post-affiliated begin))))
24530 ;; Ensure we never leave point invisible.
24531 (when (org-invisible-p (point)) (beginning-of-visual-line)))))
24533 (defun org-forward-element ()
24534 "Move forward by one element.
24535 Move to the next element at the same level, when possible."
24536 (interactive)
24537 (cond ((eobp) (user-error "Cannot move further down"))
24538 ((org-with-limited-levels (org-at-heading-p))
24539 (let ((origin (point)))
24540 (goto-char (org-end-of-subtree nil t))
24541 (unless (org-with-limited-levels (org-at-heading-p))
24542 (goto-char origin)
24543 (user-error "Cannot move further down"))))
24545 (let* ((elem (org-element-at-point))
24546 (end (org-element-property :end elem))
24547 (parent (org-element-property :parent elem)))
24548 (cond ((and parent (= (org-element-property :contents-end parent) end))
24549 (goto-char (org-element-property :end parent)))
24550 ((integer-or-marker-p end) (goto-char end))
24551 (t (message "No element at point")))))))
24553 (defun org-backward-element ()
24554 "Move backward by one element.
24555 Move to the previous element at the same level, when possible."
24556 (interactive)
24557 (cond ((bobp) (user-error "Cannot move further up"))
24558 ((org-with-limited-levels (org-at-heading-p))
24559 ;; At a headline, move to the previous one, if any, or stay
24560 ;; here.
24561 (let ((origin (point)))
24562 (org-with-limited-levels (org-backward-heading-same-level 1))
24563 ;; When current headline has no sibling above, move to its
24564 ;; parent.
24565 (when (= (point) origin)
24566 (or (org-with-limited-levels (org-up-heading-safe))
24567 (progn (goto-char origin)
24568 (user-error "Cannot move further up"))))))
24570 (let* ((elem (org-element-at-point))
24571 (beg (org-element-property :begin elem)))
24572 (cond
24573 ;; Move to beginning of current element if point isn't
24574 ;; there already.
24575 ((null beg) (message "No element at point"))
24576 ((/= (point) beg) (goto-char beg))
24577 (t (goto-char beg)
24578 (skip-chars-backward " \r\t\n")
24579 (unless (bobp)
24580 (let ((prev (org-element-at-point)))
24581 (goto-char (org-element-property :begin prev))
24582 (while (and (setq prev (org-element-property :parent prev))
24583 (<= (org-element-property :end prev) beg))
24584 (goto-char (org-element-property :begin prev)))))))))))
24586 (defun org-up-element ()
24587 "Move to upper element."
24588 (interactive)
24589 (if (org-with-limited-levels (org-at-heading-p))
24590 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24591 (let* ((elem (org-element-at-point))
24592 (parent (org-element-property :parent elem)))
24593 (if parent (goto-char (org-element-property :begin parent))
24594 (if (org-with-limited-levels (org-before-first-heading-p))
24595 (user-error "No surrounding element")
24596 (org-with-limited-levels (org-back-to-heading)))))))
24598 (defun org-down-element ()
24599 "Move to inner element."
24600 (interactive)
24601 (let ((element (org-element-at-point)))
24602 (cond
24603 ((memq (org-element-type element) '(plain-list table))
24604 (goto-char (org-element-property :contents-begin element))
24605 (forward-char))
24606 ((memq (org-element-type element) org-element-greater-elements)
24607 ;; If contents are hidden, first disclose them.
24608 (when (org-invisible-p (line-end-position)) (org-cycle))
24609 (goto-char (or (org-element-property :contents-begin element)
24610 (user-error "No content for this element"))))
24611 (t (user-error "No inner element")))))
24613 (defun org-drag-element-backward ()
24614 "Move backward element at point."
24615 (interactive)
24616 (let ((elem (or (org-element-at-point)
24617 (user-error "No element at point"))))
24618 (if (eq (org-element-type elem) 'headline)
24619 ;; Preserve point when moving a whole tree, even if point was
24620 ;; on blank lines below the headline.
24621 (let ((offset (skip-chars-backward " \t\n")))
24622 (unwind-protect (org-move-subtree-up)
24623 (forward-char (- offset))))
24624 (let ((prev-elem
24625 (save-excursion
24626 (goto-char (org-element-property :begin elem))
24627 (skip-chars-backward " \r\t\n")
24628 (unless (bobp)
24629 (let* ((beg (org-element-property :begin elem))
24630 (prev (org-element-at-point))
24631 (up prev))
24632 (while (and (setq up (org-element-property :parent up))
24633 (<= (org-element-property :end up) beg))
24634 (setq prev up))
24635 prev)))))
24636 ;; Error out if no previous element or previous element is
24637 ;; a parent of the current one.
24638 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24639 (user-error "Cannot drag element backward")
24640 (let ((pos (point)))
24641 (org-element-swap-A-B prev-elem elem)
24642 (goto-char (+ (org-element-property :begin prev-elem)
24643 (- pos (org-element-property :begin elem))))))))))
24645 (defun org-drag-element-forward ()
24646 "Move forward element at point."
24647 (interactive)
24648 (let* ((pos (point))
24649 (elem (or (org-element-at-point)
24650 (user-error "No element at point"))))
24651 (when (= (point-max) (org-element-property :end elem))
24652 (user-error "Cannot drag element forward"))
24653 (goto-char (org-element-property :end elem))
24654 (let ((next-elem (org-element-at-point)))
24655 (when (or (org-element-nested-p elem next-elem)
24656 (and (eq (org-element-type next-elem) 'headline)
24657 (not (eq (org-element-type elem) 'headline))))
24658 (goto-char pos)
24659 (user-error "Cannot drag element forward"))
24660 ;; Compute new position of point: it's shifted by NEXT-ELEM
24661 ;; body's length (without final blanks) and by the length of
24662 ;; blanks between ELEM and NEXT-ELEM.
24663 (let ((size-next (- (save-excursion
24664 (goto-char (org-element-property :end next-elem))
24665 (skip-chars-backward " \r\t\n")
24666 (forward-line)
24667 ;; Small correction if buffer doesn't end
24668 ;; with a newline character.
24669 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24670 (org-element-property :begin next-elem)))
24671 (size-blank (- (org-element-property :end elem)
24672 (save-excursion
24673 (goto-char (org-element-property :end elem))
24674 (skip-chars-backward " \r\t\n")
24675 (forward-line)
24676 (point)))))
24677 (org-element-swap-A-B elem next-elem)
24678 (goto-char (+ pos size-next size-blank))))))
24680 (defun org-drag-line-forward (arg)
24681 "Drag the line at point ARG lines forward."
24682 (interactive "p")
24683 (dotimes (_ (abs arg))
24684 (let ((c (current-column)))
24685 (if (< 0 arg)
24686 (progn
24687 (beginning-of-line 2)
24688 (transpose-lines 1)
24689 (beginning-of-line 0))
24690 (transpose-lines 1)
24691 (beginning-of-line -1))
24692 (org-move-to-column c))))
24694 (defun org-drag-line-backward (arg)
24695 "Drag the line at point ARG lines backward."
24696 (interactive "p")
24697 (org-drag-line-forward (- arg)))
24699 (defun org-mark-element ()
24700 "Put point at beginning of this element, mark at end.
24702 Interactively, if this command is repeated or (in Transient Mark
24703 mode) if the mark is active, it marks the next element after the
24704 ones already marked."
24705 (interactive)
24706 (let (deactivate-mark)
24707 (if (and (called-interactively-p 'any)
24708 (or (and (eq last-command this-command) (mark t))
24709 (and transient-mark-mode mark-active)))
24710 (set-mark
24711 (save-excursion
24712 (goto-char (mark))
24713 (goto-char (org-element-property :end (org-element-at-point)))))
24714 (let ((element (org-element-at-point)))
24715 (end-of-line)
24716 (push-mark (org-element-property :end element) t t)
24717 (goto-char (org-element-property :begin element))))))
24719 (defun org-narrow-to-element ()
24720 "Narrow buffer to current element."
24721 (interactive)
24722 (let ((elem (org-element-at-point)))
24723 (cond
24724 ((eq (car elem) 'headline)
24725 (narrow-to-region
24726 (org-element-property :begin elem)
24727 (org-element-property :end elem)))
24728 ((memq (car elem) org-element-greater-elements)
24729 (narrow-to-region
24730 (org-element-property :contents-begin elem)
24731 (org-element-property :contents-end elem)))
24733 (narrow-to-region
24734 (org-element-property :begin elem)
24735 (org-element-property :end elem))))))
24737 (defun org-transpose-element ()
24738 "Transpose current and previous elements, keeping blank lines between.
24739 Point is moved after both elements."
24740 (interactive)
24741 (org-skip-whitespace)
24742 (let ((end (org-element-property :end (org-element-at-point))))
24743 (org-drag-element-backward)
24744 (goto-char end)))
24746 (defun org-unindent-buffer ()
24747 "Un-indent the visible part of the buffer.
24748 Relative indentation (between items, inside blocks, etc.) isn't
24749 modified."
24750 (interactive)
24751 (unless (eq major-mode 'org-mode)
24752 (user-error "Cannot un-indent a buffer not in Org mode"))
24753 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24754 (unindent-tree
24755 (lambda (contents)
24756 (dolist (element (reverse contents))
24757 (if (memq (org-element-type element) '(headline section))
24758 (funcall unindent-tree (org-element-contents element))
24759 (save-excursion
24760 (save-restriction
24761 (narrow-to-region
24762 (org-element-property :begin element)
24763 (org-element-property :end element))
24764 (org-do-remove-indentation))))))))
24765 (funcall unindent-tree (org-element-contents parse-tree))))
24767 (defun org-show-children (&optional level)
24768 "Show all direct subheadings of this heading.
24769 Prefix arg LEVEL is how many levels below the current level
24770 should be shown. Default is enough to cause the following
24771 heading to appear."
24772 (interactive "p")
24773 ;; If `orgstruct-mode' is active, use the slower version.
24774 (if orgstruct-mode (call-interactively #'outline-show-children)
24775 (save-excursion
24776 (org-back-to-heading t)
24777 (let* ((current-level (funcall outline-level))
24778 (max-level (org-get-valid-level
24779 current-level
24780 (if level (prefix-numeric-value level) 1)))
24781 (end (save-excursion (org-end-of-subtree t t)))
24782 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24783 (past-first-child nil)
24784 ;; Make sure to skip inlinetasks.
24785 (re (format regexp-fmt
24786 current-level
24787 (cond
24788 ((not (featurep 'org-inlinetask)) "")
24789 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24791 (t (1- org-inlinetask-min-level))))))
24792 ;; Display parent heading.
24793 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24794 (forward-line)
24795 ;; Display children. First child may be deeper than expected
24796 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24797 ;; MAX-LEVEL accordingly.
24798 (while (re-search-forward re end t)
24799 (unless past-first-child
24800 (setq re (format regexp-fmt
24801 current-level
24802 (max (funcall outline-level) max-level)))
24803 (setq past-first-child t))
24804 (outline-flag-region
24805 (line-end-position 0) (line-end-position) nil))))))
24807 (defun org-show-subtree ()
24808 "Show everything after this heading at deeper levels."
24809 (interactive)
24810 (outline-flag-region
24811 (point)
24812 (save-excursion
24813 (org-end-of-subtree t t))
24814 nil))
24816 (defun org-show-entry ()
24817 "Show the body directly following this heading.
24818 Show the heading too, if it is currently invisible."
24819 (interactive)
24820 (save-excursion
24821 (ignore-errors
24822 (org-back-to-heading t)
24823 (outline-flag-region
24824 (max (point-min) (1- (point)))
24825 (save-excursion
24826 (if (re-search-forward
24827 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24828 (match-beginning 1)
24829 (point-max)))
24830 nil)
24831 (org-cycle-hide-drawers 'children))))
24833 (defun org-make-options-regexp (kwds &optional extra)
24834 "Make a regular expression for keyword lines.
24835 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24836 when non-nil, is a regexp matching keywords names."
24837 (concat "^[ \t]*#\\+\\("
24838 (regexp-opt kwds)
24839 (and extra (concat (and kwds "\\|") extra))
24840 "\\):[ \t]*\\(.*\\)"))
24842 ;;;; Integration with and fixes for other packages
24844 ;;; Imenu support
24846 (defvar-local org-imenu-markers nil
24847 "All markers currently used by Imenu.")
24849 (defun org-imenu-new-marker (&optional pos)
24850 "Return a new marker for use by Imenu, and remember the marker."
24851 (let ((m (make-marker)))
24852 (move-marker m (or pos (point)))
24853 (push m org-imenu-markers)
24856 (defun org-imenu-get-tree ()
24857 "Produce the index for Imenu."
24858 (dolist (x org-imenu-markers) (move-marker x nil))
24859 (setq org-imenu-markers nil)
24860 (let* ((case-fold-search nil)
24861 (n org-imenu-depth)
24862 (re (concat "^" (org-get-limited-outline-regexp)))
24863 (subs (make-vector (1+ n) nil))
24864 (last-level 0)
24865 m level head0 head)
24866 (org-with-wide-buffer
24867 (goto-char (point-max))
24868 (while (re-search-backward re nil t)
24869 (setq level (org-reduced-level (funcall outline-level)))
24870 (when (and (<= level n)
24871 (looking-at org-complex-heading-regexp)
24872 (setq head0 (match-string-no-properties 4)))
24873 (setq head (org-link-display-format head0)
24874 m (org-imenu-new-marker))
24875 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24876 (if (>= level last-level)
24877 (push (cons head m) (aref subs level))
24878 (push (cons head (aref subs (1+ level))) (aref subs level))
24879 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24880 (setq last-level level))))
24881 (aref subs 1)))
24883 (eval-after-load "imenu"
24884 '(progn
24885 (add-hook 'imenu-after-jump-hook
24886 (lambda ()
24887 (when (derived-mode-p 'org-mode)
24888 (org-show-context 'org-goto))))))
24890 (defun org-link-display-format (s)
24891 "Replace links in string S with their description.
24892 If there is no description, use the link target."
24893 (save-match-data
24894 (replace-regexp-in-string
24895 org-bracket-link-analytic-regexp
24896 (lambda (m)
24897 (if (match-end 5) (match-string 5 m)
24898 (concat (match-string 1 m) (match-string 3 m))))
24899 s nil t)))
24901 (defun org-toggle-link-display ()
24902 "Toggle the literal or descriptive display of links."
24903 (interactive)
24904 (if org-descriptive-links
24905 (progn (org-remove-from-invisibility-spec '(org-link))
24906 (org-restart-font-lock)
24907 (setq org-descriptive-links nil))
24908 (progn (add-to-invisibility-spec '(org-link))
24909 (org-restart-font-lock)
24910 (setq org-descriptive-links t))))
24912 ;; Speedbar support
24914 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24915 "Overlay marking the agenda restriction line in speedbar.")
24916 (overlay-put org-speedbar-restriction-lock-overlay
24917 'face 'org-agenda-restriction-lock)
24918 (overlay-put org-speedbar-restriction-lock-overlay
24919 'help-echo "Agendas are currently limited to this item.")
24920 (delete-overlay org-speedbar-restriction-lock-overlay)
24922 (defun org-speedbar-set-agenda-restriction ()
24923 "Restrict future agenda commands to the location at point in speedbar.
24924 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24925 (interactive)
24926 (require 'org-agenda)
24927 (let (p m tp np dir txt)
24928 (cond
24929 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24930 'org-imenu t))
24931 (setq m (get-text-property p 'org-imenu-marker))
24932 (with-current-buffer (marker-buffer m)
24933 (goto-char m)
24934 (org-agenda-set-restriction-lock 'subtree)))
24935 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24936 'speedbar-function 'speedbar-find-file))
24937 (setq tp (previous-single-property-change
24938 (1+ p) 'speedbar-function)
24939 np (next-single-property-change
24940 tp 'speedbar-function)
24941 dir (speedbar-line-directory)
24942 txt (buffer-substring-no-properties (or tp (point-min))
24943 (or np (point-max))))
24944 (with-current-buffer (find-file-noselect
24945 (let ((default-directory dir))
24946 (expand-file-name txt)))
24947 (unless (derived-mode-p 'org-mode)
24948 (user-error "Cannot restrict to non-Org mode file"))
24949 (org-agenda-set-restriction-lock 'file)))
24950 (t (user-error "Don't know how to restrict Org mode agenda")))
24951 (move-overlay org-speedbar-restriction-lock-overlay
24952 (point-at-bol) (point-at-eol))
24953 (setq current-prefix-arg nil)
24954 (org-agenda-maybe-redo)))
24956 (defvar speedbar-file-key-map)
24957 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24958 (eval-after-load "speedbar"
24959 '(progn
24960 (speedbar-add-supported-extension ".org")
24961 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24962 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24963 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24964 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24965 (add-hook 'speedbar-visiting-tag-hook
24966 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24968 ;;; Fixes and Hacks for problems with other packages
24970 (defun org--flyspell-object-check-p (element)
24971 "Non-nil when Flyspell can check object at point.
24972 ELEMENT is the element at point."
24973 (let ((object (save-excursion
24974 (when (looking-at-p "\\>") (backward-char))
24975 (org-element-context element))))
24976 (cl-case (org-element-type object)
24977 ;; Prevent checks in links due to keybinding conflict with
24978 ;; Flyspell.
24979 ((code entity export-snippet inline-babel-call
24980 inline-src-block line-break latex-fragment link macro
24981 statistics-cookie target timestamp verbatim)
24982 nil)
24983 (footnote-reference
24984 ;; Only in inline footnotes, within the definition.
24985 (and (eq (org-element-property :type object) 'inline)
24986 (< (save-excursion
24987 (goto-char (org-element-property :begin object))
24988 (search-forward ":" nil t 2))
24989 (point))))
24990 (otherwise t))))
24992 (defun org-mode-flyspell-verify ()
24993 "Function used for `flyspell-generic-check-word-predicate'."
24994 (if (org-at-heading-p)
24995 ;; At a headline or an inlinetask, check title only. This is
24996 ;; faster than relying on `org-element-at-point'.
24997 (and (save-excursion (beginning-of-line)
24998 (and (let ((case-fold-search t))
24999 (not (looking-at-p "\\*+ END[ \t]*$")))
25000 (let ((case-fold-search nil))
25001 (looking-at org-complex-heading-regexp))))
25002 (match-beginning 4)
25003 (>= (point) (match-beginning 4))
25004 (or (not (match-beginning 5))
25005 (< (point) (match-beginning 5))))
25006 (let* ((element (org-element-at-point))
25007 (post-affiliated (org-element-property :post-affiliated element)))
25008 (cond
25009 ;; Ignore checks in all affiliated keywords but captions.
25010 ((< (point) post-affiliated)
25011 (and (save-excursion
25012 (beginning-of-line)
25013 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25014 (> (point) (match-end 0))
25015 (org--flyspell-object-check-p element)))
25016 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25017 ((let ((log (org-log-into-drawer)))
25018 (and log
25019 (let ((drawer (org-element-lineage element '(drawer))))
25020 (and drawer
25021 (eq (compare-strings
25022 log nil nil
25023 (org-element-property :drawer-name drawer) nil nil t)
25024 t)))))
25025 nil)
25027 (cl-case (org-element-type element)
25028 ((comment quote-section) t)
25029 (comment-block
25030 ;; Allow checks between block markers, not on them.
25031 (and (> (line-beginning-position) post-affiliated)
25032 (save-excursion
25033 (end-of-line)
25034 (skip-chars-forward " \r\t\n")
25035 (< (point) (org-element-property :end element)))))
25036 ;; Arbitrary list of keywords where checks are meaningful.
25037 ;; Make sure point is on the value part of the element.
25038 (keyword
25039 (and (member (org-element-property :key element)
25040 '("DESCRIPTION" "TITLE"))
25041 (save-excursion
25042 (search-backward ":" (line-beginning-position) t))))
25043 ;; Check is globally allowed in paragraphs verse blocks and
25044 ;; table rows (after affiliated keywords) but some objects
25045 ;; must not be affected.
25046 ((paragraph table-row verse-block)
25047 (let ((cbeg (org-element-property :contents-begin element))
25048 (cend (org-element-property :contents-end element)))
25049 (and cbeg (>= (point) cbeg) (< (point) cend)
25050 (org--flyspell-object-check-p element))))))))))
25051 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25053 (defun org-remove-flyspell-overlays-in (beg end)
25054 "Remove flyspell overlays in region."
25055 (and (bound-and-true-p flyspell-mode)
25056 (fboundp 'flyspell-delete-region-overlays)
25057 (flyspell-delete-region-overlays beg end)))
25059 (defvar flyspell-delayed-commands)
25060 (eval-after-load "flyspell"
25061 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25063 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25064 (eval-after-load "bookmark"
25065 '(if (boundp 'bookmark-after-jump-hook)
25066 ;; We can use the hook
25067 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25068 ;; Hook not available, use advice
25069 (defadvice bookmark-jump (after org-make-visible activate)
25070 "Make the position visible."
25071 (org-bookmark-jump-unhide))))
25073 ;; Make sure saveplace shows the location if it was hidden
25074 (eval-after-load "saveplace"
25075 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25076 "Make the position visible."
25077 (org-bookmark-jump-unhide)))
25079 ;; Make sure ecb shows the location if it was hidden
25080 (eval-after-load "ecb"
25081 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25082 "Make hierarchy visible when jumping into location from ECB tree buffer."
25083 (when (derived-mode-p 'org-mode)
25084 (org-show-context))))
25086 (defun org-bookmark-jump-unhide ()
25087 "Unhide the current position, to show the bookmark location."
25088 (and (derived-mode-p 'org-mode)
25089 (or (org-invisible-p)
25090 (save-excursion (goto-char (max (point-min) (1- (point))))
25091 (org-invisible-p)))
25092 (org-show-context 'bookmark-jump)))
25094 (defun org-mark-jump-unhide ()
25095 "Make the point visible with `org-show-context' after jumping to the mark."
25096 (when (and (derived-mode-p 'org-mode)
25097 (org-invisible-p))
25098 (org-show-context 'mark-goto)))
25100 (eval-after-load "simple"
25101 '(defadvice pop-to-mark-command (after org-make-visible activate)
25102 "Make the point visible with `org-show-context'."
25103 (org-mark-jump-unhide)))
25105 (eval-after-load "simple"
25106 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25107 "Make the point visible with `org-show-context'."
25108 (org-mark-jump-unhide)))
25110 (eval-after-load "simple"
25111 '(defadvice pop-global-mark (after org-make-visible activate)
25112 "Make the point visible with `org-show-context'."
25113 (org-mark-jump-unhide)))
25115 ;; Make session.el ignore our circular variable
25116 (defvar session-globals-exclude)
25117 (eval-after-load "session"
25118 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25120 ;;;; Finish up
25122 (provide 'org)
25124 (run-hooks 'org-load-hook)
25126 ;;; org.el ends here