Merge branch 'master' of git.sv.gnu.org:/srv/git/emacs
[emacs.git] / lisp / org / org.el
blob5d10eed151171b1fa179509260b40127952dd096
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-clocktable-shift "org-clock" (dir n))
132 (declare-function org-element-at-point "org-element" ())
133 (declare-function org-element-cache-refresh "org-element" (pos))
134 (declare-function org-element-cache-reset "org-element" (&optional all))
135 (declare-function org-element-contents "org-element" (element))
136 (declare-function org-element-context "org-element" (&optional element))
137 (declare-function org-element-copy "org-element" (datum))
138 (declare-function org-element-interpret-data "org-element" (data))
139 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
140 (declare-function org-element-link-parser "org-element" ())
141 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
142 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
143 (declare-function org-element-property "org-element" (property element))
144 (declare-function org-element-put-property "org-element" (element property value))
145 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
146 (declare-function org-element-type "org-element" (element))
147 (declare-function org-element-update-syntax "org-element" ())
148 (declare-function org-id-find-id-file "org-id" (id))
149 (declare-function org-id-get-create "org-id" (&optional force))
150 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
151 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
152 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
153 (declare-function org-plot/gnuplot "org-plot" (&optional params))
154 (declare-function org-table-align "org-table" ())
155 (declare-function org-table-begin "org-table" (&optional table-type))
156 (declare-function org-table-beginning-of-field "org-table" (&optional n))
157 (declare-function org-table-blank-field "org-table" ())
158 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
159 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
160 (declare-function org-table-cut-region "org-table" (beg end))
161 (declare-function org-table-edit-field "org-table" (arg))
162 (declare-function org-table-end "org-table" (&optional table-type))
163 (declare-function org-table-end-of-field "org-table" (&optional n))
164 (declare-function org-table-insert-row "org-table" (&optional arg))
165 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
166 (declare-function org-table-maybe-eval-formula "org-table" ())
167 (declare-function org-table-maybe-recalculate-line "org-table" ())
168 (declare-function org-table-next-row "org-table" ())
169 (declare-function org-table-paste-rectangle "org-table" ())
170 (declare-function org-table-recalculate "org-table" (&optional all noalign))
171 (declare-function org-table-wrap-region "org-table" (arg))
172 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
173 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
174 (declare-function orgtbl-mode "org-table" (&optional arg))
175 (declare-function org-export-get-backend "ox" (name))
176 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
177 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
179 (defsubst org-uniquify (list)
180 "Non-destructively remove duplicate elements from LIST."
181 (let ((res (copy-sequence list))) (delete-dups res)))
183 (defsubst org-get-at-bol (property)
184 "Get text property PROPERTY at the beginning of line."
185 (get-text-property (point-at-bol) property))
187 (defsubst org-trim (s &optional keep-lead)
188 "Remove whitespace at the beginning and the end of string S.
189 When optional argument KEEP-LEAD is non-nil, removing blank lines
190 at the beginning of the string does not affect leading indentation."
191 (replace-regexp-in-string
192 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
193 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
195 ;; load languages based on value of `org-babel-load-languages'
196 (defvar org-babel-load-languages)
198 ;;;###autoload
199 (defun org-babel-do-load-languages (sym value)
200 "Load the languages defined in `org-babel-load-languages'."
201 (set-default sym value)
202 (dolist (pair org-babel-load-languages)
203 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
204 (if active
205 (require (intern (concat "ob-" lang)))
206 (funcall 'fmakunbound
207 (intern (concat "org-babel-execute:" lang)))
208 (funcall 'fmakunbound
209 (intern (concat "org-babel-expand-body:" lang)))))))
211 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
212 ;;;###autoload
213 (defun org-babel-load-file (file &optional compile)
214 "Load Emacs Lisp source code blocks in the Org FILE.
215 This function exports the source code using `org-babel-tangle'
216 and then loads the resulting file using `load-file'. With prefix
217 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
218 file to byte-code before it is loaded."
219 (interactive "fFile to load: \nP")
220 (let* ((age (lambda (file)
221 (float-time
222 (time-subtract (current-time)
223 (nth 5 (or (file-attributes (file-truename file))
224 (file-attributes file)))))))
225 (base-name (file-name-sans-extension file))
226 (exported-file (concat base-name ".el")))
227 ;; tangle if the Org file is newer than the elisp file
228 (unless (and (file-exists-p exported-file)
229 (> (funcall age file) (funcall age exported-file)))
230 ;; Tangle-file traversal returns reversed list of tangled files
231 ;; and we want to evaluate the first target.
232 (setq exported-file
233 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
234 (message "%s %s"
235 (if compile
236 (progn (byte-compile-file exported-file 'load)
237 "Compiled and loaded")
238 (progn (load-file exported-file) "Loaded"))
239 exported-file)))
241 (defcustom org-babel-load-languages '((emacs-lisp . t))
242 "Languages which can be evaluated in Org buffers.
243 This list can be used to load support for any of the languages
244 below, note that each language will depend on a different set of
245 system executables and/or Emacs modes. When a language is
246 \"loaded\", then code blocks in that language can be evaluated
247 with `org-babel-execute-src-block' bound by default to C-c
248 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
249 be set to remove code block evaluation from the C-c C-c
250 keybinding. By default only Emacs Lisp (which has no
251 requirements) is loaded."
252 :group 'org-babel
253 :set 'org-babel-do-load-languages
254 :version "24.1"
255 :type '(alist :tag "Babel Languages"
256 :key-type
257 (choice
258 (const :tag "Awk" awk)
259 (const :tag "C" C)
260 (const :tag "R" R)
261 (const :tag "Asymptote" asymptote)
262 (const :tag "Calc" calc)
263 (const :tag "Clojure" clojure)
264 (const :tag "CSS" css)
265 (const :tag "Ditaa" ditaa)
266 (const :tag "Dot" dot)
267 (const :tag "Emacs Lisp" emacs-lisp)
268 (const :tag "Forth" forth)
269 (const :tag "Fortran" fortran)
270 (const :tag "Gnuplot" gnuplot)
271 (const :tag "Haskell" haskell)
272 (const :tag "IO" io)
273 (const :tag "J" J)
274 (const :tag "Java" java)
275 (const :tag "Javascript" js)
276 (const :tag "LaTeX" latex)
277 (const :tag "Ledger" ledger)
278 (const :tag "Lilypond" lilypond)
279 (const :tag "Lisp" lisp)
280 (const :tag "Makefile" makefile)
281 (const :tag "Maxima" maxima)
282 (const :tag "Matlab" matlab)
283 (const :tag "Mscgen" mscgen)
284 (const :tag "Ocaml" ocaml)
285 (const :tag "Octave" octave)
286 (const :tag "Org" org)
287 (const :tag "Perl" perl)
288 (const :tag "Pico Lisp" picolisp)
289 (const :tag "PlantUML" plantuml)
290 (const :tag "Python" python)
291 (const :tag "Ruby" ruby)
292 (const :tag "Sass" sass)
293 (const :tag "Scala" scala)
294 (const :tag "Scheme" scheme)
295 (const :tag "Screen" screen)
296 (const :tag "Shell Script" shell)
297 (const :tag "Shen" shen)
298 (const :tag "Sql" sql)
299 (const :tag "Sqlite" sqlite)
300 (const :tag "Stan" stan)
301 (const :tag "ebnf2ps" ebnf2ps))
302 :value-type (boolean :tag "Activate" :value t)))
304 ;;;; Customization variables
305 (defcustom org-clone-delete-id nil
306 "Remove ID property of clones of a subtree.
307 When non-nil, clones of a subtree don't inherit the ID property.
308 Otherwise they inherit the ID property with a new unique
309 identifier."
310 :type 'boolean
311 :version "24.1"
312 :group 'org-id)
314 ;;; Version
315 (org-check-version)
317 ;;;###autoload
318 (defun org-version (&optional here full message)
319 "Show the Org version.
320 Interactively, or when MESSAGE is non-nil, show it in echo area.
321 With prefix argument, or when HERE is non-nil, insert it at point.
322 In non-interactive uses, a reduced version string is output unless
323 FULL is given."
324 (interactive (list current-prefix-arg t (not current-prefix-arg)))
325 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
326 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
327 (load-suffixes (list ".el"))
328 (org-install-dir
329 (ignore-errors (org-find-library-dir "org-loaddefs"))))
330 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
331 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
332 (let* ((load-suffixes save-load-suffixes)
333 (release (org-release))
334 (git-version (org-git-version))
335 (version (format "Org mode version %s (%s @ %s)"
336 release
337 git-version
338 (if org-install-dir
339 (if (string= org-dir org-install-dir)
340 org-install-dir
341 (concat "mixed installation! "
342 org-install-dir
343 " and "
344 org-dir))
345 "org-loaddefs.el can not be found!")))
346 (version1 (if full version release)))
347 (when here (insert version1))
348 (when message (message "%s" version1))
349 version1)))
351 (defconst org-version (org-version))
354 ;;; Syntax Constants
356 ;;;; Block
358 (defconst org-block-regexp
359 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
360 "Regular expression for hiding blocks.")
362 (defconst org-dblock-start-re
363 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
364 "Matches the start line of a dynamic block, with parameters.")
366 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
367 "Matches the end of a dynamic block.")
369 ;;;; Clock and Planning
371 (defconst org-clock-string "CLOCK:"
372 "String used as prefix for timestamps clocking work hours on an item.")
374 (defvar org-closed-string "CLOSED:"
375 "String used as the prefix for timestamps logging closing a TODO entry.")
377 (defvar org-deadline-string "DEADLINE:"
378 "String to mark deadline entries.
379 \\<org-mode-map>
380 A deadline is this string, followed by a time stamp. It must be
381 a word, terminated by a colon. You can insert a schedule keyword
382 and a timestamp with `\\[org-deadline]'.")
384 (defvar org-scheduled-string "SCHEDULED:"
385 "String to mark scheduled TODO entries.
386 \\<org-mode-map>
387 A schedule is this string, followed by a time stamp. It must be
388 a word, terminated by a colon. You can insert a schedule keyword
389 and a timestamp with `\\[org-schedule]'.")
391 (defconst org-ds-keyword-length
392 (+ 2
393 (apply #'max
394 (mapcar #'length
395 (list org-deadline-string org-scheduled-string
396 org-clock-string org-closed-string))))
397 "Maximum length of the DEADLINE and SCHEDULED keywords.")
399 (defconst org-planning-line-re
400 (concat "^[ \t]*"
401 (regexp-opt
402 (list org-closed-string org-deadline-string org-scheduled-string)
404 "Matches a line with planning info.
405 Matched keyword is in group 1.")
407 (defconst org-clock-line-re
408 (concat "^[ \t]*" org-clock-string)
409 "Matches a line with clock info.")
411 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
412 "Matches the DEADLINE keyword.")
414 (defconst org-deadline-time-regexp
415 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
416 "Matches the DEADLINE keyword together with a time stamp.")
418 (defconst org-deadline-time-hour-regexp
419 (concat "\\<" org-deadline-string
420 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
421 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
423 (defconst org-deadline-line-regexp
424 (concat "\\<\\(" org-deadline-string "\\).*")
425 "Matches the DEADLINE keyword and the rest of the line.")
427 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
428 "Matches the SCHEDULED keyword.")
430 (defconst org-scheduled-time-regexp
431 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
432 "Matches the SCHEDULED keyword together with a time stamp.")
434 (defconst org-scheduled-time-hour-regexp
435 (concat "\\<" org-scheduled-string
436 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
437 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
439 (defconst org-closed-time-regexp
440 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
441 "Matches the CLOSED keyword together with a time stamp.")
443 (defconst org-keyword-time-regexp
444 (concat "\\<"
445 (regexp-opt
446 (list org-scheduled-string org-deadline-string org-closed-string
447 org-clock-string)
449 " *[[<]\\([^]>]+\\)[]>]")
450 "Matches any of the 4 keywords, together with the time stamp.")
452 (defconst org-keyword-time-not-clock-regexp
453 (concat
454 "\\<"
455 (regexp-opt
456 (list org-scheduled-string org-deadline-string org-closed-string) t)
457 " *[[<]\\([^]>]+\\)[]>]")
458 "Matches any of the 3 keywords, together with the time stamp.")
460 (defconst org-maybe-keyword-time-regexp
461 (concat "\\(\\<"
462 (regexp-opt
463 (list org-scheduled-string org-deadline-string org-closed-string
464 org-clock-string)
466 "\\)?"
467 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
468 "\\|"
469 "<%%([^\r\n>]*>\\)")
470 "Matches a timestamp, possibly preceded by a keyword.")
472 (defconst org-all-time-keywords
473 (mapcar (lambda (w) (substring w 0 -1))
474 (list org-scheduled-string org-deadline-string
475 org-clock-string org-closed-string))
476 "List of time keywords.")
478 ;;;; Drawer
480 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
481 "Matches first or last line of a hidden block.
482 Group 1 contains drawer's name or \"END\".")
484 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
485 "Regular expression matching the first line of a property drawer.")
487 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
488 "Regular expression matching the last line of a property drawer.")
490 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
491 "Regular expression matching the first line of a clock drawer.")
493 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
494 "Regular expression matching the last line of a clock drawer.")
496 (defconst org-property-drawer-re
497 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
498 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
499 "[ \t]*:END:[ \t]*$")
500 "Matches an entire property drawer.")
502 (defconst org-clock-drawer-re
503 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
504 org-clock-drawer-end-re "\\)\n?")
505 "Matches an entire clock drawer.")
507 ;;;; Headline
509 (defconst org-heading-keyword-regexp-format
510 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
511 "Printf format for a regexp matching a headline with some keyword.
512 This regexp will match the headline of any node which has the
513 exact keyword that is put into the format. The keyword isn't in
514 any group by default, but the stars and the body are.")
516 (defconst org-heading-keyword-maybe-regexp-format
517 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
518 "Printf format for a regexp matching a headline, possibly with some keyword.
519 This regexp can match any headline with the specified keyword, or
520 without a keyword. The keyword isn't in any group by default,
521 but the stars and the body are.")
523 (defconst org-archive-tag "ARCHIVE"
524 "The tag that marks a subtree as archived.
525 An archived subtree does not open during visibility cycling, and does
526 not contribute to the agenda listings.")
528 (defconst org-comment-string "COMMENT"
529 "Entries starting with this keyword will never be exported.
530 \\<org-mode-map>
531 An entry can be toggled between COMMENT and normal with
532 `\\[org-toggle-comment]'.")
535 ;;;; LaTeX Environments and Fragments
537 (defconst org-latex-regexps
538 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
539 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
540 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
541 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
542 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
543 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
544 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
545 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
546 "Regular expressions for matching embedded LaTeX.")
548 ;;;; Node Property
550 (defconst org-effort-property "Effort"
551 "The property that is being used to keep track of effort estimates.
552 Effort estimates given in this property need to have the format H:MM.")
554 ;;;; Table
556 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
557 "Detect an org-type or table-type table.")
559 (defconst org-table-line-regexp "^[ \t]*|"
560 "Detect an org-type table line.")
562 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
563 "Detect an org-type table line.")
565 (defconst org-table-hline-regexp "^[ \t]*|-"
566 "Detect an org-type table hline.")
568 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
569 "Detect a table-type table hline.")
571 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
572 "Detect the first line outside a table when searching from within it.
573 This works for both table types.")
575 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
576 "Detect a #+TBLFM line.")
578 ;;;; Timestamp
580 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
581 "Regular expression for fast time stamp matching.")
583 (defconst org-ts-regexp-inactive
584 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
585 "Regular expression for fast inactive time stamp matching.")
587 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
588 "Regular expression for fast time stamp matching.")
590 (defconst org-ts-regexp0
591 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
592 "Regular expression matching time strings for analysis.
593 This one does not require the space after the date, so it can be used
594 on a string that terminates immediately after the date.")
596 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
597 "Regular expression matching time strings for analysis.")
599 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
600 "Regular expression matching time stamps, with groups.")
602 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
603 "Regular expression matching time stamps (also [..]), with groups.")
605 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
606 "Regular expression matching a time stamp range.")
608 (defconst org-tr-regexp-both
609 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
610 "Regular expression matching a time stamp range.")
612 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
613 org-ts-regexp "\\)?")
614 "Regular expression matching a time stamp or time stamp range.")
616 (defconst org-tsr-regexp-both
617 (concat org-ts-regexp-both "\\(--?-?"
618 org-ts-regexp-both "\\)?")
619 "Regular expression matching a time stamp or time stamp range.
620 The time stamps may be either active or inactive.")
622 (defconst org-repeat-re
623 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
624 "Regular expression for specifying repeated events.
625 After a match, group 1 contains the repeat expression.")
627 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
628 "Formats for `format-time-string' which are used for time stamps.")
631 ;;; The custom variables
633 (defgroup org nil
634 "Outline-based notes management and organizer."
635 :tag "Org"
636 :group 'outlines
637 :group 'calendar)
639 (defcustom org-mode-hook nil
640 "Mode hook for Org mode, run after the mode was turned on."
641 :group 'org
642 :type 'hook)
644 (defcustom org-load-hook nil
645 "Hook that is run after org.el has been loaded."
646 :group 'org
647 :type 'hook)
649 (defcustom org-log-buffer-setup-hook nil
650 "Hook that is run after an Org log buffer is created."
651 :group 'org
652 :version "24.1"
653 :type 'hook)
655 (defvar org-modules) ; defined below
656 (defvar org-modules-loaded nil
657 "Have the modules been loaded already?")
659 (defun org-load-modules-maybe (&optional force)
660 "Load all extensions listed in `org-modules'."
661 (when (or force (not org-modules-loaded))
662 (dolist (ext org-modules)
663 (condition-case nil (require ext)
664 (error (message "Problems while trying to load feature `%s'" ext))))
665 (setq org-modules-loaded t)))
667 (defun org-set-modules (var value)
668 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
669 (set var value)
670 (when (featurep 'org)
671 (org-load-modules-maybe 'force)
672 (org-element-cache-reset 'all)))
674 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
675 "Modules that should always be loaded together with org.el.
677 If a description starts with <C>, the file is not part of Emacs
678 and loading it will require that you have downloaded and properly
679 installed the Org mode distribution.
681 You can also use this system to load external packages (i.e. neither Org
682 core modules, nor modules from the CONTRIB directory). Just add symbols
683 to the end of the list. If the package is called org-xyz.el, then you need
684 to add the symbol `xyz', and the package must have a call to:
686 (provide \\='org-xyz)
688 For export specific modules, see also `org-export-backends'."
689 :group 'org
690 :set 'org-set-modules
691 :version "24.4"
692 :package-version '(Org . "8.0")
693 :type
694 '(set :greedy t
695 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
696 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
697 (const :tag " crypt: Encryption of subtrees" org-crypt)
698 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
699 (const :tag " docview: Links to doc-view buffers" org-docview)
700 (const :tag " eww: Store link to url of eww" org-eww)
701 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
702 (const :tag " habit: Track your consistency with habits" org-habit)
703 (const :tag " id: Global IDs for identifying entries" org-id)
704 (const :tag " info: Links to Info nodes" org-info)
705 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
706 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
707 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
708 (const :tag " mouse: Additional mouse support" org-mouse)
709 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
710 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
711 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
713 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
714 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
715 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
716 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
717 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
718 (const :tag "C collector: Collect properties into tables" org-collector)
719 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
720 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
721 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
722 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
723 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
724 (const :tag "C eval: Include command output as text" org-eval)
725 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
726 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
727 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
728 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
729 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
730 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
731 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
732 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
733 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
734 (const :tag "C man: Support for links to manpages in Org mode" org-man)
735 (const :tag "C mew: Links to Mew folders/messages" org-mew)
736 (const :tag "C mtags: Support for muse-like tags" org-mtags)
737 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
738 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
739 (const :tag "C registry: A registry for Org links" org-registry)
740 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
741 (const :tag "C secretary: Team management with org-mode" org-secretary)
742 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
743 (const :tag "C toc: Table of contents for Org buffer" org-toc)
744 (const :tag "C track: Keep up with Org mode development" org-track)
745 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
746 (const :tag "C vm: Links to VM folders/messages" org-vm)
747 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
748 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
749 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
751 (defvar org-export-registered-backends) ; From ox.el.
752 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
753 (declare-function org-export-backend-name "ox" (backend) t)
754 (defcustom org-export-backends '(ascii html icalendar latex odt)
755 "List of export back-ends that should be always available.
757 If a description starts with <C>, the file is not part of Emacs
758 and loading it will require that you have downloaded and properly
759 installed the Org mode distribution.
761 Unlike to `org-modules', libraries in this list will not be
762 loaded along with Org, but only once the export framework is
763 needed.
765 This variable needs to be set before org.el is loaded. If you
766 need to make a change while Emacs is running, use the customize
767 interface or run the following code, where VAL stands for the new
768 value of the variable, after updating it:
770 (progn
771 (setq org-export-registered-backends
772 (cl-remove-if-not
773 (lambda (backend)
774 (let ((name (org-export-backend-name backend)))
775 (or (memq name val)
776 (catch \\='parentp
777 (dolist (b val)
778 (and (org-export-derived-backend-p b name)
779 (throw \\='parentp t)))))))
780 org-export-registered-backends))
781 (let ((new-list (mapcar #\\='org-export-backend-name
782 org-export-registered-backends)))
783 (dolist (backend val)
784 (cond
785 ((not (load (format \"ox-%s\" backend) t t))
786 (message \"Problems while trying to load export back-end \\=`%s\\='\"
787 backend))
788 ((not (memq backend new-list)) (push backend new-list))))
789 (set-default \\='org-export-backends new-list)))
791 Adding a back-end to this list will also pull the back-end it
792 depends on, if any."
793 :group 'org
794 :group 'org-export
795 :version "26.1"
796 :package-version '(Org . "9.0")
797 :initialize 'custom-initialize-set
798 :set (lambda (var val)
799 (if (not (featurep 'ox)) (set-default var val)
800 ;; Any back-end not required anymore (not present in VAL and not
801 ;; a parent of any back-end in the new value) is removed from the
802 ;; list of registered back-ends.
803 (setq org-export-registered-backends
804 (cl-remove-if-not
805 (lambda (backend)
806 (let ((name (org-export-backend-name backend)))
807 (or (memq name val)
808 (catch 'parentp
809 (dolist (b val)
810 (and (org-export-derived-backend-p b name)
811 (throw 'parentp t)))))))
812 org-export-registered-backends))
813 ;; Now build NEW-LIST of both new back-ends and required
814 ;; parents.
815 (let ((new-list (mapcar #'org-export-backend-name
816 org-export-registered-backends)))
817 (dolist (backend val)
818 (cond
819 ((not (load (format "ox-%s" backend) t t))
820 (message "Problems while trying to load export back-end `%s'"
821 backend))
822 ((not (memq backend new-list)) (push backend new-list))))
823 ;; Set VAR to that list with fixed dependencies.
824 (set-default var new-list))))
825 :type '(set :greedy t
826 (const :tag " ascii Export buffer to ASCII format" ascii)
827 (const :tag " beamer Export buffer to Beamer presentation" beamer)
828 (const :tag " html Export buffer to HTML format" html)
829 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
830 (const :tag " latex Export buffer to LaTeX format" latex)
831 (const :tag " man Export buffer to MAN format" man)
832 (const :tag " md Export buffer to Markdown format" md)
833 (const :tag " odt Export buffer to ODT format" odt)
834 (const :tag " org Export buffer to Org format" org)
835 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
836 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
837 (const :tag "C deck Export buffer to deck.js presentations" deck)
838 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
839 (const :tag "C groff Export buffer to Groff format" groff)
840 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
841 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
842 (const :tag "C s5 Export buffer to s5 presentations" s5)
843 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
845 (eval-after-load 'ox
846 '(dolist (backend org-export-backends)
847 (condition-case nil (require (intern (format "ox-%s" backend)))
848 (error (message "Problems while trying to load export back-end `%s'"
849 backend)))))
851 (defcustom org-support-shift-select nil
852 "Non-nil means make shift-cursor commands select text when possible.
853 \\<org-mode-map>\
855 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
856 start selecting a region, or enlarge regions started in this way.
857 In Org mode, in special contexts, these same keys are used for
858 other purposes, important enough to compete with shift selection.
859 Org tries to balance these needs by supporting `shift-select-mode'
860 outside these special contexts, under control of this variable.
862 The default of this variable is nil, to avoid confusing behavior. Shifted
863 cursor keys will then execute Org commands in the following contexts:
864 - on a headline, changing TODO state (left/right) and priority (up/down)
865 - on a time stamp, changing the time
866 - in a plain list item, changing the bullet type
867 - in a property definition line, switching between allowed values
868 - in the BEGIN line of a clock table (changing the time block).
869 Outside these contexts, the commands will throw an error.
871 When this variable is t and the cursor is not in a special
872 context, Org mode will support shift-selection for making and
873 enlarging regions. To make this more effective, the bullet
874 cycling will no longer happen anywhere in an item line, but only
875 if the cursor is exactly on the bullet.
877 If you set this variable to the symbol `always', then the keys
878 will not be special in headlines, property lines, and item lines,
879 to make shift selection work there as well. If this is what you
880 want, you can use the following alternative commands:
881 `\\[org-todo]' and `\\[org-priority]' \
882 to change TODO state and priority,
883 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
884 can be used to switch TODO sets,
885 `\\[org-ctrl-c-minus]' to cycle item bullet types,
886 and properties can be edited by hand or in column view.
888 However, when the cursor is on a timestamp, shift-cursor commands
889 will still edit the time stamp - this is just too good to give up."
890 :group 'org
891 :type '(choice
892 (const :tag "Never" nil)
893 (const :tag "When outside special context" t)
894 (const :tag "Everywhere except timestamps" always)))
896 (defcustom org-loop-over-headlines-in-active-region nil
897 "Shall some commands act upon headlines in the active region?
899 When set to t, some commands will be performed in all headlines
900 within the active region.
902 When set to `start-level', some commands will be performed in all
903 headlines within the active region, provided that these headlines
904 are of the same level than the first one.
906 When set to a string, those commands will be performed on the
907 matching headlines within the active region. Such string must be
908 a tags/property/todo match as it is used in the agenda tags view.
910 The list of commands is: `org-schedule', `org-deadline',
911 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
912 `org-archive-to-archive-sibling'. The archiving commands skip
913 already archived entries."
914 :type '(choice (const :tag "Don't loop" nil)
915 (const :tag "All headlines in active region" t)
916 (const :tag "In active region, headlines at the same level than the first one" start-level)
917 (string :tag "Tags/Property/Todo matcher"))
918 :version "24.1"
919 :group 'org-todo
920 :group 'org-archive)
922 (defgroup org-startup nil
923 "Options concerning startup of Org mode."
924 :tag "Org Startup"
925 :group 'org)
927 (defcustom org-startup-folded t
928 "Non-nil means entering Org mode will switch to OVERVIEW.
930 This can also be configured on a per-file basis by adding one of
931 the following lines anywhere in the buffer:
933 #+STARTUP: fold (or `overview', this is equivalent)
934 #+STARTUP: nofold (or `showall', this is equivalent)
935 #+STARTUP: content
936 #+STARTUP: showeverything
938 Set `org-agenda-inhibit-startup' to a non-nil value if you want
939 to ignore this option when Org opens agenda files for the first
940 time."
941 :group 'org-startup
942 :type '(choice
943 (const :tag "nofold: show all" nil)
944 (const :tag "fold: overview" t)
945 (const :tag "content: all headlines" content)
946 (const :tag "show everything, even drawers" showeverything)))
948 (defcustom org-startup-truncated t
949 "Non-nil means entering Org mode will set `truncate-lines'.
950 This is useful since some lines containing links can be very long and
951 uninteresting. Also tables look terrible when wrapped.
953 The variable `org-startup-truncated' allows to configure
954 truncation for Org mode different to the other modes that use the
955 variable `truncate-lines' and as a shortcut instead of putting
956 the variable `truncate-lines' into the `org-mode-hook'. If one
957 wants to configure truncation for Org mode not statically but
958 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
959 the variable `truncate-lines' has to be used because in such a
960 case it is too late to set the variable `org-startup-truncated'."
961 :group 'org-startup
962 :type 'boolean)
964 (defcustom org-startup-indented nil
965 "Non-nil means turn on `org-indent-mode' on startup.
966 This can also be configured on a per-file basis by adding one of
967 the following lines anywhere in the buffer:
969 #+STARTUP: indent
970 #+STARTUP: noindent"
971 :group 'org-structure
972 :type '(choice
973 (const :tag "Not" nil)
974 (const :tag "Globally (slow on startup in large files)" t)))
976 (defcustom org-use-sub-superscripts t
977 "Non-nil means interpret \"_\" and \"^\" for display.
979 If you want to control how Org exports those characters, see
980 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
981 used to be an alias for `org-export-with-sub-superscripts' in
982 Org <8.0, it is not anymore.
984 When this option is turned on, you can use TeX-like syntax for
985 sub- and superscripts within the buffer. Several characters after
986 \"_\" or \"^\" will be considered as a single item - so grouping
987 with {} is normally not needed. For example, the following things
988 will be parsed as single sub- or superscripts:
990 10^24 or 10^tau several digits will be considered 1 item.
991 10^-12 or 10^-tau a leading sign with digits or a word
992 x^2-y^3 will be read as x^2 - y^3, because items are
993 terminated by almost any nonword/nondigit char.
994 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
996 Still, ambiguity is possible. So when in doubt, use {} to enclose
997 the sub/superscript. If you set this variable to the symbol `{}',
998 the braces are *required* in order to trigger interpretations as
999 sub/superscript. This can be helpful in documents that need \"_\"
1000 frequently in plain text."
1001 :group 'org-startup
1002 :version "24.4"
1003 :package-version '(Org . "8.0")
1004 :type '(choice
1005 (const :tag "Always interpret" t)
1006 (const :tag "Only with braces" {})
1007 (const :tag "Never interpret" nil)))
1009 (defcustom org-startup-with-beamer-mode nil
1010 "Non-nil means turn on `org-beamer-mode' on startup.
1011 This can also be configured on a per-file basis by adding one of
1012 the following lines anywhere in the buffer:
1014 #+STARTUP: beamer"
1015 :group 'org-startup
1016 :version "24.1"
1017 :type 'boolean)
1019 (defcustom org-startup-align-all-tables nil
1020 "Non-nil means align all tables when visiting a file.
1021 This is useful when the column width in tables is forced with <N> cookies
1022 in table fields. Such tables will look correct only after the first re-align.
1023 This can also be configured on a per-file basis by adding one of
1024 the following lines anywhere in the buffer:
1025 #+STARTUP: align
1026 #+STARTUP: noalign"
1027 :group 'org-startup
1028 :type 'boolean)
1030 (defcustom org-startup-with-inline-images nil
1031 "Non-nil means show inline images when loading a new Org file.
1032 This can also be configured on a per-file basis by adding one of
1033 the following lines anywhere in the buffer:
1034 #+STARTUP: inlineimages
1035 #+STARTUP: noinlineimages"
1036 :group 'org-startup
1037 :version "24.1"
1038 :type 'boolean)
1040 (defcustom org-startup-with-latex-preview nil
1041 "Non-nil means preview LaTeX fragments when loading a new Org file.
1043 This can also be configured on a per-file basis by adding one of
1044 the following lines anywhere in the buffer:
1045 #+STARTUP: latexpreview
1046 #+STARTUP: nolatexpreview"
1047 :group 'org-startup
1048 :version "24.4"
1049 :package-version '(Org . "8.0")
1050 :type 'boolean)
1052 (defcustom org-insert-mode-line-in-empty-file nil
1053 "Non-nil means insert the first line setting Org mode in empty files.
1054 When the function `org-mode' is called interactively in an empty file, this
1055 normally means that the file name does not automatically trigger Org mode.
1056 To ensure that the file will always be in Org mode in the future, a
1057 line enforcing Org mode will be inserted into the buffer, if this option
1058 has been set."
1059 :group 'org-startup
1060 :type 'boolean)
1062 (defcustom org-replace-disputed-keys nil
1063 "Non-nil means use alternative key bindings for some keys.
1064 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1065 These keys are also used by other packages like shift-selection-mode'
1066 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1067 If you want to use Org mode together with one of these other modes,
1068 or more generally if you would like to move some Org mode commands to
1069 other keys, set this variable and configure the keys with the variable
1070 `org-disputed-keys'.
1072 This option is only relevant at load-time of Org mode, and must be set
1073 *before* org.el is loaded. Changing it requires a restart of Emacs to
1074 become effective."
1075 :group 'org-startup
1076 :type 'boolean)
1078 (defcustom org-use-extra-keys nil
1079 "Non-nil means use extra key sequence definitions for certain commands.
1080 This happens automatically if `window-system' is nil. This
1081 variable lets you do the same manually. You must set it before
1082 loading Org."
1083 :group 'org-startup
1084 :type 'boolean)
1086 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1088 (defcustom org-disputed-keys
1089 '(([(shift up)] . [(meta p)])
1090 ([(shift down)] . [(meta n)])
1091 ([(shift left)] . [(meta -)])
1092 ([(shift right)] . [(meta +)])
1093 ([(control shift right)] . [(meta shift +)])
1094 ([(control shift left)] . [(meta shift -)]))
1095 "Keys for which Org mode and other modes compete.
1096 This is an alist, cars are the default keys, second element specifies
1097 the alternative to use when `org-replace-disputed-keys' is t.
1099 Keys can be specified in any syntax supported by `define-key'.
1100 The value of this option takes effect only at Org mode startup,
1101 therefore you'll have to restart Emacs to apply it after changing."
1102 :group 'org-startup
1103 :type 'alist)
1105 (defun org-key (key)
1106 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1107 Or return the original if not disputed."
1108 (when org-replace-disputed-keys
1109 (let* ((nkey (key-description key))
1110 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1111 org-disputed-keys)))
1112 (setq key (if x (cdr x) key))))
1113 key)
1115 (defun org-defkey (keymap key def)
1116 "Define a key, possibly translated, as returned by `org-key'."
1117 (define-key keymap (org-key key) def))
1119 (defcustom org-ellipsis nil
1120 "The ellipsis to use in the Org mode outline.
1122 When nil, just use the standard three dots.
1123 When a string, use that string instead.
1125 The change affects only Org mode (which will then use its own display table).
1126 Changing this requires executing `\\[org-mode]' in a buffer to become
1127 effective."
1128 :group 'org-startup
1129 :type '(choice (const :tag "Default" nil)
1130 (string :tag "String" :value "...#"))
1131 :safe #'string-or-null-p)
1133 (defvar org-display-table nil
1134 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1136 (defgroup org-keywords nil
1137 "Keywords in Org mode."
1138 :tag "Org Keywords"
1139 :group 'org)
1141 (defcustom org-closed-keep-when-no-todo nil
1142 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1143 :group 'org-todo
1144 :group 'org-keywords
1145 :version "24.4"
1146 :package-version '(Org . "8.0")
1147 :type 'boolean)
1149 (defgroup org-structure nil
1150 "Options concerning the general structure of Org files."
1151 :tag "Org Structure"
1152 :group 'org)
1154 (defgroup org-reveal-location nil
1155 "Options about how to make context of a location visible."
1156 :tag "Org Reveal Location"
1157 :group 'org-structure)
1159 (defcustom org-show-context-detail '((agenda . local)
1160 (bookmark-jump . lineage)
1161 (isearch . lineage)
1162 (default . ancestors))
1163 "Alist between context and visibility span when revealing a location.
1165 \\<org-mode-map>Some actions may move point into invisible
1166 locations. As a consequence, Org always expose a neighborhood
1167 around point. How much is shown depends on the initial action,
1168 or context. Valid contexts are
1170 agenda when exposing an entry from the agenda
1171 org-goto when using the command `org-goto' (`\\[org-goto]')
1172 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1173 tags-tree when constructing a sparse tree based on tags matches
1174 link-search when exposing search matches associated with a link
1175 mark-goto when exposing the jump goal of a mark
1176 bookmark-jump when exposing a bookmark location
1177 isearch when exiting from an incremental search
1178 default default for all contexts not set explicitly
1180 Allowed visibility spans are
1182 minimal show current headline; if point is not on headline,
1183 also show entry
1185 local show current headline, entry and next headline
1187 ancestors show current headline and its direct ancestors; if
1188 point is not on headline, also show entry
1190 lineage show current headline, its direct ancestors and all
1191 their children; if point is not on headline, also show
1192 entry and first child
1194 tree show current headline, its direct ancestors and all
1195 their children; if point is not on headline, also show
1196 entry and all children
1198 canonical show current headline, its direct ancestors along with
1199 their entries and children; if point is not located on
1200 the headline, also show current entry and all children
1202 As special cases, a nil or t value means show all contexts in
1203 `minimal' or `canonical' view, respectively.
1205 Some views can make displayed information very compact, but also
1206 make it harder to edit the location of the match. In such
1207 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1208 more context."
1209 :group 'org-reveal-location
1210 :version "26.1"
1211 :package-version '(Org . "9.0")
1212 :type '(choice
1213 (const :tag "Canonical" t)
1214 (const :tag "Minimal" nil)
1215 (repeat :greedy t :tag "Individual contexts"
1216 (cons
1217 (choice :tag "Context"
1218 (const agenda)
1219 (const org-goto)
1220 (const occur-tree)
1221 (const tags-tree)
1222 (const link-search)
1223 (const mark-goto)
1224 (const bookmark-jump)
1225 (const isearch)
1226 (const default))
1227 (choice :tag "Detail level"
1228 (const minimal)
1229 (const local)
1230 (const ancestors)
1231 (const lineage)
1232 (const tree)
1233 (const canonical))))))
1235 (defcustom org-indirect-buffer-display 'other-window
1236 "How should indirect tree buffers be displayed?
1238 This applies to indirect buffers created with the commands
1239 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1241 Valid values are:
1242 current-window Display in the current window
1243 other-window Just display in another window.
1244 dedicated-frame Create one new frame, and re-use it each time.
1245 new-frame Make a new frame each time. Note that in this case
1246 previously-made indirect buffers are kept, and you need to
1247 kill these buffers yourself."
1248 :group 'org-structure
1249 :group 'org-agenda-windows
1250 :type '(choice
1251 (const :tag "In current window" current-window)
1252 (const :tag "In current frame, other window" other-window)
1253 (const :tag "Each time a new frame" new-frame)
1254 (const :tag "One dedicated frame" dedicated-frame)))
1256 (defcustom org-use-speed-commands nil
1257 "Non-nil means activate single letter commands at beginning of a headline.
1258 This may also be a function to test for appropriate locations where speed
1259 commands should be active.
1261 For example, to activate speed commands when the point is on any
1262 star at the beginning of the headline, you can do this:
1264 (setq org-use-speed-commands
1265 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1266 :group 'org-structure
1267 :type '(choice
1268 (const :tag "Never" nil)
1269 (const :tag "At beginning of headline stars" t)
1270 (function)))
1272 (defcustom org-speed-commands-user nil
1273 "Alist of additional speed commands.
1274 This list will be checked before `org-speed-commands-default'
1275 when the variable `org-use-speed-commands' is non-nil
1276 and when the cursor is at the beginning of a headline.
1277 The car if each entry is a string with a single letter, which must
1278 be assigned to `self-insert-command' in the global map.
1279 The cdr is either a command to be called interactively, a function
1280 to be called, or a form to be evaluated.
1281 An entry that is just a list with a single string will be interpreted
1282 as a descriptive headline that will be added when listing the speed
1283 commands in the Help buffer using the `?' speed command."
1284 :group 'org-structure
1285 :type '(repeat :value ("k" . ignore)
1286 (choice :value ("k" . ignore)
1287 (list :tag "Descriptive Headline" (string :tag "Headline"))
1288 (cons :tag "Letter and Command"
1289 (string :tag "Command letter")
1290 (choice
1291 (function)
1292 (sexp))))))
1294 (defcustom org-bookmark-names-plist
1295 '(:last-capture "org-capture-last-stored"
1296 :last-refile "org-refile-last-stored"
1297 :last-capture-marker "org-capture-last-stored-marker")
1298 "Names for bookmarks automatically set by some Org commands.
1299 This can provide strings as names for a number of bookmarks Org sets
1300 automatically. The following keys are currently implemented:
1301 :last-capture
1302 :last-capture-marker
1303 :last-refile
1304 When a key does not show up in the property list, the corresponding bookmark
1305 is not set."
1306 :group 'org-structure
1307 :type 'plist)
1309 (defgroup org-cycle nil
1310 "Options concerning visibility cycling in Org mode."
1311 :tag "Org Cycle"
1312 :group 'org-structure)
1314 (defcustom org-cycle-skip-children-state-if-no-children t
1315 "Non-nil means skip CHILDREN state in entries that don't have any."
1316 :group 'org-cycle
1317 :type 'boolean)
1319 (defcustom org-cycle-max-level nil
1320 "Maximum level which should still be subject to visibility cycling.
1321 Levels higher than this will, for cycling, be treated as text, not a headline.
1322 When `org-odd-levels-only' is set, a value of N in this variable actually
1323 means 2N-1 stars as the limiting headline.
1324 When nil, cycle all levels.
1325 Note that the limiting level of cycling is also influenced by
1326 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1327 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1328 than its value."
1329 :group 'org-cycle
1330 :type '(choice
1331 (const :tag "No limit" nil)
1332 (integer :tag "Maximum level")))
1334 (defcustom org-hide-block-startup nil
1335 "Non-nil means entering Org mode will fold all blocks.
1336 This can also be set in on a per-file basis with
1338 #+STARTUP: hideblocks
1339 #+STARTUP: showblocks"
1340 :group 'org-startup
1341 :group 'org-cycle
1342 :type 'boolean)
1344 (defcustom org-cycle-global-at-bob nil
1345 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1347 This makes it possible to do global cycling without having to use `S-TAB'
1348 or `\\[universal-argument] TAB'. For this special case to work, the first \
1349 line of the buffer
1350 must not be a headline -- it may be empty or some other text.
1352 When used in this way, `org-cycle-hook' is disabled temporarily to make
1353 sure the cursor stays at the beginning of the buffer.
1355 When this option is nil, don't do anything special at the beginning of
1356 the buffer."
1357 :group 'org-cycle
1358 :type 'boolean)
1360 (defcustom org-cycle-level-after-item/entry-creation t
1361 "Non-nil means cycle entry level or item indentation in new empty entries.
1363 When the cursor is at the end of an empty headline, i.e., with only stars
1364 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1365 and then all possible ancestor states, before returning to the original state.
1366 This makes data entry extremely fast: M-RET to create a new headline,
1367 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1369 When the cursor is at the end of an empty plain list item, one TAB will
1370 make it a subitem, two or more tabs will back up to make this an item
1371 higher up in the item hierarchy."
1372 :group 'org-cycle
1373 :type 'boolean)
1375 (defcustom org-cycle-emulate-tab t
1376 "Where should `org-cycle' emulate TAB.
1377 nil Never
1378 white Only in completely white lines
1379 whitestart Only at the beginning of lines, before the first non-white char
1380 t Everywhere except in headlines
1381 exc-hl-bol Everywhere except at the start of a headline
1382 If TAB is used in a place where it does not emulate TAB, the current subtree
1383 visibility is cycled."
1384 :group 'org-cycle
1385 :type '(choice (const :tag "Never" nil)
1386 (const :tag "Only in completely white lines" white)
1387 (const :tag "Before first char in a line" whitestart)
1388 (const :tag "Everywhere except in headlines" t)
1389 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1391 (defcustom org-cycle-separator-lines 2
1392 "Number of empty lines needed to keep an empty line between collapsed trees.
1393 If you leave an empty line between the end of a subtree and the following
1394 headline, this empty line is hidden when the subtree is folded.
1395 Org mode will leave (exactly) one empty line visible if the number of
1396 empty lines is equal or larger to the number given in this variable.
1397 So the default 2 means at least 2 empty lines after the end of a subtree
1398 are needed to produce free space between a collapsed subtree and the
1399 following headline.
1401 If the number is negative, and the number of empty lines is at least -N,
1402 all empty lines are shown.
1404 Special case: when 0, never leave empty lines in collapsed view."
1405 :group 'org-cycle
1406 :type 'integer)
1407 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1409 (defcustom org-pre-cycle-hook nil
1410 "Hook that is run before visibility cycling is happening.
1411 The function(s) in this hook must accept a single argument which indicates
1412 the new state that will be set right after running this hook. The
1413 argument is a symbol. Before a global state change, it can have the values
1414 `overview', `content', or `all'. Before a local state change, it can have
1415 the values `folded', `children', or `subtree'."
1416 :group 'org-cycle
1417 :type 'hook)
1419 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1420 org-cycle-hide-drawers
1421 org-cycle-show-empty-lines
1422 org-optimize-window-after-visibility-change)
1423 "Hook that is run after `org-cycle' has changed the buffer visibility.
1424 The function(s) in this hook must accept a single argument which indicates
1425 the new state that was set by the most recent `org-cycle' command. The
1426 argument is a symbol. After a global state change, it can have the values
1427 `overview', `contents', or `all'. After a local state change, it can have
1428 the values `folded', `children', or `subtree'."
1429 :group 'org-cycle
1430 :type 'hook
1431 :version "26.1"
1432 :package-version '(Org . "8.3"))
1434 (defgroup org-edit-structure nil
1435 "Options concerning structure editing in Org mode."
1436 :tag "Org Edit Structure"
1437 :group 'org-structure)
1439 (defcustom org-odd-levels-only nil
1440 "Non-nil means skip even levels and only use odd levels for the outline.
1441 This has the effect that two stars are being added/taken away in
1442 promotion/demotion commands. It also influences how levels are
1443 handled by the exporters.
1444 Changing it requires restart of `font-lock-mode' to become effective
1445 for fontification also in regions already fontified.
1446 You may also set this on a per-file basis by adding one of the following
1447 lines to the buffer:
1449 #+STARTUP: odd
1450 #+STARTUP: oddeven"
1451 :group 'org-edit-structure
1452 :group 'org-appearance
1453 :type 'boolean)
1455 (defcustom org-adapt-indentation t
1456 "Non-nil means adapt indentation to outline node level.
1458 When this variable is set, Org assumes that you write outlines by
1459 indenting text in each node to align with the headline (after the
1460 stars). The following issues are influenced by this variable:
1462 - The indentation is increased by one space in a demotion
1463 command, and decreased by one in a promotion command. However,
1464 in the latter case, if shifting some line in the entry body
1465 would alter document structure (e.g., insert a new headline),
1466 indentation is not changed at all.
1468 - Property drawers and planning information is inserted indented
1469 when this variable is set. When nil, they will not be indented.
1471 - TAB indents a line relative to current level. The lines below
1472 a headline will be indented when this variable is set.
1474 Note that this is all about true indentation, by adding and
1475 removing space characters. See also `org-indent.el' which does
1476 level-dependent indentation in a virtual way, i.e. at display
1477 time in Emacs."
1478 :group 'org-edit-structure
1479 :type 'boolean)
1481 (defcustom org-special-ctrl-a/e nil
1482 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1484 When t, `C-a' will bring back the cursor to the beginning of the
1485 headline text, i.e. after the stars and after a possible TODO
1486 keyword. In an item, this will be the position after bullet and
1487 check-box, if any. When the cursor is already at that position,
1488 another `C-a' will bring it to the beginning of the line.
1490 `C-e' will jump to the end of the headline, ignoring the presence
1491 of tags in the headline. A second `C-e' will then jump to the
1492 true end of the line, after any tags. This also means that, when
1493 this variable is non-nil, `C-e' also will never jump beyond the
1494 end of the heading of a folded section, i.e. not after the
1495 ellipses.
1497 When set to the symbol `reversed', the first `C-a' or `C-e' works
1498 normally, going to the true line boundary first. Only a directly
1499 following, identical keypress will bring the cursor to the
1500 special positions.
1502 This may also be a cons cell where the behavior for `C-a' and
1503 `C-e' is set separately."
1504 :group 'org-edit-structure
1505 :type '(choice
1506 (const :tag "off" nil)
1507 (const :tag "on: after stars/bullet and before tags first" t)
1508 (const :tag "reversed: true line boundary first" reversed)
1509 (cons :tag "Set C-a and C-e separately"
1510 (choice :tag "Special C-a"
1511 (const :tag "off" nil)
1512 (const :tag "on: after stars/bullet first" t)
1513 (const :tag "reversed: before stars/bullet first" reversed))
1514 (choice :tag "Special C-e"
1515 (const :tag "off" nil)
1516 (const :tag "on: before tags first" t)
1517 (const :tag "reversed: after tags first" reversed)))))
1518 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1520 (defcustom org-special-ctrl-k nil
1521 "Non-nil means `C-k' will behave specially in headlines.
1522 When nil, `C-k' will call the default `kill-line' command.
1523 When t, the following will happen while the cursor is in the headline:
1525 - When the cursor is at the beginning of a headline, kill the entire
1526 line and possible the folded subtree below the line.
1527 - When in the middle of the headline text, kill the headline up to the tags.
1528 - When after the headline text, kill the tags."
1529 :group 'org-edit-structure
1530 :type 'boolean)
1532 (defcustom org-ctrl-k-protect-subtree nil
1533 "Non-nil means, do not delete a hidden subtree with C-k.
1534 When set to the symbol `error', simply throw an error when C-k is
1535 used to kill (part-of) a headline that has hidden text behind it.
1536 Any other non-nil value will result in a query to the user, if it is
1537 OK to kill that hidden subtree. When nil, kill without remorse."
1538 :group 'org-edit-structure
1539 :version "24.1"
1540 :type '(choice
1541 (const :tag "Do not protect hidden subtrees" nil)
1542 (const :tag "Protect hidden subtrees with a security query" t)
1543 (const :tag "Never kill a hidden subtree with C-k" error)))
1545 (defcustom org-special-ctrl-o t
1546 "Non-nil means, make `C-o' insert a row in tables."
1547 :group 'org-edit-structure
1548 :type 'boolean)
1550 (defcustom org-catch-invisible-edits nil
1551 "Check if in invisible region before inserting or deleting a character.
1552 Valid values are:
1554 nil Do not check, so just do invisible edits.
1555 error Throw an error and do nothing.
1556 show Make point visible, and do the requested edit.
1557 show-and-error Make point visible, then throw an error and abort the edit.
1558 smart Make point visible, and do insertion/deletion if it is
1559 adjacent to visible text and the change feels predictable.
1560 Never delete a previously invisible character or add in the
1561 middle or right after an invisible region. Basically, this
1562 allows insertion and backward-delete right before ellipses.
1563 FIXME: maybe in this case we should not even show?"
1564 :group 'org-edit-structure
1565 :version "24.1"
1566 :type '(choice
1567 (const :tag "Do not check" nil)
1568 (const :tag "Throw error when trying to edit" error)
1569 (const :tag "Unhide, but do not do the edit" show-and-error)
1570 (const :tag "Show invisible part and do the edit" show)
1571 (const :tag "Be smart and do the right thing" smart)))
1573 (defcustom org-yank-folded-subtrees t
1574 "Non-nil means when yanking subtrees, fold them.
1575 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1576 it starts with a heading and all other headings in it are either children
1577 or siblings, then fold all the subtrees. However, do this only if no
1578 text after the yank would be swallowed into a folded tree by this action."
1579 :group 'org-edit-structure
1580 :type 'boolean)
1582 (defcustom org-yank-adjusted-subtrees nil
1583 "Non-nil means when yanking subtrees, adjust the level.
1584 With this setting, `org-paste-subtree' is used to insert the subtree, see
1585 this function for details."
1586 :group 'org-edit-structure
1587 :type 'boolean)
1589 (defcustom org-M-RET-may-split-line '((default . t))
1590 "Non-nil means M-RET will split the line at the cursor position.
1591 When nil, it will go to the end of the line before making a
1592 new line.
1593 You may also set this option in a different way for different
1594 contexts. Valid contexts are:
1596 headline when creating a new headline
1597 item when creating a new item
1598 table in a table field
1599 default the value to be used for all contexts not explicitly
1600 customized"
1601 :group 'org-structure
1602 :group 'org-table
1603 :type '(choice
1604 (const :tag "Always" t)
1605 (const :tag "Never" nil)
1606 (repeat :greedy t :tag "Individual contexts"
1607 (cons
1608 (choice :tag "Context"
1609 (const headline)
1610 (const item)
1611 (const table)
1612 (const default))
1613 (boolean)))))
1616 (defcustom org-insert-heading-respect-content nil
1617 "Non-nil means insert new headings after the current subtree.
1618 \\<org-mode-map>
1619 When nil, the new heading is created directly after the current line.
1620 The commands `\\[org-insert-heading-respect-content]' and \
1621 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1622 for the duration of the command."
1623 :group 'org-structure
1624 :type 'boolean)
1626 (defcustom org-blank-before-new-entry '((heading . auto)
1627 (plain-list-item . auto))
1628 "Should `org-insert-heading' leave a blank line before new heading/item?
1629 The value is an alist, with `heading' and `plain-list-item' as CAR,
1630 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1631 which case Org will look at the surrounding headings/items and try to
1632 make an intelligent decision whether to insert a blank line or not."
1633 :group 'org-edit-structure
1634 :type '(list
1635 (cons (const heading)
1636 (choice (const :tag "Never" nil)
1637 (const :tag "Always" t)
1638 (const :tag "Auto" auto)))
1639 (cons (const plain-list-item)
1640 (choice (const :tag "Never" nil)
1641 (const :tag "Always" t)
1642 (const :tag "Auto" auto)))))
1644 (defcustom org-insert-heading-hook nil
1645 "Hook being run after inserting a new heading."
1646 :group 'org-edit-structure
1647 :type 'hook)
1649 (defcustom org-enable-fixed-width-editor t
1650 "Non-nil means lines starting with \":\" are treated as fixed-width.
1651 This currently only means they are never auto-wrapped.
1652 When nil, such lines will be treated like ordinary lines."
1653 :group 'org-edit-structure
1654 :type 'boolean)
1656 (defcustom org-goto-auto-isearch t
1657 "Non-nil means typing characters in `org-goto' starts incremental search.
1658 When nil, you can use these keybindings to navigate the buffer:
1660 q Quit the org-goto interface
1661 n Go to the next visible heading
1662 p Go to the previous visible heading
1663 f Go one heading forward on same level
1664 b Go one heading backward on same level
1665 u Go one heading up"
1666 :group 'org-edit-structure
1667 :type 'boolean)
1669 (defgroup org-sparse-trees nil
1670 "Options concerning sparse trees in Org mode."
1671 :tag "Org Sparse Trees"
1672 :group 'org-structure)
1674 (defcustom org-highlight-sparse-tree-matches t
1675 "Non-nil means highlight all matches that define a sparse tree.
1676 The highlights will automatically disappear the next time the buffer is
1677 changed by an edit command."
1678 :group 'org-sparse-trees
1679 :type 'boolean)
1681 (defcustom org-remove-highlights-with-change t
1682 "Non-nil means any change to the buffer will remove temporary highlights.
1683 \\<org-mode-map>\
1684 Such highlights are created by `org-occur' and `org-clock-display'.
1685 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1686 to get rid of the highlights.
1687 The highlights created by `org-toggle-latex-fragment' always need
1688 `\\[org-toggle-latex-fragment]' to be removed."
1689 :group 'org-sparse-trees
1690 :group 'org-time
1691 :type 'boolean)
1693 (defcustom org-occur-case-fold-search t
1694 "Non-nil means `org-occur' should be case-insensitive.
1695 If set to `smart' the search will be case-insensitive only if it
1696 doesn't specify any upper case character."
1697 :group 'org-sparse-trees
1698 :version "26.1"
1699 :type '(choice
1700 (const :tag "Case-sensitive" nil)
1701 (const :tag "Case-insensitive" t)
1702 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1704 (defcustom org-occur-hook '(org-first-headline-recenter)
1705 "Hook that is run after `org-occur' has constructed a sparse tree.
1706 This can be used to recenter the window to show as much of the structure
1707 as possible."
1708 :group 'org-sparse-trees
1709 :type 'hook)
1711 (defgroup org-imenu-and-speedbar nil
1712 "Options concerning imenu and speedbar in Org mode."
1713 :tag "Org Imenu and Speedbar"
1714 :group 'org-structure)
1716 (defcustom org-imenu-depth 2
1717 "The maximum level for Imenu access to Org headlines.
1718 This also applied for speedbar access."
1719 :group 'org-imenu-and-speedbar
1720 :type 'integer)
1722 (defgroup org-table nil
1723 "Options concerning tables in Org mode."
1724 :tag "Org Table"
1725 :group 'org)
1727 (defcustom org-enable-table-editor 'optimized
1728 "Non-nil means lines starting with \"|\" are handled by the table editor.
1729 When nil, such lines will be treated like ordinary lines.
1731 When equal to the symbol `optimized', the table editor will be optimized to
1732 do the following:
1733 - Automatic overwrite mode in front of whitespace in table fields.
1734 This makes the structure of the table stay in tact as long as the edited
1735 field does not exceed the column width.
1736 - Minimize the number of realigns. Normally, the table is aligned each time
1737 TAB or RET are pressed to move to another field. With optimization this
1738 happens only if changes to a field might have changed the column width.
1739 Optimization requires replacing the functions `self-insert-command',
1740 `delete-char', and `backward-delete-char' in Org buffers, with a
1741 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1742 good at guessing when a re-align will be necessary, but you can always
1743 force one with `\\[org-ctrl-c-ctrl-c]'.
1745 If you would like to use the optimized version in Org mode, but the
1746 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1748 This variable can be used to turn on and off the table editor during a session,
1749 but in order to toggle optimization, a restart is required.
1751 See also the variable `org-table-auto-blank-field'."
1752 :group 'org-table
1753 :type '(choice
1754 (const :tag "off" nil)
1755 (const :tag "on" t)
1756 (const :tag "on, optimized" optimized)))
1758 (defcustom org-self-insert-cluster-for-undo nil
1759 "Non-nil means cluster self-insert commands for undo when possible.
1760 If this is set, then, like in the Emacs command loop, 20 consecutive
1761 characters will be undone together.
1762 This is configurable, because there is some impact on typing performance."
1763 :group 'org-table
1764 :type 'boolean)
1766 (defcustom org-table-tab-recognizes-table.el t
1767 "Non-nil means TAB will automatically notice a table.el table.
1768 When it sees such a table, it moves point into it and - if necessary -
1769 calls `table-recognize-table'."
1770 :group 'org-table-editing
1771 :type 'boolean)
1773 (defgroup org-link nil
1774 "Options concerning links in Org mode."
1775 :tag "Org Link"
1776 :group 'org)
1778 (defvar-local org-link-abbrev-alist-local nil
1779 "Buffer-local version of `org-link-abbrev-alist', which see.
1780 The value of this is taken from the #+LINK lines.")
1782 (defcustom org-link-parameters
1783 '(("doi" :follow org--open-doi-link)
1784 ("elisp" :follow org--open-elisp-link)
1785 ("file" :complete org-file-complete-link)
1786 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1787 ("help" :follow org--open-help-link)
1788 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1789 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1790 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1791 ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
1792 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1793 ("shell" :follow org--open-shell-link))
1794 "An alist of properties that defines all the links in Org mode.
1795 The key in each association is a string of the link type.
1796 Subsequent optional elements make up a p-list of link properties.
1798 :follow - A function that takes the link path as an argument.
1800 :export - A function that takes the link path, description and
1801 export-backend as arguments.
1803 :store - A function responsible for storing the link. See the
1804 function `org-store-link-functions'.
1806 :complete - A function that inserts a link with completion. The
1807 function takes one optional prefix arg.
1809 :face - A face for the link, or a function that returns a face.
1810 The function takes one argument which is the link path. The
1811 default face is `org-link'.
1813 :mouse-face - The mouse-face. The default is `highlight'.
1815 :display - `full' will not fold the link in descriptive
1816 display. Default is `org-link'.
1818 :help-echo - A string or function that takes (window object position)
1819 as arguments and returns a string.
1821 :keymap - A keymap that is active on the link. The default is
1822 `org-mouse-map'.
1824 :htmlize-link - A function for the htmlize-link. Defaults
1825 to (list :uri \"type:path\")
1827 :activate-func - A function to run at the end of font-lock
1828 activation. The function must accept (link-start link-end path bracketp)
1829 as arguments."
1830 :group 'org-link
1831 :type '(alist :tag "Link display parameters"
1832 :value-type plist))
1834 (defun org-link-get-parameter (type key)
1835 "Get TYPE link property for KEY.
1836 TYPE is a string and KEY is a plist keyword."
1837 (plist-get
1838 (cdr (assoc type org-link-parameters))
1839 key))
1841 (defun org-link-set-parameters (type &rest parameters)
1842 "Set link TYPE properties to PARAMETERS.
1843 PARAMETERS should be :key val pairs."
1844 (let ((data (assoc type org-link-parameters)))
1845 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1846 (push (cons type parameters) org-link-parameters)
1847 (org-make-link-regexps)
1848 (org-element-update-syntax))))
1850 (defun org-link-types ()
1851 "Return a list of known link types."
1852 (mapcar #'car org-link-parameters))
1854 (defcustom org-link-abbrev-alist nil
1855 "Alist of link abbreviations.
1856 The car of each element is a string, to be replaced at the start of a link.
1857 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1858 links in Org buffers can have an optional tag after a double colon, e.g.,
1860 [[linkkey:tag][description]]
1862 The `linkkey' must be a single word, starting with a letter, followed
1863 by letters, numbers, `-' or `_'.
1865 If REPLACE is a string, the tag will simply be appended to create the link.
1866 If the string contains \"%s\", the tag will be inserted there. If the string
1867 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1868 at that point (see the function `url-hexify-string'). If the string contains
1869 the specifier \"%(my-function)\", then the custom function `my-function' will
1870 be invoked: this function takes the tag as its only argument and must return
1871 a string.
1873 REPLACE may also be a function that will be called with the tag as the
1874 only argument to create the link, which should be returned as a string.
1876 See the manual for examples."
1877 :group 'org-link
1878 :type '(repeat
1879 (cons
1880 (string :tag "Protocol")
1881 (choice
1882 (string :tag "Format")
1883 (function)))))
1885 (defcustom org-descriptive-links t
1886 "Non-nil means Org will display descriptive links.
1887 E.g. [[http://orgmode.org][Org website]] will be displayed as
1888 \"Org Website\", hiding the link itself and just displaying its
1889 description. When set to nil, Org will display the full links
1890 literally.
1892 You can interactively set the value of this variable by calling
1893 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1894 :group 'org-link
1895 :type 'boolean)
1897 (defcustom org-link-file-path-type 'adaptive
1898 "How the path name in file links should be stored.
1899 Valid values are:
1901 relative Relative to the current directory, i.e. the directory of the file
1902 into which the link is being inserted.
1903 absolute Absolute path, if possible with ~ for home directory.
1904 noabbrev Absolute path, no abbreviation of home directory.
1905 adaptive Use relative path for files in the current directory and sub-
1906 directories of it. For other files, use an absolute path."
1907 :group 'org-link
1908 :type '(choice
1909 (const relative)
1910 (const absolute)
1911 (const noabbrev)
1912 (const adaptive)))
1914 (defvaralias 'org-activate-links 'org-highlight-links)
1915 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1916 "Types of links that should be highlighted in Org files.
1918 This is a list of symbols, each one of them leading to the
1919 highlighting of a certain link type.
1921 You can still open links that are not highlighted.
1923 In principle, it does not hurt to turn on highlighting for all
1924 link types. There may be a small gain when turning off unused
1925 link types. The types are:
1927 bracket The recommended [[link][description]] or [[link]] links with hiding.
1928 angle Links in angular brackets that may contain whitespace like
1929 <bbdb:Carsten Dominik>.
1930 plain Plain links in normal text, no whitespace, like http://google.com.
1931 radio Text that is matched by a radio target, see manual for details.
1932 tag Tag settings in a headline (link to tag search).
1933 date Time stamps (link to calendar).
1934 footnote Footnote labels.
1936 If you set this variable during an Emacs session, use `org-mode-restart'
1937 in the Org buffer so that the change takes effect."
1938 :group 'org-link
1939 :group 'org-appearance
1940 :type '(set :greedy t
1941 (const :tag "Double bracket links" bracket)
1942 (const :tag "Angular bracket links" angle)
1943 (const :tag "Plain text links" plain)
1944 (const :tag "Radio target matches" radio)
1945 (const :tag "Tags" tag)
1946 (const :tag "Timestamps" date)
1947 (const :tag "Footnotes" footnote)))
1949 (defcustom org-make-link-description-function nil
1950 "Function to use for generating link descriptions from links.
1951 When nil, the link location will be used. This function must take
1952 two parameters: the first one is the link, the second one is the
1953 description generated by `org-insert-link'. The function should
1954 return the description to use."
1955 :group 'org-link
1956 :type '(choice (const nil) (function)))
1958 (defgroup org-link-store nil
1959 "Options concerning storing links in Org mode."
1960 :tag "Org Store Link"
1961 :group 'org-link)
1963 (defcustom org-url-hexify-p t
1964 "When non-nil, hexify URL when creating a link."
1965 :type 'boolean
1966 :version "24.3"
1967 :group 'org-link-store)
1969 (defcustom org-email-link-description-format "Email %c: %.30s"
1970 "Format of the description part of a link to an email or usenet message.
1971 The following %-escapes will be replaced by corresponding information:
1973 %F full \"From\" field
1974 %f name, taken from \"From\" field, address if no name
1975 %T full \"To\" field
1976 %t first name in \"To\" field, address if no name
1977 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1978 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1979 %s subject
1980 %d date
1981 %m message-id.
1983 You may use normal field width specification between the % and the letter.
1984 This is for example useful to limit the length of the subject.
1986 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1987 :group 'org-link-store
1988 :type 'string)
1990 (defcustom org-from-is-user-regexp
1991 (let (r1 r2)
1992 (when (and user-mail-address (not (string= user-mail-address "")))
1993 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1994 (when (and user-full-name (not (string= user-full-name "")))
1995 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1996 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1997 "Regexp matched against the \"From:\" header of an email or usenet message.
1998 It should match if the message is from the user him/herself."
1999 :group 'org-link-store
2000 :type 'regexp)
2002 (defcustom org-context-in-file-links t
2003 "Non-nil means file links from `org-store-link' contain context.
2004 \\<org-mode-map>
2005 A search string will be added to the file name with :: as separator
2006 and used to find the context when the link is activated by the command
2007 `org-open-at-point'. When this option is t, the entire active region
2008 will be placed in the search string of the file link. If set to a
2009 positive integer, only the first n lines of context will be stored.
2011 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2012 \\[org-store-link]')
2013 negates this setting for the duration of the command."
2014 :group 'org-link-store
2015 :type '(choice boolean integer))
2017 (defcustom org-keep-stored-link-after-insertion nil
2018 "Non-nil means keep link in list for entire session.
2019 \\<org-mode-map>
2020 The command `org-store-link' adds a link pointing to the current
2021 location to an internal list. These links accumulate during a session.
2022 The command `org-insert-link' can be used to insert links into any
2023 Org file (offering completion for all stored links).
2025 When this option is nil, every link which has been inserted once using
2026 `\\[org-insert-link]' will be removed from the list, to make completing the \
2027 unused
2028 links more efficient."
2029 :group 'org-link-store
2030 :type 'boolean)
2032 (defgroup org-link-follow nil
2033 "Options concerning following links in Org mode."
2034 :tag "Org Follow Link"
2035 :group 'org-link)
2037 (defcustom org-link-translation-function nil
2038 "Function to translate links with different syntax to Org syntax.
2039 This can be used to translate links created for example by the Planner
2040 or emacs-wiki packages to Org syntax.
2041 The function must accept two parameters, a TYPE containing the link
2042 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2043 which is everything after the link protocol. It should return a cons
2044 with possibly modified values of type and path.
2045 Org contains a function for this, so if you set this variable to
2046 `org-translate-link-from-planner', you should be able follow many
2047 links created by planner."
2048 :group 'org-link-follow
2049 :type '(choice (const nil) (function)))
2051 (defcustom org-follow-link-hook nil
2052 "Hook that is run after a link has been followed."
2053 :group 'org-link-follow
2054 :type 'hook)
2056 (defcustom org-tab-follows-link nil
2057 "Non-nil means on links TAB will follow the link.
2058 Needs to be set before org.el is loaded.
2059 This really should not be used, it does not make sense, and the
2060 implementation is bad."
2061 :group 'org-link-follow
2062 :type 'boolean)
2064 (defcustom org-return-follows-link nil
2065 "Non-nil means on links RET will follow the link.
2066 In tables, the special behavior of RET has precedence."
2067 :group 'org-link-follow
2068 :type 'boolean)
2070 (defcustom org-mouse-1-follows-link
2071 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2072 "Non-nil means mouse-1 on a link will follow the link.
2073 A longer mouse click will still set point. Needs to be set
2074 before org.el is loaded."
2075 :group 'org-link-follow
2076 :version "24.4"
2077 :package-version '(Org . "8.3")
2078 :type '(choice
2079 (const :tag "A double click follows the link" double)
2080 (const :tag "Unconditionally follow the link with mouse-1" t)
2081 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2083 (defcustom org-mark-ring-length 4
2084 "Number of different positions to be recorded in the ring.
2085 Changing this requires a restart of Emacs to work correctly."
2086 :group 'org-link-follow
2087 :type 'integer)
2089 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2090 "Non-nil means internal fuzzy links can only match headlines.
2092 When nil, the a fuzzy link may point to a target or a named
2093 construct in the document. When set to the special value
2094 `query-to-create', offer to create a new headline when none
2095 matched.
2097 Spaces and statistics cookies are ignored during heading searches."
2098 :group 'org-link-follow
2099 :version "24.1"
2100 :type '(choice
2101 (const :tag "Use fuzzy text search" nil)
2102 (const :tag "Match only exact headline" t)
2103 (const :tag "Match exact headline or query to create it"
2104 query-to-create))
2105 :safe #'symbolp)
2107 (defcustom org-link-frame-setup
2108 '((vm . vm-visit-folder-other-frame)
2109 (vm-imap . vm-visit-imap-folder-other-frame)
2110 (gnus . org-gnus-no-new-news)
2111 (file . find-file-other-window)
2112 (wl . wl-other-frame))
2113 "Setup the frame configuration for following links.
2114 When following a link with Emacs, it may often be useful to display
2115 this link in another window or frame. This variable can be used to
2116 set this up for the different types of links.
2117 For VM, use any of
2118 `vm-visit-folder'
2119 `vm-visit-folder-other-window'
2120 `vm-visit-folder-other-frame'
2121 For Gnus, use any of
2122 `gnus'
2123 `gnus-other-frame'
2124 `org-gnus-no-new-news'
2125 For FILE, use any of
2126 `find-file'
2127 `find-file-other-window'
2128 `find-file-other-frame'
2129 For Wanderlust use any of
2130 `wl'
2131 `wl-other-frame'
2132 For the calendar, use the variable `calendar-setup'.
2133 For BBDB, it is currently only possible to display the matches in
2134 another window."
2135 :group 'org-link-follow
2136 :type '(list
2137 (cons (const vm)
2138 (choice
2139 (const vm-visit-folder)
2140 (const vm-visit-folder-other-window)
2141 (const vm-visit-folder-other-frame)))
2142 (cons (const vm-imap)
2143 (choice
2144 (const vm-visit-imap-folder)
2145 (const vm-visit-imap-folder-other-window)
2146 (const vm-visit-imap-folder-other-frame)))
2147 (cons (const gnus)
2148 (choice
2149 (const gnus)
2150 (const gnus-other-frame)
2151 (const org-gnus-no-new-news)))
2152 (cons (const file)
2153 (choice
2154 (const find-file)
2155 (const find-file-other-window)
2156 (const find-file-other-frame)))
2157 (cons (const wl)
2158 (choice
2159 (const wl)
2160 (const wl-other-frame)))))
2162 (defcustom org-display-internal-link-with-indirect-buffer nil
2163 "Non-nil means use indirect buffer to display infile links.
2164 Activating internal links (from one location in a file to another location
2165 in the same file) normally just jumps to the location. When the link is
2166 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2167 is displayed in
2168 another window. When this option is set, the other window actually displays
2169 an indirect buffer clone of the current buffer, to avoid any visibility
2170 changes to the current buffer."
2171 :group 'org-link-follow
2172 :type 'boolean)
2174 (defcustom org-open-non-existing-files nil
2175 "Non-nil means `org-open-file' will open non-existing files.
2176 When nil, an error will be generated.
2177 This variable applies only to external applications because they
2178 might choke on non-existing files. If the link is to a file that
2179 will be opened in Emacs, the variable is ignored."
2180 :group 'org-link-follow
2181 :type 'boolean)
2183 (defcustom org-open-directory-means-index-dot-org nil
2184 "Non-nil means a link to a directory really means to index.org.
2185 When nil, following a directory link will run dired or open a finder/explorer
2186 window on that directory."
2187 :group 'org-link-follow
2188 :type 'boolean)
2190 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2191 "Non-nil means ask for confirmation before executing shell links.
2192 Shell links can be dangerous: just think about a link
2194 [[shell:rm -rf ~/*][Google Search]]
2196 This link would show up in your Org document as \"Google Search\",
2197 but really it would remove your entire home directory.
2198 Therefore we advise against setting this variable to nil.
2199 Just change it to `y-or-n-p' if you want to confirm with a
2200 single keystroke rather than having to type \"yes\"."
2201 :group 'org-link-follow
2202 :type '(choice
2203 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2204 (const :tag "with y-or-n (faster)" y-or-n-p)
2205 (const :tag "no confirmation (dangerous)" nil)))
2206 (put 'org-confirm-shell-link-function
2207 'safe-local-variable
2208 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2210 (defcustom org-confirm-shell-link-not-regexp ""
2211 "A regexp to skip confirmation for shell links."
2212 :group 'org-link-follow
2213 :version "24.1"
2214 :type 'regexp)
2216 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2217 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2218 Elisp links can be dangerous: just think about a link
2220 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2222 This link would show up in your Org document as \"Google Search\",
2223 but really it would remove your entire home directory.
2224 Therefore we advise against setting this variable to nil.
2225 Just change it to `y-or-n-p' if you want to confirm with a
2226 single keystroke rather than having to type \"yes\"."
2227 :group 'org-link-follow
2228 :type '(choice
2229 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2230 (const :tag "with y-or-n (faster)" y-or-n-p)
2231 (const :tag "no confirmation (dangerous)" nil)))
2232 (put 'org-confirm-shell-link-function
2233 'safe-local-variable
2234 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2236 (defcustom org-confirm-elisp-link-not-regexp ""
2237 "A regexp to skip confirmation for Elisp links."
2238 :group 'org-link-follow
2239 :version "24.1"
2240 :type 'regexp)
2242 (defconst org-file-apps-defaults-gnu
2243 '((remote . emacs)
2244 (system . mailcap)
2245 (t . mailcap))
2246 "Default file applications on a UNIX or GNU/Linux system.
2247 See `org-file-apps'.")
2249 (defconst org-file-apps-defaults-macosx
2250 '((remote . emacs)
2251 (system . "open %s")
2252 ("ps.gz" . "gv %s")
2253 ("eps.gz" . "gv %s")
2254 ("dvi" . "xdvi %s")
2255 ("fig" . "xfig %s")
2256 (t . "open %s"))
2257 "Default file applications on a macOS system.
2258 The system \"open\" is known as a default, but we use X11 applications
2259 for some files for which the OS does not have a good default.
2260 See `org-file-apps'.")
2262 (defconst org-file-apps-defaults-windowsnt
2263 (list '(remote . emacs)
2264 (cons 'system (lambda (file _path)
2265 (with-no-warnings (w32-shell-execute "open" file))))
2266 (cons t (lambda (file _path)
2267 (with-no-warnings (w32-shell-execute "open" file)))))
2268 "Default file applications on a Windows NT system.
2269 The system \"open\" is used for most files.
2270 See `org-file-apps'.")
2272 (defcustom org-file-apps
2273 '((auto-mode . emacs)
2274 ("\\.mm\\'" . default)
2275 ("\\.x?html?\\'" . default)
2276 ("\\.pdf\\'" . default))
2277 "External applications for opening `file:path' items in a document.
2278 \\<org-mode-map>\
2280 Org mode uses system defaults for different file types, but
2281 you can use this variable to set the application for a given file
2282 extension. The entries in this list are cons cells where the car identifies
2283 files and the cdr the corresponding command.
2285 Possible values for the file identifier are:
2287 \"string\" A string as a file identifier can be interpreted in different
2288 ways, depending on its contents:
2290 - Alphanumeric characters only:
2291 Match links with this file extension.
2292 Example: (\"pdf\" . \"evince %s\")
2293 to open PDFs with evince.
2295 - Regular expression: Match links where the
2296 filename matches the regexp. If you want to
2297 use groups here, use shy groups.
2299 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2300 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2301 to open *.html and *.xhtml with firefox.
2303 - Regular expression which contains (non-shy) groups:
2304 Match links where the whole link, including \"::\", and
2305 anything after that, matches the regexp.
2306 In a custom command string, %1, %2, etc. are replaced with
2307 the parts of the link that were matched by the groups.
2308 For backwards compatibility, if a command string is given
2309 that does not use any of the group matches, this case is
2310 handled identically to the second one (i.e. match against
2311 file name only).
2312 In a custom function, you can access the group matches with
2313 (match-string n link).
2315 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2316 \"evince -p %1 %s\")
2317 to open [[file:document.pdf::5]] with evince at page 5.
2319 `directory' Matches a directory
2320 `remote' Matches a remote file, accessible through tramp or efs.
2321 Remote files most likely should be visited through Emacs
2322 because external applications cannot handle such paths.
2323 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2324 so all files Emacs knows how to handle. Using this with
2325 command `emacs' will open most files in Emacs. Beware that this
2326 will also open html files inside Emacs, unless you add
2327 (\"html\" . default) to the list as well.
2328 `system' The system command to open files, like `open' on Windows
2329 and macOS, and mailcap under GNU/Linux. This is the command
2330 that will be selected if you call `org-open-at-point' with a
2331 double prefix argument (`\\[universal-argument] \
2332 \\[universal-argument] \\[org-open-at-point]').
2333 t Default for files not matched by any of the other options.
2335 Possible values for the command are:
2337 `emacs' The file will be visited by the current Emacs process.
2338 `default' Use the default application for this file type, which is the
2339 association for t in the list, most likely in the system-specific
2340 part. This can be used to overrule an unwanted setting in the
2341 system-specific variable.
2342 `system' Use the system command for opening files, like \"open\".
2343 This command is specified by the entry whose car is `system'.
2344 Most likely, the system-specific version of this variable
2345 does define this command, but you can overrule/replace it
2346 here.
2347 `mailcap' Use command specified in the mailcaps.
2348 string A command to be executed by a shell; %s will be replaced
2349 by the path to the file.
2350 function A Lisp function, which will be called with two arguments:
2351 the file path and the original link string, without the
2352 \"file:\" prefix.
2354 For more examples, see the system specific constants
2355 `org-file-apps-defaults-macosx'
2356 `org-file-apps-defaults-windowsnt'
2357 `org-file-apps-defaults-gnu'."
2358 :group 'org-link-follow
2359 :type '(repeat
2360 (cons (choice :value ""
2361 (string :tag "Extension")
2362 (const :tag "System command to open files" system)
2363 (const :tag "Default for unrecognized files" t)
2364 (const :tag "Remote file" remote)
2365 (const :tag "Links to a directory" directory)
2366 (const :tag "Any files that have Emacs modes"
2367 auto-mode))
2368 (choice :value ""
2369 (const :tag "Visit with Emacs" emacs)
2370 (const :tag "Use default" default)
2371 (const :tag "Use the system command" system)
2372 (string :tag "Command")
2373 (function :tag "Function")))))
2375 (defcustom org-doi-server-url "http://dx.doi.org/"
2376 "The URL of the DOI server."
2377 :type 'string
2378 :version "24.3"
2379 :group 'org-link-follow)
2381 (defgroup org-refile nil
2382 "Options concerning refiling entries in Org mode."
2383 :tag "Org Refile"
2384 :group 'org)
2386 (defcustom org-directory "~/org"
2387 "Directory with Org files.
2388 This is just a default location to look for Org files. There is no need
2389 at all to put your files into this directory. It is used in the
2390 following situations:
2392 1. When a capture template specifies a target file that is not an
2393 absolute path. The path will then be interpreted relative to
2394 `org-directory'
2395 2. When the value of variable `org-agenda-files' is a single file, any
2396 relative paths in this file will be taken as relative to
2397 `org-directory'."
2398 :group 'org-refile
2399 :group 'org-capture
2400 :type 'directory)
2402 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2403 "Default target for storing notes.
2404 Used as a fall back file for org-capture.el, for templates that
2405 do not specify a target file."
2406 :group 'org-refile
2407 :group 'org-capture
2408 :type 'file)
2410 (defcustom org-goto-interface 'outline
2411 "The default interface to be used for `org-goto'.
2412 Allowed values are:
2413 outline The interface shows an outline of the relevant file
2414 and the correct heading is found by moving through
2415 the outline or by searching with incremental search.
2416 outline-path-completion Headlines in the current buffer are offered via
2417 completion. This is the interface also used by
2418 the refile command."
2419 :group 'org-refile
2420 :type '(choice
2421 (const :tag "Outline" outline)
2422 (const :tag "Outline-path-completion" outline-path-completion)))
2424 (defcustom org-goto-max-level 5
2425 "Maximum target level when running `org-goto' with refile interface."
2426 :group 'org-refile
2427 :type 'integer)
2429 (defcustom org-reverse-note-order nil
2430 "Non-nil means store new notes at the beginning of a file or entry.
2431 When nil, new notes will be filed to the end of a file or entry.
2432 This can also be a list with cons cells of regular expressions that
2433 are matched against file names, and values."
2434 :group 'org-capture
2435 :group 'org-refile
2436 :type '(choice
2437 (const :tag "Reverse always" t)
2438 (const :tag "Reverse never" nil)
2439 (repeat :tag "By file name regexp"
2440 (cons regexp boolean))))
2442 (defcustom org-log-refile nil
2443 "Information to record when a task is refiled.
2445 Possible values are:
2447 nil Don't add anything
2448 time Add a time stamp to the task
2449 note Prompt for a note and add it with template `org-log-note-headings'
2451 This option can also be set with on a per-file-basis with
2453 #+STARTUP: nologrefile
2454 #+STARTUP: logrefile
2455 #+STARTUP: lognoterefile
2457 You can have local logging settings for a subtree by setting the LOGGING
2458 property to one or more of these keywords.
2460 When bulk-refiling from the agenda, the value `note' is forbidden and
2461 will temporarily be changed to `time'."
2462 :group 'org-refile
2463 :group 'org-progress
2464 :version "24.1"
2465 :type '(choice
2466 (const :tag "No logging" nil)
2467 (const :tag "Record timestamp" time)
2468 (const :tag "Record timestamp with note." note)))
2470 (defcustom org-refile-targets nil
2471 "Targets for refiling entries with `\\[org-refile]'.
2472 This is a list of cons cells. Each cell contains:
2473 - a specification of the files to be considered, either a list of files,
2474 or a symbol whose function or variable value will be used to retrieve
2475 a file name or a list of file names. If you use `org-agenda-files' for
2476 that, all agenda files will be scanned for targets. Nil means consider
2477 headings in the current buffer.
2478 - A specification of how to find candidate refile targets. This may be
2479 any of:
2480 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2481 This tag has to be present in all target headlines, inheritance will
2482 not be considered.
2483 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2484 todo keyword.
2485 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2486 headlines that are refiling targets.
2487 - a cons cell (:level . N). Any headline of level N is considered a target.
2488 Note that, when `org-odd-levels-only' is set, level corresponds to
2489 order in hierarchy, not to the number of stars.
2490 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2491 Note that, when `org-odd-levels-only' is set, level corresponds to
2492 order in hierarchy, not to the number of stars.
2494 Each element of this list generates a set of possible targets.
2495 The union of these sets is presented (with completion) to
2496 the user by `org-refile'.
2498 You can set the variable `org-refile-target-verify-function' to a function
2499 to verify each headline found by the simple criteria above.
2501 When this variable is nil, all top-level headlines in the current buffer
2502 are used, equivalent to the value `((nil . (:level . 1))'."
2503 :group 'org-refile
2504 :type '(repeat
2505 (cons
2506 (choice :value org-agenda-files
2507 (const :tag "All agenda files" org-agenda-files)
2508 (const :tag "Current buffer" nil)
2509 (function) (variable) (file))
2510 (choice :tag "Identify target headline by"
2511 (cons :tag "Specific tag" (const :value :tag) (string))
2512 (cons :tag "TODO keyword" (const :value :todo) (string))
2513 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2514 (cons :tag "Level number" (const :value :level) (integer))
2515 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2517 (defcustom org-refile-target-verify-function nil
2518 "Function to verify if the headline at point should be a refile target.
2519 The function will be called without arguments, with point at the
2520 beginning of the headline. It should return t and leave point
2521 where it is if the headline is a valid target for refiling.
2523 If the target should not be selected, the function must return nil.
2524 In addition to this, it may move point to a place from where the search
2525 should be continued. For example, the function may decide that the entire
2526 subtree of the current entry should be excluded and move point to the end
2527 of the subtree."
2528 :group 'org-refile
2529 :type '(choice
2530 (const nil)
2531 (function)))
2533 (defcustom org-refile-use-cache nil
2534 "Non-nil means cache refile targets to speed up the process.
2535 \\<org-mode-map>\
2536 The cache for a particular file will be updated automatically when
2537 the buffer has been killed, or when any of the marker used for flagging
2538 refile targets no longer points at a live buffer.
2539 If you have added new entries to a buffer that might themselves be targets,
2540 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2541 if you find that easier, \
2542 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2543 \\[org-refile]'."
2544 :group 'org-refile
2545 :version "24.1"
2546 :type 'boolean)
2548 (defcustom org-refile-use-outline-path nil
2549 "Non-nil means provide refile targets as paths.
2550 So a level 3 headline will be available as level1/level2/level3.
2552 When the value is `file', also include the file name (without directory)
2553 into the path. In this case, you can also stop the completion after
2554 the file name, to get entries inserted as top level in the file.
2556 When `full-file-path', include the full file path."
2557 :group 'org-refile
2558 :type '(choice
2559 (const :tag "Not" nil)
2560 (const :tag "Yes" t)
2561 (const :tag "Start with file name" file)
2562 (const :tag "Start with full file path" full-file-path)))
2564 (defcustom org-outline-path-complete-in-steps t
2565 "Non-nil means complete the outline path in hierarchical steps.
2566 When Org uses the refile interface to select an outline path (see
2567 `org-refile-use-outline-path'), the completion of the path can be
2568 done in a single go, or it can be done in steps down the headline
2569 hierarchy. Going in steps is probably the best if you do not use
2570 a special completion package like `ido' or `icicles'. However,
2571 when using these packages, going in one step can be very fast,
2572 while still showing the whole path to the entry."
2573 :group 'org-refile
2574 :type 'boolean)
2576 (defcustom org-refile-allow-creating-parent-nodes nil
2577 "Non-nil means allow the creation of new nodes as refile targets.
2578 New nodes are then created by adding \"/new node name\" to the completion
2579 of an existing node. When the value of this variable is `confirm',
2580 new node creation must be confirmed by the user (recommended).
2581 When nil, the completion must match an existing entry.
2583 Note that, if the new heading is not seen by the criteria
2584 listed in `org-refile-targets', multiple instances of the same
2585 heading would be created by trying again to file under the new
2586 heading."
2587 :group 'org-refile
2588 :type '(choice
2589 (const :tag "Never" nil)
2590 (const :tag "Always" t)
2591 (const :tag "Prompt for confirmation" confirm)))
2593 (defcustom org-refile-active-region-within-subtree nil
2594 "Non-nil means also refile active region within a subtree.
2596 By default `org-refile' doesn't allow refiling regions if they
2597 don't contain a set of subtrees, but it might be convenient to
2598 do so sometimes: in that case, the first line of the region is
2599 converted to a headline before refiling."
2600 :group 'org-refile
2601 :version "24.1"
2602 :type 'boolean)
2604 (defgroup org-todo nil
2605 "Options concerning TODO items in Org mode."
2606 :tag "Org TODO"
2607 :group 'org)
2609 (defgroup org-progress nil
2610 "Options concerning Progress logging in Org mode."
2611 :tag "Org Progress"
2612 :group 'org-time)
2614 (defvar org-todo-interpretation-widgets
2615 '((:tag "Sequence (cycling hits every state)" sequence)
2616 (:tag "Type (cycling directly to DONE)" type))
2617 "The available interpretation symbols for customizing `org-todo-keywords'.
2618 Interested libraries should add to this list.")
2620 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2621 "List of TODO entry keyword sequences and their interpretation.
2622 \\<org-mode-map>This is a list of sequences.
2624 Each sequence starts with a symbol, either `sequence' or `type',
2625 indicating if the keywords should be interpreted as a sequence of
2626 action steps, or as different types of TODO items. The first
2627 keywords are states requiring action - these states will select a headline
2628 for inclusion into the global TODO list Org produces. If one of the
2629 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2630 signify that no further action is necessary. If \"|\" is not found,
2631 the last keyword is treated as the only DONE state of the sequence.
2633 The command `\\[org-todo]' cycles an entry through these states, and one
2634 additional state where no keyword is present. For details about this
2635 cycling, see the manual.
2637 TODO keywords and interpretation can also be set on a per-file basis with
2638 the special #+SEQ_TODO and #+TYP_TODO lines.
2640 Each keyword can optionally specify a character for fast state selection
2641 \(in combination with the variable `org-use-fast-todo-selection')
2642 and specifiers for state change logging, using the same syntax that
2643 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2644 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2645 indicates to record a time stamp each time this state is selected.
2647 Each keyword may also specify if a timestamp or a note should be
2648 recorded when entering or leaving the state, by adding additional
2649 characters in the parenthesis after the keyword. This looks like this:
2650 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2651 record only the time of the state change. With X and Y being either
2652 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2653 Y when leaving the state if and only if the *target* state does not
2654 define X. You may omit any of the fast-selection key or X or /Y,
2655 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2657 For backward compatibility, this variable may also be just a list
2658 of keywords. In this case the interpretation (sequence or type) will be
2659 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2660 :group 'org-todo
2661 :group 'org-keywords
2662 :type '(choice
2663 (repeat :tag "Old syntax, just keywords"
2664 (string :tag "Keyword"))
2665 (repeat :tag "New syntax"
2666 (cons
2667 (choice
2668 :tag "Interpretation"
2669 ;;Quick and dirty way to see
2670 ;;`org-todo-interpretations'. This takes the
2671 ;;place of item arguments
2672 :convert-widget
2673 (lambda (widget)
2674 (widget-put widget
2675 :args (mapcar
2676 (lambda (x)
2677 (widget-convert
2678 (cons 'const x)))
2679 org-todo-interpretation-widgets))
2680 widget))
2681 (repeat
2682 (string :tag "Keyword"))))))
2684 (defvar-local org-todo-keywords-1 nil
2685 "All TODO and DONE keywords active in a buffer.")
2686 (defvar org-todo-keywords-for-agenda nil)
2687 (defvar org-done-keywords-for-agenda nil)
2688 (defvar org-todo-keyword-alist-for-agenda nil)
2689 (defvar org-tag-alist-for-agenda nil
2690 "Alist of all tags from all agenda files.")
2691 (defvar org-tag-groups-alist-for-agenda nil
2692 "Alist of all groups tags from all current agenda files.")
2693 (defvar-local org-tag-groups-alist nil)
2694 (defvar org-agenda-contributing-files nil)
2695 (defvar-local org-current-tag-alist nil
2696 "Alist of all tag groups in current buffer.
2697 This variable takes into consideration `org-tag-alist',
2698 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2699 (defvar-local org-not-done-keywords nil)
2700 (defvar-local org-done-keywords nil)
2701 (defvar-local org-todo-heads nil)
2702 (defvar-local org-todo-sets nil)
2703 (defvar-local org-todo-log-states nil)
2704 (defvar-local org-todo-kwd-alist nil)
2705 (defvar-local org-todo-key-alist nil)
2706 (defvar-local org-todo-key-trigger nil)
2708 (defcustom org-todo-interpretation 'sequence
2709 "Controls how TODO keywords are interpreted.
2710 This variable is in principle obsolete and is only used for
2711 backward compatibility, if the interpretation of todo keywords is
2712 not given already in `org-todo-keywords'. See that variable for
2713 more information."
2714 :group 'org-todo
2715 :group 'org-keywords
2716 :type '(choice (const sequence)
2717 (const type)))
2719 (defcustom org-use-fast-todo-selection t
2720 "\\<org-mode-map>\
2721 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2722 This variable describes if and under what circumstances the cycling
2723 mechanism for TODO keywords will be replaced by a single-key, direct
2724 selection scheme.
2726 When nil, fast selection is never used.
2728 When the symbol `prefix', it will be used when `org-todo' is called
2729 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2730 in an Org buffer, and
2731 `\\[universal-argument] t' in an agenda buffer.
2733 When t, fast selection is used by default. In this case, the prefix
2734 argument forces cycling instead.
2736 In all cases, the special interface is only used if access keys have
2737 actually been assigned by the user, i.e. if keywords in the configuration
2738 are followed by a letter in parenthesis, like TODO(t)."
2739 :group 'org-todo
2740 :type '(choice
2741 (const :tag "Never" nil)
2742 (const :tag "By default" t)
2743 (const :tag "Only with C-u C-c C-t" prefix)))
2745 (defcustom org-provide-todo-statistics t
2746 "Non-nil means update todo statistics after insert and toggle.
2747 ALL-HEADLINES means update todo statistics by including headlines
2748 with no TODO keyword as well, counting them as not done.
2749 A list of TODO keywords means the same, but skip keywords that are
2750 not in this list.
2751 When set to a list of two lists, the first list contains keywords
2752 to consider as TODO keywords, the second list contains keywords
2753 to consider as DONE keywords.
2755 When this is set, todo statistics is updated in the parent of the
2756 current entry each time a todo state is changed."
2757 :group 'org-todo
2758 :type '(choice
2759 (const :tag "Yes, only for TODO entries" t)
2760 (const :tag "Yes, including all entries" all-headlines)
2761 (repeat :tag "Yes, for TODOs in this list"
2762 (string :tag "TODO keyword"))
2763 (list :tag "Yes, for TODOs and DONEs in these lists"
2764 (repeat (string :tag "TODO keyword"))
2765 (repeat (string :tag "DONE keyword")))
2766 (other :tag "No TODO statistics" nil)))
2768 (defcustom org-hierarchical-todo-statistics t
2769 "Non-nil means TODO statistics covers just direct children.
2770 When nil, all entries in the subtree are considered.
2771 This has only an effect if `org-provide-todo-statistics' is set.
2772 To set this to nil for only a single subtree, use a COOKIE_DATA
2773 property and include the word \"recursive\" into the value."
2774 :group 'org-todo
2775 :type 'boolean)
2777 (defcustom org-after-todo-state-change-hook nil
2778 "Hook which is run after the state of a TODO item was changed.
2779 The new state (a string with a TODO keyword, or nil) is available in the
2780 Lisp variable `org-state'."
2781 :group 'org-todo
2782 :type 'hook)
2784 (defvar org-blocker-hook nil
2785 "Hook for functions that are allowed to block a state change.
2787 Functions in this hook should not modify the buffer.
2788 Each function gets as its single argument a property list,
2789 see `org-trigger-hook' for more information about this list.
2791 If any of the functions in this hook returns nil, the state change
2792 is blocked.")
2794 (defvar org-trigger-hook nil
2795 "Hook for functions that are triggered by a state change.
2797 Each function gets as its single argument a property list with at
2798 least the following elements:
2800 (:type type-of-change :position pos-at-entry-start
2801 :from old-state :to new-state)
2803 Depending on the type, more properties may be present.
2805 This mechanism is currently implemented for:
2807 TODO state changes
2808 ------------------
2809 :type todo-state-change
2810 :from previous state (keyword as a string), or nil, or a symbol
2811 `todo' or `done', to indicate the general type of state.
2812 :to new state, like in :from")
2814 (defcustom org-enforce-todo-dependencies nil
2815 "Non-nil means undone TODO entries will block switching the parent to DONE.
2816 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2817 be blocked if any prior sibling is not yet done.
2818 Finally, if the parent is blocked because of ordered siblings of its own,
2819 the child will also be blocked."
2820 :set (lambda (var val)
2821 (set var val)
2822 (if val
2823 (add-hook 'org-blocker-hook
2824 'org-block-todo-from-children-or-siblings-or-parent)
2825 (remove-hook 'org-blocker-hook
2826 'org-block-todo-from-children-or-siblings-or-parent)))
2827 :group 'org-todo
2828 :type 'boolean)
2830 (defcustom org-enforce-todo-checkbox-dependencies nil
2831 "Non-nil means unchecked boxes will block switching the parent to DONE.
2832 When this is nil, checkboxes have no influence on switching TODO states.
2833 When non-nil, you first need to check off all check boxes before the TODO
2834 entry can be switched to DONE.
2835 This variable needs to be set before org.el is loaded, and you need to
2836 restart Emacs after a change to make the change effective. The only way
2837 to change is while Emacs is running is through the customize interface."
2838 :set (lambda (var val)
2839 (set var val)
2840 (if val
2841 (add-hook 'org-blocker-hook
2842 'org-block-todo-from-checkboxes)
2843 (remove-hook 'org-blocker-hook
2844 'org-block-todo-from-checkboxes)))
2845 :group 'org-todo
2846 :type 'boolean)
2848 (defcustom org-treat-insert-todo-heading-as-state-change nil
2849 "Non-nil means inserting a TODO heading is treated as state change.
2850 So when the command `\\[org-insert-todo-heading]' is used, state change
2851 logging will apply if appropriate. When nil, the new TODO item will
2852 be inserted directly, and no logging will take place."
2853 :group 'org-todo
2854 :type 'boolean)
2856 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2857 "Non-nil means switching TODO states with S-cursor counts as state change.
2858 This is the default behavior. However, setting this to nil allows a
2859 convenient way to select a TODO state and bypass any logging associated
2860 with that."
2861 :group 'org-todo
2862 :type 'boolean)
2864 (defcustom org-todo-state-tags-triggers nil
2865 "Tag changes that should be triggered by TODO state changes.
2866 This is a list. Each entry is
2868 (state-change (tag . flag) .......)
2870 State-change can be a string with a state, and empty string to indicate the
2871 state that has no TODO keyword, or it can be one of the symbols `todo'
2872 or `done', meaning any not-done or done state, respectively."
2873 :group 'org-todo
2874 :group 'org-tags
2875 :type '(repeat
2876 (cons (choice :tag "When changing to"
2877 (const :tag "Not-done state" todo)
2878 (const :tag "Done state" done)
2879 (string :tag "State"))
2880 (repeat
2881 (cons :tag "Tag action"
2882 (string :tag "Tag")
2883 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2885 (defcustom org-log-done nil
2886 "Information to record when a task moves to the DONE state.
2888 Possible values are:
2890 nil Don't add anything, just change the keyword
2891 time Add a time stamp to the task
2892 note Prompt for a note and add it with template `org-log-note-headings'
2894 This option can also be set with on a per-file-basis with
2896 #+STARTUP: nologdone
2897 #+STARTUP: logdone
2898 #+STARTUP: lognotedone
2900 You can have local logging settings for a subtree by setting the LOGGING
2901 property to one or more of these keywords."
2902 :group 'org-todo
2903 :group 'org-progress
2904 :type '(choice
2905 (const :tag "No logging" nil)
2906 (const :tag "Record CLOSED timestamp" time)
2907 (const :tag "Record CLOSED timestamp with note." note)))
2909 ;; Normalize old uses of org-log-done.
2910 (cond
2911 ((eq org-log-done t) (setq org-log-done 'time))
2912 ((and (listp org-log-done) (memq 'done org-log-done))
2913 (setq org-log-done 'note)))
2915 (defcustom org-log-reschedule nil
2916 "Information to record when the scheduling date of a tasks is modified.
2918 Possible values are:
2920 nil Don't add anything, just change the date
2921 time Add a time stamp to the task
2922 note Prompt for a note and add it with template `org-log-note-headings'
2924 This option can also be set with on a per-file-basis with
2926 #+STARTUP: nologreschedule
2927 #+STARTUP: logreschedule
2928 #+STARTUP: lognotereschedule"
2929 :group 'org-todo
2930 :group 'org-progress
2931 :type '(choice
2932 (const :tag "No logging" nil)
2933 (const :tag "Record timestamp" time)
2934 (const :tag "Record timestamp with note." note)))
2936 (defcustom org-log-redeadline nil
2937 "Information to record when the deadline date of a tasks is modified.
2939 Possible values are:
2941 nil Don't add anything, just change the date
2942 time Add a time stamp to the task
2943 note Prompt for a note and add it with template `org-log-note-headings'
2945 This option can also be set with on a per-file-basis with
2947 #+STARTUP: nologredeadline
2948 #+STARTUP: logredeadline
2949 #+STARTUP: lognoteredeadline
2951 You can have local logging settings for a subtree by setting the LOGGING
2952 property to one or more of these keywords."
2953 :group 'org-todo
2954 :group 'org-progress
2955 :type '(choice
2956 (const :tag "No logging" nil)
2957 (const :tag "Record timestamp" time)
2958 (const :tag "Record timestamp with note." note)))
2960 (defcustom org-log-note-clock-out nil
2961 "Non-nil means record a note when clocking out of an item.
2962 This can also be configured on a per-file basis by adding one of
2963 the following lines anywhere in the buffer:
2965 #+STARTUP: lognoteclock-out
2966 #+STARTUP: nolognoteclock-out"
2967 :group 'org-todo
2968 :group 'org-progress
2969 :type 'boolean)
2971 (defcustom org-log-done-with-time t
2972 "Non-nil means the CLOSED time stamp will contain date and time.
2973 When nil, only the date will be recorded."
2974 :group 'org-progress
2975 :type 'boolean)
2977 (defcustom org-log-note-headings
2978 '((done . "CLOSING NOTE %t")
2979 (state . "State %-12s from %-12S %t")
2980 (note . "Note taken on %t")
2981 (reschedule . "Rescheduled from %S on %t")
2982 (delschedule . "Not scheduled, was %S on %t")
2983 (redeadline . "New deadline from %S on %t")
2984 (deldeadline . "Removed deadline, was %S on %t")
2985 (refile . "Refiled on %t")
2986 (clock-out . ""))
2987 "Headings for notes added to entries.
2989 The value is an alist, with the car being a symbol indicating the
2990 note context, and the cdr is the heading to be used. The heading
2991 may also be the empty string. The following placeholders can be
2992 used:
2994 %t a time stamp.
2995 %T an active time stamp instead the default inactive one
2996 %d a short-format time stamp.
2997 %D an active short-format time stamp.
2998 %s the new TODO state or time stamp (inactive), in double quotes.
2999 %S the old TODO state or time stamp (inactive), in double quotes.
3000 %u the user name.
3001 %U full user name.
3003 In fact, it is not a good idea to change the `state' entry,
3004 because Agenda Log mode depends on the format of these entries."
3005 :group 'org-todo
3006 :group 'org-progress
3007 :type '(list :greedy t
3008 (cons (const :tag "Heading when closing an item" done) string)
3009 (cons (const :tag
3010 "Heading when changing todo state (todo sequence only)"
3011 state) string)
3012 (cons (const :tag "Heading when just taking a note" note) string)
3013 (cons (const :tag "Heading when rescheduling" reschedule) string)
3014 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3015 (cons (const :tag "Heading when changing deadline" redeadline) string)
3016 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3017 (cons (const :tag "Heading when refiling" refile) string)
3018 (cons (const :tag "Heading when clocking out" clock-out) string)))
3020 (unless (assq 'note org-log-note-headings)
3021 (push '(note . "%t") org-log-note-headings))
3023 (defcustom org-log-into-drawer nil
3024 "Non-nil means insert state change notes and time stamps into a drawer.
3025 When nil, state changes notes will be inserted after the headline and
3026 any scheduling and clock lines, but not inside a drawer.
3028 The value of this variable should be the name of the drawer to use.
3029 LOGBOOK is proposed as the default drawer for this purpose, you can
3030 also set this to a string to define the drawer of your choice.
3032 A value of t is also allowed, representing \"LOGBOOK\".
3034 A value of t or nil can also be set with on a per-file-basis with
3036 #+STARTUP: logdrawer
3037 #+STARTUP: nologdrawer
3039 If this variable is set, `org-log-state-notes-insert-after-drawers'
3040 will be ignored.
3042 You can set the property LOG_INTO_DRAWER to overrule this setting for
3043 a subtree.
3045 Do not check directly this variable in a Lisp program. Call
3046 function `org-log-into-drawer' instead."
3047 :group 'org-todo
3048 :group 'org-progress
3049 :type '(choice
3050 (const :tag "Not into a drawer" nil)
3051 (const :tag "LOGBOOK" t)
3052 (string :tag "Other")))
3054 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3056 (defun org-log-into-drawer ()
3057 "Name of the log drawer, as a string, or nil.
3058 This is the value of `org-log-into-drawer'. However, if the
3059 current entry has or inherits a LOG_INTO_DRAWER property, it will
3060 be used instead of the default value."
3061 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3062 (cond ((equal p "nil") nil)
3063 ((equal p "t") "LOGBOOK")
3064 ((stringp p) p)
3065 (p "LOGBOOK")
3066 ((stringp org-log-into-drawer) org-log-into-drawer)
3067 (org-log-into-drawer "LOGBOOK"))))
3069 (defcustom org-log-state-notes-insert-after-drawers nil
3070 "Non-nil means insert state change notes after any drawers in entry.
3071 Only the drawers that *immediately* follow the headline and the
3072 deadline/scheduled line are skipped.
3073 When nil, insert notes right after the heading and perhaps the line
3074 with deadline/scheduling if present.
3076 This variable will have no effect if `org-log-into-drawer' is
3077 set."
3078 :group 'org-todo
3079 :group 'org-progress
3080 :type 'boolean)
3082 (defcustom org-log-states-order-reversed t
3083 "Non-nil means the latest state note will be directly after heading.
3084 When nil, the state change notes will be ordered according to time.
3086 This option can also be set with on a per-file-basis with
3088 #+STARTUP: logstatesreversed
3089 #+STARTUP: nologstatesreversed"
3090 :group 'org-todo
3091 :group 'org-progress
3092 :type 'boolean)
3094 (defcustom org-todo-repeat-to-state nil
3095 "The TODO state to which a repeater should return the repeating task.
3096 By default this is the first task in a TODO sequence, or the previous state
3097 in a TODO_TYP set. But you can specify another task here.
3098 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3099 :group 'org-todo
3100 :version "24.1"
3101 :type '(choice (const :tag "Head of sequence" nil)
3102 (string :tag "Specific state")))
3104 (defcustom org-log-repeat 'time
3105 "Non-nil means record moving through the DONE state when triggering repeat.
3106 An auto-repeating task is immediately switched back to TODO when
3107 marked DONE. If you are not logging state changes (by adding \"@\"
3108 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3109 record a closing note, there will be no record of the task moving
3110 through DONE. This variable forces taking a note anyway.
3112 nil Don't force a record
3113 time Record a time stamp
3114 note Prompt for a note and add it with template `org-log-note-headings'
3116 This option can also be set with on a per-file-basis with
3118 #+STARTUP: nologrepeat
3119 #+STARTUP: logrepeat
3120 #+STARTUP: lognoterepeat
3122 You can have local logging settings for a subtree by setting the LOGGING
3123 property to one or more of these keywords."
3124 :group 'org-todo
3125 :group 'org-progress
3126 :type '(choice
3127 (const :tag "Don't force a record" nil)
3128 (const :tag "Force recording the DONE state" time)
3129 (const :tag "Force recording a note with the DONE state" note)))
3132 (defgroup org-priorities nil
3133 "Priorities in Org mode."
3134 :tag "Org Priorities"
3135 :group 'org-todo)
3137 (defcustom org-enable-priority-commands t
3138 "Non-nil means priority commands are active.
3139 When nil, these commands will be disabled, so that you never accidentally
3140 set a priority."
3141 :group 'org-priorities
3142 :type 'boolean)
3144 (defcustom org-highest-priority ?A
3145 "The highest priority of TODO items. A character like ?A, ?B etc.
3146 Must have a smaller ASCII number than `org-lowest-priority'."
3147 :group 'org-priorities
3148 :type 'character)
3150 (defcustom org-lowest-priority ?C
3151 "The lowest priority of TODO items. A character like ?A, ?B etc.
3152 Must have a larger ASCII number than `org-highest-priority'."
3153 :group 'org-priorities
3154 :type 'character)
3156 (defcustom org-default-priority ?B
3157 "The default priority of TODO items.
3158 This is the priority an item gets if no explicit priority is given.
3159 When starting to cycle on an empty priority the first step in the cycle
3160 depends on `org-priority-start-cycle-with-default'. The resulting first
3161 step priority must not exceed the range from `org-highest-priority' to
3162 `org-lowest-priority' which means that `org-default-priority' has to be
3163 in this range exclusive or inclusive the range boundaries. Else the
3164 first step refuses to set the default and the second will fall back
3165 to (depending on the command used) the highest or lowest priority."
3166 :group 'org-priorities
3167 :type 'character)
3169 (defcustom org-priority-start-cycle-with-default t
3170 "Non-nil means start with default priority when starting to cycle.
3171 When this is nil, the first step in the cycle will be (depending on the
3172 command used) one higher or lower than the default priority.
3173 See also `org-default-priority'."
3174 :group 'org-priorities
3175 :type 'boolean)
3177 (defcustom org-get-priority-function nil
3178 "Function to extract the priority from a string.
3179 The string is normally the headline. If this is nil Org computes the
3180 priority from the priority cookie like [#A] in the headline. It returns
3181 an integer, increasing by 1000 for each priority level.
3182 The user can set a different function here, which should take a string
3183 as an argument and return the numeric priority."
3184 :group 'org-priorities
3185 :version "24.1"
3186 :type '(choice
3187 (const nil)
3188 (function)))
3190 (defgroup org-time nil
3191 "Options concerning time stamps and deadlines in Org mode."
3192 :tag "Org Time"
3193 :group 'org)
3195 (defcustom org-time-stamp-rounding-minutes '(0 5)
3196 "Number of minutes to round time stamps to.
3197 \\<org-mode-map>\
3198 These are two values, the first applies when first creating a time stamp.
3199 The second applies when changing it with the commands `S-up' and `S-down'.
3200 When changing the time stamp, this means that it will change in steps
3201 of N minutes, as given by the second value.
3203 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3204 numbers should be factors of 60, so for example 5, 10, 15.
3206 When this is larger than 1, you can still force an exact time stamp by using
3207 a double prefix argument to a time stamp command like \
3208 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3209 and by using a prefix arg to `S-up/down' to specify the exact number
3210 of minutes to shift."
3211 :group 'org-time
3212 :get (lambda (var) ; Make sure both elements are there
3213 (if (integerp (default-value var))
3214 (list (default-value var) 5)
3215 (default-value var)))
3216 :type '(list
3217 (integer :tag "when inserting times")
3218 (integer :tag "when modifying times")))
3220 ;; Normalize old customizations of this variable.
3221 (when (integerp org-time-stamp-rounding-minutes)
3222 (setq org-time-stamp-rounding-minutes
3223 (list org-time-stamp-rounding-minutes
3224 org-time-stamp-rounding-minutes)))
3226 (defcustom org-display-custom-times nil
3227 "Non-nil means overlay custom formats over all time stamps.
3228 The formats are defined through the variable `org-time-stamp-custom-formats'.
3229 To turn this on on a per-file basis, insert anywhere in the file:
3230 #+STARTUP: customtime"
3231 :group 'org-time
3232 :set 'set-default
3233 :type 'sexp)
3234 (make-variable-buffer-local 'org-display-custom-times)
3236 (defcustom org-time-stamp-custom-formats
3237 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3238 "Custom formats for time stamps. See `format-time-string' for the syntax.
3239 These are overlaid over the default ISO format if the variable
3240 `org-display-custom-times' is set. Time like %H:%M should be at the
3241 end of the second format. The custom formats are also honored by export
3242 commands, if custom time display is turned on at the time of export."
3243 :group 'org-time
3244 :type 'sexp)
3246 (defun org-time-stamp-format (&optional long inactive)
3247 "Get the right format for a time string."
3248 (let ((f (if long (cdr org-time-stamp-formats)
3249 (car org-time-stamp-formats))))
3250 (if inactive
3251 (concat "[" (substring f 1 -1) "]")
3252 f)))
3254 (defcustom org-time-clocksum-format
3255 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3256 "The format string used when creating CLOCKSUM lines.
3257 This is also used when Org mode generates a time duration.
3259 The value can be a single format string containing two
3260 %-sequences, which will be filled with the number of hours and
3261 minutes in that order.
3263 Alternatively, the value can be a plist associating any of the
3264 keys :years, :months, :weeks, :days, :hours or :minutes with
3265 format strings. The time duration is formatted using only the
3266 time components that are needed and concatenating the results.
3267 If a time unit in absent, it falls back to the next smallest
3268 unit.
3270 The keys :require-years, :require-months, :require-days,
3271 :require-weeks, :require-hours, :require-minutes are also
3272 meaningful. A non-nil value for these keys indicates that the
3273 corresponding time component should always be included, even if
3274 its value is 0.
3277 For example,
3279 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3280 :require-minutes t)
3282 means durations longer than a day will be expressed in days,
3283 hours and minutes, and durations less than a day will always be
3284 expressed in hours and minutes (even for durations less than an
3285 hour).
3287 The value
3289 (:days \"%dd\" :minutes \"%dm\")
3291 means durations longer than a day will be expressed in days and
3292 minutes, and durations less than a day will be expressed entirely
3293 in minutes (even for durations longer than an hour)."
3294 :group 'org-time
3295 :group 'org-clock
3296 :version "24.4"
3297 :package-version '(Org . "8.0")
3298 :type '(choice (string :tag "Format string")
3299 (set :tag "Plist"
3300 (group :inline t (const :tag "Years" :years)
3301 (string :tag "Format string"))
3302 (group :inline t
3303 (const :tag "Always show years" :require-years)
3304 (const t))
3305 (group :inline t (const :tag "Months" :months)
3306 (string :tag "Format string"))
3307 (group :inline t
3308 (const :tag "Always show months" :require-months)
3309 (const t))
3310 (group :inline t (const :tag "Weeks" :weeks)
3311 (string :tag "Format string"))
3312 (group :inline t
3313 (const :tag "Always show weeks" :require-weeks)
3314 (const t))
3315 (group :inline t (const :tag "Days" :days)
3316 (string :tag "Format string"))
3317 (group :inline t
3318 (const :tag "Always show days" :require-days)
3319 (const t))
3320 (group :inline t (const :tag "Hours" :hours)
3321 (string :tag "Format string"))
3322 (group :inline t
3323 (const :tag "Always show hours" :require-hours)
3324 (const t))
3325 (group :inline t (const :tag "Minutes" :minutes)
3326 (string :tag "Format string"))
3327 (group :inline t
3328 (const :tag "Always show minutes" :require-minutes)
3329 (const t)))))
3331 (defcustom org-time-clocksum-use-fractional nil
3332 "When non-nil, `\\[org-clock-display]' uses fractional times.
3333 See `org-time-clocksum-format' for more on time clock formats."
3334 :group 'org-time
3335 :group 'org-clock
3336 :version "24.3"
3337 :type 'boolean)
3339 (defcustom org-time-clocksum-use-effort-durations nil
3340 "When non-nil, `\\[org-clock-display]' uses effort durations.
3341 E.g. by default, one day is considered to be a 8 hours effort,
3342 so a task that has been clocked for 16 hours will be displayed
3343 as during 2 days in the clock display or in the clocktable.
3345 See `org-effort-durations' on how to set effort durations
3346 and `org-time-clocksum-format' for more on time clock formats."
3347 :group 'org-time
3348 :group 'org-clock
3349 :version "24.4"
3350 :package-version '(Org . "8.0")
3351 :type 'boolean)
3353 (defcustom org-time-clocksum-fractional-format "%.2f"
3354 "The format string used when creating CLOCKSUM lines,
3355 or when Org mode generates a time duration, if
3356 `org-time-clocksum-use-fractional' is enabled.
3358 The value can be a single format string containing one
3359 %-sequence, which will be filled with the number of hours as
3360 a float.
3362 Alternatively, the value can be a plist associating any of the
3363 keys :years, :months, :weeks, :days, :hours or :minutes with
3364 a format string. The time duration is formatted using the
3365 largest time unit which gives a non-zero integer part. If all
3366 specified formats have zero integer part, the smallest time unit
3367 is used."
3368 :group 'org-time
3369 :type '(choice (string :tag "Format string")
3370 (set (group :inline t (const :tag "Years" :years)
3371 (string :tag "Format string"))
3372 (group :inline t (const :tag "Months" :months)
3373 (string :tag "Format string"))
3374 (group :inline t (const :tag "Weeks" :weeks)
3375 (string :tag "Format string"))
3376 (group :inline t (const :tag "Days" :days)
3377 (string :tag "Format string"))
3378 (group :inline t (const :tag "Hours" :hours)
3379 (string :tag "Format string"))
3380 (group :inline t (const :tag "Minutes" :minutes)
3381 (string :tag "Format string")))))
3383 (defcustom org-deadline-warning-days 14
3384 "Number of days before expiration during which a deadline becomes active.
3385 This variable governs the display in sparse trees and in the agenda.
3386 When 0 or negative, it means use this number (the absolute value of it)
3387 even if a deadline has a different individual lead time specified.
3389 Custom commands can set this variable in the options section."
3390 :group 'org-time
3391 :group 'org-agenda-daily/weekly
3392 :type 'integer)
3394 (defcustom org-scheduled-delay-days 0
3395 "Number of days before a scheduled item becomes active.
3396 This variable governs the display in sparse trees and in the agenda.
3397 The default value (i.e. 0) means: don't delay scheduled item.
3398 When negative, it means use this number (the absolute value of it)
3399 even if a scheduled item has a different individual delay time
3400 specified.
3402 Custom commands can set this variable in the options section."
3403 :group 'org-time
3404 :group 'org-agenda-daily/weekly
3405 :version "24.4"
3406 :package-version '(Org . "8.0")
3407 :type 'integer)
3409 (defcustom org-read-date-prefer-future t
3410 "Non-nil means assume future for incomplete date input from user.
3411 This affects the following situations:
3412 1. The user gives a month but not a year.
3413 For example, if it is April and you enter \"feb 2\", this will be read
3414 as Feb 2, *next* year. \"May 5\", however, will be this year.
3415 2. The user gives a day, but no month.
3416 For example, if today is the 15th, and you enter \"3\", Org will read
3417 this as the third of *next* month. However, if you enter \"17\",
3418 it will be considered as *this* month.
3420 If you set this variable to the symbol `time', then also the following
3421 will work:
3423 3. If the user gives a time.
3424 If the time is before now, it will be interpreted as tomorrow.
3426 Currently none of this works for ISO week specifications.
3428 When this option is nil, the current day, month and year will always be
3429 used as defaults.
3431 See also `org-agenda-jump-prefer-future'."
3432 :group 'org-time
3433 :type '(choice
3434 (const :tag "Never" nil)
3435 (const :tag "Check month and day" t)
3436 (const :tag "Check month, day, and time" time)))
3438 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3439 "Should the agenda jump command prefer the future for incomplete dates?
3440 The default is to do the same as configured in `org-read-date-prefer-future'.
3441 But you can also set a deviating value here.
3442 This may t or nil, or the symbol `org-read-date-prefer-future'."
3443 :group 'org-agenda
3444 :group 'org-time
3445 :version "24.1"
3446 :type '(choice
3447 (const :tag "Use org-read-date-prefer-future"
3448 org-read-date-prefer-future)
3449 (const :tag "Never" nil)
3450 (const :tag "Always" t)))
3452 (defcustom org-read-date-force-compatible-dates t
3453 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3455 Depending on the system Emacs is running on, certain dates cannot
3456 be represented with the type used internally to represent time.
3457 Dates between 1970-1-1 and 2038-1-1 can always be represented
3458 correctly. Some systems allow for earlier dates, some for later,
3459 some for both. One way to find out it to insert any date into an
3460 Org buffer, putting the cursor on the year and hitting S-up and
3461 S-down to test the range.
3463 When this variable is set to t, the date/time prompt will not let
3464 you specify dates outside the 1970-2037 range, so it is certain that
3465 these dates will work in whatever version of Emacs you are
3466 running, and also that you can move a file from one Emacs implementation
3467 to another. WHenever Org is forcing the year for you, it will display
3468 a message and beep.
3470 When this variable is nil, Org will check if the date is
3471 representable in the specific Emacs implementation you are using.
3472 If not, it will force a year, usually the current year, and beep
3473 to remind you. Currently this setting is not recommended because
3474 the likelihood that you will open your Org files in an Emacs that
3475 has limited date range is not negligible.
3477 A workaround for this problem is to use diary sexp dates for time
3478 stamps outside of this range."
3479 :group 'org-time
3480 :version "24.1"
3481 :type 'boolean)
3483 (defcustom org-read-date-display-live t
3484 "Non-nil means display current interpretation of date prompt live.
3485 This display will be in an overlay, in the minibuffer."
3486 :group 'org-time
3487 :type 'boolean)
3489 (defcustom org-read-date-popup-calendar t
3490 "Non-nil means pop up a calendar when prompting for a date.
3491 In the calendar, the date can be selected with mouse-1. However, the
3492 minibuffer will also be active, and you can simply enter the date as well.
3493 When nil, only the minibuffer will be available."
3494 :group 'org-time
3495 :type 'boolean)
3496 (defvaralias 'org-popup-calendar-for-date-prompt
3497 'org-read-date-popup-calendar)
3499 (defcustom org-extend-today-until 0
3500 "The hour when your day really ends. Must be an integer.
3501 This has influence for the following applications:
3502 - When switching the agenda to \"today\". It it is still earlier than
3503 the time given here, the day recognized as TODAY is actually yesterday.
3504 - When a date is read from the user and it is still before the time given
3505 here, the current date and time will be assumed to be yesterday, 23:59.
3506 Also, timestamps inserted in capture templates follow this rule.
3508 IMPORTANT: This is a feature whose implementation is and likely will
3509 remain incomplete. Really, it is only here because past midnight seems to
3510 be the favorite working time of John Wiegley :-)"
3511 :group 'org-time
3512 :type 'integer)
3514 (defcustom org-use-effective-time nil
3515 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3516 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3517 \"effective time\" of any timestamps between midnight and 8am will be
3518 23:59 of the previous day."
3519 :group 'org-time
3520 :version "24.1"
3521 :type 'boolean)
3523 (defcustom org-use-last-clock-out-time-as-effective-time nil
3524 "When non-nil, use the last clock out time for `org-todo'.
3525 Note that this option has precedence over the combined use of
3526 `org-use-effective-time' and `org-extend-today-until'."
3527 :group 'org-time
3528 :version "24.4"
3529 :package-version '(Org . "8.0")
3530 :type 'boolean)
3532 (defcustom org-edit-timestamp-down-means-later nil
3533 "Non-nil means S-down will increase the time in a time stamp.
3534 When nil, S-up will increase."
3535 :group 'org-time
3536 :type 'boolean)
3538 (defcustom org-calendar-follow-timestamp-change t
3539 "Non-nil means make the calendar window follow timestamp changes.
3540 When a timestamp is modified and the calendar window is visible, it will be
3541 moved to the new date."
3542 :group 'org-time
3543 :type 'boolean)
3545 (defgroup org-tags nil
3546 "Options concerning tags in Org mode."
3547 :tag "Org Tags"
3548 :group 'org)
3550 (defcustom org-tag-alist nil
3551 "Default tags available in Org files.
3553 The value of this variable is an alist. Associations either:
3555 (TAG)
3556 (TAG . SELECT)
3557 (SPECIAL)
3559 where TAG is a tag as a string, SELECT is character, used to
3560 select that tag through the fast tag selection interface, and
3561 SPECIAL is one of the following keywords: `:startgroup',
3562 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3563 `:newline'. These keywords are used to define a hierarchy of
3564 tags. See manual for details.
3566 When this variable is nil, Org mode bases tag input on what is
3567 already in the buffer. The value can be overridden locally by
3568 using a TAGS keyword, e.g.,
3570 #+TAGS: tag1 tag2
3572 See also `org-tag-persistent-alist' to sidestep this behavior."
3573 :group 'org-tags
3574 :type '(repeat
3575 (choice
3576 (cons (string :tag "Tag name")
3577 (character :tag "Access char"))
3578 (const :tag "Start radio group" (:startgroup))
3579 (const :tag "Start tag group, non distinct" (:startgrouptag))
3580 (const :tag "Group tags delimiter" (:grouptags))
3581 (const :tag "End radio group" (:endgroup))
3582 (const :tag "End tag group, non distinct" (:endgrouptag))
3583 (const :tag "New line" (:newline)))))
3585 (defcustom org-tag-persistent-alist nil
3586 "Tags always available in Org files.
3588 The value of this variable is an alist. Associations either:
3590 (TAG)
3591 (TAG . SELECT)
3592 (SPECIAL)
3594 where TAG is a tag as a string, SELECT is a character, used to
3595 select that tag through the fast tag selection interface, and
3596 SPECIAL is one of the following keywords: `:startgroup',
3597 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3598 `:newline'. These keywords are used to define a hierarchy of
3599 tags. See manual for details.
3601 Unlike to `org-tag-alist', tags defined in this variable do not
3602 depend on a local TAGS keyword. Instead, to disable these tags
3603 on a per-file basis, insert anywhere in the file:
3605 #+STARTUP: noptag"
3606 :group 'org-tags
3607 :type '(repeat
3608 (choice
3609 (cons (string :tag "Tag name")
3610 (character :tag "Access char"))
3611 (const :tag "Start radio group" (:startgroup))
3612 (const :tag "Start tag group, non distinct" (:startgrouptag))
3613 (const :tag "Group tags delimiter" (:grouptags))
3614 (const :tag "End radio group" (:endgroup))
3615 (const :tag "End tag group, non distinct" (:endgrouptag))
3616 (const :tag "New line" (:newline)))))
3618 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3619 "If non-nil, always offer completion for all tags of all agenda files.
3620 Instead of customizing this variable directly, you might want to
3621 set it locally for capture buffers, because there no list of
3622 tags in that file can be created dynamically (there are none).
3624 (add-hook \\='org-capture-mode-hook
3625 (lambda ()
3626 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3627 :group 'org-tags
3628 :version "24.1"
3629 :type 'boolean)
3631 (defvar org-file-tags nil
3632 "List of tags that can be inherited by all entries in the file.
3633 The tags will be inherited if the variable `org-use-tag-inheritance'
3634 says they should be.
3635 This variable is populated from #+FILETAGS lines.")
3637 (defcustom org-use-fast-tag-selection 'auto
3638 "Non-nil means use fast tag selection scheme.
3639 This is a special interface to select and deselect tags with single keys.
3640 When nil, fast selection is never used.
3641 When the symbol `auto', fast selection is used if and only if selection
3642 characters for tags have been configured, either through the variable
3643 `org-tag-alist' or through a #+TAGS line in the buffer.
3644 When t, fast selection is always used and selection keys are assigned
3645 automatically if necessary."
3646 :group 'org-tags
3647 :type '(choice
3648 (const :tag "Always" t)
3649 (const :tag "Never" nil)
3650 (const :tag "When selection characters are configured" auto)))
3652 (defcustom org-fast-tag-selection-single-key nil
3653 "Non-nil means fast tag selection exits after first change.
3654 When nil, you have to press RET to exit it.
3655 During fast tag selection, you can toggle this flag with `C-c'.
3656 This variable can also have the value `expert'. In this case, the window
3657 displaying the tags menu is not even shown, until you press C-c again."
3658 :group 'org-tags
3659 :type '(choice
3660 (const :tag "No" nil)
3661 (const :tag "Yes" t)
3662 (const :tag "Expert" expert)))
3664 (defvar org-fast-tag-selection-include-todo nil
3665 "Non-nil means fast tags selection interface will also offer TODO states.
3666 This is an undocumented feature, you should not rely on it.")
3668 (defcustom org-tags-column -77
3669 "The column to which tags should be indented in a headline.
3670 If this number is positive, it specifies the column. If it is negative,
3671 it means that the tags should be flushright to that column. For example,
3672 -80 works well for a normal 80 character screen.
3673 When 0, place tags directly after headline text, with only one space in
3674 between."
3675 :group 'org-tags
3676 :type 'integer)
3678 (defcustom org-auto-align-tags t
3679 "Non-nil keeps tags aligned when modifying headlines.
3680 Some operations (i.e. demoting) change the length of a headline and
3681 therefore shift the tags around. With this option turned on, after
3682 each such operation the tags are again aligned to `org-tags-column'."
3683 :group 'org-tags
3684 :type 'boolean)
3686 (defcustom org-use-tag-inheritance t
3687 "Non-nil means tags in levels apply also for sublevels.
3688 When nil, only the tags directly given in a specific line apply there.
3689 This may also be a list of tags that should be inherited, or a regexp that
3690 matches tags that should be inherited. Additional control is possible
3691 with the variable `org-tags-exclude-from-inheritance' which gives an
3692 explicit list of tags to be excluded from inheritance, even if the value of
3693 `org-use-tag-inheritance' would select it for inheritance.
3695 If this option is t, a match early-on in a tree can lead to a large
3696 number of matches in the subtree when constructing the agenda or creating
3697 a sparse tree. If you only want to see the first match in a tree during
3698 a search, check out the variable `org-tags-match-list-sublevels'."
3699 :group 'org-tags
3700 :type '(choice
3701 (const :tag "Not" nil)
3702 (const :tag "Always" t)
3703 (repeat :tag "Specific tags" (string :tag "Tag"))
3704 (regexp :tag "Tags matched by regexp")))
3706 (defcustom org-tags-exclude-from-inheritance nil
3707 "List of tags that should never be inherited.
3708 This is a way to exclude a few tags from inheritance. For way to do
3709 the opposite, to actively allow inheritance for selected tags,
3710 see the variable `org-use-tag-inheritance'."
3711 :group 'org-tags
3712 :type '(repeat (string :tag "Tag")))
3714 (defun org-tag-inherit-p (tag)
3715 "Check if TAG is one that should be inherited."
3716 (cond
3717 ((member tag org-tags-exclude-from-inheritance) nil)
3718 ((eq org-use-tag-inheritance t) t)
3719 ((not org-use-tag-inheritance) nil)
3720 ((stringp org-use-tag-inheritance)
3721 (string-match org-use-tag-inheritance tag))
3722 ((listp org-use-tag-inheritance)
3723 (member tag org-use-tag-inheritance))
3724 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3726 (defcustom org-tags-match-list-sublevels t
3727 "Non-nil means list also sublevels of headlines matching a search.
3728 This variable applies to tags/property searches, and also to stuck
3729 projects because this search is based on a tags match as well.
3731 When set to the symbol `indented', sublevels are indented with
3732 leading dots.
3734 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3735 the sublevels of a headline matching a tag search often also match
3736 the same search. Listing all of them can create very long lists.
3737 Setting this variable to nil causes subtrees of a match to be skipped.
3739 This variable is semi-obsolete and probably should always be true. It
3740 is better to limit inheritance to certain tags using the variables
3741 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3742 :group 'org-tags
3743 :type '(choice
3744 (const :tag "No, don't list them" nil)
3745 (const :tag "Yes, do list them" t)
3746 (const :tag "List them, indented with leading dots" indented)))
3748 (defcustom org-tags-sort-function nil
3749 "When set, tags are sorted using this function as a comparator."
3750 :group 'org-tags
3751 :type '(choice
3752 (const :tag "No sorting" nil)
3753 (const :tag "Alphabetical" string<)
3754 (const :tag "Reverse alphabetical" string>)
3755 (function :tag "Custom function" nil)))
3757 (defvar org-tags-history nil
3758 "History of minibuffer reads for tags.")
3759 (defvar org-last-tags-completion-table nil
3760 "The last used completion table for tags.")
3761 (defvar org-after-tags-change-hook nil
3762 "Hook that is run after the tags in a line have changed.")
3764 (defgroup org-properties nil
3765 "Options concerning properties in Org mode."
3766 :tag "Org Properties"
3767 :group 'org)
3769 (defcustom org-property-format "%-10s %s"
3770 "How property key/value pairs should be formatted by `indent-line'.
3771 When `indent-line' hits a property definition, it will format the line
3772 according to this format, mainly to make sure that the values are
3773 lined-up with respect to each other."
3774 :group 'org-properties
3775 :type 'string)
3777 (defcustom org-properties-postprocess-alist nil
3778 "Alist of properties and functions to adjust inserted values.
3779 Elements of this alist must be of the form
3781 ([string] [function])
3783 where [string] must be a property name and [function] must be a
3784 lambda expression: this lambda expression must take one argument,
3785 the value to adjust, and return the new value as a string.
3787 For example, this element will allow the property \"Remaining\"
3788 to be updated wrt the relation between the \"Effort\" property
3789 and the clock summary:
3791 ((\"Remaining\" (lambda(value)
3792 (let ((clocksum (org-clock-sum-current-item))
3793 (effort (org-duration-string-to-minutes
3794 (org-entry-get (point) \"Effort\"))))
3795 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3796 :group 'org-properties
3797 :version "24.1"
3798 :type '(alist :key-type (string :tag "Property")
3799 :value-type (function :tag "Function")))
3801 (defcustom org-use-property-inheritance nil
3802 "Non-nil means properties apply also for sublevels.
3804 This setting is chiefly used during property searches. Turning it on can
3805 cause significant overhead when doing a search, which is why it is not
3806 on by default.
3808 When nil, only the properties directly given in the current entry count.
3809 When t, every property is inherited. The value may also be a list of
3810 properties that should have inheritance, or a regular expression matching
3811 properties that should be inherited.
3813 However, note that some special properties use inheritance under special
3814 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3815 and the properties ending in \"_ALL\" when they are used as descriptor
3816 for valid values of a property.
3818 Note for programmers:
3819 When querying an entry with `org-entry-get', you can control if inheritance
3820 should be used. By default, `org-entry-get' looks only at the local
3821 properties. You can request inheritance by setting the inherit argument
3822 to t (to force inheritance) or to `selective' (to respect the setting
3823 in this variable)."
3824 :group 'org-properties
3825 :type '(choice
3826 (const :tag "Not" nil)
3827 (const :tag "Always" t)
3828 (repeat :tag "Specific properties" (string :tag "Property"))
3829 (regexp :tag "Properties matched by regexp")))
3831 (defun org-property-inherit-p (property)
3832 "Return a non-nil value if PROPERTY should be inherited."
3833 (cond
3834 ((eq org-use-property-inheritance t) t)
3835 ((not org-use-property-inheritance) nil)
3836 ((stringp org-use-property-inheritance)
3837 (string-match org-use-property-inheritance property))
3838 ((listp org-use-property-inheritance)
3839 (member-ignore-case property org-use-property-inheritance))
3840 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3842 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3843 "The default column format, if no other format has been defined.
3844 This variable can be set on the per-file basis by inserting a line
3846 #+COLUMNS: %25ITEM ....."
3847 :group 'org-properties
3848 :type 'string)
3850 (defcustom org-columns-ellipses ".."
3851 "The ellipses to be used when a field in column view is truncated.
3852 When this is the empty string, as many characters as possible are shown,
3853 but then there will be no visual indication that the field has been truncated.
3854 When this is a string of length N, the last N characters of a truncated
3855 field are replaced by this string. If the column is narrower than the
3856 ellipses string, only part of the ellipses string will be shown."
3857 :group 'org-properties
3858 :type 'string)
3860 (defconst org-global-properties-fixed
3861 '(("VISIBILITY_ALL" . "folded children content all")
3862 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3863 "List of property/value pairs that can be inherited by any entry.
3865 These are fixed values, for the preset properties. The user variable
3866 that can be used to add to this list is `org-global-properties'.
3868 The entries in this list are cons cells where the car is a property
3869 name and cdr is a string with the value. If the value represents
3870 multiple items like an \"_ALL\" property, separate the items by
3871 spaces.")
3873 (defcustom org-global-properties nil
3874 "List of property/value pairs that can be inherited by any entry.
3876 This list will be combined with the constant `org-global-properties-fixed'.
3878 The entries in this list are cons cells where the car is a property
3879 name and cdr is a string with the value.
3881 You can set buffer-local values for the same purpose in the variable
3882 `org-file-properties' this by adding lines like
3884 #+PROPERTY: NAME VALUE"
3885 :group 'org-properties
3886 :type '(repeat
3887 (cons (string :tag "Property")
3888 (string :tag "Value"))))
3890 (defvar-local org-file-properties nil
3891 "List of property/value pairs that can be inherited by any entry.
3892 Valid for the current buffer.
3893 This variable is populated from #+PROPERTY lines.")
3895 (defgroup org-agenda nil
3896 "Options concerning agenda views in Org mode."
3897 :tag "Org Agenda"
3898 :group 'org)
3900 (defvar-local org-category nil
3901 "Variable used by org files to set a category for agenda display.
3902 Such files should use a file variable to set it, for example
3904 # -*- mode: org; org-category: \"ELisp\"
3906 or contain a special line
3908 #+CATEGORY: ELisp
3910 If the file does not specify a category, then file's base name
3911 is used instead.")
3912 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3914 (defcustom org-agenda-files nil
3915 "The files to be used for agenda display.
3917 If an entry is a directory, all files in that directory that are matched
3918 by `org-agenda-file-regexp' will be part of the file list.
3920 If the value of the variable is not a list but a single file name, then
3921 the list of agenda files is actually stored and maintained in that file,
3922 one agenda file per line. In this file paths can be given relative to
3923 `org-directory'. Tilde expansion and environment variable substitution
3924 are also made.
3926 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3927 and removed with `\\[org-remove-file]'."
3928 :group 'org-agenda
3929 :type '(choice
3930 (repeat :tag "List of files and directories" file)
3931 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3933 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3934 "Regular expression to match files for `org-agenda-files'.
3935 If any element in the list in that variable contains a directory instead
3936 of a normal file, all files in that directory that are matched by this
3937 regular expression will be included."
3938 :group 'org-agenda
3939 :type 'regexp)
3941 (defcustom org-agenda-text-search-extra-files nil
3942 "List of extra files to be searched by text search commands.
3943 These files will be searched in addition to the agenda files by the
3944 commands `org-search-view' (`\\[org-agenda] s') \
3945 and `org-occur-in-agenda-files'.
3946 Note that these files will only be searched for text search commands,
3947 not for the other agenda views like todo lists, tag searches or the weekly
3948 agenda. This variable is intended to list notes and possibly archive files
3949 that should also be searched by these two commands.
3950 In fact, if the first element in the list is the symbol `agenda-archives',
3951 then all archive files of all agenda files will be added to the search
3952 scope."
3953 :group 'org-agenda
3954 :type '(set :greedy t
3955 (const :tag "Agenda Archives" agenda-archives)
3956 (repeat :inline t (file))))
3958 (defvaralias 'org-agenda-multi-occur-extra-files
3959 'org-agenda-text-search-extra-files)
3961 (defcustom org-agenda-skip-unavailable-files nil
3962 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3963 A nil value means to remove them, after a query, from the list."
3964 :group 'org-agenda
3965 :type 'boolean)
3967 (defcustom org-calendar-to-agenda-key [?c]
3968 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3969 The command `org-calendar-goto-agenda' will be bound to this key. The
3970 default is the character `c' because then `c' can be used to switch back and
3971 forth between agenda and calendar."
3972 :group 'org-agenda
3973 :type 'sexp)
3975 (defcustom org-calendar-insert-diary-entry-key [?i]
3976 "The key to be installed in `calendar-mode-map' for adding diary entries.
3977 This option is irrelevant until `org-agenda-diary-file' has been configured
3978 to point to an Org file. When that is the case, the command
3979 `org-agenda-diary-entry' will be bound to the key given here, by default
3980 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3981 if you want to continue doing this, you need to change this to a different
3982 key."
3983 :group 'org-agenda
3984 :type 'sexp)
3986 (defcustom org-agenda-diary-file 'diary-file
3987 "File to which to add new entries with the `i' key in agenda and calendar.
3988 When this is the symbol `diary-file', the functionality in the Emacs
3989 calendar will be used to add entries to the `diary-file'. But when this
3990 points to a file, `org-agenda-diary-entry' will be used instead."
3991 :group 'org-agenda
3992 :type '(choice
3993 (const :tag "The standard Emacs diary file" diary-file)
3994 (file :tag "Special Org file diary entries")))
3996 (eval-after-load "calendar"
3997 '(progn
3998 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3999 'org-calendar-goto-agenda)
4000 (add-hook 'calendar-mode-hook
4001 (lambda ()
4002 (unless (eq org-agenda-diary-file 'diary-file)
4003 (define-key calendar-mode-map
4004 org-calendar-insert-diary-entry-key
4005 'org-agenda-diary-entry))))))
4007 (defgroup org-latex nil
4008 "Options for embedding LaTeX code into Org mode."
4009 :tag "Org LaTeX"
4010 :group 'org)
4012 (defcustom org-format-latex-options
4013 '(:foreground default :background default :scale 1.0
4014 :html-foreground "Black" :html-background "Transparent"
4015 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
4016 "Options for creating images from LaTeX fragments.
4017 This is a property list with the following properties:
4018 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
4019 `default' means use the foreground of the default face.
4020 `auto' means use the foreground from the text face.
4021 :background the background color, or \"Transparent\".
4022 `default' means use the background of the default face.
4023 `auto' means use the background from the text face.
4024 :scale a scaling factor for the size of the images, to get more pixels
4025 :html-foreground, :html-background, :html-scale
4026 the same numbers for HTML export.
4027 :matchers a list indicating which matchers should be used to
4028 find LaTeX fragments. Valid members of this list are:
4029 \"begin\" find environments
4030 \"$1\" find single characters surrounded by $.$
4031 \"$\" find math expressions surrounded by $...$
4032 \"$$\" find math expressions surrounded by $$....$$
4033 \"\\(\" find math expressions surrounded by \\(...\\)
4034 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
4035 :group 'org-latex
4036 :type 'plist)
4038 (defcustom org-format-latex-signal-error t
4039 "Non-nil means signal an error when image creation of LaTeX snippets fails.
4040 When nil, just push out a message."
4041 :group 'org-latex
4042 :version "24.1"
4043 :type 'boolean)
4045 (defcustom org-latex-to-mathml-jar-file nil
4046 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
4047 Use this to specify additional executable file say a jar file.
4049 When using MathToWeb as the converter, specify the full-path to
4050 your mathtoweb.jar file."
4051 :group 'org-latex
4052 :version "24.1"
4053 :type '(choice
4054 (const :tag "None" nil)
4055 (file :tag "JAR file" :must-match t)))
4057 (defcustom org-latex-to-mathml-convert-command nil
4058 "Command to convert LaTeX fragments to MathML.
4059 Replace format-specifiers in the command as noted below and use
4060 `shell-command' to convert LaTeX to MathML.
4061 %j: Executable file in fully expanded form as specified by
4062 `org-latex-to-mathml-jar-file'.
4063 %I: Input LaTeX file in fully expanded form.
4064 %i: The latex fragment to be converted.
4065 %o: Output MathML file.
4067 This command is used by `org-create-math-formula'.
4069 When using MathToWeb as the converter, set this option to
4070 \"java -jar %j -unicode -force -df %o %I\".
4072 When using LaTeXML set this option to
4073 \"latexmlmath \"%i\" --presentationmathml=%o\"."
4074 :group 'org-latex
4075 :version "24.1"
4076 :type '(choice
4077 (const :tag "None" nil)
4078 (string :tag "\nShell command")))
4080 (defcustom org-preview-latex-default-process 'dvipng
4081 "The default process to convert LaTeX fragments to image files.
4082 All available processes and theirs documents can be found in
4083 `org-preview-latex-process-alist', which see."
4084 :group 'org-latex
4085 :version "26.1"
4086 :package-version '(Org . "9.0")
4087 :type 'symbol)
4089 (defcustom org-preview-latex-process-alist
4090 '((dvipng
4091 :programs ("latex" "dvipng")
4092 :description "dvi > png"
4093 :message "you need to install the programs: latex and dvipng."
4094 :image-input-type "dvi"
4095 :image-output-type "png"
4096 :image-size-adjust (1.0 . 1.0)
4097 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4098 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
4099 (dvisvgm
4100 :programs ("latex" "dvisvgm")
4101 :description "dvi > svg"
4102 :message "you need to install the programs: latex and dvisvgm."
4103 :use-xcolor t
4104 :image-input-type "dvi"
4105 :image-output-type "svg"
4106 :image-size-adjust (1.7 . 1.5)
4107 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4108 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
4109 (imagemagick
4110 :programs ("latex" "convert")
4111 :description "pdf > png"
4112 :message "you need to install the programs: latex and imagemagick."
4113 :use-xcolor t
4114 :image-input-type "pdf"
4115 :image-output-type "png"
4116 :image-size-adjust (1.0 . 1.0)
4117 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4118 :image-converter
4119 ("convert -density %D -trim -antialias %f -quality 100 %O")))
4120 "Definitions of external processes for LaTeX previewing.
4121 Org mode can use some external commands to generate TeX snippet's images for
4122 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4123 `org-create-formula-image' how to call them.
4125 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4126 PROPERTIES accepts the following attributes:
4128 :programs list of strings, required programs.
4129 :description string, describe the process.
4130 :message string, message it when required programs cannot be found.
4131 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4132 :image-output-type string, output file type of image converter (e.g., \"png\").
4133 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4134 deal with background and foreground color of image.
4135 Otherwise, dvipng style background and foreground color
4136 format are generated. You may then refer to them in
4137 command options with \"%F\" and \"%B\".
4138 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4139 image size showed in buffer and the cdr element is for
4140 HTML file. This option is only useful for process
4141 developers, users should use variable
4142 `org-format-latex-options' instead.
4143 :post-clean list of strings, files matched are to be cleaned up once
4144 the image is generated. When nil, the files with \".dvi\",
4145 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4146 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4147 be cleaned up.
4148 :latex-header list of strings, the LaTeX header of the snippet file.
4149 When nil, the fallback value is used instead, which is
4150 controlled by `org-format-latex-header',
4151 `org-latex-default-packages-alist' and
4152 `org-latex-packages-alist', which see.
4153 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4154 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4155 replaced with values defined below.
4156 :image-converter list of image converter commands strings. Each of them is
4157 given to the shell and supports any of the following
4158 place-holders defined below.
4160 Place-holders used by `:image-converter' and `:latex-compiler':
4162 %f input file name
4163 %b base name of input file
4164 %o base directory of input file
4165 %O absolute output file name
4167 Place-holders only used by `:image-converter':
4169 %F foreground of image
4170 %B background of image
4171 %D dpi, which is used to adjust image size by some processing commands.
4172 %S the image size scale ratio, which is used to adjust image size by some
4173 processing commands."
4174 :group 'org-latex
4175 :version "26.1"
4176 :package-version '(Org . "9.0")
4177 :type '(alist :tag "LaTeX to image backends"
4178 :value-type (plist)))
4180 (defcustom org-preview-latex-image-directory "ltximg/"
4181 "Path to store latex preview images.
4182 A relative path here creates many directories relative to the
4183 processed org files paths. An absolute path puts all preview
4184 images at the same place."
4185 :group 'org-latex
4186 :version "26.1"
4187 :package-version '(Org . "9.0")
4188 :type 'string)
4190 (defun org-format-latex-mathml-available-p ()
4191 "Return t if `org-latex-to-mathml-convert-command' is usable."
4192 (save-match-data
4193 (when (and (boundp 'org-latex-to-mathml-convert-command)
4194 org-latex-to-mathml-convert-command)
4195 (let ((executable (car (split-string
4196 org-latex-to-mathml-convert-command))))
4197 (when (executable-find executable)
4198 (if (string-match
4199 "%j" org-latex-to-mathml-convert-command)
4200 (file-readable-p org-latex-to-mathml-jar-file)
4201 t))))))
4203 (defcustom org-format-latex-header "\\documentclass{article}
4204 \\usepackage[usenames]{color}
4205 \[PACKAGES]
4206 \[DEFAULT-PACKAGES]
4207 \\pagestyle{empty} % do not remove
4208 % The settings below are copied from fullpage.sty
4209 \\setlength{\\textwidth}{\\paperwidth}
4210 \\addtolength{\\textwidth}{-3cm}
4211 \\setlength{\\oddsidemargin}{1.5cm}
4212 \\addtolength{\\oddsidemargin}{-2.54cm}
4213 \\setlength{\\evensidemargin}{\\oddsidemargin}
4214 \\setlength{\\textheight}{\\paperheight}
4215 \\addtolength{\\textheight}{-\\headheight}
4216 \\addtolength{\\textheight}{-\\headsep}
4217 \\addtolength{\\textheight}{-\\footskip}
4218 \\addtolength{\\textheight}{-3cm}
4219 \\setlength{\\topmargin}{1.5cm}
4220 \\addtolength{\\topmargin}{-2.54cm}"
4221 "The document header used for processing LaTeX fragments.
4222 It is imperative that this header make sure that no page number
4223 appears on the page. The package defined in the variables
4224 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4225 will either replace the placeholder \"[PACKAGES]\" in this
4226 header, or they will be appended."
4227 :group 'org-latex
4228 :type 'string)
4230 (defun org-set-packages-alist (var val)
4231 "Set the packages alist and make sure it has 3 elements per entry."
4232 (set var (mapcar (lambda (x)
4233 (if (and (consp x) (= (length x) 2))
4234 (list (car x) (nth 1 x) t)
4236 val)))
4238 (defun org-get-packages-alist (var)
4239 "Get the packages alist and make sure it has 3 elements per entry."
4240 (mapcar (lambda (x)
4241 (if (and (consp x) (= (length x) 2))
4242 (list (car x) (nth 1 x) t)
4244 (default-value var)))
4246 (defcustom org-latex-default-packages-alist
4247 '(("AUTO" "inputenc" t ("pdflatex"))
4248 ("T1" "fontenc" t ("pdflatex"))
4249 ("" "graphicx" t)
4250 ("" "grffile" t)
4251 ("" "longtable" nil)
4252 ("" "wrapfig" nil)
4253 ("" "rotating" nil)
4254 ("normalem" "ulem" t)
4255 ("" "amsmath" t)
4256 ("" "textcomp" t)
4257 ("" "amssymb" t)
4258 ("" "capt-of" nil)
4259 ("" "hyperref" nil))
4260 "Alist of default packages to be inserted in the header.
4262 Change this only if one of the packages here causes an
4263 incompatibility with another package you are using.
4265 The packages in this list are needed by one part or another of
4266 Org mode to function properly:
4268 - inputenc, fontenc: for basic font and character selection
4269 - graphicx: for including images
4270 - grffile: allow periods and spaces in graphics file names
4271 - longtable: For multipage tables
4272 - wrapfig: for figure placement
4273 - rotating: for sideways figures and tables
4274 - ulem: for underline and strike-through
4275 - amsmath: for subscript and superscript and math environments
4276 - textcomp, amssymb: for various symbols used
4277 for interpreting the entities in `org-entities'. You can skip
4278 some of these packages if you don't use any of their symbols.
4279 - capt-of: for captions outside of floats
4280 - hyperref: for cross references
4282 Therefore you should not modify this variable unless you know
4283 what you are doing. The one reason to change it anyway is that
4284 you might be loading some other package that conflicts with one
4285 of the default packages. Each element is either a cell or
4286 a string.
4288 A cell is of the format
4290 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4292 If SNIPPET-FLAG is non-nil, the package also needs to be included
4293 when compiling LaTeX snippets into images for inclusion into
4294 non-LaTeX output. COMPILERS is a list of compilers that should
4295 include the package, see `org-latex-compiler'. If the document
4296 compiler is not in the list, and the list is non-nil, the package
4297 will not be inserted in the final document.
4299 A string will be inserted as-is in the header of the document."
4300 :group 'org-latex
4301 :group 'org-export-latex
4302 :set 'org-set-packages-alist
4303 :get 'org-get-packages-alist
4304 :version "26.1"
4305 :package-version '(Org . "8.3")
4306 :type '(repeat
4307 (choice
4308 (list :tag "options/package pair"
4309 (string :tag "options")
4310 (string :tag "package")
4311 (boolean :tag "Snippet"))
4312 (string :tag "A line of LaTeX"))))
4314 (defcustom org-latex-packages-alist nil
4315 "Alist of packages to be inserted in every LaTeX header.
4317 These will be inserted after `org-latex-default-packages-alist'.
4318 Each element is either a cell or a string.
4320 A cell is of the format:
4322 (\"options\" \"package\" SNIPPET-FLAG)
4324 SNIPPET-FLAG, when non-nil, indicates that this package is also
4325 needed when turning LaTeX snippets into images for inclusion into
4326 non-LaTeX output.
4328 A string will be inserted as-is in the header of the document.
4330 Make sure that you only list packages here which:
4332 - you want in every file;
4333 - do not conflict with the setup in `org-format-latex-header';
4334 - do not conflict with the default packages in
4335 `org-latex-default-packages-alist'."
4336 :group 'org-latex
4337 :group 'org-export-latex
4338 :set 'org-set-packages-alist
4339 :get 'org-get-packages-alist
4340 :type '(repeat
4341 (choice
4342 (list :tag "options/package pair"
4343 (string :tag "options")
4344 (string :tag "package")
4345 (boolean :tag "Snippet"))
4346 (string :tag "A line of LaTeX"))))
4348 (defgroup org-appearance nil
4349 "Settings for Org mode appearance."
4350 :tag "Org Appearance"
4351 :group 'org)
4353 (defcustom org-level-color-stars-only nil
4354 "Non-nil means fontify only the stars in each headline.
4355 When nil, the entire headline is fontified.
4356 Changing it requires restart of `font-lock-mode' to become effective
4357 also in regions already fontified."
4358 :group 'org-appearance
4359 :type 'boolean)
4361 (defcustom org-hide-leading-stars nil
4362 "Non-nil means hide the first N-1 stars in a headline.
4363 This works by using the face `org-hide' for these stars. This
4364 face is white for a light background, and black for a dark
4365 background. You may have to customize the face `org-hide' to
4366 make this work.
4367 Changing it requires restart of `font-lock-mode' to become effective
4368 also in regions already fontified.
4369 You may also set this on a per-file basis by adding one of the following
4370 lines to the buffer:
4372 #+STARTUP: hidestars
4373 #+STARTUP: showstars"
4374 :group 'org-appearance
4375 :type 'boolean)
4377 (defcustom org-hidden-keywords nil
4378 "List of symbols corresponding to keywords to be hidden the org buffer.
4379 For example, a value \\='(title) for this list will make the document's title
4380 appear in the buffer without the initial #+TITLE: keyword."
4381 :group 'org-appearance
4382 :version "24.1"
4383 :type '(set (const :tag "#+AUTHOR" author)
4384 (const :tag "#+DATE" date)
4385 (const :tag "#+EMAIL" email)
4386 (const :tag "#+TITLE" title)))
4388 (defcustom org-custom-properties nil
4389 "List of properties (as strings) with a special meaning.
4390 The default use of these custom properties is to let the user
4391 hide them with `org-toggle-custom-properties-visibility'."
4392 :group 'org-properties
4393 :group 'org-appearance
4394 :version "24.3"
4395 :type '(repeat (string :tag "Property Name")))
4397 (defcustom org-fontify-done-headline nil
4398 "Non-nil means change the face of a headline if it is marked DONE.
4399 Normally, only the TODO/DONE keyword indicates the state of a headline.
4400 When this is non-nil, the headline after the keyword is set to the
4401 `org-headline-done' as an additional indication."
4402 :group 'org-appearance
4403 :type 'boolean)
4405 (defcustom org-fontify-emphasized-text t
4406 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4407 Changing this variable requires a restart of Emacs to take effect."
4408 :group 'org-appearance
4409 :type 'boolean)
4411 (defcustom org-fontify-whole-heading-line nil
4412 "Non-nil means fontify the whole line for headings.
4413 This is useful when setting a background color for the
4414 org-level-* faces."
4415 :group 'org-appearance
4416 :type 'boolean)
4418 (defcustom org-highlight-latex-and-related nil
4419 "Non-nil means highlight LaTeX related syntax in the buffer.
4420 When non nil, the value should be a list containing any of the
4421 following symbols:
4422 `latex' Highlight LaTeX snippets and environments.
4423 `script' Highlight subscript and superscript.
4424 `entities' Highlight entities."
4425 :group 'org-appearance
4426 :version "24.4"
4427 :package-version '(Org . "8.0")
4428 :type '(choice
4429 (const :tag "No highlighting" nil)
4430 (set :greedy t :tag "Highlight"
4431 (const :tag "LaTeX snippets and environments" latex)
4432 (const :tag "Subscript and superscript" script)
4433 (const :tag "Entities" entities))))
4435 (defcustom org-hide-emphasis-markers nil
4436 "Non-nil mean font-lock should hide the emphasis marker characters."
4437 :group 'org-appearance
4438 :type 'boolean)
4440 (defcustom org-hide-macro-markers nil
4441 "Non-nil mean font-lock should hide the brackets marking macro calls."
4442 :group 'org-appearance
4443 :type 'boolean)
4445 (defcustom org-pretty-entities nil
4446 "Non-nil means show entities as UTF8 characters.
4447 When nil, the \\name form remains in the buffer."
4448 :group 'org-appearance
4449 :version "24.1"
4450 :type 'boolean)
4452 (defcustom org-pretty-entities-include-sub-superscripts t
4453 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4454 :group 'org-appearance
4455 :version "24.1"
4456 :type 'boolean)
4458 (defvar org-emph-re nil
4459 "Regular expression for matching emphasis.
4460 After a match, the match groups contain these elements:
4461 0 The match of the full regular expression, including the characters
4462 before and after the proper match
4463 1 The character before the proper match, or empty at beginning of line
4464 2 The proper match, including the leading and trailing markers
4465 3 The leading marker like * or /, indicating the type of highlighting
4466 4 The text between the emphasis markers, not including the markers
4467 5 The character after the match, empty at the end of a line")
4468 (defvar org-verbatim-re nil
4469 "Regular expression for matching verbatim text.")
4470 (defvar org-emphasis-regexp-components) ; defined just below
4471 (defvar org-emphasis-alist) ; defined just below
4472 (defun org-set-emph-re (var val)
4473 "Set variable and compute the emphasis regular expression."
4474 (set var val)
4475 (when (and (boundp 'org-emphasis-alist)
4476 (boundp 'org-emphasis-regexp-components)
4477 org-emphasis-alist org-emphasis-regexp-components)
4478 (let* ((e org-emphasis-regexp-components)
4479 (pre (car e))
4480 (post (nth 1 e))
4481 (border (nth 2 e))
4482 (body (nth 3 e))
4483 (nl (nth 4 e))
4484 (body1 (concat body "*?"))
4485 (markers (mapconcat 'car org-emphasis-alist ""))
4486 (vmarkers (mapconcat
4487 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4488 org-emphasis-alist "")))
4489 ;; make sure special characters appear at the right position in the class
4490 (if (string-match "\\^" markers)
4491 (setq markers (concat (replace-match "" t t markers) "^")))
4492 (if (string-match "-" markers)
4493 (setq markers (concat (replace-match "" t t markers) "-")))
4494 (if (string-match "\\^" vmarkers)
4495 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4496 (if (string-match "-" vmarkers)
4497 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4498 (if (> nl 0)
4499 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4500 (int-to-string nl) "\\}")))
4501 ;; Make the regexp
4502 (setq org-emph-re
4503 (concat "\\([" pre "]\\|^\\)"
4504 "\\("
4505 "\\([" markers "]\\)"
4506 "\\("
4507 "[^" border "]\\|"
4508 "[^" border "]"
4509 body1
4510 "[^" border "]"
4511 "\\)"
4512 "\\3\\)"
4513 "\\([" post "]\\|$\\)"))
4514 (setq org-verbatim-re
4515 (concat "\\([" pre "]\\|^\\)"
4516 "\\("
4517 "\\([" vmarkers "]\\)"
4518 "\\("
4519 "[^" border "]\\|"
4520 "[^" border "]"
4521 body1
4522 "[^" border "]"
4523 "\\)"
4524 "\\3\\)"
4525 "\\([" post "]\\|$\\)")))))
4527 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4528 ;; set this option proved cumbersome. See this message/thread:
4529 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4530 (defvar org-emphasis-regexp-components
4531 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4532 "Components used to build the regular expression for emphasis.
4533 This is a list with five entries. Terminology: In an emphasis string
4534 like \" *strong word* \", we call the initial space PREMATCH, the final
4535 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4536 and \"trong wor\" is the body. The different components in this variable
4537 specify what is allowed/forbidden in each part:
4539 pre Chars allowed as prematch. Beginning of line will be allowed too.
4540 post Chars allowed as postmatch. End of line will be allowed too.
4541 border The chars *forbidden* as border characters.
4542 body-regexp A regexp like \".\" to match a body character. Don't use
4543 non-shy groups here, and don't allow newline here.
4544 newline The maximum number of newlines allowed in an emphasis exp.
4546 You need to reload Org or to restart Emacs after customizing this.")
4548 (defcustom org-emphasis-alist
4549 '(("*" bold)
4550 ("/" italic)
4551 ("_" underline)
4552 ("=" org-verbatim verbatim)
4553 ("~" org-code verbatim)
4554 ("+" (:strike-through t)))
4555 "Alist of characters and faces to emphasize text.
4556 Text starting and ending with a special character will be emphasized,
4557 for example *bold*, _underlined_ and /italic/. This variable sets the
4558 marker characters and the face to be used by font-lock for highlighting
4559 in Org buffers.
4561 You need to reload Org or to restart Emacs after customizing this."
4562 :group 'org-appearance
4563 :set 'org-set-emph-re
4564 :version "24.4"
4565 :package-version '(Org . "8.0")
4566 :type '(repeat
4567 (list
4568 (string :tag "Marker character")
4569 (choice
4570 (face :tag "Font-lock-face")
4571 (plist :tag "Face property list"))
4572 (option (const verbatim)))))
4574 (defvar org-protecting-blocks '("src" "example" "export")
4575 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4576 This is needed for font-lock setup.")
4578 ;;; Functions and variables from their packages
4579 ;; Declared here to avoid compiler warnings
4580 (defvar mark-active)
4582 ;; Various packages
4583 (declare-function calc-eval "calc" (str &optional separator &rest args))
4584 (declare-function calendar-forward-day "cal-move" (arg))
4585 (declare-function calendar-goto-date "cal-move" (date))
4586 (declare-function calendar-goto-today "cal-move" ())
4587 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4588 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4589 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4590 (declare-function cdlatex-tab "ext:cdlatex" ())
4591 (declare-function dired-get-filename
4592 "dired"
4593 (&optional localp no-error-if-not-filep))
4594 (declare-function iswitchb-read-buffer
4595 "iswitchb"
4596 (prompt &optional
4597 default require-match _predicate start matches-set))
4598 (declare-function org-agenda-change-all-lines
4599 "org-agenda"
4600 (newhead hdmarker &optional fixface just-this))
4601 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4602 "org-agenda"
4603 (&optional end))
4604 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4605 (declare-function org-agenda-format-item
4606 "org-agenda"
4607 (extra txt &optional level category tags dotime
4608 remove-re habitp))
4609 (declare-function org-agenda-maybe-redo "org-agenda" ())
4610 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4611 (declare-function org-agenda-save-markers-for-cut-and-paste
4612 "org-agenda"
4613 (beg end))
4614 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4615 (declare-function org-agenda-skip "org-agenda" ())
4616 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4617 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4618 (declare-function org-indent-mode "org-indent" (&optional arg))
4619 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4620 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4621 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4622 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4623 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4624 (declare-function parse-time-string "parse-time" (string))
4625 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4627 (defvar align-mode-rules-list)
4628 (defvar calc-embedded-close-formula)
4629 (defvar calc-embedded-open-formula)
4630 (defvar calc-embedded-open-mode)
4631 (defvar font-lock-unfontify-region-function)
4632 (defvar iswitchb-temp-buflist)
4633 (defvar org-agenda-tags-todo-honor-ignore-options)
4634 (defvar remember-data-file)
4635 (defvar texmathp-why)
4637 ;;;###autoload
4638 (defun turn-on-orgtbl ()
4639 "Unconditionally turn on `orgtbl-mode'."
4640 (require 'org-table)
4641 (orgtbl-mode 1))
4643 (defun org-at-table-p (&optional table-type)
4644 "Non-nil if the cursor is inside an Org table.
4645 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4646 If `org-enable-table-editor' is nil, return nil unconditionally."
4647 (and
4648 org-enable-table-editor
4649 (save-excursion
4650 (beginning-of-line)
4651 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4652 (or (not (derived-mode-p 'org-mode))
4653 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4654 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4656 (defun org-at-table.el-p ()
4657 "Non-nil when point is at a table.el table."
4658 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4659 (let ((element (org-element-at-point)))
4660 (and (eq (org-element-type element) 'table)
4661 (eq (org-element-property :type element) 'table.el)))))
4663 (defun org-at-table-hline-p ()
4664 "Non-nil when point is inside a hline in a table.
4665 Assume point is already in a table. If `org-enable-table-editor'
4666 is nil, return nil unconditionally."
4667 (and org-enable-table-editor
4668 (save-excursion
4669 (beginning-of-line)
4670 (looking-at org-table-hline-regexp))))
4672 (defun org-table-map-tables (function &optional quietly)
4673 "Apply FUNCTION to the start of all tables in the buffer."
4674 (org-with-wide-buffer
4675 (goto-char (point-min))
4676 (while (re-search-forward org-table-any-line-regexp nil t)
4677 (unless quietly
4678 (message "Mapping tables: %d%%"
4679 (floor (* 100.0 (point)) (buffer-size))))
4680 (beginning-of-line 1)
4681 (when (and (looking-at org-table-line-regexp)
4682 ;; Exclude tables in src/example/verbatim/clocktable blocks
4683 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4684 (save-excursion (funcall function))
4685 (or (looking-at org-table-line-regexp)
4686 (forward-char 1)))
4687 (re-search-forward org-table-any-border-regexp nil 1)))
4688 (unless quietly (message "Mapping tables: done")))
4690 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4691 (declare-function org-clock-update-mode-line "org-clock" ())
4692 (declare-function org-resolve-clocks "org-clock"
4693 (&optional also-non-dangling-p prompt last-valid))
4695 (defun org-at-TBLFM-p (&optional pos)
4696 "Non-nil when point (or POS) is in #+TBLFM line."
4697 (save-excursion
4698 (goto-char (or pos (point)))
4699 (beginning-of-line)
4700 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4701 (eq (org-element-type (org-element-at-point)) 'table))))
4703 (defvar org-clock-start-time)
4704 (defvar org-clock-marker (make-marker)
4705 "Marker recording the last clock-in.")
4706 (defvar org-clock-hd-marker (make-marker)
4707 "Marker recording the last clock-in, but the headline position.")
4708 (defvar org-clock-heading ""
4709 "The heading of the current clock entry.")
4710 (defun org-clock-is-active ()
4711 "Return the buffer where the clock is currently running.
4712 Return nil if no clock is running."
4713 (marker-buffer org-clock-marker))
4715 (defun org-check-running-clock ()
4716 "Check if the current buffer contains the running clock.
4717 If yes, offer to stop it and to save the buffer with the changes."
4718 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4719 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4720 (buffer-name))))
4721 (org-clock-out)
4722 (when (y-or-n-p "Save changed buffer?")
4723 (save-buffer))))
4725 (defun org-clocktable-try-shift (dir n)
4726 "Check if this line starts a clock table, if yes, shift the time block."
4727 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4728 (org-clocktable-shift dir n)))
4730 ;;;###autoload
4731 (defun org-clock-persistence-insinuate ()
4732 "Set up hooks for clock persistence."
4733 (require 'org-clock)
4734 (add-hook 'org-mode-hook 'org-clock-load)
4735 (add-hook 'kill-emacs-hook 'org-clock-save))
4737 (defgroup org-archive nil
4738 "Options concerning archiving in Org mode."
4739 :tag "Org Archive"
4740 :group 'org-structure)
4742 (defcustom org-archive-location "%s_archive::"
4743 "The location where subtrees should be archived.
4745 The value of this variable is a string, consisting of two parts,
4746 separated by a double-colon. The first part is a filename and
4747 the second part is a headline.
4749 When the filename is omitted, archiving happens in the same file.
4750 %s in the filename will be replaced by the current file
4751 name (without the directory part). Archiving to a different file
4752 is useful to keep archived entries from contributing to the
4753 Org Agenda.
4755 The archived entries will be filed as subtrees of the specified
4756 headline. When the headline is omitted, the subtrees are simply
4757 filed away at the end of the file, as top-level entries. Also in
4758 the heading you can use %s to represent the file name, this can be
4759 useful when using the same archive for a number of different files.
4761 Here are a few examples:
4762 \"%s_archive::\"
4763 If the current file is Projects.org, archive in file
4764 Projects.org_archive, as top-level trees. This is the default.
4766 \"::* Archived Tasks\"
4767 Archive in the current file, under the top-level headline
4768 \"* Archived Tasks\".
4770 \"~/org/archive.org::\"
4771 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4773 \"~/org/archive.org::* From %s\"
4774 Archive in file ~/org/archive.org (absolute path), under headlines
4775 \"From FILENAME\" where file name is the current file name.
4777 \"~/org/datetree.org::datetree/* Finished Tasks\"
4778 The \"datetree/\" string is special, signifying to archive
4779 items to the datetree. Items are placed in either the CLOSED
4780 date of the item, or the current date if there is no CLOSED date.
4781 The heading will be a subentry to the current date. There doesn't
4782 need to be a heading, but there always needs to be a slash after
4783 datetree. For example, to store archived items directly in the
4784 datetree, use \"~/org/datetree.org::datetree/\".
4786 \"basement::** Finished Tasks\"
4787 Archive in file ./basement (relative path), as level 3 trees
4788 below the level 2 heading \"** Finished Tasks\".
4790 You may set this option on a per-file basis by adding to the buffer a
4791 line like
4793 #+ARCHIVE: basement::** Finished Tasks
4795 You may also define it locally for a subtree by setting an ARCHIVE property
4796 in the entry. If such a property is found in an entry, or anywhere up
4797 the hierarchy, it will be used."
4798 :group 'org-archive
4799 :type 'string)
4801 (defcustom org-agenda-skip-archived-trees t
4802 "Non-nil means the agenda will skip any items located in archived trees.
4803 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4804 variable is no longer recommended, you should leave it at the value t.
4805 Instead, use the key `v' to cycle the archives-mode in the agenda."
4806 :group 'org-archive
4807 :group 'org-agenda-skip
4808 :type 'boolean)
4810 (defcustom org-columns-skip-archived-trees t
4811 "Non-nil means ignore archived trees when creating column view."
4812 :group 'org-archive
4813 :group 'org-properties
4814 :type 'boolean)
4816 (defcustom org-cycle-open-archived-trees nil
4817 "Non-nil means `org-cycle' will open archived trees.
4818 An archived tree is a tree marked with the tag ARCHIVE.
4819 When nil, archived trees will stay folded. You can still open them with
4820 normal outline commands like `show-all', but not with the cycling commands."
4821 :group 'org-archive
4822 :group 'org-cycle
4823 :type 'boolean)
4825 (defcustom org-sparse-tree-open-archived-trees nil
4826 "Non-nil means sparse tree construction shows matches in archived trees.
4827 When nil, matches in these trees are highlighted, but the trees are kept in
4828 collapsed state."
4829 :group 'org-archive
4830 :group 'org-sparse-trees
4831 :type 'boolean)
4833 (defcustom org-sparse-tree-default-date-type nil
4834 "The default date type when building a sparse tree.
4835 When this is nil, a date is a scheduled or a deadline timestamp.
4836 Otherwise, these types are allowed:
4838 all: all timestamps
4839 active: only active timestamps (<...>)
4840 inactive: only inactive timestamps ([...])
4841 scheduled: only scheduled timestamps
4842 deadline: only deadline timestamps"
4843 :type '(choice (const :tag "Scheduled or deadline" nil)
4844 (const :tag "All timestamps" all)
4845 (const :tag "Only active timestamps" active)
4846 (const :tag "Only inactive timestamps" inactive)
4847 (const :tag "Only scheduled timestamps" scheduled)
4848 (const :tag "Only deadline timestamps" deadline)
4849 (const :tag "Only closed timestamps" closed))
4850 :version "26.1"
4851 :package-version '(Org . "8.3")
4852 :group 'org-sparse-trees)
4854 (defun org-cycle-hide-archived-subtrees (state)
4855 "Re-hide all archived subtrees after a visibility state change."
4856 (when (and (not org-cycle-open-archived-trees)
4857 (not (memq state '(overview folded))))
4858 (save-excursion
4859 (let* ((globalp (memq state '(contents all)))
4860 (beg (if globalp (point-min) (point)))
4861 (end (if globalp (point-max) (org-end-of-subtree t))))
4862 (org-hide-archived-subtrees beg end)
4863 (goto-char beg)
4864 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4865 (message "%s" (substitute-command-keys
4866 "Subtree is archived and stays closed. Use \
4867 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4869 (defun org-force-cycle-archived ()
4870 "Cycle subtree even if it is archived."
4871 (interactive)
4872 (setq this-command 'org-cycle)
4873 (let ((org-cycle-open-archived-trees t))
4874 (call-interactively 'org-cycle)))
4876 (defun org-hide-archived-subtrees (beg end)
4877 "Re-hide all archived subtrees after a visibility state change."
4878 (org-with-wide-buffer
4879 (let ((case-fold-search nil)
4880 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4881 (goto-char beg)
4882 ;; Include headline point is currently on.
4883 (beginning-of-line)
4884 (while (and (< (point) end) (re-search-forward re end t))
4885 (when (member org-archive-tag (org-get-tags))
4886 (org-flag-subtree t)
4887 (org-end-of-subtree t))))))
4889 (declare-function outline-end-of-heading "outline" ())
4890 (declare-function outline-flag-region "outline" (from to flag))
4891 (defun org-flag-subtree (flag)
4892 (save-excursion
4893 (org-back-to-heading t)
4894 (outline-end-of-heading)
4895 (outline-flag-region (point)
4896 (progn (org-end-of-subtree t) (point))
4897 flag)))
4899 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4901 ;; Declare Column View Code
4903 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4904 (declare-function org-columns-compute "org-colview" (property))
4906 ;; Declare ID code
4908 (declare-function org-id-store-link "org-id")
4909 (declare-function org-id-locations-load "org-id")
4910 (declare-function org-id-locations-save "org-id")
4911 (defvar org-id-track-globally)
4913 ;;; Variables for pre-computed regular expressions, all buffer local
4915 (defvar-local org-todo-regexp nil
4916 "Matches any of the TODO state keywords.
4917 Since TODO keywords are case-sensitive, `case-fold-search' is
4918 expected to be bound to nil when matching against this regexp.")
4920 (defvar-local org-not-done-regexp nil
4921 "Matches any of the TODO state keywords except the last one.
4922 Since TODO keywords are case-sensitive, `case-fold-search' is
4923 expected to be bound to nil when matching against this regexp.")
4925 (defvar-local org-not-done-heading-regexp nil
4926 "Matches a TODO headline that is not done.
4927 Since TODO keywords are case-sensitive, `case-fold-search' is
4928 expected to be bound to nil when matching against this regexp.")
4930 (defvar-local org-todo-line-regexp nil
4931 "Matches a headline and puts TODO state into group 2 if present.
4932 Since TODO keywords are case-sensitive, `case-fold-search' is
4933 expected to be bound to nil when matching against this regexp.")
4935 (defvar-local org-complex-heading-regexp nil
4936 "Matches a headline and puts everything into groups:
4938 group 1: Stars
4939 group 2: The TODO keyword, maybe
4940 group 3: Priority cookie
4941 group 4: True headline
4942 group 5: Tags
4944 Since TODO keywords are case-sensitive, `case-fold-search' is
4945 expected to be bound to nil when matching against this regexp.")
4947 (defvar-local org-complex-heading-regexp-format nil
4948 "Printf format to make regexp to match an exact headline.
4949 This regexp will match the headline of any node which has the
4950 exact headline text that is put into the format, but may have any
4951 TODO state, priority and tags.")
4953 (defvar-local org-todo-line-tags-regexp nil
4954 "Matches a headline and puts TODO state into group 2 if present.
4955 Also put tags into group 4 if tags are present.")
4957 (defconst org-plain-time-of-day-regexp
4958 (concat
4959 "\\(\\<[012]?[0-9]"
4960 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4961 "\\(--?"
4962 "\\(\\<[012]?[0-9]"
4963 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4964 "\\)?")
4965 "Regular expression to match a plain time or time range.
4966 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4967 groups carry important information:
4968 0 the full match
4969 1 the first time, range or not
4970 8 the second time, if it is a range.")
4972 (defconst org-plain-time-extension-regexp
4973 (concat
4974 "\\(\\<[012]?[0-9]"
4975 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4976 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4977 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4978 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4979 groups carry important information:
4980 0 the full match
4981 7 hours of duration
4982 9 minutes of duration")
4984 (defconst org-stamp-time-of-day-regexp
4985 (concat
4986 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4987 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4988 "\\(--?"
4989 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4990 "Regular expression to match a timestamp time or time range.
4991 After a match, the following groups carry important information:
4992 0 the full match
4993 1 date plus weekday, for back referencing to make sure both times are on the same day
4994 2 the first time, range or not
4995 4 the second time, if it is a range.")
4997 (defconst org-startup-options
4998 '(("fold" org-startup-folded t)
4999 ("overview" org-startup-folded t)
5000 ("nofold" org-startup-folded nil)
5001 ("showall" org-startup-folded nil)
5002 ("showeverything" org-startup-folded showeverything)
5003 ("content" org-startup-folded content)
5004 ("indent" org-startup-indented t)
5005 ("noindent" org-startup-indented nil)
5006 ("hidestars" org-hide-leading-stars t)
5007 ("showstars" org-hide-leading-stars nil)
5008 ("odd" org-odd-levels-only t)
5009 ("oddeven" org-odd-levels-only nil)
5010 ("align" org-startup-align-all-tables t)
5011 ("noalign" org-startup-align-all-tables nil)
5012 ("inlineimages" org-startup-with-inline-images t)
5013 ("noinlineimages" org-startup-with-inline-images nil)
5014 ("latexpreview" org-startup-with-latex-preview t)
5015 ("nolatexpreview" org-startup-with-latex-preview nil)
5016 ("customtime" org-display-custom-times t)
5017 ("logdone" org-log-done time)
5018 ("lognotedone" org-log-done note)
5019 ("nologdone" org-log-done nil)
5020 ("lognoteclock-out" org-log-note-clock-out t)
5021 ("nolognoteclock-out" org-log-note-clock-out nil)
5022 ("logrepeat" org-log-repeat state)
5023 ("lognoterepeat" org-log-repeat note)
5024 ("logdrawer" org-log-into-drawer t)
5025 ("nologdrawer" org-log-into-drawer nil)
5026 ("logstatesreversed" org-log-states-order-reversed t)
5027 ("nologstatesreversed" org-log-states-order-reversed nil)
5028 ("nologrepeat" org-log-repeat nil)
5029 ("logreschedule" org-log-reschedule time)
5030 ("lognotereschedule" org-log-reschedule note)
5031 ("nologreschedule" org-log-reschedule nil)
5032 ("logredeadline" org-log-redeadline time)
5033 ("lognoteredeadline" org-log-redeadline note)
5034 ("nologredeadline" org-log-redeadline nil)
5035 ("logrefile" org-log-refile time)
5036 ("lognoterefile" org-log-refile note)
5037 ("nologrefile" org-log-refile nil)
5038 ("fninline" org-footnote-define-inline t)
5039 ("nofninline" org-footnote-define-inline nil)
5040 ("fnlocal" org-footnote-section nil)
5041 ("fnauto" org-footnote-auto-label t)
5042 ("fnprompt" org-footnote-auto-label nil)
5043 ("fnconfirm" org-footnote-auto-label confirm)
5044 ("fnplain" org-footnote-auto-label plain)
5045 ("fnadjust" org-footnote-auto-adjust t)
5046 ("nofnadjust" org-footnote-auto-adjust nil)
5047 ("constcgs" constants-unit-system cgs)
5048 ("constSI" constants-unit-system SI)
5049 ("noptag" org-tag-persistent-alist nil)
5050 ("hideblocks" org-hide-block-startup t)
5051 ("nohideblocks" org-hide-block-startup nil)
5052 ("beamer" org-startup-with-beamer-mode t)
5053 ("entitiespretty" org-pretty-entities t)
5054 ("entitiesplain" org-pretty-entities nil))
5055 "Variable associated with STARTUP options for org-mode.
5056 Each element is a list of three items: the startup options (as written
5057 in the #+STARTUP line), the corresponding variable, and the value to set
5058 this variable to if the option is found. An optional forth element PUSH
5059 means to push this value onto the list in the variable.")
5061 (defcustom org-group-tags t
5062 "When non-nil (the default), use group tags.
5063 This can be turned on/off through `org-toggle-tags-groups'."
5064 :group 'org-tags
5065 :group 'org-startup
5066 :type 'boolean)
5068 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5070 (defun org-toggle-tags-groups ()
5071 "Toggle support for group tags.
5072 Support for group tags is controlled by the option
5073 `org-group-tags', which is non-nil by default."
5074 (interactive)
5075 (setq org-group-tags (not org-group-tags))
5076 (cond ((and (derived-mode-p 'org-agenda-mode)
5077 org-group-tags)
5078 (org-agenda-redo))
5079 ((derived-mode-p 'org-mode)
5080 (let ((org-inhibit-startup t)) (org-mode))))
5081 (message "Groups tags support has been turned %s"
5082 (if org-group-tags "on" "off")))
5084 (defun org-set-regexps-and-options (&optional tags-only)
5085 "Precompute regular expressions used in the current buffer.
5086 When optional argument TAGS-ONLY is non-nil, only compute tags
5087 related expressions."
5088 (when (derived-mode-p 'org-mode)
5089 (let ((alist (org--setup-collect-keywords
5090 (org-make-options-regexp
5091 (append '("FILETAGS" "TAGS" "SETUPFILE")
5092 (and (not tags-only)
5093 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
5094 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
5095 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
5096 ;; Startup options. Get this early since it does change
5097 ;; behavior for other options (e.g., tags).
5098 (let ((startup (cdr (assq 'startup alist))))
5099 (dolist (option startup)
5100 (let ((entry (assoc-string option org-startup-options t)))
5101 (when entry
5102 (let ((var (nth 1 entry))
5103 (val (nth 2 entry)))
5104 (if (not (nth 3 entry)) (set (make-local-variable var) val)
5105 (unless (listp (symbol-value var))
5106 (set (make-local-variable var) nil))
5107 (add-to-list var val)))))))
5108 (setq-local org-file-tags
5109 (mapcar #'org-add-prop-inherited
5110 (cdr (assq 'filetags alist))))
5111 (setq org-current-tag-alist
5112 (append org-tag-persistent-alist
5113 (let ((tags (cdr (assq 'tags alist))))
5114 (if tags (org-tag-string-to-alist tags)
5115 org-tag-alist))))
5116 (setq org-tag-groups-alist
5117 (org-tag-alist-to-groups org-current-tag-alist))
5118 (unless tags-only
5119 ;; File properties.
5120 (setq-local org-file-properties (cdr (assq 'property alist)))
5121 ;; Archive location.
5122 (let ((archive (cdr (assq 'archive alist))))
5123 (when archive (setq-local org-archive-location archive)))
5124 ;; Category.
5125 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
5126 (when cat
5127 (setq-local org-category (intern cat))
5128 (setq-local org-file-properties
5129 (org--update-property-plist
5130 "CATEGORY" cat org-file-properties))))
5131 ;; Columns.
5132 (let ((column (cdr (assq 'columns alist))))
5133 (when column (setq-local org-columns-default-format column)))
5134 ;; Constants.
5135 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
5136 ;; Link abbreviations.
5137 (let ((links (cdr (assq 'link alist))))
5138 (when links (setq org-link-abbrev-alist-local (nreverse links))))
5139 ;; Priorities.
5140 (let ((priorities (cdr (assq 'priorities alist))))
5141 (when priorities
5142 (setq-local org-highest-priority (nth 0 priorities))
5143 (setq-local org-lowest-priority (nth 1 priorities))
5144 (setq-local org-default-priority (nth 2 priorities))))
5145 ;; Scripts.
5146 (let ((scripts (assq 'scripts alist)))
5147 (when scripts
5148 (setq-local org-use-sub-superscripts (cdr scripts))))
5149 ;; TODO keywords.
5150 (setq-local org-todo-kwd-alist nil)
5151 (setq-local org-todo-key-alist nil)
5152 (setq-local org-todo-key-trigger nil)
5153 (setq-local org-todo-keywords-1 nil)
5154 (setq-local org-done-keywords nil)
5155 (setq-local org-todo-heads nil)
5156 (setq-local org-todo-sets nil)
5157 (setq-local org-todo-log-states nil)
5158 (let ((todo-sequences
5159 (or (nreverse (cdr (assq 'todo alist)))
5160 (let ((d (default-value 'org-todo-keywords)))
5161 (if (not (stringp (car d))) d
5162 ;; XXX: Backward compatibility code.
5163 (list (cons org-todo-interpretation d)))))))
5164 (dolist (sequence todo-sequences)
5165 (let* ((sequence (or (run-hook-with-args-until-success
5166 'org-todo-setup-filter-hook sequence)
5167 sequence))
5168 (sequence-type (car sequence))
5169 (keywords (cdr sequence))
5170 (sep (member "|" keywords))
5171 names alist)
5172 (dolist (k (remove "|" keywords))
5173 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5175 (error "Invalid TODO keyword %s" k))
5176 (let ((name (match-string 1 k))
5177 (key (match-string 2 k))
5178 (log (org-extract-log-state-settings k)))
5179 (push name names)
5180 (push (cons name (and key (string-to-char key))) alist)
5181 (when log (push log org-todo-log-states))))
5182 (let* ((names (nreverse names))
5183 (done (if sep (org-remove-keyword-keys (cdr sep))
5184 (last names)))
5185 (head (car names))
5186 (tail (list sequence-type head (car done) (org-last done))))
5187 (add-to-list 'org-todo-heads head 'append)
5188 (push names org-todo-sets)
5189 (setq org-done-keywords (append org-done-keywords done nil))
5190 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5191 (setq org-todo-key-alist
5192 (append org-todo-key-alist
5193 (and alist
5194 (append '((:startgroup))
5195 (nreverse alist)
5196 '((:endgroup))))))
5197 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5198 (setq org-todo-sets (nreverse org-todo-sets)
5199 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5200 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5201 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5202 ;; Compute the regular expressions and other local variables.
5203 ;; Using `org-outline-regexp-bol' would complicate them much,
5204 ;; because of the fixed white space at the end of that string.
5205 (unless org-done-keywords
5206 (setq org-done-keywords
5207 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5208 (setq org-not-done-keywords
5209 (org-delete-all org-done-keywords
5210 (copy-sequence org-todo-keywords-1))
5211 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5212 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5213 org-not-done-heading-regexp
5214 (format org-heading-keyword-regexp-format org-not-done-regexp)
5215 org-todo-line-regexp
5216 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5217 org-complex-heading-regexp
5218 (concat "^\\(\\*+\\)"
5219 "\\(?: +" org-todo-regexp "\\)?"
5220 "\\(?: +\\(\\[#.\\]\\)\\)?"
5221 "\\(?: +\\(.*?\\)\\)??"
5222 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5223 "[ \t]*$")
5224 org-complex-heading-regexp-format
5225 (concat "^\\(\\*+\\)"
5226 "\\(?: +" org-todo-regexp "\\)?"
5227 "\\(?: +\\(\\[#.\\]\\)\\)?"
5228 "\\(?: +"
5229 ;; Stats cookies can be stuck to body.
5230 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5231 "\\(%s\\)"
5232 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5233 "\\)"
5234 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5235 "[ \t]*$")
5236 org-todo-line-tags-regexp
5237 (concat "^\\(\\*+\\)"
5238 "\\(?: +" org-todo-regexp "\\)?"
5239 "\\(?: +\\(.*?\\)\\)??"
5240 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5241 "[ \t]*$"))
5242 (org-compute-latex-and-related-regexp)))))
5244 (defun org--setup-collect-keywords (regexp &optional files alist)
5245 "Return setup keywords values as an alist.
5247 REGEXP matches a subset of setup keywords. FILES is a list of
5248 file names already visited. It is used to avoid circular setup
5249 files. ALIST, when non-nil, is the alist computed so far.
5251 Return value contains the following keys: `archive', `category',
5252 `columns', `constants', `filetags', `link', `priorities',
5253 `property', `scripts', `startup', `tags' and `todo'."
5254 (org-with-wide-buffer
5255 (goto-char (point-min))
5256 (let ((case-fold-search t))
5257 (while (re-search-forward regexp nil t)
5258 (let ((element (org-element-at-point)))
5259 (when (eq (org-element-type element) 'keyword)
5260 (let ((key (org-element-property :key element))
5261 (value (org-element-property :value element)))
5262 (cond
5263 ((equal key "ARCHIVE")
5264 (when (org-string-nw-p value)
5265 (push (cons 'archive value) alist)))
5266 ((equal key "CATEGORY") (push (cons 'category value) alist))
5267 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5268 ((equal key "CONSTANTS")
5269 (let* ((constants (assq 'constants alist))
5270 (store (cdr constants)))
5271 (dolist (pair (org-split-string value))
5272 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5273 pair)
5274 (let* ((name (match-string 1 pair))
5275 (value (match-string 2 pair))
5276 (old (assoc name store)))
5277 (if old (setcdr old value)
5278 (push (cons name value) store)))))
5279 (if constants (setcdr constants store)
5280 (push (cons 'constants store) alist))))
5281 ((equal key "FILETAGS")
5282 (when (org-string-nw-p value)
5283 (let ((old (assq 'filetags alist))
5284 (new (apply #'nconc
5285 (mapcar (lambda (x) (org-split-string x ":"))
5286 (org-split-string value)))))
5287 (if old (setcdr old (append new (cdr old)))
5288 (push (cons 'filetags new) alist)))))
5289 ((equal key "LINK")
5290 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5291 (let ((links (assq 'link alist))
5292 (pair (cons (match-string-no-properties 1 value)
5293 (match-string-no-properties 2 value))))
5294 (if links (push pair (cdr links))
5295 (push (list 'link pair) alist)))))
5296 ((equal key "OPTIONS")
5297 (when (and (org-string-nw-p value)
5298 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5299 (push (cons 'scripts (read (match-string 1 value))) alist)))
5300 ((equal key "PRIORITIES")
5301 (push (cons 'priorities
5302 (let ((prio (org-split-string value)))
5303 (if (< (length prio) 3) '(?A ?C ?B)
5304 (mapcar #'string-to-char prio))))
5305 alist))
5306 ((equal key "PROPERTY")
5307 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5308 (let* ((property (assq 'property alist))
5309 (value (org--update-property-plist
5310 (match-string-no-properties 1 value)
5311 (match-string-no-properties 2 value)
5312 (cdr property))))
5313 (if property (setcdr property value)
5314 (push (cons 'property value) alist)))))
5315 ((equal key "STARTUP")
5316 (let ((startup (assq 'startup alist)))
5317 (if startup
5318 (setcdr startup
5319 (append (cdr startup) (org-split-string value)))
5320 (push (cons 'startup (org-split-string value)) alist))))
5321 ((equal key "TAGS")
5322 (let ((tag-cell (assq 'tags alist)))
5323 (if tag-cell
5324 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5325 (push (cons 'tags value) alist))))
5326 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5327 (let ((todo (assq 'todo alist))
5328 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5329 (org-split-string value))))
5330 (if todo (push value (cdr todo))
5331 (push (list 'todo value) alist))))
5332 ((equal key "SETUPFILE")
5333 (unless buffer-read-only ; Do not check in Gnus messages.
5334 (let ((f (and (org-string-nw-p value)
5335 (expand-file-name
5336 (org-unbracket-string "\"" "\"" value)))))
5337 (when (and f (file-readable-p f) (not (member f files)))
5338 (with-temp-buffer
5339 (setq default-directory (file-name-directory f))
5340 (insert-file-contents f)
5341 (setq alist
5342 ;; Fake Org mode to benefit from cache
5343 ;; without recurring needlessly.
5344 (let ((major-mode 'org-mode))
5345 (org--setup-collect-keywords
5346 regexp (cons f files) alist)))))))))))))))
5347 alist)
5349 (defun org-tag-string-to-alist (s)
5350 "Return tag alist associated to string S.
5351 S is a value for TAGS keyword or produced with
5352 `org-tag-alist-to-string'. Return value is an alist suitable for
5353 `org-tag-alist' or `org-tag-persistent-alist'."
5354 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5355 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5356 "\\|{.+?}\\)" ; regular expression
5357 "\\(?:(\\(.\\))\\)?\\'"))
5358 alist group-flag)
5359 (dolist (tokens lines (cdr (nreverse alist)))
5360 (push '(:newline) alist)
5361 (while tokens
5362 (let ((token (pop tokens)))
5363 (pcase token
5364 ("{"
5365 (push '(:startgroup) alist)
5366 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5367 ("}"
5368 (push '(:endgroup) alist)
5369 (setq group-flag nil))
5370 ("["
5371 (push '(:startgrouptag) alist)
5372 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5373 ("]"
5374 (push '(:endgrouptag) alist)
5375 (setq group-flag nil))
5376 (":"
5377 (push '(:grouptags) alist))
5378 ((guard (string-match tag-re token))
5379 (let ((tag (match-string 1 token))
5380 (key (and (match-beginning 2)
5381 (string-to-char (match-string 2 token)))))
5382 ;; Push all tags in groups, no matter if they already
5383 ;; appear somewhere else in the list.
5384 (when (or group-flag (not (assoc tag alist)))
5385 (push (cons tag key) alist))))))))))
5387 (defun org-tag-alist-to-string (alist &optional skip-key)
5388 "Return tag string associated to ALIST.
5390 ALIST is an alist, as defined in `org-tag-alist' or
5391 `org-tag-persistent-alist', or produced with
5392 `org-tag-string-to-alist'.
5394 Return value is a string suitable as a value for \"TAGS\"
5395 keyword.
5397 When optional argument SKIP-KEY is non-nil, skip selection keys
5398 next to tags."
5399 (mapconcat (lambda (token)
5400 (pcase token
5401 (`(:startgroup) "{")
5402 (`(:endgroup) "}")
5403 (`(:startgrouptag) "[")
5404 (`(:endgrouptag) "]")
5405 (`(:grouptags) ":")
5406 (`(:newline) "\\n")
5407 ((and
5408 (guard (not skip-key))
5409 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5410 (format "%s(%c)" tag key))
5411 (`(,(and tag (pred stringp)) . ,_) tag)
5412 (_ (user-error "Invalid tag token: %S" token))))
5413 alist
5414 " "))
5416 (defun org-tag-alist-to-groups (alist)
5417 "Return group alist from tag ALIST.
5418 ALIST is an alist, as defined in `org-tag-alist' or
5419 `org-tag-persistent-alist', or produced with
5420 `org-tag-string-to-alist'. Return value is an alist following
5421 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5422 a string, summarizing TAGS, as a list of strings."
5423 (let (groups group-status current-group)
5424 (dolist (token alist (nreverse groups))
5425 (pcase token
5426 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5427 (`(,(or :endgroup :endgrouptag))
5428 (when (eq group-status 'append)
5429 (push (nreverse current-group) groups))
5430 (setq group-status nil))
5431 (`(:grouptags) (setq group-status 'append))
5432 ((and `(,tag . ,_) (guard group-status))
5433 (if (eq group-status 'append) (push tag current-group)
5434 (setq current-group (list tag))))
5435 (_ nil)))))
5437 (defun org-file-contents (file &optional noerror)
5438 "Return the contents of FILE, as a string."
5439 (if (and file (file-readable-p file))
5440 (with-temp-buffer
5441 (insert-file-contents file)
5442 (buffer-string))
5443 (funcall (if noerror 'message 'error)
5444 "Cannot read file \"%s\"%s"
5445 file
5446 (let ((from (buffer-file-name (buffer-base-buffer))))
5447 (if from (concat " (referenced in file \"" from "\")") "")))))
5449 (defun org-extract-log-state-settings (x)
5450 "Extract the log state setting from a TODO keyword string.
5451 This will extract info from a string like \"WAIT(w@/!)\"."
5452 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5453 (let ((kw (match-string 1 x))
5454 (log1 (and (match-end 3) (match-string 3 x)))
5455 (log2 (and (match-end 4) (match-string 4 x))))
5456 (and (or log1 log2)
5457 (list kw
5458 (and log1 (if (equal log1 "!") 'time 'note))
5459 (and log2 (if (equal log2 "!") 'time 'note)))))))
5461 (defun org-remove-keyword-keys (list)
5462 "Remove a pair of parenthesis at the end of each string in LIST."
5463 (mapcar (lambda (x)
5464 (if (string-match "(.*)$" x)
5465 (substring x 0 (match-beginning 0))
5467 list))
5469 (defun org-assign-fast-keys (alist)
5470 "Assign fast keys to a keyword-key alist.
5471 Respect keys that are already there."
5472 (let (new e (alt ?0))
5473 (while (setq e (pop alist))
5474 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5475 (cdr e)) ;; Key already assigned.
5476 (push e new)
5477 (let ((clist (string-to-list (downcase (car e))))
5478 (used (append new alist)))
5479 (when (= (car clist) ?@)
5480 (pop clist))
5481 (while (and clist (rassoc (car clist) used))
5482 (pop clist))
5483 (unless clist
5484 (while (rassoc alt used)
5485 (cl-incf alt)))
5486 (push (cons (car e) (or (car clist) alt)) new))))
5487 (nreverse new)))
5489 ;;; Some variables used in various places
5491 (defvar org-window-configuration nil
5492 "Used in various places to store a window configuration.")
5493 (defvar org-selected-window nil
5494 "Used in various places to store a window configuration.")
5495 (defvar org-finish-function nil
5496 "Function to be called when `C-c C-c' is used.
5497 This is for getting out of special buffers like capture.")
5498 (defvar org-last-state)
5500 ;; Defined somewhere in this file, but used before definition.
5501 (defvar org-entities) ;; defined in org-entities.el
5502 (defvar org-struct-menu)
5503 (defvar org-org-menu)
5504 (defvar org-tbl-menu)
5506 ;;;; Define the Org mode
5508 ;; We use a before-change function to check if a table might need
5509 ;; an update.
5510 (defvar org-table-may-need-update t
5511 "Indicates that a table might need an update.
5512 This variable is set by `org-before-change-function'.
5513 `org-table-align' sets it back to nil.")
5514 (defun org-before-change-function (_beg _end)
5515 "Every change indicates that a table might need an update."
5516 (setq org-table-may-need-update t))
5517 (defvar org-mode-map)
5518 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5519 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5520 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5521 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5522 (defvar org-table-buffer-is-an nil)
5524 (defvar bidi-paragraph-direction)
5525 (defvar buffer-face-mode-face)
5527 (require 'outline)
5529 ;; Other stuff we need.
5530 (require 'time-date)
5531 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5532 (require 'easymenu)
5533 (autoload 'easy-menu-add "easymenu")
5534 (require 'overlay)
5536 ;; (require 'org-macs) moved higher up in the file before it is first used
5537 (require 'org-entities)
5538 ;; (require 'org-compat) moved higher up in the file before it is first used
5539 (require 'org-faces)
5540 (require 'org-list)
5541 (require 'org-pcomplete)
5542 (require 'org-src)
5543 (require 'org-footnote)
5544 (require 'org-macro)
5546 ;; babel
5547 (require 'ob)
5549 ;;;###autoload
5550 (define-derived-mode org-mode outline-mode "Org"
5551 "Outline-based notes management and organizer, alias
5552 \"Carsten's outline-mode for keeping track of everything.\"
5554 Org mode develops organizational tasks around a NOTES file which
5555 contains information about projects as plain text. Org mode is
5556 implemented on top of Outline mode, which is ideal to keep the content
5557 of large files well structured. It supports ToDo items, deadlines and
5558 time stamps, which magically appear in the diary listing of the Emacs
5559 calendar. Tables are easily created with a built-in table editor.
5560 Plain text URL-like links connect to websites, emails (VM), Usenet
5561 messages (Gnus), BBDB entries, and any files related to the project.
5562 For printing and sharing of notes, an Org file (or a part of it)
5563 can be exported as a structured ASCII or HTML file.
5565 The following commands are available:
5567 \\{org-mode-map}"
5569 ;; Get rid of Outline menus, they are not needed
5570 ;; Need to do this here because define-derived-mode sets up
5571 ;; the keymap so late. Still, it is a waste to call this each time
5572 ;; we switch another buffer into Org mode.
5573 (define-key org-mode-map [menu-bar headings] 'undefined)
5574 (define-key org-mode-map [menu-bar hide] 'undefined)
5575 (define-key org-mode-map [menu-bar show] 'undefined)
5577 (org-load-modules-maybe)
5578 (org-install-agenda-files-menu)
5579 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5580 (add-to-invisibility-spec '(org-cwidth))
5581 (add-to-invisibility-spec '(org-hide-block . t))
5582 (setq-local outline-regexp org-outline-regexp)
5583 (setq-local outline-level 'org-outline-level)
5584 (setq bidi-paragraph-direction 'left-to-right)
5585 (when (and org-ellipsis
5586 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5587 (fboundp 'make-glyph-code))
5588 (unless org-display-table
5589 (setq org-display-table (make-display-table)))
5590 (set-display-table-slot
5591 org-display-table 4
5592 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5593 (if (stringp org-ellipsis) org-ellipsis "..."))))
5594 (setq buffer-display-table org-display-table))
5595 (org-set-regexps-and-options)
5596 (org-set-font-lock-defaults)
5597 (when (and org-tag-faces (not org-tags-special-faces-re))
5598 ;; tag faces set outside customize.... force initialization.
5599 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5600 ;; Calc embedded
5601 (setq-local calc-embedded-open-mode "# ")
5602 ;; Modify a few syntax entries
5603 (modify-syntax-entry ?@ "w")
5604 (modify-syntax-entry ?\" "\"")
5605 (modify-syntax-entry ?\\ "_")
5606 (modify-syntax-entry ?~ "_")
5607 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5608 ;; Activate before-change-function
5609 (setq-local org-table-may-need-update t)
5610 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5611 ;; Check for running clock before killing a buffer
5612 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5613 ;; Initialize macros templates.
5614 (org-macro-initialize-templates)
5615 ;; Initialize radio targets.
5616 (org-update-radio-target-regexp)
5617 ;; Indentation.
5618 (setq-local indent-line-function 'org-indent-line)
5619 (setq-local indent-region-function 'org-indent-region)
5620 ;; Filling and auto-filling.
5621 (org-setup-filling)
5622 ;; Comments.
5623 (org-setup-comments-handling)
5624 ;; Initialize cache.
5625 (org-element-cache-reset)
5626 ;; Beginning/end of defun
5627 (setq-local beginning-of-defun-function 'org-backward-element)
5628 (setq-local end-of-defun-function
5629 (lambda ()
5630 (if (not (org-at-heading-p))
5631 (org-forward-element)
5632 (org-forward-element)
5633 (forward-char -1))))
5634 ;; Next error for sparse trees
5635 (setq-local next-error-function 'org-occur-next-match)
5636 ;; Make sure dependence stuff works reliably, even for users who set it
5637 ;; too late :-(
5638 (if org-enforce-todo-dependencies
5639 (add-hook 'org-blocker-hook
5640 'org-block-todo-from-children-or-siblings-or-parent)
5641 (remove-hook 'org-blocker-hook
5642 'org-block-todo-from-children-or-siblings-or-parent))
5643 (if org-enforce-todo-checkbox-dependencies
5644 (add-hook 'org-blocker-hook
5645 'org-block-todo-from-checkboxes)
5646 (remove-hook 'org-blocker-hook
5647 'org-block-todo-from-checkboxes))
5649 ;; Align options lines
5650 (setq-local
5651 align-mode-rules-list
5652 '((org-in-buffer-settings
5653 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5654 (modes . '(org-mode)))))
5656 ;; Imenu
5657 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5659 ;; Make isearch reveal context
5660 (setq-local outline-isearch-open-invisible-function
5661 (lambda (&rest _) (org-show-context 'isearch)))
5663 ;; Setup the pcomplete hooks
5664 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5665 (setq-local pcomplete-command-name-function 'org-command-at-point)
5666 (setq-local pcomplete-default-completion-function 'ignore)
5667 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5668 (setq-local pcomplete-termination-string "")
5669 (setq-local buffer-face-mode-face 'org-default)
5671 ;; If empty file that did not turn on Org mode automatically, make
5672 ;; it to.
5673 (when (and org-insert-mode-line-in-empty-file
5674 (called-interactively-p 'any)
5675 (= (point-min) (point-max)))
5676 (insert "# -*- mode: org -*-\n\n"))
5677 (unless org-inhibit-startup
5678 (org-unmodified
5679 (when org-startup-with-beamer-mode (org-beamer-mode))
5680 (when org-startup-align-all-tables
5681 (org-table-map-tables #'org-table-align t))
5682 (when org-startup-with-inline-images (org-display-inline-images))
5683 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5684 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5685 (when org-startup-truncated (setq truncate-lines t))
5686 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5687 (org-refresh-effort-properties)))
5688 ;; Try to set `org-hide' face correctly.
5689 (let ((foreground (org-find-invisible-foreground)))
5690 (when foreground
5691 (set-face-foreground 'org-hide foreground))))
5693 ;; Update `customize-package-emacs-version-alist'
5694 (add-to-list 'customize-package-emacs-version-alist
5695 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5696 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5697 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5698 ("9.0" . "26.1")))
5700 (defvar org-mode-transpose-word-syntax-table
5701 (let ((st (make-syntax-table text-mode-syntax-table)))
5702 (dolist (c org-emphasis-alist st)
5703 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5705 (when (fboundp 'abbrev-table-put)
5706 (abbrev-table-put org-mode-abbrev-table
5707 :parents (list text-mode-abbrev-table)))
5709 (defun org-find-invisible-foreground ()
5710 (let ((candidates (remove
5711 "unspecified-bg"
5712 (nconc
5713 (list (face-background 'default)
5714 (face-background 'org-default))
5715 (mapcar
5716 (lambda (alist)
5717 (when (boundp alist)
5718 (cdr (assq 'background-color (symbol-value alist)))))
5719 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5720 (list (face-foreground 'org-hide))))))
5721 (car (remove nil candidates))))
5723 (defun org-current-time (&optional rounding-minutes past)
5724 "Current time, possibly rounded to ROUNDING-MINUTES.
5725 When ROUNDING-MINUTES is not an integer, fall back on the car of
5726 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5727 the rounding returns a past time."
5728 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5729 (car org-time-stamp-rounding-minutes)))
5730 (time (decode-time)) res)
5731 (if (< r 1)
5732 (current-time)
5733 (setq res
5734 (apply 'encode-time
5735 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5736 (nthcdr 2 time))))
5737 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5738 (seconds-to-time (- (float-time res) (* r 60)))
5739 res))))
5741 (defun org-today ()
5742 "Return today date, considering `org-extend-today-until'."
5743 (time-to-days
5744 (time-subtract (current-time)
5745 (list 0 (* 3600 org-extend-today-until) 0))))
5747 ;;;; Font-Lock stuff, including the activators
5749 (defvar org-mouse-map (make-sparse-keymap))
5750 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5751 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5752 (when org-mouse-1-follows-link
5753 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5754 (when org-tab-follows-link
5755 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5756 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5758 (require 'font-lock)
5760 (defconst org-non-link-chars "]\t\n\r<>")
5761 (defvar org-link-types-re nil
5762 "Matches a link that has a url-like prefix like \"http:\"")
5763 (defvar org-link-re-with-space nil
5764 "Matches a link with spaces, optional angular brackets around it.")
5765 (defvar org-link-re-with-space2 nil
5766 "Matches a link with spaces, optional angular brackets around it.")
5767 (defvar org-link-re-with-space3 nil
5768 "Matches a link with spaces, only for internal part in bracket links.")
5769 (defvar org-angle-link-re nil
5770 "Matches link with angular brackets, spaces are allowed.")
5771 (defvar org-plain-link-re nil
5772 "Matches plain link, without spaces.")
5773 (defvar org-bracket-link-regexp nil
5774 "Matches a link in double brackets.")
5775 (defvar org-bracket-link-analytic-regexp nil
5776 "Regular expression used to analyze links.
5777 Here is what the match groups contain after a match:
5778 1: http:
5779 2: http
5780 3: path
5781 4: [desc]
5782 5: desc")
5783 (defvar org-bracket-link-analytic-regexp++ nil
5784 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5785 (defvar org-any-link-re nil
5786 "Regular expression matching any link.")
5788 (defconst org-match-sexp-depth 3
5789 "Number of stacked braces for sub/superscript matching.")
5791 (defun org-create-multibrace-regexp (left right n)
5792 "Create a regular expression which will match a balanced sexp.
5793 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5794 as single character strings.
5795 The regexp returned will match the entire expression including the
5796 delimiters. It will also define a single group which contains the
5797 match except for the outermost delimiters. The maximum depth of
5798 stacked delimiters is N. Escaping delimiters is not possible."
5799 (let* ((nothing (concat "[^" left right "]*?"))
5800 (or "\\|")
5801 (re nothing)
5802 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5803 (while (> n 1)
5804 (setq n (1- n)
5805 re (concat re or next)
5806 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5807 (concat left "\\(" re "\\)" right)))
5809 (defconst org-match-substring-regexp
5810 (concat
5811 "\\(\\S-\\)\\([_^]\\)\\("
5812 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5813 "\\|"
5814 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5815 "\\|"
5816 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5817 "The regular expression matching a sub- or superscript.")
5819 (defconst org-match-substring-with-braces-regexp
5820 (concat
5821 "\\(\\S-\\)\\([_^]\\)"
5822 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5823 "The regular expression matching a sub- or superscript, forcing braces.")
5825 (defun org-make-link-regexps ()
5826 "Update the link regular expressions.
5827 This should be called after the variable `org-link-parameters' has changed."
5828 (let ((types-re (regexp-opt (org-link-types) t)))
5829 (setq org-link-types-re
5830 (concat "\\`" types-re ":")
5831 org-link-re-with-space
5832 (concat "<?" types-re ":"
5833 "\\([^" org-non-link-chars " ]"
5834 "[^" org-non-link-chars "]*"
5835 "[^" org-non-link-chars " ]\\)>?")
5836 org-link-re-with-space2
5837 (concat "<?" types-re ":"
5838 "\\([^" org-non-link-chars " ]"
5839 "[^\t\n\r]*"
5840 "[^" org-non-link-chars " ]\\)>?")
5841 org-link-re-with-space3
5842 (concat "<?" types-re ":"
5843 "\\([^" org-non-link-chars " ]"
5844 "[^\t\n\r]*\\)")
5845 org-angle-link-re
5846 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5847 types-re)
5848 org-plain-link-re
5849 (concat
5850 "\\<" types-re ":"
5851 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5852 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5853 org-bracket-link-regexp
5854 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5855 org-bracket-link-analytic-regexp
5856 (concat
5857 "\\[\\["
5858 "\\(" types-re ":\\)?"
5859 "\\([^]]+\\)"
5860 "\\]"
5861 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5862 "\\]")
5863 org-bracket-link-analytic-regexp++
5864 (concat
5865 "\\[\\["
5866 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5867 "\\([^]]+\\)"
5868 "\\]"
5869 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5870 "\\]")
5871 org-any-link-re
5872 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5873 org-angle-link-re "\\)\\|\\("
5874 org-plain-link-re "\\)"))))
5876 (org-make-link-regexps)
5878 (defvar org-emph-face nil)
5880 (defun org-do-emphasis-faces (limit)
5881 "Run through the buffer and emphasize strings."
5882 (let (rtn a)
5883 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5884 (let* ((border (char-after (match-beginning 3)))
5885 (bre (regexp-quote (char-to-string border))))
5886 (when (and (not (= border (char-after (match-beginning 4))))
5887 (not (string-match-p (concat bre ".*" bre)
5888 (replace-regexp-in-string
5889 "\n" " "
5890 (substring (match-string 2) 1 -1)))))
5891 (setq rtn t)
5892 (setq a (assoc (match-string 3) org-emphasis-alist))
5893 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5894 'face
5895 (nth 1 a))
5896 (and (nth 2 a)
5897 (org-remove-flyspell-overlays-in
5898 (match-beginning 0) (match-end 0)))
5899 (add-text-properties (match-beginning 2) (match-end 2)
5900 '(font-lock-multiline t org-emphasis t))
5901 (when org-hide-emphasis-markers
5902 (add-text-properties (match-end 4) (match-beginning 5)
5903 '(invisible org-link))
5904 (add-text-properties (match-beginning 3) (match-end 3)
5905 '(invisible org-link)))))
5906 (goto-char (1+ (match-beginning 0))))
5907 rtn))
5909 (defun org-emphasize (&optional char)
5910 "Insert or change an emphasis, i.e. a font like bold or italic.
5911 If there is an active region, change that region to a new emphasis.
5912 If there is no region, just insert the marker characters and position
5913 the cursor between them.
5914 CHAR should be the marker character. If it is a space, it means to
5915 remove the emphasis of the selected region.
5916 If CHAR is not given (for example in an interactive call) it will be
5917 prompted for."
5918 (interactive)
5919 (let ((erc org-emphasis-regexp-components)
5920 (string "") beg end move s)
5921 (if (org-region-active-p)
5922 (setq beg (region-beginning)
5923 end (region-end)
5924 string (buffer-substring beg end))
5925 (setq move t))
5927 (unless char
5928 (message "Emphasis marker or tag: [%s]"
5929 (mapconcat #'car org-emphasis-alist ""))
5930 (setq char (read-char-exclusive)))
5931 (if (equal char ?\s)
5932 (setq s ""
5933 move nil)
5934 (unless (assoc (char-to-string char) org-emphasis-alist)
5935 (user-error "No such emphasis marker: \"%c\"" char))
5936 (setq s (char-to-string char)))
5937 (while (and (> (length string) 1)
5938 (equal (substring string 0 1) (substring string -1))
5939 (assoc (substring string 0 1) org-emphasis-alist))
5940 (setq string (substring string 1 -1)))
5941 (setq string (concat s string s))
5942 (when beg (delete-region beg end))
5943 (unless (or (bolp)
5944 (string-match (concat "[" (nth 0 erc) "\n]")
5945 (char-to-string (char-before (point)))))
5946 (insert " "))
5947 (unless (or (eobp)
5948 (string-match (concat "[" (nth 1 erc) "\n]")
5949 (char-to-string (char-after (point)))))
5950 (insert " ") (backward-char 1))
5951 (insert string)
5952 (and move (backward-char 1))))
5954 (defconst org-nonsticky-props
5955 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5957 (defsubst org-rear-nonsticky-at (pos)
5958 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5960 (defun org-activate-links (limit)
5961 "Add link properties to links.
5962 This includes angle, plain, and bracket links."
5963 (catch :exit
5964 (while (re-search-forward org-any-link-re limit t)
5965 (let* ((start (match-beginning 0))
5966 (end (match-end 0))
5967 (style (cond ((eq ?< (char-after start)) 'angle)
5968 ((eq ?\[ (char-after (1+ start))) 'bracket)
5969 (t 'plain))))
5970 (when (and (memq style org-highlight-links)
5971 ;; Do not confuse plain links with tags.
5972 (not (and (eq style 'plain)
5973 (let ((face (get-text-property
5974 (max (1- start) (point-min)) 'face)))
5975 (if (consp face) (memq 'org-tag face)
5976 (eq 'org-tag face))))))
5977 (let* ((link-object (save-excursion
5978 (goto-char start)
5979 (save-match-data (org-element-link-parser))))
5980 (link (org-element-property :raw-link link-object))
5981 (type (org-element-property :type link-object))
5982 (path (org-element-property :path link-object))
5983 (properties ;for link's visible part
5984 (list
5985 'face (pcase (org-link-get-parameter type :face)
5986 ((and (pred functionp) face) (funcall face path))
5987 ((and (pred facep) face) face)
5988 ((and (pred consp) face) face) ;anonymous
5989 (_ 'org-link))
5990 'mouse-face (or (org-link-get-parameter type :mouse-face)
5991 'highlight)
5992 'keymap (or (org-link-get-parameter type :keymap)
5993 org-mouse-map)
5994 'help-echo (pcase (org-link-get-parameter type :help-echo)
5995 ((and (pred stringp) echo) echo)
5996 ((and (pred functionp) echo) echo)
5997 (_ (concat "LINK: " link)))
5998 'htmlize-link (pcase (org-link-get-parameter type
5999 :htmlize-link)
6000 ((and (pred functionp) f) (funcall f))
6001 (_ `(:uri ,link)))
6002 'font-lock-multiline t)))
6003 (org-remove-flyspell-overlays-in start end)
6004 (org-rear-nonsticky-at end)
6005 (if (not (eq 'bracket style))
6006 (add-text-properties start end properties)
6007 ;; Handle invisible parts in bracket links.
6008 (remove-text-properties start end '(invisible nil))
6009 (let ((hidden
6010 (append `(invisible
6011 ,(or (org-link-get-parameter type :display)
6012 'org-link))
6013 properties))
6014 (visible-start (or (match-beginning 4) (match-beginning 2)))
6015 (visible-end (or (match-end 4) (match-end 2))))
6016 (add-text-properties start visible-start hidden)
6017 (add-text-properties visible-start visible-end properties)
6018 (add-text-properties visible-end end hidden)
6019 (org-rear-nonsticky-at visible-start)
6020 (org-rear-nonsticky-at visible-end)))
6021 (let ((f (org-link-get-parameter type :activate-func)))
6022 (when (functionp f)
6023 (funcall f start end path (eq style 'bracket))))
6024 (throw :exit t))))) ;signal success
6025 nil))
6027 (defun org-activate-code (limit)
6028 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
6029 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6030 (remove-text-properties (match-beginning 0) (match-end 0)
6031 '(display t invisible t intangible t))
6034 (defcustom org-src-fontify-natively t
6035 "When non-nil, fontify code in code blocks.
6036 See also the `org-block' face."
6037 :type 'boolean
6038 :version "24.4"
6039 :package-version '(Org . "8.3")
6040 :group 'org-appearance
6041 :group 'org-babel)
6043 (defcustom org-allow-promoting-top-level-subtree nil
6044 "When non-nil, allow promoting a top level subtree.
6045 The leading star of the top level headline will be replaced
6046 by a #."
6047 :type 'boolean
6048 :version "24.1"
6049 :group 'org-appearance)
6051 (defun org-fontify-meta-lines-and-blocks (limit)
6052 (condition-case nil
6053 (org-fontify-meta-lines-and-blocks-1 limit)
6054 (error (message "org-mode fontification error in %S at %d"
6055 (current-buffer)
6056 (line-number-at-pos)))))
6058 (defun org-fontify-meta-lines-and-blocks-1 (limit)
6059 "Fontify #+ lines and blocks."
6060 (let ((case-fold-search t))
6061 (when (re-search-forward
6062 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
6063 limit t)
6064 (let ((beg (match-beginning 0))
6065 (block-start (match-end 0))
6066 (block-end nil)
6067 (lang (match-string 7))
6068 (beg1 (line-beginning-position 2))
6069 (dc1 (downcase (match-string 2)))
6070 (dc3 (downcase (match-string 3)))
6071 end end1 quoting block-type)
6072 (cond
6073 ((and (match-end 4) (equal dc3 "+begin"))
6074 ;; Truly a block
6075 (setq block-type (downcase (match-string 5))
6076 quoting (member block-type org-protecting-blocks))
6077 (when (re-search-forward
6078 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
6079 nil t) ;; on purpose, we look further than LIMIT
6080 (setq end (min (point-max) (match-end 0))
6081 end1 (min (point-max) (1- (match-beginning 0))))
6082 (setq block-end (match-beginning 0))
6083 (when quoting
6084 (org-remove-flyspell-overlays-in beg1 end1)
6085 (remove-text-properties beg end
6086 '(display t invisible t intangible t)))
6087 (add-text-properties
6088 beg end '(font-lock-fontified t font-lock-multiline t))
6089 (add-text-properties beg beg1 '(face org-meta-line))
6090 (org-remove-flyspell-overlays-in beg beg1)
6091 (add-text-properties ; For end_src
6092 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6093 (org-remove-flyspell-overlays-in end1 end)
6094 (cond
6095 ((and lang (not (string= lang "")) org-src-fontify-natively)
6096 (org-src-font-lock-fontify-block lang block-start block-end)
6097 (add-text-properties beg1 block-end '(src-block t)))
6098 (quoting
6099 (add-text-properties beg1 (min (point-max) (1+ end1))
6100 (list 'face
6101 (list :inherit
6102 (let ((face-name
6103 (intern (format "org-block-%s" lang))))
6104 (append (and (facep face-name) (list face-name))
6105 '(org-block))))))) ; end of source block
6106 ((not org-fontify-quote-and-verse-blocks))
6107 ((string= block-type "quote")
6108 (add-face-text-property
6109 beg1 (min (point-max) (1+ end1)) 'org-quote t))
6110 ((string= block-type "verse")
6111 (add-face-text-property
6112 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
6113 (add-text-properties beg beg1 '(face org-block-begin-line))
6114 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6115 '(face org-block-end-line))
6117 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6118 (org-remove-flyspell-overlays-in
6119 (match-beginning 0)
6120 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6121 (add-text-properties
6122 beg (match-end 3)
6123 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6124 '(font-lock-fontified t invisible t)
6125 '(font-lock-fontified t face org-document-info-keyword)))
6126 (add-text-properties
6127 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6128 (if (string-equal dc1 "+title:")
6129 '(font-lock-fontified t face org-document-title)
6130 '(font-lock-fontified t face org-document-info))))
6131 ((string-prefix-p "+caption" dc1)
6132 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6133 (remove-text-properties (match-beginning 0) (match-end 0)
6134 '(display t invisible t intangible t))
6135 ;; Handle short captions.
6136 (save-excursion
6137 (beginning-of-line)
6138 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6139 (add-text-properties (line-beginning-position) (match-end 1)
6140 '(font-lock-fontified t face org-meta-line))
6141 (add-text-properties (match-end 0) (line-end-position)
6142 '(font-lock-fontified t face org-block))
6144 ((member dc3 '(" " ""))
6145 (org-remove-flyspell-overlays-in beg (match-end 0))
6146 (add-text-properties
6147 beg (match-end 0)
6148 '(font-lock-fontified t face font-lock-comment-face)))
6149 (t ;; just any other in-buffer setting, but not indented
6150 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6151 (remove-text-properties (match-beginning 0) (match-end 0)
6152 '(display t invisible t intangible t))
6153 (add-text-properties beg (match-end 0)
6154 '(font-lock-fontified t face org-meta-line))
6155 t))))))
6157 (defun org-fontify-drawers (limit)
6158 "Fontify drawers."
6159 (when (re-search-forward org-drawer-regexp limit t)
6160 (add-text-properties
6161 (match-beginning 0) (match-end 0)
6162 '(font-lock-fontified t face org-special-keyword))
6163 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6166 (defun org-fontify-macros (limit)
6167 "Fontify macros."
6168 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6169 (add-text-properties
6170 (match-beginning 0) (match-end 0)
6171 '(font-lock-fontified t face org-macro))
6172 (when org-hide-macro-markers
6173 (add-text-properties (match-end 2) (match-beginning 2)
6174 '(invisible t))
6175 (add-text-properties (match-beginning 1) (match-end 1)
6176 '(invisible t)))
6177 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6180 (defun org-activate-footnote-links (limit)
6181 "Add text properties for footnotes."
6182 (let ((fn (org-footnote-next-reference-or-definition limit)))
6183 (when fn
6184 (let* ((beg (nth 1 fn))
6185 (end (nth 2 fn))
6186 (label (car fn))
6187 (referencep (/= (line-beginning-position) beg)))
6188 (when (and referencep (nth 3 fn))
6189 (save-excursion
6190 (goto-char beg)
6191 (search-forward (or label "fn:"))
6192 (org-remove-flyspell-overlays-in beg (match-end 0))))
6193 (add-text-properties beg end
6194 (list 'mouse-face 'highlight
6195 'keymap org-mouse-map
6196 'help-echo
6197 (if referencep "Footnote reference"
6198 "Footnote definition")
6199 'font-lock-fontified t
6200 'font-lock-multiline t
6201 'face 'org-footnote))))))
6203 (defun org-activate-dates (limit)
6204 "Add text properties for dates."
6205 (when (and (re-search-forward org-tsr-regexp-both limit t)
6206 (not (equal (char-before (match-beginning 0)) 91)))
6207 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6208 (add-text-properties (match-beginning 0) (match-end 0)
6209 (list 'mouse-face 'highlight
6210 'keymap org-mouse-map))
6211 (org-rear-nonsticky-at (match-end 0))
6212 (when org-display-custom-times
6213 (if (match-end 3)
6214 (org-display-custom-time (match-beginning 3) (match-end 3))
6215 (org-display-custom-time (match-beginning 1) (match-end 1))))
6218 (defvar-local org-target-link-regexp nil
6219 "Regular expression matching radio targets in plain text.")
6221 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6222 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6223 border border border))
6224 "Regular expression matching a link target.")
6226 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6227 "Regular expression matching a radio target.")
6229 (defconst org-any-target-regexp
6230 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6231 "Regular expression matching any target.")
6233 (defun org-activate-target-links (limit)
6234 "Add text properties for target matches."
6235 (when org-target-link-regexp
6236 (let ((case-fold-search t))
6237 (when (re-search-forward org-target-link-regexp limit t)
6238 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6239 (add-text-properties (match-beginning 1) (match-end 1)
6240 (list 'mouse-face 'highlight
6241 'keymap org-mouse-map
6242 'help-echo "Radio target link"
6243 'org-linked-text t))
6244 (org-rear-nonsticky-at (match-end 1))
6245 t))))
6247 (defun org-update-radio-target-regexp ()
6248 "Find all radio targets in this file and update the regular expression.
6249 Also refresh fontification if needed."
6250 (interactive)
6251 (let ((old-regexp org-target-link-regexp)
6252 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6253 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6254 (targets
6255 (org-with-wide-buffer
6256 (goto-char (point-min))
6257 (let (rtn)
6258 (while (re-search-forward org-radio-target-regexp nil t)
6259 ;; Make sure point is really within the object.
6260 (backward-char)
6261 (let ((obj (org-element-context)))
6262 (when (eq (org-element-type obj) 'radio-target)
6263 (cl-pushnew (org-element-property :value obj) rtn
6264 :test #'equal))))
6265 rtn))))
6266 (setq org-target-link-regexp
6267 (and targets
6268 (concat before-re
6269 (mapconcat
6270 (lambda (x)
6271 (replace-regexp-in-string
6272 " +" "\\s-+" (regexp-quote x) t t))
6273 targets
6274 "\\|")
6275 after-re)))
6276 (unless (equal old-regexp org-target-link-regexp)
6277 ;; Clean-up cache.
6278 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6279 ((not org-target-link-regexp) old-regexp)
6281 (concat before-re
6282 (mapconcat
6283 (lambda (re)
6284 (substring re (length before-re)
6285 (- (length after-re))))
6286 (list old-regexp org-target-link-regexp)
6287 "\\|")
6288 after-re)))))
6289 (org-with-wide-buffer
6290 (goto-char (point-min))
6291 (while (re-search-forward regexp nil t)
6292 (org-element-cache-refresh (match-beginning 1)))))
6293 ;; Re fontify buffer.
6294 (when (memq 'radio org-highlight-links)
6295 (org-restart-font-lock)))))
6297 (defun org-hide-wide-columns (limit)
6298 (let (s e)
6299 (setq s (text-property-any (point) (or limit (point-max))
6300 'org-cwidth t))
6301 (when s
6302 (setq e (next-single-property-change s 'org-cwidth))
6303 (add-text-properties s e '(invisible org-cwidth))
6304 (goto-char e)
6305 t)))
6307 (defvar org-latex-and-related-regexp nil
6308 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6310 (defun org-compute-latex-and-related-regexp ()
6311 "Compute regular expression for LaTeX, entities and sub/superscript.
6312 Result depends on variable `org-highlight-latex-and-related'."
6313 (setq-local
6314 org-latex-and-related-regexp
6315 (let* ((re-sub
6316 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6317 ((eq org-use-sub-superscripts '{})
6318 (list org-match-substring-with-braces-regexp))
6319 (org-use-sub-superscripts (list org-match-substring-regexp))))
6320 (re-latex
6321 (when (memq 'latex org-highlight-latex-and-related)
6322 (let ((matchers (plist-get org-format-latex-options :matchers)))
6323 (delq nil
6324 (mapcar (lambda (x)
6325 (and (member (car x) matchers) (nth 1 x)))
6326 org-latex-regexps)))))
6327 (re-entities
6328 (when (memq 'entities org-highlight-latex-and-related)
6329 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6330 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6332 (defun org-do-latex-and-related (limit)
6333 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6334 LIMIT bounds the search for syntax to highlight. Stop at first
6335 highlighted object, if any. Return t if some highlighting was
6336 done, nil otherwise."
6337 (when (org-string-nw-p org-latex-and-related-regexp)
6338 (catch 'found
6339 (while (re-search-forward org-latex-and-related-regexp limit t)
6340 (unless
6341 (cl-some
6342 (lambda (f)
6343 (memq f '(org-code org-verbatim underline org-special-keyword)))
6344 (save-excursion
6345 (goto-char (1+ (match-beginning 0)))
6346 (face-at-point nil t)))
6347 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6348 '(?_ ?^))
6350 0)))
6351 (font-lock-prepend-text-property
6352 (+ offset (match-beginning 0)) (match-end 0)
6353 'face 'org-latex-and-related)
6354 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6355 '(font-lock-multiline t)))
6356 (throw 'found t)))
6357 nil)))
6359 (defun org-restart-font-lock ()
6360 "Restart `font-lock-mode', to force refontification."
6361 (when (and (boundp 'font-lock-mode) font-lock-mode)
6362 (font-lock-mode -1)
6363 (font-lock-mode 1)))
6365 (defun org-activate-tags (limit)
6366 (when (re-search-forward
6367 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6368 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6369 (add-text-properties (match-beginning 1) (match-end 1)
6370 (list 'mouse-face 'highlight
6371 'keymap org-mouse-map))
6372 (org-rear-nonsticky-at (match-end 1))
6375 (defun org-outline-level ()
6376 "Compute the outline level of the heading at point.
6378 If this is called at a normal headline, the level is the number
6379 of stars. Use `org-reduced-level' to remove the effect of
6380 `org-odd-levels'. Unlike to `org-current-level', this function
6381 takes into consideration inlinetasks."
6382 (org-with-wide-buffer
6383 (end-of-line)
6384 (if (re-search-backward org-outline-regexp-bol nil t)
6385 (1- (- (match-end 0) (match-beginning 0)))
6386 0)))
6388 (defvar org-font-lock-keywords nil)
6390 (defsubst org-re-property (property &optional literal allow-null value)
6391 "Return a regexp matching a PROPERTY line.
6393 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6394 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6395 non-nil, match properties even without a value.
6397 Match group 3 is set to the value when it exists. If there is no
6398 value and ALLOW-NULL is non-nil, it is set to the empty string.
6400 With optional argument VALUE, match only property lines with
6401 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6402 unless LITERAL is non-nil."
6403 (concat
6404 "^\\(?4:[ \t]*\\)"
6405 (format "\\(?1::\\(?2:%s\\):\\)"
6406 (if literal property (regexp-quote property)))
6407 (cond (value
6408 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6409 (if literal value (regexp-quote value))))
6410 (allow-null
6411 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6413 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6415 (defconst org-property-re
6416 (org-re-property "\\S-+" 'literal t)
6417 "Regular expression matching a property line.
6418 There are four matching groups:
6419 1: :PROPKEY: including the leading and trailing colon,
6420 2: PROPKEY without the leading and trailing colon,
6421 3: PROPVAL without leading or trailing spaces,
6422 4: the indentation of the current line,
6423 5: trailing whitespace.")
6425 (defvar org-font-lock-hook nil
6426 "Functions to be called for special font lock stuff.")
6428 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6430 (defvar org-font-lock-set-keywords-hook nil
6431 "Functions that can manipulate `org-font-lock-extra-keywords'.
6432 This is called after `org-font-lock-extra-keywords' is defined, but before
6433 it is installed to be used by font lock. This can be useful if something
6434 needs to be inserted at a specific position in the font-lock sequence.")
6436 (defun org-font-lock-hook (limit)
6437 "Run `org-font-lock-hook' within LIMIT."
6438 (run-hook-with-args 'org-font-lock-hook limit))
6440 (defun org-set-font-lock-defaults ()
6441 "Set font lock defaults for the current buffer."
6442 (let* ((em org-fontify-emphasized-text)
6443 (lk org-highlight-links)
6444 (org-font-lock-extra-keywords
6445 (list
6446 ;; Call the hook
6447 '(org-font-lock-hook)
6448 ;; Headlines
6449 `(,(if org-fontify-whole-heading-line
6450 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6451 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6452 (1 (org-get-level-face 1))
6453 (2 (org-get-level-face 2))
6454 (3 (org-get-level-face 3)))
6455 ;; Table lines
6456 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6457 (1 'org-table t))
6458 ;; Table internals
6459 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6460 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6461 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6462 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6463 ;; Drawers
6464 '(org-fontify-drawers)
6465 ;; Properties
6466 (list org-property-re
6467 '(1 'org-special-keyword t)
6468 '(3 'org-property-value t))
6469 ;; Link related fontification.
6470 '(org-activate-links)
6471 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6472 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6473 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6474 (when (memq 'footnote lk) '(org-activate-footnote-links))
6475 ;; Targets.
6476 (list org-any-target-regexp '(0 'org-target t))
6477 ;; Diary sexps.
6478 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6479 ;; Macro
6480 '(org-fontify-macros)
6481 '(org-hide-wide-columns (0 nil append))
6482 ;; TODO keyword
6483 (list (format org-heading-keyword-regexp-format
6484 org-todo-regexp)
6485 '(2 (org-get-todo-face 2) t))
6486 ;; DONE
6487 (if org-fontify-done-headline
6488 (list (format org-heading-keyword-regexp-format
6489 (concat
6490 "\\(?:"
6491 (mapconcat 'regexp-quote org-done-keywords "\\|")
6492 "\\)"))
6493 '(2 'org-headline-done t))
6494 nil)
6495 ;; Priorities
6496 '(org-font-lock-add-priority-faces)
6497 ;; Tags
6498 '(org-font-lock-add-tag-faces)
6499 ;; Tags groups
6500 (when (and org-group-tags org-tag-groups-alist)
6501 (list (concat org-outline-regexp-bol ".+\\(:"
6502 (regexp-opt (mapcar 'car org-tag-groups-alist))
6503 ":\\).*$")
6504 '(1 'org-tag-group prepend)))
6505 ;; Special keywords
6506 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6507 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6508 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6509 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6510 ;; Emphasis
6511 (when em '(org-do-emphasis-faces))
6512 ;; Checkboxes
6513 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6514 1 'org-checkbox prepend)
6515 (when (cdr (assq 'checkbox org-list-automatic-rules))
6516 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6517 (0 (org-get-checkbox-statistics-face) t)))
6518 ;; Description list items
6519 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6520 1 'org-list-dt prepend)
6521 ;; ARCHIVEd headings
6522 (list (concat
6523 org-outline-regexp-bol
6524 "\\(.*:" org-archive-tag ":.*\\)")
6525 '(1 'org-archived prepend))
6526 ;; Specials
6527 '(org-do-latex-and-related)
6528 '(org-fontify-entities)
6529 '(org-raise-scripts)
6530 ;; Code
6531 '(org-activate-code (1 'org-code t))
6532 ;; COMMENT
6533 (list (format
6534 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6535 org-todo-regexp
6536 org-comment-string)
6537 '(9 'org-special-keyword t))
6538 ;; Blocks and meta lines
6539 '(org-fontify-meta-lines-and-blocks))))
6540 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6541 (run-hooks 'org-font-lock-set-keywords-hook)
6542 ;; Now set the full font-lock-keywords
6543 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6544 (setq-local font-lock-defaults
6545 '(org-font-lock-keywords t nil nil backward-paragraph))
6546 (kill-local-variable 'font-lock-keywords)
6547 nil))
6549 (defun org-toggle-pretty-entities ()
6550 "Toggle the composition display of entities as UTF8 characters."
6551 (interactive)
6552 (setq-local org-pretty-entities (not org-pretty-entities))
6553 (org-restart-font-lock)
6554 (if org-pretty-entities
6555 (message "Entities are now displayed as UTF8 characters")
6556 (save-restriction
6557 (widen)
6558 (decompose-region (point-min) (point-max))
6559 (message "Entities are now displayed as plain text"))))
6561 (defvar-local org-custom-properties-overlays nil
6562 "List of overlays used for custom properties.")
6564 (defun org-toggle-custom-properties-visibility ()
6565 "Display or hide properties in `org-custom-properties'."
6566 (interactive)
6567 (if org-custom-properties-overlays
6568 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6569 (setq org-custom-properties-overlays nil))
6570 (when org-custom-properties
6571 (org-with-wide-buffer
6572 (goto-char (point-min))
6573 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6574 (while (re-search-forward regexp nil t)
6575 (let ((end (cdr (save-match-data (org-get-property-block)))))
6576 (when (and end (< (point) end))
6577 ;; Hide first custom property in current drawer.
6578 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6579 (overlay-put o 'invisible t)
6580 (overlay-put o 'org-custom-property t)
6581 (push o org-custom-properties-overlays))
6582 ;; Hide additional custom properties in the same drawer.
6583 (while (re-search-forward regexp end t)
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 ;; Each entry is limited to a single property drawer.
6589 (outline-next-heading)))))))
6591 (defun org-fontify-entities (limit)
6592 "Find an entity to fontify."
6593 (let (ee)
6594 (when org-pretty-entities
6595 (catch 'match
6596 ;; "\_ "-family is left out on purpose. Only the first one,
6597 ;; i.e., "\_ ", could be fontified anyway, and it would be
6598 ;; confusing when adding a second white space character.
6599 (while (re-search-forward
6600 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6601 limit t)
6602 (when (and (not (org-at-comment-p))
6603 (setq ee (org-entity-get (match-string 1)))
6604 (= (length (nth 6 ee)) 1))
6605 (let* ((end (if (equal (match-string 2) "{}")
6606 (match-end 2)
6607 (match-end 1))))
6608 (add-text-properties
6609 (match-beginning 0) end
6610 (list 'font-lock-fontified t))
6611 (compose-region (match-beginning 0) end
6612 (nth 6 ee) nil)
6613 (backward-char 1)
6614 (throw 'match t))))
6615 nil))))
6617 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6618 "Fontify string S like in Org mode."
6619 (with-temp-buffer
6620 (insert s)
6621 (let ((org-odd-levels-only odd-levels))
6622 (org-mode)
6623 (org-font-lock-ensure)
6624 (buffer-string))))
6626 (defvar org-m nil)
6627 (defvar org-l nil)
6628 (defvar org-f nil)
6629 (defun org-get-level-face (n)
6630 "Get the right face for match N in font-lock matching of headlines."
6631 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6632 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6633 (if org-cycle-level-faces
6634 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6635 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6636 (cond
6637 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6638 ((eq n 2) org-f)
6639 (t (unless org-level-color-stars-only org-f))))
6641 (defun org-face-from-face-or-color (context inherit face-or-color)
6642 "Create a face list that inherits INHERIT, but sets the foreground color.
6643 When FACE-OR-COLOR is not a string, just return it."
6644 (if (stringp face-or-color)
6645 (list :inherit inherit
6646 (cdr (assoc context org-faces-easy-properties))
6647 face-or-color)
6648 face-or-color))
6650 (defun org-get-todo-face (kwd)
6651 "Get the right face for a TODO keyword KWD.
6652 If KWD is a number, get the corresponding match group."
6653 (when (numberp kwd) (setq kwd (match-string kwd)))
6654 (or (org-face-from-face-or-color
6655 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6656 (and (member kwd org-done-keywords) 'org-done)
6657 'org-todo))
6659 (defun org-get-priority-face (priority)
6660 "Get the right face for PRIORITY.
6661 PRIORITY is a character."
6662 (or (org-face-from-face-or-color
6663 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6664 'org-priority))
6666 (defun org-get-tag-face (tag)
6667 "Get the right face for TAG.
6668 If TAG is a number, get the corresponding match group."
6669 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6670 (or (org-face-from-face-or-color
6671 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6672 'org-tag)))
6674 (defun org-font-lock-add-priority-faces (limit)
6675 "Add the special priority faces."
6676 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6677 (add-text-properties
6678 (match-beginning 1) (match-end 1)
6679 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6680 'font-lock-fontified t))))
6682 (defun org-font-lock-add-tag-faces (limit)
6683 "Add the special tag faces."
6684 (when (and org-tag-faces org-tags-special-faces-re)
6685 (while (re-search-forward org-tags-special-faces-re limit t)
6686 (add-text-properties (match-beginning 1) (match-end 1)
6687 (list 'face (org-get-tag-face 1)
6688 'font-lock-fontified t))
6689 (backward-char 1))))
6691 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6692 "Remove fontification and activation overlays from links."
6693 (font-lock-default-unfontify-region beg end)
6694 (let* ((buffer-undo-list t)
6695 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6696 (inhibit-modification-hooks t)
6697 deactivate-mark buffer-file-name buffer-file-truename)
6698 (decompose-region beg end)
6699 (remove-text-properties beg end
6700 '(mouse-face t keymap t org-linked-text t
6701 invisible t intangible t
6702 org-emphasis t))
6703 (org-remove-font-lock-display-properties beg end)))
6705 (defconst org-script-display '(((raise -0.3) (height 0.7))
6706 ((raise 0.3) (height 0.7))
6707 ((raise -0.5))
6708 ((raise 0.5)))
6709 "Display properties for showing superscripts and subscripts.")
6711 (defun org-remove-font-lock-display-properties (beg end)
6712 "Remove specific display properties that have been added by font lock.
6713 The will remove the raise properties that are used to show superscripts
6714 and subscripts."
6715 (let (next prop)
6716 (while (< beg end)
6717 (setq next (next-single-property-change beg 'display nil end)
6718 prop (get-text-property beg 'display))
6719 (when (member prop org-script-display)
6720 (put-text-property beg next 'display nil))
6721 (setq beg next))))
6723 (defun org-raise-scripts (limit)
6724 "Add raise properties to sub/superscripts."
6725 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6726 (re-search-forward
6727 (if (eq org-use-sub-superscripts t)
6728 org-match-substring-regexp
6729 org-match-substring-with-braces-regexp)
6730 limit t))
6731 (let* ((pos (point)) table-p comment-p
6732 (mpos (match-beginning 3))
6733 (emph-p (get-text-property mpos 'org-emphasis))
6734 (link-p (get-text-property mpos 'mouse-face))
6735 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6736 (goto-char (point-at-bol))
6737 (setq table-p (looking-at-p org-table-dataline-regexp)
6738 comment-p (looking-at-p "^[ \t]*#[ +]"))
6739 (goto-char pos)
6740 ;; Handle a_b^c
6741 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6742 (unless (or comment-p emph-p link-p keyw-p)
6743 (put-text-property (match-beginning 3) (match-end 0)
6744 'display
6745 (if (equal (char-after (match-beginning 2)) ?^)
6746 (nth (if table-p 3 1) org-script-display)
6747 (nth (if table-p 2 0) org-script-display)))
6748 (add-text-properties (match-beginning 2) (match-end 2)
6749 (list 'invisible t
6750 'org-dwidth t 'org-dwidth-n 1))
6751 (if (and (eq (char-after (match-beginning 3)) ?{)
6752 (eq (char-before (match-end 3)) ?}))
6753 (progn
6754 (add-text-properties
6755 (match-beginning 3) (1+ (match-beginning 3))
6756 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6757 (add-text-properties
6758 (1- (match-end 3)) (match-end 3)
6759 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6760 t)))
6762 ;;;; Visibility cycling, including org-goto and indirect buffer
6764 ;;; Cycling
6766 (defvar-local org-cycle-global-status nil)
6767 (put 'org-cycle-global-status 'org-state t)
6768 (defvar-local org-cycle-subtree-status nil)
6769 (put 'org-cycle-subtree-status 'org-state t)
6771 (defvar org-inlinetask-min-level)
6773 (defun org-unlogged-message (&rest args)
6774 "Display a message, but avoid logging it in the *Messages* buffer."
6775 (let ((message-log-max nil))
6776 (apply 'message args)))
6778 ;;;###autoload
6779 (defun org-cycle (&optional arg)
6780 "TAB-action and visibility cycling for Org mode.
6782 This is the command invoked in Org mode by the `TAB' key. Its main
6783 purpose is outline visibility cycling, but it also invokes other actions
6784 in special contexts.
6786 When this function is called with a `\\[universal-argument]' prefix, rotate \
6787 the entire
6788 buffer through 3 states (global cycling)
6789 1. OVERVIEW: Show only top-level headlines.
6790 2. CONTENTS: Show all headlines of all levels, but no body text.
6791 3. SHOW ALL: Show everything.
6793 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6794 switch to the startup visibility,
6795 determined by the variable `org-startup-folded', and by any VISIBILITY
6796 properties in the buffer.
6798 With a `\\[universal-argument] \\[universal-argument] \
6799 \\[universal-argument]' prefix argument, show the entire buffer, including
6800 any drawers.
6802 When inside a table, re-align the table and move to the next field.
6804 When point is at the beginning of a headline, rotate the subtree started
6805 by this line through 3 different states (local cycling)
6806 1. FOLDED: Only the main headline is shown.
6807 2. CHILDREN: The main headline and the direct children are shown.
6808 From this state, you can move to one of the children
6809 and zoom in further.
6810 3. SUBTREE: Show the entire subtree, including body text.
6811 If there is no subtree, switch directly from CHILDREN to FOLDED.
6813 When point is at the beginning of an empty headline and the variable
6814 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6815 of the headline by demoting and promoting it to likely levels. This
6816 speeds up creation document structure by pressing `TAB' once or several
6817 times right after creating a new headline.
6819 When there is a numeric prefix, go up to a heading with level ARG, do
6820 a `show-subtree' and return to the previous cursor position. If ARG
6821 is negative, go up that many levels.
6823 When point is not at the beginning of a headline, execute the global
6824 binding for `TAB', which is re-indenting the line. See the option
6825 `org-cycle-emulate-tab' for details.
6827 As a special case, if point is at the beginning of the buffer and there is
6828 no headline in line 1, this function will act as if called with prefix arg
6829 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6830 prefix arg, but only
6831 if the variable `org-cycle-global-at-bob' is t."
6832 (interactive "P")
6833 (org-load-modules-maybe)
6834 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6835 (and org-cycle-level-after-item/entry-creation
6836 (or (org-cycle-level)
6837 (org-cycle-item-indentation))))
6838 (let* ((limit-level
6839 (or org-cycle-max-level
6840 (and (boundp 'org-inlinetask-min-level)
6841 org-inlinetask-min-level
6842 (1- org-inlinetask-min-level))))
6843 (nstars (and limit-level
6844 (if org-odd-levels-only
6845 (and limit-level (1- (* limit-level 2)))
6846 limit-level)))
6847 (org-outline-regexp
6848 (if (not (derived-mode-p 'org-mode))
6849 outline-regexp
6850 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6851 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6852 (not (looking-at org-outline-regexp))))
6853 (org-cycle-hook
6854 (if bob-special
6855 (delq 'org-optimize-window-after-visibility-change
6856 (copy-sequence org-cycle-hook))
6857 org-cycle-hook))
6858 (pos (point)))
6860 (cond
6862 ((equal arg '(16))
6863 (setq last-command 'dummy)
6864 (org-set-startup-visibility)
6865 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6867 ((equal arg '(64))
6868 (outline-show-all)
6869 (org-unlogged-message "Entire buffer visible, including drawers"))
6871 ((equal arg '(4)) (org-cycle-internal-global))
6873 ;; Try hiding block at point.
6874 ((org-hide-block-toggle-maybe))
6876 ;; Try cdlatex TAB completion
6877 ((org-try-cdlatex-tab))
6879 ;; Table: enter it or move to the next field.
6880 ((org-at-table-p 'any)
6881 (if (org-at-table.el-p)
6882 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6883 Use `\\[org-edit-special]' to edit table.el tables"))
6884 (if arg (org-table-edit-field t)
6885 (org-table-justify-field-maybe)
6886 (call-interactively 'org-table-next-field))))
6888 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6890 ;; Global cycling: delegate to `org-cycle-internal-global'.
6891 (bob-special (org-cycle-internal-global))
6893 ;; Drawers: delegate to `org-flag-drawer'.
6894 ((save-excursion
6895 (beginning-of-line 1)
6896 (looking-at org-drawer-regexp))
6897 (org-flag-drawer ; toggle block visibility
6898 (not (get-char-property (match-end 0) 'invisible))))
6900 ;; Show-subtree, ARG levels up from here.
6901 ((integerp arg)
6902 (save-excursion
6903 (org-back-to-heading)
6904 (outline-up-heading (if (< arg 0) (- arg)
6905 (- (funcall outline-level) arg)))
6906 (org-show-subtree)))
6908 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6909 ((and (featurep 'org-inlinetask)
6910 (org-inlinetask-at-task-p)
6911 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6912 (org-inlinetask-toggle-visibility))
6914 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6915 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6916 (save-excursion (move-beginning-of-line 1)
6917 (looking-at org-outline-regexp)))
6918 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6919 (org-cycle-internal-local))
6921 ;; From there: TAB emulation and template completion.
6922 (buffer-read-only (org-back-to-heading))
6924 ((run-hook-with-args-until-success
6925 'org-tab-after-check-for-cycling-hook))
6927 ((org-try-structure-completion))
6929 ((run-hook-with-args-until-success
6930 'org-tab-before-tab-emulation-hook))
6932 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6933 (or (not (bolp))
6934 (not (looking-at org-outline-regexp))))
6935 (call-interactively (global-key-binding "\t")))
6937 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6938 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6939 (or (and (eq org-cycle-emulate-tab 'white)
6940 (= (match-end 0) (point-at-eol)))
6941 (and (eq org-cycle-emulate-tab 'whitestart)
6942 (>= (match-end 0) pos))))
6944 (eq org-cycle-emulate-tab t))
6945 (call-interactively (global-key-binding "\t")))
6947 (t (save-excursion
6948 (org-back-to-heading)
6949 (org-cycle)))))))
6951 (defun org-cycle-internal-global ()
6952 "Do the global cycling action."
6953 ;; Hack to avoid display of messages for .org attachments in Gnus
6954 (let ((ga (string-match "\\*fontification" (buffer-name))))
6955 (cond
6956 ((and (eq last-command this-command)
6957 (eq org-cycle-global-status 'overview))
6958 ;; We just created the overview - now do table of contents
6959 ;; This can be slow in very large buffers, so indicate action
6960 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6961 (unless ga (org-unlogged-message "CONTENTS..."))
6962 (org-content)
6963 (unless ga (org-unlogged-message "CONTENTS...done"))
6964 (setq org-cycle-global-status 'contents)
6965 (run-hook-with-args 'org-cycle-hook 'contents))
6967 ((and (eq last-command this-command)
6968 (eq org-cycle-global-status 'contents))
6969 ;; We just showed the table of contents - now show everything
6970 (run-hook-with-args 'org-pre-cycle-hook 'all)
6971 (outline-show-all)
6972 (unless ga (org-unlogged-message "SHOW ALL"))
6973 (setq org-cycle-global-status 'all)
6974 (run-hook-with-args 'org-cycle-hook 'all))
6977 ;; Default action: go to overview
6978 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6979 (org-overview)
6980 (unless ga (org-unlogged-message "OVERVIEW"))
6981 (setq org-cycle-global-status 'overview)
6982 (run-hook-with-args 'org-cycle-hook 'overview)))))
6984 (defvar org-called-with-limited-levels nil
6985 "Non-nil when `org-with-limited-levels' is currently active.")
6987 (defun org-invisible-p (&optional pos)
6988 "Non-nil if the character after POS is invisible.
6989 If POS is nil, use `point' instead."
6990 (get-char-property (or pos (point)) 'invisible))
6992 (defun org-cycle-internal-local ()
6993 "Do the local cycling action."
6994 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6995 ;; First, determine end of headline (EOH), end of subtree or item
6996 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6997 (save-excursion
6998 (if (org-at-item-p)
6999 (progn
7000 (beginning-of-line)
7001 (setq struct (org-list-struct))
7002 (setq eoh (point-at-eol))
7003 (setq eos (org-list-get-item-end-before-blank (point) struct))
7004 (setq has-children (org-list-has-child-p (point) struct)))
7005 (org-back-to-heading)
7006 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7007 (setq eos (save-excursion (org-end-of-subtree t t)
7008 (when (bolp) (backward-char)) (point)))
7009 (setq has-children
7010 (or (save-excursion
7011 (let ((level (funcall outline-level)))
7012 (outline-next-heading)
7013 (and (org-at-heading-p t)
7014 (> (funcall outline-level) level))))
7015 (save-excursion
7016 (org-list-search-forward (org-item-beginning-re) eos t)))))
7017 ;; Determine end invisible part of buffer (EOL)
7018 (beginning-of-line 2)
7019 (while (and (not (eobp)) ;This is like `next-line'.
7020 (get-char-property (1- (point)) 'invisible))
7021 (goto-char (next-single-char-property-change (point) 'invisible))
7022 (and (eolp) (beginning-of-line 2)))
7023 (setq eol (point)))
7024 ;; Find out what to do next and set `this-command'
7025 (cond
7026 ((= eos eoh)
7027 ;; Nothing is hidden behind this heading
7028 (unless (org-before-first-heading-p)
7029 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7030 (org-unlogged-message "EMPTY ENTRY")
7031 (setq org-cycle-subtree-status nil)
7032 (save-excursion
7033 (goto-char eos)
7034 (outline-next-heading)
7035 (when (org-invisible-p) (org-flag-heading nil))))
7036 ((and (or (>= eol eos)
7037 (not (string-match "\\S-" (buffer-substring eol eos))))
7038 (or has-children
7039 (not (setq children-skipped
7040 org-cycle-skip-children-state-if-no-children))))
7041 ;; Entire subtree is hidden in one line: children view
7042 (unless (org-before-first-heading-p)
7043 (run-hook-with-args 'org-pre-cycle-hook 'children))
7044 (if (org-at-item-p)
7045 (org-list-set-item-visibility (point-at-bol) struct 'children)
7046 (org-show-entry)
7047 (org-with-limited-levels (org-show-children))
7048 ;; FIXME: This slows down the func way too much.
7049 ;; How keep drawers hidden in subtree anyway?
7050 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
7051 ;; (org-cycle-hide-drawers 'subtree))
7053 ;; Fold every list in subtree to top-level items.
7054 (when (eq org-cycle-include-plain-lists 'integrate)
7055 (save-excursion
7056 (org-back-to-heading)
7057 (while (org-list-search-forward (org-item-beginning-re) eos t)
7058 (beginning-of-line 1)
7059 (let* ((struct (org-list-struct))
7060 (prevs (org-list-prevs-alist struct))
7061 (end (org-list-get-bottom-point struct)))
7062 (dolist (e (org-list-get-all-items (point) struct prevs))
7063 (org-list-set-item-visibility e struct 'folded))
7064 (goto-char (if (< end eos) end eos)))))))
7065 (org-unlogged-message "CHILDREN")
7066 (save-excursion
7067 (goto-char eos)
7068 (outline-next-heading)
7069 (when (org-invisible-p) (org-flag-heading nil)))
7070 (setq org-cycle-subtree-status 'children)
7071 (unless (org-before-first-heading-p)
7072 (run-hook-with-args 'org-cycle-hook 'children)))
7073 ((or children-skipped
7074 (and (eq last-command this-command)
7075 (eq org-cycle-subtree-status 'children)))
7076 ;; We just showed the children, or no children are there,
7077 ;; now show everything.
7078 (unless (org-before-first-heading-p)
7079 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7080 (outline-flag-region eoh eos nil)
7081 (org-unlogged-message
7082 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7083 (setq org-cycle-subtree-status 'subtree)
7084 (unless (org-before-first-heading-p)
7085 (run-hook-with-args 'org-cycle-hook 'subtree)))
7087 ;; Default action: hide the subtree.
7088 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7089 (outline-flag-region eoh eos t)
7090 (org-unlogged-message "FOLDED")
7091 (setq org-cycle-subtree-status 'folded)
7092 (unless (org-before-first-heading-p)
7093 (run-hook-with-args 'org-cycle-hook 'folded))))))
7095 ;;;###autoload
7096 (defun org-global-cycle (&optional arg)
7097 "Cycle the global visibility. For details see `org-cycle'.
7098 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7099 With a numeric prefix, show all headlines up to that level."
7100 (interactive "P")
7101 (let ((org-cycle-include-plain-lists
7102 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7103 (cond
7104 ((integerp arg)
7105 (outline-show-all)
7106 (outline-hide-sublevels arg)
7107 (setq org-cycle-global-status 'contents))
7108 ((equal arg '(4))
7109 (org-set-startup-visibility)
7110 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7112 (org-cycle '(4))))))
7114 (defun org-set-startup-visibility ()
7115 "Set the visibility required by startup options and properties."
7116 (cond
7117 ((eq org-startup-folded t)
7118 (org-overview))
7119 ((eq org-startup-folded 'content)
7120 (org-content))
7121 ((or (eq org-startup-folded 'showeverything)
7122 (eq org-startup-folded nil))
7123 (outline-show-all)))
7124 (unless (eq org-startup-folded 'showeverything)
7125 (when org-hide-block-startup (org-hide-block-all))
7126 (org-set-visibility-according-to-property 'no-cleanup)
7127 (org-cycle-hide-archived-subtrees 'all)
7128 (org-cycle-hide-drawers 'all)
7129 (org-cycle-show-empty-lines t)))
7131 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7132 "Switch subtree visibilities according to :VISIBILITY: property."
7133 (interactive)
7134 (org-with-wide-buffer
7135 (goto-char (point-min))
7136 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7137 (if (not (org-at-property-p)) (outline-next-heading)
7138 (let ((state (match-string 3)))
7139 (save-excursion
7140 (org-back-to-heading t)
7141 (outline-hide-subtree)
7142 (org-reveal)
7143 (cond
7144 ((equal state "folded")
7145 (outline-hide-subtree))
7146 ((equal state "children")
7147 (org-show-hidden-entry)
7148 (org-show-children))
7149 ((equal state "content")
7150 (save-excursion
7151 (save-restriction
7152 (org-narrow-to-subtree)
7153 (org-content))))
7154 ((member state '("all" "showall"))
7155 (outline-show-subtree)))))))
7156 (unless no-cleanup
7157 (org-cycle-hide-archived-subtrees 'all)
7158 (org-cycle-hide-drawers 'all)
7159 (org-cycle-show-empty-lines 'all))))
7161 ;; This function uses outline-regexp instead of the more fundamental
7162 ;; org-outline-regexp so that org-cycle-global works outside of Org
7163 ;; buffers, where outline-regexp is needed.
7164 (defun org-overview ()
7165 "Switch to overview mode, showing only top-level headlines.
7166 This shows all headlines with a level equal or greater than the level
7167 of the first headline in the buffer. This is important, because if the
7168 first headline is not level one, then (hide-sublevels 1) gives confusing
7169 results."
7170 (interactive)
7171 (save-excursion
7172 (let ((level
7173 (save-excursion
7174 (goto-char (point-min))
7175 (when (re-search-forward (concat "^" outline-regexp) nil t)
7176 (goto-char (match-beginning 0))
7177 (funcall outline-level)))))
7178 (and level (outline-hide-sublevels level)))))
7180 (defun org-content (&optional arg)
7181 "Show all headlines in the buffer, like a table of contents.
7182 With numerical argument N, show content up to level N."
7183 (interactive "P")
7184 (org-overview)
7185 (save-excursion
7186 ;; Visit all headings and show their offspring
7187 (and (integerp arg) (org-overview))
7188 (goto-char (point-max))
7189 (catch 'exit
7190 (while (and (progn (condition-case nil
7191 (outline-previous-visible-heading 1)
7192 (error (goto-char (point-min))))
7194 (looking-at org-outline-regexp))
7195 (if (integerp arg)
7196 (org-show-children (1- arg))
7197 (outline-show-branches))
7198 (when (bobp) (throw 'exit nil))))))
7200 (defun org-optimize-window-after-visibility-change (state)
7201 "Adjust the window after a change in outline visibility.
7202 This function is the default value of the hook `org-cycle-hook'."
7203 (when (get-buffer-window (current-buffer))
7204 (cond
7205 ((eq state 'content) nil)
7206 ((eq state 'all) nil)
7207 ((eq state 'folded) nil)
7208 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7209 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7211 (defun org-remove-empty-overlays-at (pos)
7212 "Remove outline overlays that do not contain non-white stuff."
7213 (dolist (o (overlays-at pos))
7214 (and (eq 'outline (overlay-get o 'invisible))
7215 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7216 (overlay-end o))))
7217 (delete-overlay o))))
7219 (defun org-clean-visibility-after-subtree-move ()
7220 "Fix visibility issues after moving a subtree."
7221 ;; First, find a reasonable region to look at:
7222 ;; Start two siblings above, end three below
7223 (let* ((beg (save-excursion
7224 (and (org-get-last-sibling)
7225 (org-get-last-sibling))
7226 (point)))
7227 (end (save-excursion
7228 (and (org-get-next-sibling)
7229 (org-get-next-sibling)
7230 (org-get-next-sibling))
7231 (if (org-at-heading-p)
7232 (point-at-eol)
7233 (point))))
7234 (level (looking-at "\\*+"))
7235 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7236 (save-excursion
7237 (save-restriction
7238 (narrow-to-region beg end)
7239 (when re
7240 ;; Properly fold already folded siblings
7241 (goto-char (point-min))
7242 (while (re-search-forward re nil t)
7243 (when (and (not (org-invisible-p))
7244 (save-excursion
7245 (goto-char (point-at-eol)) (org-invisible-p)))
7246 (outline-hide-entry))))
7247 (org-cycle-show-empty-lines 'overview)
7248 (org-cycle-hide-drawers 'overview)))))
7250 (defun org-cycle-show-empty-lines (state)
7251 "Show empty lines above all visible headlines.
7252 The region to be covered depends on STATE when called through
7253 `org-cycle-hook'. Lisp program can use t for STATE to get the
7254 entire buffer covered. Note that an empty line is only shown if there
7255 are at least `org-cycle-separator-lines' empty lines before the headline."
7256 (when (/= org-cycle-separator-lines 0)
7257 (save-excursion
7258 (let* ((n (abs org-cycle-separator-lines))
7259 (re (cond
7260 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7261 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7262 (t (let ((ns (number-to-string (- n 2))))
7263 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7264 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7265 beg end)
7266 (cond
7267 ((memq state '(overview contents t))
7268 (setq beg (point-min) end (point-max)))
7269 ((memq state '(children folded))
7270 (setq beg (point)
7271 end (progn (org-end-of-subtree t t)
7272 (line-beginning-position 2)))))
7273 (when beg
7274 (goto-char beg)
7275 (while (re-search-forward re end t)
7276 (unless (get-char-property (match-end 1) 'invisible)
7277 (let ((e (match-end 1))
7278 (b (if (>= org-cycle-separator-lines 0)
7279 (match-beginning 1)
7280 (save-excursion
7281 (goto-char (match-beginning 0))
7282 (skip-chars-backward " \t\n")
7283 (line-end-position)))))
7284 (outline-flag-region b e nil))))))))
7285 ;; Never hide empty lines at the end of the file.
7286 (save-excursion
7287 (goto-char (point-max))
7288 (outline-previous-heading)
7289 (outline-end-of-heading)
7290 (when (and (looking-at "[ \t\n]+")
7291 (= (match-end 0) (point-max)))
7292 (outline-flag-region (point) (match-end 0) nil))))
7294 (defun org-show-empty-lines-in-parent ()
7295 "Move to the parent and re-show empty lines before visible headlines."
7296 (save-excursion
7297 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7298 (org-cycle-show-empty-lines context))))
7300 (defun org-files-list ()
7301 "Return `org-agenda-files' list, plus all open Org files.
7302 This is useful for operations that need to scan all of a user's
7303 open and agenda-wise Org files."
7304 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7305 (dolist (buf (buffer-list))
7306 (with-current-buffer buf
7307 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7308 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7309 files))
7311 (defsubst org-entry-beginning-position ()
7312 "Return the beginning position of the current entry."
7313 (save-excursion (org-back-to-heading t) (point)))
7315 (defsubst org-entry-end-position ()
7316 "Return the end position of the current entry."
7317 (save-excursion (outline-next-heading) (point)))
7319 (defun org-cycle-hide-drawers (state &optional exceptions)
7320 "Re-hide all drawers after a visibility state change.
7321 When non-nil, optional argument EXCEPTIONS is a list of strings
7322 specifying which drawers should not be hidden."
7323 (when (and (derived-mode-p 'org-mode)
7324 (not (memq state '(overview folded contents))))
7325 (save-excursion
7326 (let* ((globalp (memq state '(contents all)))
7327 (beg (if globalp (point-min) (point)))
7328 (end (if globalp (point-max)
7329 (if (eq state 'children)
7330 (save-excursion (outline-next-heading) (point))
7331 (org-end-of-subtree t)))))
7332 (goto-char beg)
7333 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7334 (unless (member-ignore-case (match-string 1) exceptions)
7335 (let ((drawer (org-element-at-point)))
7336 (when (memq (org-element-type drawer) '(drawer property-drawer))
7337 (org-flag-drawer t drawer)
7338 ;; Make sure to skip drawer entirely or we might flag
7339 ;; it another time when matching its ending line with
7340 ;; `org-drawer-regexp'.
7341 (goto-char (org-element-property :end drawer))))))))))
7343 (defun org-flag-drawer (flag &optional element)
7344 "When FLAG is non-nil, hide the drawer we are at.
7345 Otherwise make it visible. When optional argument ELEMENT is
7346 a parsed drawer, as returned by `org-element-at-point', hide or
7347 show that drawer instead."
7348 (let ((drawer (or element
7349 (and (save-excursion
7350 (beginning-of-line)
7351 (looking-at-p org-drawer-regexp))
7352 (org-element-at-point)))))
7353 (when (memq (org-element-type drawer) '(drawer property-drawer))
7354 (let ((post (org-element-property :post-affiliated drawer)))
7355 (save-excursion
7356 (outline-flag-region
7357 (progn (goto-char post) (line-end-position))
7358 (progn (goto-char (org-element-property :end drawer))
7359 (skip-chars-backward " \r\t\n")
7360 (line-end-position))
7361 flag))
7362 ;; When the drawer is hidden away, make sure point lies in
7363 ;; a visible part of the buffer.
7364 (when (and flag (> (line-beginning-position) post))
7365 (goto-char post))))))
7367 (defun org-subtree-end-visible-p ()
7368 "Is the end of the current subtree visible?"
7369 (pos-visible-in-window-p
7370 (save-excursion (org-end-of-subtree t) (point))))
7372 (defun org-first-headline-recenter ()
7373 "Move cursor to the first headline and recenter the headline."
7374 (let ((window (get-buffer-window)))
7375 (when window
7376 (goto-char (point-min))
7377 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7378 (set-window-start window (line-beginning-position))))))
7380 ;;; Saving and restoring visibility
7382 (defun org-outline-overlay-data (&optional use-markers)
7383 "Return a list of the locations of all outline overlays.
7384 These are overlays with the `invisible' property value `outline'.
7385 The return value is a list of cons cells, with start and stop
7386 positions for each overlay.
7387 If USE-MARKERS is set, return the positions as markers."
7388 (let (beg end)
7389 (org-with-wide-buffer
7390 (delq nil
7391 (mapcar (lambda (o)
7392 (when (eq (overlay-get o 'invisible) 'outline)
7393 (setq beg (overlay-start o)
7394 end (overlay-end o))
7395 (and beg end (> end beg)
7396 (if use-markers
7397 (cons (copy-marker beg)
7398 (copy-marker end t))
7399 (cons beg end)))))
7400 (overlays-in (point-min) (point-max)))))))
7402 (defun org-set-outline-overlay-data (data)
7403 "Create visibility overlays for all positions in DATA.
7404 DATA should have been made by `org-outline-overlay-data'."
7405 (org-with-wide-buffer
7406 (outline-show-all)
7407 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7409 ;;; Folding of blocks
7411 (defvar-local org-hide-block-overlays nil
7412 "Overlays hiding blocks.")
7414 (defun org-block-map (function &optional start end)
7415 "Call FUNCTION at the head of all source blocks in the current buffer.
7416 Optional arguments START and END can be used to limit the range."
7417 (let ((start (or start (point-min)))
7418 (end (or end (point-max))))
7419 (save-excursion
7420 (goto-char start)
7421 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7422 (save-excursion
7423 (save-match-data
7424 (goto-char (match-beginning 0))
7425 (funcall function)))))))
7427 (defun org-hide-block-toggle-all ()
7428 "Toggle the visibility of all blocks in the current buffer."
7429 (org-block-map 'org-hide-block-toggle))
7431 (defun org-hide-block-all ()
7432 "Fold all blocks in the current buffer."
7433 (interactive)
7434 (org-show-block-all)
7435 (org-block-map 'org-hide-block-toggle-maybe))
7437 (defun org-show-block-all ()
7438 "Unfold all blocks in the current buffer."
7439 (interactive)
7440 (mapc #'delete-overlay org-hide-block-overlays)
7441 (setq org-hide-block-overlays nil))
7443 (defun org-hide-block-toggle-maybe ()
7444 "Toggle visibility of block at point.
7445 Unlike to `org-hide-block-toggle', this function does not throw
7446 an error. Return a non-nil value when toggling is successful."
7447 (interactive)
7448 (ignore-errors (org-hide-block-toggle)))
7450 (defun org-hide-block-toggle (&optional force)
7451 "Toggle the visibility of the current block.
7452 When optional argument FORCE is `off', make block visible. If it
7453 is non-nil, hide it unconditionally. Throw an error when not at
7454 a block. Return a non-nil value when toggling is successful."
7455 (interactive)
7456 (let ((element (org-element-at-point)))
7457 (unless (memq (org-element-type element)
7458 '(center-block comment-block dynamic-block example-block
7459 export-block quote-block special-block
7460 src-block verse-block))
7461 (user-error "Not at a block"))
7462 (let* ((start (save-excursion
7463 (goto-char (org-element-property :post-affiliated element))
7464 (line-end-position)))
7465 (end (save-excursion
7466 (goto-char (org-element-property :end element))
7467 (skip-chars-backward " \r\t\n")
7468 (line-end-position)))
7469 (overlays (overlays-at start)))
7470 (cond
7471 ;; Do nothing when not before or at the block opening line or
7472 ;; at the block closing line.
7473 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7474 ((and (not (eq force 'off))
7475 (not (memq t (mapcar
7476 (lambda (o)
7477 (eq (overlay-get o 'invisible) 'org-hide-block))
7478 overlays))))
7479 (let ((ov (make-overlay start end)))
7480 (overlay-put ov 'invisible 'org-hide-block)
7481 ;; Make the block accessible to `isearch'.
7482 (overlay-put
7483 ov 'isearch-open-invisible
7484 (lambda (ov)
7485 (when (memq ov org-hide-block-overlays)
7486 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7487 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7488 (delete-overlay ov))))
7489 (push ov org-hide-block-overlays)
7490 ;; When the block is hidden away, make sure point is left in
7491 ;; a visible part of the buffer.
7492 (when (> (line-beginning-position) start)
7493 (goto-char start)
7494 (beginning-of-line))
7495 ;; Signal successful toggling.
7497 ((or (not force) (eq force 'off))
7498 (dolist (ov overlays t)
7499 (when (memq ov org-hide-block-overlays)
7500 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7501 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7502 (delete-overlay ov))))))))
7504 ;; Remove overlays when changing major mode
7505 (add-hook 'org-mode-hook
7506 (lambda () (add-hook 'change-major-mode-hook
7507 'org-show-block-all 'append 'local)))
7509 ;;; Org-goto
7511 (defvar org-goto-window-configuration nil)
7512 (defvar org-goto-marker nil)
7513 (defvar org-goto-map)
7514 (defun org-goto-map ()
7515 "Set the keymap `org-goto'."
7516 (setq org-goto-map
7517 (let ((map (make-sparse-keymap)))
7518 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7519 mouse-drag-region universal-argument org-occur)))
7520 (dolist (cmd cmds)
7521 (substitute-key-definition cmd cmd map global-map)))
7522 (suppress-keymap map)
7523 (org-defkey map "\C-m" 'org-goto-ret)
7524 (org-defkey map [(return)] 'org-goto-ret)
7525 (org-defkey map [(left)] 'org-goto-left)
7526 (org-defkey map [(right)] 'org-goto-right)
7527 (org-defkey map [(control ?g)] 'org-goto-quit)
7528 (org-defkey map "\C-i" 'org-cycle)
7529 (org-defkey map [(tab)] 'org-cycle)
7530 (org-defkey map [(down)] 'outline-next-visible-heading)
7531 (org-defkey map [(up)] 'outline-previous-visible-heading)
7532 (if org-goto-auto-isearch
7533 (if (fboundp 'define-key-after)
7534 (define-key-after map [t] 'org-goto-local-auto-isearch)
7535 nil)
7536 (org-defkey map "q" 'org-goto-quit)
7537 (org-defkey map "n" 'outline-next-visible-heading)
7538 (org-defkey map "p" 'outline-previous-visible-heading)
7539 (org-defkey map "f" 'outline-forward-same-level)
7540 (org-defkey map "b" 'outline-backward-same-level)
7541 (org-defkey map "u" 'outline-up-heading))
7542 (org-defkey map "/" 'org-occur)
7543 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7544 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7545 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7546 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7547 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7548 map)))
7550 (defconst org-goto-help
7551 "Browse buffer copy, to find location or copy text.%s
7552 RET=jump to location C-g=quit and return to previous location
7553 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7555 (defvar org-goto-start-pos) ; dynamically scoped parameter
7557 (defun org-goto (&optional alternative-interface)
7558 "Look up a different location in the current file, keeping current visibility.
7560 When you want look-up or go to a different location in a
7561 document, the fastest way is often to fold the entire buffer and
7562 then dive into the tree. This method has the disadvantage, that
7563 the previous location will be folded, which may not be what you
7564 want.
7566 This command works around this by showing a copy of the current
7567 buffer in an indirect buffer, in overview mode. You can dive
7568 into the tree in that copy, use org-occur and incremental search
7569 to find a location. When pressing RET or `Q', the command
7570 returns to the original buffer in which the visibility is still
7571 unchanged. After RET it will also jump to the location selected
7572 in the indirect buffer and expose the headline hierarchy above.
7574 With a prefix argument, use the alternative interface: e.g., if
7575 `org-goto-interface' is `outline' use `outline-path-completion'."
7576 (interactive "P")
7577 (org-goto-map)
7578 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7579 (org-refile-use-outline-path t)
7580 (org-refile-target-verify-function nil)
7581 (interface
7582 (if (not alternative-interface)
7583 org-goto-interface
7584 (if (eq org-goto-interface 'outline)
7585 'outline-path-completion
7586 'outline)))
7587 (org-goto-start-pos (point))
7588 (selected-point
7589 (if (eq interface 'outline)
7590 (car (org-get-location (current-buffer) org-goto-help))
7591 (let ((pa (org-refile-get-location "Goto")))
7592 (org-refile-check-position pa)
7593 (nth 3 pa)))))
7594 (if selected-point
7595 (progn
7596 (org-mark-ring-push org-goto-start-pos)
7597 (goto-char selected-point)
7598 (when (or (org-invisible-p) (org-invisible-p2))
7599 (org-show-context 'org-goto)))
7600 (message "Quit"))))
7602 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7603 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7604 (defvar org-goto-local-auto-isearch-map) ; defined below
7606 (defun org-get-location (_buf help)
7607 "Let the user select a location in current buffer.
7608 This function uses a recursive edit. It returns the selected position
7609 or nil."
7610 (org-no-popups
7611 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7612 (isearch-hide-immediately nil)
7613 (isearch-search-fun-function
7614 (lambda () 'org-goto-local-search-headings))
7615 (org-goto-selected-point org-goto-exit-command))
7616 (save-excursion
7617 (save-window-excursion
7618 (delete-other-windows)
7619 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7620 (pop-to-buffer-same-window
7621 (condition-case nil
7622 (make-indirect-buffer (current-buffer) "*org-goto*")
7623 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7624 (with-output-to-temp-buffer "*Org Help*"
7625 (princ (format help (if org-goto-auto-isearch
7626 " Just type for auto-isearch."
7627 " n/p/f/b/u to navigate, q to quit."))))
7628 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7629 (setq buffer-read-only nil)
7630 (let ((org-startup-truncated t)
7631 (org-startup-folded nil)
7632 (org-startup-align-all-tables nil))
7633 (org-mode)
7634 (org-overview))
7635 (setq buffer-read-only t)
7636 (if (and (boundp 'org-goto-start-pos)
7637 (integer-or-marker-p org-goto-start-pos))
7638 (progn (goto-char org-goto-start-pos)
7639 (when (org-invisible-p)
7640 (org-show-set-visibility 'lineage)))
7641 (goto-char (point-min)))
7642 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7643 (message "Select location and press RET")
7644 (use-local-map org-goto-map)
7645 (recursive-edit)))
7646 (kill-buffer "*org-goto*")
7647 (cons org-goto-selected-point org-goto-exit-command))))
7649 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7650 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7651 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7652 (if (fboundp 'isearch-other-control-char)
7653 (progn
7654 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7655 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7656 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7657 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7658 (define-key org-goto-local-auto-isearch-map [return] nil))
7660 (defun org-goto-local-search-headings (string bound noerror)
7661 "Search and make sure that any matches are in headlines."
7662 (catch 'return
7663 (while (if isearch-forward
7664 (search-forward string bound noerror)
7665 (search-backward string bound noerror))
7666 (when (save-match-data
7667 (and (save-excursion
7668 (beginning-of-line)
7669 (looking-at org-complex-heading-regexp))
7670 (or (not (match-beginning 5))
7671 (< (point) (match-beginning 5)))))
7672 (throw 'return (point))))))
7674 (defun org-goto-local-auto-isearch ()
7675 "Start isearch."
7676 (interactive)
7677 (goto-char (point-min))
7678 (let ((keys (this-command-keys)))
7679 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7680 (isearch-mode t)
7681 (isearch-process-search-char (string-to-char keys)))))
7683 (defun org-goto-ret (&optional _arg)
7684 "Finish `org-goto' by going to the new location."
7685 (interactive "P")
7686 (setq org-goto-selected-point (point))
7687 (setq org-goto-exit-command 'return)
7688 (throw 'exit nil))
7690 (defun org-goto-left ()
7691 "Finish `org-goto' by going to the new location."
7692 (interactive)
7693 (if (org-at-heading-p)
7694 (progn
7695 (beginning-of-line 1)
7696 (setq org-goto-selected-point (point)
7697 org-goto-exit-command 'left)
7698 (throw 'exit nil))
7699 (user-error "Not on a heading")))
7701 (defun org-goto-right ()
7702 "Finish `org-goto' by going to the new location."
7703 (interactive)
7704 (if (org-at-heading-p)
7705 (progn
7706 (setq org-goto-selected-point (point)
7707 org-goto-exit-command 'right)
7708 (throw 'exit nil))
7709 (user-error "Not on a heading")))
7711 (defun org-goto-quit ()
7712 "Finish `org-goto' without cursor motion."
7713 (interactive)
7714 (setq org-goto-selected-point nil)
7715 (setq org-goto-exit-command 'quit)
7716 (throw 'exit nil))
7718 ;;; Indirect buffer display of subtrees
7720 (defvar org-indirect-dedicated-frame nil
7721 "This is the frame being used for indirect tree display.")
7722 (defvar org-last-indirect-buffer nil)
7724 (defun org-tree-to-indirect-buffer (&optional arg)
7725 "Create indirect buffer and narrow it to current subtree.
7727 With a numerical prefix ARG, go up to this level and then take that tree.
7728 If ARG is negative, go up that many levels.
7730 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7731 indirect buffer previously made with this command, to avoid proliferation of
7732 indirect buffers. However, when you call the command with a \
7733 `\\[universal-argument]' prefix, or
7734 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7735 so that you can work with several indirect buffers at the same time. If
7736 `org-indirect-buffer-display' is `dedicated-frame', the \
7737 `\\[universal-argument]' prefix also
7738 requests that a new frame be made for the new buffer, so that the dedicated
7739 frame is not changed."
7740 (interactive "P")
7741 (let ((cbuf (current-buffer))
7742 (cwin (selected-window))
7743 (pos (point))
7744 beg end level heading ibuf)
7745 (save-excursion
7746 (org-back-to-heading t)
7747 (when (numberp arg)
7748 (setq level (org-outline-level))
7749 (when (< arg 0) (setq arg (+ level arg)))
7750 (while (> (setq level (org-outline-level)) arg)
7751 (org-up-heading-safe)))
7752 (setq beg (point)
7753 heading (org-get-heading 'no-tags))
7754 (org-end-of-subtree t t)
7755 (when (org-at-heading-p) (backward-char 1))
7756 (setq end (point)))
7757 (when (and (buffer-live-p org-last-indirect-buffer)
7758 (not (eq org-indirect-buffer-display 'new-frame))
7759 (not arg))
7760 (kill-buffer org-last-indirect-buffer))
7761 (setq ibuf (org-get-indirect-buffer cbuf heading)
7762 org-last-indirect-buffer ibuf)
7763 (cond
7764 ((or (eq org-indirect-buffer-display 'new-frame)
7765 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7766 (select-frame (make-frame))
7767 (delete-other-windows)
7768 (pop-to-buffer-same-window ibuf)
7769 (org-set-frame-title heading))
7770 ((eq org-indirect-buffer-display 'dedicated-frame)
7771 (raise-frame
7772 (select-frame (or (and org-indirect-dedicated-frame
7773 (frame-live-p org-indirect-dedicated-frame)
7774 org-indirect-dedicated-frame)
7775 (setq org-indirect-dedicated-frame (make-frame)))))
7776 (delete-other-windows)
7777 (pop-to-buffer-same-window ibuf)
7778 (org-set-frame-title (concat "Indirect: " heading)))
7779 ((eq org-indirect-buffer-display 'current-window)
7780 (pop-to-buffer-same-window ibuf))
7781 ((eq org-indirect-buffer-display 'other-window)
7782 (pop-to-buffer ibuf))
7783 (t (error "Invalid value")))
7784 (narrow-to-region beg end)
7785 (outline-show-all)
7786 (goto-char pos)
7787 (run-hook-with-args 'org-cycle-hook 'all)
7788 (and (window-live-p cwin) (select-window cwin))))
7790 (defun org-get-indirect-buffer (&optional buffer heading)
7791 (setq buffer (or buffer (current-buffer)))
7792 (let ((n 1) (base (buffer-name buffer)) bname)
7793 (while (buffer-live-p
7794 (get-buffer
7795 (setq bname
7796 (concat base "-"
7797 (if heading (concat heading "-" (number-to-string n))
7798 (number-to-string n))))))
7799 (setq n (1+ n)))
7800 (condition-case nil
7801 (make-indirect-buffer buffer bname 'clone)
7802 (error (make-indirect-buffer buffer bname)))))
7804 (defun org-set-frame-title (title)
7805 "Set the title of the current frame to the string TITLE."
7806 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7808 ;;;; Structure editing
7810 ;;; Inserting headlines
7812 (defun org--line-empty-p (n)
7813 "Is the Nth next line empty?
7815 Counts the current line as N = 1 and the previous line as N = 0;
7816 see `beginning-of-line'."
7817 (save-excursion
7818 (and (not (bobp))
7819 (or (beginning-of-line n) t)
7820 (save-match-data
7821 (looking-at "[ \t]*$")))))
7823 (defun org-previous-line-empty-p ()
7824 "Is the previous line a blank line?
7825 When NEXT is non-nil, check the next line instead."
7826 (org--line-empty-p 0))
7828 (defun org-next-line-empty-p ()
7829 "Is the previous line a blank line?
7830 When NEXT is non-nil, check the next line instead."
7831 (org--line-empty-p 2))
7833 (defun org-insert-heading (&optional arg invisible-ok top)
7834 "Insert a new heading or an item with the same depth at point.
7836 If point is at the beginning of a heading or a list item, insert
7837 a new heading or a new item above the current one. When at the
7838 beginning of a regular line of text, turn it into a heading.
7840 If point is in the middle of a line, split it and create a new
7841 headline/item with the text in the current line after point (see
7842 `org-M-RET-may-split-line' on how to modify this behavior). As
7843 a special case, on a headline, splitting can only happen on the
7844 title itself. E.g., this excludes breaking stars or tags.
7846 With a `\\[universal-argument]' prefix, set \
7847 `org-insert-heading-respect-content' to
7848 a non-nil value for the duration of the command. This forces the
7849 insertion of a heading after the current subtree, independently
7850 on the location of point.
7852 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7853 insert the heading at the end of the tree
7854 above the current heading. For example, if point is within a
7855 2nd-level heading, then it will insert a 2nd-level heading at
7856 the end of the 1st-level parent subtree.
7858 When INVISIBLE-OK is set, stop at invisible headlines when going
7859 back. This is important for non-interactive uses of the
7860 command.
7862 When optional argument TOP is non-nil, insert a level 1 heading,
7863 unconditionally."
7864 (interactive "P")
7865 (let ((itemp (and (not top) (org-in-item-p)))
7866 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7867 (respect-content (or org-insert-heading-respect-content
7868 (equal arg '(4))))
7869 (initial-content ""))
7871 (cond
7873 ((or (= (buffer-size) 0)
7874 (and (not (save-excursion
7875 (and (ignore-errors (org-back-to-heading invisible-ok))
7876 (org-at-heading-p))))
7877 (or arg (not itemp))))
7878 ;; At beginning of buffer or so high up that only a heading
7879 ;; makes sense.
7880 (cond ((and (bolp) (not respect-content)) (insert "* "))
7881 ((not respect-content)
7882 (unless may-split (end-of-line))
7883 (insert "\n* "))
7884 ((re-search-forward org-outline-regexp-bol nil t)
7885 (beginning-of-line)
7886 (insert "* \n")
7887 (backward-char))
7888 (t (goto-char (point-max))
7889 (insert "\n* ")))
7890 (run-hooks 'org-insert-heading-hook))
7892 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7895 ;; Maybe move at the end of the subtree
7896 (when (equal arg '(16))
7897 (org-up-heading-safe)
7898 (org-end-of-subtree t))
7899 ;; Insert a heading
7900 (save-restriction
7901 (widen)
7902 (let* ((level nil)
7903 (on-heading (org-at-heading-p))
7904 (empty-line-p (if on-heading
7905 (org-previous-line-empty-p)
7906 ;; We will decide later
7907 nil))
7908 ;; Get a level string to fall back on.
7909 (fix-level
7910 (if (org-before-first-heading-p) "*"
7911 (save-excursion
7912 (org-back-to-heading t)
7913 (when (org-previous-line-empty-p) (setq empty-line-p t))
7914 (looking-at org-outline-regexp)
7915 (make-string (1- (length (match-string 0))) ?*))))
7916 (stars
7917 (save-excursion
7918 (condition-case nil
7919 (if top "* "
7920 (org-back-to-heading invisible-ok)
7921 (when (and (not on-heading)
7922 (featurep 'org-inlinetask)
7923 (integerp org-inlinetask-min-level)
7924 (>= (length (match-string 0))
7925 org-inlinetask-min-level))
7926 ;; Find a heading level before the inline
7927 ;; task.
7928 (while (and (setq level (org-up-heading-safe))
7929 (>= level org-inlinetask-min-level)))
7930 (if (org-at-heading-p)
7931 (org-back-to-heading invisible-ok)
7932 (error "This should not happen")))
7933 (unless (and (save-excursion
7934 (save-match-data
7935 (org-backward-heading-same-level
7936 1 invisible-ok))
7937 (= (point) (match-beginning 0)))
7938 (not (org-next-line-empty-p)))
7939 (setq empty-line-p (or empty-line-p
7940 (org-previous-line-empty-p))))
7941 (match-string 0))
7942 (error (or fix-level "* ")))))
7943 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7944 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7946 ;; If we insert after content, move there and clean up
7947 ;; whitespace.
7948 (when respect-content
7949 (if (not (org-before-first-heading-p))
7950 (org-end-of-subtree nil t)
7951 (re-search-forward org-outline-regexp-bol)
7952 (beginning-of-line 0))
7953 (skip-chars-backward " \r\t\n")
7954 (and (not (looking-back "^\\*+" (line-beginning-position)))
7955 (looking-at "[ \t]+") (replace-match ""))
7956 (unless (eobp) (forward-char 1))
7957 (when (looking-at "^\\*")
7958 (unless (bobp) (backward-char 1))
7959 (insert "\n")))
7961 ;; If we are splitting, grab the text that should be moved
7962 ;; to the new headline.
7963 (when may-split
7964 (if (org-at-heading-p)
7965 ;; This is a heading: split intelligently (keeping
7966 ;; tags).
7967 (let ((pos (point)))
7968 (beginning-of-line)
7969 (let ((case-fold-search nil))
7970 (unless (looking-at org-complex-heading-regexp)
7971 (error "This should not happen")))
7972 (when (and (match-beginning 4)
7973 (> pos (match-beginning 4))
7974 (< pos (match-end 4)))
7975 (setq initial-content (buffer-substring pos (match-end 4)))
7976 (goto-char pos)
7977 (delete-region (point) (match-end 4))
7978 (if (looking-at "[ \t]*$")
7979 (replace-match "")
7980 (insert (make-string (length initial-content) ?\s)))
7981 (setq initial-content (org-trim initial-content)))
7982 (goto-char pos))
7983 ;; A normal line.
7984 (setq initial-content
7985 (org-trim
7986 (delete-and-extract-region (point) (line-end-position))))))
7988 ;; If we are at the beginning of the line, insert before it.
7989 ;; Otherwise, after it.
7990 (cond
7991 ((and (bolp) (looking-at "[ \t]*$")))
7992 ((bolp) (save-excursion (insert "\n")))
7993 (t (end-of-line)
7994 (insert "\n")))
7996 ;; Insert the new heading
7997 (insert stars)
7998 (just-one-space)
7999 (insert initial-content)
8000 (unless (and blank (org-previous-line-empty-p))
8001 (org-N-empty-lines-before-current (if blank 1 0)))
8002 ;; Adjust visibility, which may be messed up if we removed
8003 ;; blank lines while previous entry was hidden.
8004 (let ((bol (line-beginning-position)))
8005 (dolist (o (overlays-at (1- bol)))
8006 (when (and (eq (overlay-get o 'invisible) 'outline)
8007 (eq (overlay-end o) bol))
8008 (move-overlay o (overlay-start o) (1- bol)))))
8009 (run-hooks 'org-insert-heading-hook)))))))
8011 (defun org-N-empty-lines-before-current (N)
8012 "Make the number of empty lines before current exactly N.
8013 So this will delete or add empty lines."
8014 (save-excursion
8015 (beginning-of-line)
8016 (let ((p (point)))
8017 (skip-chars-backward " \r\t\n")
8018 (unless (bolp) (forward-line))
8019 (delete-region (point) p))
8020 (when (> N 0) (insert (make-string N ?\n)))))
8022 (defun org-get-heading (&optional no-tags no-todo)
8023 "Return the heading of the current entry, without the stars.
8024 When NO-TAGS is non-nil, don't include tags.
8025 When NO-TODO is non-nil, don't include TODO keywords."
8026 (save-excursion
8027 (org-back-to-heading t)
8028 (let ((case-fold-search nil))
8029 (cond
8030 ((and no-tags no-todo)
8031 (looking-at org-complex-heading-regexp)
8032 ;; Return value has to be a string, but match group 4 is
8033 ;; optional.
8034 (or (match-string 4) ""))
8035 (no-tags
8036 (looking-at (concat org-outline-regexp
8037 "\\(.*?\\)"
8038 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8039 (match-string 1))
8040 (no-todo
8041 (looking-at org-todo-line-regexp)
8042 (match-string 3))
8043 (t (looking-at org-heading-regexp)
8044 (match-string 2))))))
8046 (defvar orgstruct-mode) ; defined below
8048 (defun org-heading-components ()
8049 "Return the components of the current heading.
8050 This is a list with the following elements:
8051 - the level as an integer
8052 - the reduced level, different if `org-odd-levels-only' is set.
8053 - the TODO keyword, or nil
8054 - the priority character, like ?A, or nil if no priority is given
8055 - the headline text itself, or the tags string if no headline text
8056 - the tags string, or nil."
8057 (save-excursion
8058 (org-back-to-heading t)
8059 (when (let (case-fold-search)
8060 (looking-at
8061 (if orgstruct-mode
8062 org-heading-regexp
8063 org-complex-heading-regexp)))
8064 (if orgstruct-mode
8065 (list (length (match-string 1))
8066 (org-reduced-level (length (match-string 1)))
8069 (match-string 2)
8070 nil)
8071 (list (length (match-string 1))
8072 (org-reduced-level (length (match-string 1)))
8073 (match-string-no-properties 2)
8074 (and (match-end 3) (aref (match-string 3) 2))
8075 (match-string-no-properties 4)
8076 (match-string-no-properties 5))))))
8078 (defun org-get-entry ()
8079 "Get the entry text, after heading, entire subtree."
8080 (save-excursion
8081 (org-back-to-heading t)
8082 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8084 (defun org-edit-headline (&optional heading)
8085 "Edit the current headline.
8086 Set it to HEADING when provided."
8087 (interactive)
8088 (org-with-wide-buffer
8089 (org-back-to-heading t)
8090 (let ((case-fold-search nil))
8091 (when (looking-at org-complex-heading-regexp)
8092 (let* ((old (match-string-no-properties 4))
8093 (new (save-match-data
8094 (org-trim (or heading (read-string "Edit: " old))))))
8095 (unless (equal old new)
8096 (if old (replace-match new t t nil 4)
8097 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8098 (insert " " new))
8099 (org-set-tags nil t)
8100 (when (looking-at "[ \t]*$") (replace-match ""))))))))
8102 (defun org-insert-heading-after-current ()
8103 "Insert a new heading with same level as current, after current subtree."
8104 (interactive)
8105 (org-back-to-heading)
8106 (org-insert-heading)
8107 (org-move-subtree-down)
8108 (end-of-line 1))
8110 (defun org-insert-heading-respect-content (&optional invisible-ok)
8111 "Insert heading with `org-insert-heading-respect-content' set to t."
8112 (interactive)
8113 (org-insert-heading '(4) invisible-ok))
8115 (defun org-insert-todo-heading-respect-content (&optional force-state)
8116 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8117 (interactive)
8118 (org-insert-todo-heading force-state '(4)))
8120 (defun org-insert-todo-heading (arg &optional force-heading)
8121 "Insert a new heading with the same level and TODO state as current heading.
8123 If the heading has no TODO state, or if the state is DONE, use
8124 the first state (TODO by default). Also with one prefix arg,
8125 force first state. With two prefix args, force inserting at the
8126 end of the parent subtree.
8128 When called at a plain list item, insert a new item with an
8129 unchecked check box."
8130 (interactive "P")
8131 (when (or force-heading (not (org-insert-item 'checkbox)))
8132 (org-insert-heading (or (and (equal arg '(16)) '(16))
8133 force-heading))
8134 (save-excursion
8135 (org-back-to-heading)
8136 (outline-previous-heading)
8137 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
8138 (let* ((new-mark-x
8139 (if (or (equal arg '(4))
8140 (not (match-beginning 2))
8141 (member (match-string 2) org-done-keywords))
8142 (car org-todo-keywords-1)
8143 (match-string 2)))
8144 (new-mark
8146 (run-hook-with-args-until-success
8147 'org-todo-get-default-hook new-mark-x nil)
8148 new-mark-x)))
8149 (beginning-of-line 1)
8150 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8151 (if org-treat-insert-todo-heading-as-state-change
8152 (org-todo new-mark)
8153 (insert new-mark " "))))
8154 (when org-provide-todo-statistics
8155 (org-update-parent-todo-statistics))))
8157 (defun org-insert-subheading (arg)
8158 "Insert a new subheading and demote it.
8159 Works for outline headings and for plain lists alike."
8160 (interactive "P")
8161 (org-insert-heading arg)
8162 (cond
8163 ((org-at-heading-p) (org-do-demote))
8164 ((org-at-item-p) (org-indent-item))))
8166 (defun org-insert-todo-subheading (arg)
8167 "Insert a new subheading with TODO keyword or checkbox and demote it.
8168 Works for outline headings and for plain lists alike."
8169 (interactive "P")
8170 (org-insert-todo-heading arg)
8171 (cond
8172 ((org-at-heading-p) (org-do-demote))
8173 ((org-at-item-p) (org-indent-item))))
8175 ;;; Promotion and Demotion
8177 (defvar org-after-demote-entry-hook nil
8178 "Hook run after an entry has been demoted.
8179 The cursor will be at the beginning of the entry.
8180 When a subtree is being demoted, the hook will be called for each node.")
8182 (defvar org-after-promote-entry-hook nil
8183 "Hook run after an entry has been promoted.
8184 The cursor will be at the beginning of the entry.
8185 When a subtree is being promoted, the hook will be called for each node.")
8187 (defun org-promote-subtree ()
8188 "Promote the entire subtree.
8189 See also `org-promote'."
8190 (interactive)
8191 (save-excursion
8192 (org-with-limited-levels (org-map-tree 'org-promote)))
8193 (org-fix-position-after-promote))
8195 (defun org-demote-subtree ()
8196 "Demote the entire subtree.
8197 See `org-demote' and `org-promote'."
8198 (interactive)
8199 (save-excursion
8200 (org-with-limited-levels (org-map-tree 'org-demote)))
8201 (org-fix-position-after-promote))
8203 (defun org-do-promote ()
8204 "Promote the current heading higher up the tree.
8205 If the region is active in `transient-mark-mode', promote all
8206 headings in the region."
8207 (interactive)
8208 (save-excursion
8209 (if (org-region-active-p)
8210 (org-map-region 'org-promote (region-beginning) (region-end))
8211 (org-promote)))
8212 (org-fix-position-after-promote))
8214 (defun org-do-demote ()
8215 "Demote the current heading lower down the tree.
8216 If the region is active in `transient-mark-mode', demote all
8217 headings in the region."
8218 (interactive)
8219 (save-excursion
8220 (if (org-region-active-p)
8221 (org-map-region 'org-demote (region-beginning) (region-end))
8222 (org-demote)))
8223 (org-fix-position-after-promote))
8225 (defun org-fix-position-after-promote ()
8226 "Fix cursor position and indentation after demoting/promoting."
8227 (let ((pos (point)))
8228 (when (save-excursion
8229 (beginning-of-line)
8230 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8231 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8232 (cond ((eobp) (insert " "))
8233 ((eolp) (insert " "))
8234 ((equal (char-after) ?\s) (forward-char 1))))))
8236 (defun org-current-level ()
8237 "Return the level of the current entry, or nil if before the first headline.
8238 The level is the number of stars at the beginning of the
8239 headline. Use `org-reduced-level' to remove the effect of
8240 `org-odd-levels'. Unlike to `org-outline-level', this function
8241 ignores inlinetasks."
8242 (let ((level (org-with-limited-levels (org-outline-level))))
8243 (and (> level 0) level)))
8245 (defun org-get-previous-line-level ()
8246 "Return the outline depth of the last headline before the current line.
8247 Returns 0 for the first headline in the buffer, and nil if before the
8248 first headline."
8249 (and (org-current-level)
8250 (or (and (/= (line-beginning-position) (point-min))
8251 (save-excursion (beginning-of-line 0) (org-current-level)))
8252 0)))
8254 (defun org-reduced-level (l)
8255 "Compute the effective level of a heading.
8256 This takes into account the setting of `org-odd-levels-only'."
8257 (cond
8258 ((zerop l) 0)
8259 (org-odd-levels-only (1+ (floor (/ l 2))))
8260 (t l)))
8262 (defun org-level-increment ()
8263 "Return the number of stars that will be added or removed at a
8264 time to headlines when structure editing, based on the value of
8265 `org-odd-levels-only'."
8266 (if org-odd-levels-only 2 1))
8268 (defun org-get-valid-level (level &optional change)
8269 "Rectify a level change under the influence of `org-odd-levels-only'
8270 LEVEL is a current level, CHANGE is by how much the level should be
8271 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8272 even level numbers will become the next higher odd number."
8273 (if org-odd-levels-only
8274 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8275 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8276 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8277 (max 1 (+ level (or change 0)))))
8279 (defun org-promote ()
8280 "Promote the current heading higher up the tree."
8281 (org-with-wide-buffer
8282 (org-back-to-heading t)
8283 (let* ((after-change-functions (remq 'flyspell-after-change-function
8284 after-change-functions))
8285 (level (save-match-data (funcall outline-level)))
8286 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8287 (diff (abs (- level (length up-head) -1))))
8288 (cond
8289 ((and (= level 1) org-allow-promoting-top-level-subtree)
8290 (replace-match "# " nil t))
8291 ((= level 1)
8292 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8293 (t (replace-match up-head nil t)))
8294 (unless (= level 1)
8295 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8296 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8297 (run-hooks 'org-after-promote-entry-hook))))
8299 (defun org-demote ()
8300 "Demote the current heading lower down the tree."
8301 (org-with-wide-buffer
8302 (org-back-to-heading t)
8303 (let* ((after-change-functions (remq 'flyspell-after-change-function
8304 after-change-functions))
8305 (level (save-match-data (funcall outline-level)))
8306 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8307 (diff (abs (- level (length down-head) -1))))
8308 (replace-match down-head nil t)
8309 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8310 (when org-adapt-indentation (org-fixup-indentation diff))
8311 (run-hooks 'org-after-demote-entry-hook))))
8313 (defun org-cycle-level ()
8314 "Cycle the level of an empty headline through possible states.
8315 This goes first to child, then to parent, level, then up the hierarchy.
8316 After top level, it switches back to sibling level."
8317 (interactive)
8318 (let ((org-adapt-indentation nil))
8319 (when (org-point-at-end-of-empty-headline)
8320 (setq this-command 'org-cycle-level) ; Only needed for caching
8321 (let ((cur-level (org-current-level))
8322 (prev-level (org-get-previous-line-level)))
8323 (cond
8324 ;; If first headline in file, promote to top-level.
8325 ((= prev-level 0)
8326 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8327 do (org-do-promote)))
8328 ;; If same level as prev, demote one.
8329 ((= prev-level cur-level)
8330 (org-do-demote))
8331 ;; If parent is top-level, promote to top level if not already.
8332 ((= prev-level 1)
8333 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8334 do (org-do-promote)))
8335 ;; If top-level, return to prev-level.
8336 ((= cur-level 1)
8337 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8338 do (org-do-demote)))
8339 ;; If less than prev-level, promote one.
8340 ((< cur-level prev-level)
8341 (org-do-promote))
8342 ;; If deeper than prev-level, promote until higher than
8343 ;; prev-level.
8344 ((> cur-level prev-level)
8345 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8346 do (org-do-promote))))
8347 t))))
8349 (defun org-map-tree (fun)
8350 "Call FUN for every heading underneath the current one."
8351 (org-back-to-heading t)
8352 (let ((level (funcall outline-level)))
8353 (save-excursion
8354 (funcall fun)
8355 (while (and (progn
8356 (outline-next-heading)
8357 (> (funcall outline-level) level))
8358 (not (eobp)))
8359 (funcall fun)))))
8361 (defun org-map-region (fun beg end)
8362 "Call FUN for every heading between BEG and END."
8363 (let ((org-ignore-region t))
8364 (save-excursion
8365 (setq end (copy-marker end))
8366 (goto-char beg)
8367 (when (and (re-search-forward org-outline-regexp-bol nil t)
8368 (< (point) end))
8369 (funcall fun))
8370 (while (and (progn
8371 (outline-next-heading)
8372 (< (point) end))
8373 (not (eobp)))
8374 (funcall fun)))))
8376 (defun org-fixup-indentation (diff)
8377 "Change the indentation in the current entry by DIFF.
8379 DIFF is an integer. Indentation is done according to the
8380 following rules:
8382 - Planning information and property drawers are always indented
8383 according to the new level of the headline;
8385 - Footnote definitions and their contents are ignored;
8387 - Inlinetasks' boundaries are not shifted;
8389 - Empty lines are ignored;
8391 - Other lines' indentation are shifted by DIFF columns, unless
8392 it would introduce a structural change in the document, in
8393 which case no shifting is done at all.
8395 Assume point is at a heading or an inlinetask beginning."
8396 (org-with-wide-buffer
8397 (narrow-to-region (line-beginning-position)
8398 (save-excursion
8399 (if (org-with-limited-levels (org-at-heading-p))
8400 (org-with-limited-levels (outline-next-heading))
8401 (org-inlinetask-goto-end))
8402 (point)))
8403 (forward-line)
8404 ;; Indent properly planning info and property drawer.
8405 (when (looking-at-p org-planning-line-re)
8406 (org-indent-line)
8407 (forward-line))
8408 (when (looking-at org-property-drawer-re)
8409 (goto-char (match-end 0))
8410 (forward-line)
8411 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8412 (catch 'no-shift
8413 (when (zerop diff) (throw 'no-shift nil))
8414 ;; If DIFF is negative, first check if a shift is possible at all
8415 ;; (e.g., it doesn't break structure). This can only happen if
8416 ;; some contents are not properly indented.
8417 (let ((case-fold-search t))
8418 (when (< diff 0)
8419 (let ((diff (- diff))
8420 (forbidden-re (concat org-outline-regexp
8421 "\\|"
8422 (substring org-footnote-definition-re 1))))
8423 (save-excursion
8424 (while (not (eobp))
8425 (cond
8426 ((looking-at-p "[ \t]*$") (forward-line))
8427 ((and (looking-at-p org-footnote-definition-re)
8428 (let ((e (org-element-at-point)))
8429 (and (eq (org-element-type e) 'footnote-definition)
8430 (goto-char (org-element-property :end e))))))
8431 ((looking-at-p org-outline-regexp) (forward-line))
8432 ;; Give up if shifting would move before column 0 or
8433 ;; if it would introduce a headline or a footnote
8434 ;; definition.
8436 (skip-chars-forward " \t")
8437 (let ((ind (current-column)))
8438 (when (or (< ind diff)
8439 (and (= ind diff) (looking-at-p forbidden-re)))
8440 (throw 'no-shift nil)))
8441 ;; Ignore contents of example blocks and source
8442 ;; blocks if their indentation is meant to be
8443 ;; preserved. Jump to block's closing line.
8444 (beginning-of-line)
8445 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8446 (let ((e (org-element-at-point)))
8447 (and (memq (org-element-type e)
8448 '(example-block src-block))
8449 (or org-src-preserve-indentation
8450 (org-element-property :preserve-indent e))
8451 (goto-char (org-element-property :end e))
8452 (progn (skip-chars-backward " \r\t\n")
8453 (beginning-of-line)
8454 t))))
8455 (forward-line))))))))
8456 ;; Shift lines but footnote definitions, inlinetasks boundaries
8457 ;; by DIFF. Also skip contents of source or example blocks
8458 ;; when indentation is meant to be preserved.
8459 (while (not (eobp))
8460 (cond
8461 ((and (looking-at-p org-footnote-definition-re)
8462 (let ((e (org-element-at-point)))
8463 (and (eq (org-element-type e) 'footnote-definition)
8464 (goto-char (org-element-property :end e))))))
8465 ((looking-at-p org-outline-regexp) (forward-line))
8466 ((looking-at-p "[ \t]*$") (forward-line))
8468 (indent-line-to (+ (org-get-indentation) diff))
8469 (beginning-of-line)
8470 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8471 (let ((e (org-element-at-point)))
8472 (and (memq (org-element-type e)
8473 '(example-block src-block))
8474 (or org-src-preserve-indentation
8475 (org-element-property :preserve-indent e))
8476 (goto-char (org-element-property :end e))
8477 (progn (skip-chars-backward " \r\t\n")
8478 (beginning-of-line)
8479 t))))
8480 (forward-line)))))))))
8482 (defun org-convert-to-odd-levels ()
8483 "Convert an Org file with all levels allowed to one with odd levels.
8484 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8485 level 5 etc."
8486 (interactive)
8487 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8488 (let ((outline-level 'org-outline-level)
8489 (org-odd-levels-only nil) n)
8490 (save-excursion
8491 (goto-char (point-min))
8492 (while (re-search-forward "^\\*\\*+ " nil t)
8493 (setq n (- (length (match-string 0)) 2))
8494 (while (>= (setq n (1- n)) 0)
8495 (org-demote))
8496 (end-of-line 1))))))
8498 (defun org-convert-to-oddeven-levels ()
8499 "Convert an Org file with only odd levels to one with odd/even levels.
8500 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8501 file contains a section with an even level, conversion would
8502 destroy the structure of the file. An error is signaled in this
8503 case."
8504 (interactive)
8505 (goto-char (point-min))
8506 ;; First check if there are no even levels
8507 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8508 (org-show-set-visibility 'canonical)
8509 (error "Not all levels are odd in this file. Conversion not possible"))
8510 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8511 (let ((outline-regexp org-outline-regexp)
8512 (outline-level 'org-outline-level)
8513 (org-odd-levels-only nil) n)
8514 (save-excursion
8515 (goto-char (point-min))
8516 (while (re-search-forward "^\\*\\*+ " nil t)
8517 (setq n (/ (1- (length (match-string 0))) 2))
8518 (while (>= (setq n (1- n)) 0)
8519 (org-promote))
8520 (end-of-line 1))))))
8522 (defun org-tr-level (n)
8523 "Make N odd if required."
8524 (if org-odd-levels-only (1+ (/ n 2)) n))
8526 ;;; Vertical tree motion, cutting and pasting of subtrees
8528 (defun org-move-subtree-up (&optional arg)
8529 "Move the current subtree up past ARG headlines of the same level."
8530 (interactive "p")
8531 (org-move-subtree-down (- (prefix-numeric-value arg))))
8533 (defun org-move-subtree-down (&optional arg)
8534 "Move the current subtree down past ARG headlines of the same level."
8535 (interactive "p")
8536 (setq arg (prefix-numeric-value arg))
8537 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8538 'org-get-last-sibling))
8539 (ins-point (make-marker))
8540 (cnt (abs arg))
8541 (col (current-column))
8542 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8543 ;; Select the tree
8544 (org-back-to-heading)
8545 (setq beg0 (point))
8546 (save-excursion
8547 (setq ne-beg (org-back-over-empty-lines))
8548 (setq beg (point)))
8549 (save-match-data
8550 (save-excursion (outline-end-of-heading)
8551 (setq folded (org-invisible-p)))
8552 (progn (org-end-of-subtree nil t)
8553 (unless (eobp) (backward-char))))
8554 (outline-next-heading)
8555 (setq ne-end (org-back-over-empty-lines))
8556 (setq end (point))
8557 (goto-char beg0)
8558 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8559 ;; include less whitespace
8560 (save-excursion
8561 (goto-char beg)
8562 (forward-line (- ne-beg ne-end))
8563 (setq beg (point))))
8564 ;; Find insertion point, with error handling
8565 (while (> cnt 0)
8566 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8567 (progn (goto-char beg0)
8568 (user-error "Cannot move past superior level or buffer limit")))
8569 (setq cnt (1- cnt)))
8570 (when (> arg 0)
8571 ;; Moving forward - still need to move over subtree
8572 (org-end-of-subtree t t)
8573 (save-excursion
8574 (org-back-over-empty-lines)
8575 (or (bolp) (newline))))
8576 (setq ne-ins (org-back-over-empty-lines))
8577 (move-marker ins-point (point))
8578 (setq txt (buffer-substring beg end))
8579 (org-save-markers-in-region beg end)
8580 (delete-region beg end)
8581 (org-remove-empty-overlays-at beg)
8582 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8583 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8584 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8585 (let ((bbb (point)))
8586 (insert-before-markers txt)
8587 (org-reinstall-markers-in-region bbb)
8588 (move-marker ins-point bbb))
8589 (or (bolp) (insert "\n"))
8590 (setq ins-end (point))
8591 (goto-char ins-point)
8592 (org-skip-whitespace)
8593 (when (and (< arg 0)
8594 (org-first-sibling-p)
8595 (> ne-ins ne-beg))
8596 ;; Move whitespace back to beginning
8597 (save-excursion
8598 (goto-char ins-end)
8599 (let ((kill-whole-line t))
8600 (kill-line (- ne-ins ne-beg)) (point)))
8601 (insert (make-string (- ne-ins ne-beg) ?\n)))
8602 (move-marker ins-point nil)
8603 (if folded
8604 (outline-hide-subtree)
8605 (org-show-entry)
8606 (org-show-children)
8607 (org-cycle-hide-drawers 'children))
8608 (org-clean-visibility-after-subtree-move)
8609 ;; move back to the initial column we were at
8610 (move-to-column col)))
8612 (defvar org-subtree-clip ""
8613 "Clipboard for cut and paste of subtrees.
8614 This is actually only a copy of the kill, because we use the normal kill
8615 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8617 (defvar org-subtree-clip-folded nil
8618 "Was the last copied subtree folded?
8619 This is used to fold the tree back after pasting.")
8621 (defun org-cut-subtree (&optional n)
8622 "Cut the current subtree into the clipboard.
8623 With prefix arg N, cut this many sequential subtrees.
8624 This is a short-hand for marking the subtree and then cutting it."
8625 (interactive "p")
8626 (org-copy-subtree n 'cut))
8628 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8629 "Copy the current subtree it in the clipboard.
8630 With prefix arg N, copy this many sequential subtrees.
8631 This is a short-hand for marking the subtree and then copying it.
8632 If CUT is non-nil, actually cut the subtree.
8633 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8634 of some markers in the region, even if CUT is non-nil. This is
8635 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8636 (interactive "p")
8637 (let (beg end folded (beg0 (point)))
8638 (if (called-interactively-p 'any)
8639 (org-back-to-heading nil) ; take what looks like a subtree
8640 (org-back-to-heading t)) ; take what is really there
8641 (setq beg (point))
8642 (skip-chars-forward " \t\r\n")
8643 (save-match-data
8644 (if nosubtrees
8645 (outline-next-heading)
8646 (save-excursion (outline-end-of-heading)
8647 (setq folded (org-invisible-p)))
8648 (ignore-errors (org-forward-heading-same-level (1- n) t))
8649 (org-end-of-subtree t t)))
8650 ;; Include the end of an inlinetask
8651 (when (and (featurep 'org-inlinetask)
8652 (looking-at-p (concat (org-inlinetask-outline-regexp)
8653 "END[ \t]*$")))
8654 (end-of-line))
8655 (setq end (point))
8656 (goto-char beg0)
8657 (when (> end beg)
8658 (setq org-subtree-clip-folded folded)
8659 (when (or cut force-store-markers)
8660 (org-save-markers-in-region beg end))
8661 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8662 (setq org-subtree-clip (current-kill 0))
8663 (message "%s: Subtree(s) with %d characters"
8664 (if cut "Cut" "Copied")
8665 (length org-subtree-clip)))))
8667 (defun org-paste-subtree (&optional level tree for-yank remove)
8668 "Paste the clipboard as a subtree, with modification of headline level.
8669 The entire subtree is promoted or demoted in order to match a new headline
8670 level.
8672 If the cursor is at the beginning of a headline, the same level as
8673 that headline is used to paste the tree.
8675 If not, the new level is derived from the *visible* headings
8676 before and after the insertion point, and taken to be the inferior headline
8677 level of the two. So if the previous visible heading is level 3 and the
8678 next is level 4 (or vice versa), level 4 will be used for insertion.
8679 This makes sure that the subtree remains an independent subtree and does
8680 not swallow low level entries.
8682 You can also force a different level, either by using a numeric prefix
8683 argument, or by inserting the heading marker by hand. For example, if the
8684 cursor is after \"*****\", then the tree will be shifted to level 5.
8686 If optional TREE is given, use this text instead of the kill ring.
8688 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8689 move back over whitespace before inserting, and move point to the end of
8690 the inserted text when done.
8692 When REMOVE is non-nil, remove the subtree from the clipboard."
8693 (interactive "P")
8694 (setq tree (or tree (and kill-ring (current-kill 0))))
8695 (unless (org-kill-is-subtree-p tree)
8696 (user-error "%s"
8697 (substitute-command-keys
8698 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8699 (org-with-limited-levels
8700 (let* ((visp (not (org-invisible-p)))
8701 (txt tree)
8702 (^re_ "\\(\\*+\\)[ \t]*")
8703 (old-level (if (string-match org-outline-regexp-bol txt)
8704 (- (match-end 0) (match-beginning 0) 1)
8705 -1))
8706 (force-level (cond (level (prefix-numeric-value level))
8707 ((and (looking-at "[ \t]*$")
8708 (string-match
8709 "^\\*+$" (buffer-substring
8710 (point-at-bol) (point))))
8711 (- (match-end 0) (match-beginning 0)))
8712 ((and (bolp)
8713 (looking-at org-outline-regexp))
8714 (- (match-end 0) (point) 1))))
8715 (previous-level (save-excursion
8716 (condition-case nil
8717 (progn
8718 (outline-previous-visible-heading 1)
8719 (if (looking-at ^re_)
8720 (- (match-end 0) (match-beginning 0) 1)
8722 (error 1))))
8723 (next-level (save-excursion
8724 (condition-case nil
8725 (progn
8726 (or (looking-at org-outline-regexp)
8727 (outline-next-visible-heading 1))
8728 (if (looking-at ^re_)
8729 (- (match-end 0) (match-beginning 0) 1)
8731 (error 1))))
8732 (new-level (or force-level (max previous-level next-level)))
8733 (shift (if (or (= old-level -1)
8734 (= new-level -1)
8735 (= old-level new-level))
8737 (- new-level old-level)))
8738 (delta (if (> shift 0) -1 1))
8739 (func (if (> shift 0) 'org-demote 'org-promote))
8740 (org-odd-levels-only nil)
8741 beg end newend)
8742 ;; Remove the forced level indicator
8743 (when force-level
8744 (delete-region (point-at-bol) (point)))
8745 ;; Paste
8746 (beginning-of-line (if (bolp) 1 2))
8747 (setq beg (point))
8748 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8749 (insert-before-markers txt)
8750 (unless (string-suffix-p "\n" txt) (insert "\n"))
8751 (setq newend (point))
8752 (org-reinstall-markers-in-region beg)
8753 (setq end (point))
8754 (goto-char beg)
8755 (skip-chars-forward " \t\n\r")
8756 (setq beg (point))
8757 (when (and (org-invisible-p) visp)
8758 (save-excursion (outline-show-heading)))
8759 ;; Shift if necessary
8760 (unless (= shift 0)
8761 (save-restriction
8762 (narrow-to-region beg end)
8763 (while (not (= shift 0))
8764 (org-map-region func (point-min) (point-max))
8765 (setq shift (+ delta shift)))
8766 (goto-char (point-min))
8767 (setq newend (point-max))))
8768 (when (or (called-interactively-p 'interactive) for-yank)
8769 (message "Clipboard pasted as level %d subtree" new-level))
8770 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8771 kill-ring
8772 (eq org-subtree-clip (current-kill 0))
8773 org-subtree-clip-folded)
8774 ;; The tree was folded before it was killed/copied
8775 (outline-hide-subtree))
8776 (and for-yank (goto-char newend))
8777 (and remove (setq kill-ring (cdr kill-ring))))))
8779 (defun org-kill-is-subtree-p (&optional txt)
8780 "Check if the current kill is an outline subtree, or a set of trees.
8781 Returns nil if kill does not start with a headline, or if the first
8782 headline level is not the largest headline level in the tree.
8783 So this will actually accept several entries of equal levels as well,
8784 which is OK for `org-paste-subtree'.
8785 If optional TXT is given, check this string instead of the current kill."
8786 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8787 (re (org-get-limited-outline-regexp))
8788 (^re (concat "^" re))
8789 (start-level (and kill
8790 (string-match
8791 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8792 kill)
8793 (- (match-end 2) (match-beginning 2) 1)))
8794 (start (1+ (or (match-beginning 2) -1))))
8795 (if (not start-level)
8796 (progn
8797 nil) ;; does not even start with a heading
8798 (catch 'exit
8799 (while (setq start (string-match ^re kill (1+ start)))
8800 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8801 (throw 'exit nil)))
8802 t))))
8804 (defvar org-markers-to-move nil
8805 "Markers that should be moved with a cut-and-paste operation.
8806 Those markers are stored together with their positions relative to
8807 the start of the region.")
8809 (defun org-save-markers-in-region (beg end)
8810 "Check markers in region.
8811 If these markers are between BEG and END, record their position relative
8812 to BEG, so that after moving the block of text, we can put the markers back
8813 into place.
8814 This function gets called just before an entry or tree gets cut from the
8815 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8816 called immediately, to move the markers with the entries."
8817 (setq org-markers-to-move nil)
8818 (when (featurep 'org-clock)
8819 (org-clock-save-markers-for-cut-and-paste beg end))
8820 (when (featurep 'org-agenda)
8821 (org-agenda-save-markers-for-cut-and-paste beg end)))
8823 (defun org-check-and-save-marker (marker beg end)
8824 "Check if MARKER is between BEG and END.
8825 If yes, remember the marker and the distance to BEG."
8826 (when (and (marker-buffer marker)
8827 (equal (marker-buffer marker) (current-buffer))
8828 (>= marker beg) (< marker end))
8829 (push (cons marker (- marker beg)) org-markers-to-move)))
8831 (defun org-reinstall-markers-in-region (beg)
8832 "Move all remembered markers to their position relative to BEG."
8833 (dolist (x org-markers-to-move)
8834 (move-marker (car x) (+ beg (cdr x))))
8835 (setq org-markers-to-move nil))
8837 (defun org-narrow-to-subtree ()
8838 "Narrow buffer to the current subtree."
8839 (interactive)
8840 (save-excursion
8841 (save-match-data
8842 (org-with-limited-levels
8843 (narrow-to-region
8844 (progn (org-back-to-heading t) (point))
8845 (progn (org-end-of-subtree t t)
8846 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8847 (point)))))))
8849 (defun org-narrow-to-block ()
8850 "Narrow buffer to the current block."
8851 (interactive)
8852 (let* ((case-fold-search t)
8853 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8854 "^[ \t]*#\\+end_.*")))
8855 (if blockp
8856 (narrow-to-region (car blockp) (cdr blockp))
8857 (user-error "Not in a block"))))
8859 (defun org-clone-subtree-with-time-shift (n &optional shift)
8860 "Clone the task (subtree) at point N times.
8861 The clones will be inserted as siblings.
8863 In interactive use, the user will be prompted for the number of
8864 clones to be produced. If the entry has a timestamp, the user
8865 will also be prompted for a time shift, which may be a repeater
8866 as used in time stamps, for example `+3d'. To disable this,
8867 you can call the function with a universal prefix argument.
8869 When a valid repeater is given and the entry contains any time
8870 stamps, the clones will become a sequence in time, with time
8871 stamps in the subtree shifted for each clone produced. If SHIFT
8872 is nil or the empty string, time stamps will be left alone. The
8873 ID property of the original subtree is removed.
8875 In each clone, all the CLOCK entries will be removed. This
8876 prevents Org from considering that the clocked times overlap.
8878 If the original subtree did contain time stamps with a repeater,
8879 the following will happen:
8880 - the repeater will be removed in each clone
8881 - an additional clone will be produced, with the current, unshifted
8882 date(s) in the entry.
8883 - the original entry will be placed *after* all the clones, with
8884 repeater intact.
8885 - the start days in the repeater in the original entry will be shifted
8886 to past the last clone.
8887 In this way you can spell out a number of instances of a repeating task,
8888 and still retain the repeater to cover future instances of the task.
8890 As described above, N+1 clones are produced when the original
8891 subtree has a repeater. Setting N to 0, then, can be used to
8892 remove the repeater from a subtree and create a shifted clone
8893 with the original repeater."
8894 (interactive "nNumber of clones to produce: ")
8895 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8896 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8897 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8898 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8899 (shift
8900 (or shift
8901 (if (and (not (equal current-prefix-arg '(4)))
8902 (save-excursion
8903 (goto-char beg)
8904 (re-search-forward org-ts-regexp-both end-of-tree t)))
8905 (read-from-minibuffer
8906 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8907 ""))) ;No time shift
8908 (doshift
8909 (and (org-string-nw-p shift)
8910 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8911 shift)
8912 (user-error "Invalid shift specification %s" shift)))))
8913 (goto-char end-of-tree)
8914 (unless (bolp) (insert "\n"))
8915 (let* ((end (point))
8916 (template (buffer-substring beg end))
8917 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8918 (shift-what (pcase (and doshift (match-string 2 shift))
8919 (`nil nil)
8920 ("d" 'day)
8921 ("w" (setq shift-n (* 7 shift-n)) 'day)
8922 ("m" 'month)
8923 ("y" 'year)
8924 (_ (error "Unsupported time unit"))))
8925 (nmin 1)
8926 (nmax n)
8927 (n-no-remove -1)
8928 (idprop (org-entry-get nil "ID")))
8929 (when (and doshift
8930 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8931 template))
8932 (delete-region beg end)
8933 (setq end beg)
8934 (setq nmin 0)
8935 (setq nmax (1+ nmax))
8936 (setq n-no-remove nmax))
8937 (goto-char end)
8938 (cl-loop for n from nmin to nmax do
8939 (insert
8940 ;; Prepare clone.
8941 (with-temp-buffer
8942 (insert template)
8943 (org-mode)
8944 (goto-char (point-min))
8945 (org-show-subtree)
8946 (and idprop (if org-clone-delete-id
8947 (org-entry-delete nil "ID")
8948 (org-id-get-create t)))
8949 (unless (= n 0)
8950 (while (re-search-forward org-clock-line-re nil t)
8951 (delete-region (line-beginning-position)
8952 (line-beginning-position 2)))
8953 (goto-char (point-min))
8954 (while (re-search-forward org-drawer-regexp nil t)
8955 (org-remove-empty-drawer-at (point))))
8956 (goto-char (point-min))
8957 (when doshift
8958 (while (re-search-forward org-ts-regexp-both nil t)
8959 (org-timestamp-change (* n shift-n) shift-what))
8960 (unless (= n n-no-remove)
8961 (goto-char (point-min))
8962 (while (re-search-forward org-ts-regexp nil t)
8963 (save-excursion
8964 (goto-char (match-beginning 0))
8965 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8966 (delete-region (match-beginning 1) (match-end 1)))))))
8967 (buffer-string)))))
8968 (goto-char beg)))
8970 ;;; Outline Sorting
8972 (defun org-sort (with-case)
8973 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8974 Optional argument WITH-CASE means sort case-sensitively."
8975 (interactive "P")
8976 (cond
8977 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8978 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8980 (org-call-with-arg 'org-sort-entries with-case))))
8982 (defun org-sort-remove-invisible (s)
8983 "Remove invisible links from string S."
8984 (remove-text-properties 0 (length s) org-rm-props s)
8985 (while (string-match org-bracket-link-regexp s)
8986 (setq s (replace-match (if (match-end 2)
8987 (match-string 3 s)
8988 (match-string 1 s))
8989 t t s)))
8990 (let ((st (format " %s " s)))
8991 (while (string-match org-emph-re st)
8992 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8993 (setq s (substring st 1 -1)))
8996 (defvar org-priority-regexp) ; defined later in the file
8998 (defvar org-after-sorting-entries-or-items-hook nil
8999 "Hook that is run after a bunch of entries or items have been sorted.
9000 When children are sorted, the cursor is in the parent line when this
9001 hook gets called. When a region or a plain list is sorted, the cursor
9002 will be in the first entry of the sorted region/list.")
9004 (defun org-sort-entries
9005 (&optional with-case sorting-type getkey-func compare-func property
9006 interactive?)
9007 "Sort entries on a certain level of an outline tree.
9008 If there is an active region, the entries in the region are sorted.
9009 Else, if the cursor is before the first entry, sort the top-level items.
9010 Else, the children of the entry at point are sorted.
9012 Sorting can be alphabetically, numerically, by date/time as given by
9013 a time stamp, by a property, by priority order, or by a custom function.
9015 The command prompts for the sorting type unless it has been given to the
9016 function through the SORTING-TYPE argument, which needs to be a character,
9017 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9018 the precise meaning of each character:
9020 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9021 c By creation time, which is assumed to be the first inactive time stamp
9022 at the beginning of a line.
9023 d By deadline date/time.
9024 k By clocking time.
9025 n Numerically, by converting the beginning of the entry/item to a number.
9026 o By order of TODO keywords.
9027 p By priority according to the cookie.
9028 r By the value of a property.
9029 s By scheduled date/time.
9030 t By date/time, either the first active time stamp in the entry, or, if
9031 none exist, by the first inactive one.
9033 Capital letters will reverse the sort order.
9035 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9036 called with point at the beginning of the record. It must return a
9037 value that is compatible with COMPARE-FUNC, the function used to
9038 compare entries.
9040 Comparing entries ignores case by default. However, with an optional argument
9041 WITH-CASE, the sorting considers case as well.
9043 Sorting is done against the visible part of the headlines, it ignores hidden
9044 links.
9046 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
9048 A non-nil value for INTERACTIVE? is used to signal that this
9049 function is being called interactively."
9050 (interactive (list current-prefix-arg nil nil nil nil t))
9051 (let ((case-func (if with-case 'identity 'downcase))
9052 (cmstr
9053 ;; The clock marker is lost when using `sort-subr', let's
9054 ;; store the clocking string.
9055 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9056 (save-excursion
9057 (goto-char org-clock-marker)
9058 (buffer-substring-no-properties (line-beginning-position)
9059 (point)))))
9060 start beg end stars re re2
9061 txt what tmp)
9062 ;; Find beginning and end of region to sort
9063 (cond
9064 ((org-region-active-p)
9065 ;; we will sort the region
9066 (setq end (region-end)
9067 what "region")
9068 (goto-char (region-beginning))
9069 (unless (org-at-heading-p) (outline-next-heading))
9070 (setq start (point)))
9071 ((or (org-at-heading-p)
9072 (ignore-errors (progn (org-back-to-heading) t)))
9073 ;; we will sort the children of the current headline
9074 (org-back-to-heading)
9075 (setq start (point)
9076 end (progn (org-end-of-subtree t t)
9077 (or (bolp) (insert "\n"))
9078 (when (>= (org-back-over-empty-lines) 1)
9079 (forward-line 1))
9080 (point))
9081 what "children")
9082 (goto-char start)
9083 (outline-show-subtree)
9084 (outline-next-heading))
9086 ;; we will sort the top-level entries in this file
9087 (goto-char (point-min))
9088 (or (org-at-heading-p) (outline-next-heading))
9089 (setq start (point))
9090 (goto-char (point-max))
9091 (beginning-of-line 1)
9092 (when (looking-at ".*?\\S-")
9093 ;; File ends in a non-white line
9094 (end-of-line 1)
9095 (insert "\n"))
9096 (setq end (point-max))
9097 (setq what "top-level")
9098 (goto-char start)
9099 (outline-show-all)))
9101 (setq beg (point))
9102 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9104 (looking-at "\\(\\*+\\)")
9105 (setq stars (match-string 1)
9106 re (concat "^" (regexp-quote stars) " +")
9107 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9108 txt (buffer-substring beg end))
9109 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9110 (when (and (not (equal stars "*")) (string-match re2 txt))
9111 (user-error "Region to sort contains a level above the first entry"))
9113 (unless sorting-type
9114 (message
9115 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9116 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9117 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9118 what)
9119 (setq sorting-type (read-char-exclusive)))
9121 (unless getkey-func
9122 (and (= (downcase sorting-type) ?f)
9123 (setq getkey-func
9124 (or (and interactive?
9125 (org-read-function
9126 "Function for extracting keys: "))
9127 (error "Missing key extractor")))))
9129 (and (= (downcase sorting-type) ?r)
9130 (not property)
9131 (setq property
9132 (completing-read "Property: "
9133 (mapcar #'list (org-buffer-property-keys t))
9134 nil t)))
9136 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9137 (message "Sorting entries...")
9139 (save-restriction
9140 (narrow-to-region start end)
9141 (let ((dcst (downcase sorting-type))
9142 (case-fold-search nil)
9143 (now (current-time)))
9144 (sort-subr
9145 (/= dcst sorting-type)
9146 ;; This function moves to the beginning character of the "record" to
9147 ;; be sorted.
9148 (lambda nil
9149 (if (re-search-forward re nil t)
9150 (goto-char (match-beginning 0))
9151 (goto-char (point-max))))
9152 ;; This function moves to the last character of the "record" being
9153 ;; sorted.
9154 (lambda nil
9155 (save-match-data
9156 (condition-case nil
9157 (outline-forward-same-level 1)
9158 (error
9159 (goto-char (point-max))))))
9160 ;; This function returns the value that gets sorted against.
9161 (lambda nil
9162 (cond
9163 ((= dcst ?n)
9164 (if (looking-at org-complex-heading-regexp)
9165 (string-to-number (org-sort-remove-invisible (match-string 4)))
9166 nil))
9167 ((= dcst ?a)
9168 (if (looking-at org-complex-heading-regexp)
9169 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9170 nil))
9171 ((= dcst ?k)
9172 (or (get-text-property (point) :org-clock-minutes) 0))
9173 ((= dcst ?t)
9174 (let ((end (save-excursion (outline-next-heading) (point))))
9175 (if (or (re-search-forward org-ts-regexp end t)
9176 (re-search-forward org-ts-regexp-both end t))
9177 (org-time-string-to-seconds (match-string 0))
9178 (float-time now))))
9179 ((= dcst ?c)
9180 (let ((end (save-excursion (outline-next-heading) (point))))
9181 (if (re-search-forward
9182 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9183 end t)
9184 (org-time-string-to-seconds (match-string 0))
9185 (float-time now))))
9186 ((= dcst ?s)
9187 (let ((end (save-excursion (outline-next-heading) (point))))
9188 (if (re-search-forward org-scheduled-time-regexp end t)
9189 (org-time-string-to-seconds (match-string 1))
9190 (float-time now))))
9191 ((= dcst ?d)
9192 (let ((end (save-excursion (outline-next-heading) (point))))
9193 (if (re-search-forward org-deadline-time-regexp end t)
9194 (org-time-string-to-seconds (match-string 1))
9195 (float-time now))))
9196 ((= dcst ?p)
9197 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9198 (string-to-char (match-string 2))
9199 org-default-priority))
9200 ((= dcst ?r)
9201 (or (org-entry-get nil property) ""))
9202 ((= dcst ?o)
9203 (when (looking-at org-complex-heading-regexp)
9204 (let* ((m (match-string 2))
9205 (s (if (member m org-done-keywords) '- '+)))
9206 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9207 ((= dcst ?f)
9208 (if getkey-func
9209 (progn
9210 (setq tmp (funcall getkey-func))
9211 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9212 tmp)
9213 (error "Invalid key function `%s'" getkey-func)))
9214 (t (error "Invalid sorting type `%c'" sorting-type))))
9216 (cond
9217 ((= dcst ?a) 'string<)
9218 ((= dcst ?f)
9219 (or compare-func
9220 (and interactive?
9221 (org-read-function
9222 (concat "Function for comparing keys "
9223 "(empty for default `sort-subr' predicate): ")
9224 'allow-empty))))
9225 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9226 (run-hooks 'org-after-sorting-entries-or-items-hook)
9227 ;; Reset the clock marker if needed
9228 (when cmstr
9229 (save-excursion
9230 (goto-char start)
9231 (search-forward cmstr nil t)
9232 (move-marker org-clock-marker (point))))
9233 (message "Sorting entries...done")))
9235 ;;; The orgstruct minor mode
9237 ;; Define a minor mode which can be used in other modes in order to
9238 ;; integrate the Org mode structure editing commands.
9240 ;; This is really a hack, because the Org mode structure commands use
9241 ;; keys which normally belong to the major mode. Here is how it
9242 ;; works: The minor mode defines all the keys necessary to operate the
9243 ;; structure commands, but wraps the commands into a function which
9244 ;; tests if the cursor is currently at a headline or a plain list
9245 ;; item. If that is the case, the structure command is used,
9246 ;; temporarily setting many Org mode variables like regular
9247 ;; expressions for filling etc. However, when any of those keys is
9248 ;; used at a different location, function uses `key-binding' to look
9249 ;; up if the key has an associated command in another currently active
9250 ;; keymap (minor modes, major mode, global), and executes that
9251 ;; command. There might be problems if any of the keys is otherwise
9252 ;; used as a prefix key.
9254 (defcustom orgstruct-heading-prefix-regexp ""
9255 "Regexp that matches the custom prefix of Org headlines in
9256 orgstruct(++)-mode."
9257 :group 'org
9258 :version "24.4"
9259 :package-version '(Org . "8.3")
9260 :type 'regexp)
9261 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9263 (defcustom orgstruct-setup-hook nil
9264 "Hook run after orgstruct-mode-map is filled."
9265 :group 'org
9266 :version "24.4"
9267 :package-version '(Org . "8.0")
9268 :type 'hook)
9270 (defvar orgstruct-initialized nil)
9272 (defvar org-local-vars nil
9273 "List of local variables, for use by `orgstruct-mode'.")
9275 ;;;###autoload
9276 (define-minor-mode orgstruct-mode
9277 "Toggle the minor mode `orgstruct-mode'.
9278 This mode is for using Org mode structure commands in other
9279 modes. The following keys behave as if Org mode were active, if
9280 the cursor is on a headline, or on a plain list item (both as
9281 defined by Org mode)."
9282 nil " OrgStruct" (make-sparse-keymap)
9283 (funcall (if orgstruct-mode
9284 'add-to-invisibility-spec
9285 'remove-from-invisibility-spec)
9286 '(outline . t))
9287 (when orgstruct-mode
9288 (org-load-modules-maybe)
9289 (unless orgstruct-initialized
9290 (orgstruct-setup)
9291 (setq orgstruct-initialized t))))
9293 ;;;###autoload
9294 (defun turn-on-orgstruct ()
9295 "Unconditionally turn on `orgstruct-mode'."
9296 (orgstruct-mode 1))
9298 (defvar-local orgstruct-is-++ nil
9299 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9300 (defvar-local org-fb-vars nil)
9301 (defun orgstruct++-mode (&optional arg)
9302 "Toggle `orgstruct-mode', the enhanced version of it.
9303 In addition to setting orgstruct-mode, this also exports all
9304 indentation and autofilling variables from Org mode into the
9305 buffer. It will also recognize item context in multiline items."
9306 (interactive "P")
9307 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9308 (if (< arg 1)
9309 (progn (orgstruct-mode -1)
9310 (dolist (v org-fb-vars)
9311 (set (make-local-variable (car v))
9312 (if (eq (car-safe (cadr v)) 'quote)
9313 (cl-cadadr v)
9314 (nth 1 v)))))
9315 (orgstruct-mode 1)
9316 (setq org-fb-vars nil)
9317 (unless org-local-vars
9318 (setq org-local-vars (org-get-local-variables)))
9319 (let (var val)
9320 (dolist (x org-local-vars)
9321 (when (string-match
9322 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9323 \\|fill-prefix\\|indent-\\)"
9324 (symbol-name (car x)))
9325 (setq var (car x) val (nth 1 x))
9326 (push (list var `(quote ,(eval var))) org-fb-vars)
9327 (set (make-local-variable var)
9328 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9329 (setq-local orgstruct-is-++ t))))
9331 ;;;###autoload
9332 (defun turn-on-orgstruct++ ()
9333 "Unconditionally turn on `orgstruct++-mode'."
9334 (orgstruct++-mode 1))
9336 (defun orgstruct-error ()
9337 "Error when there is no default binding for a structure key."
9338 (interactive)
9339 (funcall (if (fboundp 'user-error)
9340 'user-error
9341 'error)
9342 "This key has no function outside structure elements"))
9344 (defun orgstruct-setup ()
9345 "Setup orgstruct keymap."
9346 (dolist (cell '((org-demote . t)
9347 (org-metaleft . t)
9348 (org-metaright . t)
9349 (org-promote . t)
9350 (org-shiftmetaleft . t)
9351 (org-shiftmetaright . t)
9352 org-backward-element
9353 org-backward-heading-same-level
9354 org-ctrl-c-ret
9355 org-ctrl-c-minus
9356 org-ctrl-c-star
9357 org-cycle
9358 org-force-cycle-archived
9359 org-forward-heading-same-level
9360 org-insert-heading
9361 org-insert-heading-respect-content
9362 org-kill-note-or-show-branches
9363 org-mark-subtree
9364 org-meta-return
9365 org-metadown
9366 org-metaup
9367 org-narrow-to-subtree
9368 org-promote-subtree
9369 org-reveal
9370 org-shiftdown
9371 org-shiftleft
9372 org-shiftmetadown
9373 org-shiftmetaup
9374 org-shiftright
9375 org-shifttab
9376 org-shifttab
9377 org-shiftup
9378 org-show-children
9379 org-show-subtree
9380 org-sort
9381 org-up-element
9382 outline-demote
9383 outline-next-visible-heading
9384 outline-previous-visible-heading
9385 outline-promote
9386 outline-up-heading))
9387 (let ((f (or (car-safe cell) cell))
9388 (disable-when-heading-prefix (cdr-safe cell)))
9389 (when (fboundp f)
9390 (let ((new-bindings))
9391 (dolist (binding (nconc (where-is-internal f org-mode-map)
9392 (where-is-internal f outline-mode-map)))
9393 (push binding new-bindings)
9394 ;; TODO use local-function-key-map
9395 (dolist (rep '(("<tab>" . "TAB")
9396 ("<return>" . "RET")
9397 ("<escape>" . "ESC")
9398 ("<delete>" . "DEL")))
9399 (setq binding (read-kbd-macro
9400 (let ((case-fold-search))
9401 (replace-regexp-in-string
9402 (regexp-quote (cdr rep))
9403 (car rep)
9404 (key-description binding)))))
9405 (cl-pushnew binding new-bindings :test 'equal)))
9406 (dolist (binding new-bindings)
9407 (let ((key (lookup-key orgstruct-mode-map binding)))
9408 (when (or (not key) (numberp key))
9409 (ignore-errors
9410 (org-defkey orgstruct-mode-map
9411 binding
9412 (orgstruct-make-binding
9413 f binding disable-when-heading-prefix))))))))))
9414 (run-hooks 'orgstruct-setup-hook))
9416 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9417 "Create a function for binding in the structure minor mode.
9418 FUN is the command to call inside a table. KEY is the key that
9419 should be checked in for a command to execute outside of tables.
9420 Non-nil `disable-when-heading-prefix' means to disable the command
9421 if `orgstruct-heading-prefix-regexp' is not empty."
9422 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9423 (let ((nname name)
9424 (i 0))
9425 (while (fboundp (intern nname))
9426 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9427 (setq name (intern nname)))
9428 (eval
9429 (let ((bindings '((org-heading-regexp
9430 (concat "^"
9431 orgstruct-heading-prefix-regexp
9432 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9433 (org-outline-regexp
9434 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9435 (org-outline-regexp-bol
9436 (concat "^" org-outline-regexp))
9437 (outline-regexp org-outline-regexp)
9438 (outline-heading-end-regexp "\n")
9439 (outline-level 'org-outline-level)
9440 (outline-heading-alist))))
9441 `(defun ,name (arg)
9442 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9443 "Outside of structure, run the binding of `"
9444 (key-description key) "'."
9445 (when disable-when-heading-prefix
9446 (concat
9447 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9448 "back to the default binding due to limitations of Org's implementation of\n"
9449 "`" (symbol-name fun) "'.")))
9450 (interactive "p")
9451 (let* ((disable
9452 ,(and disable-when-heading-prefix
9453 '(not (string= orgstruct-heading-prefix-regexp ""))))
9454 (fallback
9455 (or disable
9456 (not
9457 (let* ,bindings
9458 (org-context-p 'headline 'item
9459 ,(when (memq fun
9460 '(org-insert-heading
9461 org-insert-heading-respect-content
9462 org-meta-return))
9463 '(when orgstruct-is-++
9464 'item-body))))))))
9465 (if fallback
9466 (let* ((orgstruct-mode)
9467 (binding
9468 (let ((key ,key))
9469 (catch 'exit
9470 (dolist
9471 (rep
9472 '(nil
9473 ("<\\([^>]*\\)tab>" . "\\1TAB")
9474 ("<\\([^>]*\\)return>" . "\\1RET")
9475 ("<\\([^>]*\\)escape>" . "\\1ESC")
9476 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9477 nil)
9478 (when rep
9479 (setq key (read-kbd-macro
9480 (let ((case-fold-search))
9481 (replace-regexp-in-string
9482 (car rep)
9483 (cdr rep)
9484 (key-description key))))))
9485 (when (key-binding key)
9486 (throw 'exit (key-binding key))))))))
9487 (if (keymapp binding)
9488 (org-set-transient-map binding)
9489 (let ((func (or binding
9490 (unless disable
9491 'orgstruct-error))))
9492 (when func
9493 (call-interactively func)))))
9494 (org-run-like-in-org-mode
9495 (lambda ()
9496 (interactive)
9497 (let* ,bindings
9498 (call-interactively ',fun)))))))))
9499 name))
9501 (defun org-contextualize-keys (alist contexts)
9502 "Return valid elements in ALIST depending on CONTEXTS.
9504 `org-agenda-custom-commands' or `org-capture-templates' are the
9505 values used for ALIST, and `org-agenda-custom-commands-contexts'
9506 or `org-capture-templates-contexts' are the associated contexts
9507 definitions."
9508 (let ((contexts
9509 ;; normalize contexts
9510 (mapcar
9511 (lambda(c) (cond ((listp (cadr c))
9512 (list (car c) (car c) (nth 1 c)))
9513 ((string= "" (cadr c))
9514 (list (car c) (car c) (nth 2 c)))
9515 (t c)))
9516 contexts))
9517 (a alist) r s)
9518 ;; loop over all commands or templates
9519 (dolist (c a)
9520 (let (vrules repl)
9521 (cond
9522 ((not (assoc (car c) contexts))
9523 (push c r))
9524 ((and (assoc (car c) contexts)
9525 (setq vrules (org-contextualize-validate-key
9526 (car c) contexts)))
9527 (mapc (lambda (vr)
9528 (unless (equal (car vr) (cadr vr))
9529 (setq repl vr)))
9530 vrules)
9531 (if (not repl) (push c r)
9532 (push (cadr repl) s)
9533 (push
9534 (cons (car c)
9535 (cdr (or (assoc (cadr repl) alist)
9536 (error "Undefined key `%s' as contextual replacement for `%s'"
9537 (cadr repl) (car c)))))
9538 r))))))
9539 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9540 (delq
9542 (delete-dups
9543 (mapcar (lambda (x)
9544 (let ((tpl (car x)))
9545 (unless (delq
9547 (mapcar (lambda (y)
9548 (equal y tpl))
9550 x)))
9551 (reverse r))))))
9553 (defun org-contextualize-validate-key (key contexts)
9554 "Check CONTEXTS for agenda or capture KEY."
9555 (let (res)
9556 (dolist (r contexts)
9557 (dolist (rr (car (last r)))
9558 (when
9559 (and (equal key (car r))
9560 (if (functionp rr) (funcall rr)
9561 (or (and (eq (car rr) 'in-file)
9562 (buffer-file-name)
9563 (string-match (cdr rr) (buffer-file-name)))
9564 (and (eq (car rr) 'in-mode)
9565 (string-match (cdr rr) (symbol-name major-mode)))
9566 (and (eq (car rr) 'in-buffer)
9567 (string-match (cdr rr) (buffer-name)))
9568 (when (and (eq (car rr) 'not-in-file)
9569 (buffer-file-name))
9570 (not (string-match (cdr rr) (buffer-file-name))))
9571 (when (eq (car rr) 'not-in-mode)
9572 (not (string-match (cdr rr) (symbol-name major-mode))))
9573 (when (eq (car rr) 'not-in-buffer)
9574 (not (string-match (cdr rr) (buffer-name)))))))
9575 (push r res))))
9576 (delete-dups (delq nil res))))
9578 (defun org-context-p (&rest contexts)
9579 "Check if local context is any of CONTEXTS.
9580 Possible values in the list of contexts are `table', `headline', and `item'."
9581 (let ((pos (point)))
9582 (goto-char (point-at-bol))
9583 (prog1 (or (and (memq 'table contexts)
9584 (looking-at "[ \t]*|"))
9585 (and (memq 'headline contexts)
9586 (looking-at org-outline-regexp))
9587 (and (memq 'item contexts)
9588 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9589 (and (memq 'item-body contexts)
9590 (org-in-item-p)))
9591 (goto-char pos))))
9593 (defconst org-unique-local-variables
9594 '(org-element--cache
9595 org-element--cache-objects
9596 org-element--cache-sync-keys
9597 org-element--cache-sync-requests
9598 org-element--cache-sync-timer)
9599 "List of local variables that cannot be transferred to another buffer.")
9601 (defun org-get-local-variables ()
9602 "Return a list of all local variables in an Org mode buffer."
9603 (delq nil
9604 (mapcar
9605 (lambda (x)
9606 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9607 (name (car binding)))
9608 (and (not (get name 'org-state))
9609 (not (memq name org-unique-local-variables))
9610 (string-match-p
9611 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9612 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9613 (symbol-name name))
9614 binding)))
9615 (with-temp-buffer
9616 (org-mode)
9617 (buffer-local-variables)))))
9619 (defun org-clone-local-variables (from-buffer &optional regexp)
9620 "Clone local variables from FROM-BUFFER.
9621 Optional argument REGEXP selects variables to clone."
9622 (dolist (pair (buffer-local-variables from-buffer))
9623 (pcase pair
9624 (`(,name . ,value) ;ignore unbound variables
9625 (when (and (not (memq name org-unique-local-variables))
9626 (or (null regexp) (string-match-p regexp (symbol-name name))))
9627 (set (make-local-variable name) value))))))
9629 ;;;###autoload
9630 (defun org-run-like-in-org-mode (cmd)
9631 "Run a command, pretending that the current buffer is in Org mode.
9632 This will temporarily bind local variables that are typically bound in
9633 Org mode to the values they have in Org mode, and then interactively
9634 call CMD."
9635 (org-load-modules-maybe)
9636 (unless org-local-vars
9637 (setq org-local-vars (org-get-local-variables)))
9638 (let (binds)
9639 (dolist (var org-local-vars)
9640 (when (or (not (boundp (car var)))
9641 (eq (symbol-value (car var))
9642 (default-value (car var))))
9643 (push (list (car var) `(quote ,(cadr var))) binds)))
9644 (eval `(let ,binds
9645 (call-interactively (quote ,cmd))))))
9647 (defun org-get-category (&optional pos force-refresh)
9648 "Get the category applying to position POS."
9649 (save-match-data
9650 (when force-refresh (org-refresh-category-properties))
9651 (let ((pos (or pos (point))))
9652 (or (get-text-property pos 'org-category)
9653 (progn (org-refresh-category-properties)
9654 (get-text-property pos 'org-category))))))
9656 ;;; Refresh properties
9658 (defun org-refresh-properties (dprop tprop)
9659 "Refresh buffer text properties.
9660 DPROP is the drawer property and TPROP is either the
9661 corresponding text property to set, or an alist with each element
9662 being a text property (as a symbol) and a function to apply to
9663 the value of the drawer property."
9664 (let* ((case-fold-search t)
9665 (inhibit-read-only t)
9666 (inherit? (org-property-inherit-p dprop))
9667 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9668 (global (and inherit? (org--property-global-value dprop nil))))
9669 (org-with-silent-modifications
9670 (org-with-point-at 1
9671 ;; Set global values (e.g., values defined through
9672 ;; "#+PROPERTY:" keywords) to the whole buffer.
9673 (when global (put-text-property (point-min) (point-max) tprop global))
9674 ;; Set local values.
9675 (while (re-search-forward property-re nil t)
9676 (when (org-at-property-p)
9677 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9678 (outline-next-heading))))))
9680 (defun org-refresh-property (tprop p &optional inherit)
9681 "Refresh the buffer text property TPROP from the drawer property P.
9682 The refresh happens only for the current headline, or the whole
9683 sub-tree if optional argument INHERIT is non-nil."
9684 (unless (org-before-first-heading-p)
9685 (save-excursion
9686 (org-back-to-heading t)
9687 (let ((start (point))
9688 (end (save-excursion
9689 (if inherit (org-end-of-subtree t t)
9690 (or (outline-next-heading) (point-max))))))
9691 (if (symbolp tprop)
9692 ;; TPROP is a text property symbol.
9693 (put-text-property start end tprop p)
9694 ;; TPROP is an alist with (property . function) elements.
9695 (pcase-dolist (`(,prop . ,f) tprop)
9696 (put-text-property start end prop (funcall f p))))))))
9698 (defun org-refresh-category-properties ()
9699 "Refresh category text properties in the buffer."
9700 (let ((case-fold-search t)
9701 (inhibit-read-only t)
9702 (default-category
9703 (cond ((null org-category)
9704 (if buffer-file-name
9705 (file-name-sans-extension
9706 (file-name-nondirectory buffer-file-name))
9707 "???"))
9708 ((symbolp org-category) (symbol-name org-category))
9709 (t org-category))))
9710 (org-with-silent-modifications
9711 (org-with-wide-buffer
9712 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9713 ;; This is the default category for the buffer. If none is
9714 ;; found, fall-back to `org-category' or buffer file name.
9715 (put-text-property
9716 (point-min) (point-max)
9717 'org-category
9718 (catch 'buffer-category
9719 (goto-char (point-max))
9720 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9721 (let ((element (org-element-at-point)))
9722 (when (eq (org-element-type element) 'keyword)
9723 (throw 'buffer-category
9724 (org-element-property :value element)))))
9725 default-category))
9726 ;; Set sub-tree specific categories.
9727 (goto-char (point-min))
9728 (let ((regexp (org-re-property "CATEGORY")))
9729 (while (re-search-forward regexp nil t)
9730 (let ((value (match-string-no-properties 3)))
9731 (when (org-at-property-p)
9732 (put-text-property
9733 (save-excursion (org-back-to-heading t) (point))
9734 (save-excursion (org-end-of-subtree t t) (point))
9735 'org-category
9736 value)))))))))
9738 (defun org-refresh-stats-properties ()
9739 "Refresh stats text properties in the buffer."
9740 (org-with-silent-modifications
9741 (org-with-point-at 1
9742 (let ((regexp (concat org-outline-regexp-bol
9743 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9744 (while (re-search-forward regexp nil t)
9745 (let* ((numerator (string-to-number (match-string 1)))
9746 (denominator (and (match-end 2)
9747 (string-to-number (match-string 2))))
9748 (stats (cond ((not denominator) numerator) ;percent
9749 ((= denominator 0) 0)
9750 (t (/ (* numerator 100) denominator)))))
9751 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9752 'org-stats stats)))))))
9754 (defun org-refresh-effort-properties ()
9755 "Refresh effort properties"
9756 (org-refresh-properties
9757 org-effort-property
9758 '((effort . identity)
9759 (effort-minutes . org-duration-string-to-minutes))))
9761 ;;;; Link Stuff
9763 ;;; Link abbreviations
9765 (defun org-link-expand-abbrev (link)
9766 "Apply replacements as defined in `org-link-abbrev-alist'."
9767 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9768 (let* ((key (match-string 1 link))
9769 (as (or (assoc key org-link-abbrev-alist-local)
9770 (assoc key org-link-abbrev-alist)))
9771 (tag (and (match-end 2) (match-string 3 link)))
9772 rpl)
9773 (if (not as)
9774 link
9775 (setq rpl (cdr as))
9776 (cond
9777 ((symbolp rpl) (funcall rpl tag))
9778 ((string-match "%(\\([^)]+\\))" rpl)
9779 (replace-match
9780 (save-match-data
9781 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9782 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9783 ((string-match "%h" rpl)
9784 (replace-match (url-hexify-string (or tag "")) t t rpl))
9785 (t (concat rpl tag)))))
9786 link))
9788 ;;; Storing and inserting links
9790 (defvar org-insert-link-history nil
9791 "Minibuffer history for links inserted with `org-insert-link'.")
9793 (defvar org-stored-links nil
9794 "Contains the links stored with `org-store-link'.")
9796 (defvar org-store-link-plist nil
9797 "Plist with info about the most recently link created with `org-store-link'.")
9799 (defun org-store-link-functions ()
9800 "Return a list of functions that are called to create and store a link.
9801 The functions defined in the :store property of
9802 `org-link-parameters'.
9804 Each function will be called in turn until one returns a non-nil
9805 value. Each function should check if it is responsible for
9806 creating this link (for example by looking at the major mode).
9807 If not, it must exit and return nil. If yes, it should return
9808 a non-nil value after calling `org-store-link-props' with a list
9809 of properties and values. Special properties are:
9811 :type The link prefix, like \"http\". This must be given.
9812 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9813 This is obligatory as well.
9814 :description Optional default description for the second pair
9815 of brackets in an Org mode link. The user can still change
9816 this when inserting this link into an Org mode buffer.
9818 In addition to these, any additional properties can be specified
9819 and then used in capture templates."
9820 (cl-loop for link in org-link-parameters
9821 with store-func
9822 do (setq store-func (org-link-get-parameter (car link) :store))
9823 if store-func
9824 collect store-func))
9826 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9827 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9829 ;;;###autoload
9830 (defun org-store-link (arg)
9831 "Store an org-link to the current location.
9832 \\<org-mode-map>
9833 This link is added to `org-stored-links' and can later be inserted
9834 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9836 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9837 A single
9838 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9839 `org-gnus-prefer-web-links' for links to Usenet articles.
9841 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9842 skipping storing functions that are not
9843 part of Org core.
9845 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9846 prefix ARG forces storing a link for each line in the
9847 active region."
9848 (interactive "P")
9849 (org-load-modules-maybe)
9850 (if (and (equal arg '(64)) (org-region-active-p))
9851 (save-excursion
9852 (let ((end (region-end)))
9853 (goto-char (region-beginning))
9854 (set-mark (point))
9855 (while (< (point-at-eol) end)
9856 (move-end-of-line 1) (activate-mark)
9857 (let (current-prefix-arg)
9858 (call-interactively 'org-store-link))
9859 (move-beginning-of-line 2)
9860 (set-mark (point)))))
9861 (setq org-store-link-plist nil)
9862 (let (link cpltxt desc description search
9863 txt custom-id agenda-link sfuns sfunsn)
9864 (cond
9866 ;; Store a link using an external link type
9867 ((and (not (equal arg '(16)))
9868 (setq sfuns
9869 (delq
9870 nil (mapcar (lambda (f)
9871 (let (fs) (if (funcall f) (push f fs))))
9872 (org-store-link-functions)))
9873 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9874 (or (and (cdr sfuns)
9875 (funcall (intern
9876 (completing-read
9877 "Which function for creating the link? "
9878 sfunsn nil t (car sfunsn)))))
9879 (funcall (caar sfuns)))
9880 (setq link (plist-get org-store-link-plist :link)
9881 desc (or (plist-get org-store-link-plist
9882 :description)
9883 link))))
9885 ;; Store a link from a source code buffer.
9886 ((org-src-edit-buffer-p)
9887 (let ((coderef-format (org-src-coderef-format)))
9888 (cond ((save-excursion
9889 (beginning-of-line)
9890 (looking-at (org-src-coderef-regexp coderef-format)))
9891 (setq link (format "(%s)" (match-string-no-properties 3))))
9892 ((called-interactively-p 'any)
9893 (let ((label (read-string "Code line label: ")))
9894 (end-of-line)
9895 (setq link (format coderef-format label))
9896 (let ((gc (- 79 (length link))))
9897 (if (< (current-column) gc)
9898 (org-move-to-column gc t)
9899 (insert " ")))
9900 (insert link)
9901 (setq link (concat "(" label ")"))
9902 (setq desc nil)))
9903 (t (setq link nil)))))
9905 ;; We are in the agenda, link to referenced location
9906 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9907 (let ((m (or (get-text-property (point) 'org-hd-marker)
9908 (get-text-property (point) 'org-marker))))
9909 (when m
9910 (org-with-point-at m
9911 (setq agenda-link
9912 (if (called-interactively-p 'any)
9913 (call-interactively 'org-store-link)
9914 (org-store-link nil)))))))
9916 ((eq major-mode 'calendar-mode)
9917 (let ((cd (calendar-cursor-to-date)))
9918 (setq link
9919 (format-time-string
9920 (car org-time-stamp-formats)
9921 (apply 'encode-time
9922 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9923 nil nil nil))))
9924 (org-store-link-props :type "calendar" :date cd)))
9926 ((eq major-mode 'help-mode)
9927 (setq link (concat "help:" (save-excursion
9928 (goto-char (point-min))
9929 (looking-at "^[^ ]+")
9930 (match-string 0))))
9931 (org-store-link-props :type "help"))
9933 ((eq major-mode 'w3-mode)
9934 (setq cpltxt (if (and (buffer-name)
9935 (not (string-match "Untitled" (buffer-name))))
9936 (buffer-name)
9937 (url-view-url t))
9938 link (url-view-url t))
9939 (org-store-link-props :type "w3" :url (url-view-url t)))
9941 ((eq major-mode 'image-mode)
9942 (setq cpltxt (concat "file:"
9943 (abbreviate-file-name buffer-file-name))
9944 link cpltxt)
9945 (org-store-link-props :type "image" :file buffer-file-name))
9947 ;; In dired, store a link to the file of the current line
9948 ((derived-mode-p 'dired-mode)
9949 (let ((file (dired-get-filename nil t)))
9950 (setq file (if file
9951 (abbreviate-file-name
9952 (expand-file-name (dired-get-filename nil t)))
9953 ;; otherwise, no file so use current directory.
9954 default-directory))
9955 (setq cpltxt (concat "file:" file)
9956 link cpltxt)))
9958 ((setq search (run-hook-with-args-until-success
9959 'org-create-file-search-functions))
9960 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9961 "::" search))
9962 (setq cpltxt (or description link)))
9964 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9965 (org-with-limited-levels
9966 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9967 (cond
9968 ;; Store a link using the target at point
9969 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9970 (setq cpltxt
9971 (concat "file:"
9972 (abbreviate-file-name
9973 (buffer-file-name (buffer-base-buffer)))
9974 "::" (match-string 1))
9975 link cpltxt))
9976 ((and (featurep 'org-id)
9977 (or (eq org-id-link-to-org-use-id t)
9978 (and (called-interactively-p 'any)
9979 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9980 (and (eq org-id-link-to-org-use-id
9981 'create-if-interactive-and-no-custom-id)
9982 (not custom-id))))
9983 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9984 ;; Store a link using the ID at point
9985 (setq link (condition-case nil
9986 (prog1 (org-id-store-link)
9987 (setq desc (or (plist-get org-store-link-plist
9988 :description)
9989 "")))
9990 (error
9991 ;; Probably before first headline, link only to file
9992 (concat "file:"
9993 (abbreviate-file-name
9994 (buffer-file-name (buffer-base-buffer))))))))
9996 ;; Just link to current headline
9997 (setq cpltxt (concat "file:"
9998 (abbreviate-file-name
9999 (buffer-file-name (buffer-base-buffer)))))
10000 ;; Add a context search string
10001 (when (org-xor org-context-in-file-links
10002 (equal arg '(4)))
10003 (let* ((element (org-element-at-point))
10004 (name (org-element-property :name element)))
10005 (setq txt (cond
10006 ((org-at-heading-p) nil)
10007 (name)
10008 ((org-region-active-p)
10009 (buffer-substring (region-beginning) (region-end)))))
10010 (when (or (null txt) (string-match "\\S-" txt))
10011 (setq cpltxt
10012 (concat cpltxt "::"
10013 (condition-case nil
10014 (org-make-org-heading-search-string txt)
10015 (error "")))
10016 desc (or name
10017 (nth 4 (ignore-errors (org-heading-components)))
10018 "NONE")))))
10019 (when (string-match "::\\'" cpltxt)
10020 (setq cpltxt (substring cpltxt 0 -2)))
10021 (setq link cpltxt)))))
10023 ((buffer-file-name (buffer-base-buffer))
10024 ;; Just link to this file here.
10025 (setq cpltxt (concat "file:"
10026 (abbreviate-file-name
10027 (buffer-file-name (buffer-base-buffer)))))
10028 ;; Add a context string.
10029 (when (org-xor org-context-in-file-links
10030 (equal arg '(4)))
10031 (setq txt (if (org-region-active-p)
10032 (buffer-substring (region-beginning) (region-end))
10033 (buffer-substring (point-at-bol) (point-at-eol))))
10034 ;; Only use search option if there is some text.
10035 (when (string-match "\\S-" txt)
10036 (setq cpltxt
10037 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10038 desc "NONE")))
10039 (setq link cpltxt))
10041 ((called-interactively-p 'interactive)
10042 (user-error "No method for storing a link from this buffer"))
10044 (t (setq link nil)))
10046 ;; We're done setting link and desc, clean up
10047 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10048 (setq link (or link cpltxt)
10049 desc (or desc cpltxt))
10050 (cond ((not desc))
10051 ((equal desc "NONE") (setq desc nil))
10052 (t (setq desc
10053 (replace-regexp-in-string
10054 org-bracket-link-analytic-regexp
10055 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10056 desc))))
10057 ;; Return the link
10058 (if (not (and (or (called-interactively-p 'any)
10059 executing-kbd-macro)
10060 link))
10061 (or agenda-link (and link (org-make-link-string link desc)))
10062 (push (list link desc) org-stored-links)
10063 (message "Stored: %s" (or desc link))
10064 (when custom-id
10065 (setq link (concat "file:" (abbreviate-file-name
10066 (buffer-file-name)) "::#" custom-id))
10067 (push (list link desc) org-stored-links))
10068 (car org-stored-links)))))
10070 (defun org-store-link-props (&rest plist)
10071 "Store link properties, extract names, addresses and dates."
10072 (let ((x (plist-get plist :from)))
10073 (when x
10074 (let ((adr (mail-extract-address-components x)))
10075 (setq plist (plist-put plist :fromname (car adr)))
10076 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10077 (let ((x (plist-get plist :to)))
10078 (when x
10079 (let ((adr (mail-extract-address-components x)))
10080 (setq plist (plist-put plist :toname (car adr)))
10081 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10082 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10083 (when x
10084 (setq plist (plist-put plist :date-timestamp
10085 (format-time-string
10086 (org-time-stamp-format t) x)))
10087 (setq plist (plist-put plist :date-timestamp-inactive
10088 (format-time-string
10089 (org-time-stamp-format t t) x)))))
10090 (let ((from (plist-get plist :from))
10091 (to (plist-get plist :to)))
10092 (when (and from to org-from-is-user-regexp)
10093 (setq plist
10094 (plist-put plist :fromto
10095 (if (string-match org-from-is-user-regexp from)
10096 (concat "to %t")
10097 (concat "from %f"))))))
10098 (setq org-store-link-plist plist))
10100 (defun org-add-link-props (&rest plist)
10101 "Add these properties to the link property list."
10102 (let (key value)
10103 (while plist
10104 (setq key (pop plist) value (pop plist))
10105 (setq org-store-link-plist
10106 (plist-put org-store-link-plist key value)))))
10108 (defun org-email-link-description (&optional fmt)
10109 "Return the description part of an email link.
10110 This takes information from `org-store-link-plist' and formats it
10111 according to FMT (default from `org-email-link-description-format')."
10112 (setq fmt (or fmt org-email-link-description-format))
10113 (let* ((p org-store-link-plist)
10114 (to (plist-get p :toaddress))
10115 (from (plist-get p :fromaddress))
10116 (table
10117 (list
10118 (cons "%c" (plist-get p :fromto))
10119 (cons "%F" (plist-get p :from))
10120 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10121 (cons "%T" (plist-get p :to))
10122 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10123 (cons "%s" (plist-get p :subject))
10124 (cons "%d" (plist-get p :date))
10125 (cons "%m" (plist-get p :message-id)))))
10126 (when (string-match "%c" fmt)
10127 ;; Check if the user wrote this message
10128 (if (and org-from-is-user-regexp from to
10129 (save-match-data (string-match org-from-is-user-regexp from)))
10130 (setq fmt (replace-match "to %t" t t fmt))
10131 (setq fmt (replace-match "from %f" t t fmt))))
10132 (org-replace-escapes fmt table)))
10134 (defun org-make-org-heading-search-string (&optional string)
10135 "Make search string for the current headline or STRING."
10136 (let ((s (or string
10137 (and (derived-mode-p 'org-mode)
10138 (save-excursion
10139 (org-back-to-heading t)
10140 (org-element-property :raw-value (org-element-at-point))))))
10141 (lines org-context-in-file-links))
10142 (or string (setq s (concat "*" s))) ; Add * for headlines
10143 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10144 (when (and string (integerp lines) (> lines 0))
10145 (let ((slines (org-split-string s "\n")))
10146 (when (< lines (length slines))
10147 (setq s (mapconcat
10148 'identity
10149 (reverse (nthcdr (- (length slines) lines)
10150 (reverse slines))) "\n")))))
10151 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10153 (defun org-make-link-string (link &optional description)
10154 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10155 (unless (org-string-nw-p link) (error "Empty link"))
10156 (let ((uri (cond ((string-match org-link-types-re link)
10157 (concat (match-string 1 link)
10158 (org-link-escape (substring link (match-end 1)))))
10159 ;; For readability, url-encode internal links only
10160 ;; when absolutely needed (i.e, when they contain
10161 ;; square brackets). File links however, are
10162 ;; encoded since, e.g., spaces are significant.
10163 ((or (file-name-absolute-p link)
10164 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10165 (org-link-escape link))
10166 (t link)))
10167 (description
10168 (and (org-string-nw-p description)
10169 ;; Remove brackets from description, as they are fatal.
10170 (replace-regexp-in-string
10171 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10172 (org-trim description)))))
10173 (format "[[%s]%s]"
10175 (if description (format "[%s]" description) ""))))
10177 (defconst org-link-escape-chars
10178 ;;%20 %5B %5D %25
10179 '(?\s ?\[ ?\] ?%)
10180 "List of characters that should be escaped in a link when stored to Org.
10181 This is the list that is used for internal purposes.")
10183 (defun org-link-escape (text &optional table merge)
10184 "Return percent escaped representation of TEXT.
10185 TEXT is a string with the text to escape.
10186 Optional argument TABLE is a list with characters that should be
10187 escaped. When nil, `org-link-escape-chars' is used.
10188 If optional argument MERGE is set, merge TABLE into
10189 `org-link-escape-chars'."
10190 (let ((characters-to-encode
10191 (cond ((null table) org-link-escape-chars)
10192 (merge (append org-link-escape-chars table))
10193 (t table))))
10194 (mapconcat
10195 (lambda (c)
10196 (if (or (memq c characters-to-encode)
10197 (and org-url-hexify-p (or (< c 32) (> c 126))))
10198 (mapconcat (lambda (e) (format "%%%.2X" e))
10199 (or (encode-coding-char c 'utf-8)
10200 (error "Unable to percent escape character: %c" c))
10202 (char-to-string c)))
10203 text "")))
10205 (defun org-link-unescape (str)
10206 "Unhex hexified Unicode parts in string STR.
10207 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10208 reciprocal of `org-link-escape', which see."
10209 (if (org-string-nw-p str)
10210 (replace-regexp-in-string
10211 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10212 str))
10214 (defun org-link-unescape-compound (hex)
10215 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10216 Note: this function also decodes single byte encodings like
10217 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10218 (save-match-data
10219 (let* ((bytes (cdr (split-string hex "%")))
10220 (ret "")
10221 (eat 0)
10222 (sum 0))
10223 (while bytes
10224 (let* ((val (string-to-number (pop bytes) 16))
10225 (shift-xor
10226 (if (= 0 eat)
10227 (cond
10228 ((>= val 252) (cons 6 252))
10229 ((>= val 248) (cons 5 248))
10230 ((>= val 240) (cons 4 240))
10231 ((>= val 224) (cons 3 224))
10232 ((>= val 192) (cons 2 192))
10233 (t (cons 0 0)))
10234 (cons 6 128))))
10235 (when (>= val 192) (setq eat (car shift-xor)))
10236 (setq val (logxor val (cdr shift-xor)))
10237 (setq sum (+ (lsh sum (car shift-xor)) val))
10238 (when (> eat 0) (setq eat (- eat 1)))
10239 (cond
10240 ((= 0 eat) ;multi byte
10241 (setq ret (concat ret (char-to-string sum)))
10242 (setq sum 0))
10243 ((not bytes) ; single byte(s)
10244 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10245 ret)))
10247 (defun org-link-unescape-single-byte-sequence (hex)
10248 "Unhexify hex-encoded single byte character sequences."
10249 (mapconcat (lambda (byte)
10250 (char-to-string (string-to-number byte 16)))
10251 (cdr (split-string hex "%")) ""))
10253 (defun org-xor (a b)
10254 "Exclusive or."
10255 (if a (not b) b))
10257 (defun org-fixup-message-id-for-http (s)
10258 "Replace special characters in a message id, so it can be used in an http query."
10259 (when (string-match "%" s)
10260 (setq s (mapconcat (lambda (c)
10261 (if (eq c ?%)
10262 "%25"
10263 (char-to-string c)))
10264 s "")))
10265 (while (string-match "<" s)
10266 (setq s (replace-match "%3C" t t s)))
10267 (while (string-match ">" s)
10268 (setq s (replace-match "%3E" t t s)))
10269 (while (string-match "@" s)
10270 (setq s (replace-match "%40" t t s)))
10273 (defun org-link-prettify (link)
10274 "Return a human-readable representation of LINK.
10275 The car of LINK must be a raw link.
10276 The cdr of LINK must be either a link description or nil."
10277 (let ((desc (or (cadr link) "<no description>")))
10278 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10279 "<" (car link) ">")))
10281 ;;;###autoload
10282 (defun org-insert-link-global ()
10283 "Insert a link like Org mode does.
10284 This command can be called in any mode to insert a link in Org syntax."
10285 (interactive)
10286 (org-load-modules-maybe)
10287 (org-run-like-in-org-mode 'org-insert-link))
10289 (defun org-insert-all-links (arg &optional pre post)
10290 "Insert all links in `org-stored-links'.
10291 When a universal prefix, do not delete the links from `org-stored-links'.
10292 When `ARG' is a number, insert the last N link(s).
10293 `PRE' and `POST' are optional arguments to define a string to
10294 prepend or to append."
10295 (interactive "P")
10296 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10297 (links (copy-sequence org-stored-links))
10298 (pr (or pre "- "))
10299 (po (or post "\n"))
10300 (cnt 1) l)
10301 (if (null org-stored-links)
10302 (message "No link to insert")
10303 (while (and (or (listp arg) (>= arg cnt))
10304 (setq l (if (listp arg)
10305 (pop links)
10306 (pop org-stored-links))))
10307 (setq cnt (1+ cnt))
10308 (insert pr)
10309 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10310 (insert po)))))
10312 (defun org-insert-last-stored-link (arg)
10313 "Insert the last link stored in `org-stored-links'."
10314 (interactive "p")
10315 (org-insert-all-links arg "" "\n"))
10317 (defun org-link-fontify-links-to-this-file ()
10318 "Fontify links to the current file in `org-stored-links'."
10319 (let ((f (buffer-file-name)) a b)
10320 (setq a (mapcar (lambda(l)
10321 (let ((ll (car l)))
10322 (when (and (string-match "^file:\\(.+\\)::" ll)
10323 (equal f (expand-file-name (match-string 1 ll))))
10324 ll)))
10325 org-stored-links))
10326 (when (featurep 'org-id)
10327 (setq b (mapcar (lambda(l)
10328 (let ((ll (car l)))
10329 (when (and (string-match "^id:\\(.+\\)$" ll)
10330 (equal f (expand-file-name
10331 (or (org-id-find-id-file
10332 (match-string 1 ll)) ""))))
10333 ll)))
10334 org-stored-links)))
10335 (mapcar (lambda(l)
10336 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10337 (delq nil (append a b)))))
10339 (defvar org--links-history nil)
10340 (defun org-insert-link (&optional complete-file link-location default-description)
10341 "Insert a link. At the prompt, enter the link.
10343 Completion can be used to insert any of the link protocol prefixes in use.
10345 The history can be used to select a link previously stored with
10346 `org-store-link'. When the empty string is entered (i.e. if you just
10347 press `RET' at the prompt), the link defaults to the most recently
10348 stored link. As `SPC' triggers completion in the minibuffer, you need to
10349 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10351 You will also be prompted for a description, and if one is given, it will
10352 be displayed in the buffer instead of the link.
10354 If there is already a link at point, this command will allow you to edit
10355 link and description parts.
10357 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10358 file name can be
10359 selected using completion. The path to the file will be relative to the
10360 current directory if the file is in the current directory or a subdirectory.
10361 Otherwise, the link will be the absolute path as completed in the minibuffer
10362 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10363 option `org-link-file-path-type'.
10365 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10366 absolute path even if the file is in
10367 the current directory or below.
10369 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10370 prefix negates `org-keep-stored-link-after-insertion'.
10372 If `org-make-link-description-function' is non-nil, this function will be
10373 called with the link target, and the result will be the default
10374 link description.
10376 If the LINK-LOCATION parameter is non-nil, this value will be used as
10377 the link location instead of reading one interactively.
10379 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10380 as the default description."
10381 (interactive "P")
10382 (let* ((wcf (current-window-configuration))
10383 (origbuf (current-buffer))
10384 (region (when (org-region-active-p)
10385 (buffer-substring (region-beginning) (region-end))))
10386 (remove (and region (list (region-beginning) (region-end))))
10387 (desc region)
10388 (link link-location)
10389 (abbrevs org-link-abbrev-alist-local)
10390 entry all-prefixes auto-desc)
10391 (cond
10392 (link-location) ; specified by arg, just use it.
10393 ((org-in-regexp org-bracket-link-regexp 1)
10394 ;; We do have a link at point, and we are going to edit it.
10395 (setq remove (list (match-beginning 0) (match-end 0)))
10396 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10397 (setq link (read-string "Link: "
10398 (org-link-unescape
10399 (match-string-no-properties 1)))))
10400 ((or (org-in-regexp org-angle-link-re)
10401 (org-in-regexp org-plain-link-re))
10402 ;; Convert to bracket link
10403 (setq remove (list (match-beginning 0) (match-end 0))
10404 link (read-string "Link: "
10405 (org-unbracket-string "<" ">" (match-string 0)))))
10406 ((member complete-file '((4) (16)))
10407 ;; Completing read for file names.
10408 (setq link (org-file-complete-link complete-file)))
10410 ;; Read link, with completion for stored links.
10411 (org-link-fontify-links-to-this-file)
10412 (org-switch-to-buffer-other-window "*Org Links*")
10413 (with-current-buffer "*Org Links*"
10414 (erase-buffer)
10415 (insert "Insert a link.
10416 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10417 (when org-stored-links
10418 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10419 (insert (mapconcat 'org-link-prettify
10420 (reverse org-stored-links) "\n")))
10421 (goto-char (point-min)))
10422 (let ((cw (selected-window)))
10423 (select-window (get-buffer-window "*Org Links*" 'visible))
10424 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10425 (unless (pos-visible-in-window-p (point-max))
10426 (org-fit-window-to-buffer))
10427 (and (window-live-p cw) (select-window cw)))
10428 (setq all-prefixes (append (mapcar 'car abbrevs)
10429 (mapcar 'car org-link-abbrev-alist)
10430 (org-link-types)))
10431 (unwind-protect
10432 ;; Fake a link history, containing the stored links.
10433 (let ((org--links-history
10434 (append (mapcar #'car org-stored-links)
10435 org-insert-link-history)))
10436 (setq link
10437 (org-completing-read
10438 "Link: "
10439 (append
10440 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10441 (mapcar #'car org-stored-links))
10442 nil nil nil
10443 'org--links-history
10444 (caar org-stored-links)))
10445 (unless (org-string-nw-p link) (user-error "No link selected"))
10446 (dolist (l org-stored-links)
10447 (when (equal link (cadr l))
10448 (setq link (car l))
10449 (setq auto-desc t)))
10450 (when (or (member link all-prefixes)
10451 (and (equal ":" (substring link -1))
10452 (member (substring link 0 -1) all-prefixes)
10453 (setq link (substring link 0 -1))))
10454 (setq link (with-current-buffer origbuf
10455 (org-link-try-special-completion link)))))
10456 (set-window-configuration wcf)
10457 (kill-buffer "*Org Links*"))
10458 (setq entry (assoc link org-stored-links))
10459 (or entry (push link org-insert-link-history))
10460 (setq desc (or desc (nth 1 entry)))))
10462 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10463 (not org-keep-stored-link-after-insertion))
10464 (setq org-stored-links (delq (assoc link org-stored-links)
10465 org-stored-links)))
10467 (when (and (string-match org-plain-link-re link)
10468 (not (string-match org-ts-regexp link)))
10469 ;; URL-like link, normalize the use of angular brackets.
10470 (setq link (org-unbracket-string "<" ">" link)))
10472 ;; Check if we are linking to the current file with a search
10473 ;; option If yes, simplify the link by using only the search
10474 ;; option.
10475 (when (and buffer-file-name
10476 (let ((case-fold-search nil))
10477 (string-match "\\`file:\\(.+?\\)::" link)))
10478 (let ((path (match-string-no-properties 1 link))
10479 (search (substring-no-properties link (match-end 0))))
10480 (save-match-data
10481 (when (equal (file-truename buffer-file-name) (file-truename path))
10482 ;; We are linking to this same file, with a search option
10483 (setq link search)))))
10485 ;; Check if we can/should use a relative path. If yes, simplify the link
10486 (let ((case-fold-search nil))
10487 (when (string-match "\\`\\(file\\|docview\\):" link)
10488 (let* ((type (match-string-no-properties 0 link))
10489 (path (substring-no-properties link (match-end 0)))
10490 (origpath path))
10491 (cond
10492 ((or (eq org-link-file-path-type 'absolute)
10493 (equal complete-file '(16)))
10494 (setq path (abbreviate-file-name (expand-file-name path))))
10495 ((eq org-link-file-path-type 'noabbrev)
10496 (setq path (expand-file-name path)))
10497 ((eq org-link-file-path-type 'relative)
10498 (setq path (file-relative-name path)))
10500 (save-match-data
10501 (if (string-match (concat "^" (regexp-quote
10502 (expand-file-name
10503 (file-name-as-directory
10504 default-directory))))
10505 (expand-file-name path))
10506 ;; We are linking a file with relative path name.
10507 (setq path (substring (expand-file-name path)
10508 (match-end 0)))
10509 (setq path (abbreviate-file-name (expand-file-name path)))))))
10510 (setq link (concat type path))
10511 (when (equal desc origpath)
10512 (setq desc path)))))
10514 (if org-make-link-description-function
10515 (setq desc
10516 (or (condition-case nil
10517 (funcall org-make-link-description-function link desc)
10518 (error (progn (message "Can't get link description from `%s'"
10519 (symbol-name org-make-link-description-function))
10520 (sit-for 2) nil)))
10521 (read-string "Description: " default-description)))
10522 (if default-description (setq desc default-description)
10523 (setq desc (or (and auto-desc desc)
10524 (read-string "Description: " desc)))))
10526 (unless (string-match "\\S-" desc) (setq desc nil))
10527 (when remove (apply 'delete-region remove))
10528 (insert (org-make-link-string link desc))
10529 ;; Redisplay so as the new link has proper invisible characters.
10530 (sit-for 0)))
10532 (defun org-link-try-special-completion (type)
10533 "If there is completion support for link type TYPE, offer it."
10534 (let ((fun (org-link-get-parameter type :complete)))
10535 (if (functionp fun)
10536 (funcall fun)
10537 (read-string "Link (no completion support): " (concat type ":")))))
10539 (defun org-file-complete-link (&optional arg)
10540 "Create a file link using completion."
10541 (let ((file (read-file-name "File: "))
10542 (pwd (file-name-as-directory (expand-file-name ".")))
10543 (pwd1 (file-name-as-directory (abbreviate-file-name
10544 (expand-file-name ".")))))
10545 (cond ((equal arg '(16))
10546 (concat "file:"
10547 (abbreviate-file-name (expand-file-name file))))
10548 ((string-match
10549 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10550 (concat "file:" (match-string 1 file)))
10551 ((string-match
10552 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10553 (expand-file-name file))
10554 (concat "file:"
10555 (match-string 1 (expand-file-name file))))
10556 (t (concat "file:" file)))))
10558 (defun org-completing-read (&rest args)
10559 "Completing-read with SPACE being a normal character."
10560 (let ((enable-recursive-minibuffers t)
10561 (minibuffer-local-completion-map
10562 (copy-keymap minibuffer-local-completion-map)))
10563 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10564 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10565 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10566 'org-time-stamp-inactive)
10567 (apply #'completing-read args)))
10569 ;;; Opening/following a link
10571 (defvar org-link-search-failed nil)
10573 (defvar org-open-link-functions nil
10574 "Hook for functions finding a plain text link.
10575 These functions must take a single argument, the link content.
10576 They will be called for links that look like [[link text][description]]
10577 when LINK TEXT does not have a protocol like \"http:\" and does not look
10578 like a filename (e.g. \"./blue.png\").
10580 These functions will be called *before* Org attempts to resolve the
10581 link by doing text searches in the current buffer - so if you want a
10582 link \"[[target]]\" to still find \"<<target>>\", your function should
10583 handle this as a special case.
10585 When the function does handle the link, it must return a non-nil value.
10586 If it decides that it is not responsible for this link, it must return
10587 nil to indicate that that Org can continue with other options like
10588 exact and fuzzy text search.")
10590 (defun org-next-link (&optional search-backward)
10591 "Move forward to the next link.
10592 If the link is in hidden text, expose it."
10593 (interactive "P")
10594 (when (and org-link-search-failed (eq this-command last-command))
10595 (goto-char (point-min))
10596 (message "Link search wrapped back to beginning of buffer"))
10597 (setq org-link-search-failed nil)
10598 (let* ((pos (point))
10599 (ct (org-context))
10600 (a (assq :link ct))
10601 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10602 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10603 ((looking-at org-any-link-re)
10604 ;; Don't stay stuck at link without an org-link face
10605 (forward-char (if search-backward -1 1))))
10606 (if (funcall srch-fun org-any-link-re nil t)
10607 (progn
10608 (goto-char (match-beginning 0))
10609 (when (org-invisible-p) (org-show-context)))
10610 (goto-char pos)
10611 (setq org-link-search-failed t)
10612 (message "No further link found"))))
10614 (defun org-previous-link ()
10615 "Move backward to the previous link.
10616 If the link is in hidden text, expose it."
10617 (interactive)
10618 (funcall 'org-next-link t))
10620 (defun org-translate-link (s)
10621 "Translate a link string if a translation function has been defined."
10622 (with-temp-buffer
10623 (insert (org-trim s))
10624 (org-trim (org-element-interpret-data (org-element-context)))))
10626 (defun org-translate-link-from-planner (type path)
10627 "Translate a link from Emacs Planner syntax so that Org can follow it.
10628 This is still an experimental function, your mileage may vary."
10629 (cond
10630 ((member type '("http" "https" "news" "ftp"))
10631 ;; standard Internet links are the same.
10632 nil)
10633 ((and (equal type "irc") (string-match "^//" path))
10634 ;; Planner has two / at the beginning of an irc link, we have 1.
10635 ;; We should have zero, actually....
10636 (setq path (substring path 1)))
10637 ((and (equal type "lisp") (string-match "^/" path))
10638 ;; Planner has a slash, we do not.
10639 (setq type "elisp" path (substring path 1)))
10640 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10641 ;; A typical message link. Planner has the id after the final slash,
10642 ;; we separate it with a hash mark
10643 (setq path (concat (match-string 1 path) "#"
10644 (org-unbracket-string "<" ">" (match-string 2 path))))))
10645 (cons type path))
10647 (defun org-find-file-at-mouse (ev)
10648 "Open file link or URL at mouse."
10649 (interactive "e")
10650 (mouse-set-point ev)
10651 (org-open-at-point 'in-emacs))
10653 (defun org-open-at-mouse (ev)
10654 "Open file link or URL at mouse.
10655 See the docstring of `org-open-file' for details."
10656 (interactive "e")
10657 (mouse-set-point ev)
10658 (when (eq major-mode 'org-agenda-mode)
10659 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10660 (org-open-at-point))
10662 (defvar org-window-config-before-follow-link nil
10663 "The window configuration before following a link.
10664 This is saved in case the need arises to restore it.")
10666 ;;;###autoload
10667 (defun org-open-at-point-global ()
10668 "Follow a link or time-stamp like Org mode does.
10669 This command can be called in any mode to follow an external link
10670 or a time-stamp that has Org mode syntax. Its behavior is
10671 undefined when called on internal links (e.g., fuzzy links).
10672 Raise an error when there is nothing to follow. "
10673 (interactive)
10674 (cond ((org-in-regexp org-any-link-re)
10675 (org-open-link-from-string (match-string-no-properties 0)))
10676 ((or (org-in-regexp org-ts-regexp-both nil t)
10677 (org-in-regexp org-tsr-regexp-both nil t))
10678 (org-follow-timestamp-link))
10679 (t (user-error "No link found"))))
10681 ;;;###autoload
10682 (defun org-open-link-from-string (s &optional arg reference-buffer)
10683 "Open a link in the string S, as if it was in Org mode."
10684 (interactive "sLink: \nP")
10685 (let ((reference-buffer (or reference-buffer (current-buffer))))
10686 (with-temp-buffer
10687 (let ((org-inhibit-startup (not reference-buffer)))
10688 (org-mode)
10689 (insert s)
10690 (goto-char (point-min))
10691 (when reference-buffer
10692 (setq org-link-abbrev-alist-local
10693 (with-current-buffer reference-buffer
10694 org-link-abbrev-alist-local)))
10695 (org-open-at-point arg reference-buffer)))))
10697 (defvar org-open-at-point-functions nil
10698 "Hook that is run when following a link at point.
10700 Functions in this hook must return t if they identify and follow
10701 a link at point. If they don't find anything interesting at point,
10702 they must return nil.")
10704 (defvar org-link-search-inhibit-query nil)
10705 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10706 (defun org--open-doi-link (path)
10707 "Open a \"doi\" type link.
10708 PATH is a the path to search for, as a string."
10709 (browse-url (url-encode-url (concat org-doi-server-url path))))
10711 (defun org--open-elisp-link (path)
10712 "Open a \"elisp\" type link.
10713 PATH is the sexp to evaluate, as a string."
10714 (let ((cmd path))
10715 (if (or (and (org-string-nw-p
10716 org-confirm-elisp-link-not-regexp)
10717 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10718 (not org-confirm-elisp-link-function)
10719 (funcall org-confirm-elisp-link-function
10720 (format "Execute \"%s\" as elisp? "
10721 (org-add-props cmd nil 'face 'org-warning))))
10722 (message "%s => %s" cmd
10723 (if (eq (string-to-char cmd) ?\()
10724 (eval (read cmd))
10725 (call-interactively (read cmd))))
10726 (user-error "Abort"))))
10728 (defun org--open-help-link (path)
10729 "Open a \"help\" type link.
10730 PATH is a symbol name, as a string."
10731 (pcase (intern path)
10732 ((and (pred fboundp) variable) (describe-function variable))
10733 ((and (pred boundp) function) (describe-variable function))
10734 (name (user-error "Unknown function or variable: %s" name))))
10736 (defun org--open-shell-link (path)
10737 "Open a \"shell\" type link.
10738 PATH is the command to execute, as a string."
10739 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10740 (cmd path))
10741 (if (or (and (org-string-nw-p
10742 org-confirm-shell-link-not-regexp)
10743 (string-match
10744 org-confirm-shell-link-not-regexp cmd))
10745 (not org-confirm-shell-link-function)
10746 (funcall org-confirm-shell-link-function
10747 (format "Execute \"%s\" in shell? "
10748 (org-add-props cmd nil
10749 'face 'org-warning))))
10750 (progn
10751 (message "Executing %s" cmd)
10752 (shell-command cmd buf)
10753 (when (featurep 'midnight)
10754 (setq clean-buffer-list-kill-buffer-names
10755 (cons (buffer-name buf)
10756 clean-buffer-list-kill-buffer-names))))
10757 (user-error "Abort"))))
10759 (defun org-open-at-point (&optional arg reference-buffer)
10760 "Open link, timestamp, footnote or tags at point.
10762 When point is on a link, follow it. Normally, files will be
10763 opened by an appropriate application. If the optional prefix
10764 argument ARG is non-nil, Emacs will visit the file. With
10765 a double prefix argument, try to open outside of Emacs, in the
10766 application the system uses for this file type.
10768 When point is on a timestamp, open the agenda at the day
10769 specified.
10771 When point is a footnote definition, move to the first reference
10772 found. If it is on a reference, move to the associated
10773 definition.
10775 When point is on a headline, display a list of every link in the
10776 entry, so it is possible to pick one, or all, of them. If point
10777 is on a tag, call `org-tags-view' instead.
10779 When optional argument REFERENCE-BUFFER is non-nil, it should
10780 specify a buffer from where the link search should happen. This
10781 is used internally by `org-open-link-from-string'.
10783 On top of syntactically correct links, this function will open
10784 the link at point in comments or comment blocks and the first
10785 link in a property drawer line."
10786 (interactive "P")
10787 ;; On a code block, open block's results.
10788 (unless (call-interactively 'org-babel-open-src-block-result)
10789 (org-load-modules-maybe)
10790 (setq org-window-config-before-follow-link (current-window-configuration))
10791 (org-remove-occur-highlights nil nil t)
10792 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10793 (let* ((context
10794 ;; Only consider supported types, even if they are not
10795 ;; the closest one.
10796 (org-element-lineage
10797 (org-element-context)
10798 '(clock comment comment-block footnote-definition
10799 footnote-reference headline inlinetask keyword link
10800 node-property timestamp)
10802 (type (org-element-type context))
10803 (value (org-element-property :value context)))
10804 (cond
10805 ((not context) (user-error "No link found"))
10806 ;; Exception: open timestamps and links in properties
10807 ;; drawers, keywords and comments.
10808 ((memq type '(comment comment-block keyword node-property))
10809 (call-interactively #'org-open-at-point-global))
10810 ;; On a headline or an inlinetask, but not on a timestamp,
10811 ;; a link, a footnote reference or on tags.
10812 ((and (memq type '(headline inlinetask))
10813 ;; Not on tags.
10814 (let ((case-fold-search nil))
10815 (save-excursion
10816 (beginning-of-line)
10817 (looking-at org-complex-heading-regexp))
10818 (or (not (match-beginning 5))
10819 (< (point) (match-beginning 5)))))
10820 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10821 (links (car data))
10822 (links-end (cdr data)))
10823 (if links
10824 (dolist (link (if (stringp links) (list links) links))
10825 (search-forward link nil links-end)
10826 (goto-char (match-beginning 0))
10827 (org-open-at-point))
10828 (require 'org-attach)
10829 (org-attach-reveal 'if-exists))))
10830 ;; On a clock line, make sure point is on the timestamp
10831 ;; before opening it.
10832 ((and (eq type 'clock)
10833 value
10834 (>= (point) (org-element-property :begin value))
10835 (<= (point) (org-element-property :end value)))
10836 (org-follow-timestamp-link))
10837 ;; Do nothing on white spaces after an object.
10838 ((>= (point)
10839 (save-excursion
10840 (goto-char (org-element-property :end context))
10841 (skip-chars-backward " \t")
10842 (point)))
10843 (user-error "No link found"))
10844 ((eq type 'timestamp) (org-follow-timestamp-link))
10845 ;; On tags within a headline or an inlinetask.
10846 ((and (memq type '(headline inlinetask))
10847 (let ((case-fold-search nil))
10848 (save-excursion (beginning-of-line)
10849 (looking-at org-complex-heading-regexp))
10850 (and (match-beginning 5)
10851 (>= (point) (match-beginning 5)))))
10852 (org-tags-view arg (substring (match-string 5) 0 -1)))
10853 ((eq type 'link)
10854 ;; When link is located within the description of another
10855 ;; link (e.g., an inline image), always open the parent
10856 ;; link.
10857 (let* ((link (let ((up (org-element-property :parent context)))
10858 (if (eq (org-element-type up) 'link) up context)))
10859 (type (org-element-property :type link))
10860 (path (org-link-unescape (org-element-property :path link))))
10861 ;; Switch back to REFERENCE-BUFFER needed when called in
10862 ;; a temporary buffer through `org-open-link-from-string'.
10863 (with-current-buffer (or reference-buffer (current-buffer))
10864 (cond
10865 ((equal type "file")
10866 (if (string-match "[*?{]" (file-name-nondirectory path))
10867 (dired path)
10868 ;; Look into `org-link-parameters' in order to find
10869 ;; a DEDICATED-FUNCTION to open file. The function
10870 ;; will be applied on raw link instead of parsed
10871 ;; link due to the limitation in `org-add-link-type'
10872 ;; ("open" function called with a single argument).
10873 ;; If no such function is found, fallback to
10874 ;; `org-open-file'.
10875 (let* ((option (org-element-property :search-option link))
10876 (app (org-element-property :application link))
10877 (dedicated-function
10878 (org-link-get-parameter
10879 (if app (concat type "+" app) type)
10880 :follow)))
10881 (if dedicated-function
10882 (funcall dedicated-function
10883 (concat path
10884 (and option (concat "::" option))))
10885 (apply #'org-open-file
10886 path
10887 (cond (arg)
10888 ((equal app "emacs") 'emacs)
10889 ((equal app "sys") 'system))
10890 (cond ((not option) nil)
10891 ((string-match-p "\\`[0-9]+\\'" option)
10892 (list (string-to-number option)))
10893 (t (list nil
10894 (org-link-unescape option)))))))))
10895 ((functionp (org-link-get-parameter type :follow))
10896 (funcall (org-link-get-parameter type :follow) path))
10897 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10898 (unless (run-hook-with-args-until-success
10899 'org-open-link-functions path)
10900 (if (not arg) (org-mark-ring-push)
10901 (switch-to-buffer-other-window
10902 (org-get-buffer-for-internal-link (current-buffer))))
10903 (let ((destination
10904 (org-with-wide-buffer
10905 (if (equal type "radio")
10906 (org-search-radio-target
10907 (org-element-property :path link))
10908 (org-link-search
10909 (if (member type '("custom-id" "coderef"))
10910 (org-element-property :raw-link link)
10911 path)
10912 ;; Prevent fuzzy links from matching
10913 ;; themselves.
10914 (and (equal type "fuzzy")
10915 (+ 2 (org-element-property :begin link)))))
10916 (point))))
10917 (unless (and (<= (point-min) destination)
10918 (>= (point-max) destination))
10919 (widen))
10920 (goto-char destination))))
10921 (t (browse-url-at-point))))))
10922 ;; On a footnote reference or at a footnote definition's label.
10923 ((or (eq type 'footnote-reference)
10924 (and (eq type 'footnote-definition)
10925 (save-excursion
10926 ;; Do not validate action when point is on the
10927 ;; spaces right after the footnote label, in
10928 ;; order to be on par with behaviour on links.
10929 (skip-chars-forward " \t")
10930 (let ((begin
10931 (org-element-property :contents-begin context)))
10932 (if begin (< (point) begin)
10933 (= (org-element-property :post-affiliated context)
10934 (line-beginning-position)))))))
10935 (org-footnote-action))
10936 (t (user-error "No link found")))))
10937 (run-hook-with-args 'org-follow-link-hook)))
10939 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10940 "Offer links in the current entry and return the selected link.
10941 If there is only one link, return it.
10942 If NTH is an integer, return the NTH link found.
10943 If ZERO is a string, check also this string for a link, and if
10944 there is one, return it."
10945 (with-current-buffer buffer
10946 (org-with-wide-buffer
10947 (goto-char marker)
10948 (let ((cnt ?0)
10949 have-zero end links link c)
10950 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10951 (push (match-string 0 zero) links)
10952 (setq cnt (1- cnt) have-zero t))
10953 (save-excursion
10954 (org-back-to-heading t)
10955 (setq end (save-excursion (outline-next-heading) (point)))
10956 (while (re-search-forward org-any-link-re end t)
10957 (push (match-string 0) links))
10958 (setq links (org-uniquify (reverse links))))
10959 (cond
10960 ((null links)
10961 (message "No links"))
10962 ((equal (length links) 1)
10963 (setq link (car links)))
10964 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10965 (setq link (nth (if have-zero nth (1- nth)) links)))
10966 (t ; we have to select a link
10967 (save-excursion
10968 (save-window-excursion
10969 (delete-other-windows)
10970 (with-output-to-temp-buffer "*Select Link*"
10971 (dolist (l links)
10972 (cond
10973 ((not (string-match org-bracket-link-regexp l))
10974 (princ (format "[%c] %s\n" (cl-incf cnt)
10975 (org-unbracket-string "<" ">" l))))
10976 ((match-end 3)
10977 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10978 (match-string 3 l) (match-string 1 l))))
10979 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10980 (match-string 1 l)))))))
10981 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10982 (message "Select link to open, RET to open all:")
10983 (setq c (read-char-exclusive))
10984 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10985 (when (equal c ?q) (user-error "Abort"))
10986 (if (equal c ?\C-m)
10987 (setq link links)
10988 (setq nth (- c ?0))
10989 (when have-zero (setq nth (1+ nth)))
10990 (unless (and (integerp nth) (>= (length links) nth))
10991 (user-error "Invalid link selection"))
10992 (setq link (nth (1- nth) links)))))
10993 (cons link end)))))
10995 ;; TODO: These functions are deprecated since `org-open-at-point'
10996 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10997 (defun org-open-file-with-system (path)
10998 "Open file at PATH using the system way of opening it."
10999 (org-open-file path 'system))
11000 (defun org-open-file-with-emacs (path)
11001 "Open file at PATH in Emacs."
11002 (org-open-file path 'emacs))
11005 ;;; File search
11007 (defvar org-create-file-search-functions nil
11008 "List of functions to construct the right search string for a file link.
11009 These functions are called in turn with point at the location to
11010 which the link should point.
11012 A function in the hook should first test if it would like to
11013 handle this file type, for example by checking the `major-mode'
11014 or the file extension. If it decides not to handle this file, it
11015 should just return nil to give other functions a chance. If it
11016 does handle the file, it must return the search string to be used
11017 when following the link. The search string will be part of the
11018 file link, given after a double colon, and `org-open-at-point'
11019 will automatically search for it. If special measures must be
11020 taken to make the search successful, another function should be
11021 added to the companion hook `org-execute-file-search-functions',
11022 which see.
11024 A function in this hook may also use `setq' to set the variable
11025 `description' to provide a suggestion for the descriptive text to
11026 be used for this link when it gets inserted into an Org buffer
11027 with \\[org-insert-link].")
11029 (defvar org-execute-file-search-functions nil
11030 "List of functions to execute a file search triggered by a link.
11032 Functions added to this hook must accept a single argument, the
11033 search string that was part of the file link, the part after the
11034 double colon. The function must first check if it would like to
11035 handle this search, for example by checking the `major-mode' or
11036 the file extension. If it decides not to handle this search, it
11037 should just return nil to give other functions a chance. If it
11038 does handle the search, it must return a non-nil value to keep
11039 other functions from trying.
11041 Each function can access the current prefix argument through the
11042 variable `current-prefix-arg'. Note that a single prefix is used
11043 to force opening a link in Emacs, so it may be good to only use a
11044 numeric or double prefix to guide the search function.
11046 In case this is needed, a function in this hook can also restore
11047 the window configuration before `org-open-at-point' was called using:
11049 (set-window-configuration org-window-config-before-follow-link)")
11051 (defun org-search-radio-target (target)
11052 "Search a radio target matching TARGET in current buffer.
11053 White spaces are not significant."
11054 (let ((re (format "<<<%s>>>"
11055 (mapconcat #'regexp-quote
11056 (org-split-string target "[ \t\n]+")
11057 "[ \t]+\\(?:\n[ \t]*\\)?")))
11058 (origin (point)))
11059 (goto-char (point-min))
11060 (catch :radio-match
11061 (while (re-search-forward re nil t)
11062 (backward-char)
11063 (let ((object (org-element-context)))
11064 (when (eq (org-element-type object) 'radio-target)
11065 (goto-char (org-element-property :begin object))
11066 (org-show-context 'link-search)
11067 (throw :radio-match nil))))
11068 (goto-char origin)
11069 (user-error "No match for radio target: %s" target))))
11071 (defun org-link-search (s &optional avoid-pos stealth)
11072 "Search for a search string S.
11074 If S starts with \"#\", it triggers a custom ID search.
11076 If S is enclosed within parenthesis, it initiates a coderef
11077 search.
11079 If S is surrounded by forward slashes, it is interpreted as
11080 a regular expression. In Org mode files, this will create an
11081 `org-occur' sparse tree. In ordinary files, `occur' will be used
11082 to list matches. If the current buffer is in `dired-mode', grep
11083 will be used to search in all files.
11085 When AVOID-POS is given, ignore matches near that position.
11087 When optional argument STEALTH is non-nil, do not modify
11088 visibility around point, thus ignoring `org-show-context-detail'
11089 variable.
11091 Search is case-insensitive and ignores white spaces. Return type
11092 of matched result, which is either `dedicated' or `fuzzy'."
11093 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11094 (let* ((case-fold-search t)
11095 (origin (point))
11096 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11097 (starred (eq (string-to-char normalized) ?*))
11098 (words (split-string (if starred (substring s 1) s)))
11099 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
11100 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11101 type)
11102 (cond
11103 ;; Check if there are any special search functions.
11104 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11105 ((eq (string-to-char s) ?#)
11106 ;; Look for a custom ID S if S starts with "#".
11107 (let* ((id (substring normalized 1))
11108 (match (org-find-property "CUSTOM_ID" id)))
11109 (if match (progn (goto-char match) (setf type 'dedicated))
11110 (error "No match for custom ID: %s" id))))
11111 ((string-match "\\`(\\(.*\\))\\'" normalized)
11112 ;; Look for coderef targets if S is enclosed within parenthesis.
11113 (let ((coderef (match-string-no-properties 1 normalized))
11114 (re (substring s-single-re 1 -1)))
11115 (goto-char (point-min))
11116 (catch :coderef-match
11117 (while (re-search-forward re nil t)
11118 (let ((element (org-element-at-point)))
11119 (when (and (memq (org-element-type element)
11120 '(example-block src-block))
11121 ;; Build proper regexp according to current
11122 ;; block's label format.
11123 (let ((label-fmt
11124 (regexp-quote
11125 (or (org-element-property :label-fmt element)
11126 org-coderef-label-format))))
11127 (save-excursion
11128 (beginning-of-line)
11129 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11130 (format label-fmt coderef))))))
11131 (setq type 'dedicated)
11132 (goto-char (match-beginning 1))
11133 (throw :coderef-match nil))))
11134 (goto-char origin)
11135 (error "No match for coderef: %s" coderef))))
11136 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11137 ;; Look for a regular expression.
11138 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11139 (match-string 1 s)))
11140 ;; From here, we handle fuzzy links.
11142 ;; Look for targets, only if not in a headline search.
11143 ((and (not starred)
11144 (let ((target (format "<<%s>>" s-multi-re)))
11145 (catch :target-match
11146 (goto-char (point-min))
11147 (while (re-search-forward target nil t)
11148 (backward-char)
11149 (let ((context (org-element-context)))
11150 (when (eq (org-element-type context) 'target)
11151 (setq type 'dedicated)
11152 (goto-char (org-element-property :begin context))
11153 (throw :target-match t))))
11154 nil))))
11155 ;; Look for elements named after S, only if not in a headline
11156 ;; search.
11157 ((and (not starred)
11158 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11159 (catch :name-match
11160 (goto-char (point-min))
11161 (while (re-search-forward name nil t)
11162 (let ((element (org-element-at-point)))
11163 (when (equal words
11164 (split-string
11165 (org-element-property :name element)))
11166 (setq type 'dedicated)
11167 (beginning-of-line)
11168 (throw :name-match t))))
11169 nil))))
11170 ;; Regular text search. Prefer headlines in Org mode buffers.
11171 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
11172 ;; statistics cookies and tags.
11173 ((and (derived-mode-p 'org-mode)
11174 (let ((title-re
11175 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
11176 org-outline-regexp-bol
11177 org-comment-string
11178 (mapconcat #'regexp-quote words ".+")))
11179 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
11180 (comment-re (format "\\`%s[ \t]+" org-comment-string)))
11181 (goto-char (point-min))
11182 (catch :found
11183 (while (re-search-forward title-re nil t)
11184 (when (equal words
11185 (split-string
11186 (replace-regexp-in-string
11187 cookie-re ""
11188 (replace-regexp-in-string
11189 comment-re "" (org-get-heading t t)))))
11190 (throw :found t)))
11191 nil)))
11192 (beginning-of-line)
11193 (setq type 'dedicated))
11194 ;; Offer to create non-existent headline depending on
11195 ;; `org-link-search-must-match-exact-headline'.
11196 ((and (derived-mode-p 'org-mode)
11197 (not org-link-search-inhibit-query)
11198 (eq org-link-search-must-match-exact-headline 'query-to-create)
11199 (yes-or-no-p "No match - create this as a new heading? "))
11200 (goto-char (point-max))
11201 (unless (bolp) (newline))
11202 (org-insert-heading nil t t)
11203 (insert s "\n")
11204 (beginning-of-line 0))
11205 ;; Only headlines are looked after. No need to process
11206 ;; further: throw an error.
11207 ((and (derived-mode-p 'org-mode)
11208 (or starred org-link-search-must-match-exact-headline))
11209 (goto-char origin)
11210 (error "No match for fuzzy expression: %s" normalized))
11211 ;; Regular text search.
11212 ((catch :fuzzy-match
11213 (goto-char (point-min))
11214 (while (re-search-forward s-multi-re nil t)
11215 ;; Skip match if it contains AVOID-POS or it is included in
11216 ;; a link with a description but outside the description.
11217 (unless (or (and avoid-pos
11218 (<= (match-beginning 0) avoid-pos)
11219 (> (match-end 0) avoid-pos))
11220 (and (save-match-data
11221 (org-in-regexp org-bracket-link-regexp))
11222 (match-beginning 3)
11223 (or (> (match-beginning 3) (point))
11224 (<= (match-end 3) (point)))
11225 (org-element-lineage
11226 (save-match-data (org-element-context))
11227 '(link) t)))
11228 (goto-char (match-beginning 0))
11229 (setq type 'fuzzy)
11230 (throw :fuzzy-match t)))
11231 nil))
11232 ;; All failed. Throw an error.
11233 (t (goto-char origin)
11234 (error "No match for fuzzy expression: %s" normalized)))
11235 ;; Disclose surroundings of match, if appropriate.
11236 (when (and (derived-mode-p 'org-mode) (not stealth))
11237 (org-show-context 'link-search))
11238 type))
11240 (defun org-get-buffer-for-internal-link (buffer)
11241 "Return a buffer to be used for displaying the link target of internal links."
11242 (cond
11243 ((not org-display-internal-link-with-indirect-buffer)
11244 buffer)
11245 ((string-suffix-p "(Clone)" (buffer-name buffer))
11246 (message "Buffer is already a clone, not making another one")
11247 ;; we also do not modify visibility in this case
11248 buffer)
11249 (t ; make a new indirect buffer for displaying the link
11250 (let* ((bn (buffer-name buffer))
11251 (ibn (concat bn "(Clone)"))
11252 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11253 (with-current-buffer ib (org-overview))
11254 ib))))
11256 (defun org-do-occur (regexp &optional cleanup)
11257 "Call the Emacs command `occur'.
11258 If CLEANUP is non-nil, remove the printout of the regular expression
11259 in the *Occur* buffer. This is useful if the regex is long and not useful
11260 to read."
11261 (occur regexp)
11262 (when cleanup
11263 (let ((cwin (selected-window)) win beg end)
11264 (when (setq win (get-buffer-window "*Occur*"))
11265 (select-window win))
11266 (goto-char (point-min))
11267 (when (re-search-forward "match[a-z]+" nil t)
11268 (setq beg (match-end 0))
11269 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11270 (setq end (1- (match-beginning 0)))))
11271 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11272 (goto-char (point-min))
11273 (select-window cwin))))
11275 ;;; The mark ring for links jumps
11277 (defvar org-mark-ring nil
11278 "Mark ring for positions before jumps in Org mode.")
11279 (defvar org-mark-ring-last-goto nil
11280 "Last position in the mark ring used to go back.")
11281 ;; Fill and close the ring
11282 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11283 (dotimes (_ org-mark-ring-length)
11284 (push (make-marker) org-mark-ring))
11285 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11286 org-mark-ring)
11288 (defun org-mark-ring-push (&optional pos buffer)
11289 "Put the current position or POS into the mark ring and rotate it."
11290 (interactive)
11291 (setq pos (or pos (point)))
11292 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11293 (move-marker (car org-mark-ring)
11294 (or pos (point))
11295 (or buffer (current-buffer)))
11296 (message "%s"
11297 (substitute-command-keys
11298 "Position saved to mark ring, go back with \
11299 `\\[org-mark-ring-goto]'.")))
11301 (defun org-mark-ring-goto (&optional n)
11302 "Jump to the previous position in the mark ring.
11303 With prefix arg N, jump back that many stored positions. When
11304 called several times in succession, walk through the entire ring.
11305 Org mode commands jumping to a different position in the current file,
11306 or to another Org file, automatically push the old position onto the ring."
11307 (interactive "p")
11308 (let (p m)
11309 (if (eq last-command this-command)
11310 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11311 (setq p org-mark-ring))
11312 (setq org-mark-ring-last-goto p)
11313 (setq m (car p))
11314 (pop-to-buffer-same-window (marker-buffer m))
11315 (goto-char m)
11316 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11318 (defun org-add-angle-brackets (s)
11319 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11320 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11323 ;;; Following specific links
11325 (defvar org-agenda-buffer-tmp-name)
11326 (defvar org-agenda-start-on-weekday)
11327 (defun org-follow-timestamp-link ()
11328 "Open an agenda view for the time-stamp date/range at point."
11329 (cond
11330 ((org-at-date-range-p t)
11331 (let ((org-agenda-start-on-weekday)
11332 (t1 (match-string 1))
11333 (t2 (match-string 2)) tt1 tt2)
11334 (setq tt1 (time-to-days (org-time-string-to-time t1))
11335 tt2 (time-to-days (org-time-string-to-time t2)))
11336 (let ((org-agenda-buffer-tmp-name
11337 (format "*Org Agenda(a:%s)"
11338 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11339 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11340 ((org-at-timestamp-p t)
11341 (let ((org-agenda-buffer-tmp-name
11342 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11343 (org-agenda-list nil (time-to-days (org-time-string-to-time
11344 (substring (match-string 1) 0 10)))
11345 1)))
11346 (t (error "This should not happen"))))
11349 ;;; Following file links
11350 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11351 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11352 (declare-function mailcap-mime-info
11353 "mailcap" (string &optional request no-decode))
11354 (defvar org-wait nil)
11355 (defun org-open-file (path &optional in-emacs line search)
11356 "Open the file at PATH.
11357 First, this expands any special file name abbreviations. Then the
11358 configuration variable `org-file-apps' is checked if it contains an
11359 entry for this file type, and if yes, the corresponding command is launched.
11361 If no application is found, Emacs simply visits the file.
11363 With optional prefix argument IN-EMACS, Emacs will visit the file.
11364 With a double \\[universal-argument] \\[universal-argument] \
11365 prefix arg, Org tries to avoid opening in Emacs
11366 and to use an external application to visit the file.
11368 Optional LINE specifies a line to go to, optional SEARCH a string
11369 to search for. If LINE or SEARCH is given, the file will be
11370 opened in Emacs, unless an entry from org-file-apps that makes
11371 use of groups in a regexp matches.
11373 If you want to change the way frames are used when following a
11374 link, please customize `org-link-frame-setup'.
11376 If the file does not exist, an error is thrown."
11377 (let* ((file (if (equal path "")
11378 buffer-file-name
11379 (substitute-in-file-name (expand-file-name path))))
11380 (file-apps (append org-file-apps (org-default-apps)))
11381 (apps (cl-remove-if
11382 'org-file-apps-entry-match-against-dlink-p file-apps))
11383 (apps-dlink (cl-remove-if-not
11384 'org-file-apps-entry-match-against-dlink-p file-apps))
11385 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11386 (dirp (unless remp (file-directory-p file)))
11387 (file (if (and dirp org-open-directory-means-index-dot-org)
11388 (concat (file-name-as-directory file) "index.org")
11389 file))
11390 (a-m-a-p (assq 'auto-mode apps))
11391 (dfile (downcase file))
11392 ;; Reconstruct the original link from the PATH, LINE and
11393 ;; SEARCH args.
11394 (link (cond (line (concat file "::" (number-to-string line)))
11395 (search (concat file "::" search))
11396 (t file)))
11397 (dlink (downcase link))
11398 (old-buffer (current-buffer))
11399 (old-pos (point))
11400 (old-mode major-mode)
11401 (ext
11402 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11403 (match-string 1 dfile)))
11404 cmd link-match-data)
11405 (cond
11406 ((member in-emacs '((16) system))
11407 (setq cmd (cdr (assq 'system apps))))
11408 (in-emacs (setq cmd 'emacs))
11410 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11411 (and dirp (cdr (assq 'directory apps)))
11412 ;; First, try matching against apps-dlink if we
11413 ;; get a match here, store the match data for
11414 ;; later.
11415 (let ((match (assoc-default dlink apps-dlink
11416 'string-match)))
11417 (if match
11418 (progn (setq link-match-data (match-data))
11419 match)
11420 (progn (setq in-emacs (or in-emacs line search))
11421 nil))) ; if we have no match in apps-dlink,
11422 ; always open the file in emacs if line or search
11423 ; is given (for backwards compatibility)
11424 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11425 'string-match)
11426 (cdr (assoc ext apps))
11427 (cdr (assq t apps))))))
11428 (when (eq cmd 'system)
11429 (setq cmd (cdr (assq 'system apps))))
11430 (when (eq cmd 'default)
11431 (setq cmd (cdr (assoc t apps))))
11432 (when (eq cmd 'mailcap)
11433 (require 'mailcap)
11434 (mailcap-parse-mailcaps)
11435 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11436 (command (mailcap-mime-info mime-type)))
11437 (if (stringp command)
11438 (setq cmd command)
11439 (setq cmd 'emacs))))
11440 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11441 (not (file-exists-p file))
11442 (not org-open-non-existing-files))
11443 (user-error "No such file: %s" file))
11444 (cond
11445 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11446 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11447 (while (string-match "['\"]%s['\"]" cmd)
11448 (setq cmd (replace-match "%s" t t cmd)))
11449 (setq cmd (replace-regexp-in-string
11450 "%s"
11451 (shell-quote-argument (convert-standard-filename file))
11453 nil t))
11455 ;; Replace "%1", "%2" etc. in command with group matches from regex
11456 (save-match-data
11457 (let ((match-index 1)
11458 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11459 (set-match-data link-match-data)
11460 (while (<= match-index number-of-groups)
11461 (let ((regex (concat "%" (number-to-string match-index)))
11462 (replace-with (match-string match-index dlink)))
11463 (while (string-match regex cmd)
11464 (setq cmd (replace-match replace-with t t cmd))))
11465 (setq match-index (+ match-index 1)))))
11467 (save-window-excursion
11468 (message "Running %s...done" cmd)
11469 (start-process-shell-command cmd nil cmd)
11470 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11471 ((or (stringp cmd)
11472 (eq cmd 'emacs))
11473 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11474 (widen)
11475 (cond (line (org-goto-line line)
11476 (when (derived-mode-p 'org-mode) (org-reveal)))
11477 (search (org-link-search search))))
11478 ((functionp cmd)
11479 (save-match-data
11480 (set-match-data link-match-data)
11481 (condition-case nil
11482 (funcall cmd file link)
11483 ;; FIXME: Remove this check when most default installations
11484 ;; of Emacs have at least Org 9.0.
11485 ((debug wrong-number-of-arguments wrong-type-argument
11486 invalid-function)
11487 (user-error "Please see Org News for version 9.0 about \
11488 `org-file-apps'--Lisp error: %S" cmd)))))
11489 ((consp cmd)
11490 ;; FIXME: Remove this check when most default installations of
11491 ;; Emacs have at least Org 9.0.
11492 ;; Heads-up instead of silently fall back to
11493 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11494 ;; with sexp instead of a function for `cmd'.
11495 (user-error "Please see Org News for version 9.0 about \
11496 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11497 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11498 (and (derived-mode-p 'org-mode)
11499 (eq old-mode 'org-mode)
11500 (or (not (eq old-buffer (current-buffer)))
11501 (not (eq old-pos (point))))
11502 (org-mark-ring-push old-pos old-buffer))))
11504 (defun org-file-apps-entry-match-against-dlink-p (entry)
11505 "This function returns non-nil if `entry' uses a regular
11506 expression which should be matched against the whole link by
11507 org-open-file.
11509 It assumes that is the case when the entry uses a regular
11510 expression which has at least one grouping construct and the
11511 action is either a lisp form or a command string containing
11512 `%1', i.e. using at least one subexpression match as a
11513 parameter."
11514 (let ((selector (car entry))
11515 (action (cdr entry)))
11516 (if (stringp selector)
11517 (and (> (regexp-opt-depth selector) 0)
11518 (or (and (stringp action)
11519 (string-match "%[0-9]" action))
11520 (consp action)))
11521 nil)))
11523 (defun org-default-apps ()
11524 "Return the default applications for this operating system."
11525 (cond
11526 ((eq system-type 'darwin)
11527 org-file-apps-defaults-macosx)
11528 ((eq system-type 'windows-nt)
11529 org-file-apps-defaults-windowsnt)
11530 (t org-file-apps-defaults-gnu)))
11532 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11533 "Convert extensions to regular expressions in the cars of LIST.
11534 Also, weed out any non-string entries, because the return value is used
11535 only for regexp matching.
11536 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11537 point to the symbol `emacs', indicating that the file should
11538 be opened in Emacs."
11539 (append
11540 (delq nil
11541 (mapcar (lambda (x)
11542 (unless (not (stringp (car x)))
11543 (if (string-match "\\W" (car x))
11545 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11546 list))
11547 (when add-auto-mode
11548 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11550 (defvar ange-ftp-name-format)
11551 (defun org-file-remote-p (file)
11552 "Test whether FILE specifies a location on a remote system.
11553 Return non-nil if the location is indeed remote.
11555 For example, the filename \"/user@host:/foo\" specifies a location
11556 on the system \"/user@host:\"."
11557 (cond ((fboundp 'file-remote-p)
11558 (file-remote-p file))
11559 ((fboundp 'tramp-handle-file-remote-p)
11560 (tramp-handle-file-remote-p file))
11561 ((and (boundp 'ange-ftp-name-format)
11562 (string-match (car ange-ftp-name-format) file))
11563 t)))
11566 ;;;; Refiling
11568 (defun org-get-org-file ()
11569 "Read a filename, with default directory `org-directory'."
11570 (let ((default (or org-default-notes-file remember-data-file)))
11571 (read-file-name (format "File name [%s]: " default)
11572 (file-name-as-directory org-directory)
11573 default)))
11575 (defun org-notes-order-reversed-p ()
11576 "Check if the current file should receive notes in reversed order."
11577 (cond
11578 ((not org-reverse-note-order) nil)
11579 ((eq t org-reverse-note-order) t)
11580 ((not (listp org-reverse-note-order)) nil)
11581 (t (catch 'exit
11582 (dolist (entry org-reverse-note-order)
11583 (when (string-match (car entry) buffer-file-name)
11584 (throw 'exit (cdr entry))))))))
11586 (defvar org-refile-target-table nil
11587 "The list of refile targets, created by `org-refile'.")
11589 (defvar org-agenda-new-buffers nil
11590 "Buffers created to visit agenda files.")
11592 (defvar org-refile-cache nil
11593 "Cache for refile targets.")
11595 (defvar org-refile-markers nil
11596 "All the markers used for caching refile locations.")
11598 (defun org-refile-marker (pos)
11599 "Get a new refile marker, but only if caching is in use."
11600 (if (not org-refile-use-cache)
11602 (let ((m (make-marker)))
11603 (move-marker m pos)
11604 (push m org-refile-markers)
11605 m)))
11607 (defun org-refile-cache-clear ()
11608 "Clear the refile cache and disable all the markers."
11609 (dolist (m org-refile-markers) (move-marker m nil))
11610 (setq org-refile-markers nil)
11611 (setq org-refile-cache nil)
11612 (message "Refile cache has been cleared"))
11614 (defun org-refile-cache-check-set (set)
11615 "Check if all the markers in the cache still have live buffers."
11616 (let (marker)
11617 (catch 'exit
11618 (while (and set (setq marker (nth 3 (pop set))))
11619 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11620 (when (and marker (null (marker-buffer marker)))
11621 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11622 (sit-for 3)
11623 (throw 'exit nil)))
11624 t)))
11626 (defun org-refile-cache-put (set &rest identifiers)
11627 "Push the refile targets SET into the cache, under IDENTIFIERS."
11628 (let* ((key (sha1 (prin1-to-string identifiers)))
11629 (entry (assoc key org-refile-cache)))
11630 (if entry
11631 (setcdr entry set)
11632 (push (cons key set) org-refile-cache))))
11634 (defun org-refile-cache-get (&rest identifiers)
11635 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11636 (cond
11637 ((not org-refile-cache) nil)
11638 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11640 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11641 org-refile-cache))))
11642 (and set (org-refile-cache-check-set set) set)))))
11644 (defvar org-outline-path-cache nil
11645 "Alist between buffer positions and outline paths.
11646 It value is an alist (POSITION . PATH) where POSITION is the
11647 buffer position at the beginning of an entry and PATH is a list
11648 of strings describing the outline path for that entry, in reverse
11649 order.")
11651 (defun org-refile-get-targets (&optional default-buffer)
11652 "Produce a table with refile targets."
11653 (let ((case-fold-search nil)
11654 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11655 (entries (or org-refile-targets '((nil . (:level . 1)))))
11656 targets tgs files desc descre)
11657 (message "Getting targets...")
11658 (with-current-buffer (or default-buffer (current-buffer))
11659 (dolist (entry entries)
11660 (setq files (car entry) desc (cdr entry))
11661 (cond
11662 ((null files) (setq files (list (current-buffer))))
11663 ((eq files 'org-agenda-files)
11664 (setq files (org-agenda-files 'unrestricted)))
11665 ((and (symbolp files) (fboundp files))
11666 (setq files (funcall files)))
11667 ((and (symbolp files) (boundp files))
11668 (setq files (symbol-value files))))
11669 (when (stringp files) (setq files (list files)))
11670 (cond
11671 ((eq (car desc) :tag)
11672 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11673 ((eq (car desc) :todo)
11674 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11675 ((eq (car desc) :regexp)
11676 (setq descre (cdr desc)))
11677 ((eq (car desc) :level)
11678 (setq descre (concat "^\\*\\{" (number-to-string
11679 (if org-odd-levels-only
11680 (1- (* 2 (cdr desc)))
11681 (cdr desc)))
11682 "\\}[ \t]")))
11683 ((eq (car desc) :maxlevel)
11684 (setq descre (concat "^\\*\\{1," (number-to-string
11685 (if org-odd-levels-only
11686 (1- (* 2 (cdr desc)))
11687 (cdr desc)))
11688 "\\}[ \t]")))
11689 (t (error "Bad refiling target description %s" desc)))
11690 (dolist (f files)
11691 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11693 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11694 (progn
11695 (when (bufferp f)
11696 (setq f (buffer-file-name (buffer-base-buffer f))))
11697 (setq f (and f (expand-file-name f)))
11698 (when (eq org-refile-use-outline-path 'file)
11699 (push (list (file-name-nondirectory f) f nil nil) tgs))
11700 (org-with-wide-buffer
11701 (goto-char (point-min))
11702 (setq org-outline-path-cache nil)
11703 (while (re-search-forward descre nil t)
11704 (beginning-of-line)
11705 (let ((case-fold-search nil))
11706 (looking-at org-complex-heading-regexp))
11707 (let ((begin (point))
11708 (heading (match-string-no-properties 4)))
11709 (unless (or (and
11710 org-refile-target-verify-function
11711 (not
11712 (funcall org-refile-target-verify-function)))
11713 (not heading))
11714 (let ((re (format org-complex-heading-regexp-format
11715 (regexp-quote heading)))
11716 (target
11717 (if (not org-refile-use-outline-path) heading
11718 (mapconcat
11719 #'org-protect-slash
11720 (append
11721 (pcase org-refile-use-outline-path
11722 (`file (list (file-name-nondirectory
11723 (buffer-file-name
11724 (buffer-base-buffer)))))
11725 (`full-file-path
11726 (list (buffer-file-name
11727 (buffer-base-buffer))))
11728 (_ nil))
11729 (org-get-outline-path t t))
11730 "/"))))
11731 (push (list target f re (org-refile-marker (point)))
11732 tgs)))
11733 (when (= (point) begin)
11734 ;; Verification function has not moved point.
11735 (end-of-line)))))))
11736 (when org-refile-use-cache
11737 (org-refile-cache-put tgs (buffer-file-name) descre))
11738 (setq targets (append tgs targets))))))
11739 (message "Getting targets...done")
11740 (delete-dups (nreverse targets))))
11742 (defun org-protect-slash (s)
11743 (replace-regexp-in-string "/" "\\/" s nil t))
11745 (defun org--get-outline-path-1 (&optional use-cache)
11746 "Return outline path to current headline.
11748 Outline path is a list of strings, in reverse order. When
11749 optional argument USE-CACHE is non-nil, make use of a cache. See
11750 `org-get-outline-path' for details.
11752 Assume buffer is widened and point is on a headline."
11753 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11754 (let ((p (point))
11755 (heading (let ((case-fold-search nil))
11756 (looking-at org-complex-heading-regexp)
11757 (if (not (match-end 4)) ""
11758 ;; Remove statistics cookies.
11759 (org-trim
11760 (org-link-display-format
11761 (replace-regexp-in-string
11762 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11763 (match-string-no-properties 4))))))))
11764 (if (org-up-heading-safe)
11765 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11766 (when use-cache
11767 (push (cons p path) org-outline-path-cache))
11768 path)
11769 ;; This is a new root node. Since we assume we are moving
11770 ;; forward, we can drop previous cache so as to limit number
11771 ;; of associations there.
11772 (let ((path (list heading)))
11773 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11774 path)))))
11776 (defun org-get-outline-path (&optional with-self use-cache)
11777 "Return the outline path to the current entry.
11779 An outline path is a list of ancestors for current headline, as
11780 a list of strings. Statistics cookies are removed and links are
11781 replaced with their description, if any, or their path otherwise.
11783 When optional argument WITH-SELF is non-nil, the path also
11784 includes the current headline.
11786 When optional argument USE-CACHE is non-nil, cache outline paths
11787 between calls to this function so as to avoid backtracking. This
11788 argument is useful when planning to find more than one outline
11789 path in the same document. In that case, there are two
11790 conditions to satisfy:
11791 - `org-outline-path-cache' is set to nil before starting the
11792 process;
11793 - outline paths are computed by increasing buffer positions."
11794 (org-with-wide-buffer
11795 (and (or (and with-self (org-back-to-heading t))
11796 (org-up-heading-safe))
11797 (reverse (org--get-outline-path-1 use-cache)))))
11799 (defun org-format-outline-path (path &optional width prefix separator)
11800 "Format the outline path PATH for display.
11801 WIDTH is the maximum number of characters that is available.
11802 PREFIX is a prefix to be included in the returned string,
11803 such as the file name.
11804 SEPARATOR is inserted between the different parts of the path,
11805 the default is \"/\"."
11806 (setq width (or width 79))
11807 (setq path (delq nil path))
11808 (unless (> width 0)
11809 (user-error "Argument `width' must be positive"))
11810 (setq separator (or separator "/"))
11811 (let* ((org-odd-levels-only nil)
11812 (fpath (concat
11813 prefix (and prefix path separator)
11814 (mapconcat
11815 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11816 (cl-loop for head in path
11817 for n from 0
11818 collect (org-add-props
11819 head nil 'face
11820 (nth (% n org-n-level-faces) org-level-faces)))
11821 separator))))
11822 (when (> (length fpath) width)
11823 (if (< width 7)
11824 ;; It's unlikely that `width' will be this small, but don't
11825 ;; waste characters by adding ".." if it is.
11826 (setq fpath (substring fpath 0 width))
11827 (setf (substring fpath (- width 2)) "..")))
11828 fpath))
11830 (defun org-display-outline-path (&optional file current separator just-return-string)
11831 "Display the current outline path in the echo area.
11833 If FILE is non-nil, prepend the output with the file name.
11834 If CURRENT is non-nil, append the current heading to the output.
11835 SEPARATOR is passed through to `org-format-outline-path'. It separates
11836 the different parts of the path and defaults to \"/\".
11837 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11838 (interactive "P")
11839 (let* (case-fold-search
11840 (bfn (buffer-file-name (buffer-base-buffer)))
11841 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11842 res)
11843 (when current (setq path (append path
11844 (save-excursion
11845 (org-back-to-heading t)
11846 (when (looking-at org-complex-heading-regexp)
11847 (list (match-string 4)))))))
11848 (setq res
11849 (org-format-outline-path
11850 path
11851 (1- (frame-width))
11852 (and file bfn (concat (file-name-nondirectory bfn) separator))
11853 separator))
11854 (if just-return-string
11855 (org-no-properties res)
11856 (org-unlogged-message "%s" res))))
11858 (defvar org-refile-history nil
11859 "History for refiling operations.")
11861 (defvar org-after-refile-insert-hook nil
11862 "Hook run after `org-refile' has inserted its stuff at the new location.
11863 Note that this is still *before* the stuff will be removed from
11864 the *old* location.")
11866 (defvar org-capture-last-stored-marker)
11867 (defvar org-refile-keep nil
11868 "Non-nil means `org-refile' will copy instead of refile.")
11870 (defun org-copy ()
11871 "Like `org-refile', but copy."
11872 (interactive)
11873 (let ((org-refile-keep t))
11874 (funcall 'org-refile nil nil nil "Copy")))
11876 (defun org-refile (&optional arg default-buffer rfloc msg)
11877 "Move the entry or entries at point to another heading.
11879 The list of target headings is compiled using the information in
11880 `org-refile-targets', which see.
11882 At the target location, the entry is filed as a subitem of the
11883 target heading. Depending on `org-reverse-note-order', the new
11884 subitem will either be the first or the last subitem.
11886 If there is an active region, all entries in that region will be
11887 refiled. However, the region must fulfill the requirement that
11888 the first heading sets the top-level of the moved text.
11890 With a `\\[universal-argument]' ARG, the command will only visit the target \
11891 location
11892 and not actually move anything.
11894 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11895 location where the last
11896 refiling operation has put the subtree.
11898 With a numeric prefix argument of `2', refile to the running clock.
11900 With a numeric prefix argument of `3', emulate `org-refile-keep'
11901 being set to t and copy to the target location, don't move it.
11902 Beware that keeping refiled entries may result in duplicated ID
11903 properties.
11905 RFLOC can be a refile location obtained in a different way.
11907 MSG is a string to replace \"Refile\" in the default prompt with
11908 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11910 See also `org-refile-use-outline-path'.
11912 If you are using target caching (see `org-refile-use-cache'), you
11913 have to clear the target cache in order to find new targets.
11914 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11915 prefix argument (`C-u C-u C-u C-c C-w')."
11916 (interactive "P")
11917 (if (member arg '(0 (64)))
11918 (org-refile-cache-clear)
11919 (let* ((actionmsg (cond (msg msg)
11920 ((equal arg 3) "Refile (and keep)")
11921 (t "Refile")))
11922 (regionp (org-region-active-p))
11923 (region-start (and regionp (region-beginning)))
11924 (region-end (and regionp (region-end)))
11925 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11926 pos it nbuf file level reversed)
11927 (setq last-command nil)
11928 (when regionp
11929 (goto-char region-start)
11930 (or (bolp) (goto-char (point-at-bol)))
11931 (setq region-start (point))
11932 (unless (or (org-kill-is-subtree-p
11933 (buffer-substring region-start region-end))
11934 (prog1 org-refile-active-region-within-subtree
11935 (let ((s (point-at-eol)))
11936 (org-toggle-heading)
11937 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11938 (user-error "The region is not a (sequence of) subtree(s)")))
11939 (if (equal arg '(16))
11940 (org-refile-goto-last-stored)
11941 (when (or
11942 (and (equal arg 2)
11943 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11944 (prog1
11945 (setq it (list (or org-clock-heading "running clock")
11946 (buffer-file-name
11947 (marker-buffer org-clock-hd-marker))
11949 (marker-position org-clock-hd-marker)))
11950 (setq arg nil)))
11951 (setq it
11952 (or rfloc
11953 (let (heading-text)
11954 (save-excursion
11955 (unless (and arg (listp arg))
11956 (org-back-to-heading t)
11957 (setq heading-text
11958 (replace-regexp-in-string
11959 org-bracket-link-regexp
11960 "\\3"
11961 (or (nth 4 (org-heading-components))
11962 ""))))
11963 (org-refile-get-location
11964 (cond ((and arg (listp arg)) "Goto")
11965 (regionp (concat actionmsg " region to"))
11966 (t (concat actionmsg " subtree \""
11967 heading-text "\" to")))
11968 default-buffer
11969 (and (not (equal '(4) arg))
11970 org-refile-allow-creating-parent-nodes)))))))
11971 (setq file (nth 1 it)
11972 pos (nth 3 it))
11973 (when (and (not arg)
11975 (equal (buffer-file-name) file)
11976 (if regionp
11977 (and (>= pos region-start)
11978 (<= pos region-end))
11979 (and (>= pos (point))
11980 (< pos (save-excursion
11981 (org-end-of-subtree t t))))))
11982 (error "Cannot refile to position inside the tree or region"))
11983 (setq nbuf (or (find-buffer-visiting file)
11984 (find-file-noselect file)))
11985 (if (and arg (not (equal arg 3)))
11986 (progn
11987 (pop-to-buffer-same-window nbuf)
11988 (goto-char pos)
11989 (org-show-context 'org-goto))
11990 (if regionp
11991 (progn
11992 (org-kill-new (buffer-substring region-start region-end))
11993 (org-save-markers-in-region region-start region-end))
11994 (org-copy-subtree 1 nil t))
11995 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11996 (find-file-noselect file)))
11997 (setq reversed (org-notes-order-reversed-p))
11998 (org-with-wide-buffer
11999 (if pos
12000 (progn
12001 (goto-char pos)
12002 (looking-at org-outline-regexp)
12003 (setq level (org-get-valid-level (funcall outline-level) 1))
12004 (goto-char
12005 (if reversed
12006 (or (outline-next-heading) (point-max))
12007 (or (save-excursion (org-get-next-sibling))
12008 (org-end-of-subtree t t)
12009 (point-max)))))
12010 (setq level 1)
12011 (if (not reversed)
12012 (goto-char (point-max))
12013 (goto-char (point-min))
12014 (or (outline-next-heading) (goto-char (point-max)))))
12015 (unless (bolp) (newline))
12016 (org-paste-subtree level nil nil t)
12017 (when org-log-refile
12018 (org-add-log-setup 'refile nil nil org-log-refile)
12019 (unless (eq org-log-refile 'note)
12020 (save-excursion (org-add-log-note))))
12021 (and org-auto-align-tags
12022 (let ((org-loop-over-headlines-in-active-region nil))
12023 (org-set-tags nil t)))
12024 (let ((bookmark-name (plist-get org-bookmark-names-plist
12025 :last-refile)))
12026 (when bookmark-name
12027 (with-demoted-errors
12028 (bookmark-set bookmark-name))))
12029 ;; If we are refiling for capture, make sure that the
12030 ;; last-capture pointers point here
12031 (when (bound-and-true-p org-capture-is-refiling)
12032 (let ((bookmark-name (plist-get org-bookmark-names-plist
12033 :last-capture-marker)))
12034 (when bookmark-name
12035 (with-demoted-errors
12036 (bookmark-set bookmark-name))))
12037 (move-marker org-capture-last-stored-marker (point)))
12038 (when (fboundp 'deactivate-mark) (deactivate-mark))
12039 (run-hooks 'org-after-refile-insert-hook)))
12040 (unless org-refile-keep
12041 (if regionp
12042 (delete-region (point) (+ (point) (- region-end region-start)))
12043 (delete-region
12044 (and (org-back-to-heading t) (point))
12045 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12046 (when (featurep 'org-inlinetask)
12047 (org-inlinetask-remove-END-maybe))
12048 (setq org-markers-to-move nil)
12049 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12051 (defun org-refile-goto-last-stored ()
12052 "Go to the location where the last refile was stored."
12053 (interactive)
12054 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12055 (message "This is the location of the last refile"))
12057 (defun org-refile--get-location (refloc tbl)
12058 "When user refile to REFLOC, find the associated target in TBL.
12059 Also check `org-refile-target-table'."
12060 (car (delq
12062 (mapcar
12063 (lambda (r) (or (assoc r tbl)
12064 (assoc r org-refile-target-table)))
12065 (list (replace-regexp-in-string "/$" "" refloc)
12066 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12068 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12069 "Prompt the user for a refile location, using PROMPT.
12070 PROMPT should not be suffixed with a colon and a space, because
12071 this function appends the default value from
12072 `org-refile-history' automatically, if that is not empty."
12073 (let ((org-refile-targets org-refile-targets)
12074 (org-refile-use-outline-path org-refile-use-outline-path))
12075 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12076 (unless org-refile-target-table
12077 (user-error "No refile targets"))
12078 (let* ((cbuf (current-buffer))
12079 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12080 (cfunc (if (and org-refile-use-outline-path
12081 org-outline-path-complete-in-steps)
12082 #'org-olpath-completing-read
12083 #'completing-read))
12084 (extra (if org-refile-use-outline-path "/" ""))
12085 (cbnex (concat (buffer-name) extra))
12086 (filename (and cfn (expand-file-name cfn)))
12087 (tbl (mapcar
12088 (lambda (x)
12089 (if (and (not (member org-refile-use-outline-path
12090 '(file full-file-path)))
12091 (not (equal filename (nth 1 x))))
12092 (cons (concat (car x) extra " ("
12093 (file-name-nondirectory (nth 1 x)) ")")
12094 (cdr x))
12095 (cons (concat (car x) extra) (cdr x))))
12096 org-refile-target-table))
12097 (completion-ignore-case t)
12098 cdef
12099 (prompt (concat prompt
12100 (or (and (car org-refile-history)
12101 (concat " (default " (car org-refile-history) ")"))
12102 (and (assoc cbnex tbl) (setq cdef cbnex)
12103 (concat " (default " cbnex ")"))) ": "))
12104 pa answ parent-target child parent old-hist)
12105 (setq old-hist org-refile-history)
12106 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12107 nil 'org-refile-history (or cdef (car org-refile-history))))
12108 (if (setq pa (org-refile--get-location answ tbl))
12109 (progn
12110 (org-refile-check-position pa)
12111 (when (or (not org-refile-history)
12112 (not (eq old-hist org-refile-history))
12113 (not (equal (car pa) (car org-refile-history))))
12114 (setq org-refile-history
12115 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12116 org-refile-history
12117 (cdr org-refile-history))))
12118 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12119 (pop org-refile-history)))
12121 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12122 (progn
12123 (setq parent (match-string 1 answ)
12124 child (match-string 2 answ))
12125 (setq parent-target (org-refile--get-location parent tbl))
12126 (when (and parent-target
12127 (or (eq new-nodes t)
12128 (and (eq new-nodes 'confirm)
12129 (y-or-n-p (format "Create new node \"%s\"? "
12130 child)))))
12131 (org-refile-new-child parent-target child)))
12132 (user-error "Invalid target location")))))
12134 (declare-function org-string-nw-p "org-macs" (s))
12135 (defun org-refile-check-position (refile-pointer)
12136 "Check if the refile pointer matches the headline to which it points."
12137 (let* ((file (nth 1 refile-pointer))
12138 (re (nth 2 refile-pointer))
12139 (pos (nth 3 refile-pointer))
12140 buffer)
12141 (if (and (not (markerp pos)) (not file))
12142 (user-error "Please indicate a target file in the refile path")
12143 (when (org-string-nw-p re)
12144 (setq buffer (if (markerp pos)
12145 (marker-buffer pos)
12146 (or (find-buffer-visiting file)
12147 (find-file-noselect file))))
12148 (with-current-buffer buffer
12149 (org-with-wide-buffer
12150 (goto-char pos)
12151 (beginning-of-line 1)
12152 (unless (looking-at-p re)
12153 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12155 (defun org-refile-new-child (parent-target child)
12156 "Use refile target PARENT-TARGET to add new CHILD below it."
12157 (unless parent-target
12158 (error "Cannot find parent for new node"))
12159 (let ((file (nth 1 parent-target))
12160 (pos (nth 3 parent-target))
12161 level)
12162 (with-current-buffer (or (find-buffer-visiting file)
12163 (find-file-noselect file))
12164 (org-with-wide-buffer
12165 (if pos
12166 (goto-char pos)
12167 (goto-char (point-max))
12168 (unless (bolp) (newline)))
12169 (when (looking-at org-outline-regexp)
12170 (setq level (funcall outline-level))
12171 (org-end-of-subtree t t))
12172 (org-back-over-empty-lines)
12173 (insert "\n" (make-string
12174 (if pos (org-get-valid-level level 1) 1) ?*)
12175 " " child "\n")
12176 (beginning-of-line 0)
12177 (list (concat (car parent-target) "/" child) file "" (point))))))
12179 (defun org-olpath-completing-read (prompt collection &rest args)
12180 "Read an outline path like a file name."
12181 (let ((thetable collection))
12182 (apply #'completing-read
12183 prompt
12184 (lambda (string predicate &optional flag)
12185 (cond
12186 ((eq flag nil) (try-completion string thetable))
12187 ((eq flag t)
12188 (let ((l (length string)))
12189 (mapcar (lambda (x)
12190 (let ((r (substring x l))
12191 (f (if (string-match " ([^)]*)$" x)
12192 (match-string 0 x)
12193 "")))
12194 (if (string-match "/" r)
12195 (concat string (substring r 0 (match-end 0)) f)
12196 x)))
12197 (all-completions string thetable predicate))))
12198 ;; Exact match?
12199 ((eq flag 'lambda) (assoc string thetable))))
12200 args)))
12202 ;;;; Dynamic blocks
12204 (defun org-find-dblock (name)
12205 "Find the first dynamic block with name NAME in the buffer.
12206 If not found, stay at current position and return nil."
12207 (let ((case-fold-search t) pos)
12208 (save-excursion
12209 (goto-char (point-min))
12210 (setq pos (and (re-search-forward
12211 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12212 (match-beginning 0))))
12213 (when pos (goto-char pos))
12214 pos))
12216 (defun org-create-dblock (plist)
12217 "Create a dynamic block section, with parameters taken from PLIST.
12218 PLIST must contain a :name entry which is used as the name of the block."
12219 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12220 (end-of-line 1)
12221 (newline))
12222 (let ((col (current-column))
12223 (name (plist-get plist :name)))
12224 (insert "#+BEGIN: " name)
12225 (while plist
12226 (if (eq (car plist) :name)
12227 (setq plist (cddr plist))
12228 (insert " " (prin1-to-string (pop plist)))))
12229 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12230 (beginning-of-line -2)))
12232 (defun org-prepare-dblock ()
12233 "Prepare dynamic block for refresh.
12234 This empties the block, puts the cursor at the insert position and returns
12235 the property list including an extra property :name with the block name."
12236 (unless (looking-at org-dblock-start-re)
12237 (user-error "Not at a dynamic block"))
12238 (let* ((begdel (1+ (match-end 0)))
12239 (name (org-no-properties (match-string 1)))
12240 (params (append (list :name name)
12241 (read (concat "(" (match-string 3) ")")))))
12242 (save-excursion
12243 (beginning-of-line 1)
12244 (skip-chars-forward " \t")
12245 (setq params (plist-put params :indentation-column (current-column))))
12246 (unless (re-search-forward org-dblock-end-re nil t)
12247 (error "Dynamic block not terminated"))
12248 (setq params
12249 (append params
12250 (list :content (buffer-substring
12251 begdel (match-beginning 0)))))
12252 (delete-region begdel (match-beginning 0))
12253 (goto-char begdel)
12254 (open-line 1)
12255 params))
12257 (defun org-map-dblocks (&optional command)
12258 "Apply COMMAND to all dynamic blocks in the current buffer.
12259 If COMMAND is not given, use `org-update-dblock'."
12260 (let ((cmd (or command 'org-update-dblock)))
12261 (save-excursion
12262 (goto-char (point-min))
12263 (while (re-search-forward org-dblock-start-re nil t)
12264 (goto-char (match-beginning 0))
12265 (save-excursion
12266 (condition-case nil
12267 (funcall cmd)
12268 (error (message "Error during update of dynamic block"))))
12269 (unless (re-search-forward org-dblock-end-re nil t)
12270 (error "Dynamic block not terminated"))))))
12272 (defun org-dblock-update (&optional arg)
12273 "User command for updating dynamic blocks.
12274 Update the dynamic block at point. With prefix ARG, update all dynamic
12275 blocks in the buffer."
12276 (interactive "P")
12277 (if arg
12278 (org-update-all-dblocks)
12279 (or (looking-at org-dblock-start-re)
12280 (org-beginning-of-dblock))
12281 (org-update-dblock)))
12283 (defun org-update-dblock ()
12284 "Update the dynamic block at point.
12285 This means to empty the block, parse for parameters and then call
12286 the correct writing function."
12287 (interactive)
12288 (save-excursion
12289 (let* ((win (selected-window))
12290 (pos (point))
12291 (line (org-current-line))
12292 (params (org-prepare-dblock))
12293 (name (plist-get params :name))
12294 (indent (plist-get params :indentation-column))
12295 (cmd (intern (concat "org-dblock-write:" name))))
12296 (message "Updating dynamic block `%s' at line %d..." name line)
12297 (funcall cmd params)
12298 (message "Updating dynamic block `%s' at line %d...done" name line)
12299 (goto-char pos)
12300 (when (and indent (> indent 0))
12301 (setq indent (make-string indent ?\ ))
12302 (save-excursion
12303 (select-window win)
12304 (org-beginning-of-dblock)
12305 (forward-line 1)
12306 (while (not (looking-at org-dblock-end-re))
12307 (insert indent)
12308 (beginning-of-line 2))
12309 (when (looking-at org-dblock-end-re)
12310 (and (looking-at "[ \t]+")
12311 (replace-match ""))
12312 (insert indent)))))))
12314 (defun org-beginning-of-dblock ()
12315 "Find the beginning of the dynamic block at point.
12316 Error if there is no such block at point."
12317 (let ((pos (point))
12318 beg)
12319 (end-of-line 1)
12320 (if (and (re-search-backward org-dblock-start-re nil t)
12321 (setq beg (match-beginning 0))
12322 (re-search-forward org-dblock-end-re nil t)
12323 (> (match-end 0) pos))
12324 (goto-char beg)
12325 (goto-char pos)
12326 (error "Not in a dynamic block"))))
12328 (defun org-update-all-dblocks ()
12329 "Update all dynamic blocks in the buffer.
12330 This function can be used in a hook."
12331 (interactive)
12332 (when (derived-mode-p 'org-mode)
12333 (org-map-dblocks 'org-update-dblock)))
12336 ;;;; Completion
12338 (declare-function org-export-backend-options "ox" (cl-x) t)
12339 (defun org-get-export-keywords ()
12340 "Return a list of all currently understood export keywords.
12341 Export keywords include options, block names, attributes and
12342 keywords relative to each registered export back-end."
12343 (let (keywords)
12344 (dolist (backend
12345 (bound-and-true-p org-export-registered-backends)
12346 (delq nil keywords))
12347 ;; Back-end name (for keywords, like #+LATEX:)
12348 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12349 (dolist (option-entry (org-export-backend-options backend))
12350 ;; Back-end options.
12351 (push (nth 1 option-entry) keywords)))))
12353 (defconst org-options-keywords
12354 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12355 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12356 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12357 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12358 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12360 (defcustom org-structure-template-alist
12361 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12362 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12363 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12364 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12365 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12366 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12367 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12368 ("L" "#+LaTeX: ")
12369 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12370 ("H" "#+HTML: ")
12371 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12372 ("A" "#+ASCII: ")
12373 ("i" "#+INDEX: ?")
12374 ("I" "#+INCLUDE: %file ?"))
12375 "Structure completion elements.
12376 This is a list of abbreviation keys and values. The value gets inserted
12377 if you type `<' followed by the key and then press the completion key,
12378 usually `TAB'. %file will be replaced by a file name after prompting
12379 for the file using completion. The cursor will be placed at the position
12380 of the `?' in the template.
12381 There are two templates for each key, the first uses the original Org syntax,
12382 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12383 the default when the /org-mtags.el/ module has been loaded. See also the
12384 variable `org-mtags-prefer-muse-templates'."
12385 :group 'org-completion
12386 :type '(repeat
12387 (list
12388 (string :tag "Key")
12389 (string :tag "Template")))
12390 :version "26.1"
12391 :package-version '(Org . "8.3"))
12393 (defun org-try-structure-completion ()
12394 "Try to complete a structure template before point.
12395 This looks for strings like \"<e\" on an otherwise empty line and
12396 expands them."
12397 (let ((l (buffer-substring (point-at-bol) (point)))
12399 (when (and (looking-at "[ \t]*$")
12400 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12401 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12402 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12403 (match-beginning 1)) a)
12404 t)))
12406 (defun org-complete-expand-structure-template (start cell)
12407 "Expand a structure template."
12408 (let ((rpl (nth 1 cell))
12409 (ind ""))
12410 (delete-region start (point))
12411 (when (string-match "\\`[ \t]*#\\+" rpl)
12412 (cond
12413 ((bolp))
12414 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12415 (setq ind (buffer-substring (point-at-bol) (point))))
12416 (t (newline))))
12417 (setq start (point))
12418 (when (string-match "%file" rpl)
12419 (setq rpl (replace-match
12420 (concat
12421 "\""
12422 (save-match-data
12423 (abbreviate-file-name (read-file-name "Include file: ")))
12424 "\"")
12425 t t rpl)))
12426 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12427 (concat "\n" ind)))
12428 (insert rpl)
12429 (when (re-search-backward "\\?" start t) (delete-char 1))))
12431 ;;;; TODO, DEADLINE, Comments
12433 (defun org-toggle-comment ()
12434 "Change the COMMENT state of an entry."
12435 (interactive)
12436 (save-excursion
12437 (org-back-to-heading)
12438 (let ((case-fold-search nil))
12439 (looking-at org-complex-heading-regexp))
12440 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12441 (skip-chars-forward " \t")
12442 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12443 (if (org-in-commented-heading-p t)
12444 (delete-region (point)
12445 (progn (search-forward " " (line-end-position) 'move)
12446 (skip-chars-forward " \t")
12447 (point)))
12448 (insert org-comment-string)
12449 (unless (eolp) (insert " ")))))
12451 (defvar org-last-todo-state-is-todo nil
12452 "This is non-nil when the last TODO state change led to a TODO state.
12453 If the last change removed the TODO tag or switched to DONE, then
12454 this is nil.")
12456 (defvar org-setting-tags nil) ; dynamically skipped
12458 (defvar org-todo-setup-filter-hook nil
12459 "Hook for functions that pre-filter todo specs.
12460 Each function takes a todo spec and returns either nil or the spec
12461 transformed into canonical form." )
12463 (defvar org-todo-get-default-hook nil
12464 "Hook for functions that get a default item for todo.
12465 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12466 nil or a string to be used for the todo mark." )
12468 (defvar org-agenda-headline-snapshot-before-repeat)
12470 (defun org-current-effective-time ()
12471 "Return current time adjusted for `org-extend-today-until' variable."
12472 (let* ((ct (org-current-time))
12473 (dct (decode-time ct))
12474 (ct1
12475 (cond
12476 (org-use-last-clock-out-time-as-effective-time
12477 (or (org-clock-get-last-clock-out-time) ct))
12478 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12479 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12480 (t ct))))
12481 ct1))
12483 (defun org-todo-yesterday (&optional arg)
12484 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12485 (interactive "P")
12486 (if (eq major-mode 'org-agenda-mode)
12487 (apply 'org-agenda-todo-yesterday arg)
12488 (let* ((org-use-effective-time t)
12489 (hour (nth 2 (decode-time (org-current-time))))
12490 (org-extend-today-until (1+ hour)))
12491 (org-todo arg))))
12493 (defvar org-block-entry-blocking ""
12494 "First entry preventing the TODO state change.")
12496 (defun org-cancel-repeater ()
12497 "Cancel a repeater by setting its numeric value to zero."
12498 (interactive)
12499 (save-excursion
12500 (org-back-to-heading t)
12501 (let ((bound1 (point))
12502 (bound0 (save-excursion (outline-next-heading) (point))))
12503 (when (and (re-search-forward
12504 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12505 org-deadline-time-regexp "\\)\\|\\("
12506 org-ts-regexp "\\)")
12507 bound0 t)
12508 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12509 bound1 t))
12510 (replace-match "0" t nil nil 1)))))
12512 (defvar org-state)
12513 (defvar org-blocked-by-checkboxes)
12514 (defun org-todo (&optional arg)
12515 "Change the TODO state of an item.
12517 The state of an item is given by a keyword at the start of the heading,
12518 like
12519 *** TODO Write paper
12520 *** DONE Call mom
12522 The different keywords are specified in the variable `org-todo-keywords'.
12523 By default the available states are \"TODO\" and \"DONE\". So, for this
12524 example: when the item starts with TODO, it is changed to DONE.
12525 When it starts with DONE, the DONE is removed. And when neither TODO nor
12526 DONE are present, add TODO at the beginning of the heading.
12528 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12529 state.
12530 With numeric prefix ARG, switch to that state.
12531 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12532 next set of TODO \
12533 keywords (nextset).
12534 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12535 prefix, circumvent any state blocking.
12536 With a numeric prefix arg of 0, inhibit note taking for the change.
12537 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12539 When called through ELisp, arg is also interpreted in the following way:
12540 `none' -> empty state
12541 \"\" -> switch to empty state
12542 `done' -> switch to DONE
12543 `nextset' -> switch to the next set of keywords
12544 `previousset' -> switch to the previous set of keywords
12545 \"WAITING\" -> switch to the specified keyword, but only if it
12546 really is a member of `org-todo-keywords'."
12547 (interactive "P")
12548 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12549 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12550 'region-start-level 'region))
12551 org-loop-over-headlines-in-active-region)
12552 (org-map-entries
12553 `(org-todo ,arg)
12554 org-loop-over-headlines-in-active-region
12555 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12556 (when (equal arg '(16)) (setq arg 'nextset))
12557 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12558 (let ((org-blocker-hook org-blocker-hook)
12559 commentp
12560 case-fold-search)
12561 (when (equal arg '(64))
12562 (setq arg nil org-blocker-hook nil))
12563 (when (and org-blocker-hook
12564 (or org-inhibit-blocking
12565 (org-entry-get nil "NOBLOCKING")))
12566 (setq org-blocker-hook nil))
12567 (save-excursion
12568 (catch 'exit
12569 (org-back-to-heading t)
12570 (when (org-in-commented-heading-p t)
12571 (org-toggle-comment)
12572 (setq commentp t))
12573 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12574 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12575 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12576 (let* ((match-data (match-data))
12577 (startpos (point-at-bol))
12578 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12579 (org-log-done org-log-done)
12580 (org-log-repeat org-log-repeat)
12581 (org-todo-log-states org-todo-log-states)
12582 (org-inhibit-logging
12583 (if (equal arg 0)
12584 (progn (setq arg nil) 'note) org-inhibit-logging))
12585 (this (match-string 1))
12586 (hl-pos (match-beginning 0))
12587 (head (org-get-todo-sequence-head this))
12588 (ass (assoc head org-todo-kwd-alist))
12589 (interpret (nth 1 ass))
12590 (done-word (nth 3 ass))
12591 (final-done-word (nth 4 ass))
12592 (org-last-state (or this ""))
12593 (completion-ignore-case t)
12594 (member (member this org-todo-keywords-1))
12595 (tail (cdr member))
12596 (org-state (cond
12597 ((and org-todo-key-trigger
12598 (or (and (equal arg '(4))
12599 (eq org-use-fast-todo-selection 'prefix))
12600 (and (not arg) org-use-fast-todo-selection
12601 (not (eq org-use-fast-todo-selection
12602 'prefix)))))
12603 ;; Use fast selection.
12604 (org-fast-todo-selection))
12605 ((and (equal arg '(4))
12606 (or (not org-use-fast-todo-selection)
12607 (not org-todo-key-trigger)))
12608 ;; Read a state with completion.
12609 (completing-read
12610 "State: " (mapcar #'list org-todo-keywords-1)
12611 nil t))
12612 ((eq arg 'right)
12613 (if this
12614 (if tail (car tail) nil)
12615 (car org-todo-keywords-1)))
12616 ((eq arg 'left)
12617 (unless (equal member org-todo-keywords-1)
12618 (if this
12619 (nth (- (length org-todo-keywords-1)
12620 (length tail) 2)
12621 org-todo-keywords-1)
12622 (org-last org-todo-keywords-1))))
12623 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12624 (setq arg nil))) ;hack to fall back to cycling
12625 (arg
12626 ;; User or caller requests a specific state.
12627 (cond
12628 ((equal arg "") nil)
12629 ((eq arg 'none) nil)
12630 ((eq arg 'done) (or done-word (car org-done-keywords)))
12631 ((eq arg 'nextset)
12632 (or (car (cdr (member head org-todo-heads)))
12633 (car org-todo-heads)))
12634 ((eq arg 'previousset)
12635 (let ((org-todo-heads (reverse org-todo-heads)))
12636 (or (car (cdr (member head org-todo-heads)))
12637 (car org-todo-heads))))
12638 ((car (member arg org-todo-keywords-1)))
12639 ((stringp arg)
12640 (user-error "State `%s' not valid in this file" arg))
12641 ((nth (1- (prefix-numeric-value arg))
12642 org-todo-keywords-1))))
12643 ((null member) (or head (car org-todo-keywords-1)))
12644 ((equal this final-done-word) nil) ;-> make empty
12645 ((null tail) nil) ;-> first entry
12646 ((memq interpret '(type priority))
12647 (if (eq this-command last-command)
12648 (car tail)
12649 (if (> (length tail) 0)
12650 (or done-word (car org-done-keywords))
12651 nil)))
12653 (car tail))))
12654 (org-state (or
12655 (run-hook-with-args-until-success
12656 'org-todo-get-default-hook org-state org-last-state)
12657 org-state))
12658 (next (if org-state (concat " " org-state " ") " "))
12659 (change-plist (list :type 'todo-state-change :from this :to org-state
12660 :position startpos))
12661 dolog now-done-p)
12662 (when org-blocker-hook
12663 (let (org-blocked-by-checkboxes block-reason)
12664 (setq org-last-todo-state-is-todo
12665 (not (member this org-done-keywords)))
12666 (unless (save-excursion
12667 (save-match-data
12668 (org-with-wide-buffer
12669 (run-hook-with-args-until-failure
12670 'org-blocker-hook change-plist))))
12671 (setq block-reason (if org-blocked-by-checkboxes
12672 "contained checkboxes"
12673 (format "\"%s\"" org-block-entry-blocking)))
12674 (if (called-interactively-p 'interactive)
12675 (user-error "TODO state change from %s to %s blocked (by %s)"
12676 this org-state block-reason)
12677 ;; Fail silently.
12678 (message "TODO state change from %s to %s blocked (by %s)"
12679 this org-state block-reason)
12680 (throw 'exit nil)))))
12681 (store-match-data match-data)
12682 (replace-match next t t)
12683 (cond ((equal this org-state)
12684 (message "TODO state was already %s" (org-trim next)))
12685 ((pos-visible-in-window-p hl-pos)
12686 (message "TODO state changed to %s" (org-trim next))))
12687 (unless head
12688 (setq head (org-get-todo-sequence-head org-state)
12689 ass (assoc head org-todo-kwd-alist)
12690 interpret (nth 1 ass)
12691 done-word (nth 3 ass)
12692 final-done-word (nth 4 ass)))
12693 (when (memq arg '(nextset previousset))
12694 (message "Keyword-Set %d/%d: %s"
12695 (- (length org-todo-sets) -1
12696 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12697 (length org-todo-sets)
12698 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12699 (setq org-last-todo-state-is-todo
12700 (not (member org-state org-done-keywords)))
12701 (setq now-done-p (and (member org-state org-done-keywords)
12702 (not (member this org-done-keywords))))
12703 (and logging (org-local-logging logging))
12704 (when (and (or org-todo-log-states org-log-done)
12705 (not (eq org-inhibit-logging t))
12706 (not (memq arg '(nextset previousset))))
12707 ;; We need to look at recording a time and note.
12708 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12709 (nth 2 (assoc this org-todo-log-states))))
12710 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12711 (setq dolog 'time))
12712 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12713 (and org-state
12714 (member org-state org-not-done-keywords)
12715 (not (member this org-not-done-keywords))))
12716 ;; This is now a todo state and was not one before
12717 ;; If there was a CLOSED time stamp, get rid of it.
12718 (org-add-planning-info nil nil 'closed))
12719 (when (and now-done-p org-log-done)
12720 ;; It is now done, and it was not done before.
12721 (org-add-planning-info 'closed (org-current-effective-time))
12722 (when (and (not dolog) (eq 'note org-log-done))
12723 (org-add-log-setup 'done org-state this 'note)))
12724 (when (and org-state dolog)
12725 ;; This is a non-nil state, and we need to log it.
12726 (org-add-log-setup 'state org-state this dolog)))
12727 ;; Fixup tag positioning.
12728 (org-todo-trigger-tag-changes org-state)
12729 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12730 (when org-provide-todo-statistics
12731 (org-update-parent-todo-statistics))
12732 (run-hooks 'org-after-todo-state-change-hook)
12733 (when (and arg (not (member org-state org-done-keywords)))
12734 (setq head (org-get-todo-sequence-head org-state)))
12735 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12736 ;; Do we need to trigger a repeat?
12737 (when now-done-p
12738 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12739 ;; This is for the agenda, take a snapshot of the headline.
12740 (save-match-data
12741 (setq org-agenda-headline-snapshot-before-repeat
12742 (org-get-heading))))
12743 (org-auto-repeat-maybe org-state))
12744 ;; Fixup cursor location if close to the keyword.
12745 (when (and (outline-on-heading-p)
12746 (not (bolp))
12747 (save-excursion (beginning-of-line 1)
12748 (looking-at org-todo-line-regexp))
12749 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12750 (goto-char (or (match-end 2) (match-end 1)))
12751 (and (looking-at " ") (just-one-space)))
12752 (when org-trigger-hook
12753 (save-excursion
12754 (run-hook-with-args 'org-trigger-hook change-plist)))
12755 (when commentp (org-toggle-comment))))))))
12757 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12758 "Block turning an entry into a TODO, using the hierarchy.
12759 This checks whether the current task should be blocked from state
12760 changes. Such blocking occurs when:
12762 1. The task has children which are not all in a completed state.
12764 2. A task has a parent with the property :ORDERED:, and there
12765 are siblings prior to the current task with incomplete
12766 status.
12768 3. The parent of the task is blocked because it has siblings that should
12769 be done first, or is child of a block grandparent TODO entry."
12771 (if (not org-enforce-todo-dependencies)
12772 t ; if locally turned off don't block
12773 (catch 'dont-block
12774 ;; If this is not a todo state change, or if this entry is already DONE,
12775 ;; do not block
12776 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12777 (member (plist-get change-plist :from)
12778 (cons 'done org-done-keywords))
12779 (member (plist-get change-plist :to)
12780 (cons 'todo org-not-done-keywords))
12781 (not (plist-get change-plist :to)))
12782 (throw 'dont-block t))
12783 ;; If this task has children, and any are undone, it's blocked
12784 (save-excursion
12785 (org-back-to-heading t)
12786 (let ((this-level (funcall outline-level)))
12787 (outline-next-heading)
12788 (let ((child-level (funcall outline-level)))
12789 (while (and (not (eobp))
12790 (> child-level this-level))
12791 ;; this todo has children, check whether they are all
12792 ;; completed
12793 (when (and (not (org-entry-is-done-p))
12794 (org-entry-is-todo-p))
12795 (setq org-block-entry-blocking (org-get-heading))
12796 (throw 'dont-block nil))
12797 (outline-next-heading)
12798 (setq child-level (funcall outline-level))))))
12799 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12800 ;; any previous siblings are undone, it's blocked
12801 (save-excursion
12802 (org-back-to-heading t)
12803 (let* ((pos (point))
12804 (parent-pos (and (org-up-heading-safe) (point)))
12805 (case-fold-search nil))
12806 (unless parent-pos (throw 'dont-block t)) ; no parent
12807 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12808 (forward-line 1)
12809 (re-search-forward org-not-done-heading-regexp pos t))
12810 (setq org-block-entry-blocking (match-string 0))
12811 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12812 ;; Search further up the hierarchy, to see if an ancestor is blocked
12813 (while t
12814 (goto-char parent-pos)
12815 (unless (looking-at org-not-done-heading-regexp)
12816 (throw 'dont-block t)) ; do not block, parent is not a TODO
12817 (setq pos (point))
12818 (setq parent-pos (and (org-up-heading-safe) (point)))
12819 (unless parent-pos (throw 'dont-block t)) ; no parent
12820 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12821 (forward-line 1)
12822 (re-search-forward org-not-done-heading-regexp pos t)
12823 (setq org-block-entry-blocking (org-get-heading)))
12824 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12826 (defcustom org-track-ordered-property-with-tag nil
12827 "Should the ORDERED property also be shown as a tag?
12828 The ORDERED property decides if an entry should require subtasks to be
12829 completed in sequence. Since a property is not very visible, setting
12830 this option means that toggling the ORDERED property with the command
12831 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12832 not relevant for the behavior, but it makes things more visible.
12834 Note that toggling the tag with tags commands will not change the property
12835 and therefore not influence behavior!
12837 This can be t, meaning the tag ORDERED should be used, It can also be a
12838 string to select a different tag for this task."
12839 :group 'org-todo
12840 :type '(choice
12841 (const :tag "No tracking" nil)
12842 (const :tag "Track with ORDERED tag" t)
12843 (string :tag "Use other tag")))
12845 (defun org-toggle-ordered-property ()
12846 "Toggle the ORDERED property of the current entry.
12847 For better visibility, you can track the value of this property with a tag.
12848 See variable `org-track-ordered-property-with-tag'."
12849 (interactive)
12850 (let* ((t1 org-track-ordered-property-with-tag)
12851 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12852 (save-excursion
12853 (org-back-to-heading)
12854 (if (org-entry-get nil "ORDERED")
12855 (progn
12856 (org-delete-property "ORDERED")
12857 (and tag (org-toggle-tag tag 'off))
12858 (message "Subtasks can be completed in arbitrary order"))
12859 (org-entry-put nil "ORDERED" "t")
12860 (and tag (org-toggle-tag tag 'on))
12861 (message "Subtasks must be completed in sequence")))))
12863 (defun org-block-todo-from-checkboxes (change-plist)
12864 "Block turning an entry into a TODO, using checkboxes.
12865 This checks whether the current task should be blocked from state
12866 changes because there are unchecked boxes in this entry."
12867 (if (not org-enforce-todo-checkbox-dependencies)
12868 t ; if locally turned off don't block
12869 (catch 'dont-block
12870 ;; If this is not a todo state change, or if this entry is already DONE,
12871 ;; do not block
12872 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12873 (member (plist-get change-plist :from)
12874 (cons 'done org-done-keywords))
12875 (member (plist-get change-plist :to)
12876 (cons 'todo org-not-done-keywords))
12877 (not (plist-get change-plist :to)))
12878 (throw 'dont-block t))
12879 ;; If this task has checkboxes that are not checked, it's blocked
12880 (save-excursion
12881 (org-back-to-heading t)
12882 (let ((beg (point)) end)
12883 (outline-next-heading)
12884 (setq end (point))
12885 (goto-char beg)
12886 (when (org-list-search-forward
12887 (concat (org-item-beginning-re)
12888 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12889 "\\[[- ]\\]")
12890 end t)
12891 (when (boundp 'org-blocked-by-checkboxes)
12892 (setq org-blocked-by-checkboxes t))
12893 (throw 'dont-block nil))))
12894 t))) ; do not block
12896 (defun org-entry-blocked-p ()
12897 "Non-nil if entry at point is blocked."
12898 (and (not (org-entry-get nil "NOBLOCKING"))
12899 (member (org-entry-get nil "TODO") org-not-done-keywords)
12900 (not (run-hook-with-args-until-failure
12901 'org-blocker-hook
12902 (list :type 'todo-state-change
12903 :position (point)
12904 :from 'todo
12905 :to 'done)))))
12907 (defun org-update-statistics-cookies (all)
12908 "Update the statistics cookie, either from TODO or from checkboxes.
12909 This should be called with the cursor in a line with a statistics
12910 cookie. When called with a \\[universal-argument] prefix, update
12911 all statistics cookies in the buffer."
12912 (interactive "P")
12913 (if all
12914 (progn
12915 (org-update-checkbox-count 'all)
12916 (org-map-entries 'org-update-parent-todo-statistics))
12917 (if (not (org-at-heading-p))
12918 (org-update-checkbox-count)
12919 (let ((pos (point-marker))
12920 end l1 l2)
12921 (ignore-errors (org-back-to-heading t))
12922 (if (not (org-at-heading-p))
12923 (org-update-checkbox-count)
12924 (setq l1 (org-outline-level))
12925 (setq end (save-excursion
12926 (outline-next-heading)
12927 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12928 (point)))
12929 (if (and (save-excursion
12930 (re-search-forward
12931 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12932 (not (save-excursion (re-search-forward
12933 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12934 (org-update-checkbox-count)
12935 (if (and l2 (> l2 l1))
12936 (progn
12937 (goto-char end)
12938 (org-update-parent-todo-statistics))
12939 (goto-char pos)
12940 (beginning-of-line 1)
12941 (while (re-search-forward
12942 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12943 (point-at-eol) t)
12944 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12945 (goto-char pos)
12946 (move-marker pos nil)))))
12948 (defvar org-entry-property-inherited-from) ;; defined below
12949 (defun org-update-parent-todo-statistics ()
12950 "Update any statistics cookie in the parent of the current headline.
12951 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12952 the entire subtree and this will travel up the hierarchy and update
12953 statistics everywhere."
12954 (let* ((prop (save-excursion (org-up-heading-safe)
12955 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12956 (recursive (or (not org-hierarchical-todo-statistics)
12957 (and prop (string-match "\\<recursive\\>" prop))))
12958 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12960 (first t)
12961 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12962 level ltoggle l1 new ndel
12963 (cnt-all 0) (cnt-done 0) is-percent kwd
12964 checkbox-beg cookie-present)
12965 (catch 'exit
12966 (save-excursion
12967 (beginning-of-line 1)
12968 (setq ltoggle (funcall outline-level))
12969 ;; Three situations are to consider:
12971 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12972 ;; to the top-level ancestor on the headline;
12974 ;; 2. If parent has "recursive" property, repeat up to the
12975 ;; headline setting that property, taking inheritance into
12976 ;; account;
12978 ;; 3. Else, move up to direct parent and proceed only once.
12979 (while (and (setq level (org-up-heading-safe))
12980 (or recursive first)
12981 (>= (point) lim))
12982 (setq first nil cookie-present nil)
12983 (unless (and level
12984 (not (string-match
12985 "\\<checkbox\\>"
12986 (downcase (or (org-entry-get nil "COOKIE_DATA")
12987 "")))))
12988 (throw 'exit nil))
12989 (while (re-search-forward box-re (point-at-eol) t)
12990 (setq cnt-all 0 cnt-done 0 cookie-present t)
12991 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12992 (save-match-data
12993 (unless (outline-next-heading) (throw 'exit nil))
12994 (while (and (looking-at org-complex-heading-regexp)
12995 (> (setq l1 (length (match-string 1))) level))
12996 (setq kwd (and (or recursive (= l1 ltoggle))
12997 (match-string 2)))
12998 (if (or (eq org-provide-todo-statistics 'all-headlines)
12999 (and (eq org-provide-todo-statistics t)
13000 (or (member kwd org-done-keywords)))
13001 (and (listp org-provide-todo-statistics)
13002 (stringp (car org-provide-todo-statistics))
13003 (or (member kwd org-provide-todo-statistics)
13004 (member kwd org-done-keywords)))
13005 (and (listp org-provide-todo-statistics)
13006 (listp (car org-provide-todo-statistics))
13007 (or (member kwd (car org-provide-todo-statistics))
13008 (and (member kwd org-done-keywords)
13009 (member kwd (cadr org-provide-todo-statistics))))))
13010 (setq cnt-all (1+ cnt-all))
13011 (and (eq org-provide-todo-statistics t)
13013 (setq cnt-all (1+ cnt-all))))
13014 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
13015 (member kwd org-done-keywords))
13016 (and (listp org-provide-todo-statistics)
13017 (listp (car org-provide-todo-statistics))
13018 (member kwd org-done-keywords)
13019 (member kwd (cadr org-provide-todo-statistics)))
13020 (and (listp org-provide-todo-statistics)
13021 (stringp (car org-provide-todo-statistics))
13022 (member kwd org-done-keywords)))
13023 (setq cnt-done (1+ cnt-done)))
13024 (outline-next-heading)))
13025 (setq new
13026 (if is-percent
13027 (format "[%d%%]" (floor (* 100.0 cnt-done)
13028 (max 1 cnt-all)))
13029 (format "[%d/%d]" cnt-done cnt-all))
13030 ndel (- (match-end 0) checkbox-beg))
13031 (goto-char checkbox-beg)
13032 (insert new)
13033 (delete-region (point) (+ (point) ndel))
13034 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
13035 (when cookie-present
13036 (run-hook-with-args 'org-after-todo-statistics-hook
13037 cnt-done (- cnt-all cnt-done))))))
13038 (run-hooks 'org-todo-statistics-hook)))
13040 (defvar org-after-todo-statistics-hook nil
13041 "Hook that is called after a TODO statistics cookie has been updated.
13042 Each function is called with two arguments: the number of not-done entries
13043 and the number of done entries.
13045 For example, the following function, when added to this hook, will switch
13046 an entry to DONE when all children are done, and back to TODO when new
13047 entries are set to a TODO status. Note that this hook is only called
13048 when there is a statistics cookie in the headline!
13050 (defun org-summary-todo (n-done n-not-done)
13051 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13052 (let (org-log-done org-log-states) ; turn off logging
13053 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13056 (defvar org-todo-statistics-hook nil
13057 "Hook that is run whenever Org thinks TODO statistics should be updated.
13058 This hook runs even if there is no statistics cookie present, in which case
13059 `org-after-todo-statistics-hook' would not run.")
13061 (defun org-todo-trigger-tag-changes (state)
13062 "Apply the changes defined in `org-todo-state-tags-triggers'."
13063 (let ((l org-todo-state-tags-triggers)
13064 changes)
13065 (when (or (not state) (equal state ""))
13066 (setq changes (append changes (cdr (assoc "" l)))))
13067 (when (and (stringp state) (> (length state) 0))
13068 (setq changes (append changes (cdr (assoc state l)))))
13069 (when (member state org-not-done-keywords)
13070 (setq changes (append changes (cdr (assq 'todo l)))))
13071 (when (member state org-done-keywords)
13072 (setq changes (append changes (cdr (assq 'done l)))))
13073 (dolist (c changes)
13074 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13076 (defun org-local-logging (value)
13077 "Get logging settings from a property VALUE."
13078 ;; Directly set the variables, they are already local.
13079 (setq org-log-done nil
13080 org-log-repeat nil
13081 org-todo-log-states nil)
13082 (dolist (w (org-split-string value))
13083 (let (a)
13084 (cond
13085 ((setq a (assoc w org-startup-options))
13086 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13087 (set (nth 1 a) (nth 2 a))))
13088 ((setq a (org-extract-log-state-settings w))
13089 (and (member (car a) org-todo-keywords-1)
13090 (push a org-todo-log-states)))))))
13092 (defun org-get-todo-sequence-head (kwd)
13093 "Return the head of the TODO sequence to which KWD belongs.
13094 If KWD is not set, check if there is a text property remembering the
13095 right sequence."
13096 (let (p)
13097 (cond
13098 ((not kwd)
13099 (or (get-text-property (point-at-bol) 'org-todo-head)
13100 (progn
13101 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13102 nil (point-at-eol)))
13103 (get-text-property p 'org-todo-head))))
13104 ((not (member kwd org-todo-keywords-1))
13105 (car org-todo-keywords-1))
13106 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13108 (defun org-fast-todo-selection ()
13109 "Fast TODO keyword selection with single keys.
13110 Returns the new TODO keyword, or nil if no state change should occur."
13111 (let* ((fulltable org-todo-key-alist)
13112 (done-keywords org-done-keywords) ;; needed for the faces.
13113 (maxlen (apply 'max (mapcar
13114 (lambda (x)
13115 (if (stringp (car x)) (string-width (car x)) 0))
13116 fulltable)))
13117 (expert nil)
13118 (fwidth (+ maxlen 3 1 3))
13119 (ncol (/ (- (window-width) 4) fwidth))
13120 tg cnt e c tbl
13121 groups ingroup)
13122 (save-excursion
13123 (save-window-excursion
13124 (if expert
13125 (set-buffer (get-buffer-create " *Org todo*"))
13126 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13127 (erase-buffer)
13128 (setq-local org-done-keywords done-keywords)
13129 (setq tbl fulltable cnt 0)
13130 (while (setq e (pop tbl))
13131 (cond
13132 ((equal e '(:startgroup))
13133 (push '() groups) (setq ingroup t)
13134 (unless (= cnt 0)
13135 (setq cnt 0)
13136 (insert "\n"))
13137 (insert "{ "))
13138 ((equal e '(:endgroup))
13139 (setq ingroup nil cnt 0)
13140 (insert "}\n"))
13141 ((equal e '(:newline))
13142 (unless (= cnt 0)
13143 (setq cnt 0)
13144 (insert "\n")
13145 (setq e (car tbl))
13146 (while (equal (car tbl) '(:newline))
13147 (insert "\n")
13148 (setq tbl (cdr tbl)))))
13150 (setq tg (car e) c (cdr e))
13151 (when ingroup (push tg (car groups)))
13152 (setq tg (org-add-props tg nil 'face
13153 (org-get-todo-face tg)))
13154 (when (and (= cnt 0) (not ingroup)) (insert " "))
13155 (insert "[" c "] " tg (make-string
13156 (- fwidth 4 (length tg)) ?\ ))
13157 (when (= (setq cnt (1+ cnt)) ncol)
13158 (insert "\n")
13159 (when ingroup (insert " "))
13160 (setq cnt 0)))))
13161 (insert "\n")
13162 (goto-char (point-min))
13163 (unless expert (org-fit-window-to-buffer))
13164 (message "[a-z..]:Set [SPC]:clear")
13165 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13166 (cond
13167 ((or (= c ?\C-g)
13168 (and (= c ?q) (not (rassoc c fulltable))))
13169 (setq quit-flag t))
13170 ((= c ?\ ) nil)
13171 ((setq e (rassoc c fulltable) tg (car e))
13173 (t (setq quit-flag t)))))))
13175 (defun org-entry-is-todo-p ()
13176 (member (org-get-todo-state) org-not-done-keywords))
13178 (defun org-entry-is-done-p ()
13179 (member (org-get-todo-state) org-done-keywords))
13181 (defun org-get-todo-state ()
13182 "Return the TODO keyword of the current subtree."
13183 (save-excursion
13184 (org-back-to-heading t)
13185 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13186 (match-end 2)
13187 (match-string 2))))
13189 (defun org-at-date-range-p (&optional inactive-ok)
13190 "Non-nil if point is inside a date range.
13192 When optional argument INACTIVE-OK is non-nil, also consider
13193 inactive time ranges.
13195 When this function returns a non-nil value, match data is set
13196 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13197 on INACTIVE-OK."
13198 (interactive)
13199 (save-excursion
13200 (catch 'exit
13201 (let ((pos (point)))
13202 (skip-chars-backward "^[<\r\n")
13203 (skip-chars-backward "<[")
13204 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13205 (>= (match-end 0) pos)
13206 (throw 'exit t))
13207 (skip-chars-backward "^<[\r\n")
13208 (skip-chars-backward "<[")
13209 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13210 (>= (match-end 0) pos)
13211 (throw 'exit t)))
13212 nil)))
13214 (defun org-get-repeat (&optional tagline)
13215 "Check if there is a deadline/schedule with repeater in this entry."
13216 (save-match-data
13217 (save-excursion
13218 (org-back-to-heading t)
13219 (and (re-search-forward (if tagline
13220 (concat tagline "\\s-*" org-repeat-re)
13221 org-repeat-re)
13222 (org-entry-end-position) t)
13223 (match-string-no-properties 1)))))
13225 (defvar org-last-changed-timestamp)
13226 (defvar org-last-inserted-timestamp)
13227 (defvar org-log-post-message)
13228 (defvar org-log-note-purpose)
13229 (defvar org-log-note-how nil)
13230 (defvar org-log-note-extra)
13231 (defun org-auto-repeat-maybe (done-word)
13232 "Check if the current headline contains a repeated time-stamp.
13234 If yes, set TODO state back to what it was and change the base date
13235 of repeating deadline/scheduled time stamps to new date.
13237 This function is run automatically after each state change to a DONE state."
13238 (let* ((repeat (org-get-repeat))
13239 (aa (assoc org-last-state org-todo-kwd-alist))
13240 (interpret (nth 1 aa))
13241 (head (nth 2 aa))
13242 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13243 (msg "Entry repeats: ")
13244 (org-log-done nil)
13245 (org-todo-log-states nil))
13246 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13247 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13248 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13249 org-todo-repeat-to-state)))
13250 (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
13251 to-state)
13252 ((eq interpret 'type) org-last-state)
13253 (head)
13254 (t 'none))))
13255 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13256 (org-entry-put nil "LAST_REPEAT" (format-time-string
13257 (org-time-stamp-format t t))))
13258 (when org-log-repeat
13259 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13260 (memq 'org-add-log-note post-command-hook))
13261 ;; We are already setup for some record.
13262 (when (eq org-log-repeat 'note)
13263 ;; Make sure we take a note, not only a time stamp.
13264 (setq org-log-note-how 'note))
13265 ;; Set up for taking a record.
13266 (org-add-log-setup 'state
13267 (or done-word (car org-done-keywords))
13268 org-last-state
13269 org-log-repeat)))
13270 (org-back-to-heading t)
13271 (org-add-planning-info nil nil 'closed)
13272 (let ((end (save-excursion (outline-next-heading) (point)))
13273 (planning-re (regexp-opt
13274 (list org-scheduled-string org-deadline-string))))
13275 (while (re-search-forward org-ts-regexp end t)
13276 (let* ((ts (match-string 0))
13277 (planning? (org-at-planning-p))
13278 (type (if (not planning?) "Plain:"
13279 (save-excursion
13280 (re-search-backward
13281 planning-re (line-beginning-position) t)
13282 (match-string 0)))))
13283 (cond
13284 ;; Ignore fake time-stamps (e.g., within comments).
13285 ((and (not planning?)
13286 (not (org-at-property-p))
13287 (not (eq 'timestamp
13288 (org-element-type (save-excursion
13289 (backward-char)
13290 (org-element-context)))))))
13291 ;; Time-stamps without a repeater are usually skipped.
13292 ;; However, a SCHEDULED time-stamp without one is
13293 ;; removed, as it is considered as no longer relevant.
13294 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13295 (when (equal type org-scheduled-string)
13296 (org-remove-timestamp-with-keyword type)))
13298 (let ((n (string-to-number (match-string 2 ts)))
13299 (what (match-string 3 ts)))
13300 (when (equal what "w") (setq n (* n 7) what "d"))
13301 (when (and (equal what "h")
13302 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13303 ts)))
13304 (user-error
13305 "Cannot repeat in Repeat in %d hour(s) because no hour \
13306 has been set"
13308 ;; Preparation, see if we need to modify the start
13309 ;; date for the change.
13310 (when (match-end 1)
13311 (let ((time (save-match-data (org-time-string-to-time ts))))
13312 (cond
13313 ((equal (match-string 1 ts) ".")
13314 ;; Shift starting date to today
13315 (org-timestamp-change
13316 (- (org-today) (time-to-days time))
13317 'day))
13318 ((equal (match-string 1 ts) "+")
13319 (let ((nshiftmax 10)
13320 (nshift 0))
13321 (while (or (= nshift 0)
13322 (not (time-less-p (current-time) time)))
13323 (when (= (cl-incf nshift) nshiftmax)
13324 (or (y-or-n-p
13325 (format "%d repeater intervals were not \
13326 enough to shift date past today. Continue? "
13327 nshift))
13328 (user-error "Abort")))
13329 (org-timestamp-change n (cdr (assoc what whata)))
13330 (org-at-timestamp-p t)
13331 (setq ts (match-string 1))
13332 (setq time
13333 (save-match-data
13334 (org-time-string-to-time ts)))))
13335 (org-timestamp-change (- n) (cdr (assoc what whata)))
13336 ;; Rematch, so that we have everything in place
13337 ;; for the real shift.
13338 (org-at-timestamp-p t)
13339 (setq ts (match-string 1))
13340 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13341 ts)))))
13342 (save-excursion
13343 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13344 (setq msg
13345 (concat
13346 msg type " " org-last-changed-timestamp " "))))))))
13347 (setq org-log-post-message msg)
13348 (message "%s" msg))))
13350 (defun org-show-todo-tree (arg)
13351 "Make a compact tree which shows all headlines marked with TODO.
13352 The tree will show the lines where the regexp matches, and all higher
13353 headlines above the match.
13354 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13355 With a numeric prefix N, construct a sparse tree for the Nth element
13356 of `org-todo-keywords-1'."
13357 (interactive "P")
13358 (let ((case-fold-search nil)
13359 (kwd-re
13360 (cond ((null arg) org-not-done-regexp)
13361 ((equal arg '(4))
13362 (let ((kwd
13363 (completing-read "Keyword (or KWD1|KWD2|...): "
13364 (mapcar #'list org-todo-keywords-1))))
13365 (concat "\\("
13366 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13367 "\\)\\>")))
13368 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13369 (regexp-quote (nth (1- (prefix-numeric-value arg))
13370 org-todo-keywords-1)))
13371 (t (user-error "Invalid prefix argument: %s" arg)))))
13372 (message "%d TODO entries found"
13373 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13375 (defun org--deadline-or-schedule (arg type time)
13376 "Insert DEADLINE or SCHEDULE information in current entry.
13377 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13378 `org-schedule' for information about ARG and TIME arguments."
13379 (let* ((deadline? (eq type 'deadline))
13380 (keyword (if deadline? org-deadline-string org-scheduled-string))
13381 (log (if deadline? org-log-redeadline org-log-reschedule))
13382 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13383 (old-date-time (and old-date (org-time-string-to-time old-date)))
13384 ;; Save repeater cookie from either TIME or current scheduled
13385 ;; time stamp. We are going to insert it back at the end of
13386 ;; the process.
13387 (repeater (or (and (org-string-nw-p time)
13388 ;; We use `org-repeat-re' because we need
13389 ;; to tell the difference between a real
13390 ;; repeater and a time delta, e.g. "+2d".
13391 (string-match org-repeat-re time)
13392 (match-string 1 time))
13393 (and (org-string-nw-p old-date)
13394 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13395 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13396 old-date)
13397 (match-string 1 old-date)))))
13398 (pcase arg
13399 (`(4)
13400 (when (and old-date log)
13401 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13402 nil old-date log))
13403 (org-remove-timestamp-with-keyword keyword)
13404 (message (if deadline? "Item no longer has a deadline."
13405 "Item is no longer scheduled.")))
13406 (`(16)
13407 (save-excursion
13408 (org-back-to-heading t)
13409 (let ((regexp (if deadline? org-deadline-time-regexp
13410 org-scheduled-time-regexp)))
13411 (if (not (re-search-forward regexp (line-end-position 2) t))
13412 (user-error (if deadline? "No deadline information to update"
13413 "No scheduled information to update"))
13414 (let* ((rpl0 (match-string 1))
13415 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13416 (msg (if deadline? "Warn starting from" "Delay until")))
13417 (replace-match
13418 (concat keyword
13419 " <" rpl
13420 (format " -%dd"
13421 (abs (- (time-to-days
13422 (save-match-data
13423 (org-read-date
13424 nil t nil msg old-date-time)))
13425 (time-to-days old-date-time))))
13426 ">") t t))))))
13428 (org-add-planning-info type time 'closed)
13429 (when (and old-date
13431 (not (equal old-date org-last-inserted-timestamp)))
13432 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13433 org-last-inserted-timestamp
13434 old-date
13435 log))
13436 (when repeater
13437 (save-excursion
13438 (org-back-to-heading t)
13439 (when (re-search-forward
13440 (concat keyword " " org-last-inserted-timestamp)
13441 (line-end-position 2)
13443 (goto-char (1- (match-end 0)))
13444 (insert " " repeater)
13445 (setq org-last-inserted-timestamp
13446 (concat (substring org-last-inserted-timestamp 0 -1)
13447 " " repeater
13448 (substring org-last-inserted-timestamp -1))))))
13449 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13450 org-last-inserted-timestamp)))))
13452 (defun org-deadline (arg &optional time)
13453 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13454 With one universal prefix argument, remove any deadline from the item.
13455 With two universal prefix arguments, prompt for a warning delay.
13456 With argument TIME, set the deadline at the corresponding date. TIME
13457 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13458 (interactive "P")
13459 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13460 (org-map-entries
13461 (lambda () (org--deadline-or-schedule arg 'deadline time))
13463 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13464 'region-start-level
13465 'region)
13466 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13467 (org--deadline-or-schedule arg 'deadline time)))
13469 (defun org-schedule (arg &optional time)
13470 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13471 With one universal prefix argument, remove any scheduling date from the item.
13472 With two universal prefix arguments, prompt for a delay cookie.
13473 With argument TIME, scheduled at the corresponding date. TIME can
13474 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13475 (interactive "P")
13476 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13477 (org-map-entries
13478 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13480 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13481 'region-start-level
13482 'region)
13483 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13484 (org--deadline-or-schedule arg 'scheduled time)))
13486 (defun org-get-scheduled-time (pom &optional inherit)
13487 "Get the scheduled time as a time tuple, of a format suitable
13488 for calling org-schedule with, or if there is no scheduling,
13489 returns nil."
13490 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13491 (when time
13492 (apply 'encode-time (org-parse-time-string time)))))
13494 (defun org-get-deadline-time (pom &optional inherit)
13495 "Get the deadline as a time tuple, of a format suitable for
13496 calling org-deadline with, or if there is no scheduling, returns
13497 nil."
13498 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13499 (when time
13500 (apply 'encode-time (org-parse-time-string time)))))
13502 (defun org-remove-timestamp-with-keyword (keyword)
13503 "Remove all time stamps with KEYWORD in the current entry."
13504 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13505 beg)
13506 (save-excursion
13507 (org-back-to-heading t)
13508 (setq beg (point))
13509 (outline-next-heading)
13510 (while (re-search-backward re beg t)
13511 (replace-match "")
13512 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13513 (equal (char-before) ?\ ))
13514 (backward-delete-char 1)
13515 (when (string-match "^[ \t]*$" (buffer-substring
13516 (point-at-bol) (point-at-eol)))
13517 (delete-region (point-at-bol)
13518 (min (point-max) (1+ (point-at-eol))))))))))
13520 (defvar org-time-was-given) ; dynamically scoped parameter
13521 (defvar org-end-time-was-given) ; dynamically scoped parameter
13523 (defun org-at-planning-p ()
13524 "Non-nil when point is on a planning info line."
13525 ;; This is as accurate and faster than `org-element-at-point' since
13526 ;; planning info location is fixed in the section.
13527 (org-with-wide-buffer
13528 (beginning-of-line)
13529 (and (looking-at-p org-planning-line-re)
13530 (eq (point)
13531 (ignore-errors
13532 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13533 (org-back-to-heading t)
13534 (org-with-limited-levels (org-back-to-heading t)))
13535 (line-beginning-position 2))))))
13537 (defun org-add-planning-info (what &optional time &rest remove)
13538 "Insert new timestamp with keyword in the planning line.
13539 WHAT indicates what kind of time stamp to add. It is a symbol
13540 among `closed', `deadline', `scheduled' and nil. TIME indicates
13541 the time to use. If none is given, the user is prompted for
13542 a date. REMOVE indicates what kind of entries to remove. An old
13543 WHAT entry will also be removed."
13544 (let (org-time-was-given org-end-time-was-given default-time default-input)
13545 (catch 'exit
13546 (when (and (memq what '(scheduled deadline))
13547 (or (not time)
13548 (and (stringp time)
13549 (string-match "^[-+]+[0-9]" time))))
13550 ;; Try to get a default date/time from existing timestamp
13551 (save-excursion
13552 (org-back-to-heading t)
13553 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13554 (when (re-search-forward (if (eq what 'scheduled)
13555 org-scheduled-time-regexp
13556 org-deadline-time-regexp)
13557 end t)
13558 (setq ts (match-string 1)
13559 default-time (apply 'encode-time (org-parse-time-string ts))
13560 default-input (and ts (org-get-compact-tod ts)))))))
13561 (when what
13562 (setq time
13563 (if (stringp time)
13564 ;; This is a string (relative or absolute), set
13565 ;; proper date.
13566 (apply #'encode-time
13567 (org-read-date-analyze
13568 time default-time (decode-time default-time)))
13569 ;; If necessary, get the time from the user
13570 (or time (org-read-date nil 'to-time nil nil
13571 default-time default-input)))))
13573 (org-with-wide-buffer
13574 (org-back-to-heading t)
13575 (forward-line)
13576 (unless (bolp) (insert "\n"))
13577 (cond ((looking-at-p org-planning-line-re)
13578 ;; Move to current indentation.
13579 (skip-chars-forward " \t")
13580 ;; Check if we have to remove something.
13581 (dolist (type (if what (cons what remove) remove))
13582 (save-excursion
13583 (when (re-search-forward
13584 (cl-case type
13585 (closed org-closed-time-regexp)
13586 (deadline org-deadline-time-regexp)
13587 (scheduled org-scheduled-time-regexp)
13588 (otherwise
13589 (error "Invalid planning type: %s" type)))
13590 (line-end-position) t)
13591 ;; Delete until next keyword or end of line.
13592 (delete-region
13593 (match-beginning 0)
13594 (if (re-search-forward org-keyword-time-not-clock-regexp
13595 (line-end-position)
13597 (match-beginning 0)
13598 (line-end-position))))))
13599 ;; If there is nothing more to add and no more keyword
13600 ;; is left, remove the line completely.
13601 (if (and (looking-at-p "[ \t]*$") (not what))
13602 (delete-region (line-beginning-position)
13603 (line-beginning-position 2))
13604 ;; If we removed last keyword, do not leave trailing
13605 ;; white space at the end of line.
13606 (let ((p (point)))
13607 (save-excursion
13608 (end-of-line)
13609 (unless (= (skip-chars-backward " \t" p) 0)
13610 (delete-region (point) (line-end-position)))))))
13611 ((not what) (throw 'exit nil)) ; Nothing to do.
13612 (t (insert-before-markers "\n")
13613 (backward-char 1)
13614 (when org-adapt-indentation
13615 (indent-to-column (1+ (org-outline-level))))))
13616 (when what
13617 ;; Insert planning keyword.
13618 (insert (cl-case what
13619 (closed org-closed-string)
13620 (deadline org-deadline-string)
13621 (scheduled org-scheduled-string)
13622 (otherwise (error "Invalid planning type: %s" what)))
13623 " ")
13624 ;; Insert associated timestamp.
13625 (let ((ts (org-insert-time-stamp
13626 time
13627 (or org-time-was-given
13628 (and (eq what 'closed) org-log-done-with-time))
13629 (eq what 'closed)
13630 nil nil (list org-end-time-was-given))))
13631 (unless (eolp) (insert " "))
13632 ts))))))
13634 (defvar org-log-note-marker (make-marker)
13635 "Marker pointing at the entry where the note is to be inserted.")
13636 (defvar org-log-note-purpose nil)
13637 (defvar org-log-note-state nil)
13638 (defvar org-log-note-previous-state nil)
13639 (defvar org-log-note-extra nil)
13640 (defvar org-log-note-window-configuration nil)
13641 (defvar org-log-note-return-to (make-marker))
13642 (defvar org-log-note-effective-time nil
13643 "Remembered current time so that dynamically scoped
13644 `org-extend-today-until' affects timestamps in state change log")
13646 (defvar org-log-post-message nil
13647 "Message to be displayed after a log note has been stored.
13648 The auto-repeater uses this.")
13650 (defun org-add-note ()
13651 "Add a note to the current entry.
13652 This is done in the same way as adding a state change note."
13653 (interactive)
13654 (org-add-log-setup 'note))
13656 (defun org-log-beginning (&optional create)
13657 "Return expected start of log notes in current entry.
13658 When optional argument CREATE is non-nil, the function creates
13659 a drawer to store notes, if necessary. Returned position ignores
13660 narrowing."
13661 (org-with-wide-buffer
13662 (let ((drawer (org-log-into-drawer)))
13663 (cond
13664 (drawer
13665 (org-end-of-meta-data)
13666 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13667 (end (if (org-at-heading-p) (point)
13668 (save-excursion (outline-next-heading) (point))))
13669 (case-fold-search t))
13670 (catch 'exit
13671 ;; Try to find existing drawer.
13672 (while (re-search-forward regexp end t)
13673 (let ((element (org-element-at-point)))
13674 (when (eq (org-element-type element) 'drawer)
13675 (let ((cend (org-element-property :contents-end element)))
13676 (when (and (not org-log-states-order-reversed) cend)
13677 (goto-char cend)))
13678 (throw 'exit nil))))
13679 ;; No drawer found. Create one, if permitted.
13680 (when create
13681 (unless (bolp) (insert "\n"))
13682 (let ((beg (point)))
13683 (insert ":" drawer ":\n:END:\n")
13684 (org-indent-region beg (point)))
13685 (end-of-line -1)))))
13687 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13688 (skip-chars-forward " \t\n")
13689 (beginning-of-line)
13690 (unless org-log-states-order-reversed
13691 (org-skip-over-state-notes)
13692 (skip-chars-backward " \t\n")
13693 (forward-line)))))
13694 (if (bolp) (point) (line-beginning-position 2))))
13696 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13697 "Set up the post command hook to take a note.
13698 If this is about to TODO state change, the new state is expected in STATE.
13699 HOW is an indicator what kind of note should be created.
13700 EXTRA is additional text that will be inserted into the notes buffer."
13701 (move-marker org-log-note-marker (point))
13702 (setq org-log-note-purpose purpose
13703 org-log-note-state state
13704 org-log-note-previous-state prev-state
13705 org-log-note-how how
13706 org-log-note-extra extra
13707 org-log-note-effective-time (org-current-effective-time))
13708 (add-hook 'post-command-hook 'org-add-log-note 'append))
13710 (defun org-skip-over-state-notes ()
13711 "Skip past the list of State notes in an entry."
13712 (when (ignore-errors (goto-char (org-in-item-p)))
13713 (let* ((struct (org-list-struct))
13714 (prevs (org-list-prevs-alist struct))
13715 (regexp
13716 (concat "[ \t]*- +"
13717 (replace-regexp-in-string
13718 " +" " +"
13719 (org-replace-escapes
13720 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13721 `(("%d" . ,org-ts-regexp-inactive)
13722 ("%D" . ,org-ts-regexp)
13723 ("%s" . "\"\\S-+\"")
13724 ("%S" . "\"\\S-+\"")
13725 ("%t" . ,org-ts-regexp-inactive)
13726 ("%T" . ,org-ts-regexp)
13727 ("%u" . ".*?")
13728 ("%U" . ".*?")))))))
13729 (while (looking-at-p regexp)
13730 (goto-char (or (org-list-get-next-item (point) struct prevs)
13731 (org-list-get-item-end (point) struct)))))))
13733 (defun org-add-log-note (&optional _purpose)
13734 "Pop up a window for taking a note, and add this note later."
13735 (remove-hook 'post-command-hook 'org-add-log-note)
13736 (setq org-log-note-window-configuration (current-window-configuration))
13737 (delete-other-windows)
13738 (move-marker org-log-note-return-to (point))
13739 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13740 (goto-char org-log-note-marker)
13741 (org-switch-to-buffer-other-window "*Org Note*")
13742 (erase-buffer)
13743 (if (memq org-log-note-how '(time state))
13744 (let (current-prefix-arg) (org-store-log-note))
13745 (let ((org-inhibit-startup t)) (org-mode))
13746 (insert (format "# Insert note for %s.
13747 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13748 (cond
13749 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13750 ((eq org-log-note-purpose 'done) "closed todo item")
13751 ((eq org-log-note-purpose 'state)
13752 (format "state change from \"%s\" to \"%s\""
13753 (or org-log-note-previous-state "")
13754 (or org-log-note-state "")))
13755 ((eq org-log-note-purpose 'reschedule)
13756 "rescheduling")
13757 ((eq org-log-note-purpose 'delschedule)
13758 "no longer scheduled")
13759 ((eq org-log-note-purpose 'redeadline)
13760 "changing deadline")
13761 ((eq org-log-note-purpose 'deldeadline)
13762 "removing deadline")
13763 ((eq org-log-note-purpose 'refile)
13764 "refiling")
13765 ((eq org-log-note-purpose 'note)
13766 "this entry")
13767 (t (error "This should not happen")))))
13768 (when org-log-note-extra (insert org-log-note-extra))
13769 (setq-local org-finish-function 'org-store-log-note)
13770 (run-hooks 'org-log-buffer-setup-hook)))
13772 (defvar org-note-abort nil) ; dynamically scoped
13773 (defun org-store-log-note ()
13774 "Finish taking a log note, and insert it to where it belongs."
13775 (let ((txt (prog1 (buffer-string)
13776 (kill-buffer)))
13777 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13778 lines)
13779 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13780 (setq txt (replace-match "" t t txt)))
13781 (when (string-match "\\s-+\\'" txt)
13782 (setq txt (replace-match "" t t txt)))
13783 (setq lines (org-split-string txt "\n"))
13784 (when (org-string-nw-p note)
13785 (setq note
13786 (org-replace-escapes
13787 note
13788 (list (cons "%u" (user-login-name))
13789 (cons "%U" user-full-name)
13790 (cons "%t" (format-time-string
13791 (org-time-stamp-format 'long 'inactive)
13792 org-log-note-effective-time))
13793 (cons "%T" (format-time-string
13794 (org-time-stamp-format 'long nil)
13795 org-log-note-effective-time))
13796 (cons "%d" (format-time-string
13797 (org-time-stamp-format nil 'inactive)
13798 org-log-note-effective-time))
13799 (cons "%D" (format-time-string
13800 (org-time-stamp-format nil nil)
13801 org-log-note-effective-time))
13802 (cons "%s" (cond
13803 ((not org-log-note-state) "")
13804 ((string-match-p org-ts-regexp
13805 org-log-note-state)
13806 (format "\"[%s]\""
13807 (substring org-log-note-state 1 -1)))
13808 (t (format "\"%s\"" org-log-note-state))))
13809 (cons "%S"
13810 (cond
13811 ((not org-log-note-previous-state) "")
13812 ((string-match-p org-ts-regexp
13813 org-log-note-previous-state)
13814 (format "\"[%s]\""
13815 (substring
13816 org-log-note-previous-state 1 -1)))
13817 (t (format "\"%s\""
13818 org-log-note-previous-state)))))))
13819 (when lines (setq note (concat note " \\\\")))
13820 (push note lines))
13821 (when (and lines (not (or current-prefix-arg org-note-abort)))
13822 (with-current-buffer (marker-buffer org-log-note-marker)
13823 (org-with-wide-buffer
13824 ;; Find location for the new note.
13825 (goto-char org-log-note-marker)
13826 (set-marker org-log-note-marker nil)
13827 ;; Note associated to a clock is to be located right after
13828 ;; the clock. Do not move point.
13829 (unless (eq org-log-note-purpose 'clock-out)
13830 (goto-char (org-log-beginning t)))
13831 ;; Make sure point is at the beginning of an empty line.
13832 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13833 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13834 ;; In an existing list, add a new item at the top level.
13835 ;; Otherwise, indent line like a regular one.
13836 (let ((itemp (org-in-item-p)))
13837 (if itemp
13838 (indent-line-to
13839 (let ((struct (save-excursion
13840 (goto-char itemp) (org-list-struct))))
13841 (org-list-get-ind (org-list-get-top-point struct) struct)))
13842 (org-indent-line)))
13843 (insert (org-list-bullet-string "-") (pop lines))
13844 (let ((ind (org-list-item-body-column (line-beginning-position))))
13845 (dolist (line lines)
13846 (insert "\n")
13847 (indent-line-to ind)
13848 (insert line)))
13849 (message "Note stored")
13850 (org-back-to-heading t)
13851 (org-cycle-hide-drawers 'children))
13852 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13853 ;; from within `org-add-log-note' because `buffer-undo-list'
13854 ;; is then modified outside of `org-with-remote-undo'.
13855 (when (eq this-command 'org-agenda-todo)
13856 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13857 ;; Don't add undo information when called from `org-agenda-todo'.
13858 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13859 (set-window-configuration org-log-note-window-configuration)
13860 (with-current-buffer (marker-buffer org-log-note-return-to)
13861 (goto-char org-log-note-return-to))
13862 (move-marker org-log-note-return-to nil)
13863 (when org-log-post-message (message "%s" org-log-post-message))))
13865 (defun org-remove-empty-drawer-at (pos)
13866 "Remove an empty drawer at position POS.
13867 POS may also be a marker."
13868 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13869 (org-with-wide-buffer
13870 (goto-char pos)
13871 (let ((drawer (org-element-at-point)))
13872 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13873 (not (org-element-property :contents-begin drawer)))
13874 (delete-region (org-element-property :begin drawer)
13875 (progn (goto-char (org-element-property :end drawer))
13876 (skip-chars-backward " \r\t\n")
13877 (forward-line)
13878 (point))))))))
13880 (defvar org-ts-type nil)
13881 (defun org-sparse-tree (&optional arg type)
13882 "Create a sparse tree, prompt for the details.
13883 This command can create sparse trees. You first need to select the type
13884 of match used to create the tree:
13886 t Show all TODO entries.
13887 T Show entries with a specific TODO keyword.
13888 m Show entries selected by a tags/property match.
13889 p Enter a property name and its value (both with completion on existing
13890 names/values) and show entries with that property.
13891 r Show entries matching a regular expression (`/' can be used as well).
13892 b Show deadlines and scheduled items before a date.
13893 a Show deadlines and scheduled items after a date.
13894 d Show deadlines due within `org-deadline-warning-days'.
13895 D Show deadlines and scheduled items between a date range."
13896 (interactive "P")
13897 (setq type (or type org-sparse-tree-default-date-type))
13898 (setq org-ts-type type)
13899 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13900 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13901 \[c]ycle through date types: %s"
13902 (cl-case type
13903 (all "all timestamps")
13904 (scheduled "only scheduled")
13905 (deadline "only deadline")
13906 (active "only active timestamps")
13907 (inactive "only inactive timestamps")
13908 (closed "with a closed time-stamp")
13909 (otherwise "scheduled/deadline")))
13910 (let ((answer (read-char-exclusive)))
13911 (cl-case answer
13913 (org-sparse-tree
13915 (cadr
13916 (memq type '(nil all scheduled deadline active inactive closed)))))
13917 (?d (call-interactively 'org-check-deadlines))
13918 (?b (call-interactively 'org-check-before-date))
13919 (?a (call-interactively 'org-check-after-date))
13920 (?D (call-interactively 'org-check-dates-range))
13921 (?t (call-interactively 'org-show-todo-tree))
13922 (?T (org-show-todo-tree '(4)))
13923 (?m (call-interactively 'org-match-sparse-tree))
13924 ((?p ?P)
13925 (let* ((kwd (completing-read
13926 "Property: " (mapcar #'list (org-buffer-property-keys))))
13927 (value (completing-read
13928 "Value: " (mapcar #'list (org-property-values kwd)))))
13929 (unless (string-match "\\`{.*}\\'" value)
13930 (setq value (concat "\"" value "\"")))
13931 (org-match-sparse-tree arg (concat kwd "=" value))))
13932 ((?r ?R ?/) (call-interactively 'org-occur))
13933 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13935 (defvar-local org-occur-highlights nil
13936 "List of overlays used for occur matches.")
13937 (defvar-local org-occur-parameters nil
13938 "Parameters of the active org-occur calls.
13939 This is a list, each call to org-occur pushes as cons cell,
13940 containing the regular expression and the callback, onto the list.
13941 The list can contain several entries if `org-occur' has been called
13942 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13943 will only contain one set of parameters. When the highlights are
13944 removed (for example with `C-c C-c', or with the next edit (depending
13945 on `org-remove-highlights-with-change'), this variable is emptied
13946 as well.")
13948 (defun org-occur (regexp &optional keep-previous callback)
13949 "Make a compact tree which shows all matches of REGEXP.
13951 The tree will show the lines where the regexp matches, and any other context
13952 defined in `org-show-context-detail', which see.
13954 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13955 done by a previous call to `org-occur' will be kept, to allow stacking of
13956 calls to this command.
13958 Optional argument CALLBACK can be a function of no argument. In this case,
13959 it is called with point at the end of the match, match data being set
13960 accordingly. Current match is shown only if the return value is non-nil.
13961 The function must neither move point nor alter narrowing."
13962 (interactive "sRegexp: \nP")
13963 (when (equal regexp "")
13964 (user-error "Regexp cannot be empty"))
13965 (unless keep-previous
13966 (org-remove-occur-highlights nil nil t))
13967 (push (cons regexp callback) org-occur-parameters)
13968 (let ((cnt 0))
13969 (save-excursion
13970 (goto-char (point-min))
13971 (when (or (not keep-previous) ; do not want to keep
13972 (not org-occur-highlights)) ; no previous matches
13973 ;; hide everything
13974 (org-overview))
13975 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13976 (isearch-no-upper-case-p regexp t)
13977 org-occur-case-fold-search)))
13978 (while (re-search-forward regexp nil t)
13979 (when (or (not callback)
13980 (save-match-data (funcall callback)))
13981 (setq cnt (1+ cnt))
13982 (when org-highlight-sparse-tree-matches
13983 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13984 (org-show-context 'occur-tree)))))
13985 (when org-remove-highlights-with-change
13986 (add-hook 'before-change-functions 'org-remove-occur-highlights
13987 nil 'local))
13988 (unless org-sparse-tree-open-archived-trees
13989 (org-hide-archived-subtrees (point-min) (point-max)))
13990 (run-hooks 'org-occur-hook)
13991 (when (called-interactively-p 'interactive)
13992 (message "%d match(es) for regexp %s" cnt regexp))
13993 cnt))
13995 (defun org-occur-next-match (&optional n _reset)
13996 "Function for `next-error-function' to find sparse tree matches.
13997 N is the number of matches to move, when negative move backwards.
13998 This function always goes back to the starting point when no
13999 match is found."
14000 (let* ((limit (if (< n 0) (point-min) (point-max)))
14001 (search-func (if (< n 0)
14002 'previous-single-char-property-change
14003 'next-single-char-property-change))
14004 (n (abs n))
14005 (pos (point))
14007 (catch 'exit
14008 (while (setq p1 (funcall search-func (point) 'org-type))
14009 (when (equal p1 limit)
14010 (goto-char pos)
14011 (user-error "No more matches"))
14012 (when (equal (get-char-property p1 'org-type) 'org-occur)
14013 (setq n (1- n))
14014 (when (= n 0)
14015 (goto-char p1)
14016 (throw 'exit (point))))
14017 (goto-char p1))
14018 (goto-char p1)
14019 (user-error "No more matches"))))
14021 (defun org-show-context (&optional key)
14022 "Make sure point and context are visible.
14023 Optional argument KEY, when non-nil, is a symbol. See
14024 `org-show-context-detail' for allowed values and how much is to
14025 be shown."
14026 (org-show-set-visibility
14027 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14028 ((cdr (assq key org-show-context-detail)))
14029 (t (cdr (assq 'default org-show-context-detail))))))
14031 (defun org-show-set-visibility (detail)
14032 "Set visibility around point according to DETAIL.
14033 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14034 `tree', `canonical' or t. See `org-show-context-detail' for more
14035 information."
14036 ;; Show current heading and possibly its entry, following headline
14037 ;; or all children.
14038 (if (and (org-at-heading-p) (not (eq detail 'local)))
14039 (org-flag-heading nil)
14040 (org-show-entry)
14041 ;; If point is hidden within a drawer or a block, make sure to
14042 ;; expose it.
14043 (dolist (o (overlays-at (point)))
14044 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14045 (delete-overlay o)))
14046 (unless (org-before-first-heading-p)
14047 (org-with-limited-levels
14048 (cl-case detail
14049 ((tree canonical t) (org-show-children))
14050 ((nil minimal ancestors))
14051 (t (save-excursion
14052 (outline-next-heading)
14053 (org-flag-heading nil)))))))
14054 ;; Show all siblings.
14055 (when (eq detail 'lineage) (org-show-siblings))
14056 ;; Show ancestors, possibly with their children.
14057 (when (memq detail '(ancestors lineage tree canonical t))
14058 (save-excursion
14059 (while (org-up-heading-safe)
14060 (org-flag-heading nil)
14061 (when (memq detail '(canonical t)) (org-show-entry))
14062 (when (memq detail '(tree canonical t)) (org-show-children))))))
14064 (defvar org-reveal-start-hook nil
14065 "Hook run before revealing a location.")
14067 (defun org-reveal (&optional siblings)
14068 "Show current entry, hierarchy above it, and the following headline.
14070 This can be used to show a consistent set of context around
14071 locations exposed with `org-show-context'.
14073 With optional argument SIBLINGS, on each level of the hierarchy all
14074 siblings are shown. This repairs the tree structure to what it would
14075 look like when opened with hierarchical calls to `org-cycle'.
14077 With a \\[universal-argument] \\[universal-argument] prefix, \
14078 go to the parent and show the entire tree."
14079 (interactive "P")
14080 (run-hooks 'org-reveal-start-hook)
14081 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14082 ((equal siblings '(16))
14083 (save-excursion
14084 (when (org-up-heading-safe)
14085 (org-show-subtree)
14086 (run-hook-with-args 'org-cycle-hook 'subtree))))
14087 (t (org-show-set-visibility 'lineage))))
14089 (defun org-highlight-new-match (beg end)
14090 "Highlight from BEG to END and mark the highlight is an occur headline."
14091 (let ((ov (make-overlay beg end)))
14092 (overlay-put ov 'face 'secondary-selection)
14093 (overlay-put ov 'org-type 'org-occur)
14094 (push ov org-occur-highlights)))
14096 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14097 "Remove the occur highlights from the buffer.
14098 BEG and END are ignored. If NOREMOVE is nil, remove this function
14099 from the `before-change-functions' in the current buffer."
14100 (interactive)
14101 (unless org-inhibit-highlight-removal
14102 (mapc #'delete-overlay org-occur-highlights)
14103 (setq org-occur-highlights nil)
14104 (setq org-occur-parameters nil)
14105 (unless noremove
14106 (remove-hook 'before-change-functions
14107 'org-remove-occur-highlights 'local))))
14109 ;;;; Priorities
14111 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14112 "Regular expression matching the priority indicator.")
14114 (defvar org-remove-priority-next-time nil)
14116 (defun org-priority-up ()
14117 "Increase the priority of the current item."
14118 (interactive)
14119 (org-priority 'up))
14121 (defun org-priority-down ()
14122 "Decrease the priority of the current item."
14123 (interactive)
14124 (org-priority 'down))
14126 (defun org-priority (&optional action _show)
14127 "Change the priority of an item.
14128 ACTION can be `set', `up', `down', or a character."
14129 (interactive "P")
14130 (if (equal action '(4))
14131 (org-show-priority)
14132 (unless org-enable-priority-commands
14133 (user-error "Priority commands are disabled"))
14134 (setq action (or action 'set))
14135 (let (current new news have remove)
14136 (save-excursion
14137 (org-back-to-heading t)
14138 (when (looking-at org-priority-regexp)
14139 (setq current (string-to-char (match-string 2))
14140 have t))
14141 (cond
14142 ((eq action 'remove)
14143 (setq remove t new ?\ ))
14144 ((or (eq action 'set)
14145 (integerp action))
14146 (if (not (eq action 'set))
14147 (setq new action)
14148 (message "Priority %c-%c, SPC to remove: "
14149 org-highest-priority org-lowest-priority)
14150 (save-match-data
14151 (setq new (read-char-exclusive))))
14152 (when (and (= (upcase org-highest-priority) org-highest-priority)
14153 (= (upcase org-lowest-priority) org-lowest-priority))
14154 (setq new (upcase new)))
14155 (cond ((equal new ?\ ) (setq remove t))
14156 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14157 (user-error "Priority must be between `%c' and `%c'"
14158 org-highest-priority org-lowest-priority))))
14159 ((eq action 'up)
14160 (setq new (if have
14161 (1- current) ; normal cycling
14162 ;; last priority was empty
14163 (if (eq last-command this-command)
14164 org-lowest-priority ; wrap around empty to lowest
14165 ;; default
14166 (if org-priority-start-cycle-with-default
14167 org-default-priority
14168 (1- org-default-priority))))))
14169 ((eq action 'down)
14170 (setq new (if have
14171 (1+ current) ; normal cycling
14172 ;; last priority was empty
14173 (if (eq last-command this-command)
14174 org-highest-priority ; wrap around empty to highest
14175 ;; default
14176 (if org-priority-start-cycle-with-default
14177 org-default-priority
14178 (1+ org-default-priority))))))
14179 (t (user-error "Invalid action")))
14180 (when (or (< (upcase new) org-highest-priority)
14181 (> (upcase new) org-lowest-priority))
14182 (if (and (memq action '(up down))
14183 (not have) (not (eq last-command this-command)))
14184 ;; `new' is from default priority
14185 (error
14186 "The default can not be set, see `org-default-priority' why")
14187 ;; normal cycling: `new' is beyond highest/lowest priority
14188 ;; and is wrapped around to the empty priority
14189 (setq remove t)))
14190 (setq news (format "%c" new))
14191 (if have
14192 (if remove
14193 (replace-match "" t t nil 1)
14194 (replace-match news t t nil 2))
14195 (if remove
14196 (user-error "No priority cookie found in line")
14197 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14198 (if (match-end 2)
14199 (progn
14200 (goto-char (match-end 2))
14201 (insert " [#" news "]"))
14202 (goto-char (match-beginning 3))
14203 (insert "[#" news "] "))))
14204 (org-set-tags nil 'align))
14205 (if remove
14206 (message "Priority removed")
14207 (message "Priority of current item set to %s" news)))))
14209 (defun org-show-priority ()
14210 "Show the priority of the current item.
14211 This priority is composed of the main priority given with the [#A] cookies,
14212 and by additional input from the age of a schedules or deadline entry."
14213 (interactive)
14214 (let ((pri (if (eq major-mode 'org-agenda-mode)
14215 (org-get-at-bol 'priority)
14216 (save-excursion
14217 (save-match-data
14218 (beginning-of-line)
14219 (and (looking-at org-heading-regexp)
14220 (org-get-priority (match-string 0))))))))
14221 (message "Priority is %d" (if pri pri -1000))))
14223 (defun org-get-priority (s)
14224 "Find priority cookie and return priority."
14225 (save-match-data
14226 (if (functionp org-get-priority-function)
14227 (funcall org-get-priority-function)
14228 (if (not (string-match org-priority-regexp s))
14229 (* 1000 (- org-lowest-priority org-default-priority))
14230 (* 1000 (- org-lowest-priority
14231 (string-to-char (match-string 2 s))))))))
14233 ;;;; Tags
14235 (defvar org-agenda-archives-mode)
14236 (defvar org-map-continue-from nil
14237 "Position from where mapping should continue.
14238 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14240 (defvar org-scanner-tags nil
14241 "The current tag list while the tags scanner is running.")
14243 (defvar org-trust-scanner-tags nil
14244 "Should `org-get-tags-at' use the tags for the scanner.
14245 This is for internal dynamical scoping only.
14246 When this is non-nil, the function `org-get-tags-at' will return the value
14247 of `org-scanner-tags' instead of building the list by itself. This
14248 can lead to large speed-ups when the tags scanner is used in a file with
14249 many entries, and when the list of tags is retrieved, for example to
14250 obtain a list of properties. Building the tags list for each entry in such
14251 a file becomes an N^2 operation - but with this variable set, it scales
14252 as N.")
14254 (defvar org--matcher-tags-todo-only nil)
14256 (defun org-scan-tags (action matcher todo-only &optional start-level)
14257 "Scan headline tags with inheritance and produce output ACTION.
14259 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14260 or `agenda' to produce an entry list for an agenda view. It can also be
14261 a Lisp form or a function that should be called at each matched headline, in
14262 this case the return value is a list of all return values from these calls.
14264 MATCHER is a function accepting three arguments, returning
14265 a non-nil value whenever a given set of tags qualifies a headline
14266 for inclusion. See `org-make-tags-matcher' for more information.
14267 As a special case, it can also be set to t (respectively nil) in
14268 order to match all (respectively none) headline.
14270 When TODO-ONLY is non-nil, only lines with a not-done TODO
14271 keyword are included in the output.
14273 START-LEVEL can be a string with asterisks, reducing the scope to
14274 headlines matching this string."
14275 (require 'org-agenda)
14276 (let* ((re (concat "^"
14277 (if start-level
14278 ;; Get the correct level to match
14279 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14280 org-outline-regexp)
14281 " *\\(\\<\\("
14282 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14283 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14284 (props (list 'face 'default
14285 'done-face 'org-agenda-done
14286 'undone-face 'default
14287 'mouse-face 'highlight
14288 'org-not-done-regexp org-not-done-regexp
14289 'org-todo-regexp org-todo-regexp
14290 'org-complex-heading-regexp org-complex-heading-regexp
14291 'help-echo
14292 (format "mouse-2 or RET jump to org file %s"
14293 (abbreviate-file-name
14294 (or (buffer-file-name (buffer-base-buffer))
14295 (buffer-name (buffer-base-buffer)))))))
14296 (org-map-continue-from nil)
14297 lspos tags tags-list
14298 (tags-alist (list (cons 0 org-file-tags)))
14299 (llast 0) rtn rtn1 level category i txt
14300 todo marker entry priority
14301 ts-date ts-date-type ts-date-pair)
14302 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14303 (setq action (list 'lambda nil action)))
14304 (save-excursion
14305 (goto-char (point-min))
14306 (when (eq action 'sparse-tree)
14307 (org-overview)
14308 (org-remove-occur-highlights))
14309 (while (let (case-fold-search)
14310 (re-search-forward re nil t))
14311 (setq org-map-continue-from nil)
14312 (catch :skip
14313 (setq todo
14314 ;; TODO: is the 1-2 difference a bug?
14315 (when (match-end 1) (match-string-no-properties 2))
14316 tags (when (match-end 4) (match-string-no-properties 4)))
14317 (goto-char (setq lspos (match-beginning 0)))
14318 (setq level (org-reduced-level (org-outline-level))
14319 category (org-get-category))
14320 (when (eq action 'agenda)
14321 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14322 ts-date (car ts-date-pair)
14323 ts-date-type (cdr ts-date-pair)))
14324 (setq i llast llast level)
14325 ;; remove tag lists from same and sublevels
14326 (while (>= i level)
14327 (when (setq entry (assoc i tags-alist))
14328 (setq tags-alist (delete entry tags-alist)))
14329 (setq i (1- i)))
14330 ;; add the next tags
14331 (when tags
14332 (setq tags (org-split-string tags ":")
14333 tags-alist
14334 (cons (cons level tags) tags-alist)))
14335 ;; compile tags for current headline
14336 (setq tags-list
14337 (if org-use-tag-inheritance
14338 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14339 tags)
14340 org-scanner-tags tags-list)
14341 (when org-use-tag-inheritance
14342 (setcdr (car tags-alist)
14343 (mapcar (lambda (x)
14344 (setq x (copy-sequence x))
14345 (org-add-prop-inherited x))
14346 (cdar tags-alist))))
14347 (when (and tags org-use-tag-inheritance
14348 (or (not (eq t org-use-tag-inheritance))
14349 org-tags-exclude-from-inheritance))
14350 ;; Selective inheritance, remove uninherited ones.
14351 (setcdr (car tags-alist)
14352 (org-remove-uninherited-tags (cdar tags-alist))))
14353 (when (and
14355 ;; eval matcher only when the todo condition is OK
14356 (and (or (not todo-only) (member todo org-not-done-keywords))
14357 (if (functionp matcher)
14358 (let ((case-fold-search t) (org-trust-scanner-tags t))
14359 (funcall matcher todo tags-list level))
14360 matcher))
14362 ;; Call the skipper, but return t if it does not
14363 ;; skip, so that the `and' form continues evaluating.
14364 (progn
14365 (unless (eq action 'sparse-tree) (org-agenda-skip))
14368 ;; Check if timestamps are deselecting this entry
14369 (or (not todo-only)
14370 (and (member todo org-not-done-keywords)
14371 (or (not org-agenda-tags-todo-honor-ignore-options)
14372 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14374 ;; select this headline
14375 (cond
14376 ((eq action 'sparse-tree)
14377 (and org-highlight-sparse-tree-matches
14378 (org-get-heading) (match-end 0)
14379 (org-highlight-new-match
14380 (match-beginning 1) (match-end 1)))
14381 (org-show-context 'tags-tree))
14382 ((eq action 'agenda)
14383 (setq txt (org-agenda-format-item
14385 (concat
14386 (if (eq org-tags-match-list-sublevels 'indented)
14387 (make-string (1- level) ?.) "")
14388 (org-get-heading))
14389 (make-string level ?\s)
14390 category
14391 tags-list)
14392 priority (org-get-priority txt))
14393 (goto-char lspos)
14394 (setq marker (org-agenda-new-marker))
14395 (org-add-props txt props
14396 'org-marker marker 'org-hd-marker marker 'org-category category
14397 'todo-state todo
14398 'ts-date ts-date
14399 'priority priority
14400 'type (concat "tagsmatch" ts-date-type))
14401 (push txt rtn))
14402 ((functionp action)
14403 (setq org-map-continue-from nil)
14404 (save-excursion
14405 (setq rtn1 (funcall action))
14406 (push rtn1 rtn)))
14407 (t (user-error "Invalid action")))
14409 ;; if we are to skip sublevels, jump to end of subtree
14410 (unless org-tags-match-list-sublevels
14411 (org-end-of-subtree t)
14412 (backward-char 1))))
14413 ;; Get the correct position from where to continue
14414 (if org-map-continue-from
14415 (goto-char org-map-continue-from)
14416 (and (= (point) lspos) (end-of-line 1)))))
14417 (when (and (eq action 'sparse-tree)
14418 (not org-sparse-tree-open-archived-trees))
14419 (org-hide-archived-subtrees (point-min) (point-max)))
14420 (nreverse rtn)))
14422 (defun org-remove-uninherited-tags (tags)
14423 "Remove all tags that are not inherited from the list TAGS."
14424 (cond
14425 ((eq org-use-tag-inheritance t)
14426 (if org-tags-exclude-from-inheritance
14427 (org-delete-all org-tags-exclude-from-inheritance tags)
14428 tags))
14429 ((not org-use-tag-inheritance) nil)
14430 ((stringp org-use-tag-inheritance)
14431 (delq nil (mapcar
14432 (lambda (x)
14433 (if (and (string-match org-use-tag-inheritance x)
14434 (not (member x org-tags-exclude-from-inheritance)))
14435 x nil))
14436 tags)))
14437 ((listp org-use-tag-inheritance)
14438 (delq nil (mapcar
14439 (lambda (x)
14440 (if (member x org-use-tag-inheritance) x nil))
14441 tags)))))
14443 (defun org-match-sparse-tree (&optional todo-only match)
14444 "Create a sparse tree according to tags string MATCH.
14446 MATCH is a string with match syntax. It can contain a selection
14447 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14448 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14449 those. See the manual for details.
14451 If optional argument TODO-ONLY is non-nil, only select lines that
14452 are also TODO tasks."
14453 (interactive "P")
14454 (org-agenda-prepare-buffers (list (current-buffer)))
14455 (let ((org--matcher-tags-todo-only todo-only))
14456 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14457 org--matcher-tags-todo-only)))
14459 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14461 (defvar org-cached-props nil)
14462 (defun org-cached-entry-get (pom property)
14463 (if (or (eq t org-use-property-inheritance)
14464 (and (stringp org-use-property-inheritance)
14465 (let ((case-fold-search t))
14466 (string-match-p org-use-property-inheritance property)))
14467 (and (listp org-use-property-inheritance)
14468 (member-ignore-case property org-use-property-inheritance)))
14469 ;; Caching is not possible, check it directly.
14470 (org-entry-get pom property 'inherit)
14471 ;; Get all properties, so we can do complicated checks easily.
14472 (cdr (assoc-string property
14473 (or org-cached-props
14474 (setq org-cached-props (org-entry-properties pom)))
14475 t))))
14477 (defun org-global-tags-completion-table (&optional files)
14478 "Return the list of all tags in all agenda buffer/files.
14479 Optional FILES argument is a list of files which can be used
14480 instead of the agenda files."
14481 (save-excursion
14482 (org-uniquify
14483 (delq nil
14484 (apply #'append
14485 (mapcar
14486 (lambda (file)
14487 (set-buffer (find-file-noselect file))
14488 (mapcar (lambda (x)
14489 (and (stringp (car-safe x))
14490 (list (car-safe x))))
14491 (or org-current-tag-alist (org-get-buffer-tags))))
14492 (if (car-safe files) files
14493 (org-agenda-files))))))))
14495 (defun org-make-tags-matcher (match)
14496 "Create the TAGS/TODO matcher form for the selection string MATCH.
14498 Returns a cons of the selection string MATCH and a function
14499 implementing the matcher.
14501 The matcher is to be called at an Org entry, with point on the
14502 headline, and returns non-nil if the entry matches the selection
14503 string MATCH. It must be called with three arguments: the TODO
14504 keyword at the entry (or nil if none), the list of all tags at
14505 the entry including inherited ones and the reduced level of the
14506 headline. Additionally, the category of the entry, if any, must
14507 be specified as the text property `org-category' on the headline.
14509 This function sets the variable `org--matcher-tags-todo-only' to
14510 a non-nil value if the matcher restricts matching to TODO
14511 entries, otherwise it is not touched.
14513 See also `org-scan-tags'."
14514 (unless match
14515 ;; Get a new match request, with completion against the global
14516 ;; tags table and the local tags in current buffer.
14517 (let ((org-last-tags-completion-table
14518 (org-uniquify
14519 (delq nil (append (org-get-buffer-tags)
14520 (org-global-tags-completion-table))))))
14521 (setq match
14522 (completing-read
14523 "Match: "
14524 'org-tags-completion-function nil nil nil 'org-tags-history))))
14526 (let ((match0 match)
14527 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14528 (start 0)
14529 tagsmatch todomatch tagsmatcher todomatcher)
14531 ;; Expand group tags.
14532 (setq match (org-tags-expand match))
14534 ;; Check if there is a TODO part of this match, which would be the
14535 ;; part after a "/". To make sure that this slash is not part of
14536 ;; a property value to be matched against, we also check that
14537 ;; there is no / after that slash. First, find the last slash.
14538 (let ((s 0))
14539 (while (string-match "/+" match s)
14540 (setq start (match-beginning 0))
14541 (setq s (match-end 0))))
14542 (if (and (string-match "/+" match start)
14543 (not (string-match-p "\"" match start)))
14544 ;; Match contains also a TODO-matching request.
14545 (progn
14546 (setq tagsmatch (substring match 0 (match-beginning 0)))
14547 (setq todomatch (substring match (match-end 0)))
14548 (when (string-prefix-p "!" todomatch)
14549 (setq org--matcher-tags-todo-only t)
14550 (setq todomatch (substring todomatch 1)))
14551 (when (string-match "\\`\\s-*\\'" todomatch)
14552 (setq todomatch nil)))
14553 ;; Only matching tags.
14554 (setq tagsmatch match)
14555 (setq todomatch nil))
14557 ;; Make the tags matcher.
14558 (when (org-string-nw-p tagsmatch)
14559 (let ((orlist nil)
14560 (orterms (org-split-string tagsmatch "|"))
14561 term)
14562 (while (setq term (pop orterms))
14563 (while (and (equal (substring term -1) "\\") orterms)
14564 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14565 (while (string-match re term)
14566 (let* ((rest (substring term (match-end 0)))
14567 (minus (and (match-end 1)
14568 (equal (match-string 1 term) "-")))
14569 (tag (save-match-data
14570 (replace-regexp-in-string
14571 "\\\\-" "-" (match-string 2 term))))
14572 (regexp (eq (string-to-char tag) ?{))
14573 (levelp (match-end 4))
14574 (propp (match-end 5))
14576 (cond
14577 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14578 (levelp
14579 `(,(org-op-to-function (match-string 3 term))
14580 level
14581 ,(string-to-number (match-string 4 term))))
14582 (propp
14583 (let* ((gv (pcase (upcase (match-string 5 term))
14584 ("CATEGORY"
14585 '(get-text-property (point) 'org-category))
14586 ("TODO" 'todo)
14587 (p `(org-cached-entry-get nil ,p))))
14588 (pv (match-string 7 term))
14589 (regexp (eq (string-to-char pv) ?{))
14590 (strp (eq (string-to-char pv) ?\"))
14591 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14592 (po (org-op-to-function (match-string 6 term)
14593 (if timep 'time strp))))
14594 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14595 (when timep (setq pv (org-matcher-time pv)))
14596 (cond ((and regexp (eq po 'org<>))
14597 `(not (string-match ,pv (or ,gv ""))))
14598 (regexp `(string-match ,pv (or ,gv "")))
14599 (strp `(,po (or ,gv "") ,pv))
14601 `(,po
14602 (string-to-number (or ,gv ""))
14603 ,(string-to-number pv))))))
14604 (t `(member ,tag tags-list)))))
14605 (push (if minus `(not ,mm) mm) tagsmatcher)
14606 (setq term rest)))
14607 (push `(and ,@tagsmatcher) orlist)
14608 (setq tagsmatcher nil))
14609 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14611 ;; Make the TODO matcher.
14612 (when (org-string-nw-p todomatch)
14613 (let ((orlist nil))
14614 (dolist (term (org-split-string todomatch "|"))
14615 (while (string-match re term)
14616 (let* ((minus (and (match-end 1)
14617 (equal (match-string 1 term) "-")))
14618 (kwd (match-string 2 term))
14619 (regexp (eq (string-to-char kwd) ?{))
14620 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14621 `(equal todo ,kwd))))
14622 (push (if minus `(not ,mm) mm) todomatcher))
14623 (setq term (substring term (match-end 0))))
14624 (push (if (> (length todomatcher) 1)
14625 (cons 'and todomatcher)
14626 (car todomatcher))
14627 orlist)
14628 (setq todomatcher nil))
14629 (setq todomatcher (cons 'or orlist))))
14631 ;; Return the string and function of the matcher. If no
14632 ;; tags-specific or todo-specific matcher exists, match
14633 ;; everything.
14634 (let ((matcher (if (and tagsmatcher todomatcher)
14635 `(and ,tagsmatcher ,todomatcher)
14636 (or tagsmatcher todomatcher t))))
14637 (when org--matcher-tags-todo-only
14638 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14639 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14641 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14642 "Expand group tags in MATCH.
14644 This replaces every group tag in MATCH with a regexp tag search.
14645 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14646 will be replaced like this:
14648 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14649 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14650 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14652 Replacing by a regexp preserves the structure of the match.
14653 E.g., this expansion
14655 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14657 will match anything tagged with \"Lab\" and \"Home\", or tagged
14658 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14660 A group tag in MATCH can contain regular expressions of its own.
14661 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14662 will be replaced like this:
14664 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14666 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14667 assumed to be a single group tag, and the function will return
14668 the list of tags in this group.
14670 When DOWNCASE is non-nil, expand downcased TAGS."
14671 (if org-group-tags
14672 (let* ((case-fold-search t)
14673 (stable org-mode-syntax-table)
14674 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14675 (taggroups (if downcased
14676 (mapcar (lambda (tg) (mapcar #'downcase tg))
14677 taggroups)
14678 taggroups))
14679 (taggroups-keys (mapcar #'car taggroups))
14680 (return-match (if downcased (downcase match) match))
14681 (count 0)
14682 (work-already-expanded tags-already-expanded)
14683 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14684 ;; @ and _ are allowed as word-components in tags.
14685 (modify-syntax-entry ?@ "w" stable)
14686 (modify-syntax-entry ?_ "w" stable)
14687 ;; Temporarily replace regexp-expressions in the match-expression.
14688 (while (string-match "{.+?}" return-match)
14689 (cl-incf count)
14690 (push (match-string 0 return-match) regexps-in-match)
14691 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14692 (while (and taggroups-keys
14693 (with-syntax-table stable
14694 (string-match
14695 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14696 (regexp-opt taggroups-keys) "\\>\\)")
14697 return-match)))
14698 (let* ((dir (match-string 1 return-match))
14699 (tag (match-string 2 return-match))
14700 (tag (if downcased (downcase tag) tag)))
14701 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14702 (member tag work-already-expanded))
14703 (setq tags-in-group (assoc tag taggroups))
14704 (push tag work-already-expanded)
14705 ;; Recursively expand each tag in the group, if the tag hasn't
14706 ;; already been expanded. Restore the match-data after all recursive calls.
14707 (save-match-data
14708 (let (tags-expanded)
14709 (dolist (x (cdr tags-in-group))
14710 (if (and (member x taggroups-keys)
14711 (not (member x work-already-expanded)))
14712 (setq tags-expanded
14713 (delete-dups
14714 (append
14715 (org-tags-expand x t downcased
14716 work-already-expanded)
14717 tags-expanded)))
14718 (setq tags-expanded
14719 (append (list x) tags-expanded)))
14720 (setq work-already-expanded
14721 (delete-dups
14722 (append tags-expanded
14723 work-already-expanded))))
14724 (setq tags-in-group
14725 (delete-dups (cons (car tags-in-group)
14726 tags-expanded)))))
14727 ;; Filter tag-regexps from tags.
14728 (setq regexp-in-group-escaped
14729 (delq nil (mapcar (lambda (x)
14730 (if (stringp x)
14731 (and (equal "{" (substring x 0 1))
14732 (equal "}" (substring x -1))
14735 tags-in-group))
14736 regexp-in-group
14737 (mapcar (lambda (x)
14738 (substring x 1 -1))
14739 regexp-in-group-escaped)
14740 tags-in-group
14741 (delq nil (mapcar (lambda (x)
14742 (if (stringp x)
14743 (and (not (equal "{" (substring x 0 1)))
14744 (not (equal "}" (substring x -1)))
14747 tags-in-group)))
14748 ;; If single-as-list, do no more in the while-loop.
14749 (if (not single-as-list)
14750 (progn
14751 (when regexp-in-group
14752 (setq regexp-in-group
14753 (concat "\\|"
14754 (mapconcat 'identity regexp-in-group
14755 "\\|"))))
14756 (setq tags-in-group
14757 (concat dir
14758 "{\\<"
14759 (regexp-opt tags-in-group)
14760 "\\>"
14761 regexp-in-group
14762 "}"))
14763 (when (stringp tags-in-group)
14764 (org-add-props tags-in-group '(grouptag t)))
14765 (setq return-match
14766 (replace-match tags-in-group t t return-match)))
14767 (setq tags-in-group
14768 (append regexp-in-group-escaped tags-in-group))))
14769 (setq taggroups-keys (delete tag taggroups-keys))))
14770 ;; Add the regular expressions back into the match-expression again.
14771 (while regexps-in-match
14772 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14773 (pop regexps-in-match)
14774 return-match t t))
14775 (cl-decf count))
14776 (if single-as-list
14777 (if tags-in-group tags-in-group (list return-match))
14778 return-match))
14779 (if single-as-list
14780 (list (if downcased (downcase match) match))
14781 match)))
14783 (defun org-op-to-function (op &optional stringp)
14784 "Turn an operator into the appropriate function."
14785 (setq op
14786 (cond
14787 ((equal op "<" ) '(< string< org-time<))
14788 ((equal op ">" ) '(> org-string> org-time>))
14789 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14790 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14791 ((member op '("=" "==")) '(= string= org-time=))
14792 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14793 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14795 (defun org<> (a b) (not (= a b)))
14796 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14797 (defun org-string>= (a b) (not (string< a b)))
14798 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14799 (defun org-string<> (a b) (not (string= a b)))
14800 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14801 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14802 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14803 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14804 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14805 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14806 (defun org-2ft (s)
14807 "Convert S to a floating point time.
14808 If S is already a number, just return it. If it is a string, parse
14809 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14810 (cond
14811 ((numberp s) s)
14812 ((stringp s)
14813 (condition-case nil
14814 (float-time (apply 'encode-time (org-parse-time-string s)))
14815 (error 0.)))
14816 (t 0.)))
14818 (defun org-time-today ()
14819 "Time in seconds today at 0:00.
14820 Returns the float number of seconds since the beginning of the
14821 epoch to the beginning of today (00:00)."
14822 (float-time (apply 'encode-time
14823 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14825 (defun org-matcher-time (s)
14826 "Interpret a time comparison value."
14827 (save-match-data
14828 (cond
14829 ((string= s "<now>") (float-time))
14830 ((string= s "<today>") (org-time-today))
14831 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14832 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14833 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14834 (+ (org-time-today)
14835 (* (string-to-number (match-string 1 s))
14836 (cdr (assoc (match-string 2 s)
14837 '(("d" . 86400.0) ("w" . 604800.0)
14838 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14839 (t (org-2ft s)))))
14841 (defun org-match-any-p (re list)
14842 "Does re match any element of list?"
14843 (setq list (mapcar (lambda (x) (string-match re x)) list))
14844 (delq nil list))
14846 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14847 (defvar org-tags-overlay (make-overlay 1 1))
14848 (delete-overlay org-tags-overlay)
14850 (defun org-get-local-tags-at (&optional pos)
14851 "Get a list of tags defined in the current headline."
14852 (org-get-tags-at pos 'local))
14854 (defun org-get-local-tags ()
14855 "Get a list of tags defined in the current headline."
14856 (org-get-tags-at nil 'local))
14858 (defun org-get-tags-at (&optional pos local)
14859 "Get a list of all headline tags applicable at POS.
14860 POS defaults to point. If tags are inherited, the list contains
14861 the targets in the same sequence as the headlines appear, i.e.
14862 the tags of the current headline come last.
14863 When LOCAL is non-nil, only return tags from the current headline,
14864 ignore inherited ones."
14865 (interactive)
14866 (if (and org-trust-scanner-tags
14867 (or (not pos) (equal pos (point)))
14868 (not local))
14869 org-scanner-tags
14870 (let (tags ltags lastpos parent)
14871 (save-excursion
14872 (save-restriction
14873 (widen)
14874 (goto-char (or pos (point)))
14875 (save-match-data
14876 (catch 'done
14877 (condition-case nil
14878 (progn
14879 (org-back-to-heading t)
14880 (while (not (equal lastpos (point)))
14881 (setq lastpos (point))
14882 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14883 (setq ltags (org-split-string
14884 (match-string-no-properties 1) ":"))
14885 (when parent
14886 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14887 (setq tags (append
14888 (if parent
14889 (org-remove-uninherited-tags ltags)
14890 ltags)
14891 tags)))
14892 (or org-use-tag-inheritance (throw 'done t))
14893 (when local (throw 'done t))
14894 (or (org-up-heading-safe) (error nil))
14895 (setq parent t)))
14896 (error nil)))))
14897 (if local
14898 tags
14899 (reverse (delete-dups
14900 (reverse (append
14901 (org-remove-uninherited-tags
14902 org-file-tags)
14903 tags)))))))))
14905 (defun org-add-prop-inherited (s)
14906 (add-text-properties 0 (length s) '(inherited t) s)
14909 (defun org-toggle-tag (tag &optional onoff)
14910 "Toggle the tag TAG for the current line.
14911 If ONOFF is `on' or `off', don't toggle but set to this state."
14912 (let (res current)
14913 (save-excursion
14914 (org-back-to-heading t)
14915 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14916 (point-at-eol) t)
14917 (progn
14918 (setq current (match-string 1))
14919 (replace-match ""))
14920 (setq current ""))
14921 (setq current (nreverse (org-split-string current ":")))
14922 (cond
14923 ((eq onoff 'on)
14924 (setq res t)
14925 (or (member tag current) (push tag current)))
14926 ((eq onoff 'off)
14927 (or (not (member tag current)) (setq current (delete tag current))))
14928 (t (if (member tag current)
14929 (setq current (delete tag current))
14930 (setq res t)
14931 (push tag current))))
14932 (end-of-line 1)
14933 (if current
14934 (progn
14935 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14936 (org-set-tags nil t))
14937 (delete-horizontal-space))
14938 (run-hooks 'org-after-tags-change-hook))
14939 res))
14941 (defun org--align-tags-here (to-col)
14942 "Align tags on the current headline to TO-COL.
14943 Assume point is on a headline."
14944 (let ((pos (point)))
14945 (beginning-of-line)
14946 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14947 (>= pos (match-beginning 2)))
14948 ;; No tags or point within tags: do not align.
14949 (goto-char pos)
14950 (goto-char (match-beginning 1))
14951 (let ((shift (max (- (if (>= to-col 0) to-col
14952 (- (abs to-col) (string-width (match-string 2))))
14953 (current-column))
14954 1)))
14955 (replace-match (make-string shift ?\s) nil nil nil 1)
14956 ;; Preserve initial position, if possible. In any case, stop
14957 ;; before tags.
14958 (when (< pos (point)) (goto-char pos))))))
14960 (defun org-set-tags-command (&optional arg just-align)
14961 "Call the set-tags command for the current entry."
14962 (interactive "P")
14963 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14964 (org-set-tags arg just-align)
14965 (save-excursion
14966 (unless (and (org-region-active-p)
14967 org-loop-over-headlines-in-active-region)
14968 (org-back-to-heading t))
14969 (org-set-tags arg just-align))))
14971 (defun org-set-tags-to (data)
14972 "Set the tags of the current entry to DATA, replacing the current tags.
14973 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14974 If DATA is nil or the empty string, any tags will be removed."
14975 (interactive "sTags: ")
14976 (setq data
14977 (cond
14978 ((eq data nil) "")
14979 ((equal data "") "")
14980 ((stringp data)
14981 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14982 ":"))
14983 ((listp data)
14984 (concat ":" (mapconcat 'identity data ":") ":"))))
14985 (when data
14986 (save-excursion
14987 (org-back-to-heading t)
14988 (when (let ((case-fold-search nil))
14989 (looking-at org-complex-heading-regexp))
14990 (if (match-end 5)
14991 (progn
14992 (goto-char (match-beginning 5))
14993 (insert data)
14994 (delete-region (point) (point-at-eol))
14995 (org-set-tags nil 'align))
14996 (goto-char (point-at-eol))
14997 (insert " " data)
14998 (org-set-tags nil 'align)))
14999 (beginning-of-line 1)
15000 (when (looking-at ".*?\\([ \t]+\\)$")
15001 (delete-region (match-beginning 1) (match-end 1))))))
15003 (defun org-align-all-tags ()
15004 "Align the tags in all headings."
15005 (interactive)
15006 (save-excursion
15007 (or (ignore-errors (org-back-to-heading t))
15008 (outline-next-heading))
15009 (if (org-at-heading-p)
15010 (org-set-tags t)
15011 (message "No headings"))))
15013 (defvar org-indent-indentation-per-level)
15014 (defun org-set-tags (&optional arg just-align)
15015 "Set the tags for the current headline.
15016 With prefix ARG, realign all tags in headings in the current buffer.
15017 When JUST-ALIGN is non-nil, only align tags."
15018 (interactive "P")
15019 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15020 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15021 'region-start-level
15022 'region))
15023 org-loop-over-headlines-in-active-region)
15024 (org-map-entries
15025 ;; We don't use ARG and JUST-ALIGN here because these args
15026 ;; are not useful when looping over headlines.
15027 #'org-set-tags
15028 org-loop-over-headlines-in-active-region
15030 '(when (org-invisible-p) (org-end-of-subtree nil t))))
15031 (let ((org-setting-tags t))
15032 (if arg
15033 (save-excursion
15034 (goto-char (point-min))
15035 (while (re-search-forward org-outline-regexp-bol nil t)
15036 (org-set-tags nil t)
15037 (end-of-line))
15038 (message "All tags realigned to column %d" org-tags-column))
15039 (let* ((current (org-get-tags-string))
15040 (tags
15041 (if just-align current
15042 ;; Get a new set of tags from the user.
15043 (save-excursion
15044 (let* ((seen)
15045 (table
15046 (setq
15047 org-last-tags-completion-table
15048 ;; Uniquify tags in alists, yet preserve
15049 ;; structure (i.e., keywords).
15050 (delq nil
15051 (mapcar
15052 (lambda (pair)
15053 (let ((head (car pair)))
15054 (cond ((symbolp head) pair)
15055 ((member head seen) nil)
15056 (t (push head seen)
15057 pair))))
15058 (append
15059 (or org-current-tag-alist
15060 (org-get-buffer-tags))
15061 (and
15062 org-complete-tags-always-offer-all-agenda-tags
15063 (org-global-tags-completion-table
15064 (org-agenda-files))))))))
15065 (current-tags (org-split-string current ":"))
15066 (inherited-tags
15067 (nreverse (nthcdr (length current-tags)
15068 (nreverse (org-get-tags-at))))))
15069 (replace-regexp-in-string
15070 "\\([-+&]+\\|,\\)"
15072 (if (or (eq t org-use-fast-tag-selection)
15073 (and org-use-fast-tag-selection
15074 (delq nil (mapcar #'cdr table))))
15075 (org-fast-tag-selection
15076 current-tags inherited-tags table
15077 (and org-fast-tag-selection-include-todo
15078 org-todo-key-alist))
15079 (let ((org-add-colon-after-tag-completion
15080 (< 1 (length table))))
15081 (org-trim
15082 (completing-read
15083 "Tags: "
15084 #'org-tags-completion-function
15085 nil nil current 'org-tags-history))))))))))
15087 (when org-tags-sort-function
15088 (setq tags
15089 (mapconcat
15090 #'identity
15091 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15092 org-tags-sort-function)
15093 ":")))
15095 (if (or (string= ":" tags)
15096 (string= "::" tags))
15097 (setq tags ""))
15098 (if (not (org-string-nw-p tags)) (setq tags "")
15099 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
15100 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
15102 ;; Insert new tags at the correct column.
15103 (unless (equal current tags)
15104 (save-excursion
15105 (beginning-of-line)
15106 (let ((case-fold-search nil))
15107 (looking-at org-complex-heading-regexp))
15108 ;; Remove current tags, if any.
15109 (when (match-end 5) (replace-match "" nil nil nil 5))
15110 ;; Insert new tags, if any. Otherwise, remove trailing
15111 ;; white spaces.
15112 (end-of-line)
15113 (if (not (equal tags ""))
15114 ;; When text is being inserted on an invisible
15115 ;; region boundary, it can be inadvertently sucked
15116 ;; into invisibility.
15117 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
15118 (skip-chars-backward " \t")
15119 (delete-region (point) (line-end-position)))))
15120 ;; Align tags, if any. Fix tags column if `org-indent-mode'
15121 ;; is on.
15122 (unless (equal tags "")
15123 (let* ((level (save-excursion
15124 (beginning-of-line)
15125 (skip-chars-forward "\\*")))
15126 (offset (if (bound-and-true-p org-indent-mode)
15127 (* (1- org-indent-indentation-per-level)
15128 (1- level))
15130 (tags-column
15131 (+ org-tags-column
15132 (if (> org-tags-column 0) (- offset) offset))))
15133 (org--align-tags-here tags-column))))
15134 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15136 (defun org-change-tag-in-region (beg end tag off)
15137 "Add or remove TAG for each entry in the region.
15138 This works in the agenda, and also in an Org buffer."
15139 (interactive
15140 (list (region-beginning) (region-end)
15141 (let ((org-last-tags-completion-table
15142 (if (derived-mode-p 'org-mode)
15143 (org-uniquify
15144 (delq nil (append (org-get-buffer-tags)
15145 (org-global-tags-completion-table))))
15146 (org-global-tags-completion-table))))
15147 (completing-read
15148 "Tag: " 'org-tags-completion-function nil nil nil
15149 'org-tags-history))
15150 (progn
15151 (message "[s]et or [r]emove? ")
15152 (equal (read-char-exclusive) ?r))))
15153 (when (fboundp 'deactivate-mark) (deactivate-mark))
15154 (let ((agendap (equal major-mode 'org-agenda-mode))
15155 l1 l2 m buf pos newhead (cnt 0))
15156 (goto-char end)
15157 (setq l2 (1- (org-current-line)))
15158 (goto-char beg)
15159 (setq l1 (org-current-line))
15160 (cl-loop for l from l1 to l2 do
15161 (org-goto-line l)
15162 (setq m (get-text-property (point) 'org-hd-marker))
15163 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15164 (and agendap m))
15165 (setq buf (if agendap (marker-buffer m) (current-buffer))
15166 pos (if agendap m (point)))
15167 (with-current-buffer buf
15168 (save-excursion
15169 (save-restriction
15170 (goto-char pos)
15171 (setq cnt (1+ cnt))
15172 (org-toggle-tag tag (if off 'off 'on))
15173 (setq newhead (org-get-heading)))))
15174 (and agendap (org-agenda-change-all-lines newhead m))))
15175 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15177 (defun org-tags-completion-function (string _predicate &optional flag)
15178 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15179 (confirm (lambda (x) (stringp (car x)))))
15180 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15181 (setq s1 (match-string 1 string)
15182 s2 (match-string 2 string))
15183 (setq s1 "" s2 string))
15184 (cond
15185 ((eq flag nil)
15186 ;; try completion
15187 (setq rtn (try-completion s2 ctable confirm))
15188 (when (stringp rtn)
15189 (setq rtn
15190 (concat s1 s2 (substring rtn (length s2))
15191 (if (and org-add-colon-after-tag-completion
15192 (assoc rtn ctable))
15193 ":" ""))))
15194 rtn)
15195 ((eq flag t)
15196 ;; all-completions
15197 (all-completions s2 ctable confirm))
15198 ((eq flag 'lambda)
15199 ;; exact match?
15200 (assoc s2 ctable)))))
15202 (defun org-fast-tag-insert (kwd tags face &optional end)
15203 "Insert KDW, and the TAGS, the latter with face FACE.
15204 Also insert END."
15205 (insert (format "%-12s" (concat kwd ":"))
15206 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15207 (or end "")))
15209 (defun org-fast-tag-show-exit (flag)
15210 (save-excursion
15211 (org-goto-line 3)
15212 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15213 (replace-match ""))
15214 (when flag
15215 (end-of-line 1)
15216 (org-move-to-column (- (window-width) 19) t)
15217 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15219 (defun org-set-current-tags-overlay (current prefix)
15220 "Add an overlay to CURRENT tag with PREFIX."
15221 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15222 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15223 (org-overlay-display org-tags-overlay (concat prefix s))))
15225 (defvar org-last-tag-selection-key nil)
15226 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15227 "Fast tag selection with single keys.
15228 CURRENT is the current list of tags in the headline, INHERITED is the
15229 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15230 possibly with grouping information. TODO-TABLE is a similar table with
15231 TODO keywords, should these have keys assigned to them.
15232 If the keys are nil, a-z are automatically assigned.
15233 Returns the new tags string, or nil to not change the current settings."
15234 (let* ((fulltable (append table todo-table))
15235 (maxlen (apply 'max (mapcar
15236 (lambda (x)
15237 (if (stringp (car x)) (string-width (car x)) 0))
15238 fulltable)))
15239 (buf (current-buffer))
15240 (expert (eq org-fast-tag-selection-single-key 'expert))
15241 (buffer-tags nil)
15242 (fwidth (+ maxlen 3 1 3))
15243 (ncol (/ (- (window-width) 4) fwidth))
15244 (i-face 'org-done)
15245 (c-face 'org-todo)
15246 tg cnt e c char c1 c2 ntable tbl rtn
15247 ov-start ov-end ov-prefix
15248 (exit-after-next org-fast-tag-selection-single-key)
15249 (done-keywords org-done-keywords)
15250 groups ingroup intaggroup)
15251 (save-excursion
15252 (beginning-of-line 1)
15253 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15254 (setq ov-start (match-beginning 1)
15255 ov-end (match-end 1)
15256 ov-prefix "")
15257 (setq ov-start (1- (point-at-eol))
15258 ov-end (1+ ov-start))
15259 (skip-chars-forward "^\n\r")
15260 (setq ov-prefix
15261 (concat
15262 (buffer-substring (1- (point)) (point))
15263 (if (> (current-column) org-tags-column)
15265 (make-string (- org-tags-column (current-column)) ?\ ))))))
15266 (move-overlay org-tags-overlay ov-start ov-end)
15267 (save-window-excursion
15268 (if expert
15269 (set-buffer (get-buffer-create " *Org tags*"))
15270 (delete-other-windows)
15271 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15272 (org-switch-to-buffer-other-window " *Org tags*"))
15273 (erase-buffer)
15274 (setq-local org-done-keywords done-keywords)
15275 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15276 (org-fast-tag-insert "Current" current c-face "\n\n")
15277 (org-fast-tag-show-exit exit-after-next)
15278 (org-set-current-tags-overlay current ov-prefix)
15279 (setq tbl fulltable char ?a cnt 0)
15280 (while (setq e (pop tbl))
15281 (cond
15282 ((eq (car e) :startgroup)
15283 (push '() groups) (setq ingroup t)
15284 (unless (zerop cnt)
15285 (setq cnt 0)
15286 (insert "\n"))
15287 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15288 ((eq (car e) :endgroup)
15289 (setq ingroup nil cnt 0)
15290 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15291 ((eq (car e) :startgrouptag)
15292 (setq intaggroup t)
15293 (unless (zerop cnt)
15294 (setq cnt 0)
15295 (insert "\n"))
15296 (insert "[ "))
15297 ((eq (car e) :endgrouptag)
15298 (setq intaggroup nil cnt 0)
15299 (insert "]\n"))
15300 ((equal e '(:newline))
15301 (unless (zerop cnt)
15302 (setq cnt 0)
15303 (insert "\n")
15304 (setq e (car tbl))
15305 (while (equal (car tbl) '(:newline))
15306 (insert "\n")
15307 (setq tbl (cdr tbl)))))
15308 ((equal e '(:grouptags)) (insert " : "))
15310 (setq tg (copy-sequence (car e)) c2 nil)
15311 (if (cdr e)
15312 (setq c (cdr e))
15313 ;; automatically assign a character.
15314 (setq c1 (string-to-char
15315 (downcase (substring
15316 tg (if (= (string-to-char tg) ?@) 1 0)))))
15317 (if (or (rassoc c1 ntable) (rassoc c1 table))
15318 (while (or (rassoc char ntable) (rassoc char table))
15319 (setq char (1+ char)))
15320 (setq c2 c1))
15321 (setq c (or c2 char)))
15322 (when ingroup (push tg (car groups)))
15323 (setq tg (org-add-props tg nil 'face
15324 (cond
15325 ((not (assoc tg table))
15326 (org-get-todo-face tg))
15327 ((member tg current) c-face)
15328 ((member tg inherited) i-face))))
15329 (when (equal (caar tbl) :grouptags)
15330 (org-add-props tg nil 'face 'org-tag-group))
15331 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15332 (insert "[" c "] " tg (make-string
15333 (- fwidth 4 (length tg)) ?\ ))
15334 (push (cons tg c) ntable)
15335 (when (= (cl-incf cnt) ncol)
15336 (insert "\n")
15337 (when (or ingroup intaggroup) (insert " "))
15338 (setq cnt 0)))))
15339 (setq ntable (nreverse ntable))
15340 (insert "\n")
15341 (goto-char (point-min))
15342 (unless expert (org-fit-window-to-buffer))
15343 (setq rtn
15344 (catch 'exit
15345 (while t
15346 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15347 (if (not groups) "no " "")
15348 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15349 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15350 (setq org-last-tag-selection-key c)
15351 (cond
15352 ((= c ?\r) (throw 'exit t))
15353 ((= c ?!)
15354 (setq groups (not groups))
15355 (goto-char (point-min))
15356 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15357 ((= c ?\C-c)
15358 (if (not expert)
15359 (org-fast-tag-show-exit
15360 (setq exit-after-next (not exit-after-next)))
15361 (setq expert nil)
15362 (delete-other-windows)
15363 (set-window-buffer (split-window-vertically) " *Org tags*")
15364 (org-switch-to-buffer-other-window " *Org tags*")
15365 (org-fit-window-to-buffer)))
15366 ((or (= c ?\C-g)
15367 (and (= c ?q) (not (rassoc c ntable))))
15368 (delete-overlay org-tags-overlay)
15369 (setq quit-flag t))
15370 ((= c ?\ )
15371 (setq current nil)
15372 (when exit-after-next (setq exit-after-next 'now)))
15373 ((= c ?\t)
15374 (condition-case nil
15375 (setq tg (completing-read
15376 "Tag: "
15377 (or buffer-tags
15378 (with-current-buffer buf
15379 (setq buffer-tags
15380 (org-get-buffer-tags))))))
15381 (quit (setq tg "")))
15382 (when (string-match "\\S-" tg)
15383 (cl-pushnew (list tg) buffer-tags :test #'equal)
15384 (if (member tg current)
15385 (setq current (delete tg current))
15386 (push tg current)))
15387 (when exit-after-next (setq exit-after-next 'now)))
15388 ((setq e (rassoc c todo-table) tg (car e))
15389 (with-current-buffer buf
15390 (save-excursion (org-todo tg)))
15391 (when exit-after-next (setq exit-after-next 'now)))
15392 ((setq e (rassoc c ntable) tg (car e))
15393 (if (member tg current)
15394 (setq current (delete tg current))
15395 (cl-loop for g in groups do
15396 (when (member tg g)
15397 (dolist (x g) (setq current (delete x current)))))
15398 (push tg current))
15399 (when exit-after-next (setq exit-after-next 'now))))
15401 ;; Create a sorted list
15402 (setq current
15403 (sort current
15404 (lambda (a b)
15405 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15406 (when (eq exit-after-next 'now) (throw 'exit t))
15407 (goto-char (point-min))
15408 (beginning-of-line 2)
15409 (delete-region (point) (point-at-eol))
15410 (org-fast-tag-insert "Current" current c-face)
15411 (org-set-current-tags-overlay current ov-prefix)
15412 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15413 (setq tg (match-string 1))
15414 (add-text-properties
15415 (match-beginning 1) (match-end 1)
15416 (list 'face
15417 (cond
15418 ((member tg current) c-face)
15419 ((member tg inherited) i-face)
15420 (t (get-text-property (match-beginning 1) 'face))))))
15421 (goto-char (point-min)))))
15422 (delete-overlay org-tags-overlay)
15423 (if rtn
15424 (mapconcat 'identity current ":")
15425 nil))))
15427 (defun org-get-tags-string ()
15428 "Get the TAGS string in the current headline."
15429 (unless (org-at-heading-p t)
15430 (user-error "Not on a heading"))
15431 (save-excursion
15432 (beginning-of-line 1)
15433 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15434 (match-string-no-properties 1)
15435 "")))
15437 (defun org-get-tags ()
15438 "Get the list of tags specified in the current headline."
15439 (org-split-string (org-get-tags-string) ":"))
15441 (defun org-get-buffer-tags ()
15442 "Get a table of all tags used in the buffer, for completion."
15443 (org-with-wide-buffer
15444 (goto-char (point-min))
15445 (let ((tag-re (concat org-outline-regexp-bol
15446 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15447 tags)
15448 (while (re-search-forward tag-re nil t)
15449 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15450 (push tag tags)))
15451 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15453 ;;;; The mapping API
15455 (defvar org-agenda-skip-comment-trees)
15456 (defvar org-agenda-skip-function)
15457 (defun org-map-entries (func &optional match scope &rest skip)
15458 "Call FUNC at each headline selected by MATCH in SCOPE.
15460 FUNC is a function or a lisp form. The function will be called without
15461 arguments, with the cursor positioned at the beginning of the headline.
15462 The return values of all calls to the function will be collected and
15463 returned as a list.
15465 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15466 does not need to preserve point. After evaluation, the cursor will be
15467 moved to the end of the line (presumably of the headline of the
15468 processed entry) and search continues from there. Under some
15469 circumstances, this may not produce the wanted results. For example,
15470 if you have removed (e.g. archived) the current (sub)tree it could
15471 mean that the next entry will be skipped entirely. In such cases, you
15472 can specify the position from where search should continue by making
15473 FUNC set the variable `org-map-continue-from' to the desired buffer
15474 position.
15476 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15477 Only headlines that are matched by this query will be considered during
15478 the iteration. When MATCH is nil or t, all headlines will be
15479 visited by the iteration.
15481 SCOPE determines the scope of this command. It can be any of:
15483 nil The current buffer, respecting the restriction if any
15484 tree The subtree started with the entry at point
15485 region The entries within the active region, if any
15486 region-start-level
15487 The entries within the active region, but only those at
15488 the same level than the first one.
15489 file The current buffer, without restriction
15490 file-with-archives
15491 The current buffer, and any archives associated with it
15492 agenda All agenda files
15493 agenda-with-archives
15494 All agenda files with any archive files associated with them
15495 \(file1 file2 ...)
15496 If this is a list, all files in the list will be scanned
15498 The remaining args are treated as settings for the skipping facilities of
15499 the scanner. The following items can be given here:
15501 archive skip trees with the archive tag
15502 comment skip trees with the COMMENT keyword
15503 function or Emacs Lisp form:
15504 will be used as value for `org-agenda-skip-function', so
15505 whenever the function returns a position, FUNC will not be
15506 called for that entry and search will continue from the
15507 position returned
15509 If your function needs to retrieve the tags including inherited tags
15510 at the *current* entry, you can use the value of the variable
15511 `org-scanner-tags' which will be much faster than getting the value
15512 with `org-get-tags-at'. If your function gets properties with
15513 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15514 to t around the call to `org-entry-properties' to get the same speedup.
15515 Note that if your function moves around to retrieve tags and properties at
15516 a *different* entry, you cannot use these techniques."
15517 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15518 (not (org-region-active-p)))
15519 (let* ((org-agenda-archives-mode nil) ; just to make sure
15520 (org-agenda-skip-archived-trees (memq 'archive skip))
15521 (org-agenda-skip-comment-trees (memq 'comment skip))
15522 (org-agenda-skip-function
15523 (car (org-delete-all '(comment archive) skip)))
15524 (org-tags-match-list-sublevels t)
15525 (start-level (eq scope 'region-start-level))
15526 matcher res
15527 org-todo-keywords-for-agenda
15528 org-done-keywords-for-agenda
15529 org-todo-keyword-alist-for-agenda
15530 org-tag-alist-for-agenda
15531 org--matcher-tags-todo-only)
15533 (cond
15534 ((eq match t) (setq matcher t))
15535 ((eq match nil) (setq matcher t))
15536 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15538 (save-excursion
15539 (save-restriction
15540 (cond ((eq scope 'tree)
15541 (org-back-to-heading t)
15542 (org-narrow-to-subtree)
15543 (setq scope nil))
15544 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15545 (org-region-active-p))
15546 ;; If needed, set start-level to a string like "2"
15547 (when start-level
15548 (save-excursion
15549 (goto-char (region-beginning))
15550 (unless (org-at-heading-p) (outline-next-heading))
15551 (setq start-level (org-current-level))))
15552 (narrow-to-region (region-beginning)
15553 (save-excursion
15554 (goto-char (region-end))
15555 (unless (and (bolp) (org-at-heading-p))
15556 (outline-next-heading))
15557 (point)))
15558 (setq scope nil)))
15560 (if (not scope)
15561 (progn
15562 (org-agenda-prepare-buffers
15563 (and buffer-file-name (list buffer-file-name)))
15564 (setq res
15565 (org-scan-tags
15566 func matcher org--matcher-tags-todo-only start-level)))
15567 ;; Get the right scope
15568 (cond
15569 ((and scope (listp scope) (symbolp (car scope)))
15570 (setq scope (eval scope)))
15571 ((eq scope 'agenda)
15572 (setq scope (org-agenda-files t)))
15573 ((eq scope 'agenda-with-archives)
15574 (setq scope (org-agenda-files t))
15575 (setq scope (org-add-archive-files scope)))
15576 ((eq scope 'file)
15577 (setq scope (and buffer-file-name (list buffer-file-name))))
15578 ((eq scope 'file-with-archives)
15579 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15580 (org-agenda-prepare-buffers scope)
15581 (dolist (file scope)
15582 (with-current-buffer (org-find-base-buffer-visiting file)
15583 (org-with-wide-buffer
15584 (goto-char (point-min))
15585 (setq res
15586 (append
15588 (org-scan-tags
15589 func matcher org--matcher-tags-todo-only)))))))))
15590 res)))
15592 ;;; Properties API
15594 (defconst org-special-properties
15595 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15596 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15597 "The special properties valid in Org mode.
15598 These are properties that are not defined in the property drawer,
15599 but in some other way.")
15601 (defconst org-default-properties
15602 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15603 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15604 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15605 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15606 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15607 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15608 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15609 "Some properties that are used by Org mode for various purposes.
15610 Being in this list makes sure that they are offered for completion.")
15612 (defun org--valid-property-p (property)
15613 "Non nil when string PROPERTY is a valid property name."
15614 (not
15615 (or (equal property "")
15616 (string-match-p "\\s-" property))))
15618 (defun org--update-property-plist (key val props)
15619 "Associate KEY to VAL in alist PROPS.
15620 Modifications are made by side-effect. Return new alist."
15621 (let* ((appending (string= (substring key -1) "+"))
15622 (key (if appending (substring key 0 -1) key))
15623 (old (assoc-string key props t)))
15624 (if (not old) (cons (cons key val) props)
15625 (setcdr old (if appending (concat (cdr old) " " val) val))
15626 props)))
15628 (defun org-get-property-block (&optional beg force)
15629 "Return the (beg . end) range of the body of the property drawer.
15630 BEG is the beginning of the current subtree, or of the part
15631 before the first headline. If it is not given, it will be found.
15632 If the drawer does not exist, create it if FORCE is non-nil, or
15633 return nil."
15634 (org-with-wide-buffer
15635 (when beg (goto-char beg))
15636 (unless (org-before-first-heading-p)
15637 (let ((beg (cond (beg)
15638 ((or (not (featurep 'org-inlinetask))
15639 (org-inlinetask-in-task-p))
15640 (org-back-to-heading t))
15641 (t (org-with-limited-levels (org-back-to-heading t))))))
15642 (forward-line)
15643 (when (looking-at-p org-planning-line-re) (forward-line))
15644 (cond ((looking-at org-property-drawer-re)
15645 (forward-line)
15646 (cons (point) (progn (goto-char (match-end 0))
15647 (line-beginning-position))))
15648 (force
15649 (goto-char beg)
15650 (org-insert-property-drawer)
15651 (let ((pos (save-excursion (search-forward ":END:")
15652 (line-beginning-position))))
15653 (cons pos pos))))))))
15655 (defun org-at-property-p ()
15656 "Non-nil when point is inside a property drawer.
15657 See `org-property-re' for match data, if applicable."
15658 (save-excursion
15659 (beginning-of-line)
15660 (and (looking-at org-property-re)
15661 (let ((property-drawer (save-match-data (org-get-property-block))))
15662 (and property-drawer
15663 (>= (point) (car property-drawer))
15664 (< (point) (cdr property-drawer)))))))
15666 (defun org-property-action ()
15667 "Do an action on properties."
15668 (interactive)
15669 (unless (org-at-property-p) (user-error "Not at a property"))
15670 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15671 (let ((c (read-char-exclusive)))
15672 (cl-case c
15673 (?s (call-interactively #'org-set-property))
15674 (?d (call-interactively #'org-delete-property))
15675 (?D (call-interactively #'org-delete-property-globally))
15676 (?c (call-interactively #'org-compute-property-at-point))
15677 (otherwise (user-error "No such property action %c" c)))))
15679 (defun org-inc-effort ()
15680 "Increment the value of the effort property in the current entry."
15681 (interactive)
15682 (org-set-effort nil t))
15684 (defvar org-clock-effort) ; Defined in org-clock.el.
15685 (defvar org-clock-current-task) ; Defined in org-clock.el.
15686 (defun org-set-effort (&optional value increment)
15687 "Set the effort property of the current entry.
15688 With numerical prefix arg, use the nth allowed value, 0 stands for the
15689 10th allowed value.
15691 When INCREMENT is non-nil, set the property to the next allowed value."
15692 (interactive "P")
15693 (when (equal value 0) (setq value 10))
15694 (let* ((completion-ignore-case t)
15695 (prop org-effort-property)
15696 (cur (org-entry-get nil prop))
15697 (allowed (org-property-get-allowed-values nil prop 'table))
15698 (existing (mapcar 'list (org-property-values prop)))
15699 (heading (nth 4 (org-heading-components)))
15701 (val (cond
15702 ((stringp value) value)
15703 ((and allowed (integerp value))
15704 (or (car (nth (1- value) allowed))
15705 (car (org-last allowed))))
15706 ((and allowed increment)
15707 (or (cl-caadr (member (list cur) allowed))
15708 (user-error "Allowed effort values are not set")))
15709 (allowed
15710 (message "Select 1-9,0, [RET%s]: %s"
15711 (if cur (concat "=" cur) "")
15712 (mapconcat 'car allowed " "))
15713 (setq rpl (read-char-exclusive))
15714 (if (equal rpl ?\r)
15716 (setq rpl (- rpl ?0))
15717 (when (equal rpl 0) (setq rpl 10))
15718 (if (and (> rpl 0) (<= rpl (length allowed)))
15719 (car (nth (1- rpl) allowed))
15720 (org-completing-read "Effort: " allowed nil))))
15722 (org-completing-read
15723 (concat "Effort" (and cur (string-match "\\S-" cur)
15724 (concat " [" cur "]"))
15725 ": ")
15726 existing nil nil "" nil cur)))))
15727 (unless (equal (org-entry-get nil prop) val)
15728 (org-entry-put nil prop val))
15729 (org-refresh-property
15730 '((effort . identity)
15731 (effort-minutes . org-duration-string-to-minutes))
15732 val)
15733 (when (equal heading (bound-and-true-p org-clock-current-task))
15734 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15735 (org-clock-update-mode-line))
15736 (message "%s is now %s" prop val)))
15738 (defun org-entry-properties (&optional pom which)
15739 "Get all properties of the current entry.
15741 When POM is a buffer position, get all properties from the entry
15742 there instead.
15744 This includes the TODO keyword, the tags, time strings for
15745 deadline, scheduled, and clocking, and any additional properties
15746 defined in the entry.
15748 If WHICH is nil or `all', get all properties. If WHICH is
15749 `special' or `standard', only get that subclass. If WHICH is
15750 a string, only get that property.
15752 Return value is an alist. Keys are properties, as upcased
15753 strings."
15754 (org-with-point-at pom
15755 (when (and (derived-mode-p 'org-mode)
15756 (ignore-errors (org-back-to-heading t)))
15757 (catch 'exit
15758 (let* ((beg (point))
15759 (specific (and (stringp which) (upcase which)))
15760 (which (cond ((not specific) which)
15761 ((member specific org-special-properties) 'special)
15762 (t 'standard)))
15763 props)
15764 ;; Get the special properties, like TODO and TAGS.
15765 (when (memq which '(nil all special))
15766 (when (or (not specific) (string= specific "CLOCKSUM"))
15767 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15768 (when clocksum
15769 (push (cons "CLOCKSUM"
15770 (org-minutes-to-clocksum-string clocksum))
15771 props)))
15772 (when specific (throw 'exit props)))
15773 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15774 (let ((clocksumt (get-text-property (point)
15775 :org-clock-minutes-today)))
15776 (when clocksumt
15777 (push (cons "CLOCKSUM_T"
15778 (org-minutes-to-clocksum-string clocksumt))
15779 props)))
15780 (when specific (throw 'exit props)))
15781 (when (or (not specific) (string= specific "ITEM"))
15782 (let ((case-fold-search nil))
15783 (when (looking-at org-complex-heading-regexp)
15784 (push (cons "ITEM"
15785 (let ((title (match-string-no-properties 4)))
15786 (if (org-string-nw-p title)
15787 (org-remove-tabs title)
15788 "")))
15789 props)))
15790 (when specific (throw 'exit props)))
15791 (when (or (not specific) (string= specific "TODO"))
15792 (let ((case-fold-search nil))
15793 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15794 (push (cons "TODO" (match-string-no-properties 2)) props)))
15795 (when specific (throw 'exit props)))
15796 (when (or (not specific) (string= specific "PRIORITY"))
15797 (push (cons "PRIORITY"
15798 (if (looking-at org-priority-regexp)
15799 (match-string-no-properties 2)
15800 (char-to-string org-default-priority)))
15801 props)
15802 (when specific (throw 'exit props)))
15803 (when (or (not specific) (string= specific "FILE"))
15804 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15805 props)
15806 (when specific (throw 'exit props)))
15807 (when (or (not specific) (string= specific "TAGS"))
15808 (let ((value (org-string-nw-p (org-get-tags-string))))
15809 (when value (push (cons "TAGS" value) props)))
15810 (when specific (throw 'exit props)))
15811 (when (or (not specific) (string= specific "ALLTAGS"))
15812 (let ((value (org-get-tags-at)))
15813 (when value
15814 (push (cons "ALLTAGS"
15815 (format ":%s:" (mapconcat #'identity value ":")))
15816 props)))
15817 (when specific (throw 'exit props)))
15818 (when (or (not specific) (string= specific "BLOCKED"))
15819 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15820 (when specific (throw 'exit props)))
15821 (when (or (not specific)
15822 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15823 (forward-line)
15824 (when (looking-at-p org-planning-line-re)
15825 (end-of-line)
15826 (let ((bol (line-beginning-position))
15827 ;; Backward compatibility: time keywords used to
15828 ;; be configurable (before 8.3). Make sure we
15829 ;; get the correct keyword.
15830 (key-assoc `(("CLOSED" . ,org-closed-string)
15831 ("DEADLINE" . ,org-deadline-string)
15832 ("SCHEDULED" . ,org-scheduled-string))))
15833 (dolist (pair (if specific (list (assoc specific key-assoc))
15834 key-assoc))
15835 (save-excursion
15836 (when (search-backward (cdr pair) bol t)
15837 (goto-char (match-end 0))
15838 (skip-chars-forward " \t")
15839 (and (looking-at org-ts-regexp-both)
15840 (push (cons (car pair)
15841 (match-string-no-properties 0))
15842 props)))))))
15843 (when specific (throw 'exit props)))
15844 (when (or (not specific)
15845 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15846 (let ((find-ts
15847 (lambda (end ts)
15848 ;; Fix next time-stamp before END. TS is the
15849 ;; list of time-stamps found so far.
15850 (let ((ts ts)
15851 (regexp (cond
15852 ((string= specific "TIMESTAMP")
15853 org-ts-regexp)
15854 ((string= specific "TIMESTAMP_IA")
15855 org-ts-regexp-inactive)
15856 ((assoc "TIMESTAMP_IA" ts)
15857 org-ts-regexp)
15858 ((assoc "TIMESTAMP" ts)
15859 org-ts-regexp-inactive)
15860 (t org-ts-regexp-both))))
15861 (catch 'next
15862 (while (re-search-forward regexp end t)
15863 (backward-char)
15864 (let ((object (org-element-context)))
15865 ;; Accept to match timestamps in node
15866 ;; properties, too.
15867 (when (memq (org-element-type object)
15868 '(node-property timestamp))
15869 (let ((type
15870 (org-element-property :type object)))
15871 (cond
15872 ((and (memq type '(active active-range))
15873 (not (equal specific "TIMESTAMP_IA")))
15874 (unless (assoc "TIMESTAMP" ts)
15875 (push (cons "TIMESTAMP"
15876 (org-element-property
15877 :raw-value object))
15879 (when specific (throw 'exit ts))))
15880 ((and (memq type '(inactive inactive-range))
15881 (not (string= specific "TIMESTAMP")))
15882 (unless (assoc "TIMESTAMP_IA" ts)
15883 (push (cons "TIMESTAMP_IA"
15884 (org-element-property
15885 :raw-value object))
15887 (when specific (throw 'exit ts))))))
15888 ;; Both timestamp types are found,
15889 ;; move to next part.
15890 (when (= (length ts) 2) (throw 'next ts)))))
15891 ts)))))
15892 (goto-char beg)
15893 ;; First look for timestamps within headline.
15894 (let ((ts (funcall find-ts (line-end-position) nil)))
15895 (if (= (length ts) 2) (setq props (nconc ts props))
15896 ;; Then find timestamps in the section, skipping
15897 ;; planning line.
15898 (let ((end (save-excursion (outline-next-heading))))
15899 (forward-line)
15900 (when (looking-at-p org-planning-line-re) (forward-line))
15901 (setq props (nconc (funcall find-ts end ts) props))))))))
15902 ;; Get the standard properties, like :PROP:.
15903 (when (memq which '(nil all standard))
15904 ;; If we are looking after a specific property, delegate
15905 ;; to `org-entry-get', which is faster. However, make an
15906 ;; exception for "CATEGORY", since it can be also set
15907 ;; through keywords (i.e. #+CATEGORY).
15908 (if (and specific (not (equal specific "CATEGORY")))
15909 (let ((value (org-entry-get beg specific nil t)))
15910 (throw 'exit (and value (list (cons specific value)))))
15911 (let ((range (org-get-property-block beg)))
15912 (when range
15913 (let ((end (cdr range)) seen-base)
15914 (goto-char (car range))
15915 ;; Unlike to `org--update-property-plist', we
15916 ;; handle the case where base values is found
15917 ;; after its extension. We also forbid standard
15918 ;; properties to be named as special properties.
15919 (while (re-search-forward org-property-re end t)
15920 (let* ((key (upcase (match-string-no-properties 2)))
15921 (extendp (string-match-p "\\+\\'" key))
15922 (key-base (if extendp (substring key 0 -1) key))
15923 (value (match-string-no-properties 3)))
15924 (cond
15925 ((member-ignore-case key-base org-special-properties))
15926 (extendp
15927 (setq props
15928 (org--update-property-plist key value props)))
15929 ((member key seen-base))
15930 (t (push key seen-base)
15931 (let ((p (assoc-string key props t)))
15932 (if p (setcdr p (concat value " " (cdr p)))
15933 (push (cons key value) props))))))))))))
15934 (unless (assoc "CATEGORY" props)
15935 (push (cons "CATEGORY" (org-get-category beg)) props)
15936 (when (string= specific "CATEGORY") (throw 'exit props)))
15937 ;; Return value.
15938 props)))))
15940 (defun org--property-local-values (property literal-nil)
15941 "Return value for PROPERTY in current entry.
15942 Value is a list whose car is the base value for PROPERTY and cdr
15943 a list of accumulated values. Return nil if neither is found in
15944 the entry. Also return nil when PROPERTY is set to \"nil\",
15945 unless LITERAL-NIL is non-nil."
15946 (let ((range (org-get-property-block)))
15947 (when range
15948 (goto-char (car range))
15949 (let* ((case-fold-search t)
15950 (end (cdr range))
15951 (value
15952 ;; Base value.
15953 (save-excursion
15954 (let ((v (and (re-search-forward
15955 (org-re-property property nil t) end t)
15956 (match-string-no-properties 3))))
15957 (list (if literal-nil v (org-not-nil v)))))))
15958 ;; Find additional values.
15959 (let* ((property+ (org-re-property (concat property "+") nil t)))
15960 (while (re-search-forward property+ end t)
15961 (push (match-string-no-properties 3) value)))
15962 ;; Return final values.
15963 (and (not (equal value '(nil))) (nreverse value))))))
15965 (defun org--property-global-value (property literal-nil)
15966 "Return value for PROPERTY in current buffer.
15967 Return value is a string. Return nil if property is not set
15968 globally. Also return nil when PROPERTY is set to \"nil\",
15969 unless LITERAL-NIL is non-nil."
15970 (let ((global
15971 (cdr (or (assoc-string property org-file-properties t)
15972 (assoc-string property org-global-properties t)
15973 (assoc-string property org-global-properties-fixed t)))))
15974 (if literal-nil global (org-not-nil global))))
15976 (defun org-entry-get (pom property &optional inherit literal-nil)
15977 "Get value of PROPERTY for entry or content at point-or-marker POM.
15979 If INHERIT is non-nil and the entry does not have the property,
15980 then also check higher levels of the hierarchy. If INHERIT is
15981 the symbol `selective', use inheritance only if the setting in
15982 `org-use-property-inheritance' selects PROPERTY for inheritance.
15984 If the property is present but empty, the return value is the
15985 empty string. If the property is not present at all, nil is
15986 returned. In any other case, return the value as a string.
15987 Search is case-insensitive.
15989 If LITERAL-NIL is set, return the string value \"nil\" as
15990 a string, do not interpret it as the list atom nil. This is used
15991 for inheritance when a \"nil\" value can supersede a non-nil
15992 value higher up the hierarchy."
15993 (org-with-point-at pom
15994 (cond
15995 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15996 ;; We need a special property. Use `org-entry-properties' to
15997 ;; retrieve it, but specify the wanted property.
15998 (cdr (assoc-string property (org-entry-properties nil property))))
15999 ((and inherit
16000 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
16001 (org-entry-get-with-inheritance property literal-nil))
16003 (let* ((local (org--property-local-values property literal-nil))
16004 (value (and local (mapconcat #'identity (delq nil local) " "))))
16005 (if literal-nil value (org-not-nil value)))))))
16007 (defun org-property-or-variable-value (var &optional inherit)
16008 "Check if there is a property fixing the value of VAR.
16009 If yes, return this value. If not, return the current value of the variable."
16010 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
16011 (if (and prop (stringp prop) (string-match "\\S-" prop))
16012 (read prop)
16013 (symbol-value var))))
16015 (defun org-entry-delete (pom property)
16016 "Delete PROPERTY from entry at point-or-marker POM.
16017 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16018 non-nil when a property was removed."
16019 (org-with-point-at pom
16020 (pcase (org-get-property-block)
16021 (`(,begin . ,origin)
16022 (let* ((end (copy-marker origin))
16023 (re (org-re-property
16024 (concat (regexp-quote property) "\\+?") t t)))
16025 (goto-char begin)
16026 (while (re-search-forward re end t)
16027 (delete-region (match-beginning 0) (line-beginning-position 2)))
16028 ;; If drawer is empty, remove it altogether.
16029 (when (= begin end)
16030 (delete-region (line-beginning-position 0)
16031 (line-beginning-position 2)))
16032 ;; Return non-nil if some property was removed.
16033 (prog1 (/= end origin) (set-marker end nil))))
16034 (_ nil))))
16036 ;; Multi-values properties are properties that contain multiple values
16037 ;; These values are assumed to be single words, separated by whitespace.
16038 (defun org-entry-add-to-multivalued-property (pom property value)
16039 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16040 (let* ((old (org-entry-get pom property))
16041 (values (and old (org-split-string old "[ \t]"))))
16042 (setq value (org-entry-protect-space value))
16043 (unless (member value values)
16044 (setq values (append values (list value)))
16045 (org-entry-put pom property
16046 (mapconcat 'identity values " ")))))
16048 (defun org-entry-remove-from-multivalued-property (pom property value)
16049 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16050 (let* ((old (org-entry-get pom property))
16051 (values (and old (org-split-string old "[ \t]"))))
16052 (setq value (org-entry-protect-space value))
16053 (when (member value values)
16054 (setq values (delete value values))
16055 (org-entry-put pom property
16056 (mapconcat 'identity values " ")))))
16058 (defun org-entry-member-in-multivalued-property (pom property value)
16059 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16060 (let* ((old (org-entry-get pom property))
16061 (values (and old (org-split-string old "[ \t]"))))
16062 (setq value (org-entry-protect-space value))
16063 (member value values)))
16065 (defun org-entry-get-multivalued-property (pom property)
16066 "Return a list of values in a multivalued property."
16067 (let* ((value (org-entry-get pom property))
16068 (values (and value (org-split-string value "[ \t]"))))
16069 (mapcar 'org-entry-restore-space values)))
16071 (defun org-entry-put-multivalued-property (pom property &rest values)
16072 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16073 VALUES should be a list of strings. Spaces will be protected."
16074 (org-entry-put pom property
16075 (mapconcat 'org-entry-protect-space values " "))
16076 (let* ((value (org-entry-get pom property))
16077 (values (and value (org-split-string value "[ \t]"))))
16078 (mapcar 'org-entry-restore-space values)))
16080 (defun org-entry-protect-space (s)
16081 "Protect spaces and newline in string S."
16082 (while (string-match " " s)
16083 (setq s (replace-match "%20" t t s)))
16084 (while (string-match "\n" s)
16085 (setq s (replace-match "%0A" t t s)))
16088 (defun org-entry-restore-space (s)
16089 "Restore spaces and newline in string S."
16090 (while (string-match "%20" s)
16091 (setq s (replace-match " " t t s)))
16092 (while (string-match "%0A" s)
16093 (setq s (replace-match "\n" t t s)))
16096 (defvar org-entry-property-inherited-from (make-marker)
16097 "Marker pointing to the entry from where a property was inherited.
16098 Each call to `org-entry-get-with-inheritance' will set this marker to the
16099 location of the entry where the inheritance search matched. If there was
16100 no match, the marker will point nowhere.
16101 Note that also `org-entry-get' calls this function, if the INHERIT flag
16102 is set.")
16104 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16105 "Get PROPERTY of entry or content at point, search higher levels if needed.
16106 The search will stop at the first ancestor which has the property defined.
16107 If the value found is \"nil\", return nil to show that the property
16108 should be considered as undefined (this is the meaning of nil here).
16109 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16110 (move-marker org-entry-property-inherited-from nil)
16111 (org-with-wide-buffer
16112 (let (value)
16113 (catch 'exit
16114 (while t
16115 (let ((v (org--property-local-values property literal-nil)))
16116 (when v
16117 (setq value
16118 (concat (mapconcat #'identity (delq nil v) " ")
16119 (and value " ")
16120 value)))
16121 (cond
16122 ((car v)
16123 (org-back-to-heading t)
16124 (move-marker org-entry-property-inherited-from (point))
16125 (throw 'exit nil))
16126 ((org-up-heading-safe))
16128 (let ((global (org--property-global-value property literal-nil)))
16129 (cond ((not global))
16130 (value (setq value (concat global " " value)))
16131 (t (setq value global))))
16132 (throw 'exit nil))))))
16133 (if literal-nil value (org-not-nil value)))))
16135 (defvar org-property-changed-functions nil
16136 "Hook called when the value of a property has changed.
16137 Each hook function should accept two arguments, the name of the property
16138 and the new value.")
16140 (defun org-entry-put (pom property value)
16141 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16143 If the value is nil, it is converted to the empty string. If it
16144 is not a string, an error is raised. Also raise an error on
16145 invalid property names.
16147 PROPERTY can be any regular property (see
16148 `org-special-properties'). It can also be \"TODO\",
16149 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16151 For the last two properties, VALUE may have any of the special
16152 values \"earlier\" and \"later\". The function then increases or
16153 decreases scheduled or deadline date by one day."
16154 (cond ((null value) (setq value ""))
16155 ((not (stringp value)) (error "Properties values should be strings"))
16156 ((not (org--valid-property-p property))
16157 (user-error "Invalid property name: \"%s\"" property)))
16158 (org-with-point-at pom
16159 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16160 (org-back-to-heading t)
16161 (org-with-limited-levels (org-back-to-heading t)))
16162 (let ((beg (point)))
16163 (cond
16164 ((equal property "TODO")
16165 (cond ((not (org-string-nw-p value)) (setq value 'none))
16166 ((not (member value org-todo-keywords-1))
16167 (user-error "\"%s\" is not a valid TODO state" value)))
16168 (org-todo value)
16169 (org-set-tags nil 'align))
16170 ((equal property "PRIORITY")
16171 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16172 (org-set-tags nil 'align))
16173 ((equal property "SCHEDULED")
16174 (forward-line)
16175 (if (and (looking-at-p org-planning-line-re)
16176 (re-search-forward
16177 org-scheduled-time-regexp (line-end-position) t))
16178 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16179 ((string= value "later") (org-timestamp-change 1 'day))
16180 ((string= value "") (org-schedule '(4)))
16181 (t (org-schedule nil value)))
16182 (if (member value '("earlier" "later" ""))
16183 (call-interactively #'org-schedule)
16184 (org-schedule nil value))))
16185 ((equal property "DEADLINE")
16186 (forward-line)
16187 (if (and (looking-at-p org-planning-line-re)
16188 (re-search-forward
16189 org-deadline-time-regexp (line-end-position) t))
16190 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16191 ((string= value "later") (org-timestamp-change 1 'day))
16192 ((string= value "") (org-deadline '(4)))
16193 (t (org-deadline nil value)))
16194 (if (member value '("earlier" "later" ""))
16195 (call-interactively #'org-deadline)
16196 (org-deadline nil value))))
16197 ((member property org-special-properties)
16198 (error "The %s property cannot be set with `org-entry-put'" property))
16200 (let* ((range (org-get-property-block beg 'force))
16201 (end (cdr range))
16202 (case-fold-search t))
16203 (goto-char (car range))
16204 (if (re-search-forward (org-re-property property nil t) end t)
16205 (progn (delete-region (match-beginning 0) (match-end 0))
16206 (goto-char (match-beginning 0)))
16207 (goto-char end)
16208 (insert "\n")
16209 (backward-char))
16210 (insert ":" property ":")
16211 (when value (insert " " value))
16212 (org-indent-line)))))
16213 (run-hook-with-args 'org-property-changed-functions property value)))
16215 (defun org-buffer-property-keys
16216 (&optional specials defaults columns ignore-malformed)
16217 "Get all property keys in the current buffer.
16219 When SPECIALS is non-nil, also list the special properties that
16220 reflect things like tags and TODO state.
16222 When DEFAULTS is non-nil, also include properties that has
16223 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16224 DESCRIPTION, LOCATION, and LOGGING and others.
16226 When COLUMNS in non-nil, also include property names given in
16227 COLUMN formats in the current buffer.
16229 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16230 automatically performed, such drawers will be silently ignored."
16231 (let ((case-fold-search t)
16232 (props (append
16233 (and specials org-special-properties)
16234 (and defaults (cons org-effort-property org-default-properties))
16235 nil)))
16236 (org-with-wide-buffer
16237 (goto-char (point-min))
16238 (while (re-search-forward org-property-start-re nil t)
16239 (let ((range (org-get-property-block)))
16240 (catch 'skip
16241 (unless range
16242 (when (and (not ignore-malformed)
16243 (not (org-before-first-heading-p))
16244 (y-or-n-p (format "Malformed drawer at %d, repair?"
16245 (line-beginning-position))))
16246 (org-get-property-block nil t))
16247 (throw 'skip nil))
16248 (goto-char (car range))
16249 (let ((begin (car range))
16250 (end (cdr range)))
16251 ;; Make sure that found property block is not located
16252 ;; before current point, as it would generate an infloop.
16253 ;; It can happen, for example, in the following
16254 ;; situation:
16256 ;; * Headline
16257 ;; :PROPERTIES:
16258 ;; ...
16259 ;; :END:
16260 ;; *************** Inlinetask
16261 ;; #+BEGIN_EXAMPLE
16262 ;; :PROPERTIES:
16263 ;; #+END_EXAMPLE
16265 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16266 (while (< (point) end)
16267 (let ((p (progn (looking-at org-property-re)
16268 (match-string-no-properties 2))))
16269 ;; Only add true property name, not extension symbol.
16270 (push (if (not (string-match-p "\\+\\'" p)) p
16271 (substring p 0 -1))
16272 props))
16273 (forward-line))))
16274 (outline-next-heading)))
16275 (when columns
16276 (goto-char (point-min))
16277 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16278 (let ((element (org-element-at-point)))
16279 (when (memq (org-element-type element) '(keyword node-property))
16280 (let ((value (org-element-property :value element))
16281 (start 0))
16282 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16283 (setq start (match-end 0))
16284 (let ((p (match-string-no-properties 1 value)))
16285 (unless (member-ignore-case p org-special-properties)
16286 (push p props))))))))))
16287 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16289 (defun org-property-values (key)
16290 "List all non-nil values of property KEY in current buffer."
16291 (org-with-wide-buffer
16292 (goto-char (point-min))
16293 (let ((case-fold-search t)
16294 (re (org-re-property key))
16295 values)
16296 (while (re-search-forward re nil t)
16297 (push (org-entry-get (point) key) values))
16298 (delete-dups values))))
16300 (defun org-insert-property-drawer ()
16301 "Insert a property drawer into the current entry."
16302 (org-with-wide-buffer
16303 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16304 (org-back-to-heading t)
16305 (org-with-limited-levels (org-back-to-heading t)))
16306 (forward-line)
16307 (when (looking-at-p org-planning-line-re) (forward-line))
16308 (unless (looking-at-p org-property-drawer-re)
16309 ;; Make sure we start editing a line from current entry, not from
16310 ;; next one. It prevents extending text properties or overlays
16311 ;; belonging to the latter.
16312 (when (bolp) (backward-char))
16313 (let ((begin (1+ (point)))
16314 (inhibit-read-only t))
16315 (insert "\n:PROPERTIES:\n:END:")
16316 (when (eobp) (insert "\n"))
16317 (org-indent-region begin (point))))))
16319 (defun org-insert-drawer (&optional arg drawer)
16320 "Insert a drawer at point.
16322 When optional argument ARG is non-nil, insert a property drawer.
16324 Optional argument DRAWER, when non-nil, is a string representing
16325 drawer's name. Otherwise, the user is prompted for a name.
16327 If a region is active, insert the drawer around that region
16328 instead.
16330 Point is left between drawer's boundaries."
16331 (interactive "P")
16332 (let* ((drawer (if arg "PROPERTIES"
16333 (or drawer (read-from-minibuffer "Drawer: ")))))
16334 (cond
16335 ;; With C-u, fall back on `org-insert-property-drawer'
16336 (arg (org-insert-property-drawer))
16337 ;; Check validity of suggested drawer's name.
16338 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16339 (user-error "Invalid drawer name"))
16340 ;; With an active region, insert a drawer at point.
16341 ((not (org-region-active-p))
16342 (progn
16343 (unless (bolp) (insert "\n"))
16344 (insert (format ":%s:\n\n:END:\n" drawer))
16345 (forward-line -2)))
16346 ;; Otherwise, insert the drawer at point
16348 (let ((rbeg (region-beginning))
16349 (rend (copy-marker (region-end))))
16350 (unwind-protect
16351 (progn
16352 (goto-char rbeg)
16353 (beginning-of-line)
16354 (when (save-excursion
16355 (re-search-forward org-outline-regexp-bol rend t))
16356 (user-error "Drawers cannot contain headlines"))
16357 ;; Position point at the beginning of the first
16358 ;; non-blank line in region. Insert drawer's opening
16359 ;; there, then indent it.
16360 (org-skip-whitespace)
16361 (beginning-of-line)
16362 (insert ":" drawer ":\n")
16363 (forward-line -1)
16364 (indent-for-tab-command)
16365 ;; Move point to the beginning of the first blank line
16366 ;; after the last non-blank line in region. Insert
16367 ;; drawer's closing, then indent it.
16368 (goto-char rend)
16369 (skip-chars-backward " \r\t\n")
16370 (insert "\n:END:")
16371 (deactivate-mark t)
16372 (indent-for-tab-command)
16373 (unless (eolp) (insert "\n")))
16374 ;; Clear marker, whatever the outcome of insertion is.
16375 (set-marker rend nil)))))))
16377 (defvar org-property-set-functions-alist nil
16378 "Property set function alist.
16379 Each entry should have the following format:
16381 (PROPERTY . READ-FUNCTION)
16383 The read function will be called with the same argument as
16384 `org-completing-read'.")
16386 (defun org-set-property-function (property)
16387 "Get the function that should be used to set PROPERTY.
16388 This is computed according to `org-property-set-functions-alist'."
16389 (or (cdr (assoc property org-property-set-functions-alist))
16390 'org-completing-read))
16392 (defun org-read-property-value (property)
16393 "Read PROPERTY value from user."
16394 (let* ((completion-ignore-case t)
16395 (allowed (org-property-get-allowed-values nil property 'table))
16396 (cur (org-entry-get nil property))
16397 (prompt (concat property " value"
16398 (if (and cur (string-match "\\S-" cur))
16399 (concat " [" cur "]") "") ": "))
16400 (set-function (org-set-property-function property))
16401 (val (if allowed
16402 (funcall set-function prompt allowed nil
16403 (not (get-text-property 0 'org-unrestricted
16404 (caar allowed))))
16405 (funcall set-function prompt
16406 (mapcar 'list (org-property-values property))
16407 nil nil "" nil cur))))
16408 (org-trim val)))
16410 (defvar org-last-set-property nil)
16411 (defvar org-last-set-property-value nil)
16412 (defun org-read-property-name ()
16413 "Read a property name."
16414 (let ((completion-ignore-case t)
16415 (default-prop (or (and (org-at-property-p)
16416 (match-string-no-properties 2))
16417 org-last-set-property)))
16418 (org-completing-read
16419 (concat "Property"
16420 (if default-prop (concat " [" default-prop "]") "")
16421 ": ")
16422 (mapcar #'list (org-buffer-property-keys nil t t))
16423 nil nil nil nil default-prop)))
16425 (defun org-set-property-and-value (use-last)
16426 "Allow to set [PROPERTY]: [value] direction from prompt.
16427 When use-default, don't even ask, just use the last
16428 \"[PROPERTY]: [value]\" string from the history."
16429 (interactive "P")
16430 (let* ((completion-ignore-case t)
16431 (pv (or (and use-last org-last-set-property-value)
16432 (org-completing-read
16433 "Enter a \"[Property]: [value]\" pair: "
16434 nil nil nil nil nil
16435 org-last-set-property-value)))
16436 prop val)
16437 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16438 (setq prop (match-string 1 pv)
16439 val (match-string 2 pv))
16440 (org-set-property prop val))))
16442 (defun org-set-property (property value)
16443 "In the current entry, set PROPERTY to VALUE.
16445 When called interactively, this will prompt for a property name, offering
16446 completion on existing and default properties. And then it will prompt
16447 for a value, offering completion either on allowed values (via an inherited
16448 xxx_ALL property) or on existing values in other instances of this property
16449 in the current file.
16451 Throw an error when trying to set a property with an invalid name."
16452 (interactive (list nil nil))
16453 (let ((property (or property (org-read-property-name))))
16454 ;; `org-entry-put' also makes the following check, but this one
16455 ;; avoids polluting `org-last-set-property' and
16456 ;; `org-last-set-property-value' needlessly.
16457 (unless (org--valid-property-p property)
16458 (user-error "Invalid property name: \"%s\"" property))
16459 (let ((value (or value (org-read-property-value property)))
16460 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16461 (setq org-last-set-property property)
16462 (setq org-last-set-property-value (concat property ": " value))
16463 ;; Possibly postprocess the inserted value:
16464 (when fn (setq value (funcall fn value)))
16465 (unless (equal (org-entry-get nil property) value)
16466 (org-entry-put nil property value)))))
16468 (defun org-find-property (property &optional value)
16469 "Find first entry in buffer that sets PROPERTY.
16471 When optional argument VALUE is non-nil, only consider an entry
16472 if it contains PROPERTY set to this value. If PROPERTY should be
16473 explicitly set to nil, use string \"nil\" for VALUE.
16475 Return position where the entry begins, or nil if there is no
16476 such entry. If narrowing is in effect, only search the visible
16477 part of the buffer."
16478 (save-excursion
16479 (goto-char (point-min))
16480 (let ((case-fold-search t)
16481 (re (org-re-property property nil (not value) value)))
16482 (catch 'exit
16483 (while (re-search-forward re nil t)
16484 (when (if value (org-at-property-p)
16485 (org-entry-get (point) property nil t))
16486 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16488 (defun org-delete-property (property)
16489 "In the current entry, delete PROPERTY."
16490 (interactive
16491 (let* ((completion-ignore-case t)
16492 (cat (org-entry-get (point) "CATEGORY"))
16493 (props0 (org-entry-properties nil 'standard))
16494 (props (if cat props0
16495 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16496 (prop (if (< 1 (length props))
16497 (completing-read "Property: " props nil t)
16498 (caar props))))
16499 (list prop)))
16500 (if (not property)
16501 (message "No property to delete in this entry")
16502 (org-entry-delete nil property)
16503 (message "Property \"%s\" deleted" property)))
16505 (defun org-delete-property-globally (property)
16506 "Remove PROPERTY globally, from all entries.
16507 This function ignores narrowing, if any."
16508 (interactive
16509 (let* ((completion-ignore-case t)
16510 (prop (completing-read
16511 "Globally remove property: "
16512 (mapcar #'list (org-buffer-property-keys)))))
16513 (list prop)))
16514 (org-with-wide-buffer
16515 (goto-char (point-min))
16516 (let ((count 0)
16517 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16518 (while (re-search-forward re nil t)
16519 (when (org-entry-delete (point) property) (cl-incf count)))
16520 (message "Property \"%s\" removed from %d entries" property count))))
16522 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16524 (defun org-compute-property-at-point ()
16525 "Compute the property at point.
16526 This looks for an enclosing column format, extracts the operator and
16527 then applies it to the property in the column format's scope."
16528 (interactive)
16529 (unless (org-at-property-p)
16530 (user-error "Not at a property"))
16531 (let ((prop (match-string-no-properties 2)))
16532 (org-columns-get-format-and-top-level)
16533 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16534 (user-error "No operator defined for property %s" prop))
16535 (org-columns-compute prop)))
16537 (defvar org-property-allowed-value-functions nil
16538 "Hook for functions supplying allowed values for a specific property.
16539 The functions must take a single argument, the name of the property, and
16540 return a flat list of allowed values. If \":ETC\" is one of
16541 the values, this means that these values are intended as defaults for
16542 completion, but that other values should be allowed too.
16543 The functions must return nil if they are not responsible for this
16544 property.")
16546 (defun org-property-get-allowed-values (pom property &optional table)
16547 "Get allowed values for the property PROPERTY.
16548 When TABLE is non-nil, return an alist that can directly be used for
16549 completion."
16550 (let (vals)
16551 (cond
16552 ((equal property "TODO")
16553 (setq vals (org-with-point-at pom
16554 (append org-todo-keywords-1 '("")))))
16555 ((equal property "PRIORITY")
16556 (let ((n org-lowest-priority))
16557 (while (>= n org-highest-priority)
16558 (push (char-to-string n) vals)
16559 (setq n (1- n)))))
16560 ((equal property "CATEGORY"))
16561 ((member property org-special-properties))
16562 ((setq vals (run-hook-with-args-until-success
16563 'org-property-allowed-value-functions property)))
16565 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16566 (when (and vals (string-match "\\S-" vals))
16567 (setq vals (car (read-from-string (concat "(" vals ")"))))
16568 (setq vals (mapcar (lambda (x)
16569 (cond ((stringp x) x)
16570 ((numberp x) (number-to-string x))
16571 ((symbolp x) (symbol-name x))
16572 (t "???")))
16573 vals)))))
16574 (when (member ":ETC" vals)
16575 (setq vals (remove ":ETC" vals))
16576 (org-add-props (car vals) '(org-unrestricted t)))
16577 (if table (mapcar 'list vals) vals)))
16579 (defun org-property-previous-allowed-value (&optional _previous)
16580 "Switch to the next allowed value for this property."
16581 (interactive)
16582 (org-property-next-allowed-value t))
16584 (defun org-property-next-allowed-value (&optional previous)
16585 "Switch to the next allowed value for this property."
16586 (interactive)
16587 (unless (org-at-property-p)
16588 (user-error "Not at a property"))
16589 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16590 (key (match-string 2))
16591 (value (match-string 3))
16592 (allowed (or (org-property-get-allowed-values (point) key)
16593 (and (member value '("[ ]" "[-]" "[X]"))
16594 '("[ ]" "[X]"))))
16595 (heading (save-match-data (nth 4 (org-heading-components))))
16596 nval)
16597 (unless allowed
16598 (user-error "Allowed values for this property have not been defined"))
16599 (when previous (setq allowed (reverse allowed)))
16600 (when (member value allowed)
16601 (setq nval (car (cdr (member value allowed)))))
16602 (setq nval (or nval (car allowed)))
16603 (when (equal nval value)
16604 (user-error "Only one allowed value for this property"))
16605 (org-at-property-p)
16606 (replace-match (concat " :" key ": " nval) t t)
16607 (org-indent-line)
16608 (beginning-of-line 1)
16609 (skip-chars-forward " \t")
16610 (when (equal prop org-effort-property)
16611 (org-refresh-property
16612 '((effort . identity)
16613 (effort-minutes . org-duration-string-to-minutes))
16614 nval)
16615 (when (string= org-clock-current-task heading)
16616 (setq org-clock-effort nval)
16617 (org-clock-update-mode-line)))
16618 (run-hook-with-args 'org-property-changed-functions key nval)))
16620 (defun org-find-olp (path &optional this-buffer)
16621 "Return a marker pointing to the entry at outline path OLP.
16622 If anything goes wrong, throw an error.
16623 You can wrap this call to catch the error like this:
16625 (condition-case msg
16626 (org-mobile-locate-entry (match-string 4))
16627 (error (nth 1 msg)))
16629 The return value will then be either a string with the error message,
16630 or a marker if everything is OK.
16632 If THIS-BUFFER is set, the outline path does not contain a file,
16633 only headings."
16634 (let* ((file (if this-buffer buffer-file-name (pop path)))
16635 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16636 (level 1)
16637 (lmin 1)
16638 (lmax 1)
16639 end found flevel)
16640 (unless buffer (error "File not found :%s" file))
16641 (with-current-buffer buffer
16642 (org-with-wide-buffer
16643 (goto-char (point-min))
16644 (dolist (heading path)
16645 (let ((re (format org-complex-heading-regexp-format
16646 (regexp-quote heading)))
16647 (cnt 0))
16648 (while (re-search-forward re end t)
16649 (setq level (- (match-end 1) (match-beginning 1)))
16650 (when (and (>= level lmin) (<= level lmax))
16651 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16652 (when (= cnt 0)
16653 (error "Heading not found on level %d: %s" lmax heading))
16654 (when (> cnt 1)
16655 (error "Heading not unique on level %d: %s" lmax heading))
16656 (goto-char found)
16657 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16658 (setq end (save-excursion (org-end-of-subtree t t)))))
16659 (when (org-at-heading-p)
16660 (point-marker))))))
16662 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16663 "Find node HEADING in BUFFER.
16664 Return a marker to the heading if it was found, or nil if not.
16665 If POS-ONLY is set, return just the position instead of a marker.
16667 The heading text must match exact, but it may have a TODO keyword,
16668 a priority cookie and tags in the standard locations."
16669 (with-current-buffer (or buffer (current-buffer))
16670 (org-with-wide-buffer
16671 (goto-char (point-min))
16672 (let (case-fold-search)
16673 (when (re-search-forward
16674 (format org-complex-heading-regexp-format
16675 (regexp-quote heading)) nil t)
16676 (if pos-only
16677 (match-beginning 0)
16678 (move-marker (make-marker) (match-beginning 0))))))))
16680 (defun org-find-exact-heading-in-directory (heading &optional dir)
16681 "Find Org node headline HEADING in all .org files in directory DIR.
16682 When the target headline is found, return a marker to this location."
16683 (let ((files (directory-files (or dir default-directory)
16684 t "\\`[^.#].*\\.org\\'"))
16685 visiting m buffer)
16686 (catch 'found
16687 (dolist (file files)
16688 (message "trying %s" file)
16689 (setq visiting (org-find-base-buffer-visiting file))
16690 (setq buffer (or visiting (find-file-noselect file)))
16691 (setq m (org-find-exact-headline-in-buffer
16692 heading buffer))
16693 (when (and (not m) (not visiting)) (kill-buffer buffer))
16694 (and m (throw 'found m))))))
16696 (defun org-find-entry-with-id (ident)
16697 "Locate the entry that contains the ID property with exact value IDENT.
16698 IDENT can be a string, a symbol or a number, this function will search for
16699 the string representation of it.
16700 Return the position where this entry starts, or nil if there is no such entry."
16701 (interactive "sID: ")
16702 (let ((id (cond
16703 ((stringp ident) ident)
16704 ((symbolp ident) (symbol-name ident))
16705 ((numberp ident) (number-to-string ident))
16706 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16707 (org-with-wide-buffer (org-find-property "ID" id))))
16709 ;;;; Timestamps
16711 (defvar org-last-changed-timestamp nil)
16712 (defvar org-last-inserted-timestamp nil
16713 "The last time stamp inserted with `org-insert-time-stamp'.")
16714 (defvar org-ts-what) ; dynamically scoped parameter
16716 (defun org-time-stamp (arg &optional inactive)
16717 "Prompt for a date/time and insert a time stamp.
16719 If the user specifies a time like HH:MM or if this command is
16720 called with at least one prefix argument, the time stamp contains
16721 the date and the time. Otherwise, only the date is included.
16723 All parts of a date not specified by the user are filled in from
16724 the timestamp at point, if any, or the current date/time
16725 otherwise.
16727 If there is already a timestamp at the cursor, it is replaced.
16729 With two universal prefix arguments, insert an active timestamp
16730 with the current time without prompting the user.
16732 When called from lisp, the timestamp is inactive if INACTIVE is
16733 non-nil."
16734 (interactive "P")
16735 (let* ((ts (cond
16736 ((org-at-date-range-p t)
16737 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16738 ((org-at-timestamp-p t) (match-string 0))))
16739 ;; Default time is either the timestamp at point or today.
16740 ;; When entering a range, only the range start is considered.
16741 (default-time (if (not ts) (current-time)
16742 (apply #'encode-time (org-parse-time-string ts))))
16743 (default-input (and ts (org-get-compact-tod ts)))
16744 (repeater (and ts
16745 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16746 (match-string 0 ts)))
16747 org-time-was-given
16748 org-end-time-was-given
16749 (time
16750 (and (if (equal arg '(16)) (current-time)
16751 ;; Preserve `this-command' and `last-command'.
16752 (let ((this-command this-command)
16753 (last-command last-command))
16754 (org-read-date
16755 arg 'totime nil nil default-time default-input
16756 inactive))))))
16757 (cond
16758 ((and ts
16759 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16760 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16761 (insert "--")
16762 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16764 ;; Make sure we're on a timestamp. When in the middle of a date
16765 ;; range, move arbitrarily to range end.
16766 (unless (org-at-timestamp-p t)
16767 (skip-chars-forward "-")
16768 (org-at-timestamp-p t))
16769 (replace-match "")
16770 (setq org-last-changed-timestamp
16771 (org-insert-time-stamp
16772 time (or org-time-was-given arg)
16773 inactive nil nil (list org-end-time-was-given)))
16774 (when repeater
16775 (backward-char)
16776 (insert " " repeater)
16777 (setq org-last-changed-timestamp
16778 (concat (substring org-last-inserted-timestamp 0 -1)
16779 " " repeater ">")))
16780 (message "Timestamp updated"))
16781 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16782 (t (org-insert-time-stamp
16783 time (or org-time-was-given arg) inactive nil nil
16784 (list org-end-time-was-given))))))
16786 ;; FIXME: can we use this for something else, like computing time differences?
16787 (defun org-get-compact-tod (s)
16788 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16789 (let* ((t1 (match-string 1 s))
16790 (h1 (string-to-number (match-string 2 s)))
16791 (m1 (string-to-number (match-string 3 s)))
16792 (t2 (and (match-end 4) (match-string 5 s)))
16793 (h2 (and t2 (string-to-number (match-string 6 s))))
16794 (m2 (and t2 (string-to-number (match-string 7 s))))
16795 dh dm)
16796 (if (not t2)
16798 (setq dh (- h2 h1) dm (- m2 m1))
16799 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16800 (concat t1 "+" (number-to-string dh)
16801 (and (/= 0 dm) (format ":%02d" dm)))))))
16803 (defun org-time-stamp-inactive (&optional arg)
16804 "Insert an inactive time stamp.
16805 An inactive time stamp is enclosed in square brackets instead of angle
16806 brackets. It is inactive in the sense that it does not trigger agenda entries,
16807 does not link to the calendar and cannot be changed with the S-cursor keys.
16808 So these are more for recording a certain time/date."
16809 (interactive "P")
16810 (org-time-stamp arg 'inactive))
16812 (defvar org-date-ovl (make-overlay 1 1))
16813 (overlay-put org-date-ovl 'face 'org-date-selected)
16814 (delete-overlay org-date-ovl)
16816 (defvar org-ans1) ; dynamically scoped parameter
16817 (defvar org-ans2) ; dynamically scoped parameter
16819 (defvar org-plain-time-of-day-regexp) ; defined below
16821 (defvar org-overriding-default-time nil) ; dynamically scoped
16822 (defvar org-read-date-overlay nil)
16823 (defvar org-dcst nil) ; dynamically scoped
16824 (defvar org-read-date-history nil)
16825 (defvar org-read-date-final-answer nil)
16826 (defvar org-read-date-analyze-futurep nil)
16827 (defvar org-read-date-analyze-forced-year nil)
16828 (defvar org-read-date-inactive)
16830 (defvar org-read-date-minibuffer-local-map
16831 (let* ((map (make-sparse-keymap)))
16832 (set-keymap-parent map minibuffer-local-map)
16833 (org-defkey map (kbd ".")
16834 (lambda () (interactive)
16835 ;; Are we at the beginning of the prompt?
16836 (if (looking-back "^[^:]+: "
16837 (let ((inhibit-field-text-motion t))
16838 (line-beginning-position)))
16839 (org-eval-in-calendar '(calendar-goto-today))
16840 (insert "."))))
16841 (org-defkey map (kbd "C-.")
16842 (lambda () (interactive)
16843 (org-eval-in-calendar '(calendar-goto-today))))
16844 (org-defkey map [(meta shift left)]
16845 (lambda () (interactive)
16846 (org-eval-in-calendar '(calendar-backward-month 1))))
16847 (org-defkey map [(meta shift right)]
16848 (lambda () (interactive)
16849 (org-eval-in-calendar '(calendar-forward-month 1))))
16850 (org-defkey map [(meta shift up)]
16851 (lambda () (interactive)
16852 (org-eval-in-calendar '(calendar-backward-year 1))))
16853 (org-defkey map [(meta shift down)]
16854 (lambda () (interactive)
16855 (org-eval-in-calendar '(calendar-forward-year 1))))
16856 (org-defkey map [?\e (shift left)]
16857 (lambda () (interactive)
16858 (org-eval-in-calendar '(calendar-backward-month 1))))
16859 (org-defkey map [?\e (shift right)]
16860 (lambda () (interactive)
16861 (org-eval-in-calendar '(calendar-forward-month 1))))
16862 (org-defkey map [?\e (shift up)]
16863 (lambda () (interactive)
16864 (org-eval-in-calendar '(calendar-backward-year 1))))
16865 (org-defkey map [?\e (shift down)]
16866 (lambda () (interactive)
16867 (org-eval-in-calendar '(calendar-forward-year 1))))
16868 (org-defkey map [(shift up)]
16869 (lambda () (interactive)
16870 (org-eval-in-calendar '(calendar-backward-week 1))))
16871 (org-defkey map [(shift down)]
16872 (lambda () (interactive)
16873 (org-eval-in-calendar '(calendar-forward-week 1))))
16874 (org-defkey map [(shift left)]
16875 (lambda () (interactive)
16876 (org-eval-in-calendar '(calendar-backward-day 1))))
16877 (org-defkey map [(shift right)]
16878 (lambda () (interactive)
16879 (org-eval-in-calendar '(calendar-forward-day 1))))
16880 (org-defkey map "!"
16881 (lambda () (interactive)
16882 (org-eval-in-calendar '(diary-view-entries))
16883 (message "")))
16884 (org-defkey map ">"
16885 (lambda () (interactive)
16886 (org-eval-in-calendar '(calendar-scroll-left 1))))
16887 (org-defkey map "<"
16888 (lambda () (interactive)
16889 (org-eval-in-calendar '(calendar-scroll-right 1))))
16890 (org-defkey map "\C-v"
16891 (lambda () (interactive)
16892 (org-eval-in-calendar
16893 '(calendar-scroll-left-three-months 1))))
16894 (org-defkey map "\M-v"
16895 (lambda () (interactive)
16896 (org-eval-in-calendar
16897 '(calendar-scroll-right-three-months 1))))
16898 map)
16899 "Keymap for minibuffer commands when using `org-read-date'.")
16901 (defvar org-def)
16902 (defvar org-defdecode)
16903 (defvar org-with-time)
16905 (defvar calendar-setup) ; Dynamically scoped.
16906 (defun org-read-date (&optional with-time to-time from-string prompt
16907 default-time default-input inactive)
16908 "Read a date, possibly a time, and make things smooth for the user.
16909 The prompt will suggest to enter an ISO date, but you can also enter anything
16910 which will at least partially be understood by `parse-time-string'.
16911 Unrecognized parts of the date will default to the current day, month, year,
16912 hour and minute. If this command is called to replace a timestamp at point,
16913 or to enter the second timestamp of a range, the default time is taken
16914 from the existing stamp. Furthermore, the command prefers the future,
16915 so if you are giving a date where the year is not given, and the day-month
16916 combination is already past in the current year, it will assume you
16917 mean next year. For details, see the manual. A few examples:
16919 3-2-5 --> 2003-02-05
16920 feb 15 --> currentyear-02-15
16921 2/15 --> currentyear-02-15
16922 sep 12 9 --> 2009-09-12
16923 12:45 --> today 12:45
16924 22 sept 0:34 --> currentyear-09-22 0:34
16925 12 --> currentyear-currentmonth-12
16926 Fri --> nearest Friday after today
16927 -Tue --> last Tuesday
16928 etc.
16930 Furthermore you can specify a relative date by giving, as the *first* thing
16931 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16932 change in days weeks, months, years.
16933 With a single plus or minus, the date is relative to today. With a double
16934 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16935 +4d --> four days from today
16936 +4 --> same as above
16937 +2w --> two weeks from today
16938 ++5 --> five days from default date
16940 The function understands only English month and weekday abbreviations.
16942 While prompting, a calendar is popped up - you can also select the
16943 date with the mouse (button 1). The calendar shows a period of three
16944 months. To scroll it to other months, use the keys `>' and `<'.
16945 If you don't like the calendar, turn it off with
16946 (setq org-read-date-popup-calendar nil)
16948 With optional argument TO-TIME, the date will immediately be converted
16949 to an internal time.
16950 With an optional argument WITH-TIME, the prompt will suggest to
16951 also insert a time. Note that when WITH-TIME is not set, you can
16952 still enter a time, and this function will inform the calling routine
16953 about this change. The calling routine may then choose to change the
16954 format used to insert the time stamp into the buffer to include the time.
16955 With optional argument FROM-STRING, read from this string instead from
16956 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16957 the time/date that is used for everything that is not specified by the
16958 user."
16959 (require 'parse-time)
16960 (let* ((org-with-time with-time)
16961 (org-time-stamp-rounding-minutes
16962 (if (equal org-with-time '(16))
16963 '(0 0)
16964 org-time-stamp-rounding-minutes))
16965 (org-dcst org-display-custom-times)
16966 (ct (org-current-time))
16967 (org-def (or org-overriding-default-time default-time ct))
16968 (org-defdecode (decode-time org-def))
16969 (cur-frame (selected-frame))
16970 (mouse-autoselect-window nil) ; Don't let the mouse jump
16971 (calendar-setup
16972 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16973 (calendar-move-hook nil)
16974 (calendar-view-diary-initially-flag nil)
16975 (calendar-view-holidays-initially-flag nil)
16976 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16977 ;; Rationalize `org-def' and `org-defdecode', if required.
16978 (when (< (nth 2 org-defdecode) org-extend-today-until)
16979 (setf (nth 2 org-defdecode) -1)
16980 (setf (nth 1 org-defdecode) 59)
16981 (setq org-def (apply #'encode-time org-defdecode))
16982 (setq org-defdecode (decode-time org-def)))
16983 (let* ((timestr (format-time-string
16984 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16985 org-def))
16986 (prompt (concat (if prompt (concat prompt " ") "")
16987 (format "Date+time [%s]: " timestr))))
16988 (cond
16989 (from-string (setq ans from-string))
16990 (org-read-date-popup-calendar
16991 (save-excursion
16992 (save-window-excursion
16993 (calendar)
16994 (when (eq calendar-setup 'calendar-only)
16995 (setq cal-frame
16996 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16997 (select-frame cal-frame))
16998 (org-eval-in-calendar '(setq cursor-type nil) t)
16999 (unwind-protect
17000 (progn
17001 (calendar-forward-day (- (time-to-days org-def)
17002 (calendar-absolute-from-gregorian
17003 (calendar-current-date))))
17004 (org-eval-in-calendar nil t)
17005 (let* ((old-map (current-local-map))
17006 (map (copy-keymap calendar-mode-map))
17007 (minibuffer-local-map
17008 (copy-keymap org-read-date-minibuffer-local-map)))
17009 (org-defkey map (kbd "RET") 'org-calendar-select)
17010 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17011 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17012 (unwind-protect
17013 (progn
17014 (use-local-map map)
17015 (setq org-read-date-inactive inactive)
17016 (add-hook 'post-command-hook 'org-read-date-display)
17017 (setq org-ans0
17018 (read-string prompt
17019 default-input
17020 'org-read-date-history
17021 nil))
17022 ;; org-ans0: from prompt
17023 ;; org-ans1: from mouse click
17024 ;; org-ans2: from calendar motion
17025 (setq ans
17026 (concat org-ans0 " " (or org-ans1 org-ans2))))
17027 (remove-hook 'post-command-hook 'org-read-date-display)
17028 (use-local-map old-map)
17029 (when org-read-date-overlay
17030 (delete-overlay org-read-date-overlay)
17031 (setq org-read-date-overlay nil)))))
17032 (bury-buffer "*Calendar*")
17033 (when cal-frame
17034 (delete-frame cal-frame)
17035 (select-frame-set-input-focus cur-frame))))))
17037 (t ; Naked prompt only
17038 (unwind-protect
17039 (setq ans (read-string prompt default-input
17040 'org-read-date-history timestr))
17041 (when org-read-date-overlay
17042 (delete-overlay org-read-date-overlay)
17043 (setq org-read-date-overlay nil))))))
17045 (setq final (org-read-date-analyze ans org-def org-defdecode))
17047 (when org-read-date-analyze-forced-year
17048 (message "Year was forced into %s"
17049 (if org-read-date-force-compatible-dates
17050 "compatible range (1970-2037)"
17051 "range representable on this machine"))
17052 (ding))
17054 ;; One round trip to get rid of 34th of August and stuff like that....
17055 (setq final (decode-time (apply 'encode-time final)))
17057 (setq org-read-date-final-answer ans)
17059 (if to-time
17060 (apply 'encode-time final)
17061 (if (and (boundp 'org-time-was-given) org-time-was-given)
17062 (format "%04d-%02d-%02d %02d:%02d"
17063 (nth 5 final) (nth 4 final) (nth 3 final)
17064 (nth 2 final) (nth 1 final))
17065 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17067 (defun org-read-date-display ()
17068 "Display the current date prompt interpretation in the minibuffer."
17069 (when org-read-date-display-live
17070 (when org-read-date-overlay
17071 (delete-overlay org-read-date-overlay))
17072 (when (minibufferp (current-buffer))
17073 (save-excursion
17074 (end-of-line 1)
17075 (while (not (equal (buffer-substring
17076 (max (point-min) (- (point) 4)) (point))
17077 " "))
17078 (insert " ")))
17079 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17080 " " (or org-ans1 org-ans2)))
17081 (org-end-time-was-given nil)
17082 (f (org-read-date-analyze ans org-def org-defdecode))
17083 (fmts (if org-dcst
17084 org-time-stamp-custom-formats
17085 org-time-stamp-formats))
17086 (fmt (if (or org-with-time
17087 (and (boundp 'org-time-was-given) org-time-was-given))
17088 (cdr fmts)
17089 (car fmts)))
17090 (txt (format-time-string fmt (apply 'encode-time f)))
17091 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17092 (txt (concat "=> " txt)))
17093 (when (and org-end-time-was-given
17094 (string-match org-plain-time-of-day-regexp txt))
17095 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17096 org-end-time-was-given
17097 (substring txt (match-end 0)))))
17098 (when org-read-date-analyze-futurep
17099 (setq txt (concat txt " (=>F)")))
17100 (setq org-read-date-overlay
17101 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17102 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17104 (defun org-read-date-analyze (ans def defdecode)
17105 "Analyze the combined answer of the date prompt."
17106 ;; FIXME: cleanup and comment
17107 ;; Pass `current-time' result to `decode-time' (instead of calling
17108 ;; without arguments) so that only `current-time' has to be
17109 ;; overridden in tests.
17110 (let ((org-def def)
17111 (org-defdecode defdecode)
17112 (nowdecode (decode-time (current-time)))
17113 delta deltan deltaw deltadef year month day
17114 hour minute second wday pm h2 m2 tl wday1
17115 iso-year iso-weekday iso-week iso-date futurep kill-year)
17116 (setq org-read-date-analyze-futurep nil
17117 org-read-date-analyze-forced-year nil)
17118 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17119 (setq ans "+0"))
17121 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17122 (setq ans (replace-match "" t t ans)
17123 deltan (car delta)
17124 deltaw (nth 1 delta)
17125 deltadef (nth 2 delta)))
17127 ;; Check if there is an iso week date in there. If yes, store the
17128 ;; info and postpone interpreting it until the rest of the parsing
17129 ;; is done.
17130 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17131 (setq iso-year (when (match-end 1)
17132 (org-small-year-to-year
17133 (string-to-number (match-string 1 ans))))
17134 iso-weekday (when (match-end 3)
17135 (string-to-number (match-string 3 ans)))
17136 iso-week (string-to-number (match-string 2 ans)))
17137 (setq ans (replace-match "" t t ans)))
17139 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17140 (when (string-match
17141 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17142 (setq year (if (match-end 2)
17143 (string-to-number (match-string 2 ans))
17144 (progn (setq kill-year t)
17145 (string-to-number (format-time-string "%Y"))))
17146 month (string-to-number (match-string 3 ans))
17147 day (string-to-number (match-string 4 ans)))
17148 (setq year (org-small-year-to-year year))
17149 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17150 t nil ans)))
17152 ;; Help matching dotted european dates
17153 (when (string-match
17154 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17155 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17156 (setq kill-year t)
17157 (string-to-number (format-time-string "%Y")))
17158 day (string-to-number (match-string 1 ans))
17159 month (string-to-number (match-string 2 ans))
17160 ans (replace-match (format "%04d-%02d-%02d" year month day)
17161 t nil ans)))
17163 ;; Help matching american dates, like 5/30 or 5/30/7
17164 (when (string-match
17165 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17166 (setq year (if (match-end 4)
17167 (string-to-number (match-string 4 ans))
17168 (progn (setq kill-year t)
17169 (string-to-number (format-time-string "%Y"))))
17170 month (string-to-number (match-string 1 ans))
17171 day (string-to-number (match-string 2 ans)))
17172 (setq year (org-small-year-to-year year))
17173 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17174 t nil ans)))
17175 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17176 ;; If there is a time with am/pm, and *no* time without it, we convert
17177 ;; so that matching will be successful.
17178 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17179 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17180 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17181 (setq hour (string-to-number (match-string 1 ans))
17182 minute (if (match-end 3)
17183 (string-to-number (match-string 3 ans))
17185 pm (equal ?p
17186 (string-to-char (downcase (match-string 4 ans)))))
17187 (if (and (= hour 12) (not pm))
17188 (setq hour 0)
17189 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17190 (setq ans (replace-match (format "%02d:%02d" hour minute)
17191 t t ans))))
17193 ;; Check if a time range is given as a duration
17194 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17195 (setq hour (string-to-number (match-string 1 ans))
17196 h2 (+ hour (string-to-number (match-string 3 ans)))
17197 minute (string-to-number (match-string 2 ans))
17198 m2 (+ minute (if (match-end 5) (string-to-number
17199 (match-string 5 ans))0)))
17200 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17201 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17202 t t ans)))
17204 ;; Check if there is a time range
17205 (when (boundp 'org-end-time-was-given)
17206 (setq org-time-was-given nil)
17207 (when (and (string-match org-plain-time-of-day-regexp ans)
17208 (match-end 8))
17209 (setq org-end-time-was-given (match-string 8 ans))
17210 (setq ans (concat (substring ans 0 (match-beginning 7))
17211 (substring ans (match-end 7))))))
17213 (setq tl (parse-time-string ans)
17214 day (or (nth 3 tl) (nth 3 org-defdecode))
17215 month
17216 (cond ((nth 4 tl))
17217 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17218 ;; Day was specified. Make sure DAY+MONTH
17219 ;; combination happens in the future.
17220 ((nth 3 tl)
17221 (setq futurep t)
17222 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17223 (nth 4 nowdecode)))
17224 (t (nth 4 org-defdecode)))
17225 year
17226 (cond ((and (not kill-year) (nth 5 tl)))
17227 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17228 ;; Month was guessed in the future and is at least
17229 ;; equal to NOWDECODE's. Fix year accordingly.
17230 (futurep
17231 (if (or (> month (nth 4 nowdecode))
17232 (>= day (nth 3 nowdecode)))
17233 (nth 5 nowdecode)
17234 (1+ (nth 5 nowdecode))))
17235 ;; Month was specified. Make sure MONTH+YEAR
17236 ;; combination happens in the future.
17237 ((nth 4 tl)
17238 (setq futurep t)
17239 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17240 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17241 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17242 (t (nth 5 nowdecode))))
17243 (t (nth 5 org-defdecode)))
17244 hour (or (nth 2 tl) (nth 2 org-defdecode))
17245 minute (or (nth 1 tl) (nth 1 org-defdecode))
17246 second (or (nth 0 tl) 0)
17247 wday (nth 6 tl))
17249 (when (and (eq org-read-date-prefer-future 'time)
17250 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17251 (equal day (nth 3 nowdecode))
17252 (equal month (nth 4 nowdecode))
17253 (equal year (nth 5 nowdecode))
17254 (nth 2 tl)
17255 (or (< (nth 2 tl) (nth 2 nowdecode))
17256 (and (= (nth 2 tl) (nth 2 nowdecode))
17257 (nth 1 tl)
17258 (< (nth 1 tl) (nth 1 nowdecode)))))
17259 (setq day (1+ day)
17260 futurep t))
17262 ;; Special date definitions below
17263 (cond
17264 (iso-week
17265 ;; There was an iso week
17266 (require 'cal-iso)
17267 (setq futurep nil)
17268 (setq year (or iso-year year)
17269 day (or iso-weekday wday 1)
17270 wday nil ; to make sure that the trigger below does not match
17271 iso-date (calendar-gregorian-from-absolute
17272 (calendar-iso-to-absolute
17273 (list iso-week day year))))
17274 ; FIXME: Should we also push ISO weeks into the future?
17275 ; (when (and org-read-date-prefer-future
17276 ; (not iso-year)
17277 ; (< (calendar-absolute-from-gregorian iso-date)
17278 ; (time-to-days (current-time))))
17279 ; (setq year (1+ year)
17280 ; iso-date (calendar-gregorian-from-absolute
17281 ; (calendar-iso-to-absolute
17282 ; (list iso-week day year)))))
17283 (setq month (car iso-date)
17284 year (nth 2 iso-date)
17285 day (nth 1 iso-date)))
17286 (deltan
17287 (setq futurep nil)
17288 (unless deltadef
17289 ;; Pass `current-time' result to `decode-time' (instead of
17290 ;; calling without arguments) so that only `current-time' has
17291 ;; to be overridden in tests.
17292 (let ((now (decode-time (current-time))))
17293 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17294 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17295 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17296 ((equal deltaw "m") (setq month (+ month deltan)))
17297 ((equal deltaw "y") (setq year (+ year deltan)))))
17298 ((and wday (not (nth 3 tl)))
17299 ;; Weekday was given, but no day, so pick that day in the week
17300 ;; on or after the derived date.
17301 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17302 (unless (equal wday wday1)
17303 (setq day (+ day (% (- wday wday1 -7) 7))))))
17304 (when (and (boundp 'org-time-was-given)
17305 (nth 2 tl))
17306 (setq org-time-was-given t))
17307 (when (< year 100) (setq year (+ 2000 year)))
17308 ;; Check of the date is representable
17309 (if org-read-date-force-compatible-dates
17310 (progn
17311 (when (< year 1970)
17312 (setq year 1970 org-read-date-analyze-forced-year t))
17313 (when (> year 2037)
17314 (setq year 2037 org-read-date-analyze-forced-year t)))
17315 (condition-case nil
17316 (ignore (encode-time second minute hour day month year))
17317 (error
17318 (setq year (nth 5 org-defdecode))
17319 (setq org-read-date-analyze-forced-year t))))
17320 (setq org-read-date-analyze-futurep futurep)
17321 (list second minute hour day month year)))
17323 (defvar parse-time-weekdays)
17324 (defun org-read-date-get-relative (s today default)
17325 "Check string S for special relative date string.
17326 TODAY and DEFAULT are internal times, for today and for a default.
17327 Return shift list (N what def-flag)
17328 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17329 N is the number of WHATs to shift.
17330 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17331 the DEFAULT date rather than TODAY."
17332 (require 'parse-time)
17333 (when (and
17334 (string-match
17335 (concat
17336 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17337 "\\([0-9]+\\)?"
17338 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17339 "\\([ \t]\\|$\\)") s)
17340 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17341 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17342 (string-to-char (substring (match-string 1 s) -1))
17343 ?+))
17344 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17345 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17346 (what (if (match-end 3) (match-string 3 s) "d"))
17347 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17348 (date (if rel default today))
17349 (wday (nth 6 (decode-time date)))
17350 delta)
17351 (if wday1
17352 (progn
17353 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17354 (when (= delta 0) (setq delta 7))
17355 (when (= dir ?-)
17356 (setq delta (- delta 7))
17357 (when (= delta 0) (setq delta -7)))
17358 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17359 (list delta "d" rel))
17360 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17362 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17363 "Turn a user-specified date into the internal representation.
17364 The internal representation needed by the calendar is (month day year).
17365 This is a wrapper to handle the brain-dead convention in calendar that
17366 user function argument order change dependent on argument order."
17367 (pcase calendar-date-style
17368 (`american (list arg1 arg2 arg3))
17369 (`european (list arg2 arg1 arg3))
17370 (`iso (list arg2 arg3 arg1))))
17372 (defun org-eval-in-calendar (form &optional keepdate)
17373 "Eval FORM in the calendar window and return to current window.
17374 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17375 (let ((sf (selected-frame))
17376 (sw (selected-window)))
17377 (select-window (get-buffer-window "*Calendar*" t))
17378 (eval form)
17379 (when (and (not keepdate) (calendar-cursor-to-date))
17380 (let* ((date (calendar-cursor-to-date))
17381 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17382 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17383 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17384 (select-window sw)
17385 (select-frame-set-input-focus sf)))
17387 (defun org-calendar-select ()
17388 "Return to `org-read-date' with the date currently selected.
17389 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17390 (interactive)
17391 (when (calendar-cursor-to-date)
17392 (let* ((date (calendar-cursor-to-date))
17393 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17394 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17395 (when (active-minibuffer-window) (exit-minibuffer))))
17397 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17398 "Insert a date stamp for the date given by the internal TIME.
17399 See `format-time-string' for the format of TIME.
17400 WITH-HM means use the stamp format that includes the time of the day.
17401 INACTIVE means use square brackets instead of angular ones, so that the
17402 stamp will not contribute to the agenda.
17403 PRE and POST are optional strings to be inserted before and after the
17404 stamp.
17405 The command returns the inserted time stamp."
17406 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17407 stamp)
17408 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17409 (insert-before-markers (or pre ""))
17410 (when (listp extra)
17411 (setq extra (car extra))
17412 (if (and (stringp extra)
17413 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17414 (setq extra (format "-%02d:%02d"
17415 (string-to-number (match-string 1 extra))
17416 (string-to-number (match-string 2 extra))))
17417 (setq extra nil)))
17418 (when extra
17419 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17420 (insert-before-markers (setq stamp (format-time-string fmt time)))
17421 (insert-before-markers (or post ""))
17422 (setq org-last-inserted-timestamp stamp)))
17424 (defun org-toggle-time-stamp-overlays ()
17425 "Toggle the use of custom time stamp formats."
17426 (interactive)
17427 (setq org-display-custom-times (not org-display-custom-times))
17428 (unless org-display-custom-times
17429 (let ((p (point-min)) (bmp (buffer-modified-p)))
17430 (while (setq p (next-single-property-change p 'display))
17431 (when (and (get-text-property p 'display)
17432 (eq (get-text-property p 'face) 'org-date))
17433 (remove-text-properties
17434 p (setq p (next-single-property-change p 'display))
17435 '(display t))))
17436 (set-buffer-modified-p bmp)))
17437 (org-restart-font-lock)
17438 (setq org-table-may-need-update t)
17439 (if org-display-custom-times
17440 (message "Time stamps are overlaid with custom format")
17441 (message "Time stamp overlays removed")))
17443 (defun org-display-custom-time (beg end)
17444 "Overlay modified time stamp format over timestamp between BEG and END."
17445 (let* ((ts (buffer-substring beg end))
17446 t1 w1 with-hm tf time str w2 (off 0))
17447 (save-match-data
17448 (setq t1 (org-parse-time-string ts t))
17449 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17450 (setq off (- (match-end 0) (match-beginning 0)))))
17451 (setq end (- end off))
17452 (setq w1 (- end beg)
17453 with-hm (and (nth 1 t1) (nth 2 t1))
17454 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17455 time (org-fix-decoded-time t1)
17456 str (org-add-props
17457 (format-time-string
17458 (substring tf 1 -1) (apply 'encode-time time))
17459 nil 'mouse-face 'highlight)
17460 w2 (length str))
17461 (unless (= w2 w1)
17462 (add-text-properties (1+ beg) (+ 2 beg)
17463 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17464 (put-text-property beg end 'display str)))
17466 (defun org-fix-decoded-time (time)
17467 "Set 0 instead of nil for the first 6 elements of time.
17468 Don't touch the rest."
17469 (let ((n 0))
17470 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17472 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17473 "Difference between TIMESTAMP-STRING and now in days.
17474 If SECONDS is non-nil, return the difference in seconds."
17475 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17476 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17477 (funcall fdiff (current-time)))))
17479 (defun org-deadline-close-p (timestamp-string &optional ndays)
17480 "Is the time in TIMESTAMP-STRING close to the current date?"
17481 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17482 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17483 (not (org-entry-is-done-p))))
17485 (defun org-get-wdays (ts &optional delay zero-delay)
17486 "Get the deadline lead time appropriate for timestring TS.
17487 When DELAY is non-nil, get the delay time for scheduled items
17488 instead of the deadline lead time. When ZERO-DELAY is non-nil
17489 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17490 don't try to find the delay cookie in the scheduled timestamp."
17491 (let ((tv (if delay org-scheduled-delay-days
17492 org-deadline-warning-days)))
17493 (cond
17494 ((or (and delay (< tv 0))
17495 (and delay zero-delay (<= tv 0))
17496 (and (not delay) (<= tv 0)))
17497 ;; Enforce this value no matter what
17498 (- tv))
17499 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17500 ;; lead time is specified.
17501 (floor (* (string-to-number (match-string 1 ts))
17502 (cdr (assoc (match-string 2 ts)
17503 '(("d" . 1) ("w" . 7)
17504 ("m" . 30.4) ("y" . 365.25)
17505 ("h" . 0.041667)))))))
17506 ;; go for the default.
17507 (t tv))))
17509 (defun org-calendar-select-mouse (ev)
17510 "Return to `org-read-date' with the date currently selected.
17511 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17512 (interactive "e")
17513 (mouse-set-point ev)
17514 (when (calendar-cursor-to-date)
17515 (let* ((date (calendar-cursor-to-date))
17516 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17517 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17518 (when (active-minibuffer-window) (exit-minibuffer))))
17520 (defun org-check-deadlines (ndays)
17521 "Check if there are any deadlines due or past due.
17522 A deadline is considered due if it happens within `org-deadline-warning-days'
17523 days from today's date. If the deadline appears in an entry marked DONE,
17524 it is not shown. A numeric prefix argument NDAYS can be used to test that
17525 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17526 are shown."
17527 (interactive "P")
17528 (let* ((org-warn-days
17529 (cond
17530 ((equal ndays '(4)) 100000)
17531 (ndays (prefix-numeric-value ndays))
17532 (t (abs org-deadline-warning-days))))
17533 (case-fold-search nil)
17534 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17535 (callback
17536 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17537 (message "%d deadlines past-due or due within %d days"
17538 (org-occur regexp nil callback)
17539 org-warn-days)))
17541 (defsubst org-re-timestamp (type)
17542 "Return a regexp for timestamp TYPE.
17543 Allowed values for TYPE are:
17545 all: all timestamps
17546 active: only active timestamps (<...>)
17547 inactive: only inactive timestamps ([...])
17548 scheduled: only scheduled timestamps
17549 deadline: only deadline timestamps
17550 closed: only closed time-stamps
17552 When TYPE is nil, fall back on returning a regexp that matches
17553 both scheduled and deadline timestamps."
17554 (cl-case type
17555 (all org-ts-regexp-both)
17556 (active org-ts-regexp)
17557 (inactive org-ts-regexp-inactive)
17558 (scheduled org-scheduled-time-regexp)
17559 (deadline org-deadline-time-regexp)
17560 (closed org-closed-time-regexp)
17561 (otherwise
17562 (concat "\\<"
17563 (regexp-opt (list org-deadline-string org-scheduled-string))
17564 " *<\\([^>]+\\)>"))))
17566 (defun org-check-before-date (d)
17567 "Check if there are deadlines or scheduled entries before date D."
17568 (interactive (list (org-read-date)))
17569 (let* ((case-fold-search nil)
17570 (regexp (org-re-timestamp org-ts-type))
17571 (ts-type org-ts-type)
17572 (callback
17573 (lambda ()
17574 (let ((match (match-string 1)))
17575 (and (if (memq ts-type '(active inactive all))
17576 (eq (org-element-type (save-excursion
17577 (backward-char)
17578 (org-element-context)))
17579 'timestamp)
17580 (org-at-planning-p))
17581 (time-less-p
17582 (org-time-string-to-time match)
17583 (org-time-string-to-time d)))))))
17584 (message "%d entries before %s"
17585 (org-occur regexp nil callback)
17586 d)))
17588 (defun org-check-after-date (d)
17589 "Check if there are deadlines or scheduled entries after date D."
17590 (interactive (list (org-read-date)))
17591 (let* ((case-fold-search nil)
17592 (regexp (org-re-timestamp org-ts-type))
17593 (ts-type org-ts-type)
17594 (callback
17595 (lambda ()
17596 (let ((match (match-string 1)))
17597 (and (if (memq ts-type '(active inactive all))
17598 (eq (org-element-type (save-excursion
17599 (backward-char)
17600 (org-element-context)))
17601 'timestamp)
17602 (org-at-planning-p))
17603 (not (time-less-p
17604 (org-time-string-to-time match)
17605 (org-time-string-to-time d))))))))
17606 (message "%d entries after %s"
17607 (org-occur regexp nil callback)
17608 d)))
17610 (defun org-check-dates-range (start-date end-date)
17611 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17612 (interactive (list (org-read-date nil nil nil "Range starts")
17613 (org-read-date nil nil nil "Range end")))
17614 (let ((case-fold-search nil)
17615 (regexp (org-re-timestamp org-ts-type))
17616 (callback
17617 (let ((type org-ts-type))
17618 (lambda ()
17619 (let ((match (match-string 1)))
17620 (and
17621 (if (memq type '(active inactive all))
17622 (eq (org-element-type (save-excursion
17623 (backward-char)
17624 (org-element-context)))
17625 'timestamp)
17626 (org-at-planning-p))
17627 (not (time-less-p
17628 (org-time-string-to-time match)
17629 (org-time-string-to-time start-date)))
17630 (time-less-p
17631 (org-time-string-to-time match)
17632 (org-time-string-to-time end-date))))))))
17633 (message "%d entries between %s and %s"
17634 (org-occur regexp nil callback) start-date end-date)))
17636 (defun org-evaluate-time-range (&optional to-buffer)
17637 "Evaluate a time range by computing the difference between start and end.
17638 Normally the result is just printed in the echo area, but with prefix arg
17639 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17640 If the time range is actually in a table, the result is inserted into the
17641 next column.
17642 For time difference computation, a year is assumed to be exactly 365
17643 days in order to avoid rounding problems."
17644 (interactive "P")
17646 (org-clock-update-time-maybe)
17647 (save-excursion
17648 (unless (org-at-date-range-p t)
17649 (goto-char (point-at-bol))
17650 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17651 (unless (org-at-date-range-p t)
17652 (user-error "Not at a time-stamp range, and none found in current line")))
17653 (let* ((ts1 (match-string 1))
17654 (ts2 (match-string 2))
17655 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17656 (match-end (match-end 0))
17657 (time1 (org-time-string-to-time ts1))
17658 (time2 (org-time-string-to-time ts2))
17659 (t1 (float-time time1))
17660 (t2 (float-time time2))
17661 (diff (abs (- t2 t1)))
17662 (negative (< (- t2 t1) 0))
17663 ;; (ys (floor (* 365 24 60 60)))
17664 (ds (* 24 60 60))
17665 (hs (* 60 60))
17666 (fy "%dy %dd %02d:%02d")
17667 (fy1 "%dy %dd")
17668 (fd "%dd %02d:%02d")
17669 (fd1 "%dd")
17670 (fh "%02d:%02d")
17671 y d h m align)
17672 (if havetime
17673 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17675 d (floor (/ diff ds)) diff (mod diff ds)
17676 h (floor (/ diff hs)) diff (mod diff hs)
17677 m (floor (/ diff 60)))
17678 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17680 d (floor (+ (/ diff ds) 0.5))
17681 h 0 m 0))
17682 (if (not to-buffer)
17683 (message "%s" (org-make-tdiff-string y d h m))
17684 (if (org-at-table-p)
17685 (progn
17686 (goto-char match-end)
17687 (setq align t)
17688 (and (looking-at " *|") (goto-char (match-end 0))))
17689 (goto-char match-end))
17690 (when (looking-at
17691 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17692 (replace-match ""))
17693 (when negative (insert " -"))
17694 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17695 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17696 (insert " " (format fh h m))))
17697 (when align (org-table-align))
17698 (message "Time difference inserted")))))
17700 (defun org-make-tdiff-string (y d h m)
17701 (let ((fmt "")
17702 (l nil))
17703 (when (> y 0)
17704 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17705 (push y l))
17706 (when (> d 0)
17707 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17708 (push d l))
17709 (when (> h 0)
17710 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17711 (push h l))
17712 (when (> m 0)
17713 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17714 (push m l))
17715 (apply 'format fmt (nreverse l))))
17717 (defun org-time-string-to-time (s &optional buffer pos)
17718 "Convert a timestamp string into internal time."
17719 (condition-case errdata
17720 (apply 'encode-time (org-parse-time-string s))
17721 (error (error "Bad timestamp `%s'%s\nError was: %s"
17722 s (if (not (and buffer pos))
17724 (format-message " at %d in buffer `%s'" pos buffer))
17725 (cdr errdata)))))
17727 (defun org-time-string-to-seconds (s)
17728 "Convert a timestamp string to a number of seconds."
17729 (float-time (org-time-string-to-time s)))
17731 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17733 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17734 "Convert time stamp S to an absolute day number.
17736 If DAYNR in non-nil, and there is a specifier for a cyclic time
17737 stamp, get the closest date to DAYNR. If PREFER is
17738 `past' (respectively `future') return a date past (respectively
17739 after) or equal to DAYNR.
17741 POS is the location of time stamp S, as a buffer position in
17742 BUFFER.
17744 Diary sexp timestamps are matched against DAYNR, when non-nil.
17745 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17746 signaled."
17747 (cond
17748 ((string-match "\\`%%\\((.*)\\)" s)
17749 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17750 ;; only able to match individual dates. If it fails, raise an
17751 ;; error.
17752 (if (and daynr
17753 (org-diary-sexp-entry
17754 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17755 daynr
17756 (signal 'org-diary-sexp-no-match (list s))))
17757 (daynr (org-closest-date s daynr prefer))
17758 (t (time-to-days
17759 (condition-case errdata
17760 (apply #'encode-time (org-parse-time-string s))
17761 (error (error "Bad timestamp `%s'%s\nError was: %s"
17763 (if (not (and buffer pos)) ""
17764 (format-message " at %d in buffer `%s'" pos buffer))
17765 (cdr errdata))))))))
17767 (defun org-days-to-iso-week (days)
17768 "Return the iso week number."
17769 (require 'cal-iso)
17770 (car (calendar-iso-from-absolute days)))
17772 (defun org-small-year-to-year (year)
17773 "Convert 2-digit years into 4-digit years.
17774 YEAR is expanded into one of the 30 next years, if possible, or
17775 into a past one. Any year larger than 99 is returned unchanged."
17776 (if (>= year 100) year
17777 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17778 (century (/ current 100))
17779 (offset (- year (% current 100))))
17780 (cond ((> offset 30) (+ (* (1- century) 100) year))
17781 ((> offset -70) (+ (* century 100) year))
17782 (t (+ (* (1+ century) 100) year))))))
17784 (defun org-time-from-absolute (d)
17785 "Return the time corresponding to date D.
17786 D may be an absolute day number, or a calendar-type list (month day year)."
17787 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17788 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17790 (defvar org-agenda-current-date)
17791 (defun org-calendar-holiday ()
17792 "List of holidays, for Diary display in Org mode."
17793 (require 'holidays)
17794 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17795 (and hl (mapconcat #'identity hl "; "))))
17797 (defun org-diary-sexp-entry (sexp entry d)
17798 "Process a SEXP diary ENTRY for date D."
17799 (require 'diary-lib)
17800 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17801 ;; dynamically.
17802 (let* ((sexp `(let ((entry ,entry)
17803 (date ',d))
17804 ,(car (read-from-string sexp))))
17805 (result (if calendar-debug-sexp (eval sexp)
17806 (condition-case nil
17807 (eval sexp)
17808 (error
17809 (beep)
17810 (message "Bad sexp at line %d in %s: %s"
17811 (org-current-line)
17812 (buffer-file-name) sexp)
17813 (sleep-for 2))))))
17814 (cond ((stringp result) (split-string result "; "))
17815 ((and (consp result)
17816 (not (consp (cdr result)))
17817 (stringp (cdr result))) (cdr result))
17818 ((and (consp result)
17819 (stringp (car result))) result)
17820 (result entry))))
17822 (defun org-diary-to-ical-string (frombuf)
17823 "Get iCalendar entries from diary entries in buffer FROMBUF.
17824 This uses the icalendar.el library."
17825 (let* ((tmpdir temporary-file-directory)
17826 (tmpfile (make-temp-name
17827 (expand-file-name "orgics" tmpdir)))
17828 buf rtn b e)
17829 (with-current-buffer frombuf
17830 (icalendar-export-region (point-min) (point-max) tmpfile)
17831 (setq buf (find-buffer-visiting tmpfile))
17832 (set-buffer buf)
17833 (goto-char (point-min))
17834 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17835 (setq b (match-beginning 0)))
17836 (goto-char (point-max))
17837 (when (re-search-backward "^END:VEVENT" nil t)
17838 (setq e (match-end 0)))
17839 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17840 (kill-buffer buf)
17841 (delete-file tmpfile)
17842 rtn))
17844 (defun org-closest-date (start current prefer)
17845 "Return closest date to CURRENT starting from START.
17847 CURRENT and START are both time stamps.
17849 When PREFER is `past', return a date that is either CURRENT or
17850 past. When PREFER is `future', return a date that is either
17851 CURRENT or future.
17853 Only time stamps with a repeater are modified. Any other time
17854 stamp stay unchanged. In any case, return value is an absolute
17855 day number."
17856 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17857 ;; No repeater. Do not shift time stamp.
17858 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17859 (let ((value (string-to-number (match-string 1 start)))
17860 (type (match-string 2 start)))
17861 (if (= 0 value)
17862 ;; Repeater with a 0-value is considered as void.
17863 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17864 (let* ((base (org-date-to-gregorian start))
17865 (target (org-date-to-gregorian current))
17866 (sday (calendar-absolute-from-gregorian base))
17867 (cday (calendar-absolute-from-gregorian target))
17868 n1 n2)
17869 ;; If START is already past CURRENT, just return START.
17870 (if (<= cday sday) sday
17871 ;; Compute closest date before (N1) and closest date past
17872 ;; (N2) CURRENT.
17873 (pcase type
17874 ("h"
17875 (let ((missing-hours
17876 (mod (+ (- (* 24 (- cday sday))
17877 (nth 2 (org-parse-time-string start)))
17878 org-extend-today-until)
17879 value)))
17880 (setf n1 (if (= missing-hours 0) cday
17881 (- cday (1+ (/ missing-hours 24)))))
17882 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17883 ((or "d" "w")
17884 (let ((value (if (equal type "w") (* 7 value) value)))
17885 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17886 (setf n2 (+ n1 value))))
17887 ("m"
17888 (let* ((add-months
17889 (lambda (d n)
17890 ;; Add N months to gregorian date D, i.e.,
17891 ;; a list (MONTH DAY YEAR). Return a valid
17892 ;; gregorian date.
17893 (let ((m (+ (nth 0 d) n)))
17894 (list (mod m 12)
17895 (nth 1 d)
17896 (+ (/ m 12) (nth 2 d))))))
17897 (months ; Complete months to TARGET.
17898 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17899 (- (nth 0 target) (nth 0 base))
17900 ;; If START's day is greater than
17901 ;; TARGET's, remove incomplete month.
17902 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17903 value)
17904 value))
17905 (before (funcall add-months base months)))
17906 (setf n1 (calendar-absolute-from-gregorian before))
17907 (setf n2
17908 (calendar-absolute-from-gregorian
17909 (funcall add-months before value)))))
17911 (let* ((d (nth 1 base))
17912 (m (nth 0 base))
17913 (y (nth 2 base))
17914 (years ; Complete years to TARGET.
17915 (* (/ (- (nth 2 target)
17917 ;; If START's month and day are
17918 ;; greater than TARGET's, remove
17919 ;; incomplete year.
17920 (if (or (> (nth 0 target) m)
17921 (and (= (nth 0 target) m)
17922 (> (nth 1 target) d)))
17925 value)
17926 value))
17927 (before (list m d (+ y years))))
17928 (setf n1 (calendar-absolute-from-gregorian before))
17929 (setf n2 (calendar-absolute-from-gregorian
17930 (list m d (+ (nth 2 before) value)))))))
17931 ;; Handle PREFER parameter, if any.
17932 (cond
17933 ((eq prefer 'past) (if (= cday n2) n2 n1))
17934 ((eq prefer 'future) (if (= cday n1) n1 n2))
17935 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17937 (defun org-date-to-gregorian (d)
17938 "Turn any specification of date D into a Gregorian date for the calendar."
17939 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17940 ((and (listp d) (= (length d) 3)) d)
17941 ((stringp d)
17942 (let ((d (org-parse-time-string d)))
17943 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17944 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17946 (defun org-parse-time-string (s &optional nodefault zone)
17947 "Parse the standard Org time string.
17949 This should be a lot faster than the normal `parse-time-string'.
17951 If time is not given, defaults to 0:00. However, with optional
17952 NODEFAULT, hour and minute fields will be nil if not given.
17954 The optional ZONE is omitted or nil for Emacs local time, t for
17955 Universal Time, ‘wall’ for system wall clock time, or a string as
17956 in the TZ environment variable."
17957 (cond ((string-match org-ts-regexp0 s)
17958 (list 0
17959 (when (or (match-beginning 8) (not nodefault))
17960 (string-to-number (or (match-string 8 s) "0")))
17961 (when (or (match-beginning 7) (not nodefault))
17962 (string-to-number (or (match-string 7 s) "0")))
17963 (string-to-number (match-string 4 s))
17964 (string-to-number (match-string 3 s))
17965 (string-to-number (match-string 2 s))
17966 nil nil zone))
17967 ((string-match "^<[^>]+>$" s)
17968 ;; FIXME: `decode-time' needs to be called with ZONE as its
17969 ;; second argument. However, this requires at least Emacs
17970 ;; 25.1. We can do it when we switch to this version as our
17971 ;; minimal requirement.
17972 (decode-time (seconds-to-time (org-matcher-time s))))
17973 (t (error "Not a standard Org time string: %s" s))))
17975 (defun org-timestamp-up (&optional arg)
17976 "Increase the date item at the cursor by one.
17977 If the cursor is on the year, change the year. If it is on the month,
17978 the day or the time, change that.
17979 With prefix ARG, change by that many units."
17980 (interactive "p")
17981 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17983 (defun org-timestamp-down (&optional arg)
17984 "Decrease the date item at the cursor by one.
17985 If the cursor is on the year, change the year. If it is on the month,
17986 the day or the time, change that.
17987 With prefix ARG, change by that many units."
17988 (interactive "p")
17989 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17991 (defun org-timestamp-up-day (&optional arg)
17992 "Increase the date in the time stamp by one day.
17993 With prefix ARG, change that many days."
17994 (interactive "p")
17995 (if (and (not (org-at-timestamp-p t))
17996 (org-at-heading-p))
17997 (org-todo 'up)
17998 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
18000 (defun org-timestamp-down-day (&optional arg)
18001 "Decrease the date in the time stamp by one day.
18002 With prefix ARG, change that many days."
18003 (interactive "p")
18004 (if (and (not (org-at-timestamp-p t))
18005 (org-at-heading-p))
18006 (org-todo 'down)
18007 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
18009 (defun org-at-timestamp-p (&optional inactive-ok)
18010 "Non-nil if point is inside a timestamp.
18012 When optional argument INACTIVE-OK is non-nil, also consider
18013 inactive timestamps.
18015 When this function returns a non-nil value, match data is set
18016 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18017 INACTIVE-OK."
18018 (interactive)
18019 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18020 (pos (point))
18021 (ans (or (looking-at tsr)
18022 (save-excursion
18023 (skip-chars-backward "^[<\n\r\t")
18024 (when (> (point) (point-min)) (backward-char 1))
18025 (and (looking-at tsr)
18026 (> (- (match-end 0) pos) -1))))))
18027 (and ans
18028 (boundp 'org-ts-what)
18029 (setq org-ts-what
18030 (cond
18031 ((= pos (match-beginning 0)) 'bracket)
18032 ;; Point is considered to be "on the bracket" whether
18033 ;; it's really on it or right after it.
18034 ((= pos (1- (match-end 0))) 'bracket)
18035 ((= pos (match-end 0)) 'after)
18036 ((org-pos-in-match-range pos 2) 'year)
18037 ((org-pos-in-match-range pos 3) 'month)
18038 ((org-pos-in-match-range pos 7) 'hour)
18039 ((org-pos-in-match-range pos 8) 'minute)
18040 ((or (org-pos-in-match-range pos 4)
18041 (org-pos-in-match-range pos 5)) 'day)
18042 ((and (> pos (or (match-end 8) (match-end 5)))
18043 (< pos (match-end 0)))
18044 (- pos (or (match-end 8) (match-end 5))))
18045 (t 'day))))
18046 ans))
18048 (defun org-toggle-timestamp-type ()
18049 "Toggle the type (<active> or [inactive]) of a time stamp."
18050 (interactive)
18051 (when (org-at-timestamp-p t)
18052 (let ((beg (match-beginning 0)) (end (match-end 0))
18053 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18054 (save-excursion
18055 (goto-char beg)
18056 (while (re-search-forward "[][<>]" end t)
18057 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18058 t t)))
18059 (message "Timestamp is now %sactive"
18060 (if (equal (char-after beg) ?<) "" "in")))))
18062 (defun org-at-clock-log-p nil
18063 "Is the cursor on the clock log line?"
18064 (save-excursion
18065 (beginning-of-line)
18066 (looking-at org-clock-line-re)))
18068 (defvar org-clock-history) ; defined in org-clock.el
18069 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18070 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18071 "Change the date in the time stamp at point.
18072 The date will be changed by N times WHAT. WHAT can be `day', `month',
18073 `year', `minute', `second'. If WHAT is not given, the cursor position
18074 in the timestamp determines what will be changed.
18075 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18076 (let ((origin (point)) origin-cat
18077 with-hm inactive
18078 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18079 org-ts-what
18080 extra rem
18081 ts time time0 fixnext clrgx)
18082 (unless (org-at-timestamp-p t)
18083 (user-error "Not at a timestamp"))
18084 (if (and (not what) (eq org-ts-what 'bracket))
18085 (org-toggle-timestamp-type)
18086 ;; Point isn't on brackets. Remember the part of the time-stamp
18087 ;; the point was in. Indeed, size of time-stamps may change,
18088 ;; but point must be kept in the same category nonetheless.
18089 (setq origin-cat org-ts-what)
18090 (when (and (not what) (not (eq org-ts-what 'day))
18091 org-display-custom-times
18092 (get-text-property (point) 'display)
18093 (not (get-text-property (1- (point)) 'display)))
18094 (setq org-ts-what 'day))
18095 (setq org-ts-what (or what org-ts-what)
18096 inactive (= (char-after (match-beginning 0)) ?\[)
18097 ts (match-string 0))
18098 (replace-match "")
18099 (when (string-match
18100 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18102 (setq extra (match-string 1 ts))
18103 (when suppress-tmp-delay
18104 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18105 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18106 (setq with-hm t))
18107 (setq time0 (org-parse-time-string ts))
18108 (when (and updown
18109 (eq org-ts-what 'minute)
18110 (not current-prefix-arg))
18111 ;; This looks like s-up and s-down. Change by one rounding step.
18112 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18113 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18114 (setcar (cdr time0) (+ (nth 1 time0)
18115 (if (> n 0) (- rem) (- dm rem))))))
18116 (setq time
18117 (apply #'encode-time
18118 (or (car time0) 0)
18119 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18120 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18121 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18122 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18123 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18124 (nthcdr 6 time0)))
18125 (when (and (member org-ts-what '(hour minute))
18126 extra
18127 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18128 (setq extra (org-modify-ts-extra
18129 extra
18130 (if (eq org-ts-what 'hour) 2 5)
18131 n dm)))
18132 (when (integerp org-ts-what)
18133 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18134 (when (eq what 'calendar)
18135 (let ((cal-date (org-get-date-from-calendar)))
18136 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18137 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18138 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18139 (setcar time0 (or (car time0) 0))
18140 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18141 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18142 (setq time (apply 'encode-time time0))))
18143 ;; Insert the new time-stamp, and ensure point stays in the same
18144 ;; category as before (i.e. not after the last position in that
18145 ;; category).
18146 (let ((pos (point)))
18147 ;; Stay before inserted string. `save-excursion' is of no use.
18148 (setq org-last-changed-timestamp
18149 (org-insert-time-stamp time with-hm inactive nil nil extra))
18150 (goto-char pos))
18151 (save-match-data
18152 (looking-at org-ts-regexp3)
18153 (goto-char
18154 (pcase origin-cat
18155 ;; `day' category ends before `hour' if any, or at the end
18156 ;; of the day name.
18157 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18158 (`hour (min (match-end 7) origin))
18159 (`minute (min (1- (match-end 8)) origin))
18160 ((pred integerp) (min (1- (match-end 0)) origin))
18161 ;; Point was right after the time-stamp. However, the
18162 ;; time-stamp length might have changed, so refer to
18163 ;; (match-end 0) instead.
18164 (`after (match-end 0))
18165 ;; `year' and `month' have both fixed size: point couldn't
18166 ;; have moved into another part.
18167 (_ origin))))
18168 ;; Update clock if on a CLOCK line.
18169 (org-clock-update-time-maybe)
18170 ;; Maybe adjust the closest clock in `org-clock-history'
18171 (when org-clock-adjust-closest
18172 (if (not (and (org-at-clock-log-p)
18173 (< 1 (length (delq nil (mapcar 'marker-position
18174 org-clock-history))))))
18175 (message "No clock to adjust")
18176 (cond ((save-excursion ; fix previous clock?
18177 (re-search-backward org-ts-regexp0 nil t)
18178 (looking-back (concat org-clock-string " \\[")
18179 (line-beginning-position)))
18180 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18181 ((save-excursion ; fix next clock?
18182 (re-search-backward org-ts-regexp0 nil t)
18183 (looking-at (concat org-ts-regexp0 "\\] =>")))
18184 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18185 (save-window-excursion
18186 ;; Find closest clock to point, adjust the previous/next one in history
18187 (let* ((p (save-excursion (org-back-to-heading t)))
18188 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18189 (clfixnth
18190 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18191 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18192 (if (not clfixpos)
18193 (message "No clock to adjust")
18194 (save-excursion
18195 (org-goto-marker-or-bmk clfixpos)
18196 (org-show-subtree)
18197 (when (re-search-forward clrgx nil t)
18198 (goto-char (match-beginning 1))
18199 (let (org-clock-adjust-closest)
18200 (org-timestamp-change n org-ts-what updown))
18201 (message "Clock adjusted in %s for heading: %s"
18202 (file-name-nondirectory (buffer-file-name))
18203 (org-get-heading t t)))))))))
18204 ;; Try to recenter the calendar window, if any.
18205 (when (and org-calendar-follow-timestamp-change
18206 (get-buffer-window "*Calendar*" t)
18207 (memq org-ts-what '(day month year)))
18208 (org-recenter-calendar (time-to-days time))))))
18210 (defun org-modify-ts-extra (s pos n dm)
18211 "Change the different parts of the lead-time and repeat fields in timestamp."
18212 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18213 ng h m new rem)
18214 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18215 (cond
18216 ((or (org-pos-in-match-range pos 2)
18217 (org-pos-in-match-range pos 3))
18218 (setq m (string-to-number (match-string 3 s))
18219 h (string-to-number (match-string 2 s)))
18220 (if (org-pos-in-match-range pos 2)
18221 (setq h (+ h n))
18222 (setq n (* dm (with-no-warnings (signum n))))
18223 (unless (= 0 (setq rem (% m dm)))
18224 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18225 (setq m (+ m n)))
18226 (when (< m 0) (setq m (+ m 60) h (1- h)))
18227 (when (> m 59) (setq m (- m 60) h (1+ h)))
18228 (setq h (mod h 24))
18229 (setq ng 1 new (format "-%02d:%02d" h m)))
18230 ((org-pos-in-match-range pos 6)
18231 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18232 ((org-pos-in-match-range pos 5)
18233 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18235 ((org-pos-in-match-range pos 9)
18236 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18237 ((org-pos-in-match-range pos 8)
18238 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18240 (when ng
18241 (setq s (concat
18242 (substring s 0 (match-beginning ng))
18244 (substring s (match-end ng))))))
18247 (defun org-recenter-calendar (d)
18248 "If the calendar is visible, recenter it to date D."
18249 (let ((cwin (get-buffer-window "*Calendar*" t)))
18250 (when cwin
18251 (let ((calendar-move-hook nil))
18252 (with-selected-window cwin
18253 (calendar-goto-date
18254 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18256 (defun org-goto-calendar (&optional arg)
18257 "Go to the Emacs calendar at the current date.
18258 If there is a time stamp in the current line, go to that date.
18259 A prefix ARG can be used to force the current date."
18260 (interactive "P")
18261 (let ((tsr org-ts-regexp) diff
18262 (calendar-move-hook nil)
18263 (calendar-view-holidays-initially-flag nil)
18264 (calendar-view-diary-initially-flag nil))
18265 (when (or (org-at-timestamp-p)
18266 (save-excursion
18267 (beginning-of-line 1)
18268 (looking-at (concat ".*" tsr))))
18269 (let ((d1 (time-to-days (current-time)))
18270 (d2 (time-to-days
18271 (org-time-string-to-time (match-string 1)))))
18272 (setq diff (- d2 d1))))
18273 (calendar)
18274 (calendar-goto-today)
18275 (when (and diff (not arg)) (calendar-forward-day diff))))
18277 (defun org-get-date-from-calendar ()
18278 "Return a list (month day year) of date at point in calendar."
18279 (with-current-buffer "*Calendar*"
18280 (save-match-data
18281 (calendar-cursor-to-date))))
18283 (defun org-date-from-calendar ()
18284 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18285 If there is already a time stamp at the cursor position, update it."
18286 (interactive)
18287 (if (org-at-timestamp-p t)
18288 (org-timestamp-change 0 'calendar)
18289 (let ((cal-date (org-get-date-from-calendar)))
18290 (org-insert-time-stamp
18291 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18293 (defcustom org-effort-durations
18294 `(("min" . 1)
18295 ("h" . 60)
18296 ("d" . ,(* 60 8))
18297 ("w" . ,(* 60 8 5))
18298 ("m" . ,(* 60 8 5 4))
18299 ("y" . ,(* 60 8 5 40)))
18300 "Conversion factor to minutes for an effort modifier.
18302 Each entry has the form (MODIFIER . MINUTES).
18304 In an effort string, a number followed by MODIFIER is multiplied
18305 by the specified number of MINUTES to obtain an effort in
18306 minutes.
18308 For example, if the value of this variable is ((\"hours\" . 60)), then an
18309 effort string \"2hours\" is equivalent to 120 minutes."
18310 :group 'org-agenda
18311 :version "26.1"
18312 :package-version '(Org . "8.3")
18313 :type '(alist :key-type (string :tag "Modifier")
18314 :value-type (number :tag "Minutes")))
18316 (defun org-minutes-to-clocksum-string (m)
18317 "Format number of minutes as a clocksum string.
18318 The format is determined by `org-time-clocksum-format',
18319 `org-time-clocksum-use-fractional' and
18320 `org-time-clocksum-fractional-format' and
18321 `org-time-clocksum-use-effort-durations'."
18322 (let ((clocksum "")
18323 (m (round m)) ; Don't allow fractions of minutes
18324 h d w mo y fmt n)
18325 (setq h (if org-time-clocksum-use-effort-durations
18326 (cdr (assoc "h" org-effort-durations)) 60)
18327 d (if org-time-clocksum-use-effort-durations
18328 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18329 w (if org-time-clocksum-use-effort-durations
18330 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18331 mo (if org-time-clocksum-use-effort-durations
18332 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18333 y (if org-time-clocksum-use-effort-durations
18334 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18335 ;; fractional format
18336 (if org-time-clocksum-use-fractional
18337 (cond
18338 ;; single format string
18339 ((stringp org-time-clocksum-fractional-format)
18340 (format org-time-clocksum-fractional-format (/ m (float h))))
18341 ;; choice of fractional formats for different time units
18342 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18343 (> (/ (truncate m) (* y d h)) 0))
18344 (format fmt (/ m (* y d (float h)))))
18345 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18346 (> (/ (truncate m) (* mo d h)) 0))
18347 (format fmt (/ m (* mo d (float h)))))
18348 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18349 (> (/ (truncate m) (* w d h)) 0))
18350 (format fmt (/ m (* w d (float h)))))
18351 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18352 (> (/ (truncate m) (* d h)) 0))
18353 (format fmt (/ m (* d (float h)))))
18354 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18355 (> (/ (truncate m) h) 0))
18356 (format fmt (/ m (float h))))
18357 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18358 (format fmt m))
18359 ;; fall back to smallest time unit with a format
18360 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18361 (format fmt (/ m (float h))))
18362 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18363 (format fmt (/ m (* d (float h)))))
18364 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18365 (format fmt (/ m (* w d (float h)))))
18366 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18367 (format fmt (/ m (* mo d (float h)))))
18368 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18369 (format fmt (/ m (* y d (float h))))))
18370 ;; standard (non-fractional) format, with single format string
18371 (if (stringp org-time-clocksum-format)
18372 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18373 ;; separate formats components
18374 (and (setq fmt (plist-get org-time-clocksum-format :years))
18375 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18376 (plist-get org-time-clocksum-format :require-years))
18377 (setq clocksum (concat clocksum (format fmt n))
18378 m (- m (* n y d h))))
18379 (and (setq fmt (plist-get org-time-clocksum-format :months))
18380 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18381 (plist-get org-time-clocksum-format :require-months))
18382 (setq clocksum (concat clocksum (format fmt n))
18383 m (- m (* n mo d h))))
18384 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18385 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18386 (plist-get org-time-clocksum-format :require-weeks))
18387 (setq clocksum (concat clocksum (format fmt n))
18388 m (- m (* n w d h))))
18389 (and (setq fmt (plist-get org-time-clocksum-format :days))
18390 (or (> (setq n (/ (truncate m) (* d h))) 0)
18391 (plist-get org-time-clocksum-format :require-days))
18392 (setq clocksum (concat clocksum (format fmt n))
18393 m (- m (* n d h))))
18394 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18395 (or (> (setq n (/ (truncate m) h)) 0)
18396 (plist-get org-time-clocksum-format :require-hours))
18397 (setq clocksum (concat clocksum (format fmt n))
18398 m (- m (* n h))))
18399 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18400 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18401 (setq clocksum (concat clocksum (format fmt m))))
18402 ;; return formatted time duration
18403 clocksum))))
18405 (defun org-hours-to-clocksum-string (n)
18406 (org-minutes-to-clocksum-string (* n 60)))
18408 (defun org-hh:mm-string-to-minutes (s)
18409 "Convert a string H:MM to a number of minutes.
18410 If the string is just a number, interpret it as minutes.
18411 In fact, the first hh:mm or number in the string will be taken,
18412 there can be extra stuff in the string.
18413 If no number is found, the return value is 0."
18414 (cond
18415 ((integerp s) s)
18416 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18417 (+ (* (string-to-number (match-string 1 s)) 60)
18418 (string-to-number (match-string 2 s))))
18419 ((string-match "\\([0-9]+\\)" s)
18420 (string-to-number (match-string 1 s)))
18421 (t 0)))
18423 (defcustom org-image-actual-width t
18424 "Should we use the actual width of images when inlining them?
18426 When set to t, always use the image width.
18428 When set to a number, use imagemagick (when available) to set
18429 the image's width to this value.
18431 When set to a number in a list, try to get the width from any
18432 #+ATTR.* keyword if it matches a width specification like
18434 #+ATTR_HTML: :width 300px
18436 and fall back on that number if none is found.
18438 When set to nil, try to get the width from an #+ATTR.* keyword
18439 and fall back on the original width if none is found.
18441 This requires Emacs >= 24.1, build with imagemagick support."
18442 :group 'org-appearance
18443 :version "24.4"
18444 :package-version '(Org . "8.0")
18445 :type '(choice
18446 (const :tag "Use the image width" t)
18447 (integer :tag "Use a number of pixels")
18448 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18449 (const :tag "Use #+ATTR* or don't resize" nil)))
18451 (defcustom org-agenda-inhibit-startup nil
18452 "Inhibit startup when preparing agenda buffers.
18453 When this variable is t, the initialization of the Org agenda
18454 buffers is inhibited: e.g. the visibility state is not set, the
18455 tables are not re-aligned, etc."
18456 :type 'boolean
18457 :version "24.3"
18458 :group 'org-agenda)
18460 (defcustom org-agenda-ignore-properties nil
18461 "Avoid updating text properties when building the agenda.
18462 Properties are used to prepare buffers for effort estimates,
18463 appointments, statistics and subtree-local categories.
18464 If you don't use these in the agenda, you can add them to this
18465 list and agenda building will be a bit faster.
18466 The value is a list, with zero or more of the symbols `effort', `appt',
18467 `stats' or `category'."
18468 :type '(set :greedy t
18469 (const effort)
18470 (const appt)
18471 (const stats)
18472 (const category))
18473 :version "26.1"
18474 :package-version '(Org . "8.3")
18475 :group 'org-agenda)
18477 (defun org-duration-string-to-minutes (s &optional output-to-string)
18478 "Convert a duration string S to minutes.
18480 A bare number is interpreted as minutes, modifiers can be set by
18481 customizing `org-effort-durations' (which see).
18483 Entries containing a colon are interpreted as H:MM by
18484 `org-hh:mm-string-to-minutes'."
18485 (let ((result 0)
18486 (re (concat "\\([0-9.]+\\) *\\("
18487 (regexp-opt (mapcar 'car org-effort-durations))
18488 "\\)")))
18489 (while (string-match re s)
18490 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18491 (string-to-number (match-string 1 s))))
18492 (setq s (replace-match "" nil t s)))
18493 (setq result (floor result))
18494 (cl-incf result (org-hh:mm-string-to-minutes s))
18495 (if output-to-string (number-to-string result) result)))
18497 ;;;; Files
18499 (defun org-save-all-org-buffers ()
18500 "Save all Org buffers without user confirmation."
18501 (interactive)
18502 (message "Saving all Org buffers...")
18503 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18504 (when (featurep 'org-id) (org-id-locations-save))
18505 (message "Saving all Org buffers... done"))
18507 (defun org-revert-all-org-buffers ()
18508 "Revert all Org buffers.
18509 Prompt for confirmation when there are unsaved changes.
18510 Be sure you know what you are doing before letting this function
18511 overwrite your changes.
18513 This function is useful in a setup where one tracks org files
18514 with a version control system, to revert on one machine after pulling
18515 changes from another. I believe the procedure must be like this:
18517 1. M-x org-save-all-org-buffers
18518 2. Pull changes from the other machine, resolve conflicts
18519 3. M-x org-revert-all-org-buffers"
18520 (interactive)
18521 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18522 (user-error "Abort"))
18523 (save-excursion
18524 (save-window-excursion
18525 (dolist (b (buffer-list))
18526 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18527 (with-current-buffer b buffer-file-name))
18528 (pop-to-buffer-same-window b)
18529 (revert-buffer t 'no-confirm)))
18530 (when (and (featurep 'org-id) org-id-track-globally)
18531 (org-id-locations-load)))))
18533 ;;;; Agenda files
18535 ;;;###autoload
18536 (defun org-switchb (&optional arg)
18537 "Switch between Org buffers.
18539 With `\\[universal-argument]' prefix, restrict available buffers to files.
18541 With `\\[universal-argument] \\[universal-argument]' \
18542 prefix, restrict available buffers to agenda files."
18543 (interactive "P")
18544 (let ((blist (org-buffer-list
18545 (cond ((equal arg '(4)) 'files)
18546 ((equal arg '(16)) 'agenda)))))
18547 (pop-to-buffer-same-window
18548 (completing-read "Org buffer: "
18549 (mapcar #'list (mapcar #'buffer-name blist))
18550 nil t))))
18552 (defun org-buffer-list (&optional predicate exclude-tmp)
18553 "Return a list of Org buffers.
18554 PREDICATE can be `export', `files' or `agenda'.
18556 export restrict the list to Export buffers.
18557 files restrict the list to buffers visiting Org files.
18558 agenda restrict the list to buffers visiting agenda files.
18560 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18561 (let* ((bfn nil)
18562 (agenda-files (and (eq predicate 'agenda)
18563 (mapcar 'file-truename (org-agenda-files t))))
18564 (filter
18565 (cond
18566 ((eq predicate 'files)
18567 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18568 ((eq predicate 'export)
18569 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18570 ((eq predicate 'agenda)
18571 (lambda (b)
18572 (with-current-buffer b
18573 (and (derived-mode-p 'org-mode)
18574 (setq bfn (buffer-file-name b))
18575 (member (file-truename bfn) agenda-files)))))
18576 (t (lambda (b) (with-current-buffer b
18577 (or (derived-mode-p 'org-mode)
18578 (string-match "\\*Org .*Export"
18579 (buffer-name b)))))))))
18580 (delq nil
18581 (mapcar
18582 (lambda(b)
18583 (if (and (funcall filter b)
18584 (or (not exclude-tmp)
18585 (not (string-match "tmp" (buffer-name b)))))
18587 nil))
18588 (buffer-list)))))
18590 (defun org-agenda-files (&optional unrestricted archives)
18591 "Get the list of agenda files.
18592 Optional UNRESTRICTED means return the full list even if a restriction
18593 is currently in place.
18594 When ARCHIVES is t, include all archive files that are really being
18595 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18596 `org-agenda-archives-mode' is t."
18597 (let ((files
18598 (cond
18599 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18600 ((stringp org-agenda-files) (org-read-agenda-file-list))
18601 ((listp org-agenda-files) org-agenda-files)
18602 (t (error "Invalid value of `org-agenda-files'")))))
18603 (setq files (apply 'append
18604 (mapcar (lambda (f)
18605 (if (file-directory-p f)
18606 (directory-files
18607 f t org-agenda-file-regexp)
18608 (list f)))
18609 files)))
18610 (when org-agenda-skip-unavailable-files
18611 (setq files (delq nil
18612 (mapcar (function
18613 (lambda (file)
18614 (and (file-readable-p file) file)))
18615 files))))
18616 (when (or (eq archives t)
18617 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18618 (setq files (org-add-archive-files files)))
18619 files))
18621 (defun org-agenda-file-p (&optional file)
18622 "Return non-nil, if FILE is an agenda file.
18623 If FILE is omitted, use the file associated with the current
18624 buffer."
18625 (let ((fname (or file (buffer-file-name))))
18626 (and fname
18627 (member (file-truename fname)
18628 (mapcar #'file-truename (org-agenda-files t))))))
18630 (defun org-edit-agenda-file-list ()
18631 "Edit the list of agenda files.
18632 Depending on setup, this either uses customize to edit the variable
18633 `org-agenda-files', or it visits the file that is holding the list. In the
18634 latter case, the buffer is set up in a way that saving it automatically kills
18635 the buffer and restores the previous window configuration."
18636 (interactive)
18637 (if (stringp org-agenda-files)
18638 (let ((cw (current-window-configuration)))
18639 (find-file org-agenda-files)
18640 (setq-local org-window-configuration cw)
18641 (add-hook 'after-save-hook
18642 (lambda ()
18643 (set-window-configuration
18644 (prog1 org-window-configuration
18645 (kill-buffer (current-buffer))))
18646 (org-install-agenda-files-menu)
18647 (message "New agenda file list installed"))
18648 nil 'local)
18649 (message "%s" (substitute-command-keys
18650 "Edit list and finish with \\[save-buffer]")))
18651 (customize-variable 'org-agenda-files)))
18653 (defun org-store-new-agenda-file-list (list)
18654 "Set new value for the agenda file list and save it correctly."
18655 (if (stringp org-agenda-files)
18656 (let ((fe (org-read-agenda-file-list t)) b u)
18657 (while (setq b (find-buffer-visiting org-agenda-files))
18658 (kill-buffer b))
18659 (with-temp-file org-agenda-files
18660 (insert
18661 (mapconcat
18662 (lambda (f) ;; Keep un-expanded entries.
18663 (if (setq u (assoc f fe))
18664 (cdr u)
18666 list "\n")
18667 "\n")))
18668 (let ((org-mode-hook nil) (org-inhibit-startup t)
18669 (org-insert-mode-line-in-empty-file nil))
18670 (setq org-agenda-files list)
18671 (customize-save-variable 'org-agenda-files org-agenda-files))))
18673 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18674 "Read the list of agenda files from a file.
18675 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18676 filenames, used by `org-store-new-agenda-file-list' to write back
18677 un-expanded file names."
18678 (when (file-directory-p org-agenda-files)
18679 (error "`org-agenda-files' cannot be a single directory"))
18680 (when (stringp org-agenda-files)
18681 (with-temp-buffer
18682 (insert-file-contents org-agenda-files)
18683 (mapcar
18684 (lambda (f)
18685 (let ((e (expand-file-name (substitute-in-file-name f)
18686 org-directory)))
18687 (if pair-with-expansion
18688 (cons e f)
18689 e)))
18690 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18692 ;;;###autoload
18693 (defun org-cycle-agenda-files ()
18694 "Cycle through the files in `org-agenda-files'.
18695 If the current buffer visits an agenda file, find the next one in the list.
18696 If the current buffer does not, find the first agenda file."
18697 (interactive)
18698 (let* ((fs (or (org-agenda-files t)
18699 (user-error "No agenda files")))
18700 (files (copy-sequence fs))
18701 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18702 file)
18703 (when tcf
18704 (while (and (setq file (pop files))
18705 (not (equal (file-truename file) tcf)))))
18706 (find-file (car (or files fs)))
18707 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18709 (defun org-agenda-file-to-front (&optional to-end)
18710 "Move/add the current file to the top of the agenda file list.
18711 If the file is not present in the list, it is added to the front. If it is
18712 present, it is moved there. With optional argument TO-END, add/move to the
18713 end of the list."
18714 (interactive "P")
18715 (let ((org-agenda-skip-unavailable-files nil)
18716 (file-alist (mapcar (lambda (x)
18717 (cons (file-truename x) x))
18718 (org-agenda-files t)))
18719 (ctf (file-truename
18720 (or buffer-file-name
18721 (user-error "Please save the current buffer to a file"))))
18722 x had)
18723 (setq x (assoc ctf file-alist) had x)
18725 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18726 (if to-end
18727 (setq file-alist (append (delq x file-alist) (list x)))
18728 (setq file-alist (cons x (delq x file-alist))))
18729 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18730 (org-install-agenda-files-menu)
18731 (message "File %s to %s of agenda file list"
18732 (if had "moved" "added") (if to-end "end" "front"))))
18734 (defun org-remove-file (&optional file)
18735 "Remove current file from the list of files in variable `org-agenda-files'.
18736 These are the files which are being checked for agenda entries.
18737 Optional argument FILE means use this file instead of the current."
18738 (interactive)
18739 (let* ((org-agenda-skip-unavailable-files nil)
18740 (file (or file buffer-file-name
18741 (user-error "Current buffer does not visit a file")))
18742 (true-file (file-truename file))
18743 (afile (abbreviate-file-name file))
18744 (files (delq nil (mapcar
18745 (lambda (x)
18746 (unless (equal true-file
18747 (file-truename x))
18749 (org-agenda-files t)))))
18750 (if (not (= (length files) (length (org-agenda-files t))))
18751 (progn
18752 (org-store-new-agenda-file-list files)
18753 (org-install-agenda-files-menu)
18754 (message "Removed from Org Agenda list: %s" afile))
18755 (message "File was not in list: %s (not removed)" afile))))
18757 (defun org-file-menu-entry (file)
18758 (vector file (list 'find-file file) t))
18760 (defun org-check-agenda-file (file)
18761 "Make sure FILE exists. If not, ask user what to do."
18762 (unless (file-exists-p file)
18763 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18764 (abbreviate-file-name file))
18765 (let ((r (downcase (read-char-exclusive))))
18766 (cond
18767 ((equal r ?r)
18768 (org-remove-file file)
18769 (throw 'nextfile t))
18770 (t (user-error "Abort"))))))
18772 (defun org-get-agenda-file-buffer (file)
18773 "Get an agenda buffer visiting FILE.
18774 If the buffer needs to be created, add it to the list of buffers
18775 which might be released later."
18776 (let ((buf (org-find-base-buffer-visiting file)))
18777 (if buf
18778 buf ; just return it
18779 ;; Make a new buffer and remember it
18780 (setq buf (find-file-noselect file))
18781 (when buf (push buf org-agenda-new-buffers))
18782 buf)))
18784 (defun org-release-buffers (blist)
18785 "Release all buffers in list, asking the user for confirmation when needed.
18786 When a buffer is unmodified, it is just killed. When modified, it is saved
18787 \(if the user agrees) and then killed."
18788 (let (file)
18789 (dolist (buf blist)
18790 (setq file (buffer-file-name buf))
18791 (when (and (buffer-modified-p buf)
18792 file
18793 (y-or-n-p (format "Save file %s? " file)))
18794 (with-current-buffer buf (save-buffer)))
18795 (kill-buffer buf))))
18797 (defun org-agenda-prepare-buffers (files)
18798 "Create buffers for all agenda files, protect archived trees and comments."
18799 (interactive)
18800 (let ((pa '(:org-archived t))
18801 (pc '(:org-comment t))
18802 (pall '(:org-archived t :org-comment t))
18803 (inhibit-read-only t)
18804 (org-inhibit-startup org-agenda-inhibit-startup)
18805 (rea (concat ":" org-archive-tag ":"))
18806 re pos)
18807 (setq org-tag-alist-for-agenda nil
18808 org-tag-groups-alist-for-agenda nil)
18809 (save-excursion
18810 (save-restriction
18811 (dolist (file files)
18812 (catch 'nextfile
18813 (if (bufferp file)
18814 (set-buffer file)
18815 (org-check-agenda-file file)
18816 (set-buffer (org-get-agenda-file-buffer file)))
18817 (widen)
18818 (org-set-regexps-and-options 'tags-only)
18819 (setq pos (point))
18820 (or (memq 'category org-agenda-ignore-properties)
18821 (org-refresh-category-properties))
18822 (or (memq 'stats org-agenda-ignore-properties)
18823 (org-refresh-stats-properties))
18824 (or (memq 'effort org-agenda-ignore-properties)
18825 (org-refresh-effort-properties))
18826 (or (memq 'appt org-agenda-ignore-properties)
18827 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18828 (setq org-todo-keywords-for-agenda
18829 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18830 (setq org-done-keywords-for-agenda
18831 (append org-done-keywords-for-agenda org-done-keywords))
18832 (setq org-todo-keyword-alist-for-agenda
18833 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18834 (setq org-tag-alist-for-agenda
18835 (org-uniquify
18836 (append org-tag-alist-for-agenda
18837 org-current-tag-alist)))
18838 ;; Merge current file's tag groups into global
18839 ;; `org-tag-groups-alist-for-agenda'.
18840 (when org-group-tags
18841 (dolist (alist org-tag-groups-alist)
18842 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18843 (if old
18844 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18845 (push alist org-tag-groups-alist-for-agenda)))))
18846 (org-with-silent-modifications
18847 (save-excursion
18848 (remove-text-properties (point-min) (point-max) pall)
18849 (when org-agenda-skip-archived-trees
18850 (goto-char (point-min))
18851 (while (re-search-forward rea nil t)
18852 (when (org-at-heading-p t)
18853 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18854 (goto-char (point-min))
18855 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18856 (while (re-search-forward re nil t)
18857 (when (save-match-data (org-in-commented-heading-p t))
18858 (add-text-properties
18859 (match-beginning 0) (org-end-of-subtree t) pc)))))
18860 (goto-char pos)))))
18861 (setq org-todo-keywords-for-agenda
18862 (org-uniquify org-todo-keywords-for-agenda))
18863 (setq org-todo-keyword-alist-for-agenda
18864 (org-uniquify org-todo-keyword-alist-for-agenda))))
18867 ;;;; CDLaTeX minor mode
18869 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18870 "Keymap for the minor `org-cdlatex-mode'.")
18872 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18873 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18874 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18875 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18876 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18878 (defvar org-cdlatex-texmathp-advice-is-done nil
18879 "Flag remembering if we have applied the advice to texmathp already.")
18881 (define-minor-mode org-cdlatex-mode
18882 "Toggle the minor `org-cdlatex-mode'.
18883 This mode supports entering LaTeX environment and math in LaTeX fragments
18884 in Org mode.
18885 \\{org-cdlatex-mode-map}"
18886 nil " OCDL" nil
18887 (when org-cdlatex-mode
18888 (require 'cdlatex)
18889 (run-hooks 'cdlatex-mode-hook)
18890 (cdlatex-compute-tables))
18891 (unless org-cdlatex-texmathp-advice-is-done
18892 (setq org-cdlatex-texmathp-advice-is-done t)
18893 (defadvice texmathp (around org-math-always-on activate)
18894 "Always return t in Org buffers.
18895 This is because we want to insert math symbols without dollars even outside
18896 the LaTeX math segments. If Org mode thinks that point is actually inside
18897 an embedded LaTeX fragment, let `texmathp' do its job.
18898 `\\[org-cdlatex-mode-map]'"
18899 (interactive)
18900 (let (p)
18901 (cond
18902 ((not (derived-mode-p 'org-mode)) ad-do-it)
18903 ((eq this-command 'cdlatex-math-symbol)
18904 (setq ad-return-value t
18905 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18907 (let ((p (org-inside-LaTeX-fragment-p)))
18908 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18909 (setq ad-return-value t
18910 texmathp-why '("Org mode embedded math" . 0))
18911 (when p ad-do-it)))))))))
18913 (defun turn-on-org-cdlatex ()
18914 "Unconditionally turn on `org-cdlatex-mode'."
18915 (org-cdlatex-mode 1))
18917 (defun org-try-cdlatex-tab ()
18918 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18919 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18920 - inside a LaTeX fragment, or
18921 - after the first word in a line, where an abbreviation expansion could
18922 insert a LaTeX environment."
18923 (when org-cdlatex-mode
18924 (cond
18925 ;; Before any word on the line: No expansion possible.
18926 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18927 ;; Just after first word on the line: Expand it. Make sure it
18928 ;; cannot happen on headlines, though.
18929 ((save-excursion
18930 (skip-chars-backward "a-zA-Z0-9*")
18931 (skip-chars-backward " \t")
18932 (and (bolp) (not (org-at-heading-p))))
18933 (cdlatex-tab) t)
18934 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18936 (defun org-cdlatex-underscore-caret (&optional _arg)
18937 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18938 Revert to the normal definition outside of these fragments."
18939 (interactive "P")
18940 (if (org-inside-LaTeX-fragment-p)
18941 (call-interactively 'cdlatex-sub-superscript)
18942 (let (org-cdlatex-mode)
18943 (call-interactively (key-binding (vector last-input-event))))))
18945 (defun org-cdlatex-math-modify (&optional _arg)
18946 "Execute `cdlatex-math-modify' in LaTeX fragments.
18947 Revert to the normal definition outside of these fragments."
18948 (interactive "P")
18949 (if (org-inside-LaTeX-fragment-p)
18950 (call-interactively 'cdlatex-math-modify)
18951 (let (org-cdlatex-mode)
18952 (call-interactively (key-binding (vector last-input-event))))))
18954 (defun org-cdlatex-environment-indent (&optional environment item)
18955 "Execute `cdlatex-environment' and indent the inserted environment.
18957 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18959 The inserted environment is indented to current indentation
18960 unless point is at the beginning of the line, in which the
18961 environment remains unintended."
18962 (interactive)
18963 ;; cdlatex-environment always return nil. Therefore, capture output
18964 ;; first and determine if an environment was selected.
18965 (let* ((beg (point-marker))
18966 (end (copy-marker (point) t))
18967 (inserted (progn
18968 (ignore-errors (cdlatex-environment environment item))
18969 (< beg end)))
18970 ;; Figure out how many lines to move forward after the
18971 ;; environment has been inserted.
18972 (lines (when inserted
18973 (save-excursion
18974 (- (cl-loop while (< beg (point))
18975 with x = 0
18976 do (forward-line -1)
18977 (cl-incf x)
18978 finally return x)
18979 (if (progn (goto-char beg)
18980 (and (progn (skip-chars-forward " \t") (eolp))
18981 (progn (skip-chars-backward " \t") (bolp))))
18982 1 0)))))
18983 (env (org-trim (delete-and-extract-region beg end))))
18984 (when inserted
18985 ;; Get indentation of next line unless at column 0.
18986 (let ((ind (if (bolp) 0
18987 (save-excursion
18988 (org-return-indent)
18989 (prog1 (org-get-indentation)
18990 (when (progn (skip-chars-forward " \t") (eolp))
18991 (delete-region beg (point)))))))
18992 (bol (progn (skip-chars-backward " \t") (bolp))))
18993 ;; Insert a newline before environment unless at column zero
18994 ;; to "escape" the current line. Insert a newline if
18995 ;; something is one the same line as \end{ENVIRONMENT}.
18996 (insert
18997 (concat (unless bol "\n") env
18998 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18999 (unless (zerop ind)
19000 (save-excursion
19001 (goto-char beg)
19002 (while (< (point) end)
19003 (unless (eolp) (indent-line-to ind))
19004 (forward-line))))
19005 (goto-char beg)
19006 (forward-line lines)
19007 (indent-line-to ind)))
19008 (set-marker beg nil)
19009 (set-marker end nil)))
19012 ;;;; LaTeX fragments
19014 (defun org-inside-LaTeX-fragment-p ()
19015 "Test if point is inside a LaTeX fragment.
19016 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19017 sequence appearing also before point.
19018 Even though the matchers for math are configurable, this function assumes
19019 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19020 delimiters are skipped when they have been removed by customization.
19021 The return value is nil, or a cons cell with the delimiter and the
19022 position of this delimiter.
19024 This function does a reasonably good job, but can locally be fooled by
19025 for example currency specifications. For example it will assume being in
19026 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19027 fragments that are properly closed, but during editing, we have to live
19028 with the uncertainty caused by missing closing delimiters. This function
19029 looks only before point, not after."
19030 (catch 'exit
19031 (let ((pos (point))
19032 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19033 (lim (progn
19034 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19035 (point)))
19036 dd-on str (start 0) m re)
19037 (goto-char pos)
19038 (when dodollar
19039 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19040 re (nth 1 (assoc "$" org-latex-regexps)))
19041 (while (string-match re str start)
19042 (cond
19043 ((= (match-end 0) (length str))
19044 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19045 ((= (match-end 0) (- (length str) 5))
19046 (throw 'exit nil))
19047 (t (setq start (match-end 0))))))
19048 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19049 (goto-char pos)
19050 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19051 (and (match-beginning 2) (throw 'exit nil))
19052 ;; count $$
19053 (while (re-search-backward "\\$\\$" lim t)
19054 (setq dd-on (not dd-on)))
19055 (goto-char pos)
19056 (when dd-on (cons "$$" m))))))
19058 (defun org-inside-latex-macro-p ()
19059 "Is point inside a LaTeX macro or its arguments?"
19060 (save-match-data
19061 (org-in-regexp
19062 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19064 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19065 "Build an overlay between BEG and END using IMAGE file.
19066 Argument IMAGETYPE is the extension of the displayed image,
19067 as a string. It defaults to \"png\"."
19068 (let ((ov (make-overlay beg end))
19069 (imagetype (or (intern imagetype) 'png)))
19070 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19071 (overlay-put ov 'evaporate t)
19072 (overlay-put ov
19073 'modification-hooks
19074 (list (lambda (o _flag _beg _end &optional _l)
19075 (delete-overlay o))))
19076 (overlay-put ov
19077 'display
19078 (list 'image :type imagetype :file image :ascent 'center))))
19080 (defun org--list-latex-overlays (&optional beg end)
19081 "List all Org LaTeX overlays in current buffer.
19082 Limit to overlays between BEG and END when those are provided."
19083 (cl-remove-if-not
19084 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19085 (overlays-in (or beg (point-min)) (or end (point-max)))))
19087 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19088 "Remove all overlays with LaTeX fragment images in current buffer.
19089 When optional arguments BEG and END are non-nil, remove all
19090 overlays between them instead. Return a non-nil value when some
19091 overlays were removed, nil otherwise."
19092 (let ((overlays (org--list-latex-overlays beg end)))
19093 (mapc #'delete-overlay overlays)
19094 overlays))
19096 (defun org-toggle-latex-fragment (&optional arg)
19097 "Preview the LaTeX fragment at point, or all locally or globally.
19099 If the cursor is on a LaTeX fragment, create the image and overlay
19100 it over the source code, if there is none. Remove it otherwise.
19101 If there is no fragment at point, display all fragments in the
19102 current section.
19104 With prefix ARG, preview or clear image for all fragments in the
19105 current subtree or in the whole buffer when used before the first
19106 headline. With a prefix ARG `\\[universal-argument] \
19107 \\[universal-argument]' preview or clear images
19108 for all fragments in the buffer."
19109 (interactive "P")
19110 (when (display-graphic-p)
19111 (catch 'exit
19112 (save-excursion
19113 (let (beg end msg)
19114 (cond
19115 ((or (equal arg '(16))
19116 (and (equal arg '(4))
19117 (org-with-limited-levels (org-before-first-heading-p))))
19118 (if (org-remove-latex-fragment-image-overlays)
19119 (progn (message "LaTeX fragments images removed from buffer")
19120 (throw 'exit nil))
19121 (setq msg "Creating images for buffer...")))
19122 ((equal arg '(4))
19123 (org-with-limited-levels (org-back-to-heading t))
19124 (setq beg (point))
19125 (setq end (progn (org-end-of-subtree t) (point)))
19126 (if (org-remove-latex-fragment-image-overlays beg end)
19127 (progn
19128 (message "LaTeX fragment images removed from subtree")
19129 (throw 'exit nil))
19130 (setq msg "Creating images for subtree...")))
19131 ((let ((datum (org-element-context)))
19132 (when (memq (org-element-type datum)
19133 '(latex-environment latex-fragment))
19134 (setq beg (org-element-property :begin datum))
19135 (setq end (org-element-property :end datum))
19136 (if (org-remove-latex-fragment-image-overlays beg end)
19137 (progn (message "LaTeX fragment image removed")
19138 (throw 'exit nil))
19139 (setq msg "Creating image...")))))
19141 (org-with-limited-levels
19142 (setq beg (if (org-at-heading-p) (line-beginning-position)
19143 (outline-previous-heading)
19144 (point)))
19145 (setq end (progn (outline-next-heading) (point)))
19146 (if (org-remove-latex-fragment-image-overlays beg end)
19147 (progn
19148 (message "LaTeX fragment images removed from section")
19149 (throw 'exit nil))
19150 (setq msg "Creating images for section...")))))
19151 (let ((file (buffer-file-name (buffer-base-buffer))))
19152 (org-format-latex
19153 (concat org-preview-latex-image-directory "org-ltximg")
19154 beg end
19155 ;; Emacs cannot overlay images from remote hosts. Create
19156 ;; it in `temporary-file-directory' instead.
19157 (if (or (not file) (file-remote-p file))
19158 temporary-file-directory
19159 default-directory)
19160 'overlays msg 'forbuffer org-preview-latex-default-process))
19161 (message (concat msg "done")))))))
19163 (defun org-format-latex
19164 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19165 "Replace LaTeX fragments with links to an image.
19167 The function takes care of creating the replacement image.
19169 Only consider fragments between BEG and END when those are
19170 provided.
19172 When optional argument OVERLAYS is non-nil, display the image on
19173 top of the fragment instead of replacing it.
19175 PROCESSING-TYPE is the conversion method to use, as a symbol.
19177 Some of the options can be changed using the variable
19178 `org-format-latex-options', which see."
19179 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19180 (unless (eq processing-type 'verbatim)
19181 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19182 (cnt 0)
19183 checkdir-flag)
19184 (goto-char (or beg (point-min)))
19185 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19186 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19187 (overlay-recenter (or end (point-max))))
19188 (while (re-search-forward math-regexp end t)
19189 (unless (and overlays
19190 (eq (get-char-property (point) 'org-overlay-type)
19191 'org-latex-overlay))
19192 (let* ((context (org-element-context))
19193 (type (org-element-type context)))
19194 (when (memq type '(latex-environment latex-fragment))
19195 (let ((block-type (eq type 'latex-environment))
19196 (value (org-element-property :value context))
19197 (beg (org-element-property :begin context))
19198 (end (save-excursion
19199 (goto-char (org-element-property :end context))
19200 (skip-chars-backward " \r\t\n")
19201 (point))))
19202 (cond
19203 ((eq processing-type 'mathjax)
19204 ;; Prepare for MathJax processing.
19205 (if (not (string-match "\\`\\$\\$?" value))
19206 (goto-char end)
19207 (delete-region beg end)
19208 (if (string= (match-string 0 value) "$$")
19209 (insert "\\[" (substring value 2 -2) "\\]")
19210 (insert "\\(" (substring value 1 -1) "\\)"))))
19211 ((assq processing-type org-preview-latex-process-alist)
19212 ;; Process to an image.
19213 (cl-incf cnt)
19214 (goto-char beg)
19215 (let* ((processing-info
19216 (cdr (assq processing-type org-preview-latex-process-alist)))
19217 (face (face-at-point))
19218 ;; Get the colors from the face at point.
19220 (let ((color (plist-get org-format-latex-options
19221 :foreground)))
19222 (if (and forbuffer (eq color 'auto))
19223 (face-attribute face :foreground nil 'default)
19224 color)))
19226 (let ((color (plist-get org-format-latex-options
19227 :background)))
19228 (if (and forbuffer (eq color 'auto))
19229 (face-attribute face :background nil 'default)
19230 color)))
19231 (hash (sha1 (prin1-to-string
19232 (list org-format-latex-header
19233 org-latex-default-packages-alist
19234 org-latex-packages-alist
19235 org-format-latex-options
19236 forbuffer value fg bg))))
19237 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19238 (absprefix (expand-file-name prefix dir))
19239 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19240 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19241 (sep (and block-type "\n\n"))
19242 (link (concat sep "[[file:" linkfile "]]" sep))
19243 (options
19244 (org-combine-plists
19245 org-format-latex-options
19246 `(:foreground ,fg :background ,bg))))
19247 (when msg (message msg cnt))
19248 (unless checkdir-flag ; Ensure the directory exists.
19249 (setq checkdir-flag t)
19250 (let ((todir (file-name-directory absprefix)))
19251 (unless (file-directory-p todir)
19252 (make-directory todir t))))
19253 (unless (file-exists-p movefile)
19254 (org-create-formula-image
19255 value movefile options forbuffer processing-type))
19256 (if overlays
19257 (progn
19258 (dolist (o (overlays-in beg end))
19259 (when (eq (overlay-get o 'org-overlay-type)
19260 'org-latex-overlay)
19261 (delete-overlay o)))
19262 (org--format-latex-make-overlay beg end movefile imagetype)
19263 (goto-char end))
19264 (delete-region beg end)
19265 (insert
19266 (org-add-props link
19267 (list 'org-latex-src
19268 (replace-regexp-in-string "\"" "" value)
19269 'org-latex-src-embed-type
19270 (if block-type 'paragraph 'character)))))))
19271 ((eq processing-type 'mathml)
19272 ;; Process to MathML.
19273 (unless (org-format-latex-mathml-available-p)
19274 (user-error "LaTeX to MathML converter not configured"))
19275 (cl-incf cnt)
19276 (when msg (message msg cnt))
19277 (goto-char beg)
19278 (delete-region beg end)
19279 (insert (org-format-latex-as-mathml
19280 value block-type prefix dir)))
19282 (error "Unknown conversion process %s for LaTeX fragments"
19283 processing-type)))))))))))
19285 (defun org-create-math-formula (latex-frag &optional mathml-file)
19286 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19287 Use `org-latex-to-mathml-convert-command'. If the conversion is
19288 sucessful, return the portion between \"<math...> </math>\"
19289 elements otherwise return nil. When MATHML-FILE is specified,
19290 write the results in to that file. When invoked as an
19291 interactive command, prompt for LATEX-FRAG, with initial value
19292 set to the current active region and echo the results for user
19293 inspection."
19294 (interactive (list (let ((frag (when (org-region-active-p)
19295 (buffer-substring-no-properties
19296 (region-beginning) (region-end)))))
19297 (read-string "LaTeX Fragment: " frag nil frag))))
19298 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19299 (let* ((tmp-in-file
19300 (let ((file (file-relative-name
19301 (make-temp-name (expand-file-name "ltxmathml-in")))))
19302 (write-region latex-frag nil file)
19303 file))
19304 (tmp-out-file (file-relative-name
19305 (make-temp-name (expand-file-name "ltxmathml-out"))))
19306 (cmd (format-spec
19307 org-latex-to-mathml-convert-command
19308 `((?j . ,(and org-latex-to-mathml-jar-file
19309 (shell-quote-argument
19310 (expand-file-name
19311 org-latex-to-mathml-jar-file))))
19312 (?I . ,(shell-quote-argument tmp-in-file))
19313 (?i . ,latex-frag)
19314 (?o . ,(shell-quote-argument tmp-out-file)))))
19315 mathml shell-command-output)
19316 (when (called-interactively-p 'any)
19317 (unless (org-format-latex-mathml-available-p)
19318 (user-error "LaTeX to MathML converter not configured")))
19319 (message "Running %s" cmd)
19320 (setq shell-command-output (shell-command-to-string cmd))
19321 (setq mathml
19322 (when (file-readable-p tmp-out-file)
19323 (with-current-buffer (find-file-noselect tmp-out-file t)
19324 (goto-char (point-min))
19325 (when (re-search-forward
19326 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19327 (regexp-quote
19328 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19329 nil t)
19330 (prog1 (match-string 0) (kill-buffer))))))
19331 (cond
19332 (mathml
19333 (setq mathml
19334 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19335 (when mathml-file
19336 (write-region mathml nil mathml-file))
19337 (when (called-interactively-p 'any)
19338 (message mathml)))
19339 ((message "LaTeX to MathML conversion failed")
19340 (message shell-command-output)))
19341 (delete-file tmp-in-file)
19342 (when (file-exists-p tmp-out-file)
19343 (delete-file tmp-out-file))
19344 mathml))
19346 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19347 prefix &optional dir)
19348 "Use `org-create-math-formula' but check local cache first."
19349 (let* ((absprefix (expand-file-name prefix dir))
19350 (print-length nil) (print-level nil)
19351 (formula-id (concat
19352 "formula-"
19353 (sha1
19354 (prin1-to-string
19355 (list latex-frag
19356 org-latex-to-mathml-convert-command)))))
19357 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19358 (formula-cache-dir (file-name-directory formula-cache)))
19360 (unless (file-directory-p formula-cache-dir)
19361 (make-directory formula-cache-dir t))
19363 (unless (file-exists-p formula-cache)
19364 (org-create-math-formula latex-frag formula-cache))
19366 (if (file-exists-p formula-cache)
19367 ;; Successful conversion. Return the link to MathML file.
19368 (org-add-props
19369 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19370 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19371 'org-latex-src-embed-type (if latex-frag-type
19372 'paragraph 'character)))
19373 ;; Failed conversion. Return the LaTeX fragment verbatim
19374 latex-frag)))
19376 (defun org--get-display-dpi ()
19377 "Get the DPI of the display.
19378 The function assumes that the display has the same pixel width in
19379 the horizontal and vertical directions."
19380 (if (display-graphic-p)
19381 (round (/ (display-pixel-height)
19382 (/ (display-mm-height) 25.4)))
19383 (error "Attempt to calculate the dpi of a non-graphic display")))
19385 (defun org-create-formula-image
19386 (string tofile options buffer &optional processing-type)
19387 "Create an image from LaTeX source using external processes.
19389 The LaTeX STRING is saved to a temporary LaTeX file, then
19390 converted to an image file by process PROCESSING-TYPE defined in
19391 `org-preview-latex-process-alist'. A nil value defaults to
19392 `org-preview-latex-default-process'.
19394 The generated image file is eventually moved to TOFILE.
19396 The OPTIONS argument controls the size, foreground color and
19397 background color of the generated image.
19399 When BUFFER non-nil, this function is used for LaTeX previewing.
19400 Otherwise, it is used to deal with LaTeX snippets showed in
19401 a HTML file."
19402 (let* ((processing-type (or processing-type
19403 org-preview-latex-default-process))
19404 (processing-info
19405 (cdr (assq processing-type org-preview-latex-process-alist)))
19406 (programs (plist-get processing-info :programs))
19407 (error-message (or (plist-get processing-info :message) ""))
19408 (use-xcolor (plist-get processing-info :use-xcolor))
19409 (image-input-type (plist-get processing-info :image-input-type))
19410 (image-output-type (plist-get processing-info :image-output-type))
19411 (post-clean (or (plist-get processing-info :post-clean)
19412 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19413 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19414 (latex-header
19415 (or (plist-get processing-info :latex-header)
19416 (org-latex-make-preamble
19417 (org-export-get-environment (org-export-get-backend 'latex))
19418 org-format-latex-header
19419 'snippet)))
19420 (latex-compiler (plist-get processing-info :latex-compiler))
19421 (image-converter (plist-get processing-info :image-converter))
19422 (tmpdir temporary-file-directory)
19423 (texfilebase (make-temp-name
19424 (expand-file-name "orgtex" tmpdir)))
19425 (texfile (concat texfilebase ".tex"))
19426 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19427 '(1.0 . 1.0)))
19428 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19429 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19430 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19431 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19432 "Black"))
19433 (bg (or (plist-get options (if buffer :background :html-background))
19434 "Transparent"))
19435 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19436 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19437 (dolist (program programs)
19438 (org-check-external-command program error-message))
19439 (if use-xcolor
19440 (progn (if (eq fg 'default)
19441 (setq fg (org-latex-color :foreground))
19442 (setq fg (org-latex-color-format fg)))
19443 (if (eq bg 'default)
19444 (setq bg (org-latex-color :background))
19445 (setq bg (org-latex-color-format
19446 (if (string= bg "Transparent") "white" bg))))
19447 (with-temp-file texfile
19448 (insert latex-header)
19449 (insert "\n\\begin{document}\n"
19450 "\\definecolor{fg}{rgb}{" fg "}\n"
19451 "\\definecolor{bg}{rgb}{" bg "}\n"
19452 "\n\\pagecolor{bg}\n"
19453 "\n{\\color{fg}\n"
19454 string
19455 "\n}\n"
19456 "\n\\end{document}\n")))
19457 (if (eq fg 'default)
19458 (setq fg (org-dvipng-color :foreground))
19459 (unless (string= fg "Transparent")
19460 (setq fg (org-dvipng-color-format fg))))
19461 (if (eq bg 'default)
19462 (setq bg (org-dvipng-color :background))
19463 (unless (string= bg "Transparent")
19464 (setq bg (org-dvipng-color-format bg))))
19465 (with-temp-file texfile
19466 (insert latex-header)
19467 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19469 (let* ((err-msg (format "Please adjust '%s' part of \
19470 `org-preview-latex-process-alist'."
19471 processing-type))
19472 (image-input-file
19473 (org-compile-file
19474 texfile latex-compiler image-input-type err-msg log-buf))
19475 (image-output-file
19476 (org-compile-file
19477 image-input-file image-converter image-output-type err-msg log-buf
19478 `((?F . ,(shell-quote-argument fg))
19479 (?B . ,(shell-quote-argument bg))
19480 (?D . ,(shell-quote-argument (format "%s" dpi)))
19481 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19482 (copy-file image-output-file tofile 'replace)
19483 (dolist (e post-clean)
19484 (when (file-exists-p (concat texfilebase e))
19485 (delete-file (concat texfilebase e))))
19486 image-output-file)))
19488 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19489 "Fill a LaTeX header template TPL.
19490 In the template, the following place holders will be recognized:
19492 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19493 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19494 [PACKAGES] \\usepackage statements for PKG
19495 [NO-PACKAGES] do not include PKG
19496 [EXTRA] the string EXTRA
19497 [NO-EXTRA] do not include EXTRA
19499 For backward compatibility, if both the positive and the negative place
19500 holder is missing, the positive one (without the \"NO-\") will be
19501 assumed to be present at the end of the template.
19502 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19503 EXTRA is a string.
19504 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19505 (let (rpl (end ""))
19506 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19507 (setq rpl (if (or (match-end 1) (not def-pkg))
19508 "" (org-latex-packages-to-string def-pkg snippets-p t))
19509 tpl (replace-match rpl t t tpl))
19510 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19512 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19513 (setq rpl (if (or (match-end 1) (not pkg))
19514 "" (org-latex-packages-to-string pkg snippets-p t))
19515 tpl (replace-match rpl t t tpl))
19516 (when pkg (setq end
19517 (concat end "\n"
19518 (org-latex-packages-to-string pkg snippets-p)))))
19520 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19521 (setq rpl (if (or (match-end 1) (not extra))
19522 "" (concat extra "\n"))
19523 tpl (replace-match rpl t t tpl))
19524 (when (and extra (string-match "\\S-" extra))
19525 (setq end (concat end "\n" extra))))
19527 (if (string-match "\\S-" end)
19528 (concat tpl "\n" end)
19529 tpl)))
19531 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19532 "Turn an alist of packages into a string with the \\usepackage macros."
19533 (setq pkg (mapconcat (lambda(p)
19534 (cond
19535 ((stringp p) p)
19536 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19537 (format "%% Package %s omitted" (cadr p)))
19538 ((equal "" (car p))
19539 (format "\\usepackage{%s}" (cadr p)))
19541 (format "\\usepackage[%s]{%s}"
19542 (car p) (cadr p)))))
19544 "\n"))
19545 (if newline (concat pkg "\n") pkg))
19547 (defun org-dvipng-color (attr)
19548 "Return a RGB color specification for dvipng."
19549 (org-dvipng-color-format (face-attribute 'default attr nil)))
19551 (defun org-dvipng-color-format (color-name)
19552 "Convert COLOR-NAME to a RGB color value for dvipng."
19553 (apply #'format "rgb %s %s %s"
19554 (mapcar 'org-normalize-color
19555 (color-values color-name))))
19557 (defun org-latex-color (attr)
19558 "Return a RGB color for the LaTeX color package."
19559 (org-latex-color-format (face-attribute 'default attr nil)))
19561 (defun org-latex-color-format (color-name)
19562 "Convert COLOR-NAME to a RGB color value."
19563 (apply #'format "%s,%s,%s"
19564 (mapcar 'org-normalize-color
19565 (color-values color-name))))
19567 (defun org-normalize-color (value)
19568 "Return string to be used as color value for an RGB component."
19569 (format "%g" (/ value 65535.0)))
19573 ;; Image display
19575 (defvar-local org-inline-image-overlays nil)
19577 (defun org-toggle-inline-images (&optional include-linked)
19578 "Toggle the display of inline images.
19579 INCLUDE-LINKED is passed to `org-display-inline-images'."
19580 (interactive "P")
19581 (if org-inline-image-overlays
19582 (progn
19583 (org-remove-inline-images)
19584 (when (called-interactively-p 'interactive)
19585 (message "Inline image display turned off")))
19586 (org-display-inline-images include-linked)
19587 (when (called-interactively-p 'interactive)
19588 (message (if org-inline-image-overlays
19589 (format "%d images displayed inline"
19590 (length org-inline-image-overlays))
19591 "No images to display inline")))))
19593 (defun org-redisplay-inline-images ()
19594 "Refresh the display of inline images."
19595 (interactive)
19596 (if (not org-inline-image-overlays)
19597 (org-toggle-inline-images)
19598 (org-toggle-inline-images)
19599 (org-toggle-inline-images)))
19601 (defun org-display-inline-images (&optional include-linked refresh beg end)
19602 "Display inline images.
19604 An inline image is a link which follows either of these
19605 conventions:
19607 1. Its path is a file with an extension matching return value
19608 from `image-file-name-regexp' and it has no contents.
19610 2. Its description consists in a single link of the previous
19611 type.
19613 When optional argument INCLUDE-LINKED is non-nil, also links with
19614 a text description part will be inlined. This can be nice for
19615 a quick look at those images, but it does not reflect what
19616 exported files will look like.
19618 When optional argument REFRESH is non-nil, refresh existing
19619 images between BEG and END. This will create new image displays
19620 only if necessary. BEG and END default to the buffer
19621 boundaries."
19622 (interactive "P")
19623 (when (display-graphic-p)
19624 (unless refresh
19625 (org-remove-inline-images)
19626 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19627 (org-with-wide-buffer
19628 (goto-char (or beg (point-min)))
19629 (let ((case-fold-search t)
19630 (file-extension-re (image-file-name-regexp)))
19631 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19632 (let ((link (save-match-data (org-element-context))))
19633 ;; Check if we're at an inline image.
19634 (when (and (equal (org-element-property :type link) "file")
19635 (or include-linked
19636 (not (org-element-property :contents-begin link)))
19637 (let ((parent (org-element-property :parent link)))
19638 (or (not (eq (org-element-type parent) 'link))
19639 (not (cdr (org-element-contents parent)))))
19640 (string-match-p file-extension-re
19641 (org-element-property :path link)))
19642 (let ((file (expand-file-name
19643 (org-link-unescape
19644 (org-element-property :path link)))))
19645 (when (file-exists-p file)
19646 (let ((width
19647 ;; Apply `org-image-actual-width' specifications.
19648 (cond
19649 ((not (image-type-available-p 'imagemagick)) nil)
19650 ((eq org-image-actual-width t) nil)
19651 ((listp org-image-actual-width)
19653 ;; First try to find a width among
19654 ;; attributes associated to the paragraph
19655 ;; containing link.
19656 (let ((paragraph
19657 (let ((e link))
19658 (while (and (setq e (org-element-property
19659 :parent e))
19660 (not (eq (org-element-type e)
19661 'paragraph))))
19662 e)))
19663 (when paragraph
19664 (save-excursion
19665 (goto-char (org-element-property :begin paragraph))
19666 (when
19667 (re-search-forward
19668 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19669 (org-element-property
19670 :post-affiliated paragraph)
19672 (string-to-number (match-string 1))))))
19673 ;; Otherwise, fall-back to provided number.
19674 (car org-image-actual-width)))
19675 ((numberp org-image-actual-width)
19676 org-image-actual-width)))
19677 (old (get-char-property-and-overlay
19678 (org-element-property :begin link)
19679 'org-image-overlay)))
19680 (if (and (car-safe old) refresh)
19681 (image-refresh (overlay-get (cdr old) 'display))
19682 (let ((image (create-image file
19683 (and width 'imagemagick)
19685 :width width)))
19686 (when image
19687 (let* ((link
19688 ;; If inline image is the description
19689 ;; of another link, be sure to
19690 ;; consider the latter as the one to
19691 ;; apply the overlay on.
19692 (let ((parent
19693 (org-element-property :parent link)))
19694 (if (eq (org-element-type parent) 'link)
19695 parent
19696 link)))
19697 (ov (make-overlay
19698 (org-element-property :begin link)
19699 (progn
19700 (goto-char
19701 (org-element-property :end link))
19702 (skip-chars-backward " \t")
19703 (point)))))
19704 (overlay-put ov 'display image)
19705 (overlay-put ov 'face 'default)
19706 (overlay-put ov 'org-image-overlay t)
19707 (overlay-put
19708 ov 'modification-hooks
19709 (list 'org-display-inline-remove-overlay))
19710 (push ov org-inline-image-overlays)))))))))))))))
19712 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19713 "Remove inline-display overlay if a corresponding region is modified."
19714 (let ((inhibit-modification-hooks t))
19715 (when (and ov after)
19716 (delete ov org-inline-image-overlays)
19717 (delete-overlay ov))))
19719 (defun org-remove-inline-images ()
19720 "Remove inline display of images."
19721 (interactive)
19722 (mapc #'delete-overlay org-inline-image-overlays)
19723 (setq org-inline-image-overlays nil))
19725 ;;;; Key bindings
19727 ;; Outline functions from `outline-mode-prefix-map'
19728 ;; that can be remapped in Org:
19729 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19730 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19731 (define-key org-mode-map [remap outline-forward-same-level]
19732 'org-forward-heading-same-level)
19733 (define-key org-mode-map [remap outline-backward-same-level]
19734 'org-backward-heading-same-level)
19735 (define-key org-mode-map [remap outline-show-branches]
19736 'org-kill-note-or-show-branches)
19737 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19738 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19739 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19740 (define-key org-mode-map [remap outline-next-visible-heading]
19741 'org-next-visible-heading)
19742 (define-key org-mode-map [remap outline-previous-visible-heading]
19743 'org-previous-visible-heading)
19744 (define-key org-mode-map [remap show-children] 'org-show-children)
19746 ;; Outline functions from `outline-mode-prefix-map' that can not
19747 ;; be remapped in Org:
19749 ;; - the column "key binding" shows whether the Outline function is still
19750 ;; available in Org mode on the same key that it has been bound to in
19751 ;; Outline mode:
19752 ;; - "overridden": key used for a different functionality in Org mode
19753 ;; - else: key still bound to the same Outline function in Org mode
19755 ;; | Outline function | key binding | Org replacement |
19756 ;; |------------------------------------+-------------+--------------------------|
19757 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19758 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19759 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19760 ;; | `show-entry' | overridden | no replacement |
19761 ;; | `show-branches' | `C-c C-k' | still same function |
19762 ;; | `show-subtree' | overridden | visibility cycling |
19763 ;; | `show-all' | overridden | no replacement |
19764 ;; | `hide-subtree' | overridden | visibility cycling |
19765 ;; | `hide-body' | overridden | no replacement |
19766 ;; | `hide-entry' | overridden | visibility cycling |
19767 ;; | `hide-leaves' | overridden | no replacement |
19768 ;; | `hide-sublevels' | overridden | no replacement |
19769 ;; | `hide-other' | overridden | no replacement |
19771 ;; Make `C-c C-x' a prefix key
19772 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19774 ;; TAB key with modifiers
19775 (org-defkey org-mode-map "\C-i" 'org-cycle)
19776 (org-defkey org-mode-map [(tab)] 'org-cycle)
19777 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19778 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19779 ;; The following line is necessary under Suse GNU/Linux
19780 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19781 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19782 (define-key org-mode-map [backtab] 'org-shifttab)
19784 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19785 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19786 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19788 ;; Cursor keys with modifiers
19789 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19790 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19791 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19792 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19794 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19795 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19796 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19797 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19798 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19799 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19801 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19802 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19803 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19804 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19806 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19807 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19808 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19809 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19811 ;; Babel keys
19812 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19813 (dolist (pair org-babel-key-bindings)
19814 (define-key org-babel-map (car pair) (cdr pair)))
19816 ;;; Extra keys for tty access.
19817 ;; We only set them when really needed because otherwise the
19818 ;; menus don't show the simple keys
19820 (when (or org-use-extra-keys (not window-system))
19821 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19822 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19823 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19824 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19825 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19826 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19827 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19828 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19829 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19830 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19831 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19832 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19833 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19834 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19835 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19836 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19837 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19838 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19839 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19840 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19841 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19842 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19843 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19844 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19845 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19846 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19847 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19848 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19850 ;; All the other keys
19852 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19853 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19854 (if (boundp 'narrow-map)
19855 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19856 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19857 (if (boundp 'narrow-map)
19858 (org-defkey narrow-map "b" 'org-narrow-to-block)
19859 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19860 (if (boundp 'narrow-map)
19861 (org-defkey narrow-map "e" 'org-narrow-to-element)
19862 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19863 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19864 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19865 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19866 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19867 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19868 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19869 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19870 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19871 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19872 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19873 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19874 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19875 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19876 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19877 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19878 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19879 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19880 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19881 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19882 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19883 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19884 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19885 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19886 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19887 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19888 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19889 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19890 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19891 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19892 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19893 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19894 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19895 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19896 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19897 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19898 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19899 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19900 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19901 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19902 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19903 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19904 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19905 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19906 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19907 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19908 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19909 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19910 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19911 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19912 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19913 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19914 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19915 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19916 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19917 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19918 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19919 (org-defkey org-mode-map "\C-c^" 'org-sort)
19920 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19921 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19922 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19923 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19924 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19925 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19926 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19927 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19928 (org-defkey org-mode-map "\C-m" 'org-return)
19929 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19930 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19931 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19932 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19933 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19934 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19935 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19936 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19937 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19938 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19939 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19940 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19941 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19942 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19943 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19944 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19945 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19946 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19947 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19948 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19949 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19950 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19951 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19952 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19953 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19955 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19956 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19957 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19959 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19960 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19961 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19962 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19963 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19964 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19965 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19966 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19967 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19968 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19969 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19970 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19971 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19972 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19973 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19974 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19975 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19976 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19977 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19978 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19979 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19980 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19982 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19983 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19984 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19985 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19986 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19988 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19990 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19992 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19993 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19995 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19998 (defconst org-speed-commands-default
20000 ("Outline Navigation")
20001 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20002 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20003 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20004 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20005 ("F" . org-next-block)
20006 ("B" . org-previous-block)
20007 ("u" . (org-speed-move-safe 'outline-up-heading))
20008 ("j" . org-goto)
20009 ("g" . (org-refile t))
20010 ("Outline Visibility")
20011 ("c" . org-cycle)
20012 ("C" . org-shifttab)
20013 (" " . org-display-outline-path)
20014 ("s" . org-narrow-to-subtree)
20015 ("=" . org-columns)
20016 ("Outline Structure Editing")
20017 ("U" . org-metaup)
20018 ("D" . org-metadown)
20019 ("r" . org-metaright)
20020 ("l" . org-metaleft)
20021 ("R" . org-shiftmetaright)
20022 ("L" . org-shiftmetaleft)
20023 ("i" . (progn (forward-char 1) (call-interactively
20024 'org-insert-heading-respect-content)))
20025 ("^" . org-sort)
20026 ("w" . org-refile)
20027 ("a" . org-archive-subtree-default-with-confirmation)
20028 ("@" . org-mark-subtree)
20029 ("#" . org-toggle-comment)
20030 ("Clock Commands")
20031 ("I" . org-clock-in)
20032 ("O" . org-clock-out)
20033 ("Meta Data Editing")
20034 ("t" . org-todo)
20035 ("," . (org-priority))
20036 ("0" . (org-priority ?\ ))
20037 ("1" . (org-priority ?A))
20038 ("2" . (org-priority ?B))
20039 ("3" . (org-priority ?C))
20040 (":" . org-set-tags-command)
20041 ("e" . org-set-effort)
20042 ("E" . org-inc-effort)
20043 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20044 (org-entry-put (point) "APPT_WARNTIME" m)))
20045 ("Agenda Views etc")
20046 ("v" . org-agenda)
20047 ("/" . org-sparse-tree)
20048 ("Misc")
20049 ("o" . org-open-at-point)
20050 ("?" . org-speed-command-help)
20051 ("<" . (org-agenda-set-restriction-lock 'subtree))
20052 (">" . (org-agenda-remove-restriction-lock))
20054 "The default speed commands.")
20056 (defun org-print-speed-command (e)
20057 (if (> (length (car e)) 1)
20058 (progn
20059 (princ "\n")
20060 (princ (car e))
20061 (princ "\n")
20062 (princ (make-string (length (car e)) ?-))
20063 (princ "\n"))
20064 (princ (car e))
20065 (princ " ")
20066 (if (symbolp (cdr e))
20067 (princ (symbol-name (cdr e)))
20068 (prin1 (cdr e)))
20069 (princ "\n")))
20071 (defun org-speed-command-help ()
20072 "Show the available speed commands."
20073 (interactive)
20074 (if (not org-use-speed-commands)
20075 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20076 (with-output-to-temp-buffer "*Help*"
20077 (princ "User-defined Speed commands\n===========================\n")
20078 (mapc #'org-print-speed-command org-speed-commands-user)
20079 (princ "\n")
20080 (princ "Built-in Speed commands\n=======================\n")
20081 (mapc #'org-print-speed-command org-speed-commands-default))
20082 (with-current-buffer "*Help*"
20083 (setq truncate-lines t))))
20085 (defun org-speed-move-safe (cmd)
20086 "Execute CMD, but make sure that the cursor always ends up in a headline.
20087 If not, return to the original position and throw an error."
20088 (interactive)
20089 (let ((pos (point)))
20090 (call-interactively cmd)
20091 (unless (and (bolp) (org-at-heading-p))
20092 (goto-char pos)
20093 (error "Boundary reached while executing %s" cmd))))
20095 (defvar org-self-insert-command-undo-counter 0)
20097 (defvar org-table-auto-blank-field) ; defined in org-table.el
20098 (defvar org-speed-command nil)
20100 (defun org-speed-command-activate (keys)
20101 "Hook for activating single-letter speed commands.
20102 `org-speed-commands-default' specifies a minimal command set.
20103 Use `org-speed-commands-user' for further customization."
20104 (when (or (and (bolp) (looking-at org-outline-regexp))
20105 (and (functionp org-use-speed-commands)
20106 (funcall org-use-speed-commands)))
20107 (cdr (assoc keys (append org-speed-commands-user
20108 org-speed-commands-default)))))
20110 (defun org-babel-speed-command-activate (keys)
20111 "Hook for activating single-letter code block commands."
20112 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20113 (cdr (assoc keys org-babel-key-bindings))))
20115 (defcustom org-speed-command-hook
20116 '(org-speed-command-default-hook org-babel-speed-command-hook)
20117 "Hook for activating speed commands at strategic locations.
20118 Hook functions are called in sequence until a valid handler is
20119 found.
20121 Each hook takes a single argument, a user-pressed command key
20122 which is also a `self-insert-command' from the global map.
20124 Within the hook, examine the cursor position and the command key
20125 and return nil or a valid handler as appropriate. Handler could
20126 be one of an interactive command, a function, or a form.
20128 Set `org-use-speed-commands' to non-nil value to enable this
20129 hook. The default setting is `org-speed-command-activate'."
20130 :group 'org-structure
20131 :version "24.1"
20132 :type 'hook)
20134 (defun org-self-insert-command (N)
20135 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20136 If the cursor is in a table looking at whitespace, the whitespace is
20137 overwritten, and the table is not marked as requiring realignment."
20138 (interactive "p")
20139 (org-check-before-invisible-edit 'insert)
20140 (cond
20141 ((and org-use-speed-commands
20142 (let ((kv (this-command-keys-vector)))
20143 (setq org-speed-command
20144 (run-hook-with-args-until-success
20145 'org-speed-command-hook
20146 (make-string 1 (aref kv (1- (length kv))))))))
20147 (cond
20148 ((commandp org-speed-command)
20149 (setq this-command org-speed-command)
20150 (call-interactively org-speed-command))
20151 ((functionp org-speed-command)
20152 (funcall org-speed-command))
20153 ((and org-speed-command (listp org-speed-command))
20154 (eval org-speed-command))
20155 (t (let (org-use-speed-commands)
20156 (call-interactively 'org-self-insert-command)))))
20157 ((and
20158 (org-at-table-p)
20159 (progn
20160 ;; Check if we blank the field, and if that triggers align.
20161 (and (featurep 'org-table) org-table-auto-blank-field
20162 (memq last-command
20163 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20164 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20165 ;; Got extra space, this field does not determine
20166 ;; column width.
20167 (let (org-table-may-need-update) (org-table-blank-field))
20168 ;; No extra space, this field may determine column
20169 ;; width.
20170 (org-table-blank-field)))
20172 (eq N 1)
20173 (looking-at "[^|\n]* \\( \\)|"))
20174 ;; There is room for insertion without re-aligning the table.
20175 (delete-region (match-beginning 1) (match-end 1))
20176 (self-insert-command N))
20178 (setq org-table-may-need-update t)
20179 (self-insert-command N)
20180 (org-fix-tags-on-the-fly)
20181 (when org-self-insert-cluster-for-undo
20182 (if (not (eq last-command 'org-self-insert-command))
20183 (setq org-self-insert-command-undo-counter 1)
20184 (if (>= org-self-insert-command-undo-counter 20)
20185 (setq org-self-insert-command-undo-counter 1)
20186 (and (> org-self-insert-command-undo-counter 0)
20187 buffer-undo-list (listp buffer-undo-list)
20188 (not (cadr buffer-undo-list)) ; remove nil entry
20189 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20190 (setq org-self-insert-command-undo-counter
20191 (1+ org-self-insert-command-undo-counter))))))))
20193 (defun org-check-before-invisible-edit (kind)
20194 "Check is editing if kind KIND would be dangerous with invisible text around.
20195 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20196 ;; First, try to get out of here as quickly as possible, to reduce overhead
20197 (when (and org-catch-invisible-edits
20198 (or (not (boundp 'visible-mode)) (not visible-mode))
20199 (or (get-char-property (point) 'invisible)
20200 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20201 ;; OK, we need to take a closer look
20202 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20203 (invisible-before-point (unless (bobp) (get-char-property
20204 (1- (point)) 'invisible)))
20205 (border-and-ok-direction
20207 ;; Check if we are acting predictably before invisible text
20208 (and invisible-at-point (not invisible-before-point)
20209 (memq kind '(insert delete-backward)))
20210 ;; Check if we are acting predictably after invisible text
20211 ;; This works not well, and I have turned it off. It seems
20212 ;; better to always show and stop after invisible text.
20213 ;; (and (not invisible-at-point) invisible-before-point
20214 ;; (memq kind '(insert delete)))
20216 (when (or (memq invisible-at-point '(outline org-hide-block t))
20217 (memq invisible-before-point '(outline org-hide-block t)))
20218 (when (eq org-catch-invisible-edits 'error)
20219 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20220 (if (and org-custom-properties-overlays
20221 (y-or-n-p "Display invisible properties in this buffer? "))
20222 (org-toggle-custom-properties-visibility)
20223 ;; Make the area visible
20224 (save-excursion
20225 (when invisible-before-point
20226 (goto-char (previous-single-char-property-change
20227 (point) 'invisible)))
20228 (outline-show-subtree))
20229 (cond
20230 ((eq org-catch-invisible-edits 'show)
20231 ;; That's it, we do the edit after showing
20232 (message
20233 "Unfolding invisible region around point before editing")
20234 (sit-for 1))
20235 ((and (eq org-catch-invisible-edits 'smart)
20236 border-and-ok-direction)
20237 (message "Unfolding invisible region around point before editing"))
20239 ;; Don't do the edit, make the user repeat it in full visibility
20240 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20242 (defun org-fix-tags-on-the-fly ()
20243 "Align tags in headline at point.
20244 Unlike to `org-set-tags', it ignores region and sorting."
20245 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
20246 (org-at-heading-p))
20247 (let ((org-ignore-region t)
20248 (org-tags-sort-function nil))
20249 (org-set-tags nil t))))
20251 (defun org-delete-backward-char (N)
20252 "Like `delete-backward-char', insert whitespace at field end in tables.
20253 When deleting backwards, in tables this function will insert whitespace in
20254 front of the next \"|\" separator, to keep the table aligned. The table will
20255 still be marked for re-alignment if the field did fill the entire column,
20256 because, in this case the deletion might narrow the column."
20257 (interactive "p")
20258 (save-match-data
20259 (org-check-before-invisible-edit 'delete-backward)
20260 (if (and (org-at-table-p)
20261 (eq N 1)
20262 (string-match "|" (buffer-substring (point-at-bol) (point)))
20263 (looking-at ".*?|"))
20264 (let ((pos (point))
20265 (noalign (looking-at "[^|\n\r]* |"))
20266 (c org-table-may-need-update))
20267 (backward-delete-char N)
20268 (unless overwrite-mode
20269 (skip-chars-forward "^|")
20270 (insert " ")
20271 (goto-char (1- pos)))
20272 ;; noalign: if there were two spaces at the end, this field
20273 ;; does not determine the width of the column.
20274 (when noalign (setq org-table-may-need-update c)))
20275 (backward-delete-char N)
20276 (org-fix-tags-on-the-fly))))
20278 (defun org-delete-char (N)
20279 "Like `delete-char', but insert whitespace at field end in tables.
20280 When deleting characters, in tables this function will insert whitespace in
20281 front of the next \"|\" separator, to keep the table aligned. The table will
20282 still be marked for re-alignment if the field did fill the entire column,
20283 because, in this case the deletion might narrow the column."
20284 (interactive "p")
20285 (save-match-data
20286 (org-check-before-invisible-edit 'delete)
20287 (if (and (org-at-table-p)
20288 (not (bolp))
20289 (not (= (char-after) ?|))
20290 (eq N 1))
20291 (if (looking-at ".*?|")
20292 (let ((pos (point))
20293 (noalign (looking-at "[^|\n\r]* |"))
20294 (c org-table-may-need-update))
20295 (replace-match
20296 (concat (substring (match-string 0) 1 -1) " |") nil t)
20297 (goto-char pos)
20298 ;; noalign: if there were two spaces at the end, this field
20299 ;; does not determine the width of the column.
20300 (when noalign (setq org-table-may-need-update c)))
20301 (delete-char N))
20302 (delete-char N)
20303 (org-fix-tags-on-the-fly))))
20305 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20306 (put 'org-self-insert-command 'delete-selection
20307 (lambda ()
20308 (not (run-hook-with-args-until-success
20309 'self-insert-uses-region-functions))))
20310 (put 'orgtbl-self-insert-command 'delete-selection
20311 (lambda ()
20312 (not (run-hook-with-args-until-success
20313 'self-insert-uses-region-functions))))
20314 (put 'org-delete-char 'delete-selection 'supersede)
20315 (put 'org-delete-backward-char 'delete-selection 'supersede)
20316 (put 'org-yank 'delete-selection 'yank)
20318 ;; Make `flyspell-mode' delay after some commands
20319 (put 'org-self-insert-command 'flyspell-delayed t)
20320 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20321 (put 'org-delete-char 'flyspell-delayed t)
20322 (put 'org-delete-backward-char 'flyspell-delayed t)
20324 ;; Make pabbrev-mode expand after Org mode commands
20325 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20326 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20328 (defun org-remap (map &rest commands)
20329 "In MAP, remap the functions given in COMMANDS.
20330 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20331 (let (new old)
20332 (while commands
20333 (setq old (pop commands) new (pop commands))
20334 (org-defkey map (vector 'remap old) new))))
20336 (defun org-transpose-words ()
20337 "Transpose words for Org.
20338 This uses the `org-mode-transpose-word-syntax-table' syntax
20339 table, which interprets characters in `org-emphasis-alist' as
20340 word constituents."
20341 (interactive)
20342 (with-syntax-table org-mode-transpose-word-syntax-table
20343 (call-interactively 'transpose-words)))
20344 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20346 (when (eq org-enable-table-editor 'optimized)
20347 ;; If the user wants maximum table support, we need to hijack
20348 ;; some standard editing functions
20349 (org-remap org-mode-map
20350 'self-insert-command 'org-self-insert-command
20351 'delete-char 'org-delete-char
20352 'delete-backward-char 'org-delete-backward-char)
20353 (org-defkey org-mode-map "|" 'org-force-self-insert))
20355 (defvar org-ctrl-c-ctrl-c-hook nil
20356 "Hook for functions attaching themselves to `C-c C-c'.
20358 This can be used to add additional functionality to the C-c C-c
20359 key which executes context-dependent commands. This hook is run
20360 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20361 run after the last test.
20363 Each function will be called with no arguments. The function
20364 must check if the context is appropriate for it to act. If yes,
20365 it should do its thing and then return a non-nil value. If the
20366 context is wrong, just do nothing and return nil.")
20368 (defvar org-ctrl-c-ctrl-c-final-hook nil
20369 "Hook for functions attaching themselves to `C-c C-c'.
20371 This can be used to add additional functionality to the C-c C-c
20372 key which executes context-dependent commands. This hook is run
20373 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20374 before the first test.
20376 Each function will be called with no arguments. The function
20377 must check if the context is appropriate for it to act. If yes,
20378 it should do its thing and then return a non-nil value. If the
20379 context is wrong, just do nothing and return nil.")
20381 (defvar org-tab-first-hook nil
20382 "Hook for functions to attach themselves to TAB.
20383 See `org-ctrl-c-ctrl-c-hook' for more information.
20384 This hook runs as the first action when TAB is pressed, even before
20385 `org-cycle' messes around with the `outline-regexp' to cater for
20386 inline tasks and plain list item folding.
20387 If any function in this hook returns t, any other actions that
20388 would have been caused by TAB (such as table field motion or visibility
20389 cycling) will not occur.")
20391 (defvar org-tab-after-check-for-table-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 it has been established that the cursor is not in a
20395 table, but before checking if the cursor is in a headline or if global cycling
20396 should be done.
20397 If any function in this hook returns t, not other actions like visibility
20398 cycling will be done.")
20400 (defvar org-tab-after-check-for-cycling-hook nil
20401 "Hook for functions to attach themselves to TAB.
20402 See `org-ctrl-c-ctrl-c-hook' for more information.
20403 This hook runs after it has been established that not table field motion and
20404 not visibility should be done because of current context. This is probably
20405 the place where a package like yasnippets can hook in.")
20407 (defvar org-tab-before-tab-emulation-hook nil
20408 "Hook for functions to attach themselves to TAB.
20409 See `org-ctrl-c-ctrl-c-hook' for more information.
20410 This hook runs after every other options for TAB have been exhausted, but
20411 before indentation and \t insertion takes place.")
20413 (defvar org-metaleft-hook nil
20414 "Hook for functions attaching themselves to `M-left'.
20415 See `org-ctrl-c-ctrl-c-hook' for more information.")
20416 (defvar org-metaright-hook nil
20417 "Hook for functions attaching themselves to `M-right'.
20418 See `org-ctrl-c-ctrl-c-hook' for more information.")
20419 (defvar org-metaup-hook nil
20420 "Hook for functions attaching themselves to `M-up'.
20421 See `org-ctrl-c-ctrl-c-hook' for more information.")
20422 (defvar org-metadown-hook nil
20423 "Hook for functions attaching themselves to `M-down'.
20424 See `org-ctrl-c-ctrl-c-hook' for more information.")
20425 (defvar org-shiftmetaleft-hook nil
20426 "Hook for functions attaching themselves to `M-S-left'.
20427 See `org-ctrl-c-ctrl-c-hook' for more information.")
20428 (defvar org-shiftmetaright-hook nil
20429 "Hook for functions attaching themselves to `M-S-right'.
20430 See `org-ctrl-c-ctrl-c-hook' for more information.")
20431 (defvar org-shiftmetaup-hook nil
20432 "Hook for functions attaching themselves to `M-S-up'.
20433 See `org-ctrl-c-ctrl-c-hook' for more information.")
20434 (defvar org-shiftmetadown-hook nil
20435 "Hook for functions attaching themselves to `M-S-down'.
20436 See `org-ctrl-c-ctrl-c-hook' for more information.")
20437 (defvar org-metareturn-hook nil
20438 "Hook for functions attaching themselves to `M-RET'.
20439 See `org-ctrl-c-ctrl-c-hook' for more information.")
20440 (defvar org-shiftup-hook nil
20441 "Hook for functions attaching themselves to `S-up'.
20442 See `org-ctrl-c-ctrl-c-hook' for more information.")
20443 (defvar org-shiftup-final-hook nil
20444 "Hook for functions attaching themselves to `S-up'.
20445 This one runs after all other options except shift-select have been excluded.
20446 See `org-ctrl-c-ctrl-c-hook' for more information.")
20447 (defvar org-shiftdown-hook nil
20448 "Hook for functions attaching themselves to `S-down'.
20449 See `org-ctrl-c-ctrl-c-hook' for more information.")
20450 (defvar org-shiftdown-final-hook nil
20451 "Hook for functions attaching themselves to `S-down'.
20452 This one runs after all other options except shift-select have been excluded.
20453 See `org-ctrl-c-ctrl-c-hook' for more information.")
20454 (defvar org-shiftleft-hook nil
20455 "Hook for functions attaching themselves to `S-left'.
20456 See `org-ctrl-c-ctrl-c-hook' for more information.")
20457 (defvar org-shiftleft-final-hook nil
20458 "Hook for functions attaching themselves to `S-left'.
20459 This one runs after all other options except shift-select have been excluded.
20460 See `org-ctrl-c-ctrl-c-hook' for more information.")
20461 (defvar org-shiftright-hook nil
20462 "Hook for functions attaching themselves to `S-right'.
20463 See `org-ctrl-c-ctrl-c-hook' for more information.")
20464 (defvar org-shiftright-final-hook nil
20465 "Hook for functions attaching themselves to `S-right'.
20466 This one runs after all other options except shift-select have been excluded.
20467 See `org-ctrl-c-ctrl-c-hook' for more information.")
20469 (defun org-modifier-cursor-error ()
20470 "Throw an error, a modified cursor command was applied in wrong context."
20471 (user-error "This command is active in special context like tables, headlines or items"))
20473 (defun org-shiftselect-error ()
20474 "Throw an error because Shift-Cursor command was applied in wrong context."
20475 (if (and (boundp 'shift-select-mode) shift-select-mode)
20476 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20477 (user-error "This command works only in special context like headlines or timestamps")))
20479 (defun org-call-for-shift-select (cmd)
20480 (let ((this-command-keys-shift-translated t))
20481 (call-interactively cmd)))
20483 (defun org-shifttab (&optional arg)
20484 "Global visibility cycling or move to previous table field.
20485 Call `org-table-previous-field' within a table.
20486 When ARG is nil, cycle globally through visibility states.
20487 When ARG is a numeric prefix, show contents of this level."
20488 (interactive "P")
20489 (cond
20490 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20491 ((integerp arg)
20492 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20493 (message "Content view to level: %d" arg)
20494 (org-content (prefix-numeric-value arg2))
20495 (org-cycle-show-empty-lines t)
20496 (setq org-cycle-global-status 'overview)))
20497 (t (call-interactively 'org-global-cycle))))
20499 (defun org-shiftmetaleft ()
20500 "Promote subtree or delete table column.
20501 Calls `org-promote-subtree', `org-outdent-item-tree', or
20502 `org-table-delete-column', depending on context. See the
20503 individual commands for more information."
20504 (interactive)
20505 (cond
20506 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20507 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20508 ((org-at-heading-p) (call-interactively 'org-promote-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-outdent-item-tree))
20513 (t (org-modifier-cursor-error))))
20515 (defun org-shiftmetaright ()
20516 "Demote subtree or insert table column.
20517 Calls `org-demote-subtree', `org-indent-item-tree', or
20518 `org-table-insert-column', depending on context. See the
20519 individual commands for more information."
20520 (interactive)
20521 (cond
20522 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20523 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20524 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20525 ((if (not (org-region-active-p)) (org-at-item-p)
20526 (save-excursion (goto-char (region-beginning))
20527 (org-at-item-p)))
20528 (call-interactively 'org-indent-item-tree))
20529 (t (org-modifier-cursor-error))))
20531 (defun org-shiftmetaup (&optional _arg)
20532 "Drag the line at point up.
20533 In a table, kill the current row.
20534 On a clock timestamp, update the value of the timestamp like `S-<up>'
20535 but also adjust the previous clocked item in the clock history.
20536 Everywhere else, drag the line at point up."
20537 (interactive "P")
20538 (cond
20539 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20540 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20541 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20542 (call-interactively 'org-timestamp-up)))
20543 (t (call-interactively 'org-drag-line-backward))))
20545 (defun org-shiftmetadown (&optional _arg)
20546 "Drag the line at point down.
20547 In a table, insert an empty row at the current line.
20548 On a clock timestamp, update the value of the timestamp like `S-<down>'
20549 but also adjust the previous clocked item in the clock history.
20550 Everywhere else, drag the line at point down."
20551 (interactive "P")
20552 (cond
20553 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20554 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20555 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20556 (call-interactively 'org-timestamp-down)))
20557 (t (call-interactively 'org-drag-line-forward))))
20559 (defsubst org-hidden-tree-error ()
20560 (user-error
20561 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20563 (defun org-metaleft (&optional _arg)
20564 "Promote heading, list item at point or move table column left.
20566 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20567 depending on context. With no specific context, calls the Emacs
20568 default `backward-word'. See the individual commands for more
20569 information.
20571 This function runs the hook `org-metaleft-hook' as a first step,
20572 and returns at first non-nil value."
20573 (interactive "P")
20574 (cond
20575 ((run-hook-with-args-until-success 'org-metaleft-hook))
20576 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20577 ((org-with-limited-levels
20578 (or (org-at-heading-p)
20579 (and (org-region-active-p)
20580 (save-excursion
20581 (goto-char (region-beginning))
20582 (org-at-heading-p)))))
20583 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20584 (call-interactively 'org-do-promote))
20585 ;; At an inline task.
20586 ((org-at-heading-p)
20587 (call-interactively 'org-inlinetask-promote))
20588 ((or (org-at-item-p)
20589 (and (org-region-active-p)
20590 (save-excursion
20591 (goto-char (region-beginning))
20592 (org-at-item-p))))
20593 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20594 (call-interactively 'org-outdent-item))
20595 (t (call-interactively 'backward-word))))
20597 (defun org-metaright (&optional _arg)
20598 "Demote heading, list item at point or move table column right.
20600 In front of a drawer or a block keyword, indent it correctly.
20602 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20603 `org-indent-drawer' or `org-indent-block' depending on context.
20604 With no specific context, calls the Emacs default `forward-word'.
20605 See the individual commands for more information.
20607 This function runs the hook `org-metaright-hook' as a first step,
20608 and returns at first non-nil value."
20609 (interactive "P")
20610 (cond
20611 ((run-hook-with-args-until-success 'org-metaright-hook))
20612 ((org-at-table-p) (call-interactively 'org-table-move-column))
20613 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20614 ((org-at-block-p) (call-interactively 'org-indent-block))
20615 ((org-with-limited-levels
20616 (or (org-at-heading-p)
20617 (and (org-region-active-p)
20618 (save-excursion
20619 (goto-char (region-beginning))
20620 (org-at-heading-p)))))
20621 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20622 (call-interactively 'org-do-demote))
20623 ;; At an inline task.
20624 ((org-at-heading-p)
20625 (call-interactively 'org-inlinetask-demote))
20626 ((or (org-at-item-p)
20627 (and (org-region-active-p)
20628 (save-excursion
20629 (goto-char (region-beginning))
20630 (org-at-item-p))))
20631 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20632 (call-interactively 'org-indent-item))
20633 (t (call-interactively 'forward-word))))
20635 (defun org-check-for-hidden (what)
20636 "Check if there are hidden headlines/items in the current visual line.
20637 WHAT can be either `headlines' or `items'. If the current line is
20638 an outline or item heading and it has a folded subtree below it,
20639 this function returns t, nil otherwise."
20640 (let ((re (cond
20641 ((eq what 'headlines) org-outline-regexp-bol)
20642 ((eq what 'items) (org-item-beginning-re))
20643 (t (error "This should not happen"))))
20644 beg end)
20645 (save-excursion
20646 (catch 'exit
20647 (unless (org-region-active-p)
20648 (setq beg (point-at-bol))
20649 (beginning-of-line 2)
20650 (while (and (not (eobp)) ;; this is like `next-line'
20651 (get-char-property (1- (point)) 'invisible))
20652 (beginning-of-line 2))
20653 (setq end (point))
20654 (goto-char beg)
20655 (goto-char (point-at-eol))
20656 (setq end (max end (point)))
20657 (while (re-search-forward re end t)
20658 (when (get-char-property (match-beginning 0) 'invisible)
20659 (throw 'exit t))))
20660 nil))))
20662 (defun org-metaup (&optional _arg)
20663 "Move subtree up or move table row up.
20664 Calls `org-move-subtree-up' or `org-table-move-row' or
20665 `org-move-item-up', depending on context. See the individual commands
20666 for more information."
20667 (interactive "P")
20668 (cond
20669 ((run-hook-with-args-until-success 'org-metaup-hook))
20670 ((org-region-active-p)
20671 (let* ((a (min (region-beginning) (region-end)))
20672 (b (1- (max (region-beginning) (region-end))))
20673 (c (save-excursion (goto-char a)
20674 (move-beginning-of-line 0)))
20675 (d (save-excursion (goto-char a)
20676 (move-end-of-line 0) (point))))
20677 (transpose-regions a b c d)
20678 (goto-char c)))
20679 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20680 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20681 ((org-at-item-p) (call-interactively 'org-move-item-up))
20682 (t (org-drag-element-backward))))
20684 (defun org-metadown (&optional _arg)
20685 "Move subtree down or move table row down.
20686 Calls `org-move-subtree-down' or `org-table-move-row' or
20687 `org-move-item-down', depending on context. See the individual
20688 commands for more information."
20689 (interactive "P")
20690 (cond
20691 ((run-hook-with-args-until-success 'org-metadown-hook))
20692 ((org-region-active-p)
20693 (let* ((a (min (region-beginning) (region-end)))
20694 (b (max (region-beginning) (region-end)))
20695 (c (save-excursion (goto-char b)
20696 (move-beginning-of-line 1)))
20697 (d (save-excursion (goto-char b)
20698 (move-end-of-line 1) (1+ (point)))))
20699 (transpose-regions a b c d)
20700 (goto-char d)))
20701 ((org-at-table-p) (call-interactively 'org-table-move-row))
20702 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20703 ((org-at-item-p) (call-interactively 'org-move-item-down))
20704 (t (org-drag-element-forward))))
20706 (defun org-shiftup (&optional arg)
20707 "Increase item in timestamp or increase priority of current headline.
20708 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20709 depending on context. See the individual commands for more information."
20710 (interactive "P")
20711 (cond
20712 ((run-hook-with-args-until-success 'org-shiftup-hook))
20713 ((and org-support-shift-select (org-region-active-p))
20714 (org-call-for-shift-select 'previous-line))
20715 ((org-at-timestamp-p t)
20716 (call-interactively (if org-edit-timestamp-down-means-later
20717 'org-timestamp-down 'org-timestamp-up)))
20718 ((and (not (eq org-support-shift-select 'always))
20719 org-enable-priority-commands
20720 (org-at-heading-p))
20721 (call-interactively 'org-priority-up))
20722 ((and (not org-support-shift-select) (org-at-item-p))
20723 (call-interactively 'org-previous-item))
20724 ((org-clocktable-try-shift 'up arg))
20725 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20726 (org-support-shift-select
20727 (org-call-for-shift-select 'previous-line))
20728 (t (org-shiftselect-error))))
20730 (defun org-shiftdown (&optional arg)
20731 "Decrease item in timestamp or decrease priority of current headline.
20732 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20733 depending on context. See the individual commands for more information."
20734 (interactive "P")
20735 (cond
20736 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20737 ((and org-support-shift-select (org-region-active-p))
20738 (org-call-for-shift-select 'next-line))
20739 ((org-at-timestamp-p t)
20740 (call-interactively (if org-edit-timestamp-down-means-later
20741 'org-timestamp-up 'org-timestamp-down)))
20742 ((and (not (eq org-support-shift-select 'always))
20743 org-enable-priority-commands
20744 (org-at-heading-p))
20745 (call-interactively 'org-priority-down))
20746 ((and (not org-support-shift-select) (org-at-item-p))
20747 (call-interactively 'org-next-item))
20748 ((org-clocktable-try-shift 'down arg))
20749 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20750 (org-support-shift-select
20751 (org-call-for-shift-select 'next-line))
20752 (t (org-shiftselect-error))))
20754 (defun org-shiftright (&optional arg)
20755 "Cycle the thing at point or in the current line, depending on context.
20756 Depending on context, this does one of the following:
20758 - switch a timestamp at point one day into the future
20759 - on a headline, switch to the next TODO keyword.
20760 - on an item, switch entire list to the next bullet type
20761 - on a property line, switch to the next allowed value
20762 - on a clocktable definition line, move time block into the future"
20763 (interactive "P")
20764 (cond
20765 ((run-hook-with-args-until-success 'org-shiftright-hook))
20766 ((and org-support-shift-select (org-region-active-p))
20767 (org-call-for-shift-select 'forward-char))
20768 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20769 ((and (not (eq org-support-shift-select 'always))
20770 (org-at-heading-p))
20771 (let ((org-inhibit-logging
20772 (not org-treat-S-cursor-todo-selection-as-state-change))
20773 (org-inhibit-blocking
20774 (not org-treat-S-cursor-todo-selection-as-state-change)))
20775 (org-call-with-arg 'org-todo 'right)))
20776 ((or (and org-support-shift-select
20777 (not (eq org-support-shift-select 'always))
20778 (org-at-item-bullet-p))
20779 (and (not org-support-shift-select) (org-at-item-p)))
20780 (org-call-with-arg 'org-cycle-list-bullet nil))
20781 ((and (not (eq org-support-shift-select 'always))
20782 (org-at-property-p))
20783 (call-interactively 'org-property-next-allowed-value))
20784 ((org-clocktable-try-shift 'right arg))
20785 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20786 (org-support-shift-select
20787 (org-call-for-shift-select 'forward-char))
20788 (t (org-shiftselect-error))))
20790 (defun org-shiftleft (&optional arg)
20791 "Cycle the thing at point or in the current line, depending on context.
20792 Depending on context, this does one of the following:
20794 - switch a timestamp at point one day into the past
20795 - on a headline, switch to the previous TODO keyword.
20796 - on an item, switch entire list to the previous bullet type
20797 - on a property line, switch to the previous allowed value
20798 - on a clocktable definition line, move time block into the past"
20799 (interactive "P")
20800 (cond
20801 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20802 ((and org-support-shift-select (org-region-active-p))
20803 (org-call-for-shift-select 'backward-char))
20804 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20805 ((and (not (eq org-support-shift-select 'always))
20806 (org-at-heading-p))
20807 (let ((org-inhibit-logging
20808 (not org-treat-S-cursor-todo-selection-as-state-change))
20809 (org-inhibit-blocking
20810 (not org-treat-S-cursor-todo-selection-as-state-change)))
20811 (org-call-with-arg 'org-todo 'left)))
20812 ((or (and org-support-shift-select
20813 (not (eq org-support-shift-select 'always))
20814 (org-at-item-bullet-p))
20815 (and (not org-support-shift-select) (org-at-item-p)))
20816 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20817 ((and (not (eq org-support-shift-select 'always))
20818 (org-at-property-p))
20819 (call-interactively 'org-property-previous-allowed-value))
20820 ((org-clocktable-try-shift 'left arg))
20821 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20822 (org-support-shift-select
20823 (org-call-for-shift-select 'backward-char))
20824 (t (org-shiftselect-error))))
20826 (defun org-shiftcontrolright ()
20827 "Switch to next TODO set."
20828 (interactive)
20829 (cond
20830 ((and org-support-shift-select (org-region-active-p))
20831 (org-call-for-shift-select 'forward-word))
20832 ((and (not (eq org-support-shift-select 'always))
20833 (org-at-heading-p))
20834 (org-call-with-arg 'org-todo 'nextset))
20835 (org-support-shift-select
20836 (org-call-for-shift-select 'forward-word))
20837 (t (org-shiftselect-error))))
20839 (defun org-shiftcontrolleft ()
20840 "Switch to previous TODO set."
20841 (interactive)
20842 (cond
20843 ((and org-support-shift-select (org-region-active-p))
20844 (org-call-for-shift-select 'backward-word))
20845 ((and (not (eq org-support-shift-select 'always))
20846 (org-at-heading-p))
20847 (org-call-with-arg 'org-todo 'previousset))
20848 (org-support-shift-select
20849 (org-call-for-shift-select 'backward-word))
20850 (t (org-shiftselect-error))))
20852 (defun org-shiftcontrolup (&optional n)
20853 "Change timestamps synchronously up in CLOCK log lines.
20854 Optional argument N tells to change by that many units."
20855 (interactive "P")
20856 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20857 (let (org-support-shift-select)
20858 (org-clock-timestamps-up n))
20859 (user-error "Not at a clock log")))
20861 (defun org-shiftcontroldown (&optional n)
20862 "Change timestamps synchronously down in CLOCK log lines.
20863 Optional argument N tells to change by that many units."
20864 (interactive "P")
20865 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20866 (let (org-support-shift-select)
20867 (org-clock-timestamps-down n))
20868 (user-error "Not at a clock log")))
20870 (defun org-increase-number-at-point (&optional inc)
20871 "Increment the number at point.
20872 With an optional prefix numeric argument INC, increment using
20873 this numeric value."
20874 (interactive "p")
20875 (if (not (number-at-point))
20876 (user-error "Not on a number")
20877 (unless inc (setq inc 1))
20878 (let ((pos (point))
20879 (beg (skip-chars-backward "-+^/*0-9eE."))
20880 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20881 (setq nap (buffer-substring-no-properties
20882 (+ pos beg) (+ pos beg end)))
20883 (delete-region (+ pos beg) (+ pos beg end))
20884 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20885 (when (org-at-table-p)
20886 (org-table-align)
20887 (org-table-end-of-field 1))))
20889 (defun org-decrease-number-at-point (&optional inc)
20890 "Decrement the number at point.
20891 With an optional prefix numeric argument INC, decrement using
20892 this numeric value."
20893 (interactive "p")
20894 (org-increase-number-at-point (- (or inc 1))))
20896 (defun org-ctrl-c-ret ()
20897 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20898 (interactive)
20899 (cond
20900 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20901 (t (call-interactively 'org-insert-heading))))
20903 (defun org-find-visible ()
20904 (let ((s (point)))
20905 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20906 (get-char-property s 'invisible)))
20908 (defun org-find-invisible ()
20909 (let ((s (point)))
20910 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20911 (not (get-char-property s 'invisible))))
20914 (defun org-copy-visible (beg end)
20915 "Copy the visible parts of the region."
20916 (interactive "r")
20917 (let (snippets s)
20918 (save-excursion
20919 (save-restriction
20920 (narrow-to-region beg end)
20921 (setq s (goto-char (point-min)))
20922 (while (not (= (point) (point-max)))
20923 (goto-char (org-find-invisible))
20924 (push (buffer-substring s (point)) snippets)
20925 (setq s (goto-char (org-find-visible))))))
20926 (kill-new (apply 'concat (nreverse snippets)))))
20928 (defun org-copy-special ()
20929 "Copy region in table or copy current subtree.
20930 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20931 context. See the individual commands for more information."
20932 (interactive)
20933 (call-interactively
20934 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20936 (defun org-cut-special ()
20937 "Cut region in table or cut current subtree.
20938 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20939 context. See the individual commands for more information."
20940 (interactive)
20941 (call-interactively
20942 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20944 (defun org-paste-special (arg)
20945 "Paste rectangular region into table, or past subtree relative to level.
20946 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20947 See the individual commands for more information."
20948 (interactive "P")
20949 (if (org-at-table-p)
20950 (org-table-paste-rectangle)
20951 (org-paste-subtree arg)))
20953 (defun org-edit-special (&optional arg)
20954 "Call a special editor for the element at point.
20955 When at a table, call the formula editor with `org-table-edit-formulas'.
20956 When in a source code block, call `org-edit-src-code'.
20957 When in a fixed-width region, call `org-edit-fixed-width-region'.
20958 When in an export block, call `org-edit-export-block'.
20959 When at an #+INCLUDE keyword, visit the included file.
20960 When at a footnote reference, call `org-edit-footnote-reference'
20961 On a link, call `ffap' to visit the link at point.
20962 Otherwise, return a user error."
20963 (interactive "P")
20964 (let ((element (org-element-at-point)))
20965 (barf-if-buffer-read-only)
20966 (pcase (org-element-type element)
20967 (`src-block
20968 (if (not arg) (org-edit-src-code)
20969 (let* ((info (org-babel-get-src-block-info))
20970 (lang (nth 0 info))
20971 (params (nth 2 info))
20972 (session (cdr (assq :session params))))
20973 (if (not session) (org-edit-src-code)
20974 ;; At a src-block with a session and function called with
20975 ;; an ARG: switch to the buffer related to the inferior
20976 ;; process.
20977 (switch-to-buffer
20978 (funcall (intern (concat "org-babel-prep-session:" lang))
20979 session params))))))
20980 (`keyword
20981 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20982 (org-open-link-from-string
20983 (format "[[%s]]"
20984 (expand-file-name
20985 (let ((value (org-element-property :value element)))
20986 (cond ((not (org-string-nw-p value))
20987 (user-error "No file to edit"))
20988 ((string-match "\\`\"\\(.*?\\)\"" value)
20989 (match-string 1 value))
20990 ((string-match "\\`[^ \t\"]\\S-*" value)
20991 (match-string 0 value))
20992 (t (user-error "No valid file specified")))))))
20993 (user-error "No special environment to edit here")))
20994 (`table
20995 (if (eq (org-element-property :type element) 'table.el)
20996 (org-edit-table.el)
20997 (call-interactively 'org-table-edit-formulas)))
20998 ;; Only Org tables contain `table-row' type elements.
20999 (`table-row (call-interactively 'org-table-edit-formulas))
21000 (`example-block (org-edit-src-code))
21001 (`export-block (org-edit-export-block))
21002 (`fixed-width (org-edit-fixed-width-region))
21004 ;; No notable element at point. Though, we may be at a link or
21005 ;; a footnote reference, which are objects. Thus, scan deeper.
21006 (let ((context (org-element-context element)))
21007 (pcase (org-element-type context)
21008 (`footnote-reference (org-edit-footnote-reference))
21009 (`inline-src-block (org-edit-inline-src-code))
21010 (`link (call-interactively #'ffap))
21011 (_ (user-error "No special environment to edit here"))))))))
21013 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21014 (defun org-ctrl-c-ctrl-c (&optional arg)
21015 "Set tags in headline, or update according to changed information at point.
21017 This command does many different things, depending on context:
21019 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21020 this is what we do.
21022 - If the cursor is on a statistics cookie, update it.
21024 - If the cursor is in a headline, prompt for tags and insert them
21025 into the current line, aligned to `org-tags-column'. When called
21026 with prefix arg, realign all tags in the current buffer.
21028 - If the cursor is in one of the special #+KEYWORD lines, this
21029 triggers scanning the buffer for these lines and updating the
21030 information.
21032 - If the cursor is inside a table, realign the table. This command
21033 works even if the automatic table editor has been turned off.
21035 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21036 the entire table.
21038 - If the cursor is at a footnote reference or definition, jump to
21039 the corresponding definition or references, respectively.
21041 - If the cursor is a the beginning of a dynamic block, update it.
21043 - If the current buffer is a capture buffer, close note and file it.
21045 - If the cursor is on a <<<target>>>, update radio targets and
21046 corresponding links in this buffer.
21048 - If the cursor is on a numbered item in a plain list, renumber the
21049 ordered list.
21051 - If the cursor is on a checkbox, toggle it.
21053 - If the cursor is on a code block, evaluate it. The variable
21054 `org-confirm-babel-evaluate' can be used to control prompting
21055 before code block evaluation, by default every code block
21056 evaluation requires confirmation. Code block evaluation can be
21057 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21058 (interactive "P")
21059 (cond
21060 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
21061 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21062 (org-remove-occur-highlights)
21063 (message "Temporary highlights/overlays removed from current buffer"))
21064 ((and (local-variable-p 'org-finish-function)
21065 (fboundp org-finish-function))
21066 (funcall org-finish-function))
21067 ((org-babel-hash-at-point))
21068 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21070 (let* ((context
21071 (org-element-lineage
21072 (org-element-context)
21073 ;; Limit to supported contexts.
21074 '(babel-call clock dynamic-block footnote-definition
21075 footnote-reference inline-babel-call inline-src-block
21076 inlinetask item keyword node-property paragraph
21077 plain-list property-drawer radio-target src-block
21078 statistics-cookie table table-cell table-row
21079 timestamp)
21081 (type (org-element-type context)))
21082 ;; For convenience: at the first line of a paragraph on the same
21083 ;; line as an item, apply function on that item instead.
21084 (when (eq type 'paragraph)
21085 (let ((parent (org-element-property :parent context)))
21086 (when (and (eq (org-element-type parent) 'item)
21087 (= (line-beginning-position)
21088 (org-element-property :begin parent)))
21089 (setq context parent)
21090 (setq type 'item))))
21091 ;; Act according to type of element or object at point.
21093 ;; Do nothing on a blank line, except if it is contained in
21094 ;; a src block. Hence, we first check if point is in such
21095 ;; a block and then if it is at a blank line.
21096 (pcase type
21097 ((or `inline-src-block `src-block)
21098 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
21099 (org-babel-eval-wipe-error-buffer)
21100 (org-babel-execute-src-block
21101 current-prefix-arg (org-babel-get-src-block-info nil context))))
21102 ((guard (org-match-line "[ \t]*$"))
21103 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21104 (user-error
21105 (substitute-command-keys
21106 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
21107 ((or `babel-call `inline-babel-call)
21108 (let ((info (org-babel-lob-get-info context)))
21109 (when info (org-babel-execute-src-block nil info))))
21110 (`clock (org-clock-update-time-maybe))
21111 (`dynamic-block
21112 (save-excursion
21113 (goto-char (org-element-property :post-affiliated context))
21114 (org-update-dblock)))
21115 (`footnote-definition
21116 (goto-char (org-element-property :post-affiliated context))
21117 (call-interactively 'org-footnote-action))
21118 (`footnote-reference (call-interactively #'org-footnote-action))
21119 ((or `headline `inlinetask)
21120 (save-excursion (goto-char (org-element-property :begin context))
21121 (call-interactively #'org-set-tags)))
21122 (`item
21123 ;; At an item: `C-u C-u' sets checkbox to "[-]"
21124 ;; unconditionally, whereas `C-u' will toggle its presence.
21125 ;; Without a universal argument, if the item has a checkbox,
21126 ;; toggle it. Otherwise repair the list.
21127 (let* ((box (org-element-property :checkbox context))
21128 (struct (org-element-property :structure context))
21129 (old-struct (copy-tree struct))
21130 (parents (org-list-parents-alist struct))
21131 (prevs (org-list-prevs-alist struct))
21132 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21133 (org-list-set-checkbox
21134 (org-element-property :begin context) struct
21135 (cond ((equal arg '(16)) "[-]")
21136 ((and (not box) (equal arg '(4))) "[ ]")
21137 ((or (not box) (equal arg '(4))) nil)
21138 ((eq box 'on) "[ ]")
21139 (t "[X]")))
21140 ;; Mimic `org-list-write-struct' but with grabbing a return
21141 ;; value from `org-list-struct-fix-box'.
21142 (org-list-struct-fix-ind struct parents 2)
21143 (org-list-struct-fix-item-end struct)
21144 (org-list-struct-fix-bul struct prevs)
21145 (org-list-struct-fix-ind struct parents)
21146 (let ((block-item
21147 (org-list-struct-fix-box struct parents prevs orderedp)))
21148 (if (and box (equal struct old-struct))
21149 (if (equal arg '(16))
21150 (message "Checkboxes already reset")
21151 (user-error "Cannot toggle this checkbox: %s"
21152 (if (eq box 'on)
21153 "all subitems checked"
21154 "unchecked subitems")))
21155 (org-list-struct-apply-struct struct old-struct)
21156 (org-update-checkbox-count-maybe))
21157 (when block-item
21158 (message "Checkboxes were removed due to empty box at line %d"
21159 (org-current-line block-item))))))
21160 (`keyword
21161 (let ((org-inhibit-startup-visibility-stuff t)
21162 (org-startup-align-all-tables nil))
21163 (when (boundp 'org-table-coordinate-overlays)
21164 (mapc #'delete-overlay org-table-coordinate-overlays)
21165 (setq org-table-coordinate-overlays nil))
21166 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21167 (message "Local setup has been refreshed"))
21168 (`plain-list
21169 ;; At a plain list, with a double C-u argument, set
21170 ;; checkboxes of each item to "[-]", whereas a single one
21171 ;; will toggle their presence according to the state of the
21172 ;; first item in the list. Without an argument, repair the
21173 ;; list.
21174 (let* ((begin (org-element-property :contents-begin context))
21175 (beginm (move-marker (make-marker) begin))
21176 (struct (org-element-property :structure context))
21177 (old-struct (copy-tree struct))
21178 (first-box (save-excursion
21179 (goto-char begin)
21180 (looking-at org-list-full-item-re)
21181 (match-string-no-properties 3)))
21182 (new-box (cond ((equal arg '(16)) "[-]")
21183 ((equal arg '(4)) (unless first-box "[ ]"))
21184 ((equal first-box "[X]") "[ ]")
21185 (t "[X]"))))
21186 (cond
21187 (arg
21188 (dolist (pos
21189 (org-list-get-all-items
21190 begin struct (org-list-prevs-alist struct)))
21191 (org-list-set-checkbox pos struct new-box)))
21192 ((and first-box (eq (point) begin))
21193 ;; For convenience, when point is at bol on the first
21194 ;; item of the list and no argument is provided, simply
21195 ;; toggle checkbox of that item, if any.
21196 (org-list-set-checkbox begin struct new-box)))
21197 (org-list-write-struct
21198 struct (org-list-parents-alist struct) old-struct)
21199 (org-update-checkbox-count-maybe)
21200 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21201 ((or `property-drawer `node-property)
21202 (call-interactively #'org-property-action))
21203 (`radio-target
21204 (call-interactively #'org-update-radio-target-regexp))
21205 (`statistics-cookie
21206 (call-interactively #'org-update-statistics-cookies))
21207 ((or `table `table-cell `table-row)
21208 ;; At a table, recalculate every field and align it. Also
21209 ;; send the table if necessary. If the table has
21210 ;; a `table.el' type, just give up. At a table row or cell,
21211 ;; maybe recalculate line but always align table.
21212 (if (eq (org-element-property :type context) 'table.el)
21213 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21214 Use `\\[org-edit-special]' to edit table.el tables"))
21215 (let ((org-enable-table-editor t))
21216 (if (or (eq type 'table)
21217 ;; Check if point is at a TBLFM line.
21218 (and (eq type 'table-row)
21219 (= (point) (org-element-property :end context))))
21220 (save-excursion
21221 (if (org-at-TBLFM-p)
21222 (progn (require 'org-table)
21223 (org-table-calc-current-TBLFM))
21224 (goto-char (org-element-property :contents-begin context))
21225 (org-call-with-arg 'org-table-recalculate (or arg t))
21226 (orgtbl-send-table 'maybe)))
21227 (org-table-maybe-eval-formula)
21228 (cond (arg (call-interactively #'org-table-recalculate))
21229 ((org-table-maybe-recalculate-line))
21230 (t (org-table-align)))))))
21231 (`timestamp (org-timestamp-change 0 'day))
21232 ((and `nil (guard (org-at-heading-p)))
21233 ;; When point is on an unsupported object type, we can miss
21234 ;; the fact that it also is at a heading. Handle it here.
21235 (call-interactively #'org-set-tags))
21236 ((guard
21237 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
21239 (user-error
21240 (substitute-command-keys
21241 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
21243 (defun org-mode-restart ()
21244 (interactive)
21245 (let ((indent-status (bound-and-true-p org-indent-mode)))
21246 (funcall major-mode)
21247 (hack-local-variables)
21248 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21249 (org-indent-mode -1)))
21250 (message "%s restarted" major-mode))
21252 (defun org-kill-note-or-show-branches ()
21253 "Abort storing current note, or call `outline-show-branches'."
21254 (interactive)
21255 (if (not org-finish-function)
21256 (progn
21257 (outline-hide-subtree)
21258 (call-interactively 'outline-show-branches))
21259 (let ((org-note-abort t))
21260 (funcall org-finish-function))))
21262 (defun org-delete-indentation (&optional arg)
21263 "Join current line to previous and fix whitespace at join.
21265 If previous line is a headline add to headline title. Otherwise
21266 the function calls `delete-indentation'.
21268 With a non-nil optional argument, join it to the following one."
21269 (interactive "*P")
21270 (if (save-excursion
21271 (beginning-of-line (if arg 1 0))
21272 (let ((case-fold-search nil))
21273 (looking-at org-complex-heading-regexp)))
21274 ;; At headline.
21275 (let ((tags-column (when (match-beginning 5)
21276 (save-excursion (goto-char (match-beginning 5))
21277 (current-column))))
21278 (string (concat " " (progn (when arg (forward-line 1))
21279 (org-trim (delete-and-extract-region
21280 (line-beginning-position)
21281 (line-end-position)))))))
21282 (unless (bobp) (delete-region (point) (1- (point))))
21283 (goto-char (or (match-end 4)
21284 (match-beginning 5)
21285 (match-end 0)))
21286 (skip-chars-backward " \t")
21287 (save-excursion (insert string))
21288 ;; Adjust alignment of tags.
21289 (cond
21290 ((not tags-column)) ;no tags
21291 (org-auto-align-tags (org-set-tags nil t))
21292 (t (org--align-tags-here tags-column)))) ;preserve tags column
21293 (delete-indentation arg)))
21295 (defun org-open-line (n)
21296 "Insert a new row in tables, call `open-line' elsewhere.
21297 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21298 As a special case, when a document starts with a table, allow to
21299 call `open-line' on the very first character."
21300 (interactive "*p")
21301 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21302 (org-table-insert-row)
21303 (open-line n)))
21305 (defun org-return (&optional indent)
21306 "Goto next table row or insert a newline.
21308 Calls `org-table-next-row' or `newline', depending on context.
21310 When optional INDENT argument is non-nil, call
21311 `newline-and-indent' instead of `newline'.
21313 When `org-return-follows-link' is non-nil and point is on
21314 a timestamp or a link, call `org-open-at-point'. However, it
21315 will not happen if point is in a table or on a \"dead\"
21316 object (e.g., within a comment). In these case, you need to use
21317 `org-open-at-point' directly."
21318 (interactive)
21319 (let ((context (if org-return-follows-link (org-element-context)
21320 (org-element-at-point))))
21321 (cond
21322 ;; In a table, call `org-table-next-row'.
21323 ((or (and (eq (org-element-type context) 'table)
21324 (>= (point) (org-element-property :contents-begin context))
21325 (< (point) (org-element-property :contents-end context)))
21326 (org-element-lineage context '(table-row table-cell) t))
21327 (org-table-justify-field-maybe)
21328 (call-interactively #'org-table-next-row))
21329 ;; On a link or a timestamp, call `org-open-at-point' if
21330 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21331 ;; locations, e.g., in a comment, as `org-open-at-point'.
21332 ((and org-return-follows-link
21333 (or (org-in-regexp org-ts-regexp-both nil t)
21334 (org-in-regexp org-tsr-regexp-both nil t)
21335 (org-in-regexp org-any-link-re nil t)))
21336 (call-interactively #'org-open-at-point))
21337 ;; Insert newline in heading, but preserve tags.
21338 ((and (not (bolp))
21339 (save-excursion (beginning-of-line)
21340 (let ((case-fold-search nil))
21341 (looking-at org-complex-heading-regexp))))
21342 ;; At headline. Split line. However, if point is on keyword,
21343 ;; priority cookie or tags, do not break any of them: add
21344 ;; a newline after the headline instead.
21345 (let ((tags-column (and (match-beginning 5)
21346 (save-excursion (goto-char (match-beginning 5))
21347 (current-column))))
21348 (string
21349 (when (and (match-end 4) (org-point-in-group (point) 4))
21350 (delete-and-extract-region (point) (match-end 4)))))
21351 ;; Adjust tag alignment.
21352 (cond
21353 ((not (and tags-column string)))
21354 (org-auto-align-tags (org-set-tags nil t))
21355 (t (org--align-tags-here tags-column))) ;preserve tags column
21356 (end-of-line)
21357 (org-show-entry)
21358 (if indent (newline-and-indent) (newline))
21359 (when string (save-excursion (insert (org-trim string))))))
21360 ;; In a list, make sure indenting keeps trailing text within.
21361 ((and indent
21362 (not (eolp))
21363 (org-element-lineage context '(item)))
21364 (let ((trailing-data
21365 (delete-and-extract-region (point) (line-end-position))))
21366 (newline-and-indent)
21367 (save-excursion (insert trailing-data))))
21368 (t (if indent (newline-and-indent) (newline))))))
21370 (defun org-return-indent ()
21371 "Goto next table row or insert a newline and indent.
21372 Calls `org-table-next-row' or `newline-and-indent', depending on
21373 context. See the individual commands for more information."
21374 (interactive)
21375 (org-return t))
21377 (defun org-ctrl-c-star ()
21378 "Compute table, or change heading status of lines.
21379 Calls `org-table-recalculate' or `org-toggle-heading',
21380 depending on context."
21381 (interactive)
21382 (cond
21383 ((org-at-table-p)
21384 (call-interactively 'org-table-recalculate))
21386 ;; Convert all lines in region to list items
21387 (call-interactively 'org-toggle-heading))))
21389 (defun org-ctrl-c-minus ()
21390 "Insert separator line in table or modify bullet status of line.
21391 Also turns a plain line or a region of lines into list items.
21392 Calls `org-table-insert-hline', `org-toggle-item', or
21393 `org-cycle-list-bullet', depending on context."
21394 (interactive)
21395 (cond
21396 ((org-at-table-p)
21397 (call-interactively 'org-table-insert-hline))
21398 ((org-region-active-p)
21399 (call-interactively 'org-toggle-item))
21400 ((org-in-item-p)
21401 (call-interactively 'org-cycle-list-bullet))
21403 (call-interactively 'org-toggle-item))))
21405 (defun org-toggle-heading (&optional nstars)
21406 "Convert headings to normal text, or items or text to headings.
21407 If there is no active region, only convert the current line.
21409 With a `\\[universal-argument]' prefix, convert the whole list at
21410 point into heading.
21412 In a region:
21414 - If the first non blank line is a headline, remove the stars
21415 from all headlines in the region.
21417 - If it is a normal line, turn each and every normal line (i.e.,
21418 not an heading or an item) in the region into headings. If you
21419 want to convert only the first line of this region, use one
21420 universal prefix argument.
21422 - If it is a plain list item, turn all plain list items into headings.
21424 When converting a line into a heading, the number of stars is chosen
21425 such that the lines become children of the current entry. However,
21426 when a numeric prefix argument is given, its value determines the
21427 number of stars to add."
21428 (interactive "P")
21429 (let ((skip-blanks
21430 (function
21431 ;; Return beginning of first non-blank line, starting from
21432 ;; line at POS.
21433 (lambda (pos)
21434 (save-excursion
21435 (goto-char pos)
21436 (while (org-at-comment-p) (forward-line))
21437 (skip-chars-forward " \r\t\n")
21438 (point-at-bol)))))
21439 beg end toggled)
21440 ;; Determine boundaries of changes. If a universal prefix has
21441 ;; been given, put the list in a region. If region ends at a bol,
21442 ;; do not consider the last line to be in the region.
21444 (when (and current-prefix-arg (org-at-item-p))
21445 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21446 (org-mark-element))
21448 (if (org-region-active-p)
21449 (setq beg (funcall skip-blanks (region-beginning))
21450 end (copy-marker (save-excursion
21451 (goto-char (region-end))
21452 (if (bolp) (point) (point-at-eol)))))
21453 (setq beg (funcall skip-blanks (point-at-bol))
21454 end (copy-marker (point-at-eol))))
21455 ;; Ensure inline tasks don't count as headings.
21456 (org-with-limited-levels
21457 (save-excursion
21458 (goto-char beg)
21459 (cond
21460 ;; Case 1. Started at an heading: de-star headings.
21461 ((org-at-heading-p)
21462 (while (< (point) end)
21463 (when (org-at-heading-p t)
21464 (looking-at org-outline-regexp) (replace-match "")
21465 (setq toggled t))
21466 (forward-line)))
21467 ;; Case 2. Started at an item: change items into headlines.
21468 ;; One star will be added by `org-list-to-subtree'.
21469 ((org-at-item-p)
21470 (while (< (point) end)
21471 (when (org-at-item-p)
21472 ;; Pay attention to cases when region ends before list.
21473 (let* ((struct (org-list-struct))
21474 (list-end
21475 (min (org-list-get-bottom-point struct) (1+ end))))
21476 (save-restriction
21477 (narrow-to-region (point) list-end)
21478 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21479 (setq toggled t))
21480 (forward-line)))
21481 ;; Case 3. Started at normal text: make every line an heading,
21482 ;; skipping headlines and items.
21483 (t (let* ((stars
21484 (make-string
21485 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21486 (add-stars
21487 (cond (nstars "") ; stars from prefix only
21488 ((equal stars "") "*") ; before first heading
21489 (org-odd-levels-only "**") ; inside heading, odd
21490 (t "*"))) ; inside heading, oddeven
21491 (rpl (concat stars add-stars " "))
21492 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21493 (while (< (point) (if (equal nstars '(4)) lend end))
21494 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21495 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21496 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21497 (forward-line)))))))
21498 (unless toggled (message "Cannot toggle heading from here"))))
21500 (defun org-meta-return (&optional _arg)
21501 "Insert a new heading or wrap a region in a table.
21502 Calls `org-insert-heading' or `org-table-wrap-region', depending
21503 on context. See the individual commands for more information."
21504 (interactive)
21505 (org-check-before-invisible-edit 'insert)
21506 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21507 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21508 #'org-insert-heading))))
21510 ;;; Menu entries
21512 (defsubst org-in-subtree-not-table-p ()
21513 "Are we in a subtree and not in a table?"
21514 (and (not (org-before-first-heading-p))
21515 (not (org-at-table-p))))
21517 ;; Define the Org mode menus
21518 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21519 '("Tbl"
21520 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21521 ["Next Field" org-cycle (org-at-table-p)]
21522 ["Previous Field" org-shifttab (org-at-table-p)]
21523 ["Next Row" org-return (org-at-table-p)]
21524 "--"
21525 ["Blank Field" org-table-blank-field (org-at-table-p)]
21526 ["Edit Field" org-table-edit-field (org-at-table-p)]
21527 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21528 "--"
21529 ("Column"
21530 ["Move Column Left" org-metaleft (org-at-table-p)]
21531 ["Move Column Right" org-metaright (org-at-table-p)]
21532 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21533 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21534 ("Row"
21535 ["Move Row Up" org-metaup (org-at-table-p)]
21536 ["Move Row Down" org-metadown (org-at-table-p)]
21537 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21538 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21539 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21540 "--"
21541 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21542 ("Rectangle"
21543 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21544 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21545 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21546 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21547 "--"
21548 ("Calculate"
21549 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21550 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21551 ["Edit Formulas" org-edit-special (org-at-table-p)]
21552 "--"
21553 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21554 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21555 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21556 "--"
21557 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21558 "--"
21559 ["Sum Column/Rectangle" org-table-sum
21560 (or (org-at-table-p) (org-region-active-p))]
21561 ["Which Column?" org-table-current-column (org-at-table-p)])
21562 ["Debug Formulas"
21563 org-table-toggle-formula-debugger
21564 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21565 ["Show Col/Row Numbers"
21566 org-table-toggle-coordinate-overlays
21567 :style toggle
21568 :selected (bound-and-true-p org-table-overlay-coordinates)]
21569 "--"
21570 ["Create" org-table-create (and (not (org-at-table-p))
21571 org-enable-table-editor)]
21572 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21573 ["Import from File" org-table-import (not (org-at-table-p))]
21574 ["Export to File" org-table-export (org-at-table-p)]
21575 "--"
21576 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21577 "--"
21578 ("Plot"
21579 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21580 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21582 (easy-menu-define org-org-menu org-mode-map "Org menu"
21583 '("Org"
21584 ("Show/Hide"
21585 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21586 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21587 ["Sparse Tree..." org-sparse-tree t]
21588 ["Reveal Context" org-reveal t]
21589 ["Show All" outline-show-all t]
21590 "--"
21591 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21592 "--"
21593 ["New Heading" org-insert-heading t]
21594 ("Navigate Headings"
21595 ["Up" outline-up-heading t]
21596 ["Next" outline-next-visible-heading t]
21597 ["Previous" outline-previous-visible-heading t]
21598 ["Next Same Level" outline-forward-same-level t]
21599 ["Previous Same Level" outline-backward-same-level t]
21600 "--"
21601 ["Jump" org-goto t])
21602 ("Edit Structure"
21603 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21604 "--"
21605 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21606 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21607 "--"
21608 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21609 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21610 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21611 "--"
21612 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21613 "--"
21614 ["Copy visible text" org-copy-visible t]
21615 "--"
21616 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21617 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21618 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21619 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21620 "--"
21621 ["Sort Region/Children" org-sort t]
21622 "--"
21623 ["Convert to odd levels" org-convert-to-odd-levels t]
21624 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21625 ("Editing"
21626 ["Emphasis..." org-emphasize t]
21627 ["Edit Source Example" org-edit-special t]
21628 "--"
21629 ["Footnote new/jump" org-footnote-action t]
21630 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21631 ("Archive"
21632 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21633 "--"
21634 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21635 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21636 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21638 "--"
21639 ("Hyperlinks"
21640 ["Store Link (Global)" org-store-link t]
21641 ["Find existing link to here" org-occur-link-in-agenda-files t]
21642 ["Insert Link" org-insert-link t]
21643 ["Follow Link" org-open-at-point t]
21644 "--"
21645 ["Next link" org-next-link t]
21646 ["Previous link" org-previous-link t]
21647 "--"
21648 ["Descriptive Links"
21649 org-toggle-link-display
21650 :style radio
21651 :selected org-descriptive-links
21653 ["Literal Links"
21654 org-toggle-link-display
21655 :style radio
21656 :selected (not org-descriptive-links)])
21657 "--"
21658 ("TODO Lists"
21659 ["TODO/DONE/-" org-todo t]
21660 ("Select keyword"
21661 ["Next keyword" org-shiftright (org-at-heading-p)]
21662 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21663 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21664 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21665 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21666 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21667 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21668 "--"
21669 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21670 :selected org-enforce-todo-dependencies :style toggle :active t]
21671 "Settings for tree at point"
21672 ["Do Children sequentially" org-toggle-ordered-property :style radio
21673 :selected (org-entry-get nil "ORDERED")
21674 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21675 ["Do Children parallel" org-toggle-ordered-property :style radio
21676 :selected (not (org-entry-get nil "ORDERED"))
21677 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21678 "--"
21679 ["Set Priority" org-priority t]
21680 ["Priority Up" org-shiftup t]
21681 ["Priority Down" org-shiftdown t]
21682 "--"
21683 ["Get news from all feeds" org-feed-update-all t]
21684 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21685 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21686 ("TAGS and Properties"
21687 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21688 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21689 "--"
21690 ["Set property" org-set-property (not (org-before-first-heading-p))]
21691 ["Column view of properties" org-columns t]
21692 ["Insert Column View DBlock" org-columns-insert-dblock t])
21693 ("Dates and Scheduling"
21694 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21695 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21696 ("Change Date"
21697 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21698 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21699 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21700 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21701 ["Compute Time Range" org-evaluate-time-range t]
21702 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21703 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21704 "--"
21705 ["Custom time format" org-toggle-time-stamp-overlays
21706 :style radio :selected org-display-custom-times]
21707 "--"
21708 ["Goto Calendar" org-goto-calendar t]
21709 ["Date from Calendar" org-date-from-calendar t]
21710 "--"
21711 ["Start/Restart Timer" org-timer-start t]
21712 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21713 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21714 ["Insert Timer String" org-timer t]
21715 ["Insert Timer Item" org-timer-item t])
21716 ("Logging work"
21717 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21718 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21719 ["Clock out" org-clock-out t]
21720 ["Clock cancel" org-clock-cancel t]
21721 "--"
21722 ["Mark as default task" org-clock-mark-default-task t]
21723 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21724 ["Goto running clock" org-clock-goto t]
21725 "--"
21726 ["Display times" org-clock-display t]
21727 ["Create clock table" org-clock-report t]
21728 "--"
21729 ["Record DONE time"
21730 (progn (setq org-log-done (not org-log-done))
21731 (message "Switching to %s will %s record a timestamp"
21732 (car org-done-keywords)
21733 (if org-log-done "automatically" "not")))
21734 :style toggle :selected org-log-done])
21735 "--"
21736 ["Agenda Command..." org-agenda t]
21737 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21738 ("File List for Agenda")
21739 ("Special views current file"
21740 ["TODO Tree" org-show-todo-tree t]
21741 ["Check Deadlines" org-check-deadlines t]
21742 ["Timeline" org-timeline t]
21743 ["Tags/Property tree" org-match-sparse-tree t])
21744 "--"
21745 ["Export/Publish..." org-export-dispatch t]
21746 ("LaTeX"
21747 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21748 :selected org-cdlatex-mode]
21749 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21750 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21751 ["Modify math symbol" org-cdlatex-math-modify
21752 (org-inside-LaTeX-fragment-p)]
21753 ["Insert citation" org-reftex-citation t])
21754 "--"
21755 ("MobileOrg"
21756 ["Push Files and Views" org-mobile-push t]
21757 ["Get Captured and Flagged" org-mobile-pull t]
21758 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21759 "--"
21760 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21761 "--"
21762 ("Documentation"
21763 ["Show Version" org-version t]
21764 ["Info Documentation" org-info t])
21765 ("Customize"
21766 ["Browse Org Group" org-customize t]
21767 "--"
21768 ["Expand This Menu" org-create-customize-menu
21769 (fboundp 'customize-menu-create)])
21770 ["Send bug report" org-submit-bug-report t]
21771 "--"
21772 ("Refresh/Reload"
21773 ["Refresh setup current buffer" org-mode-restart t]
21774 ["Reload Org (after update)" org-reload t]
21775 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21778 (defun org-info (&optional node)
21779 "Read documentation for Org in the info system.
21780 With optional NODE, go directly to that node."
21781 (interactive)
21782 (info (format "(org)%s" (or node ""))))
21784 ;;;###autoload
21785 (defun org-submit-bug-report ()
21786 "Submit a bug report on Org via mail.
21788 Don't hesitate to report any problems or inaccurate documentation.
21790 If you don't have setup sending mail from (X)Emacs, please copy the
21791 output buffer into your mail program, as it gives us important
21792 information about your Org version and configuration."
21793 (interactive)
21794 (require 'reporter)
21795 (defvar reporter-prompt-for-summary-p)
21796 (org-load-modules-maybe)
21797 (org-require-autoloaded-modules)
21798 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21799 (reporter-submit-bug-report
21800 "emacs-orgmode@gnu.org"
21801 (org-version nil 'full)
21802 (let (list)
21803 (save-window-excursion
21804 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21805 (delete-other-windows)
21806 (erase-buffer)
21807 (insert "You are about to submit a bug report to the Org mailing list.
21809 We would like to add your full Org and Outline configuration to the
21810 bug report. This greatly simplifies the work of the maintainer and
21811 other experts on the mailing list.
21813 HOWEVER, some variables you have customized may contain private
21814 information. The names of customers, colleagues, or friends, might
21815 appear in the form of file names, tags, todo states, or search strings.
21816 If you answer yes to the prompt, you might want to check and remove
21817 such private information before sending the email.")
21818 (add-text-properties (point-min) (point-max) '(face org-warning))
21819 (when (yes-or-no-p "Include your Org configuration ")
21820 (mapatoms
21821 (lambda (v)
21822 (and (boundp v)
21823 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21824 (or (and (symbol-value v)
21825 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21826 (and
21827 (get v 'custom-type) (get v 'standard-value)
21828 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21829 (push v list)))))
21830 (kill-buffer (get-buffer "*Warn about privacy*"))
21831 list))
21832 nil nil
21833 "Remember to cover the basics, that is, what you expected to happen and
21834 what in fact did happen. You don't know how to make a good report? See
21836 http://orgmode.org/manual/Feedback.html#Feedback
21838 Your bug report will be posted to the Org mailing list.
21839 ------------------------------------------------------------------------")
21840 (save-excursion
21841 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21842 (replace-match "\\1Bug: \\3 [\\2]")))))
21845 (defun org-install-agenda-files-menu ()
21846 (let ((bl (buffer-list)))
21847 (save-excursion
21848 (while bl
21849 (set-buffer (pop bl))
21850 (when (derived-mode-p 'org-mode) (setq bl nil)))
21851 (when (derived-mode-p 'org-mode)
21852 (easy-menu-change
21853 '("Org") "File List for Agenda"
21854 (append
21855 (list
21856 ["Edit File List" (org-edit-agenda-file-list) t]
21857 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21858 ["Remove Current File from List" org-remove-file t]
21859 ["Cycle through agenda files" org-cycle-agenda-files t]
21860 ["Occur in all agenda files" org-occur-in-agenda-files t]
21861 "--")
21862 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21864 ;;;; Documentation
21866 (defun org-require-autoloaded-modules ()
21867 (interactive)
21868 (mapc #'require
21869 '(org-agenda org-archive org-attach org-clock org-colview org-id
21870 org-table org-timer)))
21872 ;;;###autoload
21873 (defun org-reload (&optional uncompiled)
21874 "Reload all org lisp files.
21875 With prefix arg UNCOMPILED, load the uncompiled versions."
21876 (interactive "P")
21877 (require 'loadhist)
21878 (let* ((org-dir (org-find-library-dir "org"))
21879 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21880 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21881 (remove-re (format "\\`%s\\'"
21882 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21883 (feats (delete-dups
21884 (mapcar 'file-name-sans-extension
21885 (mapcar 'file-name-nondirectory
21886 (delq nil
21887 (mapcar 'feature-file
21888 features))))))
21889 (lfeat (append
21890 (sort
21891 (setq feats
21892 (delq nil (mapcar
21893 (lambda (f)
21894 (if (and (string-match feature-re f)
21895 (not (string-match remove-re f)))
21896 f nil))
21897 feats)))
21898 'string-lessp)
21899 (list "org-version" "org")))
21900 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21901 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21902 load-uncore load-misses)
21903 (setq load-misses
21904 (delq 't
21905 (mapcar (lambda (f)
21906 (or (org-load-noerror-mustsuffix (concat org-dir f))
21907 (and (string= org-dir contrib-dir)
21908 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21909 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21910 (add-to-list 'load-uncore f 'append)
21913 lfeat)))
21914 (when load-uncore
21915 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21916 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21917 (if load-misses
21918 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21919 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21920 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21922 ;;;###autoload
21923 (defun org-customize ()
21924 "Call the customize function with org as argument."
21925 (interactive)
21926 (org-load-modules-maybe)
21927 (org-require-autoloaded-modules)
21928 (customize-browse 'org))
21930 (defun org-create-customize-menu ()
21931 "Create a full customization menu for Org mode, insert it into the menu."
21932 (interactive)
21933 (org-load-modules-maybe)
21934 (org-require-autoloaded-modules)
21935 (if (fboundp 'customize-menu-create)
21936 (progn
21937 (easy-menu-change
21938 '("Org") "Customize"
21939 `(["Browse Org group" org-customize t]
21940 "--"
21941 ,(customize-menu-create 'org)
21942 ["Set" Custom-set t]
21943 ["Save" Custom-save t]
21944 ["Reset to Current" Custom-reset-current t]
21945 ["Reset to Saved" Custom-reset-saved t]
21946 ["Reset to Standard Settings" Custom-reset-standard t]))
21947 (message "\"Org\"-menu now contains full customization menu"))
21948 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21950 ;;;; Miscellaneous stuff
21952 ;;; Generally useful functions
21954 (defun org-get-at-eol (property n)
21955 "Get text property PROPERTY at the end of line less N characters."
21956 (get-text-property (- (point-at-eol) n) property))
21958 (defun org-find-text-property-in-string (prop s)
21959 "Return the first non-nil value of property PROP in string S."
21960 (or (get-text-property 0 prop s)
21961 (get-text-property (or (next-single-property-change 0 prop s) 0)
21962 prop s)))
21964 (defun org-display-warning (message)
21965 "Display the given MESSAGE as a warning."
21966 (display-warning 'org message :warning))
21968 (defun org-eval (form)
21969 "Eval FORM and return result."
21970 (condition-case error
21971 (eval form)
21972 (error (format "%%![Error: %s]" error))))
21974 (defun org-in-clocktable-p ()
21975 "Check if the cursor is in a clocktable."
21976 (let ((pos (point)) start)
21977 (save-excursion
21978 (end-of-line 1)
21979 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21980 (setq start (match-beginning 0))
21981 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21982 (>= (match-end 0) pos)
21983 start))))
21985 (defun org-in-verbatim-emphasis ()
21986 (save-match-data
21987 (and (org-in-regexp org-emph-re 2)
21988 (>= (point) (match-beginning 3))
21989 (<= (point) (match-end 4))
21990 (member (match-string 3) '("=" "~")))))
21992 (defun org-overlay-display (ovl text &optional face evap)
21993 "Make overlay OVL display TEXT with face FACE."
21994 (overlay-put ovl 'display text)
21995 (if face (overlay-put ovl 'face face))
21996 (if evap (overlay-put ovl 'evaporate t)))
21998 (defun org-overlay-before-string (ovl text &optional face evap)
21999 "Make overlay OVL display TEXT with face FACE."
22000 (if face (org-add-props text nil 'face face))
22001 (overlay-put ovl 'before-string text)
22002 (if evap (overlay-put ovl 'evaporate t)))
22004 (defun org-find-overlays (prop &optional pos delete)
22005 "Find all overlays specifying PROP at POS or point.
22006 If DELETE is non-nil, delete all those overlays."
22007 (let (found)
22008 (dolist (ov (overlays-at (or pos (point))) found)
22009 (cond ((not (overlay-get ov prop)))
22010 (delete (delete-overlay ov))
22011 (t (push ov found))))))
22013 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22014 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22015 (if (and marker (marker-buffer marker)
22016 (buffer-live-p (marker-buffer marker)))
22017 (progn
22018 (pop-to-buffer-same-window (marker-buffer marker))
22019 (when (or (> marker (point-max)) (< marker (point-min)))
22020 (widen))
22021 (goto-char marker)
22022 (org-show-context 'org-goto))
22023 (if bookmark
22024 (bookmark-jump bookmark)
22025 (error "Cannot find location"))))
22027 (defun org-quote-csv-field (s)
22028 "Quote field for inclusion in CSV material."
22029 (if (string-match "[\",]" s)
22030 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22033 (defun org-force-self-insert (N)
22034 "Needed to enforce self-insert under remapping."
22035 (interactive "p")
22036 (self-insert-command N))
22038 (defun org-string-width (s)
22039 "Compute width of string, ignoring invisible characters.
22040 This ignores character with invisibility property `org-link', and also
22041 characters with property `org-cwidth', because these will become invisible
22042 upon the next fontification round."
22043 (let (b l)
22044 (when (or (eq t buffer-invisibility-spec)
22045 (assq 'org-link buffer-invisibility-spec))
22046 (while (setq b (text-property-any 0 (length s)
22047 'invisible 'org-link s))
22048 (setq s (concat (substring s 0 b)
22049 (substring s (or (next-single-property-change
22050 b 'invisible s)
22051 (length s)))))))
22052 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22053 (setq s (concat (substring s 0 b)
22054 (substring s (or (next-single-property-change
22055 b 'org-cwidth s)
22056 (length s))))))
22057 (setq l (string-width s) b -1)
22058 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22059 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22062 (defun org-shorten-string (s maxlength)
22063 "Shorten string S so that it is no longer than MAXLENGTH characters.
22064 If the string is shorter or has length MAXLENGTH, just return the
22065 original string. If it is longer, the functions finds a space in the
22066 string, breaks this string off at that locations and adds three dots
22067 as ellipsis. Including the ellipsis, the string will not be longer
22068 than MAXLENGTH. If finding a good breaking point in the string does
22069 not work, the string is just chopped off in the middle of a word
22070 if necessary."
22071 (if (<= (length s) maxlength)
22073 (let* ((n (max (- maxlength 4) 1))
22074 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22075 (if (string-match re s)
22076 (concat (match-string 1 s) "...")
22077 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22079 (defun org-get-indentation (&optional line)
22080 "Get the indentation of the current line, interpreting tabs.
22081 When LINE is given, assume it represents a line and compute its indentation."
22082 (if line
22083 (when (string-match "^ *" (org-remove-tabs line))
22084 (match-end 0))
22085 (save-excursion
22086 (beginning-of-line 1)
22087 (skip-chars-forward " \t")
22088 (current-column))))
22090 (defun org-get-string-indentation (s)
22091 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22092 (let ((n -1) (i 0) (w tab-width) c)
22093 (catch 'exit
22094 (while (< (setq n (1+ n)) (length s))
22095 (setq c (aref s n))
22096 (cond ((= c ?\ ) (setq i (1+ i)))
22097 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22098 (t (throw 'exit t)))))
22101 (defun org-remove-tabs (s &optional width)
22102 "Replace tabulators in S with spaces.
22103 Assumes that s is a single line, starting in column 0."
22104 (setq width (or width tab-width))
22105 (while (string-match "\t" s)
22106 (setq s (replace-match
22107 (make-string
22108 (- (* width (/ (+ (match-beginning 0) width) width))
22109 (match-beginning 0)) ?\ )
22110 t t s)))
22113 (defun org-fix-indentation (line ind)
22114 "Fix indentation in LINE.
22115 IND is a cons cell with target and minimum indentation.
22116 If the current indentation in LINE is smaller than the minimum,
22117 leave it alone. If it is larger than ind, set it to the target."
22118 (let* ((l (org-remove-tabs line))
22119 (i (org-get-indentation l))
22120 (i1 (car ind)) (i2 (cdr ind)))
22121 (when (>= i i2) (setq l (substring line i2)))
22122 (if (> i1 0)
22123 (concat (make-string i1 ?\ ) l)
22124 l)))
22126 (defun org-remove-indentation (code &optional n)
22127 "Remove maximum common indentation in string CODE and return it.
22128 N may optionally be the number of columns to remove. Return CODE
22129 as-is if removal failed."
22130 (with-temp-buffer
22131 (insert code)
22132 (if (org-do-remove-indentation n) (buffer-string) code)))
22134 (defun org-do-remove-indentation (&optional n)
22135 "Remove the maximum common indentation from the buffer.
22136 When optional argument N is a positive integer, remove exactly
22137 that much characters from indentation, if possible. Return nil
22138 if it fails."
22139 (catch :exit
22140 (goto-char (point-min))
22141 ;; Find maximum common indentation, if not specified.
22142 (let ((n (or n
22143 (let ((min-ind (point-max)))
22144 (save-excursion
22145 (while (re-search-forward "^[ \t]*\\S-" nil t)
22146 (let ((ind (1- (current-column))))
22147 (if (zerop ind) (throw :exit nil)
22148 (setq min-ind (min min-ind ind))))))
22149 min-ind))))
22150 (if (zerop n) (throw :exit nil)
22151 ;; Remove exactly N indentation, but give up if not possible.
22152 (while (not (eobp))
22153 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22154 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22155 ((< ind n) (throw :exit nil))
22156 (t (indent-line-to (- ind n))))
22157 (forward-line)))
22158 ;; Signal success.
22159 t))))
22161 (defun org-fill-template (template alist)
22162 "Find each %key of ALIST in TEMPLATE and replace it."
22163 (let ((case-fold-search nil))
22164 (dolist (entry (sort (copy-sequence alist)
22165 (lambda (a b) (< (length (car a)) (length (car b))))))
22166 (setq template
22167 (replace-regexp-in-string
22168 (concat "%" (regexp-quote (car entry)))
22169 (or (cdr entry) "") template t t)))
22170 template))
22172 (defun org-base-buffer (buffer)
22173 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22174 (if (not buffer)
22175 buffer
22176 (or (buffer-base-buffer buffer)
22177 buffer)))
22179 (defun org-wrap (string &optional width lines)
22180 "Wrap string to either a number of lines, or a width in characters.
22181 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22182 that costs. If there is a word longer than WIDTH, the text is actually
22183 wrapped to the length of that word.
22184 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22185 many lines, whatever width that takes.
22186 The return value is a list of lines, without newlines at the end."
22187 (let* ((words (org-split-string string "[ \t\n]+"))
22188 (maxword (apply 'max (mapcar 'org-string-width words)))
22189 w ll)
22190 (cond (width
22191 (org-do-wrap words (max maxword width)))
22192 (lines
22193 (setq w maxword)
22194 (setq ll (org-do-wrap words maxword))
22195 (if (<= (length ll) lines)
22197 (setq ll words)
22198 (while (> (length ll) lines)
22199 (setq w (1+ w))
22200 (setq ll (org-do-wrap words w)))
22201 ll))
22202 (t (error "Cannot wrap this")))))
22204 (defun org-do-wrap (words width)
22205 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22206 (let (lines line)
22207 (while words
22208 (setq line (pop words))
22209 (while (and words (< (+ (length line) (length (car words))) width))
22210 (setq line (concat line " " (pop words))))
22211 (setq lines (push line lines)))
22212 (nreverse lines)))
22214 (defun org-split-string (string &optional separators)
22215 "Splits STRING into substrings at SEPARATORS.
22216 SEPARATORS is a regular expression.
22217 No empty strings are returned if there are matches at the beginning
22218 and end of string."
22219 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22220 (let ((start 0) notfirst list)
22221 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22222 (if (and notfirst
22223 (= start (match-beginning 0))
22224 (< start (length string)))
22225 (1+ start) start))
22226 (< (match-beginning 0) (length string)))
22227 (setq notfirst t)
22228 (or (eq (match-beginning 0) 0)
22229 (and (eq (match-beginning 0) (match-end 0))
22230 (eq (match-beginning 0) start))
22231 (push (substring string start (match-beginning 0)) list))
22232 (setq start (match-end 0)))
22233 (or (eq start (length string))
22234 (push (substring string start) list))
22235 (nreverse list)))
22237 (defun org-quote-vert (s)
22238 "Replace \"|\" with \"\\vert\"."
22239 (while (string-match "|" s)
22240 (setq s (replace-match "\\vert" t t s)))
22243 (defun org-uuidgen-p (s)
22244 "Is S an ID created by UUIDGEN?"
22245 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22247 (defun org-in-src-block-p (&optional inside)
22248 "Whether point is in a code source block.
22249 When INSIDE is non-nil, don't consider we are within a src block
22250 when point is at #+BEGIN_SRC or #+END_SRC."
22251 (let ((case-fold-search t))
22252 (or (and (eq (get-char-property (point) 'src-block) t))
22253 (and (not inside)
22254 (save-match-data
22255 (save-excursion
22256 (beginning-of-line)
22257 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22259 (defun org-context ()
22260 "Return a list of contexts of the current cursor position.
22261 If several contexts apply, all are returned.
22262 Each context entry is a list with a symbol naming the context, and
22263 two positions indicating start and end of the context. Possible
22264 contexts are:
22266 :headline anywhere in a headline
22267 :headline-stars on the leading stars in a headline
22268 :todo-keyword on a TODO keyword (including DONE) in a headline
22269 :tags on the TAGS in a headline
22270 :priority on the priority cookie in a headline
22271 :item on the first line of a plain list item
22272 :item-bullet on the bullet/number of a plain list item
22273 :checkbox on the checkbox in a plain list item
22274 :table in an Org table
22275 :table-special on a special filed in a table
22276 :table-table in a table.el table
22277 :clocktable in a clocktable
22278 :src-block in a source block
22279 :link on a hyperlink
22280 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22281 :target on a <<target>>
22282 :radio-target on a <<<radio-target>>>
22283 :latex-fragment on a LaTeX fragment
22284 :latex-preview on a LaTeX fragment with overlaid preview image
22286 This function expects the position to be visible because it uses font-lock
22287 faces as a help to recognize the following contexts: :table-special, :link,
22288 and :keyword."
22289 (let* ((f (get-text-property (point) 'face))
22290 (faces (if (listp f) f (list f)))
22291 (case-fold-search t)
22292 (p (point)) clist o)
22293 ;; First the large context
22294 (cond
22295 ((org-at-heading-p t)
22296 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22297 (when (progn
22298 (beginning-of-line 1)
22299 (looking-at org-todo-line-tags-regexp))
22300 (push (org-point-in-group p 1 :headline-stars) clist)
22301 (push (org-point-in-group p 2 :todo-keyword) clist)
22302 (push (org-point-in-group p 4 :tags) clist))
22303 (goto-char p)
22304 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22305 (when (looking-at "\\[#[A-Z0-9]\\]")
22306 (push (org-point-in-group p 0 :priority) clist)))
22308 ((org-at-item-p)
22309 (push (org-point-in-group p 2 :item-bullet) clist)
22310 (push (list :item (point-at-bol)
22311 (save-excursion (org-end-of-item) (point)))
22312 clist)
22313 (and (org-at-item-checkbox-p)
22314 (push (org-point-in-group p 0 :checkbox) clist)))
22316 ((org-at-table-p)
22317 (push (list :table (org-table-begin) (org-table-end)) clist)
22318 (when (memq 'org-formula faces)
22319 (push (list :table-special
22320 (previous-single-property-change p 'face)
22321 (next-single-property-change p 'face)) clist)))
22322 ((org-at-table-p 'any)
22323 (push (list :table-table) clist)))
22324 (goto-char p)
22326 (let ((case-fold-search t))
22327 ;; New the "medium" contexts: clocktables, source blocks
22328 (cond ((org-in-clocktable-p)
22329 (push (list :clocktable
22330 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22331 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22332 (match-beginning 1))
22333 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22334 (match-end 0))) clist))
22335 ((org-in-src-block-p)
22336 (push (list :src-block
22337 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22338 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22339 (match-beginning 1))
22340 (and (search-forward "#+END_SRC" nil t)
22341 (match-beginning 0))) clist))))
22342 (goto-char p)
22344 ;; Now the small context
22345 (cond
22346 ((org-at-timestamp-p)
22347 (push (org-point-in-group p 0 :timestamp) clist))
22348 ((memq 'org-link faces)
22349 (push (list :link
22350 (previous-single-property-change p 'face)
22351 (next-single-property-change p 'face)) clist))
22352 ((memq 'org-special-keyword faces)
22353 (push (list :keyword
22354 (previous-single-property-change p 'face)
22355 (next-single-property-change p 'face)) clist))
22356 ((org-at-target-p)
22357 (push (org-point-in-group p 0 :target) clist)
22358 (goto-char (1- (match-beginning 0)))
22359 (when (looking-at org-radio-target-regexp)
22360 (push (org-point-in-group p 0 :radio-target) clist))
22361 (goto-char p))
22362 ((setq o (cl-some
22363 (lambda (o)
22364 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22366 (overlays-at (point))))
22367 (push (list :latex-fragment
22368 (overlay-start o) (overlay-end o)) clist)
22369 (push (list :latex-preview
22370 (overlay-start o) (overlay-end o)) clist))
22371 ((org-inside-LaTeX-fragment-p)
22372 ;; FIXME: positions wrong.
22373 (push (list :latex-fragment (point) (point)) clist)))
22375 (setq clist (nreverse (delq nil clist)))
22376 clist))
22378 (defun org-in-regexp (regexp &optional nlines visually)
22379 "Check if point is inside a match of REGEXP.
22381 Normally only the current line is checked, but you can include
22382 NLINES extra lines around point into the search. If VISUALLY is
22383 set, require that the cursor is not after the match but really
22384 on, so that the block visually is on the match.
22386 Return nil or a cons cell (BEG . END) where BEG and END are,
22387 respectively, the positions at the beginning and the end of the
22388 match."
22389 (catch :exit
22390 (let ((pos (point))
22391 (eol (line-end-position (if nlines (1+ nlines) 1))))
22392 (save-excursion
22393 (beginning-of-line (- 1 (or nlines 0)))
22394 (while (and (re-search-forward regexp eol t)
22395 (<= (match-beginning 0) pos))
22396 (let ((end (match-end 0)))
22397 (when (or (> end pos) (and (= end pos) (not visually)))
22398 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22400 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22401 "Non-nil when point is between matches of START-RE and END-RE.
22403 Also return a non-nil value when point is on one of the matches.
22405 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22406 buffer positions. Default values are the positions of headlines
22407 surrounding the point.
22409 The functions returns a cons cell whose car (resp. cdr) is the
22410 position before START-RE (resp. after END-RE)."
22411 (save-match-data
22412 (let ((pos (point))
22413 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22414 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22415 beg end)
22416 (save-excursion
22417 ;; Point is on a block when on START-RE or if START-RE can be
22418 ;; found before it...
22419 (and (or (org-in-regexp start-re)
22420 (re-search-backward start-re limit-up t))
22421 (setq beg (match-beginning 0))
22422 ;; ... and END-RE after it...
22423 (goto-char (match-end 0))
22424 (re-search-forward end-re limit-down t)
22425 (> (setq end (match-end 0)) pos)
22426 ;; ... without another START-RE in-between.
22427 (goto-char (match-beginning 0))
22428 (not (re-search-backward start-re (1+ beg) t))
22429 ;; Return value.
22430 (cons beg end))))))
22432 (defun org-in-block-p (names)
22433 "Non-nil when point belongs to a block whose name belongs to NAMES.
22435 NAMES is a list of strings containing names of blocks.
22437 Return first block name matched, or nil. Beware that in case of
22438 nested blocks, the returned name may not belong to the closest
22439 block from point."
22440 (save-match-data
22441 (catch 'exit
22442 (let ((case-fold-search t)
22443 (lim-up (save-excursion (outline-previous-heading)))
22444 (lim-down (save-excursion (outline-next-heading))))
22445 (dolist (name names)
22446 (let ((n (regexp-quote name)))
22447 (when (org-between-regexps-p
22448 (concat "^[ \t]*#\\+begin_" n)
22449 (concat "^[ \t]*#\\+end_" n)
22450 lim-up lim-down)
22451 (throw 'exit n)))))
22452 nil)))
22454 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22455 "Call `multi-occur' with buffers for all agenda files."
22456 (interactive "sOrg-files matching: ")
22457 (let* ((files (org-agenda-files))
22458 (tnames (mapcar #'file-truename files))
22459 (extra org-agenda-text-search-extra-files))
22460 (when (eq (car extra) 'agenda-archives)
22461 (setq extra (cdr extra))
22462 (setq files (org-add-archive-files files)))
22463 (dolist (f extra)
22464 (unless (member (file-truename f) tnames)
22465 (unless (member f files) (setq files (append files (list f))))
22466 (setq tnames (append tnames (list (file-truename f))))))
22467 (multi-occur
22468 (mapcar (lambda (x)
22469 (with-current-buffer
22470 ;; FIXME: Why not just (find-file-noselect x)?
22471 ;; Is it to avoid the "revert buffer" prompt?
22472 (or (get-file-buffer x) (find-file-noselect x))
22473 (widen)
22474 (current-buffer)))
22475 files)
22476 regexp)))
22478 (add-hook 'occur-mode-find-occurrence-hook
22479 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22481 (defun org-occur-link-in-agenda-files ()
22482 "Create a link and search for it in the agendas.
22483 The link is not stored in `org-stored-links', it is just created
22484 for the search purpose."
22485 (interactive)
22486 (let ((link (condition-case nil
22487 (org-store-link nil)
22488 (error "Unable to create a link to here"))))
22489 (org-occur-in-agenda-files (regexp-quote link))))
22491 (defun org-reverse-string (string)
22492 "Return the reverse of STRING."
22493 (apply 'string (reverse (string-to-list string))))
22495 ;; defsubst org-uniquify must be defined before first use
22497 (defun org-uniquify-alist (alist)
22498 "Merge elements of ALIST with the same key.
22500 For example, in this alist:
22502 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22503 => \\='((a 1 3) (b 2))
22505 merge (a 1) and (a 3) into (a 1 3).
22507 The function returns the new ALIST."
22508 (let (rtn)
22509 (dolist (e alist rtn)
22510 (let (n)
22511 (if (not (assoc (car e) rtn))
22512 (push e rtn)
22513 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22514 (setq rtn (assq-delete-all (car e) rtn))
22515 (push n rtn))))))
22517 (defun org-delete-all (elts list)
22518 "Remove all elements in ELTS from LIST.
22519 Comparison is done with `equal'. It is a destructive operation
22520 that may remove elements by altering the list structure."
22521 (while elts
22522 (setq list (delete (pop elts) list)))
22523 list)
22525 (defun org-back-over-empty-lines ()
22526 "Move backwards over whitespace, to the beginning of the first empty line.
22527 Returns the number of empty lines passed."
22528 (let ((pos (point)))
22529 (if (cdr (assq 'heading org-blank-before-new-entry))
22530 (skip-chars-backward " \t\n\r")
22531 (unless (eobp)
22532 (forward-line -1)))
22533 (beginning-of-line 2)
22534 (goto-char (min (point) pos))
22535 (count-lines (point) pos)))
22537 (defun org-skip-whitespace ()
22538 (skip-chars-forward " \t\n\r"))
22540 (defun org-point-in-group (point group &optional context)
22541 "Check if POINT is in match-group GROUP.
22542 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22543 match. If the match group does not exist or point is not inside it,
22544 return nil."
22545 (and (match-beginning group)
22546 (>= point (match-beginning group))
22547 (<= point (match-end group))
22548 (if context
22549 (list context (match-beginning group) (match-end group))
22550 t)))
22552 (defun org-switch-to-buffer-other-window (&rest args)
22553 "Switch to buffer in a second window on the current frame.
22554 In particular, do not allow pop-up frames.
22555 Returns the newly created buffer."
22556 (org-no-popups
22557 (apply 'switch-to-buffer-other-window args)))
22559 (defun org-combine-plists (&rest plists)
22560 "Create a single property list from all plists in PLISTS.
22561 The process starts by copying the first list, and then setting properties
22562 from the other lists. Settings in the last list are the most significant
22563 ones and overrule settings in the other lists."
22564 (let ((rtn (copy-sequence (pop plists)))
22565 p v ls)
22566 (while plists
22567 (setq ls (pop plists))
22568 (while ls
22569 (setq p (pop ls) v (pop ls))
22570 (setq rtn (plist-put rtn p v))))
22571 rtn))
22573 (defun org-replace-escapes (string table)
22574 "Replace %-escapes in STRING with values in TABLE.
22575 TABLE is an association list with keys like \"%a\" and string values.
22576 The sequences in STRING may contain normal field width and padding information,
22577 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22578 so values can contain further %-escapes if they are define later in TABLE."
22579 (let ((tbl (copy-alist table))
22580 (case-fold-search nil)
22581 (pchg 0)
22582 re rpl)
22583 (dolist (e tbl)
22584 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22585 (when (and (cdr e) (string-match re (cdr e)))
22586 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22587 (safe "SREF"))
22588 (add-text-properties 0 3 (list 'sref sref) safe)
22589 (setcdr e (replace-match safe t t (cdr e)))))
22590 (while (string-match re string)
22591 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22592 (cdr e)))
22593 (setq string (replace-match rpl t t string))))
22594 (while (setq pchg (next-property-change pchg string))
22595 (let ((sref (get-text-property pchg 'sref string)))
22596 (when (and sref (string-match "SREF" string pchg))
22597 (setq string (replace-match sref t t string)))))
22598 string))
22600 (defun org-find-base-buffer-visiting (file)
22601 "Like `find-buffer-visiting' but always return the base buffer and
22602 not an indirect buffer."
22603 (let ((buf (or (get-file-buffer file)
22604 (find-buffer-visiting file))))
22605 (if buf
22606 (or (buffer-base-buffer buf) buf)
22607 nil)))
22609 ;;; TODO: Only called once, from ox-odt which should probably use
22610 ;;; org-export-inline-image-p or something.
22611 (defun org-file-image-p (file)
22612 "Return non-nil if FILE is an image."
22613 (save-match-data
22614 (string-match (image-file-name-regexp) file)))
22616 (defun org-get-cursor-date (&optional with-time)
22617 "Return the date at cursor in as a time.
22618 This works in the calendar and in the agenda, anywhere else it just
22619 returns the current time.
22620 If WITH-TIME is non-nil, returns the time of the event at point (in
22621 the agenda) or the current time of the day."
22622 (let (date day defd tp hod mod)
22623 (when with-time
22624 (setq tp (get-text-property (point) 'time))
22625 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22626 (setq hod (string-to-number (match-string 1 tp))
22627 mod (string-to-number (match-string 2 tp))))
22628 (or tp (let ((now (decode-time)))
22629 (setq hod (nth 2 now)
22630 mod (nth 1 now)))))
22631 (cond
22632 ((eq major-mode 'calendar-mode)
22633 (setq date (calendar-cursor-to-date)
22634 defd (encode-time 0 (or mod 0) (or hod 0)
22635 (nth 1 date) (nth 0 date) (nth 2 date))))
22636 ((eq major-mode 'org-agenda-mode)
22637 (setq day (get-text-property (point) 'day))
22638 (when day
22639 (setq date (calendar-gregorian-from-absolute day)
22640 defd (encode-time 0 (or mod 0) (or hod 0)
22641 (nth 1 date) (nth 0 date) (nth 2 date))))))
22642 (or defd (current-time))))
22644 (defun org-mark-subtree (&optional up)
22645 "Mark the current subtree.
22646 This puts point at the start of the current subtree, and mark at
22647 the end. If a numeric prefix UP is given, move up into the
22648 hierarchy of headlines by UP levels before marking the subtree."
22649 (interactive "P")
22650 (org-with-limited-levels
22651 (cond ((org-at-heading-p) (beginning-of-line))
22652 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22653 (t (outline-previous-visible-heading 1))))
22654 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22655 (if (called-interactively-p 'any)
22656 (call-interactively 'org-mark-element)
22657 (org-mark-element)))
22659 (defun org-file-newer-than-p (file time)
22660 "Non-nil if FILE is newer than TIME.
22661 FILE is a filename, as a string, TIME is a list of integers, as
22662 returned by, e.g., `current-time'."
22663 (and (file-exists-p file)
22664 ;; Only compare times up to whole seconds as some file-systems
22665 ;; (e.g. HFS+) do not retain any finer granularity. As
22666 ;; a consequence, make sure we return non-nil when the two
22667 ;; times are equal.
22668 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22669 (cl-subseq time 0 2)))))
22671 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22672 "Compile a SOURCE file using PROCESS.
22674 PROCESS is either a function or a list of shell commands, as
22675 strings. EXT is a file extension, without the leading dot, as
22676 a string. It is used to check if the process actually succeeded.
22678 PROCESS must create a file with the same base name and directory
22679 as SOURCE, but ending with EXT. The function then returns its
22680 filename. Otherwise, it raises an error. The error message can
22681 then be refined by providing string ERR-MSG, which is appended to
22682 the standard message.
22684 If PROCESS is a function, it is called with a single argument:
22685 the SOURCE file.
22687 If it is a list of commands, each of them is called using
22688 `shell-command'. By default, in each command, %b, %f, %F, %o and
22689 %O are replaced with, respectively, SOURCE base name, name, full
22690 name, directory and absolute output file name. It is possible,
22691 however, to use more place-holders by specifying them in optional
22692 argument SPEC, as an alist following the pattern
22694 (CHARACTER . REPLACEMENT-STRING).
22696 When PROCESS is a list of commands, optional argument LOG-BUF can
22697 be set to a buffer or a buffer name. `shell-command' then uses
22698 it for output."
22699 (let* ((base-name (file-name-base source))
22700 (full-name (file-truename source))
22701 (out-dir (or (file-name-directory source) "./"))
22702 (output (expand-file-name (concat base-name "." ext) out-dir))
22703 (time (current-time))
22704 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22705 (save-window-excursion
22706 (pcase process
22707 ((pred functionp) (funcall process (shell-quote-argument source)))
22708 ((pred consp)
22709 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22710 (spec (append spec
22711 `((?b . ,(shell-quote-argument base-name))
22712 (?f . ,(shell-quote-argument source))
22713 (?F . ,(shell-quote-argument full-name))
22714 (?o . ,(shell-quote-argument out-dir))
22715 (?O . ,(shell-quote-argument output))))))
22716 (dolist (command process)
22717 (shell-command (format-spec command spec) log-buf))))
22718 (_ (error "No valid command to process %S%s" source err-msg))))
22719 ;; Check for process failure. Output file is expected to be
22720 ;; located in the same directory as SOURCE.
22721 (unless (org-file-newer-than-p output time)
22722 (error (format "File %S wasn't produced%s" output err-msg)))
22723 output))
22725 ;;; Indentation
22727 (defvar org-element-greater-elements)
22728 (defun org--get-expected-indentation (element contentsp)
22729 "Expected indentation column for current line, according to ELEMENT.
22730 ELEMENT is an element containing point. CONTENTSP is non-nil
22731 when indentation is to be computed according to contents of
22732 ELEMENT."
22733 (let ((type (org-element-type element))
22734 (start (org-element-property :begin element))
22735 (post-affiliated (org-element-property :post-affiliated element)))
22736 (org-with-wide-buffer
22737 (cond
22738 (contentsp
22739 (cl-case type
22740 ((diary-sexp footnote-definition) 0)
22741 ((headline inlinetask nil)
22742 (if (not org-adapt-indentation) 0
22743 (let ((level (org-current-level)))
22744 (if level (1+ level) 0))))
22745 ((item plain-list) (org-list-item-body-column post-affiliated))
22747 (goto-char start)
22748 (org-get-indentation))))
22749 ((memq type '(headline inlinetask nil))
22750 (if (org-match-line "[ \t]*$")
22751 (org--get-expected-indentation element t)
22753 ((memq type '(diary-sexp footnote-definition)) 0)
22754 ;; First paragraph of a footnote definition or an item.
22755 ;; Indent like parent.
22756 ((< (line-beginning-position) start)
22757 (org--get-expected-indentation
22758 (org-element-property :parent element) t))
22759 ;; At first line: indent according to previous sibling, if any,
22760 ;; ignoring footnote definitions and inline tasks, or parent's
22761 ;; contents.
22762 ((= (line-beginning-position) start)
22763 (catch 'exit
22764 (while t
22765 (if (= (point-min) start) (throw 'exit 0)
22766 (goto-char (1- start))
22767 (let* ((previous (org-element-at-point))
22768 (parent previous))
22769 (while (and parent (<= (org-element-property :end parent) start))
22770 (setq previous parent
22771 parent (org-element-property :parent parent)))
22772 (cond
22773 ((not previous) (throw 'exit 0))
22774 ((> (org-element-property :end previous) start)
22775 (throw 'exit (org--get-expected-indentation previous t)))
22776 ((memq (org-element-type previous)
22777 '(footnote-definition inlinetask))
22778 (setq start (org-element-property :begin previous)))
22779 (t (goto-char (org-element-property :begin previous))
22780 (throw 'exit
22781 (if (bolp) (org-get-indentation)
22782 ;; At first paragraph in an item or
22783 ;; a footnote definition.
22784 (org--get-expected-indentation
22785 (org-element-property :parent previous) t))))))))))
22786 ;; Otherwise, move to the first non-blank line above.
22788 (beginning-of-line)
22789 (let ((pos (point)))
22790 (skip-chars-backward " \r\t\n")
22791 (cond
22792 ;; Two blank lines end a footnote definition or a plain
22793 ;; list. When we indent an empty line after them, the
22794 ;; containing list or footnote definition is over, so it
22795 ;; qualifies as a previous sibling. Therefore, we indent
22796 ;; like its first line.
22797 ((and (memq type '(footnote-definition plain-list))
22798 (> (count-lines (point) pos) 2))
22799 (goto-char start)
22800 (org-get-indentation))
22801 ;; Line above is the first one of a paragraph at the
22802 ;; beginning of an item or a footnote definition. Indent
22803 ;; like parent.
22804 ((< (line-beginning-position) start)
22805 (org--get-expected-indentation
22806 (org-element-property :parent element) t))
22807 ;; Line above is the beginning of an element, i.e., point
22808 ;; was originally on the blank lines between element's start
22809 ;; and contents.
22810 ((= (line-beginning-position) post-affiliated)
22811 (org--get-expected-indentation element t))
22812 ;; POS is after contents in a greater element. Indent like
22813 ;; the beginning of the element.
22814 ((and (memq type org-element-greater-elements)
22815 (let ((cend (org-element-property :contents-end element)))
22816 (and cend (<= cend pos))))
22817 ;; As a special case, if point is at the end of a footnote
22818 ;; definition or an item, indent like the very last element
22819 ;; within. If that last element is an item, indent like
22820 ;; its contents.
22821 (if (memq type '(footnote-definition item plain-list))
22822 (let ((last (org-element-at-point)))
22823 (goto-char pos)
22824 (org--get-expected-indentation
22825 last (eq (org-element-type last) 'item)))
22826 (goto-char start)
22827 (org-get-indentation)))
22828 ;; In any other case, indent like the current line.
22829 (t (org-get-indentation)))))))))
22831 (defun org--align-node-property ()
22832 "Align node property at point.
22833 Alignment is done according to `org-property-format', which see."
22834 (when (save-excursion
22835 (beginning-of-line)
22836 (looking-at org-property-re))
22837 (replace-match
22838 (concat (match-string 4)
22839 (org-trim
22840 (format org-property-format (match-string 1) (match-string 3))))
22841 t t)))
22843 (defun org-indent-line ()
22844 "Indent line depending on context.
22846 Indentation is done according to the following rules:
22848 - Footnote definitions, diary sexps, headlines and inline tasks
22849 have to start at column 0.
22851 - On the very first line of an element, consider, in order, the
22852 next rules until one matches:
22854 1. If there's a sibling element before, ignoring footnote
22855 definitions and inline tasks, indent like its first line.
22857 2. If element has a parent, indent like its contents. More
22858 precisely, if parent is an item, indent after the
22859 description part, if any, or the bullet (see
22860 `org-list-description-max-indent'). Else, indent like
22861 parent's first line.
22863 3. Otherwise, indent relatively to current level, if
22864 `org-adapt-indentation' is non-nil, or to left margin.
22866 - On a blank line at the end of an element, indent according to
22867 the type of the element. More precisely
22869 1. If element is a plain list, an item, or a footnote
22870 definition, indent like the very last element within.
22872 2. If element is a paragraph, indent like its last non blank
22873 line.
22875 3. Otherwise, indent like its very first line.
22877 - In the code part of a source block, use language major mode
22878 to indent current line if `org-src-tab-acts-natively' is
22879 non-nil. If it is nil, do nothing.
22881 - Otherwise, indent like the first non-blank line above.
22883 The function doesn't indent an item as it could break the whole
22884 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22885 `\\[org-shiftmetaright]'.
22887 Also align node properties according to `org-property-format'."
22888 (interactive)
22889 (cond
22890 (orgstruct-is-++
22891 (let ((indent-line-function
22892 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22893 (indent-according-to-mode)))
22894 ((org-at-heading-p) 'noindent)
22896 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22897 (type (org-element-type element)))
22898 (cond ((and (memq type '(plain-list item))
22899 (= (line-beginning-position)
22900 (org-element-property :post-affiliated element)))
22901 'noindent)
22902 ((and (eq type 'latex-environment)
22903 (>= (point) (org-element-property :post-affiliated element))
22904 (< (point) (org-with-wide-buffer
22905 (goto-char (org-element-property :end element))
22906 (skip-chars-backward " \r\t\n")
22907 (line-beginning-position 2))))
22908 'noindent)
22909 ((and (eq type 'src-block)
22910 org-src-tab-acts-natively
22911 (> (line-beginning-position)
22912 (org-element-property :post-affiliated element))
22913 (< (line-beginning-position)
22914 (org-with-wide-buffer
22915 (goto-char (org-element-property :end element))
22916 (skip-chars-backward " \r\t\n")
22917 (line-beginning-position))))
22918 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22920 (let ((column (org--get-expected-indentation element nil)))
22921 ;; Preserve current column.
22922 (if (<= (current-column) (current-indentation))
22923 (indent-line-to column)
22924 (save-excursion (indent-line-to column))))
22925 ;; Align node property. Also preserve current column.
22926 (when (eq type 'node-property)
22927 (let ((column (current-column)))
22928 (org--align-node-property)
22929 (org-move-to-column column)))))))))
22931 (defun org-indent-region (start end)
22932 "Indent each non-blank line in the region.
22933 Called from a program, START and END specify the region to
22934 indent. The function will not indent contents of example blocks,
22935 verse blocks and export blocks as leading white spaces are
22936 assumed to be significant there."
22937 (interactive "r")
22938 (save-excursion
22939 (goto-char start)
22940 (skip-chars-forward " \r\t\n")
22941 (unless (eobp) (beginning-of-line))
22942 (let ((indent-to
22943 (lambda (ind pos)
22944 ;; Set IND as indentation for all lines between point and
22945 ;; POS. Blank lines are ignored. Leave point after POS
22946 ;; once done.
22947 (let ((limit (copy-marker pos)))
22948 (while (< (point) limit)
22949 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22950 (forward-line))
22951 (set-marker limit nil))))
22952 (end (copy-marker end)))
22953 (while (< (point) end)
22954 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22955 (let* ((element (org-element-at-point))
22956 (type (org-element-type element))
22957 (element-end (copy-marker (org-element-property :end element)))
22958 (ind (org--get-expected-indentation element nil)))
22959 (cond
22960 ;; Element indented as a single block. Example blocks
22961 ;; preserving indentation are a special case since the
22962 ;; "contents" must not be indented whereas the block
22963 ;; boundaries can.
22964 ((or (memq type '(export-block latex-environment))
22965 (and (eq type 'example-block)
22966 (not
22967 (or org-src-preserve-indentation
22968 (org-element-property :preserve-indent element)))))
22969 (let ((offset (- ind (org-get-indentation))))
22970 (unless (zerop offset)
22971 (indent-rigidly (org-element-property :begin element)
22972 (org-element-property :end element)
22973 offset)))
22974 (goto-char element-end))
22975 ;; Elements indented line wise. Be sure to exclude
22976 ;; example blocks (preserving indentation) and source
22977 ;; blocks from this category as they are treated
22978 ;; specially later.
22979 ((or (memq type '(paragraph table table-row))
22980 (not (or (org-element-property :contents-begin element)
22981 (memq type '(example-block src-block)))))
22982 (when (eq type 'node-property)
22983 (org--align-node-property)
22984 (beginning-of-line))
22985 (funcall indent-to ind (min element-end end)))
22986 ;; Elements consisting of three parts: before the
22987 ;; contents, the contents, and after the contents. The
22988 ;; contents are treated specially, according to the
22989 ;; element type, or not indented at all. Other parts are
22990 ;; indented as a single block.
22992 (let* ((post (copy-marker
22993 (org-element-property :post-affiliated element)))
22994 (cbeg
22995 (copy-marker
22996 (cond
22997 ((not (org-element-property :contents-begin element))
22998 ;; Fake contents for source blocks.
22999 (org-with-wide-buffer
23000 (goto-char post)
23001 (line-beginning-position 2)))
23002 ((memq type '(footnote-definition item plain-list))
23003 ;; Contents in these elements could start on
23004 ;; the same line as the beginning of the
23005 ;; element. Make sure we start indenting
23006 ;; from the second line.
23007 (org-with-wide-buffer
23008 (goto-char post)
23009 (end-of-line)
23010 (skip-chars-forward " \r\t\n")
23011 (if (eobp) (point) (line-beginning-position))))
23012 (t (org-element-property :contents-begin element)))))
23013 (cend (copy-marker
23014 (or (org-element-property :contents-end element)
23015 ;; Fake contents for source blocks.
23016 (org-with-wide-buffer
23017 (goto-char element-end)
23018 (skip-chars-backward " \r\t\n")
23019 (line-beginning-position)))
23020 t)))
23021 ;; Do not change items indentation individually as it
23022 ;; might break the list as a whole. On the other
23023 ;; hand, when at a plain list, indent it as a whole.
23024 (cond ((eq type 'plain-list)
23025 (let ((offset (- ind (org-get-indentation))))
23026 (unless (zerop offset)
23027 (indent-rigidly (org-element-property :begin element)
23028 (org-element-property :end element)
23029 offset))
23030 (goto-char cbeg)))
23031 ((eq type 'item) (goto-char cbeg))
23032 (t (funcall indent-to ind (min cbeg end))))
23033 (when (< (point) end)
23034 (cl-case type
23035 ((example-block verse-block))
23036 (src-block
23037 ;; In a source block, indent source code
23038 ;; according to language major mode, but only if
23039 ;; `org-src-tab-acts-natively' is non-nil.
23040 (when (and (< (point) end) org-src-tab-acts-natively)
23041 (ignore-errors
23042 (org-babel-do-in-edit-buffer
23043 (indent-region (point-min) (point-max))))))
23044 (t (org-indent-region (point) (min cend end))))
23045 (goto-char (min cend end))
23046 (when (< (point) end)
23047 (funcall indent-to ind (min element-end end))))
23048 (set-marker post nil)
23049 (set-marker cbeg nil)
23050 (set-marker cend nil))))
23051 (set-marker element-end nil))))
23052 (set-marker end nil))))
23054 (defun org-indent-drawer ()
23055 "Indent the drawer at point."
23056 (interactive)
23057 (unless (save-excursion
23058 (beginning-of-line)
23059 (looking-at-p org-drawer-regexp))
23060 (user-error "Not at a drawer"))
23061 (let ((element (org-element-at-point)))
23062 (unless (memq (org-element-type element) '(drawer property-drawer))
23063 (user-error "Not at a drawer"))
23064 (org-with-wide-buffer
23065 (org-indent-region (org-element-property :begin element)
23066 (org-element-property :end element))))
23067 (message "Drawer at point indented"))
23069 (defun org-indent-block ()
23070 "Indent the block at point."
23071 (interactive)
23072 (unless (save-excursion
23073 (beginning-of-line)
23074 (let ((case-fold-search t))
23075 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23076 (user-error "Not at a block"))
23077 (let ((element (org-element-at-point)))
23078 (unless (memq (org-element-type element)
23079 '(comment-block center-block dynamic-block example-block
23080 export-block quote-block special-block
23081 src-block verse-block))
23082 (user-error "Not at a block"))
23083 (org-with-wide-buffer
23084 (org-indent-region (org-element-property :begin element)
23085 (org-element-property :end element))))
23086 (message "Block at point indented"))
23089 ;;; Filling
23091 ;; We use our own fill-paragraph and auto-fill functions.
23093 ;; `org-fill-paragraph' relies on adaptive filling and context
23094 ;; checking. Appropriate `fill-prefix' is computed with
23095 ;; `org-adaptive-fill-function'.
23097 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23098 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23099 ;; `org-adaptive-fill-function' value. Internally,
23100 ;; `org-comment-line-break-function' breaks the line.
23102 ;; `org-setup-filling' installs filling and auto-filling related
23103 ;; variables during `org-mode' initialization.
23105 (defvar org-element-paragraph-separate) ; org-element.el
23106 (defun org-setup-filling ()
23107 (require 'org-element)
23108 ;; Prevent auto-fill from inserting unwanted new items.
23109 (when (boundp 'fill-nobreak-predicate)
23110 (setq-local
23111 fill-nobreak-predicate
23112 (org-uniquify
23113 (append fill-nobreak-predicate
23114 '(org-fill-line-break-nobreak-p
23115 org-fill-paragraph-with-timestamp-nobreak-p)))))
23116 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23117 (setq-local paragraph-start paragraph-ending)
23118 (setq-local paragraph-separate paragraph-ending))
23119 (setq-local fill-paragraph-function 'org-fill-paragraph)
23120 (setq-local auto-fill-inhibit-regexp nil)
23121 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23122 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23123 (setq-local comment-line-break-function 'org-comment-line-break-function))
23125 (defun org-fill-line-break-nobreak-p ()
23126 "Non-nil when a new line at point would create an Org line break."
23127 (save-excursion
23128 (skip-chars-backward "[ \t]")
23129 (skip-chars-backward "\\\\")
23130 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23132 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23133 "Non-nil when a new line at point would split a timestamp."
23134 (and (org-at-timestamp-p t)
23135 (not (looking-at org-ts-regexp-both))))
23137 (declare-function message-in-body-p "message" ())
23138 (defvar orgtbl-line-start-regexp) ; From org-table.el
23139 (defun org-adaptive-fill-function ()
23140 "Compute a fill prefix for the current line.
23141 Return fill prefix, as a string, or nil if current line isn't
23142 meant to be filled. For convenience, if `adaptive-fill-regexp'
23143 matches in paragraphs or comments, use it."
23144 (catch 'exit
23145 (when (derived-mode-p 'message-mode)
23146 (save-excursion
23147 (beginning-of-line)
23148 (cond ((not (message-in-body-p)) (throw 'exit nil))
23149 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23150 ((looking-at message-cite-prefix-regexp)
23151 (throw 'exit (match-string-no-properties 0)))
23152 ((looking-at org-outline-regexp)
23153 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23154 (org-with-wide-buffer
23155 (unless (org-at-heading-p)
23156 (let* ((p (line-beginning-position))
23157 (element (save-excursion
23158 (beginning-of-line)
23159 (org-element-at-point)))
23160 (type (org-element-type element))
23161 (post-affiliated (org-element-property :post-affiliated element)))
23162 (unless (< p post-affiliated)
23163 (cl-case type
23164 (comment
23165 (save-excursion
23166 (beginning-of-line)
23167 (looking-at "[ \t]*")
23168 (concat (match-string 0) "# ")))
23169 (footnote-definition "")
23170 ((item plain-list)
23171 (make-string (org-list-item-body-column post-affiliated) ?\s))
23172 (paragraph
23173 ;; Fill prefix is usually the same as the current line,
23174 ;; unless the paragraph is at the beginning of an item.
23175 (let ((parent (org-element-property :parent element)))
23176 (save-excursion
23177 (beginning-of-line)
23178 (cond ((eq (org-element-type parent) 'item)
23179 (make-string (org-list-item-body-column
23180 (org-element-property :begin parent))
23181 ?\s))
23182 ((and adaptive-fill-regexp
23183 ;; Locally disable
23184 ;; `adaptive-fill-function' to let
23185 ;; `fill-context-prefix' handle
23186 ;; `adaptive-fill-regexp' variable.
23187 (let (adaptive-fill-function)
23188 (fill-context-prefix
23189 post-affiliated
23190 (org-element-property :end element)))))
23191 ((looking-at "[ \t]+") (match-string 0))
23192 (t "")))))
23193 (comment-block
23194 ;; Only fill contents if P is within block boundaries.
23195 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23196 (forward-line)
23197 (point)))
23198 (cend (save-excursion
23199 (goto-char (org-element-property :end element))
23200 (skip-chars-backward " \r\t\n")
23201 (line-beginning-position))))
23202 (when (and (>= p cbeg) (< p cend))
23203 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23204 (match-string 0)
23205 "")))))))))))
23207 (declare-function message-goto-body "message" ())
23208 (defvar message-cite-prefix-regexp) ; From message.el
23209 (defun org-fill-paragraph (&optional justify)
23210 "Fill element at point, when applicable.
23212 This function only applies to comment blocks, comments, example
23213 blocks and paragraphs. Also, as a special case, re-align table
23214 when point is at one.
23216 If JUSTIFY is non-nil (interactively, with prefix argument),
23217 justify as well. If `sentence-end-double-space' is non-nil, then
23218 period followed by one space does not end a sentence, so don't
23219 break a line there. The variable `fill-column' controls the
23220 width for filling.
23222 For convenience, when point is at a plain list, an item or
23223 a footnote definition, try to fill the first paragraph within."
23224 (interactive)
23225 (if (and (derived-mode-p 'message-mode)
23226 (or (not (message-in-body-p))
23227 (save-excursion (move-beginning-of-line 1)
23228 (looking-at message-cite-prefix-regexp))))
23229 ;; First ensure filling is correct in message-mode.
23230 (let ((fill-paragraph-function
23231 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23232 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23233 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23234 (paragraph-separate
23235 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23236 (fill-paragraph nil))
23237 (with-syntax-table org-mode-transpose-word-syntax-table
23238 ;; Move to end of line in order to get the first paragraph
23239 ;; within a plain list or a footnote definition.
23240 (let ((element (save-excursion
23241 (end-of-line)
23242 (or (ignore-errors (org-element-at-point))
23243 (user-error "An element cannot be parsed line %d"
23244 (line-number-at-pos (point)))))))
23245 ;; First check if point is in a blank line at the beginning of
23246 ;; the buffer. In that case, ignore filling.
23247 (cl-case (org-element-type element)
23248 ;; Use major mode filling function is src blocks.
23249 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23250 ;; Align Org tables, leave table.el tables as-is.
23251 (table-row (org-table-align) t)
23252 (table
23253 (when (eq (org-element-property :type element) 'org)
23254 (save-excursion
23255 (goto-char (org-element-property :post-affiliated element))
23256 (org-table-align)))
23258 (paragraph
23259 ;; Paragraphs may contain `line-break' type objects.
23260 (let ((beg (max (point-min)
23261 (org-element-property :contents-begin element)))
23262 (end (min (point-max)
23263 (org-element-property :contents-end element))))
23264 ;; Do nothing if point is at an affiliated keyword.
23265 (if (< (line-end-position) beg) t
23266 (when (derived-mode-p 'message-mode)
23267 ;; In `message-mode', do not fill following citation
23268 ;; in current paragraph nor text before message body.
23269 (let ((body-start (save-excursion (message-goto-body))))
23270 (when body-start (setq beg (max body-start beg))))
23271 (when (save-excursion
23272 (re-search-forward
23273 (concat "^" message-cite-prefix-regexp) end t))
23274 (setq end (match-beginning 0))))
23275 ;; Fill paragraph, taking line breaks into account.
23276 (save-excursion
23277 (goto-char beg)
23278 (let ((cuts (list beg)))
23279 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23280 (when (eq 'line-break
23281 (org-element-type
23282 (save-excursion (backward-char)
23283 (org-element-context))))
23284 (push (point) cuts)))
23285 (dolist (c (delq end cuts))
23286 (fill-region-as-paragraph c end justify)
23287 (setq end c))))
23288 t)))
23289 ;; Contents of `comment-block' type elements should be
23290 ;; filled as plain text, but only if point is within block
23291 ;; markers.
23292 (comment-block
23293 (let* ((case-fold-search t)
23294 (beg (save-excursion
23295 (goto-char (org-element-property :begin element))
23296 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23297 (forward-line)
23298 (point)))
23299 (end (save-excursion
23300 (goto-char (org-element-property :end element))
23301 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23302 (line-beginning-position))))
23303 (if (or (< (point) beg) (> (point) end)) t
23304 (fill-region-as-paragraph
23305 (save-excursion (end-of-line)
23306 (re-search-backward "^[ \t]*$" beg 'move)
23307 (line-beginning-position))
23308 (save-excursion (beginning-of-line)
23309 (re-search-forward "^[ \t]*$" end 'move)
23310 (line-beginning-position))
23311 justify))))
23312 ;; Fill comments.
23313 (comment
23314 (let ((begin (org-element-property :post-affiliated element))
23315 (end (org-element-property :end element)))
23316 (when (and (>= (point) begin) (<= (point) end))
23317 (let ((begin (save-excursion
23318 (end-of-line)
23319 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23320 (progn (forward-line) (point))
23321 begin)))
23322 (end (save-excursion
23323 (end-of-line)
23324 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23325 (1- (line-beginning-position))
23326 (skip-chars-backward " \r\t\n")
23327 (line-end-position)))))
23328 ;; Do not fill comments when at a blank line.
23329 (when (> end begin)
23330 (let ((fill-prefix
23331 (save-excursion
23332 (beginning-of-line)
23333 (looking-at "[ \t]*#")
23334 (let ((comment-prefix (match-string 0)))
23335 (goto-char (match-end 0))
23336 (if (looking-at adaptive-fill-regexp)
23337 (concat comment-prefix (match-string 0))
23338 (concat comment-prefix " "))))))
23339 (save-excursion
23340 (fill-region-as-paragraph begin end justify))))))
23342 ;; Ignore every other element.
23343 (otherwise t))))))
23345 (defun org-auto-fill-function ()
23346 "Auto-fill function."
23347 ;; Check if auto-filling is meaningful.
23348 (let ((fc (current-fill-column)))
23349 (when (and fc (> (current-column) fc))
23350 (let* ((fill-prefix (org-adaptive-fill-function))
23351 ;; Enforce empty fill prefix, if required. Otherwise, it
23352 ;; will be computed again.
23353 (adaptive-fill-mode (not (equal fill-prefix ""))))
23354 (when fill-prefix (do-auto-fill))))))
23356 (defun org-comment-line-break-function (&optional soft)
23357 "Break line at point and indent, continuing comment if within one.
23358 The inserted newline is marked hard if variable
23359 `use-hard-newlines' is true, unless optional argument SOFT is
23360 non-nil."
23361 (if soft (insert-and-inherit ?\n) (newline 1))
23362 (save-excursion (forward-char -1) (delete-horizontal-space))
23363 (delete-horizontal-space)
23364 (indent-to-left-margin)
23365 (insert-before-markers-and-inherit fill-prefix))
23368 ;;; Fixed Width Areas
23370 (defun org-toggle-fixed-width ()
23371 "Toggle fixed-width markup.
23373 Add or remove fixed-width markup on current line, whenever it
23374 makes sense. Return an error otherwise.
23376 If a region is active and if it contains only fixed-width areas
23377 or blank lines, remove all fixed-width markup in it. If the
23378 region contains anything else, convert all non-fixed-width lines
23379 to fixed-width ones.
23381 Blank lines at the end of the region are ignored unless the
23382 region only contains such lines."
23383 (interactive)
23384 (if (not (org-region-active-p))
23385 ;; No region:
23387 ;; Remove fixed width marker only in a fixed-with element.
23389 ;; Add fixed width maker in paragraphs, in blank lines after
23390 ;; elements or at the beginning of a headline or an inlinetask,
23391 ;; and before any one-line elements (e.g., a clock).
23392 (progn
23393 (beginning-of-line)
23394 (let* ((element (org-element-at-point))
23395 (type (org-element-type element)))
23396 (cond
23397 ((and (eq type 'fixed-width)
23398 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23399 (replace-match
23400 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23401 ((and (memq type '(babel-call clock comment diary-sexp headline
23402 horizontal-rule keyword paragraph
23403 planning))
23404 (<= (org-element-property :post-affiliated element) (point)))
23405 (skip-chars-forward " \t")
23406 (insert ": "))
23407 ((and (looking-at-p "[ \t]*$")
23408 (or (eq type 'inlinetask)
23409 (save-excursion
23410 (skip-chars-forward " \r\t\n")
23411 (<= (org-element-property :end element) (point)))))
23412 (delete-region (point) (line-end-position))
23413 (org-indent-line)
23414 (insert ": "))
23415 (t (user-error "Cannot insert a fixed-width line here")))))
23416 ;; Region active.
23417 (let* ((begin (save-excursion
23418 (goto-char (region-beginning))
23419 (line-beginning-position)))
23420 (end (copy-marker
23421 (save-excursion
23422 (goto-char (region-end))
23423 (unless (eolp) (beginning-of-line))
23424 (if (save-excursion (re-search-backward "\\S-" begin t))
23425 (progn (skip-chars-backward " \r\t\n") (point))
23426 (point)))))
23427 (all-fixed-width-p
23428 (catch 'not-all-p
23429 (save-excursion
23430 (goto-char begin)
23431 (skip-chars-forward " \r\t\n")
23432 (when (eobp) (throw 'not-all-p nil))
23433 (while (< (point) end)
23434 (let ((element (org-element-at-point)))
23435 (if (eq (org-element-type element) 'fixed-width)
23436 (goto-char (org-element-property :end element))
23437 (throw 'not-all-p nil))))
23438 t))))
23439 (if all-fixed-width-p
23440 (save-excursion
23441 (goto-char begin)
23442 (while (< (point) end)
23443 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23444 (replace-match
23445 "" nil nil nil
23446 (if (= (line-end-position) (match-end 0)) 0 1)))
23447 (forward-line)))
23448 (let ((min-ind (point-max)))
23449 ;; Find minimum indentation across all lines.
23450 (save-excursion
23451 (goto-char begin)
23452 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23453 (setq min-ind 0)
23454 (catch 'zerop
23455 (while (< (point) end)
23456 (unless (looking-at-p "[ \t]*$")
23457 (let ((ind (org-get-indentation)))
23458 (setq min-ind (min min-ind ind))
23459 (when (zerop ind) (throw 'zerop t))))
23460 (forward-line)))))
23461 ;; Loop over all lines and add fixed-width markup everywhere
23462 ;; but in fixed-width lines.
23463 (save-excursion
23464 (goto-char begin)
23465 (while (< (point) end)
23466 (cond
23467 ((org-at-heading-p)
23468 (insert ": ")
23469 (forward-line)
23470 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23471 (insert ":")
23472 (forward-line)))
23473 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23474 (let* ((element (org-element-at-point))
23475 (element-end (org-element-property :end element)))
23476 (if (eq (org-element-type element) 'fixed-width)
23477 (progn (goto-char element-end)
23478 (skip-chars-backward " \r\t\n")
23479 (forward-line))
23480 (let ((limit (min end element-end)))
23481 (while (< (point) limit)
23482 (org-move-to-column min-ind t)
23483 (insert ": ")
23484 (forward-line))))))
23486 (org-move-to-column min-ind t)
23487 (insert ": ")
23488 (forward-line)))))))
23489 (set-marker end nil))))
23492 ;;; Comments
23494 ;; Org comments syntax is quite complex. It requires the entire line
23495 ;; to be just a comment. Also, even with the right syntax at the
23496 ;; beginning of line, some some elements (i.e. verse-block or
23497 ;; example-block) don't accept comments. Usual Emacs comment commands
23498 ;; cannot cope with those requirements. Therefore, Org replaces them.
23500 ;; Org still relies on `comment-dwim', but cannot trust
23501 ;; `comment-only-p'. So, `comment-region-function' and
23502 ;; `uncomment-region-function' both point
23503 ;; to`org-comment-or-uncomment-region'. Eventually,
23504 ;; `org-insert-comment' takes care of insertion of comments at the
23505 ;; beginning of line.
23507 ;; `org-setup-comments-handling' install comments related variables
23508 ;; during `org-mode' initialization.
23510 (defun org-setup-comments-handling ()
23511 (interactive)
23512 (setq-local comment-use-syntax nil)
23513 (setq-local comment-start "# ")
23514 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23515 (setq-local comment-insert-comment-function 'org-insert-comment)
23516 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23517 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23519 (defun org-insert-comment ()
23520 "Insert an empty comment above current line.
23521 If the line is empty, insert comment at its beginning. When
23522 point is within a source block, comment according to the related
23523 major mode."
23524 (if (let ((element (org-element-at-point)))
23525 (and (eq (org-element-type element) 'src-block)
23526 (< (save-excursion
23527 (goto-char (org-element-property :post-affiliated element))
23528 (line-end-position))
23529 (point))
23530 (> (save-excursion
23531 (goto-char (org-element-property :end element))
23532 (skip-chars-backward " \r\t\n")
23533 (line-beginning-position))
23534 (point))))
23535 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23536 (beginning-of-line)
23537 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23538 (open-line 1))
23539 (org-indent-line)
23540 (insert "# ")))
23542 (defvar comment-empty-lines) ; From newcomment.el.
23543 (defun org-comment-or-uncomment-region (beg end &rest _)
23544 "Comment or uncomment each non-blank line in the region.
23545 Uncomment each non-blank line between BEG and END if it only
23546 contains commented lines. Otherwise, comment them. If region is
23547 strictly within a source block, use appropriate comment syntax."
23548 (if (let ((element (org-element-at-point)))
23549 (and (eq (org-element-type element) 'src-block)
23550 (< (save-excursion
23551 (goto-char (org-element-property :post-affiliated element))
23552 (line-end-position))
23553 beg)
23554 (>= (save-excursion
23555 (goto-char (org-element-property :end element))
23556 (skip-chars-backward " \r\t\n")
23557 (line-beginning-position))
23558 end)))
23559 ;; Translate region boundaries for the Org buffer to the source
23560 ;; buffer.
23561 (let ((offset (- end beg)))
23562 (save-excursion
23563 (goto-char beg)
23564 (org-babel-do-in-edit-buffer
23565 (comment-or-uncomment-region (point) (+ offset (point))))))
23566 (save-restriction
23567 ;; Restrict region
23568 (narrow-to-region (save-excursion (goto-char beg)
23569 (skip-chars-forward " \r\t\n" end)
23570 (line-beginning-position))
23571 (save-excursion (goto-char end)
23572 (skip-chars-backward " \r\t\n" beg)
23573 (line-end-position)))
23574 (let ((uncommentp
23575 ;; UNCOMMENTP is non-nil when every non blank line between
23576 ;; BEG and END is a comment.
23577 (save-excursion
23578 (goto-char (point-min))
23579 (while (and (not (eobp))
23580 (let ((element (org-element-at-point)))
23581 (and (eq (org-element-type element) 'comment)
23582 (goto-char (min (point-max)
23583 (org-element-property
23584 :end element)))))))
23585 (eobp))))
23586 (if uncommentp
23587 ;; Only blank lines and comments in region: uncomment it.
23588 (save-excursion
23589 (goto-char (point-min))
23590 (while (not (eobp))
23591 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23592 (replace-match "" nil nil nil 1))
23593 (forward-line)))
23594 ;; Comment each line in region.
23595 (let ((min-indent (point-max)))
23596 ;; First find the minimum indentation across all lines.
23597 (save-excursion
23598 (goto-char (point-min))
23599 (while (and (not (eobp)) (not (zerop min-indent)))
23600 (unless (looking-at "[ \t]*$")
23601 (setq min-indent (min min-indent (current-indentation))))
23602 (forward-line)))
23603 ;; Then loop over all lines.
23604 (save-excursion
23605 (goto-char (point-min))
23606 (while (not (eobp))
23607 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23608 ;; Don't get fooled by invisible text (e.g. link path)
23609 ;; when moving to column MIN-INDENT.
23610 (let ((buffer-invisibility-spec nil))
23611 (org-move-to-column min-indent t))
23612 (insert comment-start))
23613 (forward-line)))))))))
23615 (defun org-comment-dwim (_arg)
23616 "Call `comment-dwim' within a source edit buffer if needed."
23617 (interactive "*P")
23618 (if (org-in-src-block-p)
23619 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23620 (call-interactively 'comment-dwim)))
23623 ;;; Timestamps API
23625 ;; This section contains tools to operate on timestamp objects, as
23626 ;; returned by, e.g. `org-element-context'.
23628 (defun org-timestamp--to-internal-time (timestamp &optional end)
23629 "Encode TIMESTAMP object into Emacs internal time.
23630 Use end of date range or time range when END is non-nil."
23631 (apply #'encode-time
23632 (cons 0
23633 (mapcar
23634 (lambda (prop) (or (org-element-property prop timestamp) 0))
23635 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23636 '(:minute-start :hour-start :day-start :month-start
23637 :year-start))))))
23639 (defun org-timestamp-has-time-p (timestamp)
23640 "Non-nil when TIMESTAMP has a time specified."
23641 (org-element-property :hour-start timestamp))
23643 (defun org-timestamp-format (timestamp format &optional end utc)
23644 "Format a TIMESTAMP object into a string.
23646 FORMAT is a format specifier to be passed to
23647 `format-time-string'.
23649 When optional argument END is non-nil, use end of date-range or
23650 time-range, if possible.
23652 When optional argument UTC is non-nil, time will be expressed as
23653 Universal Time."
23654 (format-time-string
23655 format (org-timestamp--to-internal-time timestamp end)
23656 (and utc t)))
23658 (defun org-timestamp-split-range (timestamp &optional end)
23659 "Extract a TIMESTAMP object from a date or time range.
23661 END, when non-nil, means extract the end of the range.
23662 Otherwise, extract its start.
23664 Return a new timestamp object."
23665 (let ((type (org-element-property :type timestamp)))
23666 (if (memq type '(active inactive diary)) timestamp
23667 (let ((split-ts (org-element-copy timestamp)))
23668 ;; Set new type.
23669 (org-element-put-property
23670 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23671 ;; Copy start properties over end properties if END is
23672 ;; non-nil. Otherwise, copy end properties over `start' ones.
23673 (let ((p-alist '((:minute-start . :minute-end)
23674 (:hour-start . :hour-end)
23675 (:day-start . :day-end)
23676 (:month-start . :month-end)
23677 (:year-start . :year-end))))
23678 (dolist (p-cell p-alist)
23679 (org-element-put-property
23680 split-ts
23681 (funcall (if end #'car #'cdr) p-cell)
23682 (org-element-property
23683 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23684 ;; Eventually refresh `:raw-value'.
23685 (org-element-put-property split-ts :raw-value nil)
23686 (org-element-put-property
23687 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23689 (defun org-timestamp-translate (timestamp &optional boundary)
23690 "Translate TIMESTAMP object to custom format.
23692 Format string is defined in `org-time-stamp-custom-formats',
23693 which see.
23695 When optional argument BOUNDARY is non-nil, it is either the
23696 symbol `start' or `end'. In this case, only translate the
23697 starting or ending part of TIMESTAMP if it is a date or time
23698 range. Otherwise, translate both parts.
23700 Return timestamp as-is if `org-display-custom-times' is nil or if
23701 it has a `diary' type."
23702 (let ((type (org-element-property :type timestamp)))
23703 (if (or (not org-display-custom-times) (eq type 'diary))
23704 (org-element-interpret-data timestamp)
23705 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23706 org-time-stamp-custom-formats)))
23707 (if (and (not boundary) (memq type '(active-range inactive-range)))
23708 (concat (org-timestamp-format timestamp fmt)
23709 "--"
23710 (org-timestamp-format timestamp fmt t))
23711 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23715 ;;; Other stuff.
23717 (defvar reftex-docstruct-symbol)
23718 (defvar org--rds)
23720 (defun org-reftex-citation ()
23721 "Use reftex-citation to insert a citation into the buffer.
23722 This looks for a line like
23724 #+BIBLIOGRAPHY: foo plain option:-d
23726 and derives from it that foo.bib is the bibliography file relevant
23727 for this document. It then installs the necessary environment for RefTeX
23728 to work in this buffer and calls `reftex-citation' to insert a citation
23729 into the buffer.
23731 Export of such citations to both LaTeX and HTML is handled by the contributed
23732 package ox-bibtex by Taru Karttunen."
23733 (interactive)
23734 (let ((reftex-docstruct-symbol 'org--rds)
23735 org--rds bib)
23736 (org-with-wide-buffer
23737 (let ((case-fold-search t)
23738 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23739 (if (not (save-excursion
23740 (or (re-search-forward re nil t)
23741 (re-search-backward re nil t))))
23742 (user-error "No bibliography defined in file")
23743 (setq bib (concat (match-string 1) ".bib")
23744 org--rds (list (list 'bib bib))))))
23745 (call-interactively 'reftex-citation)))
23747 ;;;; Functions extending outline functionality
23749 (defun org-beginning-of-line (&optional n)
23750 "Go to the beginning of the current visible line.
23752 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23753 tags on the first attempt, and only move to after the tags when
23754 the cursor is already beyond the end of the headline.
23756 With argument N not nil or 1, move forward N - 1 lines first."
23757 (interactive "^p")
23758 (let ((origin (point))
23759 (special (pcase org-special-ctrl-a/e
23760 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23761 deactivate-mark)
23762 ;; First move to a visible line.
23763 (if (bound-and-true-p visual-line-mode)
23764 (beginning-of-visual-line n)
23765 (move-beginning-of-line n)
23766 ;; `move-beginning-of-line' may leave point after invisible
23767 ;; characters if line starts with such of these (e.g., with
23768 ;; a link at column 0). Really move to the beginning of the
23769 ;; current visible line.
23770 (beginning-of-line))
23771 (cond
23772 ;; No special behavior. Point is already at the beginning of
23773 ;; a line, logical or visual.
23774 ((not special))
23775 ;; `beginning-of-visual-line' left point before logical beginning
23776 ;; of line: point is at the beginning of a visual line. Bail
23777 ;; out.
23778 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23779 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23780 ;; At a headline, special position is before the title, but
23781 ;; after any TODO keyword or priority cookie.
23782 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23783 (line-end-position)))
23784 (bol (point)))
23785 (if (eq special 'reversed)
23786 (when (and (= origin bol) (eq last-command this-command))
23787 (goto-char refpos))
23788 (when (or (> origin refpos) (= origin bol))
23789 (goto-char refpos)))))
23790 ((and (looking-at org-list-full-item-re)
23791 (memq (org-element-type (save-match-data (org-element-at-point)))
23792 '(item plain-list)))
23793 ;; Set special position at first white space character after
23794 ;; bullet, and check-box, if any.
23795 (let ((after-bullet
23796 (let ((box (match-end 3)))
23797 (cond ((not box) (match-end 1))
23798 ((eq (char-after box) ?\s) (1+ box))
23799 (t box)))))
23800 (if (eq special 'reversed)
23801 (when (and (= (point) origin) (eq last-command this-command))
23802 (goto-char after-bullet))
23803 (when (or (> origin after-bullet) (= (point) origin))
23804 (goto-char after-bullet)))))
23805 ;; No special context. Point is already at beginning of line.
23806 (t nil))))
23808 (defun org-end-of-line (&optional n)
23809 "Go to the end of the line, but before ellipsis, if any.
23811 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23812 tags on the first attempt, and only move to after the tags when
23813 the cursor is already beyond the end of the headline.
23815 With argument N not nil or 1, move forward N - 1 lines first."
23816 (interactive "^p")
23817 (let ((origin (point))
23818 (special (pcase org-special-ctrl-a/e
23819 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23820 deactivate-mark)
23821 ;; First move to a visible line.
23822 (if (bound-and-true-p visual-line-mode)
23823 (beginning-of-visual-line n)
23824 (move-beginning-of-line n))
23825 (cond
23826 ;; At a headline, with tags.
23827 ((and special
23828 (save-excursion
23829 (beginning-of-line)
23830 (let ((case-fold-search nil))
23831 (looking-at org-complex-heading-regexp)))
23832 (match-end 5))
23833 (let ((tags (save-excursion
23834 (goto-char (match-beginning 5))
23835 (skip-chars-backward " \t")
23836 (point)))
23837 (visual-end (and (bound-and-true-p visual-line-mode)
23838 (save-excursion
23839 (end-of-visual-line)
23840 (point)))))
23841 ;; If `end-of-visual-line' brings us before end of line or
23842 ;; even tags, i.e., the headline spans over multiple visual
23843 ;; lines, move there.
23844 (cond ((and visual-end
23845 (< visual-end tags)
23846 (<= origin visual-end))
23847 (goto-char visual-end))
23848 ((eq special 'reversed)
23849 (if (and (= origin (line-end-position))
23850 (eq this-command last-command))
23851 (goto-char tags)
23852 (end-of-line)))
23854 (if (or (< origin tags) (= origin (line-end-position)))
23855 (goto-char tags)
23856 (end-of-line))))))
23857 ((bound-and-true-p visual-line-mode)
23858 (let ((bol (line-beginning-position)))
23859 (end-of-visual-line)
23860 ;; If `end-of-visual-line' gets us past the ellipsis at the
23861 ;; end of a line, backtrack and use `end-of-line' instead.
23862 (when (/= bol (line-beginning-position))
23863 (goto-char bol)
23864 (end-of-line))))
23865 (t (end-of-line)))))
23867 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23868 (define-key org-mode-map "\C-e" 'org-end-of-line)
23870 (defun org-backward-sentence (&optional _arg)
23871 "Go to beginning of sentence, or beginning of table field.
23872 This will call `backward-sentence' or `org-table-beginning-of-field',
23873 depending on context."
23874 (interactive)
23875 (let* ((element (org-element-at-point))
23876 (contents-begin (org-element-property :contents-begin element))
23877 (table (org-element-lineage element '(table) t)))
23878 (if (and table
23879 (> (point) contents-begin)
23880 (<= (point) (org-element-property :contents-end table)))
23881 (call-interactively #'org-table-beginning-of-field)
23882 (save-restriction
23883 (when (and contents-begin
23884 (< (point-min) contents-begin)
23885 (> (point) contents-begin))
23886 (narrow-to-region contents-begin
23887 (org-element-property :contents-end element)))
23888 (call-interactively #'backward-sentence)))))
23890 (defun org-forward-sentence (&optional _arg)
23891 "Go to end of sentence, or end of table field.
23892 This will call `forward-sentence' or `org-table-end-of-field',
23893 depending on context."
23894 (interactive)
23895 (let* ((element (org-element-at-point))
23896 (contents-end (org-element-property :contents-end element))
23897 (table (org-element-lineage element '(table) t)))
23898 (if (and table
23899 (>= (point) (org-element-property :contents-begin table))
23900 (< (point) contents-end))
23901 (call-interactively #'org-table-end-of-field)
23902 (save-restriction
23903 (when (and contents-end
23904 (> (point-max) contents-end)
23905 ;; Skip blank lines between elements.
23906 (< (org-element-property :end element)
23907 (save-excursion (goto-char contents-end)
23908 (skip-chars-forward " \r\t\n"))))
23909 (narrow-to-region (org-element-property :contents-begin element)
23910 contents-end))
23911 (call-interactively #'forward-sentence)))))
23913 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23914 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23916 (defun org-kill-line (&optional _arg)
23917 "Kill line, to tags or end of line."
23918 (interactive)
23919 (cond
23920 ((or (not org-special-ctrl-k)
23921 (bolp)
23922 (not (org-at-heading-p)))
23923 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23924 org-ctrl-k-protect-subtree
23925 (or (eq org-ctrl-k-protect-subtree 'error)
23926 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23927 (user-error "C-k aborted as it would kill a hidden subtree"))
23928 (call-interactively
23929 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23930 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23931 (kill-region (point) (match-beginning 1))
23932 (org-set-tags nil t))
23933 (t (kill-region (point) (point-at-eol)))))
23935 (define-key org-mode-map "\C-k" 'org-kill-line)
23937 (defun org-yank (&optional arg)
23938 "Yank. If the kill is a subtree, treat it specially.
23939 This command will look at the current kill and check if is a single
23940 subtree, or a series of subtrees[1]. If it passes the test, and if the
23941 cursor is at the beginning of a line or after the stars of a currently
23942 empty headline, then the yank is handled specially. How exactly depends
23943 on the value of the following variables.
23945 `org-yank-folded-subtrees'
23946 By default, this variable is non-nil, which results in
23947 subtree(s) being folded after insertion, except if doing so
23948 would swallow text after the yanked text.
23950 `org-yank-adjusted-subtrees'
23951 When non-nil (the default value is nil), the subtree will be
23952 promoted or demoted in order to fit into the local outline tree
23953 structure, which means that the level will be adjusted so that it
23954 becomes the smaller one of the two *visible* surrounding headings.
23956 Any prefix to this command will cause `yank' to be called directly with
23957 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23958 will just
23959 plainly yank the text as it is.
23961 \[1] The test checks if the first non-white line is a heading
23962 and if there are no other headings with fewer stars."
23963 (interactive "P")
23964 (org-yank-generic 'yank arg))
23966 (defun org-yank-generic (command arg)
23967 "Perform some yank-like command.
23969 This function implements the behavior described in the `org-yank'
23970 documentation. However, it has been generalized to work for any
23971 interactive command with similar behavior."
23973 ;; pretend to be command COMMAND
23974 (setq this-command command)
23976 (if arg
23977 (call-interactively command)
23979 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23980 (and (org-kill-is-subtree-p)
23981 (or (bolp)
23982 (and (looking-at "[ \t]*$")
23983 (string-match
23984 "\\`\\*+\\'"
23985 (buffer-substring (point-at-bol) (point)))))))
23986 swallowp)
23987 (cond
23988 ((and subtreep org-yank-folded-subtrees)
23989 (let ((beg (point))
23990 end)
23991 (if (and subtreep org-yank-adjusted-subtrees)
23992 (org-paste-subtree nil nil 'for-yank)
23993 (call-interactively command))
23995 (setq end (point))
23996 (goto-char beg)
23997 (when (and (bolp) subtreep
23998 (not (setq swallowp
23999 (org-yank-folding-would-swallow-text beg end))))
24000 (org-with-limited-levels
24001 (or (looking-at org-outline-regexp)
24002 (re-search-forward org-outline-regexp-bol end t))
24003 (while (and (< (point) end) (looking-at org-outline-regexp))
24004 (outline-hide-subtree)
24005 (org-cycle-show-empty-lines 'folded)
24006 (condition-case nil
24007 (outline-forward-same-level 1)
24008 (error (goto-char end))))))
24009 (when swallowp
24010 (message
24011 "Inserted text not folded because that would swallow text"))
24013 (goto-char end)
24014 (skip-chars-forward " \t\n\r")
24015 (beginning-of-line 1)
24016 (push-mark beg 'nomsg)))
24017 ((and subtreep org-yank-adjusted-subtrees)
24018 (let ((beg (point-at-bol)))
24019 (org-paste-subtree nil nil 'for-yank)
24020 (push-mark beg 'nomsg)))
24022 (call-interactively command))))))
24024 (defun org-yank-folding-would-swallow-text (beg end)
24025 "Would hide-subtree at BEG swallow any text after END?"
24026 (let (level)
24027 (org-with-limited-levels
24028 (save-excursion
24029 (goto-char beg)
24030 (when (or (looking-at org-outline-regexp)
24031 (re-search-forward org-outline-regexp-bol end t))
24032 (setq level (org-outline-level)))
24033 (goto-char end)
24034 (skip-chars-forward " \t\r\n\v\f")
24035 (not (or (eobp)
24036 (and (bolp) (looking-at-p org-outline-regexp)
24037 (<= (org-outline-level) level))))))))
24039 (define-key org-mode-map "\C-y" 'org-yank)
24041 (defun org-truely-invisible-p ()
24042 "Check if point is at a character currently not visible.
24043 This version does not only check the character property, but also
24044 `visible-mode'."
24045 (unless (bound-and-true-p visible-mode)
24046 (org-invisible-p)))
24048 (defun org-invisible-p2 ()
24049 "Check if point is at a character currently not visible.
24051 If the point is at EOL (and not at the beginning of a buffer too),
24052 move it back by one char before doing this check."
24053 (save-excursion
24054 (when (and (eolp) (not (bobp)))
24055 (backward-char 1))
24056 (org-invisible-p)))
24058 (defun org-back-to-heading (&optional invisible-ok)
24059 "Call `outline-back-to-heading', but provide a better error message."
24060 (condition-case nil
24061 (outline-back-to-heading invisible-ok)
24062 (error (error "Before first headline at position %d in buffer %s"
24063 (point) (current-buffer)))))
24065 (defun org-before-first-heading-p ()
24066 "Before first heading?"
24067 (save-excursion
24068 (end-of-line)
24069 (null (re-search-backward org-outline-regexp-bol nil t))))
24071 (defun org-at-heading-p (&optional ignored)
24072 (outline-on-heading-p t))
24074 (defun org-in-commented-heading-p (&optional no-inheritance)
24075 "Non-nil if point is under a commented heading.
24076 This function also checks ancestors of the current headline,
24077 unless optional argument NO-INHERITANCE is non-nil."
24078 (cond
24079 ((org-before-first-heading-p) nil)
24080 ((let ((headline (nth 4 (org-heading-components))))
24081 (and headline
24082 (let ((case-fold-search nil))
24083 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24084 headline)))))
24085 (no-inheritance nil)
24087 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24089 (defun org-at-comment-p nil
24090 "Is cursor in a commented line?"
24091 (save-excursion
24092 (save-match-data
24093 (beginning-of-line)
24094 (looking-at "^[ \t]*# "))))
24096 (defun org-at-drawer-p nil
24097 "Is cursor at a drawer keyword?"
24098 (save-excursion
24099 (move-beginning-of-line 1)
24100 (looking-at org-drawer-regexp)))
24102 (defun org-at-block-p nil
24103 "Is cursor at a block keyword?"
24104 (save-excursion
24105 (move-beginning-of-line 1)
24106 (looking-at org-block-regexp)))
24108 (defun org-point-at-end-of-empty-headline ()
24109 "If point is at the end of an empty headline, return t, else nil.
24110 If the heading only contains a TODO keyword, it is still still considered
24111 empty."
24112 (let ((case-fold-search nil))
24113 (and (looking-at "[ \t]*$")
24114 org-todo-line-regexp
24115 (save-excursion
24116 (beginning-of-line)
24117 (looking-at org-todo-line-regexp)
24118 (string= (match-string 3) "")))))
24120 (defun org-at-heading-or-item-p ()
24121 (or (org-at-heading-p) (org-at-item-p)))
24123 (defun org-at-target-p ()
24124 (or (org-in-regexp org-radio-target-regexp)
24125 (org-in-regexp org-target-regexp)))
24126 ;; Compatibility alias with Org versions < 7.8.03
24127 (defalias 'org-on-target-p 'org-at-target-p)
24129 (defun org-up-heading-all (arg)
24130 "Move to the heading line of which the present line is a subheading.
24131 This function considers both visible and invisible heading lines.
24132 With argument, move up ARG levels."
24133 (outline-up-heading arg t))
24135 (defun org-up-heading-safe ()
24136 "Move to the heading line of which the present line is a subheading.
24137 This version will not throw an error. It will return the level of the
24138 headline found, or nil if no higher level is found.
24140 Also, this function will be a lot faster than `outline-up-heading',
24141 because it relies on stars being the outline starters. This can really
24142 make a significant difference in outlines with very many siblings."
24143 (when (ignore-errors (org-back-to-heading t))
24144 (let ((level-up (1- (funcall outline-level))))
24145 (and (> level-up 0)
24146 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24147 (funcall outline-level)))))
24149 (defun org-first-sibling-p ()
24150 "Is this heading the first child of its parents?"
24151 (interactive)
24152 (let ((re org-outline-regexp-bol)
24153 level l)
24154 (unless (org-at-heading-p t)
24155 (user-error "Not at a heading"))
24156 (setq level (funcall outline-level))
24157 (save-excursion
24158 (if (not (re-search-backward re nil t))
24160 (setq l (funcall outline-level))
24161 (< l level)))))
24163 (defun org-goto-sibling (&optional previous)
24164 "Goto the next sibling, even if it is invisible.
24165 When PREVIOUS is set, go to the previous sibling instead. Returns t
24166 when a sibling was found. When none is found, return nil and don't
24167 move point."
24168 (let ((fun (if previous 're-search-backward 're-search-forward))
24169 (pos (point))
24170 (re org-outline-regexp-bol)
24171 level l)
24172 (when (ignore-errors (org-back-to-heading t))
24173 (setq level (funcall outline-level))
24174 (catch 'exit
24175 (or previous (forward-char 1))
24176 (while (funcall fun re nil t)
24177 (setq l (funcall outline-level))
24178 (when (< l level) (goto-char pos) (throw 'exit nil))
24179 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24180 (goto-char pos)
24181 nil))))
24183 (defun org-show-siblings ()
24184 "Show all siblings of the current headline."
24185 (save-excursion
24186 (while (org-goto-sibling) (org-flag-heading nil)))
24187 (save-excursion
24188 (while (org-goto-sibling 'previous)
24189 (org-flag-heading nil))))
24191 (defun org-goto-first-child ()
24192 "Goto the first child, even if it is invisible.
24193 Return t when a child was found. Otherwise don't move point and
24194 return nil."
24195 (let (level (pos (point)) (re org-outline-regexp-bol))
24196 (when (ignore-errors (org-back-to-heading t))
24197 (setq level (outline-level))
24198 (forward-char 1)
24199 (if (and (re-search-forward re nil t) (> (outline-level) level))
24200 (progn (goto-char (match-beginning 0)) t)
24201 (goto-char pos) nil))))
24203 (defun org-show-hidden-entry ()
24204 "Show an entry where even the heading is hidden."
24205 (save-excursion
24206 (org-show-entry)))
24208 (defun org-flag-heading (flag &optional entry)
24209 "Flag the current heading. FLAG non-nil means make invisible.
24210 When ENTRY is non-nil, show the entire entry."
24211 (save-excursion
24212 (org-back-to-heading t)
24213 ;; Check if we should show the entire entry
24214 (if entry
24215 (progn
24216 (org-show-entry)
24217 (save-excursion
24218 (and (outline-next-heading)
24219 (org-flag-heading nil))))
24220 (outline-flag-region (max (point-min) (1- (point)))
24221 (save-excursion (outline-end-of-heading) (point))
24222 flag))))
24224 (defun org-get-next-sibling ()
24225 "Move to next heading of the same level, and return point.
24226 If there is no such heading, return nil.
24227 This is like outline-next-sibling, but invisible headings are ok."
24228 (let ((level (funcall outline-level)))
24229 (outline-next-heading)
24230 (while (and (not (eobp)) (> (funcall outline-level) level))
24231 (outline-next-heading))
24232 (unless (or (eobp) (< (funcall outline-level) level))
24233 (point))))
24235 (defun org-get-last-sibling ()
24236 "Move to previous heading of the same level, and return point.
24237 If there is no such heading, return nil."
24238 (let ((opoint (point))
24239 (level (funcall outline-level)))
24240 (outline-previous-heading)
24241 (when (and (/= (point) opoint) (outline-on-heading-p t))
24242 (while (and (> (funcall outline-level) level)
24243 (not (bobp)))
24244 (outline-previous-heading))
24245 (unless (< (funcall outline-level) level)
24246 (point)))))
24248 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24249 "Goto to the end of a subtree."
24250 ;; This contains an exact copy of the original function, but it uses
24251 ;; `org-back-to-heading', to make it work also in invisible
24252 ;; trees. And is uses an invisible-ok argument.
24253 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24254 ;; Furthermore, when used inside Org, finding the end of a large subtree
24255 ;; with many children and grandchildren etc, this can be much faster
24256 ;; than the outline version.
24257 (org-back-to-heading invisible-ok)
24258 (let ((first t)
24259 (level (funcall outline-level)))
24260 (if (and (derived-mode-p 'org-mode) (< level 1000))
24261 ;; A true heading (not a plain list item), in Org
24262 ;; This means we can easily find the end by looking
24263 ;; only for the right number of stars. Using a regexp to do
24264 ;; this is so much faster than using a Lisp loop.
24265 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24266 (forward-char 1)
24267 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24268 ;; something else, do it the slow way
24269 (while (and (not (eobp))
24270 (or first (> (funcall outline-level) level)))
24271 (setq first nil)
24272 (outline-next-heading)))
24273 (unless to-heading
24274 (when (memq (preceding-char) '(?\n ?\^M))
24275 ;; Go to end of line before heading
24276 (forward-char -1)
24277 (when (memq (preceding-char) '(?\n ?\^M))
24278 ;; leave blank line before heading
24279 (forward-char -1)))))
24280 (point))
24282 (defun org-end-of-meta-data (&optional full)
24283 "Skip planning line and properties drawer in current entry.
24284 When optional argument FULL is non-nil, also skip empty lines,
24285 clocking lines and regular drawers at the beginning of the
24286 entry."
24287 (org-back-to-heading t)
24288 (forward-line)
24289 (when (looking-at-p org-planning-line-re) (forward-line))
24290 (when (looking-at org-property-drawer-re)
24291 (goto-char (match-end 0))
24292 (forward-line))
24293 (when (and full (not (org-at-heading-p)))
24294 (catch 'exit
24295 (let ((end (save-excursion (outline-next-heading) (point)))
24296 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24297 (while (not (eobp))
24298 (cond ((looking-at-p org-drawer-regexp)
24299 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24300 (forward-line)
24301 (throw 'exit t)))
24302 ((looking-at-p re) (forward-line))
24303 (t (throw 'exit t))))))))
24305 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24306 "Move forward to the ARG'th subheading at same level as this one.
24307 Stop at the first and last subheadings of a superior heading.
24308 Normally this only looks at visible headings, but when INVISIBLE-OK is
24309 non-nil it will also look at invisible ones."
24310 (interactive "p")
24311 (let ((backward? (and arg (< arg 0))))
24312 (if (org-before-first-heading-p)
24313 (if backward? (goto-char (point-min)) (outline-next-heading))
24314 (org-back-to-heading invisible-ok)
24315 (unless backward? (end-of-line)) ;do not match current headline
24316 (let ((level (- (match-end 0) (match-beginning 0) 1))
24317 (f (if backward? #'re-search-backward #'re-search-forward))
24318 (count (if arg (abs arg) 1))
24319 (result (point)))
24320 (while (and (> count 0)
24321 (funcall f org-outline-regexp-bol nil 'move))
24322 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24323 (cond ((< l level) (setq count 0))
24324 ((and (= l level)
24325 (or invisible-ok
24326 (not (org-invisible-p
24327 (line-beginning-position)))))
24328 (cl-decf count)
24329 (when (= l level) (setq result (point)))))))
24330 (goto-char result))
24331 (beginning-of-line))))
24333 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24334 "Move backward to the ARG'th subheading at same level as this one.
24335 Stop at the first and last subheadings of a superior heading."
24336 (interactive "p")
24337 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24339 (defun org-next-visible-heading (arg)
24340 "Move to the next visible heading.
24342 This function wraps `outline-next-visible-heading' with
24343 `org-with-limited-levels' in order to skip over inline tasks and
24344 respect customization of `org-odd-levels-only'."
24345 (interactive "p")
24346 (org-with-limited-levels
24347 (outline-next-visible-heading arg)))
24349 (defun org-previous-visible-heading (arg)
24350 "Move to the previous visible heading.
24352 This function wraps `outline-previous-visible-heading' with
24353 `org-with-limited-levels' in order to skip over inline tasks and
24354 respect customization of `org-odd-levels-only'."
24355 (interactive "p")
24356 (org-with-limited-levels
24357 (outline-previous-visible-heading arg)))
24359 (defun org-next-block (arg &optional backward block-regexp)
24360 "Jump to the next block.
24362 With a prefix argument ARG, jump forward ARG many blocks.
24364 When BACKWARD is non-nil, jump to the previous block.
24366 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24367 Match data is set according to this regexp when the function
24368 returns.
24370 Return point at beginning of the opening line of found block.
24371 Throw an error if no block is found."
24372 (interactive "p")
24373 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24374 (case-fold-search t)
24375 (search-fn (if backward #'re-search-backward #'re-search-forward))
24376 (count (or arg 1))
24377 (origin (point))
24378 last-element)
24379 (if backward (beginning-of-line) (end-of-line))
24380 (while (and (> count 0) (funcall search-fn re nil t))
24381 (let ((element (save-excursion
24382 (goto-char (match-beginning 0))
24383 (save-match-data (org-element-at-point)))))
24384 (when (and (memq (org-element-type element)
24385 '(center-block comment-block dynamic-block
24386 example-block export-block quote-block
24387 special-block src-block verse-block))
24388 (<= (match-beginning 0)
24389 (org-element-property :post-affiliated element)))
24390 (setq last-element element)
24391 (cl-decf count))))
24392 (if (= count 0)
24393 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24394 (save-match-data (org-show-context)))
24395 (goto-char origin)
24396 (user-error "No %s code blocks" (if backward "previous" "further")))))
24398 (defun org-previous-block (arg &optional block-regexp)
24399 "Jump to the previous block.
24400 With a prefix argument ARG, jump backward ARG many source blocks.
24401 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24402 (interactive "p")
24403 (org-next-block arg t block-regexp))
24405 (defun org-forward-paragraph ()
24406 "Move forward to beginning of next paragraph or equivalent.
24408 The function moves point to the beginning of the next visible
24409 structural element, which can be a paragraph, a table, a list
24410 item, etc. It also provides some special moves for convenience:
24412 - On an affiliated keyword, jump to the beginning of the
24413 relative element.
24414 - On an item or a footnote definition, move to the second
24415 element inside, if any.
24416 - On a table or a property drawer, jump after it.
24417 - On a verse or source block, stop after blank lines."
24418 (interactive)
24419 (when (eobp) (user-error "Cannot move further down"))
24420 (let* ((deactivate-mark nil)
24421 (element (org-element-at-point))
24422 (type (org-element-type element))
24423 (post-affiliated (org-element-property :post-affiliated element))
24424 (contents-begin (org-element-property :contents-begin element))
24425 (contents-end (org-element-property :contents-end element))
24426 (end (let ((end (org-element-property :end element)) (parent element))
24427 (while (and (setq parent (org-element-property :parent parent))
24428 (= (org-element-property :contents-end parent) end))
24429 (setq end (org-element-property :end parent)))
24430 end)))
24431 (cond ((not element)
24432 (skip-chars-forward " \r\t\n")
24433 (or (eobp) (beginning-of-line)))
24434 ;; On affiliated keywords, move to element's beginning.
24435 ((< (point) post-affiliated)
24436 (goto-char post-affiliated))
24437 ;; At a table row, move to the end of the table. Similarly,
24438 ;; at a node property, move to the end of the property
24439 ;; drawer.
24440 ((memq type '(node-property table-row))
24441 (goto-char (org-element-property
24442 :end (org-element-property :parent element))))
24443 ((memq type '(property-drawer table)) (goto-char end))
24444 ;; Consider blank lines as separators in verse and source
24445 ;; blocks to ease editing.
24446 ((memq type '(src-block verse-block))
24447 (when (eq type 'src-block)
24448 (setq contents-end
24449 (save-excursion (goto-char end)
24450 (skip-chars-backward " \r\t\n")
24451 (line-beginning-position))))
24452 (beginning-of-line)
24453 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24454 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24455 (goto-char end)
24456 (skip-chars-forward " \r\t\n")
24457 (if (= (point) contents-end) (goto-char end)
24458 (beginning-of-line))))
24459 ;; With no contents, just skip element.
24460 ((not contents-begin) (goto-char end))
24461 ;; If contents are invisible, skip the element altogether.
24462 ((org-invisible-p (line-end-position))
24463 (cl-case type
24464 (headline
24465 (org-with-limited-levels (outline-next-visible-heading 1)))
24466 ;; At a plain list, make sure we move to the next item
24467 ;; instead of skipping the whole list.
24468 (plain-list (forward-char)
24469 (org-forward-paragraph))
24470 (otherwise (goto-char end))))
24471 ((>= (point) contents-end) (goto-char end))
24472 ((>= (point) contents-begin)
24473 ;; This can only happen on paragraphs and plain lists.
24474 (cl-case type
24475 (paragraph (goto-char end))
24476 ;; At a plain list, try to move to second element in
24477 ;; first item, if possible.
24478 (plain-list (end-of-line)
24479 (org-forward-paragraph))))
24480 ;; When contents start on the middle of a line (e.g. in
24481 ;; items and footnote definitions), try to reach first
24482 ;; element starting after current line.
24483 ((> (line-end-position) contents-begin)
24484 (end-of-line)
24485 (org-forward-paragraph))
24486 (t (goto-char contents-begin)))))
24488 (defun org-backward-paragraph ()
24489 "Move backward to start of previous paragraph or equivalent.
24491 The function moves point to the beginning of the current
24492 structural element, which can be a paragraph, a table, a list
24493 item, etc., or to the beginning of the previous visible one if
24494 point is already there. It also provides some special moves for
24495 convenience:
24497 - On an affiliated keyword, jump to the first one.
24498 - On a table or a property drawer, move to its beginning.
24499 - On a verse or source block, stop before blank lines."
24500 (interactive)
24501 (when (bobp) (user-error "Cannot move further up"))
24502 (let* ((deactivate-mark nil)
24503 (element (org-element-at-point))
24504 (type (org-element-type element))
24505 (contents-begin (org-element-property :contents-begin element))
24506 (contents-end (org-element-property :contents-end element))
24507 (post-affiliated (org-element-property :post-affiliated element))
24508 (begin (org-element-property :begin element)))
24509 (cond
24510 ((not element) (goto-char (point-min)))
24511 ((= (point) begin)
24512 (backward-char)
24513 (org-backward-paragraph))
24514 ((<= (point) post-affiliated) (goto-char begin))
24515 ((memq type '(node-property table-row))
24516 (goto-char (org-element-property
24517 :post-affiliated (org-element-property :parent element))))
24518 ((memq type '(property-drawer table)) (goto-char begin))
24519 ((memq type '(src-block verse-block))
24520 (when (eq type 'src-block)
24521 (setq contents-begin
24522 (save-excursion (goto-char begin) (forward-line) (point))))
24523 (if (= (point) contents-begin) (goto-char post-affiliated)
24524 ;; Inside a verse block, see blank lines as paragraph
24525 ;; separators.
24526 (let ((origin (point)))
24527 (skip-chars-backward " \r\t\n" contents-begin)
24528 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24529 (skip-chars-forward " \r\t\n" origin)
24530 (if (= (point) origin) (goto-char contents-begin)
24531 (beginning-of-line))))))
24532 ((not contents-begin) (goto-char (or post-affiliated begin)))
24533 ((eq type 'paragraph)
24534 (goto-char contents-begin)
24535 ;; When at first paragraph in an item or a footnote definition,
24536 ;; move directly to beginning of line.
24537 (let ((parent-contents
24538 (org-element-property
24539 :contents-begin (org-element-property :parent element))))
24540 (when (and parent-contents (= parent-contents contents-begin))
24541 (beginning-of-line))))
24542 ;; At the end of a greater element, move to the beginning of the
24543 ;; last element within.
24544 ((>= (point) contents-end)
24545 (goto-char (1- contents-end))
24546 (org-backward-paragraph))
24547 (t (goto-char (or post-affiliated begin))))
24548 ;; Ensure we never leave point invisible.
24549 (when (org-invisible-p (point)) (beginning-of-visual-line))))
24551 (defun org-forward-element ()
24552 "Move forward by one element.
24553 Move to the next element at the same level, when possible."
24554 (interactive)
24555 (cond ((eobp) (user-error "Cannot move further down"))
24556 ((org-with-limited-levels (org-at-heading-p))
24557 (let ((origin (point)))
24558 (goto-char (org-end-of-subtree nil t))
24559 (unless (org-with-limited-levels (org-at-heading-p))
24560 (goto-char origin)
24561 (user-error "Cannot move further down"))))
24563 (let* ((elem (org-element-at-point))
24564 (end (org-element-property :end elem))
24565 (parent (org-element-property :parent elem)))
24566 (cond ((and parent (= (org-element-property :contents-end parent) end))
24567 (goto-char (org-element-property :end parent)))
24568 ((integer-or-marker-p end) (goto-char end))
24569 (t (message "No element at point")))))))
24571 (defun org-backward-element ()
24572 "Move backward by one element.
24573 Move to the previous element at the same level, when possible."
24574 (interactive)
24575 (cond ((bobp) (user-error "Cannot move further up"))
24576 ((org-with-limited-levels (org-at-heading-p))
24577 ;; At a headline, move to the previous one, if any, or stay
24578 ;; here.
24579 (let ((origin (point)))
24580 (org-with-limited-levels (org-backward-heading-same-level 1))
24581 ;; When current headline has no sibling above, move to its
24582 ;; parent.
24583 (when (= (point) origin)
24584 (or (org-with-limited-levels (org-up-heading-safe))
24585 (progn (goto-char origin)
24586 (user-error "Cannot move further up"))))))
24588 (let* ((elem (org-element-at-point))
24589 (beg (org-element-property :begin elem)))
24590 (cond
24591 ;; Move to beginning of current element if point isn't
24592 ;; there already.
24593 ((null beg) (message "No element at point"))
24594 ((/= (point) beg) (goto-char beg))
24595 (t (goto-char beg)
24596 (skip-chars-backward " \r\t\n")
24597 (unless (bobp)
24598 (let ((prev (org-element-at-point)))
24599 (goto-char (org-element-property :begin prev))
24600 (while (and (setq prev (org-element-property :parent prev))
24601 (<= (org-element-property :end prev) beg))
24602 (goto-char (org-element-property :begin prev)))))))))))
24604 (defun org-up-element ()
24605 "Move to upper element."
24606 (interactive)
24607 (if (org-with-limited-levels (org-at-heading-p))
24608 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24609 (let* ((elem (org-element-at-point))
24610 (parent (org-element-property :parent elem)))
24611 (if parent (goto-char (org-element-property :begin parent))
24612 (if (org-with-limited-levels (org-before-first-heading-p))
24613 (user-error "No surrounding element")
24614 (org-with-limited-levels (org-back-to-heading)))))))
24616 (defun org-down-element ()
24617 "Move to inner element."
24618 (interactive)
24619 (let ((element (org-element-at-point)))
24620 (cond
24621 ((memq (org-element-type element) '(plain-list table))
24622 (goto-char (org-element-property :contents-begin element))
24623 (forward-char))
24624 ((memq (org-element-type element) org-element-greater-elements)
24625 ;; If contents are hidden, first disclose them.
24626 (when (org-invisible-p (line-end-position)) (org-cycle))
24627 (goto-char (or (org-element-property :contents-begin element)
24628 (user-error "No content for this element"))))
24629 (t (user-error "No inner element")))))
24631 (defun org-drag-element-backward ()
24632 "Move backward element at point."
24633 (interactive)
24634 (let ((elem (or (org-element-at-point)
24635 (user-error "No element at point"))))
24636 (if (eq (org-element-type elem) 'headline)
24637 ;; Preserve point when moving a whole tree, even if point was
24638 ;; on blank lines below the headline.
24639 (let ((offset (skip-chars-backward " \t\n")))
24640 (unwind-protect (org-move-subtree-up)
24641 (forward-char (- offset))))
24642 (let ((prev-elem
24643 (save-excursion
24644 (goto-char (org-element-property :begin elem))
24645 (skip-chars-backward " \r\t\n")
24646 (unless (bobp)
24647 (let* ((beg (org-element-property :begin elem))
24648 (prev (org-element-at-point))
24649 (up prev))
24650 (while (and (setq up (org-element-property :parent up))
24651 (<= (org-element-property :end up) beg))
24652 (setq prev up))
24653 prev)))))
24654 ;; Error out if no previous element or previous element is
24655 ;; a parent of the current one.
24656 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24657 (user-error "Cannot drag element backward")
24658 (let ((pos (point)))
24659 (org-element-swap-A-B prev-elem elem)
24660 (goto-char (+ (org-element-property :begin prev-elem)
24661 (- pos (org-element-property :begin elem))))))))))
24663 (defun org-drag-element-forward ()
24664 "Move forward element at point."
24665 (interactive)
24666 (let* ((pos (point))
24667 (elem (or (org-element-at-point)
24668 (user-error "No element at point"))))
24669 (when (= (point-max) (org-element-property :end elem))
24670 (user-error "Cannot drag element forward"))
24671 (goto-char (org-element-property :end elem))
24672 (let ((next-elem (org-element-at-point)))
24673 (when (or (org-element-nested-p elem next-elem)
24674 (and (eq (org-element-type next-elem) 'headline)
24675 (not (eq (org-element-type elem) 'headline))))
24676 (goto-char pos)
24677 (user-error "Cannot drag element forward"))
24678 ;; Compute new position of point: it's shifted by NEXT-ELEM
24679 ;; body's length (without final blanks) and by the length of
24680 ;; blanks between ELEM and NEXT-ELEM.
24681 (let ((size-next (- (save-excursion
24682 (goto-char (org-element-property :end next-elem))
24683 (skip-chars-backward " \r\t\n")
24684 (forward-line)
24685 ;; Small correction if buffer doesn't end
24686 ;; with a newline character.
24687 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24688 (org-element-property :begin next-elem)))
24689 (size-blank (- (org-element-property :end elem)
24690 (save-excursion
24691 (goto-char (org-element-property :end elem))
24692 (skip-chars-backward " \r\t\n")
24693 (forward-line)
24694 (point)))))
24695 (org-element-swap-A-B elem next-elem)
24696 (goto-char (+ pos size-next size-blank))))))
24698 (defun org-drag-line-forward (arg)
24699 "Drag the line at point ARG lines forward."
24700 (interactive "p")
24701 (dotimes (_ (abs arg))
24702 (let ((c (current-column)))
24703 (if (< 0 arg)
24704 (progn
24705 (beginning-of-line 2)
24706 (transpose-lines 1)
24707 (beginning-of-line 0))
24708 (transpose-lines 1)
24709 (beginning-of-line -1))
24710 (org-move-to-column c))))
24712 (defun org-drag-line-backward (arg)
24713 "Drag the line at point ARG lines backward."
24714 (interactive "p")
24715 (org-drag-line-forward (- arg)))
24717 (defun org-mark-element ()
24718 "Put point at beginning of this element, mark at end.
24720 Interactively, if this command is repeated or (in Transient Mark
24721 mode) if the mark is active, it marks the next element after the
24722 ones already marked."
24723 (interactive)
24724 (let (deactivate-mark)
24725 (if (and (called-interactively-p 'any)
24726 (or (and (eq last-command this-command) (mark t))
24727 (and transient-mark-mode mark-active)))
24728 (set-mark
24729 (save-excursion
24730 (goto-char (mark))
24731 (goto-char (org-element-property :end (org-element-at-point)))))
24732 (let ((element (org-element-at-point)))
24733 (end-of-line)
24734 (push-mark (org-element-property :end element) t t)
24735 (goto-char (org-element-property :begin element))))))
24737 (defun org-narrow-to-element ()
24738 "Narrow buffer to current element."
24739 (interactive)
24740 (let ((elem (org-element-at-point)))
24741 (cond
24742 ((eq (car elem) 'headline)
24743 (narrow-to-region
24744 (org-element-property :begin elem)
24745 (org-element-property :end elem)))
24746 ((memq (car elem) org-element-greater-elements)
24747 (narrow-to-region
24748 (org-element-property :contents-begin elem)
24749 (org-element-property :contents-end elem)))
24751 (narrow-to-region
24752 (org-element-property :begin elem)
24753 (org-element-property :end elem))))))
24755 (defun org-transpose-element ()
24756 "Transpose current and previous elements, keeping blank lines between.
24757 Point is moved after both elements."
24758 (interactive)
24759 (org-skip-whitespace)
24760 (let ((end (org-element-property :end (org-element-at-point))))
24761 (org-drag-element-backward)
24762 (goto-char end)))
24764 (defun org-unindent-buffer ()
24765 "Un-indent the visible part of the buffer.
24766 Relative indentation (between items, inside blocks, etc.) isn't
24767 modified."
24768 (interactive)
24769 (unless (eq major-mode 'org-mode)
24770 (user-error "Cannot un-indent a buffer not in Org mode"))
24771 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24772 (unindent-tree
24773 (lambda (contents)
24774 (dolist (element (reverse contents))
24775 (if (memq (org-element-type element) '(headline section))
24776 (funcall unindent-tree (org-element-contents element))
24777 (save-excursion
24778 (save-restriction
24779 (narrow-to-region
24780 (org-element-property :begin element)
24781 (org-element-property :end element))
24782 (org-do-remove-indentation))))))))
24783 (funcall unindent-tree (org-element-contents parse-tree))))
24785 (defun org-show-children (&optional level)
24786 "Show all direct subheadings of this heading.
24787 Prefix arg LEVEL is how many levels below the current level
24788 should be shown. Default is enough to cause the following
24789 heading to appear."
24790 (interactive "p")
24791 ;; If `orgstruct-mode' is active, use the slower version.
24792 (if orgstruct-mode (call-interactively #'outline-show-children)
24793 (save-excursion
24794 (org-back-to-heading t)
24795 (let* ((current-level (funcall outline-level))
24796 (max-level (org-get-valid-level
24797 current-level
24798 (if level (prefix-numeric-value level) 1)))
24799 (end (save-excursion (org-end-of-subtree t t)))
24800 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24801 (past-first-child nil)
24802 ;; Make sure to skip inlinetasks.
24803 (re (format regexp-fmt
24804 current-level
24805 (cond
24806 ((not (featurep 'org-inlinetask)) "")
24807 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24809 (t (1- org-inlinetask-min-level))))))
24810 ;; Display parent heading.
24811 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24812 (forward-line)
24813 ;; Display children. First child may be deeper than expected
24814 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24815 ;; MAX-LEVEL accordingly.
24816 (while (re-search-forward re end t)
24817 (unless past-first-child
24818 (setq re (format regexp-fmt
24819 current-level
24820 (max (funcall outline-level) max-level)))
24821 (setq past-first-child t))
24822 (outline-flag-region
24823 (line-end-position 0) (line-end-position) nil))))))
24825 (defun org-show-subtree ()
24826 "Show everything after this heading at deeper levels."
24827 (interactive)
24828 (outline-flag-region
24829 (point)
24830 (save-excursion
24831 (org-end-of-subtree t t))
24832 nil))
24834 (defun org-show-entry ()
24835 "Show the body directly following this heading.
24836 Show the heading too, if it is currently invisible."
24837 (interactive)
24838 (save-excursion
24839 (ignore-errors
24840 (org-back-to-heading t)
24841 (outline-flag-region
24842 (max (point-min) (1- (point)))
24843 (save-excursion
24844 (if (re-search-forward
24845 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24846 (match-beginning 1)
24847 (point-max)))
24848 nil)
24849 (org-cycle-hide-drawers 'children))))
24851 (defun org-make-options-regexp (kwds &optional extra)
24852 "Make a regular expression for keyword lines.
24853 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24854 when non-nil, is a regexp matching keywords names."
24855 (concat "^[ \t]*#\\+\\("
24856 (regexp-opt kwds)
24857 (and extra (concat (and kwds "\\|") extra))
24858 "\\):[ \t]*\\(.*\\)"))
24860 ;;;; Integration with and fixes for other packages
24862 ;;; Imenu support
24864 (defvar-local org-imenu-markers nil
24865 "All markers currently used by Imenu.")
24867 (defun org-imenu-new-marker (&optional pos)
24868 "Return a new marker for use by Imenu, and remember the marker."
24869 (let ((m (make-marker)))
24870 (move-marker m (or pos (point)))
24871 (push m org-imenu-markers)
24874 (defun org-imenu-get-tree ()
24875 "Produce the index for Imenu."
24876 (dolist (x org-imenu-markers) (move-marker x nil))
24877 (setq org-imenu-markers nil)
24878 (let* ((case-fold-search nil)
24879 (n org-imenu-depth)
24880 (re (concat "^" (org-get-limited-outline-regexp)))
24881 (subs (make-vector (1+ n) nil))
24882 (last-level 0)
24883 m level head0 head)
24884 (org-with-wide-buffer
24885 (goto-char (point-max))
24886 (while (re-search-backward re nil t)
24887 (setq level (org-reduced-level (funcall outline-level)))
24888 (when (and (<= level n)
24889 (looking-at org-complex-heading-regexp)
24890 (setq head0 (match-string-no-properties 4)))
24891 (setq head (org-link-display-format head0)
24892 m (org-imenu-new-marker))
24893 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24894 (if (>= level last-level)
24895 (push (cons head m) (aref subs level))
24896 (push (cons head (aref subs (1+ level))) (aref subs level))
24897 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24898 (setq last-level level))))
24899 (aref subs 1)))
24901 (eval-after-load "imenu"
24902 '(progn
24903 (add-hook 'imenu-after-jump-hook
24904 (lambda ()
24905 (when (derived-mode-p 'org-mode)
24906 (org-show-context 'org-goto))))))
24908 (defun org-link-display-format (s)
24909 "Replace links in string S with their description.
24910 If there is no description, use the link target."
24911 (save-match-data
24912 (replace-regexp-in-string
24913 org-bracket-link-analytic-regexp
24914 (lambda (m)
24915 (if (match-end 5) (match-string 5 m)
24916 (concat (match-string 1 m) (match-string 3 m))))
24917 s nil t)))
24919 (defun org-toggle-link-display ()
24920 "Toggle the literal or descriptive display of links."
24921 (interactive)
24922 (if org-descriptive-links
24923 (progn (org-remove-from-invisibility-spec '(org-link))
24924 (org-restart-font-lock)
24925 (setq org-descriptive-links nil))
24926 (progn (add-to-invisibility-spec '(org-link))
24927 (org-restart-font-lock)
24928 (setq org-descriptive-links t))))
24930 ;; Speedbar support
24932 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24933 "Overlay marking the agenda restriction line in speedbar.")
24934 (overlay-put org-speedbar-restriction-lock-overlay
24935 'face 'org-agenda-restriction-lock)
24936 (overlay-put org-speedbar-restriction-lock-overlay
24937 'help-echo "Agendas are currently limited to this item.")
24938 (delete-overlay org-speedbar-restriction-lock-overlay)
24940 (defun org-speedbar-set-agenda-restriction ()
24941 "Restrict future agenda commands to the location at point in speedbar.
24942 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24943 (interactive)
24944 (require 'org-agenda)
24945 (let (p m tp np dir txt)
24946 (cond
24947 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24948 'org-imenu t))
24949 (setq m (get-text-property p 'org-imenu-marker))
24950 (with-current-buffer (marker-buffer m)
24951 (goto-char m)
24952 (org-agenda-set-restriction-lock 'subtree)))
24953 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24954 'speedbar-function 'speedbar-find-file))
24955 (setq tp (previous-single-property-change
24956 (1+ p) 'speedbar-function)
24957 np (next-single-property-change
24958 tp 'speedbar-function)
24959 dir (speedbar-line-directory)
24960 txt (buffer-substring-no-properties (or tp (point-min))
24961 (or np (point-max))))
24962 (with-current-buffer (find-file-noselect
24963 (let ((default-directory dir))
24964 (expand-file-name txt)))
24965 (unless (derived-mode-p 'org-mode)
24966 (user-error "Cannot restrict to non-Org mode file"))
24967 (org-agenda-set-restriction-lock 'file)))
24968 (t (user-error "Don't know how to restrict Org mode agenda")))
24969 (move-overlay org-speedbar-restriction-lock-overlay
24970 (point-at-bol) (point-at-eol))
24971 (setq current-prefix-arg nil)
24972 (org-agenda-maybe-redo)))
24974 (defvar speedbar-file-key-map)
24975 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24976 (eval-after-load "speedbar"
24977 '(progn
24978 (speedbar-add-supported-extension ".org")
24979 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24980 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24981 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24982 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24983 (add-hook 'speedbar-visiting-tag-hook
24984 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24986 ;;; Fixes and Hacks for problems with other packages
24988 (defun org--flyspell-object-check-p (element)
24989 "Non-nil when Flyspell can check object at point.
24990 ELEMENT is the element at point."
24991 (let ((object (save-excursion
24992 (when (looking-at-p "\\>") (backward-char))
24993 (org-element-context element))))
24994 (cl-case (org-element-type object)
24995 ;; Prevent checks in links due to keybinding conflict with
24996 ;; Flyspell.
24997 ((code entity export-snippet inline-babel-call
24998 inline-src-block line-break latex-fragment link macro
24999 statistics-cookie target timestamp verbatim)
25000 nil)
25001 (footnote-reference
25002 ;; Only in inline footnotes, within the definition.
25003 (and (eq (org-element-property :type object) 'inline)
25004 (< (save-excursion
25005 (goto-char (org-element-property :begin object))
25006 (search-forward ":" nil t 2))
25007 (point))))
25008 (otherwise t))))
25010 (defun org-mode-flyspell-verify ()
25011 "Function used for `flyspell-generic-check-word-predicate'."
25012 (if (org-at-heading-p)
25013 ;; At a headline or an inlinetask, check title only. This is
25014 ;; faster than relying on `org-element-at-point'.
25015 (and (save-excursion (beginning-of-line)
25016 (and (let ((case-fold-search t))
25017 (not (looking-at-p "\\*+ END[ \t]*$")))
25018 (let ((case-fold-search nil))
25019 (looking-at org-complex-heading-regexp))))
25020 (match-beginning 4)
25021 (>= (point) (match-beginning 4))
25022 (or (not (match-beginning 5))
25023 (< (point) (match-beginning 5))))
25024 (let* ((element (org-element-at-point))
25025 (post-affiliated (org-element-property :post-affiliated element)))
25026 (cond
25027 ;; Ignore checks in all affiliated keywords but captions.
25028 ((< (point) post-affiliated)
25029 (and (save-excursion
25030 (beginning-of-line)
25031 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25032 (> (point) (match-end 0))
25033 (org--flyspell-object-check-p element)))
25034 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25035 ((let ((log (org-log-into-drawer)))
25036 (and log
25037 (let ((drawer (org-element-lineage element '(drawer))))
25038 (and drawer
25039 (eq (compare-strings
25040 log nil nil
25041 (org-element-property :drawer-name drawer) nil nil t)
25042 t)))))
25043 nil)
25045 (cl-case (org-element-type element)
25046 ((comment quote-section) t)
25047 (comment-block
25048 ;; Allow checks between block markers, not on them.
25049 (and (> (line-beginning-position) post-affiliated)
25050 (save-excursion
25051 (end-of-line)
25052 (skip-chars-forward " \r\t\n")
25053 (< (point) (org-element-property :end element)))))
25054 ;; Arbitrary list of keywords where checks are meaningful.
25055 ;; Make sure point is on the value part of the element.
25056 (keyword
25057 (and (member (org-element-property :key element)
25058 '("DESCRIPTION" "TITLE"))
25059 (save-excursion
25060 (search-backward ":" (line-beginning-position) t))))
25061 ;; Check is globally allowed in paragraphs verse blocks and
25062 ;; table rows (after affiliated keywords) but some objects
25063 ;; must not be affected.
25064 ((paragraph table-row verse-block)
25065 (let ((cbeg (org-element-property :contents-begin element))
25066 (cend (org-element-property :contents-end element)))
25067 (and cbeg (>= (point) cbeg) (< (point) cend)
25068 (org--flyspell-object-check-p element))))))))))
25069 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25071 (defun org-remove-flyspell-overlays-in (beg end)
25072 "Remove flyspell overlays in region."
25073 (and (bound-and-true-p flyspell-mode)
25074 (fboundp 'flyspell-delete-region-overlays)
25075 (flyspell-delete-region-overlays beg end)))
25077 (defvar flyspell-delayed-commands)
25078 (eval-after-load "flyspell"
25079 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25081 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25082 (eval-after-load "bookmark"
25083 '(if (boundp 'bookmark-after-jump-hook)
25084 ;; We can use the hook
25085 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25086 ;; Hook not available, use advice
25087 (defadvice bookmark-jump (after org-make-visible activate)
25088 "Make the position visible."
25089 (org-bookmark-jump-unhide))))
25091 ;; Make sure saveplace shows the location if it was hidden
25092 (eval-after-load "saveplace"
25093 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25094 "Make the position visible."
25095 (org-bookmark-jump-unhide)))
25097 ;; Make sure ecb shows the location if it was hidden
25098 (eval-after-load "ecb"
25099 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25100 "Make hierarchy visible when jumping into location from ECB tree buffer."
25101 (when (derived-mode-p 'org-mode)
25102 (org-show-context))))
25104 (defun org-bookmark-jump-unhide ()
25105 "Unhide the current position, to show the bookmark location."
25106 (and (derived-mode-p 'org-mode)
25107 (or (org-invisible-p)
25108 (save-excursion (goto-char (max (point-min) (1- (point))))
25109 (org-invisible-p)))
25110 (org-show-context 'bookmark-jump)))
25112 (defun org-mark-jump-unhide ()
25113 "Make the point visible with `org-show-context' after jumping to the mark."
25114 (when (and (derived-mode-p 'org-mode)
25115 (org-invisible-p))
25116 (org-show-context 'mark-goto)))
25118 (eval-after-load "simple"
25119 '(defadvice pop-to-mark-command (after org-make-visible activate)
25120 "Make the point visible with `org-show-context'."
25121 (org-mark-jump-unhide)))
25123 (eval-after-load "simple"
25124 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25125 "Make the point visible with `org-show-context'."
25126 (org-mark-jump-unhide)))
25128 (eval-after-load "simple"
25129 '(defadvice pop-global-mark (after org-make-visible activate)
25130 "Make the point visible with `org-show-context'."
25131 (org-mark-jump-unhide)))
25133 ;; Make session.el ignore our circular variable
25134 (defvar session-globals-exclude)
25135 (eval-after-load "session"
25136 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25138 ;;;; Finish up
25140 (provide 'org)
25142 (run-hooks 'org-load-hook)
25144 ;;; org.el ends here