Preserve targets order according to rules
[org-mode/org-tableheadings.git] / lisp / org.el
blob8cd8cc8badf67e1c38624290daef7900eda48881
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-nested-p "org-element" (elem-a elem-b))
141 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
142 (declare-function org-element-property "org-element" (property element))
143 (declare-function org-element-put-property "org-element" (element property value))
144 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
145 (declare-function org-element-type "org-element" (element))
146 (declare-function org-element-update-syntax "org-element" ())
147 (declare-function org-id-find-id-file "org-id" (id))
148 (declare-function org-id-get-create "org-id" (&optional force))
149 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
150 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
151 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
152 (declare-function org-plot/gnuplot "org-plot" (&optional params))
153 (declare-function org-table-align "org-table" ())
154 (declare-function org-table-begin "org-table" (&optional table-type))
155 (declare-function org-table-beginning-of-field "org-table" (&optional n))
156 (declare-function org-table-blank-field "org-table" ())
157 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
158 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
159 (declare-function org-table-cut-region "org-table" (beg end))
160 (declare-function org-table-edit-field "org-table" (arg))
161 (declare-function org-table-end "org-table" (&optional table-type))
162 (declare-function org-table-end-of-field "org-table" (&optional n))
163 (declare-function org-table-insert-row "org-table" (&optional arg))
164 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
165 (declare-function org-table-maybe-eval-formula "org-table" ())
166 (declare-function org-table-maybe-recalculate-line "org-table" ())
167 (declare-function org-table-next-row "org-table" ())
168 (declare-function org-table-paste-rectangle "org-table" ())
169 (declare-function org-table-recalculate "org-table" (&optional all noalign))
170 (declare-function org-table-wrap-region "org-table" (arg))
171 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
172 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
173 (declare-function orgtbl-mode "org-table" (&optional arg))
174 (declare-function org-export-get-backend "ox" (name))
175 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
176 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
178 (defsubst org-uniquify (list)
179 "Non-destructively remove duplicate elements from LIST."
180 (let ((res (copy-sequence list))) (delete-dups res)))
182 (defsubst org-get-at-bol (property)
183 "Get text property PROPERTY at the beginning of line."
184 (get-text-property (point-at-bol) property))
186 (defsubst org-trim (s &optional keep-lead)
187 "Remove whitespace at the beginning and the end of string S.
188 When optional argument KEEP-LEAD is non-nil, removing blank lines
189 at the beginning of the string does not affect leading indentation."
190 (replace-regexp-in-string
191 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
192 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
194 ;; load languages based on value of `org-babel-load-languages'
195 (defvar org-babel-load-languages)
197 ;;;###autoload
198 (defun org-babel-do-load-languages (sym value)
199 "Load the languages defined in `org-babel-load-languages'."
200 (set-default sym value)
201 (dolist (pair org-babel-load-languages)
202 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
203 (if active
204 (require (intern (concat "ob-" lang)))
205 (funcall 'fmakunbound
206 (intern (concat "org-babel-execute:" lang)))
207 (funcall 'fmakunbound
208 (intern (concat "org-babel-expand-body:" lang)))))))
210 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
211 ;;;###autoload
212 (defun org-babel-load-file (file &optional compile)
213 "Load Emacs Lisp source code blocks in the Org FILE.
214 This function exports the source code using `org-babel-tangle'
215 and then loads the resulting file using `load-file'. With prefix
216 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
217 file to byte-code before it is loaded."
218 (interactive "fFile to load: \nP")
219 (let* ((age (lambda (file)
220 (float-time
221 (time-subtract (current-time)
222 (nth 5 (or (file-attributes (file-truename file))
223 (file-attributes file)))))))
224 (base-name (file-name-sans-extension file))
225 (exported-file (concat base-name ".el")))
226 ;; tangle if the Org file is newer than the elisp file
227 (unless (and (file-exists-p exported-file)
228 (> (funcall age file) (funcall age exported-file)))
229 ;; Tangle-file traversal returns reversed list of tangled files
230 ;; and we want to evaluate the first target.
231 (setq exported-file
232 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
233 (message "%s %s"
234 (if compile
235 (progn (byte-compile-file exported-file 'load)
236 "Compiled and loaded")
237 (progn (load-file exported-file) "Loaded"))
238 exported-file)))
240 (defcustom org-babel-load-languages '((emacs-lisp . t))
241 "Languages which can be evaluated in Org buffers.
242 This list can be used to load support for any of the languages
243 below, note that each language will depend on a different set of
244 system executables and/or Emacs modes. When a language is
245 \"loaded\", then code blocks in that language can be evaluated
246 with `org-babel-execute-src-block' bound by default to C-c
247 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
248 be set to remove code block evaluation from the C-c C-c
249 keybinding. By default only Emacs Lisp (which has no
250 requirements) is loaded."
251 :group 'org-babel
252 :set 'org-babel-do-load-languages
253 :version "24.1"
254 :type '(alist :tag "Babel Languages"
255 :key-type
256 (choice
257 (const :tag "Awk" awk)
258 (const :tag "C" C)
259 (const :tag "R" R)
260 (const :tag "Asymptote" asymptote)
261 (const :tag "Calc" calc)
262 (const :tag "Clojure" clojure)
263 (const :tag "CSS" css)
264 (const :tag "Ditaa" ditaa)
265 (const :tag "Dot" dot)
266 (const :tag "Emacs Lisp" emacs-lisp)
267 (const :tag "Forth" forth)
268 (const :tag "Fortran" fortran)
269 (const :tag "Gnuplot" gnuplot)
270 (const :tag "Haskell" haskell)
271 (const :tag "IO" io)
272 (const :tag "J" J)
273 (const :tag "Java" java)
274 (const :tag "Javascript" js)
275 (const :tag "LaTeX" latex)
276 (const :tag "Ledger" ledger)
277 (const :tag "Lilypond" lilypond)
278 (const :tag "Lisp" lisp)
279 (const :tag "Makefile" makefile)
280 (const :tag "Maxima" maxima)
281 (const :tag "Matlab" matlab)
282 (const :tag "Mscgen" mscgen)
283 (const :tag "Ocaml" ocaml)
284 (const :tag "Octave" octave)
285 (const :tag "Org" org)
286 (const :tag "Perl" perl)
287 (const :tag "Pico Lisp" picolisp)
288 (const :tag "PlantUML" plantuml)
289 (const :tag "Python" python)
290 (const :tag "Ruby" ruby)
291 (const :tag "Sass" sass)
292 (const :tag "Scala" scala)
293 (const :tag "Scheme" scheme)
294 (const :tag "Screen" screen)
295 (const :tag "Shell Script" shell)
296 (const :tag "Shen" shen)
297 (const :tag "Sql" sql)
298 (const :tag "Sqlite" sqlite)
299 (const :tag "Stan" stan)
300 (const :tag "ebnf2ps" ebnf2ps))
301 :value-type (boolean :tag "Activate" :value t)))
303 ;;;; Customization variables
304 (defcustom org-clone-delete-id nil
305 "Remove ID property of clones of a subtree.
306 When non-nil, clones of a subtree don't inherit the ID property.
307 Otherwise they inherit the ID property with a new unique
308 identifier."
309 :type 'boolean
310 :version "24.1"
311 :group 'org-id)
313 ;;; Version
314 (org-check-version)
316 ;;;###autoload
317 (defun org-version (&optional here full message)
318 "Show the Org version.
319 Interactively, or when MESSAGE is non-nil, show it in echo area.
320 With prefix argument, or when HERE is non-nil, insert it at point.
321 In non-interactive uses, a reduced version string is output unless
322 FULL is given."
323 (interactive (list current-prefix-arg t (not current-prefix-arg)))
324 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
325 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
326 (load-suffixes (list ".el"))
327 (org-install-dir
328 (ignore-errors (org-find-library-dir "org-loaddefs"))))
329 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
330 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
331 (let* ((load-suffixes save-load-suffixes)
332 (release (org-release))
333 (git-version (org-git-version))
334 (version (format "Org mode version %s (%s @ %s)"
335 release
336 git-version
337 (if org-install-dir
338 (if (string= org-dir org-install-dir)
339 org-install-dir
340 (concat "mixed installation! "
341 org-install-dir
342 " and "
343 org-dir))
344 "org-loaddefs.el can not be found!")))
345 (version1 (if full version release)))
346 (when here (insert version1))
347 (when message (message "%s" version1))
348 version1)))
350 (defconst org-version (org-version))
353 ;;; Syntax Constants
355 ;;;; Block
357 (defconst org-block-regexp
358 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
359 "Regular expression for hiding blocks.")
361 (defconst org-dblock-start-re
362 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
363 "Matches the start line of a dynamic block, with parameters.")
365 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
366 "Matches the end of a dynamic block.")
368 ;;;; Clock and Planning
370 (defconst org-clock-string "CLOCK:"
371 "String used as prefix for timestamps clocking work hours on an item.")
373 (defvar org-closed-string "CLOSED:"
374 "String used as the prefix for timestamps logging closing a TODO entry.")
376 (defvar org-deadline-string "DEADLINE:"
377 "String to mark deadline entries.
378 \\<org-mode-map>
379 A deadline is this string, followed by a time stamp. It must be
380 a word, terminated by a colon. You can insert a schedule keyword
381 and a timestamp with `\\[org-deadline]'.")
383 (defvar org-scheduled-string "SCHEDULED:"
384 "String to mark scheduled TODO entries.
385 \\<org-mode-map>
386 A schedule is this string, followed by a time stamp. It must be
387 a word, terminated by a colon. You can insert a schedule keyword
388 and a timestamp with `\\[org-schedule]'.")
390 (defconst org-ds-keyword-length
391 (+ 2
392 (apply #'max
393 (mapcar #'length
394 (list org-deadline-string org-scheduled-string
395 org-clock-string org-closed-string))))
396 "Maximum length of the DEADLINE and SCHEDULED keywords.")
398 (defconst org-planning-line-re
399 (concat "^[ \t]*"
400 (regexp-opt
401 (list org-closed-string org-deadline-string org-scheduled-string)
403 "Matches a line with planning info.
404 Matched keyword is in group 1.")
406 (defconst org-clock-line-re
407 (concat "^[ \t]*" org-clock-string)
408 "Matches a line with clock info.")
410 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
411 "Matches the DEADLINE keyword.")
413 (defconst org-deadline-time-regexp
414 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
415 "Matches the DEADLINE keyword together with a time stamp.")
417 (defconst org-deadline-time-hour-regexp
418 (concat "\\<" org-deadline-string
419 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
420 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
422 (defconst org-deadline-line-regexp
423 (concat "\\<\\(" org-deadline-string "\\).*")
424 "Matches the DEADLINE keyword and the rest of the line.")
426 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
427 "Matches the SCHEDULED keyword.")
429 (defconst org-scheduled-time-regexp
430 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
431 "Matches the SCHEDULED keyword together with a time stamp.")
433 (defconst org-scheduled-time-hour-regexp
434 (concat "\\<" org-scheduled-string
435 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
436 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
438 (defconst org-closed-time-regexp
439 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
440 "Matches the CLOSED keyword together with a time stamp.")
442 (defconst org-keyword-time-regexp
443 (concat "\\<"
444 (regexp-opt
445 (list org-scheduled-string org-deadline-string org-closed-string
446 org-clock-string)
448 " *[[<]\\([^]>]+\\)[]>]")
449 "Matches any of the 4 keywords, together with the time stamp.")
451 (defconst org-keyword-time-not-clock-regexp
452 (concat
453 "\\<"
454 (regexp-opt
455 (list org-scheduled-string org-deadline-string org-closed-string) t)
456 " *[[<]\\([^]>]+\\)[]>]")
457 "Matches any of the 3 keywords, together with the time stamp.")
459 (defconst org-maybe-keyword-time-regexp
460 (concat "\\(\\<"
461 (regexp-opt
462 (list org-scheduled-string org-deadline-string org-closed-string
463 org-clock-string)
465 "\\)?"
466 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
467 "\\|"
468 "<%%([^\r\n>]*>\\)")
469 "Matches a timestamp, possibly preceded by a keyword.")
471 (defconst org-all-time-keywords
472 (mapcar (lambda (w) (substring w 0 -1))
473 (list org-scheduled-string org-deadline-string
474 org-clock-string org-closed-string))
475 "List of time keywords.")
477 ;;;; Drawer
479 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
480 "Matches first or last line of a hidden block.
481 Group 1 contains drawer's name or \"END\".")
483 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
484 "Regular expression matching the first line of a property drawer.")
486 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
487 "Regular expression matching the last line of a property drawer.")
489 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
490 "Regular expression matching the first line of a clock drawer.")
492 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
493 "Regular expression matching the last line of a clock drawer.")
495 (defconst org-property-drawer-re
496 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
497 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
498 "[ \t]*:END:[ \t]*$")
499 "Matches an entire property drawer.")
501 (defconst org-clock-drawer-re
502 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
503 org-clock-drawer-end-re "\\)\n?")
504 "Matches an entire clock drawer.")
506 ;;;; Headline
508 (defconst org-heading-keyword-regexp-format
509 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
510 "Printf format for a regexp matching a headline with some keyword.
511 This regexp will match the headline of any node which has the
512 exact keyword that is put into the format. The keyword isn't in
513 any group by default, but the stars and the body are.")
515 (defconst org-heading-keyword-maybe-regexp-format
516 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
517 "Printf format for a regexp matching a headline, possibly with some keyword.
518 This regexp can match any headline with the specified keyword, or
519 without a keyword. The keyword isn't in any group by default,
520 but the stars and the body are.")
522 (defconst org-archive-tag "ARCHIVE"
523 "The tag that marks a subtree as archived.
524 An archived subtree does not open during visibility cycling, and does
525 not contribute to the agenda listings.")
527 (defconst org-comment-string "COMMENT"
528 "Entries starting with this keyword will never be exported.
529 \\<org-mode-map>
530 An entry can be toggled between COMMENT and normal with
531 `\\[org-toggle-comment]'.")
534 ;;;; LaTeX Environments and Fragments
536 (defconst org-latex-regexps
537 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
538 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
539 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
540 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
541 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
542 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
543 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
544 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
545 "Regular expressions for matching embedded LaTeX.")
547 ;;;; Node Property
549 (defconst org-effort-property "Effort"
550 "The property that is being used to keep track of effort estimates.
551 Effort estimates given in this property need to have the format H:MM.")
553 ;;;; Table
555 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
556 "Detect an org-type or table-type table.")
558 (defconst org-table-line-regexp "^[ \t]*|"
559 "Detect an org-type table line.")
561 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
562 "Detect an org-type table line.")
564 (defconst org-table-hline-regexp "^[ \t]*|-"
565 "Detect an org-type table hline.")
567 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
568 "Detect a table-type table hline.")
570 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
571 "Detect the first line outside a table when searching from within it.
572 This works for both table types.")
574 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
575 "Detect a #+TBLFM line.")
577 ;;;; Timestamp
579 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
580 "Regular expression for fast time stamp matching.")
582 (defconst org-ts-regexp-inactive
583 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
584 "Regular expression for fast inactive time stamp matching.")
586 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
587 "Regular expression for fast time stamp matching.")
589 (defconst org-ts-regexp0
590 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
591 "Regular expression matching time strings for analysis.
592 This one does not require the space after the date, so it can be used
593 on a string that terminates immediately after the date.")
595 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
596 "Regular expression matching time strings for analysis.")
598 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
599 "Regular expression matching time stamps, with groups.")
601 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
602 "Regular expression matching time stamps (also [..]), with groups.")
604 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
605 "Regular expression matching a time stamp range.")
607 (defconst org-tr-regexp-both
608 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
609 "Regular expression matching a time stamp range.")
611 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
612 org-ts-regexp "\\)?")
613 "Regular expression matching a time stamp or time stamp range.")
615 (defconst org-tsr-regexp-both
616 (concat org-ts-regexp-both "\\(--?-?"
617 org-ts-regexp-both "\\)?")
618 "Regular expression matching a time stamp or time stamp range.
619 The time stamps may be either active or inactive.")
621 (defconst org-repeat-re
622 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
623 "Regular expression for specifying repeated events.
624 After a match, group 1 contains the repeat expression.")
626 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
627 "Formats for `format-time-string' which are used for time stamps.")
630 ;;; The custom variables
632 (defgroup org nil
633 "Outline-based notes management and organizer."
634 :tag "Org"
635 :group 'outlines
636 :group 'calendar)
638 (defcustom org-mode-hook nil
639 "Mode hook for Org mode, run after the mode was turned on."
640 :group 'org
641 :type 'hook)
643 (defcustom org-load-hook nil
644 "Hook that is run after org.el has been loaded."
645 :group 'org
646 :type 'hook)
648 (defcustom org-log-buffer-setup-hook nil
649 "Hook that is run after an Org log buffer is created."
650 :group 'org
651 :version "24.1"
652 :type 'hook)
654 (defvar org-modules) ; defined below
655 (defvar org-modules-loaded nil
656 "Have the modules been loaded already?")
658 (defun org-load-modules-maybe (&optional force)
659 "Load all extensions listed in `org-modules'."
660 (when (or force (not org-modules-loaded))
661 (dolist (ext org-modules)
662 (condition-case nil (require ext)
663 (error (message "Problems while trying to load feature `%s'" ext))))
664 (setq org-modules-loaded t)))
666 (defun org-set-modules (var value)
667 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
668 (set var value)
669 (when (featurep 'org)
670 (org-load-modules-maybe 'force)
671 (org-element-cache-reset 'all)))
673 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
674 "Modules that should always be loaded together with org.el.
676 If a description starts with <C>, the file is not part of Emacs
677 and loading it will require that you have downloaded and properly
678 installed the Org mode distribution.
680 You can also use this system to load external packages (i.e. neither Org
681 core modules, nor modules from the CONTRIB directory). Just add symbols
682 to the end of the list. If the package is called org-xyz.el, then you need
683 to add the symbol `xyz', and the package must have a call to:
685 (provide \\='org-xyz)
687 For export specific modules, see also `org-export-backends'."
688 :group 'org
689 :set 'org-set-modules
690 :version "24.4"
691 :package-version '(Org . "8.0")
692 :type
693 '(set :greedy t
694 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
695 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
696 (const :tag " crypt: Encryption of subtrees" org-crypt)
697 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
698 (const :tag " docview: Links to doc-view buffers" org-docview)
699 (const :tag " eww: Store link to url of eww" org-eww)
700 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
701 (const :tag " habit: Track your consistency with habits" org-habit)
702 (const :tag " id: Global IDs for identifying entries" org-id)
703 (const :tag " info: Links to Info nodes" org-info)
704 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
705 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
706 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
707 (const :tag " mouse: Additional mouse support" org-mouse)
708 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
709 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
710 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
712 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
713 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
714 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
715 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
716 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
717 (const :tag "C collector: Collect properties into tables" org-collector)
718 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
719 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
720 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
721 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
722 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
723 (const :tag "C eval: Include command output as text" org-eval)
724 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
725 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
726 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
727 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
728 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
729 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
730 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
731 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
732 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
733 (const :tag "C man: Support for links to manpages in Org mode" org-man)
734 (const :tag "C mew: Links to Mew folders/messages" org-mew)
735 (const :tag "C mtags: Support for muse-like tags" org-mtags)
736 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
737 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
738 (const :tag "C registry: A registry for Org links" org-registry)
739 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
740 (const :tag "C secretary: Team management with org-mode" org-secretary)
741 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
742 (const :tag "C toc: Table of contents for Org buffer" org-toc)
743 (const :tag "C track: Keep up with Org mode development" org-track)
744 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
745 (const :tag "C vm: Links to VM folders/messages" org-vm)
746 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
747 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
748 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
750 (defvar org-export-registered-backends) ; From ox.el.
751 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
752 (declare-function org-export-backend-name "ox" (backend) t)
753 (defcustom org-export-backends '(ascii html icalendar latex odt)
754 "List of export back-ends that should be always available.
756 If a description starts with <C>, the file is not part of Emacs
757 and loading it will require that you have downloaded and properly
758 installed the Org mode distribution.
760 Unlike to `org-modules', libraries in this list will not be
761 loaded along with Org, but only once the export framework is
762 needed.
764 This variable needs to be set before org.el is loaded. If you
765 need to make a change while Emacs is running, use the customize
766 interface or run the following code, where VAL stands for the new
767 value of the variable, after updating it:
769 (progn
770 (setq org-export-registered-backends
771 (cl-remove-if-not
772 (lambda (backend)
773 (let ((name (org-export-backend-name backend)))
774 (or (memq name val)
775 (catch \\='parentp
776 (dolist (b val)
777 (and (org-export-derived-backend-p b name)
778 (throw \\='parentp t)))))))
779 org-export-registered-backends))
780 (let ((new-list (mapcar #\\='org-export-backend-name
781 org-export-registered-backends)))
782 (dolist (backend val)
783 (cond
784 ((not (load (format \"ox-%s\" backend) t t))
785 (message \"Problems while trying to load export back-end \\=`%s\\='\"
786 backend))
787 ((not (memq backend new-list)) (push backend new-list))))
788 (set-default \\='org-export-backends new-list)))
790 Adding a back-end to this list will also pull the back-end it
791 depends on, if any."
792 :group 'org
793 :group 'org-export
794 :version "26.1"
795 :package-version '(Org . "9.0")
796 :initialize 'custom-initialize-set
797 :set (lambda (var val)
798 (if (not (featurep 'ox)) (set-default var val)
799 ;; Any back-end not required anymore (not present in VAL and not
800 ;; a parent of any back-end in the new value) is removed from the
801 ;; list of registered back-ends.
802 (setq org-export-registered-backends
803 (cl-remove-if-not
804 (lambda (backend)
805 (let ((name (org-export-backend-name backend)))
806 (or (memq name val)
807 (catch 'parentp
808 (dolist (b val)
809 (and (org-export-derived-backend-p b name)
810 (throw 'parentp t)))))))
811 org-export-registered-backends))
812 ;; Now build NEW-LIST of both new back-ends and required
813 ;; parents.
814 (let ((new-list (mapcar #'org-export-backend-name
815 org-export-registered-backends)))
816 (dolist (backend val)
817 (cond
818 ((not (load (format "ox-%s" backend) t t))
819 (message "Problems while trying to load export back-end `%s'"
820 backend))
821 ((not (memq backend new-list)) (push backend new-list))))
822 ;; Set VAR to that list with fixed dependencies.
823 (set-default var new-list))))
824 :type '(set :greedy t
825 (const :tag " ascii Export buffer to ASCII format" ascii)
826 (const :tag " beamer Export buffer to Beamer presentation" beamer)
827 (const :tag " html Export buffer to HTML format" html)
828 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
829 (const :tag " latex Export buffer to LaTeX format" latex)
830 (const :tag " man Export buffer to MAN format" man)
831 (const :tag " md Export buffer to Markdown format" md)
832 (const :tag " odt Export buffer to ODT format" odt)
833 (const :tag " org Export buffer to Org format" org)
834 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
835 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
836 (const :tag "C deck Export buffer to deck.js presentations" deck)
837 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
838 (const :tag "C groff Export buffer to Groff format" groff)
839 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
840 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
841 (const :tag "C s5 Export buffer to s5 presentations" s5)
842 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
844 (eval-after-load 'ox
845 '(dolist (backend org-export-backends)
846 (condition-case nil (require (intern (format "ox-%s" backend)))
847 (error (message "Problems while trying to load export back-end `%s'"
848 backend)))))
850 (defcustom org-support-shift-select nil
851 "Non-nil means make shift-cursor commands select text when possible.
852 \\<org-mode-map>\
854 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
855 start selecting a region, or enlarge regions started in this way.
856 In Org mode, in special contexts, these same keys are used for
857 other purposes, important enough to compete with shift selection.
858 Org tries to balance these needs by supporting `shift-select-mode'
859 outside these special contexts, under control of this variable.
861 The default of this variable is nil, to avoid confusing behavior. Shifted
862 cursor keys will then execute Org commands in the following contexts:
863 - on a headline, changing TODO state (left/right) and priority (up/down)
864 - on a time stamp, changing the time
865 - in a plain list item, changing the bullet type
866 - in a property definition line, switching between allowed values
867 - in the BEGIN line of a clock table (changing the time block).
868 Outside these contexts, the commands will throw an error.
870 When this variable is t and the cursor is not in a special
871 context, Org mode will support shift-selection for making and
872 enlarging regions. To make this more effective, the bullet
873 cycling will no longer happen anywhere in an item line, but only
874 if the cursor is exactly on the bullet.
876 If you set this variable to the symbol `always', then the keys
877 will not be special in headlines, property lines, and item lines,
878 to make shift selection work there as well. If this is what you
879 want, you can use the following alternative commands:
880 `\\[org-todo]' and `\\[org-priority]' \
881 to change TODO state and priority,
882 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
883 can be used to switch TODO sets,
884 `\\[org-ctrl-c-minus]' to cycle item bullet types,
885 and properties can be edited by hand or in column view.
887 However, when the cursor is on a timestamp, shift-cursor commands
888 will still edit the time stamp - this is just too good to give up."
889 :group 'org
890 :type '(choice
891 (const :tag "Never" nil)
892 (const :tag "When outside special context" t)
893 (const :tag "Everywhere except timestamps" always)))
895 (defcustom org-loop-over-headlines-in-active-region nil
896 "Shall some commands act upon headlines in the active region?
898 When set to t, some commands will be performed in all headlines
899 within the active region.
901 When set to `start-level', some commands will be performed in all
902 headlines within the active region, provided that these headlines
903 are of the same level than the first one.
905 When set to a string, those commands will be performed on the
906 matching headlines within the active region. Such string must be
907 a tags/property/todo match as it is used in the agenda tags view.
909 The list of commands is: `org-schedule', `org-deadline',
910 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
911 `org-archive-to-archive-sibling'. The archiving commands skip
912 already archived entries."
913 :type '(choice (const :tag "Don't loop" nil)
914 (const :tag "All headlines in active region" t)
915 (const :tag "In active region, headlines at the same level than the first one" start-level)
916 (string :tag "Tags/Property/Todo matcher"))
917 :version "24.1"
918 :group 'org-todo
919 :group 'org-archive)
921 (defgroup org-startup nil
922 "Options concerning startup of Org mode."
923 :tag "Org Startup"
924 :group 'org)
926 (defcustom org-startup-folded t
927 "Non-nil means entering Org mode will switch to OVERVIEW.
929 This can also be configured on a per-file basis by adding one of
930 the following lines anywhere in the buffer:
932 #+STARTUP: fold (or `overview', this is equivalent)
933 #+STARTUP: nofold (or `showall', this is equivalent)
934 #+STARTUP: content
935 #+STARTUP: showeverything
937 Set `org-agenda-inhibit-startup' to a non-nil value if you want
938 to ignore this option when Org opens agenda files for the first
939 time."
940 :group 'org-startup
941 :type '(choice
942 (const :tag "nofold: show all" nil)
943 (const :tag "fold: overview" t)
944 (const :tag "content: all headlines" content)
945 (const :tag "show everything, even drawers" showeverything)))
947 (defcustom org-startup-truncated t
948 "Non-nil means entering Org mode will set `truncate-lines'.
949 This is useful since some lines containing links can be very long and
950 uninteresting. Also tables look terrible when wrapped.
952 The variable `org-startup-truncated' allows to configure
953 truncation for Org mode different to the other modes that use the
954 variable `truncate-lines' and as a shortcut instead of putting
955 the variable `truncate-lines' into the `org-mode-hook'. If one
956 wants to configure truncation for Org mode not statically but
957 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
958 the variable `truncate-lines' has to be used because in such a
959 case it is too late to set the variable `org-startup-truncated'."
960 :group 'org-startup
961 :type 'boolean)
963 (defcustom org-startup-indented nil
964 "Non-nil means turn on `org-indent-mode' on startup.
965 This can also be configured on a per-file basis by adding one of
966 the following lines anywhere in the buffer:
968 #+STARTUP: indent
969 #+STARTUP: noindent"
970 :group 'org-structure
971 :type '(choice
972 (const :tag "Not" nil)
973 (const :tag "Globally (slow on startup in large files)" t)))
975 (defcustom org-use-sub-superscripts t
976 "Non-nil means interpret \"_\" and \"^\" for display.
978 If you want to control how Org exports those characters, see
979 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
980 used to be an alias for `org-export-with-sub-superscripts' in
981 Org <8.0, it is not anymore.
983 When this option is turned on, you can use TeX-like syntax for
984 sub- and superscripts within the buffer. Several characters after
985 \"_\" or \"^\" will be considered as a single item - so grouping
986 with {} is normally not needed. For example, the following things
987 will be parsed as single sub- or superscripts:
989 10^24 or 10^tau several digits will be considered 1 item.
990 10^-12 or 10^-tau a leading sign with digits or a word
991 x^2-y^3 will be read as x^2 - y^3, because items are
992 terminated by almost any nonword/nondigit char.
993 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
995 Still, ambiguity is possible. So when in doubt, use {} to enclose
996 the sub/superscript. If you set this variable to the symbol `{}',
997 the braces are *required* in order to trigger interpretations as
998 sub/superscript. This can be helpful in documents that need \"_\"
999 frequently in plain text."
1000 :group 'org-startup
1001 :version "24.4"
1002 :package-version '(Org . "8.0")
1003 :type '(choice
1004 (const :tag "Always interpret" t)
1005 (const :tag "Only with braces" {})
1006 (const :tag "Never interpret" nil)))
1008 (defcustom org-startup-with-beamer-mode nil
1009 "Non-nil means turn on `org-beamer-mode' on startup.
1010 This can also be configured on a per-file basis by adding one of
1011 the following lines anywhere in the buffer:
1013 #+STARTUP: beamer"
1014 :group 'org-startup
1015 :version "24.1"
1016 :type 'boolean)
1018 (defcustom org-startup-align-all-tables nil
1019 "Non-nil means align all tables when visiting a file.
1020 This is useful when the column width in tables is forced with <N> cookies
1021 in table fields. Such tables will look correct only after the first re-align.
1022 This can also be configured on a per-file basis by adding one of
1023 the following lines anywhere in the buffer:
1024 #+STARTUP: align
1025 #+STARTUP: noalign"
1026 :group 'org-startup
1027 :type 'boolean)
1029 (defcustom org-startup-with-inline-images nil
1030 "Non-nil means show inline images when loading a new Org file.
1031 This can also be configured on a per-file basis by adding one of
1032 the following lines anywhere in the buffer:
1033 #+STARTUP: inlineimages
1034 #+STARTUP: noinlineimages"
1035 :group 'org-startup
1036 :version "24.1"
1037 :type 'boolean)
1039 (defcustom org-startup-with-latex-preview nil
1040 "Non-nil means preview LaTeX fragments when loading a new Org file.
1042 This can also be configured on a per-file basis by adding one of
1043 the following lines anywhere in the buffer:
1044 #+STARTUP: latexpreview
1045 #+STARTUP: nolatexpreview"
1046 :group 'org-startup
1047 :version "24.4"
1048 :package-version '(Org . "8.0")
1049 :type 'boolean)
1051 (defcustom org-insert-mode-line-in-empty-file nil
1052 "Non-nil means insert the first line setting Org mode in empty files.
1053 When the function `org-mode' is called interactively in an empty file, this
1054 normally means that the file name does not automatically trigger Org mode.
1055 To ensure that the file will always be in Org mode in the future, a
1056 line enforcing Org mode will be inserted into the buffer, if this option
1057 has been set."
1058 :group 'org-startup
1059 :type 'boolean)
1061 (defcustom org-replace-disputed-keys nil
1062 "Non-nil means use alternative key bindings for some keys.
1063 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1064 These keys are also used by other packages like shift-selection-mode'
1065 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1066 If you want to use Org mode together with one of these other modes,
1067 or more generally if you would like to move some Org mode commands to
1068 other keys, set this variable and configure the keys with the variable
1069 `org-disputed-keys'.
1071 This option is only relevant at load-time of Org mode, and must be set
1072 *before* org.el is loaded. Changing it requires a restart of Emacs to
1073 become effective."
1074 :group 'org-startup
1075 :type 'boolean)
1077 (defcustom org-use-extra-keys nil
1078 "Non-nil means use extra key sequence definitions for certain commands.
1079 This happens automatically if `window-system' is nil. This
1080 variable lets you do the same manually. You must set it before
1081 loading Org."
1082 :group 'org-startup
1083 :type 'boolean)
1085 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1087 (defcustom org-disputed-keys
1088 '(([(shift up)] . [(meta p)])
1089 ([(shift down)] . [(meta n)])
1090 ([(shift left)] . [(meta -)])
1091 ([(shift right)] . [(meta +)])
1092 ([(control shift right)] . [(meta shift +)])
1093 ([(control shift left)] . [(meta shift -)]))
1094 "Keys for which Org mode and other modes compete.
1095 This is an alist, cars are the default keys, second element specifies
1096 the alternative to use when `org-replace-disputed-keys' is t.
1098 Keys can be specified in any syntax supported by `define-key'.
1099 The value of this option takes effect only at Org mode startup,
1100 therefore you'll have to restart Emacs to apply it after changing."
1101 :group 'org-startup
1102 :type 'alist)
1104 (defun org-key (key)
1105 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1106 Or return the original if not disputed."
1107 (when org-replace-disputed-keys
1108 (let* ((nkey (key-description key))
1109 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1110 org-disputed-keys)))
1111 (setq key (if x (cdr x) key))))
1112 key)
1114 (defun org-defkey (keymap key def)
1115 "Define a key, possibly translated, as returned by `org-key'."
1116 (define-key keymap (org-key key) def))
1118 (defcustom org-ellipsis nil
1119 "The ellipsis to use in the Org mode outline.
1121 When nil, just use the standard three dots.
1122 When a string, use that string instead.
1124 The change affects only Org mode (which will then use its own display table).
1125 Changing this requires executing `\\[org-mode]' in a buffer to become
1126 effective."
1127 :group 'org-startup
1128 :type '(choice (const :tag "Default" nil)
1129 (string :tag "String" :value "...#"))
1130 :safe #'string-or-null-p)
1132 (defvar org-display-table nil
1133 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1135 (defgroup org-keywords nil
1136 "Keywords in Org mode."
1137 :tag "Org Keywords"
1138 :group 'org)
1140 (defcustom org-closed-keep-when-no-todo nil
1141 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1142 :group 'org-todo
1143 :group 'org-keywords
1144 :version "24.4"
1145 :package-version '(Org . "8.0")
1146 :type 'boolean)
1148 (defgroup org-structure nil
1149 "Options concerning the general structure of Org files."
1150 :tag "Org Structure"
1151 :group 'org)
1153 (defgroup org-reveal-location nil
1154 "Options about how to make context of a location visible."
1155 :tag "Org Reveal Location"
1156 :group 'org-structure)
1158 (defcustom org-show-context-detail '((agenda . local)
1159 (bookmark-jump . lineage)
1160 (isearch . lineage)
1161 (default . ancestors))
1162 "Alist between context and visibility span when revealing a location.
1164 \\<org-mode-map>Some actions may move point into invisible
1165 locations. As a consequence, Org always expose a neighborhood
1166 around point. How much is shown depends on the initial action,
1167 or context. Valid contexts are
1169 agenda when exposing an entry from the agenda
1170 org-goto when using the command `org-goto' (`\\[org-goto]')
1171 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1172 tags-tree when constructing a sparse tree based on tags matches
1173 link-search when exposing search matches associated with a link
1174 mark-goto when exposing the jump goal of a mark
1175 bookmark-jump when exposing a bookmark location
1176 isearch when exiting from an incremental search
1177 default default for all contexts not set explicitly
1179 Allowed visibility spans are
1181 minimal show current headline; if point is not on headline,
1182 also show entry
1184 local show current headline, entry and next headline
1186 ancestors show current headline and its direct ancestors; if
1187 point is not on headline, also show entry
1189 lineage show current headline, its direct ancestors and all
1190 their children; if point is not on headline, also show
1191 entry and first child
1193 tree show current headline, its direct ancestors and all
1194 their children; if point is not on headline, also show
1195 entry and all children
1197 canonical show current headline, its direct ancestors along with
1198 their entries and children; if point is not located on
1199 the headline, also show current entry and all children
1201 As special cases, a nil or t value means show all contexts in
1202 `minimal' or `canonical' view, respectively.
1204 Some views can make displayed information very compact, but also
1205 make it harder to edit the location of the match. In such
1206 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1207 more context."
1208 :group 'org-reveal-location
1209 :version "26.1"
1210 :package-version '(Org . "9.0")
1211 :type '(choice
1212 (const :tag "Canonical" t)
1213 (const :tag "Minimal" nil)
1214 (repeat :greedy t :tag "Individual contexts"
1215 (cons
1216 (choice :tag "Context"
1217 (const agenda)
1218 (const org-goto)
1219 (const occur-tree)
1220 (const tags-tree)
1221 (const link-search)
1222 (const mark-goto)
1223 (const bookmark-jump)
1224 (const isearch)
1225 (const default))
1226 (choice :tag "Detail level"
1227 (const minimal)
1228 (const local)
1229 (const ancestors)
1230 (const lineage)
1231 (const tree)
1232 (const canonical))))))
1234 (defcustom org-indirect-buffer-display 'other-window
1235 "How should indirect tree buffers be displayed?
1237 This applies to indirect buffers created with the commands
1238 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1240 Valid values are:
1241 current-window Display in the current window
1242 other-window Just display in another window.
1243 dedicated-frame Create one new frame, and re-use it each time.
1244 new-frame Make a new frame each time. Note that in this case
1245 previously-made indirect buffers are kept, and you need to
1246 kill these buffers yourself."
1247 :group 'org-structure
1248 :group 'org-agenda-windows
1249 :type '(choice
1250 (const :tag "In current window" current-window)
1251 (const :tag "In current frame, other window" other-window)
1252 (const :tag "Each time a new frame" new-frame)
1253 (const :tag "One dedicated frame" dedicated-frame)))
1255 (defcustom org-use-speed-commands nil
1256 "Non-nil means activate single letter commands at beginning of a headline.
1257 This may also be a function to test for appropriate locations where speed
1258 commands should be active.
1260 For example, to activate speed commands when the point is on any
1261 star at the beginning of the headline, you can do this:
1263 (setq org-use-speed-commands
1264 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1265 :group 'org-structure
1266 :type '(choice
1267 (const :tag "Never" nil)
1268 (const :tag "At beginning of headline stars" t)
1269 (function)))
1271 (defcustom org-speed-commands-user nil
1272 "Alist of additional speed commands.
1273 This list will be checked before `org-speed-commands-default'
1274 when the variable `org-use-speed-commands' is non-nil
1275 and when the cursor is at the beginning of a headline.
1276 The car if each entry is a string with a single letter, which must
1277 be assigned to `self-insert-command' in the global map.
1278 The cdr is either a command to be called interactively, a function
1279 to be called, or a form to be evaluated.
1280 An entry that is just a list with a single string will be interpreted
1281 as a descriptive headline that will be added when listing the speed
1282 commands in the Help buffer using the `?' speed command."
1283 :group 'org-structure
1284 :type '(repeat :value ("k" . ignore)
1285 (choice :value ("k" . ignore)
1286 (list :tag "Descriptive Headline" (string :tag "Headline"))
1287 (cons :tag "Letter and Command"
1288 (string :tag "Command letter")
1289 (choice
1290 (function)
1291 (sexp))))))
1293 (defcustom org-bookmark-names-plist
1294 '(:last-capture "org-capture-last-stored"
1295 :last-refile "org-refile-last-stored"
1296 :last-capture-marker "org-capture-last-stored-marker")
1297 "Names for bookmarks automatically set by some Org commands.
1298 This can provide strings as names for a number of bookmarks Org sets
1299 automatically. The following keys are currently implemented:
1300 :last-capture
1301 :last-capture-marker
1302 :last-refile
1303 When a key does not show up in the property list, the corresponding bookmark
1304 is not set."
1305 :group 'org-structure
1306 :type 'plist)
1308 (defgroup org-cycle nil
1309 "Options concerning visibility cycling in Org mode."
1310 :tag "Org Cycle"
1311 :group 'org-structure)
1313 (defcustom org-cycle-skip-children-state-if-no-children t
1314 "Non-nil means skip CHILDREN state in entries that don't have any."
1315 :group 'org-cycle
1316 :type 'boolean)
1318 (defcustom org-cycle-max-level nil
1319 "Maximum level which should still be subject to visibility cycling.
1320 Levels higher than this will, for cycling, be treated as text, not a headline.
1321 When `org-odd-levels-only' is set, a value of N in this variable actually
1322 means 2N-1 stars as the limiting headline.
1323 When nil, cycle all levels.
1324 Note that the limiting level of cycling is also influenced by
1325 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1326 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1327 than its value."
1328 :group 'org-cycle
1329 :type '(choice
1330 (const :tag "No limit" nil)
1331 (integer :tag "Maximum level")))
1333 (defcustom org-hide-block-startup nil
1334 "Non-nil means entering Org mode will fold all blocks.
1335 This can also be set in on a per-file basis with
1337 #+STARTUP: hideblocks
1338 #+STARTUP: showblocks"
1339 :group 'org-startup
1340 :group 'org-cycle
1341 :type 'boolean)
1343 (defcustom org-cycle-global-at-bob nil
1344 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1346 This makes it possible to do global cycling without having to use `S-TAB'
1347 or `\\[universal-argument] TAB'. For this special case to work, the first \
1348 line of the buffer
1349 must not be a headline -- it may be empty or some other text.
1351 When used in this way, `org-cycle-hook' is disabled temporarily to make
1352 sure the cursor stays at the beginning of the buffer.
1354 When this option is nil, don't do anything special at the beginning of
1355 the buffer."
1356 :group 'org-cycle
1357 :type 'boolean)
1359 (defcustom org-cycle-level-after-item/entry-creation t
1360 "Non-nil means cycle entry level or item indentation in new empty entries.
1362 When the cursor is at the end of an empty headline, i.e., with only stars
1363 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1364 and then all possible ancestor states, before returning to the original state.
1365 This makes data entry extremely fast: M-RET to create a new headline,
1366 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1368 When the cursor is at the end of an empty plain list item, one TAB will
1369 make it a subitem, two or more tabs will back up to make this an item
1370 higher up in the item hierarchy."
1371 :group 'org-cycle
1372 :type 'boolean)
1374 (defcustom org-cycle-emulate-tab t
1375 "Where should `org-cycle' emulate TAB.
1376 nil Never
1377 white Only in completely white lines
1378 whitestart Only at the beginning of lines, before the first non-white char
1379 t Everywhere except in headlines
1380 exc-hl-bol Everywhere except at the start of a headline
1381 If TAB is used in a place where it does not emulate TAB, the current subtree
1382 visibility is cycled."
1383 :group 'org-cycle
1384 :type '(choice (const :tag "Never" nil)
1385 (const :tag "Only in completely white lines" white)
1386 (const :tag "Before first char in a line" whitestart)
1387 (const :tag "Everywhere except in headlines" t)
1388 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1390 (defcustom org-cycle-separator-lines 2
1391 "Number of empty lines needed to keep an empty line between collapsed trees.
1392 If you leave an empty line between the end of a subtree and the following
1393 headline, this empty line is hidden when the subtree is folded.
1394 Org mode will leave (exactly) one empty line visible if the number of
1395 empty lines is equal or larger to the number given in this variable.
1396 So the default 2 means at least 2 empty lines after the end of a subtree
1397 are needed to produce free space between a collapsed subtree and the
1398 following headline.
1400 If the number is negative, and the number of empty lines is at least -N,
1401 all empty lines are shown.
1403 Special case: when 0, never leave empty lines in collapsed view."
1404 :group 'org-cycle
1405 :type 'integer)
1406 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1408 (defcustom org-pre-cycle-hook nil
1409 "Hook that is run before visibility cycling is happening.
1410 The function(s) in this hook must accept a single argument which indicates
1411 the new state that will be set right after running this hook. The
1412 argument is a symbol. Before a global state change, it can have the values
1413 `overview', `content', or `all'. Before a local state change, it can have
1414 the values `folded', `children', or `subtree'."
1415 :group 'org-cycle
1416 :type 'hook)
1418 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1419 org-cycle-hide-drawers
1420 org-cycle-show-empty-lines
1421 org-optimize-window-after-visibility-change)
1422 "Hook that is run after `org-cycle' has changed the buffer visibility.
1423 The function(s) in this hook must accept a single argument which indicates
1424 the new state that was set by the most recent `org-cycle' command. The
1425 argument is a symbol. After a global state change, it can have the values
1426 `overview', `contents', or `all'. After a local state change, it can have
1427 the values `folded', `children', or `subtree'."
1428 :group 'org-cycle
1429 :type 'hook
1430 :version "26.1"
1431 :package-version '(Org . "8.3"))
1433 (defgroup org-edit-structure nil
1434 "Options concerning structure editing in Org mode."
1435 :tag "Org Edit Structure"
1436 :group 'org-structure)
1438 (defcustom org-odd-levels-only nil
1439 "Non-nil means skip even levels and only use odd levels for the outline.
1440 This has the effect that two stars are being added/taken away in
1441 promotion/demotion commands. It also influences how levels are
1442 handled by the exporters.
1443 Changing it requires restart of `font-lock-mode' to become effective
1444 for fontification also in regions already fontified.
1445 You may also set this on a per-file basis by adding one of the following
1446 lines to the buffer:
1448 #+STARTUP: odd
1449 #+STARTUP: oddeven"
1450 :group 'org-edit-structure
1451 :group 'org-appearance
1452 :type 'boolean)
1454 (defcustom org-adapt-indentation t
1455 "Non-nil means adapt indentation to outline node level.
1457 When this variable is set, Org assumes that you write outlines by
1458 indenting text in each node to align with the headline (after the
1459 stars). The following issues are influenced by this variable:
1461 - The indentation is increased by one space in a demotion
1462 command, and decreased by one in a promotion command. However,
1463 in the latter case, if shifting some line in the entry body
1464 would alter document structure (e.g., insert a new headline),
1465 indentation is not changed at all.
1467 - Property drawers and planning information is inserted indented
1468 when this variable is set. When nil, they will not be indented.
1470 - TAB indents a line relative to current level. The lines below
1471 a headline will be indented when this variable is set.
1473 Note that this is all about true indentation, by adding and
1474 removing space characters. See also `org-indent.el' which does
1475 level-dependent indentation in a virtual way, i.e. at display
1476 time in Emacs."
1477 :group 'org-edit-structure
1478 :type 'boolean)
1480 (defcustom org-special-ctrl-a/e nil
1481 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1483 When t, `C-a' will bring back the cursor to the beginning of the
1484 headline text, i.e. after the stars and after a possible TODO
1485 keyword. In an item, this will be the position after bullet and
1486 check-box, if any. When the cursor is already at that position,
1487 another `C-a' will bring it to the beginning of the line.
1489 `C-e' will jump to the end of the headline, ignoring the presence
1490 of tags in the headline. A second `C-e' will then jump to the
1491 true end of the line, after any tags. This also means that, when
1492 this variable is non-nil, `C-e' also will never jump beyond the
1493 end of the heading of a folded section, i.e. not after the
1494 ellipses.
1496 When set to the symbol `reversed', the first `C-a' or `C-e' works
1497 normally, going to the true line boundary first. Only a directly
1498 following, identical keypress will bring the cursor to the
1499 special positions.
1501 This may also be a cons cell where the behavior for `C-a' and
1502 `C-e' is set separately."
1503 :group 'org-edit-structure
1504 :type '(choice
1505 (const :tag "off" nil)
1506 (const :tag "on: after stars/bullet and before tags first" t)
1507 (const :tag "reversed: true line boundary first" reversed)
1508 (cons :tag "Set C-a and C-e separately"
1509 (choice :tag "Special C-a"
1510 (const :tag "off" nil)
1511 (const :tag "on: after stars/bullet first" t)
1512 (const :tag "reversed: before stars/bullet first" reversed))
1513 (choice :tag "Special C-e"
1514 (const :tag "off" nil)
1515 (const :tag "on: before tags first" t)
1516 (const :tag "reversed: after tags first" reversed)))))
1517 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1519 (defcustom org-special-ctrl-k nil
1520 "Non-nil means `C-k' will behave specially in headlines.
1521 When nil, `C-k' will call the default `kill-line' command.
1522 When t, the following will happen while the cursor is in the headline:
1524 - When the cursor is at the beginning of a headline, kill the entire
1525 line and possible the folded subtree below the line.
1526 - When in the middle of the headline text, kill the headline up to the tags.
1527 - When after the headline text, kill the tags."
1528 :group 'org-edit-structure
1529 :type 'boolean)
1531 (defcustom org-ctrl-k-protect-subtree nil
1532 "Non-nil means, do not delete a hidden subtree with C-k.
1533 When set to the symbol `error', simply throw an error when C-k is
1534 used to kill (part-of) a headline that has hidden text behind it.
1535 Any other non-nil value will result in a query to the user, if it is
1536 OK to kill that hidden subtree. When nil, kill without remorse."
1537 :group 'org-edit-structure
1538 :version "24.1"
1539 :type '(choice
1540 (const :tag "Do not protect hidden subtrees" nil)
1541 (const :tag "Protect hidden subtrees with a security query" t)
1542 (const :tag "Never kill a hidden subtree with C-k" error)))
1544 (defcustom org-special-ctrl-o t
1545 "Non-nil means, make `C-o' insert a row in tables."
1546 :group 'org-edit-structure
1547 :type 'boolean)
1549 (defcustom org-catch-invisible-edits nil
1550 "Check if in invisible region before inserting or deleting a character.
1551 Valid values are:
1553 nil Do not check, so just do invisible edits.
1554 error Throw an error and do nothing.
1555 show Make point visible, and do the requested edit.
1556 show-and-error Make point visible, then throw an error and abort the edit.
1557 smart Make point visible, and do insertion/deletion if it is
1558 adjacent to visible text and the change feels predictable.
1559 Never delete a previously invisible character or add in the
1560 middle or right after an invisible region. Basically, this
1561 allows insertion and backward-delete right before ellipses.
1562 FIXME: maybe in this case we should not even show?"
1563 :group 'org-edit-structure
1564 :version "24.1"
1565 :type '(choice
1566 (const :tag "Do not check" nil)
1567 (const :tag "Throw error when trying to edit" error)
1568 (const :tag "Unhide, but do not do the edit" show-and-error)
1569 (const :tag "Show invisible part and do the edit" show)
1570 (const :tag "Be smart and do the right thing" smart)))
1572 (defcustom org-yank-folded-subtrees t
1573 "Non-nil means when yanking subtrees, fold them.
1574 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1575 it starts with a heading and all other headings in it are either children
1576 or siblings, then fold all the subtrees. However, do this only if no
1577 text after the yank would be swallowed into a folded tree by this action."
1578 :group 'org-edit-structure
1579 :type 'boolean)
1581 (defcustom org-yank-adjusted-subtrees nil
1582 "Non-nil means when yanking subtrees, adjust the level.
1583 With this setting, `org-paste-subtree' is used to insert the subtree, see
1584 this function for details."
1585 :group 'org-edit-structure
1586 :type 'boolean)
1588 (defcustom org-M-RET-may-split-line '((default . t))
1589 "Non-nil means M-RET will split the line at the cursor position.
1590 When nil, it will go to the end of the line before making a
1591 new line.
1592 You may also set this option in a different way for different
1593 contexts. Valid contexts are:
1595 headline when creating a new headline
1596 item when creating a new item
1597 table in a table field
1598 default the value to be used for all contexts not explicitly
1599 customized"
1600 :group 'org-structure
1601 :group 'org-table
1602 :type '(choice
1603 (const :tag "Always" t)
1604 (const :tag "Never" nil)
1605 (repeat :greedy t :tag "Individual contexts"
1606 (cons
1607 (choice :tag "Context"
1608 (const headline)
1609 (const item)
1610 (const table)
1611 (const default))
1612 (boolean)))))
1615 (defcustom org-insert-heading-respect-content nil
1616 "Non-nil means insert new headings after the current subtree.
1617 \\<org-mode-map>
1618 When nil, the new heading is created directly after the current line.
1619 The commands `\\[org-insert-heading-respect-content]' and \
1620 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1621 for the duration of the command."
1622 :group 'org-structure
1623 :type 'boolean)
1625 (defcustom org-blank-before-new-entry '((heading . auto)
1626 (plain-list-item . auto))
1627 "Should `org-insert-heading' leave a blank line before new heading/item?
1628 The value is an alist, with `heading' and `plain-list-item' as CAR,
1629 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1630 which case Org will look at the surrounding headings/items and try to
1631 make an intelligent decision whether to insert a blank line or not."
1632 :group 'org-edit-structure
1633 :type '(list
1634 (cons (const heading)
1635 (choice (const :tag "Never" nil)
1636 (const :tag "Always" t)
1637 (const :tag "Auto" auto)))
1638 (cons (const plain-list-item)
1639 (choice (const :tag "Never" nil)
1640 (const :tag "Always" t)
1641 (const :tag "Auto" auto)))))
1643 (defcustom org-insert-heading-hook nil
1644 "Hook being run after inserting a new heading."
1645 :group 'org-edit-structure
1646 :type 'hook)
1648 (defcustom org-enable-fixed-width-editor t
1649 "Non-nil means lines starting with \":\" are treated as fixed-width.
1650 This currently only means they are never auto-wrapped.
1651 When nil, such lines will be treated like ordinary lines."
1652 :group 'org-edit-structure
1653 :type 'boolean)
1655 (defcustom org-goto-auto-isearch t
1656 "Non-nil means typing characters in `org-goto' starts incremental search.
1657 When nil, you can use these keybindings to navigate the buffer:
1659 q Quit the org-goto interface
1660 n Go to the next visible heading
1661 p Go to the previous visible heading
1662 f Go one heading forward on same level
1663 b Go one heading backward on same level
1664 u Go one heading up"
1665 :group 'org-edit-structure
1666 :type 'boolean)
1668 (defgroup org-sparse-trees nil
1669 "Options concerning sparse trees in Org mode."
1670 :tag "Org Sparse Trees"
1671 :group 'org-structure)
1673 (defcustom org-highlight-sparse-tree-matches t
1674 "Non-nil means highlight all matches that define a sparse tree.
1675 The highlights will automatically disappear the next time the buffer is
1676 changed by an edit command."
1677 :group 'org-sparse-trees
1678 :type 'boolean)
1680 (defcustom org-remove-highlights-with-change t
1681 "Non-nil means any change to the buffer will remove temporary highlights.
1682 \\<org-mode-map>\
1683 Such highlights are created by `org-occur' and `org-clock-display'.
1684 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1685 to get rid of the highlights.
1686 The highlights created by `org-toggle-latex-fragment' always need
1687 `\\[org-toggle-latex-fragment]' to be removed."
1688 :group 'org-sparse-trees
1689 :group 'org-time
1690 :type 'boolean)
1692 (defcustom org-occur-case-fold-search t
1693 "Non-nil means `org-occur' should be case-insensitive.
1694 If set to `smart' the search will be case-insensitive only if it
1695 doesn't specify any upper case character."
1696 :group 'org-sparse-trees
1697 :version "26.1"
1698 :type '(choice
1699 (const :tag "Case-sensitive" nil)
1700 (const :tag "Case-insensitive" t)
1701 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1703 (defcustom org-occur-hook '(org-first-headline-recenter)
1704 "Hook that is run after `org-occur' has constructed a sparse tree.
1705 This can be used to recenter the window to show as much of the structure
1706 as possible."
1707 :group 'org-sparse-trees
1708 :type 'hook)
1710 (defgroup org-imenu-and-speedbar nil
1711 "Options concerning imenu and speedbar in Org mode."
1712 :tag "Org Imenu and Speedbar"
1713 :group 'org-structure)
1715 (defcustom org-imenu-depth 2
1716 "The maximum level for Imenu access to Org headlines.
1717 This also applied for speedbar access."
1718 :group 'org-imenu-and-speedbar
1719 :type 'integer)
1721 (defgroup org-table nil
1722 "Options concerning tables in Org mode."
1723 :tag "Org Table"
1724 :group 'org)
1726 (defcustom org-enable-table-editor 'optimized
1727 "Non-nil means lines starting with \"|\" are handled by the table editor.
1728 When nil, such lines will be treated like ordinary lines.
1730 When equal to the symbol `optimized', the table editor will be optimized to
1731 do the following:
1732 - Automatic overwrite mode in front of whitespace in table fields.
1733 This makes the structure of the table stay in tact as long as the edited
1734 field does not exceed the column width.
1735 - Minimize the number of realigns. Normally, the table is aligned each time
1736 TAB or RET are pressed to move to another field. With optimization this
1737 happens only if changes to a field might have changed the column width.
1738 Optimization requires replacing the functions `self-insert-command',
1739 `delete-char', and `backward-delete-char' in Org buffers, with a
1740 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1741 good at guessing when a re-align will be necessary, but you can always
1742 force one with `\\[org-ctrl-c-ctrl-c]'.
1744 If you would like to use the optimized version in Org mode, but the
1745 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1747 This variable can be used to turn on and off the table editor during a session,
1748 but in order to toggle optimization, a restart is required.
1750 See also the variable `org-table-auto-blank-field'."
1751 :group 'org-table
1752 :type '(choice
1753 (const :tag "off" nil)
1754 (const :tag "on" t)
1755 (const :tag "on, optimized" optimized)))
1757 (defcustom org-self-insert-cluster-for-undo nil
1758 "Non-nil means cluster self-insert commands for undo when possible.
1759 If this is set, then, like in the Emacs command loop, 20 consecutive
1760 characters will be undone together.
1761 This is configurable, because there is some impact on typing performance."
1762 :group 'org-table
1763 :type 'boolean)
1765 (defcustom org-table-tab-recognizes-table.el t
1766 "Non-nil means TAB will automatically notice a table.el table.
1767 When it sees such a table, it moves point into it and - if necessary -
1768 calls `table-recognize-table'."
1769 :group 'org-table-editing
1770 :type 'boolean)
1772 (defgroup org-link nil
1773 "Options concerning links in Org mode."
1774 :tag "Org Link"
1775 :group 'org)
1777 (defvar-local org-link-abbrev-alist-local nil
1778 "Buffer-local version of `org-link-abbrev-alist', which see.
1779 The value of this is taken from the #+LINK lines.")
1781 (defcustom org-link-parameters
1782 '(("doi" :follow org--open-doi-link)
1783 ("elisp" :follow org--open-elisp-link)
1784 ("file" :complete org-file-complete-link)
1785 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1786 ("help" :follow org--open-help-link)
1787 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1788 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1789 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1790 ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
1791 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1792 ("shell" :follow org--open-shell-link))
1793 "An alist of properties that defines all the links in Org mode.
1794 The key in each association is a string of the link type.
1795 Subsequent optional elements make up a p-list of link properties.
1797 :follow - A function that takes the link path as an argument.
1799 :export - A function that takes the link path, description and
1800 export-backend as arguments.
1802 :store - A function responsible for storing the link. See the
1803 function `org-store-link-functions'.
1805 :complete - A function that inserts a link with completion. The
1806 function takes one optional prefix arg.
1808 :face - A face for the link, or a function that returns a face.
1809 The function takes one argument which is the link path. The
1810 default face is `org-link'.
1812 :mouse-face - The mouse-face. The default is `highlight'.
1814 :display - `full' will not fold the link in descriptive
1815 display. Default is `org-link'.
1817 :help-echo - A string or function that takes (window object position)
1818 as arguments and returns a string.
1820 :keymap - A keymap that is active on the link. The default is
1821 `org-mouse-map'.
1823 :htmlize-link - A function for the htmlize-link. Defaults
1824 to (list :uri \"type:path\")
1826 :activate-func - A function to run at the end of font-lock
1827 activation. The function must accept (link-start link-end path bracketp)
1828 as arguments."
1829 :group 'org-link
1830 :type '(alist :tag "Link display parameters"
1831 :value-type plist))
1833 (defun org-link-get-parameter (type key)
1834 "Get TYPE link property for KEY.
1835 TYPE is a string and KEY is a plist keyword."
1836 (plist-get
1837 (cdr (assoc type org-link-parameters))
1838 key))
1840 (defun org-link-set-parameters (type &rest parameters)
1841 "Set link TYPE properties to PARAMETERS.
1842 PARAMETERS should be :key val pairs."
1843 (let ((data (assoc type org-link-parameters)))
1844 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1845 (push (cons type parameters) org-link-parameters)
1846 (org-make-link-regexps)
1847 (org-element-update-syntax))))
1849 (defun org-link-types ()
1850 "Return a list of known link types."
1851 (mapcar #'car org-link-parameters))
1853 (defcustom org-link-abbrev-alist nil
1854 "Alist of link abbreviations.
1855 The car of each element is a string, to be replaced at the start of a link.
1856 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1857 links in Org buffers can have an optional tag after a double colon, e.g.,
1859 [[linkkey:tag][description]]
1861 The `linkkey' must be a single word, starting with a letter, followed
1862 by letters, numbers, `-' or `_'.
1864 If REPLACE is a string, the tag will simply be appended to create the link.
1865 If the string contains \"%s\", the tag will be inserted there. If the string
1866 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1867 at that point (see the function `url-hexify-string'). If the string contains
1868 the specifier \"%(my-function)\", then the custom function `my-function' will
1869 be invoked: this function takes the tag as its only argument and must return
1870 a string.
1872 REPLACE may also be a function that will be called with the tag as the
1873 only argument to create the link, which should be returned as a string.
1875 See the manual for examples."
1876 :group 'org-link
1877 :type '(repeat
1878 (cons
1879 (string :tag "Protocol")
1880 (choice
1881 (string :tag "Format")
1882 (function)))))
1884 (defcustom org-descriptive-links t
1885 "Non-nil means Org will display descriptive links.
1886 E.g. [[http://orgmode.org][Org website]] will be displayed as
1887 \"Org Website\", hiding the link itself and just displaying its
1888 description. When set to nil, Org will display the full links
1889 literally.
1891 You can interactively set the value of this variable by calling
1892 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1893 :group 'org-link
1894 :type 'boolean)
1896 (defcustom org-link-file-path-type 'adaptive
1897 "How the path name in file links should be stored.
1898 Valid values are:
1900 relative Relative to the current directory, i.e. the directory of the file
1901 into which the link is being inserted.
1902 absolute Absolute path, if possible with ~ for home directory.
1903 noabbrev Absolute path, no abbreviation of home directory.
1904 adaptive Use relative path for files in the current directory and sub-
1905 directories of it. For other files, use an absolute path."
1906 :group 'org-link
1907 :type '(choice
1908 (const relative)
1909 (const absolute)
1910 (const noabbrev)
1911 (const adaptive)))
1913 (defvaralias 'org-activate-links 'org-highlight-links)
1914 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1915 "Types of links that should be highlighted in Org files.
1917 This is a list of symbols, each one of them leading to the
1918 highlighting of a certain link type.
1920 You can still open links that are not highlighted.
1922 In principle, it does not hurt to turn on highlighting for all
1923 link types. There may be a small gain when turning off unused
1924 link types. The types are:
1926 bracket The recommended [[link][description]] or [[link]] links with hiding.
1927 angle Links in angular brackets that may contain whitespace like
1928 <bbdb:Carsten Dominik>.
1929 plain Plain links in normal text, no whitespace, like http://google.com.
1930 radio Text that is matched by a radio target, see manual for details.
1931 tag Tag settings in a headline (link to tag search).
1932 date Time stamps (link to calendar).
1933 footnote Footnote labels.
1935 If you set this variable during an Emacs session, use `org-mode-restart'
1936 in the Org buffer so that the change takes effect."
1937 :group 'org-link
1938 :group 'org-appearance
1939 :type '(set :greedy t
1940 (const :tag "Double bracket links" bracket)
1941 (const :tag "Angular bracket links" angle)
1942 (const :tag "Plain text links" plain)
1943 (const :tag "Radio target matches" radio)
1944 (const :tag "Tags" tag)
1945 (const :tag "Timestamps" date)
1946 (const :tag "Footnotes" footnote)))
1948 (defcustom org-make-link-description-function nil
1949 "Function to use for generating link descriptions from links.
1950 When nil, the link location will be used. This function must take
1951 two parameters: the first one is the link, the second one is the
1952 description generated by `org-insert-link'. The function should
1953 return the description to use."
1954 :group 'org-link
1955 :type '(choice (const nil) (function)))
1957 (defgroup org-link-store nil
1958 "Options concerning storing links in Org mode."
1959 :tag "Org Store Link"
1960 :group 'org-link)
1962 (defcustom org-url-hexify-p t
1963 "When non-nil, hexify URL when creating a link."
1964 :type 'boolean
1965 :version "24.3"
1966 :group 'org-link-store)
1968 (defcustom org-email-link-description-format "Email %c: %.30s"
1969 "Format of the description part of a link to an email or usenet message.
1970 The following %-escapes will be replaced by corresponding information:
1972 %F full \"From\" field
1973 %f name, taken from \"From\" field, address if no name
1974 %T full \"To\" field
1975 %t first name in \"To\" field, address if no name
1976 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1977 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1978 %s subject
1979 %d date
1980 %m message-id.
1982 You may use normal field width specification between the % and the letter.
1983 This is for example useful to limit the length of the subject.
1985 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1986 :group 'org-link-store
1987 :type 'string)
1989 (defcustom org-from-is-user-regexp
1990 (let (r1 r2)
1991 (when (and user-mail-address (not (string= user-mail-address "")))
1992 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1993 (when (and user-full-name (not (string= user-full-name "")))
1994 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1995 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1996 "Regexp matched against the \"From:\" header of an email or usenet message.
1997 It should match if the message is from the user him/herself."
1998 :group 'org-link-store
1999 :type 'regexp)
2001 (defcustom org-context-in-file-links t
2002 "Non-nil means file links from `org-store-link' contain context.
2003 \\<org-mode-map>
2004 A search string will be added to the file name with :: as separator
2005 and used to find the context when the link is activated by the command
2006 `org-open-at-point'. When this option is t, the entire active region
2007 will be placed in the search string of the file link. If set to a
2008 positive integer, only the first n lines of context will be stored.
2010 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2011 \\[org-store-link]')
2012 negates this setting for the duration of the command."
2013 :group 'org-link-store
2014 :type '(choice boolean integer))
2016 (defcustom org-keep-stored-link-after-insertion nil
2017 "Non-nil means keep link in list for entire session.
2018 \\<org-mode-map>
2019 The command `org-store-link' adds a link pointing to the current
2020 location to an internal list. These links accumulate during a session.
2021 The command `org-insert-link' can be used to insert links into any
2022 Org file (offering completion for all stored links).
2024 When this option is nil, every link which has been inserted once using
2025 `\\[org-insert-link]' will be removed from the list, to make completing the \
2026 unused
2027 links more efficient."
2028 :group 'org-link-store
2029 :type 'boolean)
2031 (defgroup org-link-follow nil
2032 "Options concerning following links in Org mode."
2033 :tag "Org Follow Link"
2034 :group 'org-link)
2036 (defcustom org-link-translation-function nil
2037 "Function to translate links with different syntax to Org syntax.
2038 This can be used to translate links created for example by the Planner
2039 or emacs-wiki packages to Org syntax.
2040 The function must accept two parameters, a TYPE containing the link
2041 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2042 which is everything after the link protocol. It should return a cons
2043 with possibly modified values of type and path.
2044 Org contains a function for this, so if you set this variable to
2045 `org-translate-link-from-planner', you should be able follow many
2046 links created by planner."
2047 :group 'org-link-follow
2048 :type '(choice (const nil) (function)))
2050 (defcustom org-follow-link-hook nil
2051 "Hook that is run after a link has been followed."
2052 :group 'org-link-follow
2053 :type 'hook)
2055 (defcustom org-tab-follows-link nil
2056 "Non-nil means on links TAB will follow the link.
2057 Needs to be set before org.el is loaded.
2058 This really should not be used, it does not make sense, and the
2059 implementation is bad."
2060 :group 'org-link-follow
2061 :type 'boolean)
2063 (defcustom org-return-follows-link nil
2064 "Non-nil means on links RET will follow the link.
2065 In tables, the special behavior of RET has precedence."
2066 :group 'org-link-follow
2067 :type 'boolean)
2069 (defcustom org-mouse-1-follows-link
2070 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2071 "Non-nil means mouse-1 on a link will follow the link.
2072 A longer mouse click will still set point. Needs to be set
2073 before org.el is loaded."
2074 :group 'org-link-follow
2075 :version "24.4"
2076 :package-version '(Org . "8.3")
2077 :type '(choice
2078 (const :tag "A double click follows the link" double)
2079 (const :tag "Unconditionally follow the link with mouse-1" t)
2080 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2082 (defcustom org-mark-ring-length 4
2083 "Number of different positions to be recorded in the ring.
2084 Changing this requires a restart of Emacs to work correctly."
2085 :group 'org-link-follow
2086 :type 'integer)
2088 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2089 "Non-nil means internal fuzzy links can only match headlines.
2091 When nil, the a fuzzy link may point to a target or a named
2092 construct in the document. When set to the special value
2093 `query-to-create', offer to create a new headline when none
2094 matched.
2096 Spaces and statistics cookies are ignored during heading searches."
2097 :group 'org-link-follow
2098 :version "24.1"
2099 :type '(choice
2100 (const :tag "Use fuzzy text search" nil)
2101 (const :tag "Match only exact headline" t)
2102 (const :tag "Match exact headline or query to create it"
2103 query-to-create))
2104 :safe #'symbolp)
2106 (defcustom org-link-frame-setup
2107 '((vm . vm-visit-folder-other-frame)
2108 (vm-imap . vm-visit-imap-folder-other-frame)
2109 (gnus . org-gnus-no-new-news)
2110 (file . find-file-other-window)
2111 (wl . wl-other-frame))
2112 "Setup the frame configuration for following links.
2113 When following a link with Emacs, it may often be useful to display
2114 this link in another window or frame. This variable can be used to
2115 set this up for the different types of links.
2116 For VM, use any of
2117 `vm-visit-folder'
2118 `vm-visit-folder-other-window'
2119 `vm-visit-folder-other-frame'
2120 For Gnus, use any of
2121 `gnus'
2122 `gnus-other-frame'
2123 `org-gnus-no-new-news'
2124 For FILE, use any of
2125 `find-file'
2126 `find-file-other-window'
2127 `find-file-other-frame'
2128 For Wanderlust use any of
2129 `wl'
2130 `wl-other-frame'
2131 For the calendar, use the variable `calendar-setup'.
2132 For BBDB, it is currently only possible to display the matches in
2133 another window."
2134 :group 'org-link-follow
2135 :type '(list
2136 (cons (const vm)
2137 (choice
2138 (const vm-visit-folder)
2139 (const vm-visit-folder-other-window)
2140 (const vm-visit-folder-other-frame)))
2141 (cons (const vm-imap)
2142 (choice
2143 (const vm-visit-imap-folder)
2144 (const vm-visit-imap-folder-other-window)
2145 (const vm-visit-imap-folder-other-frame)))
2146 (cons (const gnus)
2147 (choice
2148 (const gnus)
2149 (const gnus-other-frame)
2150 (const org-gnus-no-new-news)))
2151 (cons (const file)
2152 (choice
2153 (const find-file)
2154 (const find-file-other-window)
2155 (const find-file-other-frame)))
2156 (cons (const wl)
2157 (choice
2158 (const wl)
2159 (const wl-other-frame)))))
2161 (defcustom org-display-internal-link-with-indirect-buffer nil
2162 "Non-nil means use indirect buffer to display infile links.
2163 Activating internal links (from one location in a file to another location
2164 in the same file) normally just jumps to the location. When the link is
2165 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2166 is displayed in
2167 another window. When this option is set, the other window actually displays
2168 an indirect buffer clone of the current buffer, to avoid any visibility
2169 changes to the current buffer."
2170 :group 'org-link-follow
2171 :type 'boolean)
2173 (defcustom org-open-non-existing-files nil
2174 "Non-nil means `org-open-file' will open non-existing files.
2175 When nil, an error will be generated.
2176 This variable applies only to external applications because they
2177 might choke on non-existing files. If the link is to a file that
2178 will be opened in Emacs, the variable is ignored."
2179 :group 'org-link-follow
2180 :type 'boolean)
2182 (defcustom org-open-directory-means-index-dot-org nil
2183 "Non-nil means a link to a directory really means to index.org.
2184 When nil, following a directory link will run dired or open a finder/explorer
2185 window on that directory."
2186 :group 'org-link-follow
2187 :type 'boolean)
2189 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2190 "Non-nil means ask for confirmation before executing shell links.
2191 Shell links can be dangerous: just think about a link
2193 [[shell:rm -rf ~/*][Google Search]]
2195 This link would show up in your Org document as \"Google Search\",
2196 but really it would remove your entire home directory.
2197 Therefore we advise against setting this variable to nil.
2198 Just change it to `y-or-n-p' if you want to confirm with a
2199 single keystroke rather than having to type \"yes\"."
2200 :group 'org-link-follow
2201 :type '(choice
2202 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2203 (const :tag "with y-or-n (faster)" y-or-n-p)
2204 (const :tag "no confirmation (dangerous)" nil)))
2205 (put 'org-confirm-shell-link-function
2206 'safe-local-variable
2207 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2209 (defcustom org-confirm-shell-link-not-regexp ""
2210 "A regexp to skip confirmation for shell links."
2211 :group 'org-link-follow
2212 :version "24.1"
2213 :type 'regexp)
2215 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2216 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2217 Elisp links can be dangerous: just think about a link
2219 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2221 This link would show up in your Org document as \"Google Search\",
2222 but really it would remove your entire home directory.
2223 Therefore we advise against setting this variable to nil.
2224 Just change it to `y-or-n-p' if you want to confirm with a
2225 single keystroke rather than having to type \"yes\"."
2226 :group 'org-link-follow
2227 :type '(choice
2228 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2229 (const :tag "with y-or-n (faster)" y-or-n-p)
2230 (const :tag "no confirmation (dangerous)" nil)))
2231 (put 'org-confirm-shell-link-function
2232 'safe-local-variable
2233 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2235 (defcustom org-confirm-elisp-link-not-regexp ""
2236 "A regexp to skip confirmation for Elisp links."
2237 :group 'org-link-follow
2238 :version "24.1"
2239 :type 'regexp)
2241 (defconst org-file-apps-defaults-gnu
2242 '((remote . emacs)
2243 (system . mailcap)
2244 (t . mailcap))
2245 "Default file applications on a UNIX or GNU/Linux system.
2246 See `org-file-apps'.")
2248 (defconst org-file-apps-defaults-macosx
2249 '((remote . emacs)
2250 (system . "open %s")
2251 ("ps.gz" . "gv %s")
2252 ("eps.gz" . "gv %s")
2253 ("dvi" . "xdvi %s")
2254 ("fig" . "xfig %s")
2255 (t . "open %s"))
2256 "Default file applications on a macOS system.
2257 The system \"open\" is known as a default, but we use X11 applications
2258 for some files for which the OS does not have a good default.
2259 See `org-file-apps'.")
2261 (defconst org-file-apps-defaults-windowsnt
2262 (list '(remote . emacs)
2263 (cons 'system (lambda (file _path)
2264 (with-no-warnings (w32-shell-execute "open" file))))
2265 (cons t (lambda (file _path)
2266 (with-no-warnings (w32-shell-execute "open" file)))))
2267 "Default file applications on a Windows NT system.
2268 The system \"open\" is used for most files.
2269 See `org-file-apps'.")
2271 (defcustom org-file-apps
2272 '((auto-mode . emacs)
2273 ("\\.mm\\'" . default)
2274 ("\\.x?html?\\'" . default)
2275 ("\\.pdf\\'" . default))
2276 "External applications for opening `file:path' items in a document.
2277 \\<org-mode-map>\
2279 Org mode uses system defaults for different file types, but
2280 you can use this variable to set the application for a given file
2281 extension. The entries in this list are cons cells where the car identifies
2282 files and the cdr the corresponding command.
2284 Possible values for the file identifier are:
2286 \"string\" A string as a file identifier can be interpreted in different
2287 ways, depending on its contents:
2289 - Alphanumeric characters only:
2290 Match links with this file extension.
2291 Example: (\"pdf\" . \"evince %s\")
2292 to open PDFs with evince.
2294 - Regular expression: Match links where the
2295 filename matches the regexp. If you want to
2296 use groups here, use shy groups.
2298 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2299 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2300 to open *.html and *.xhtml with firefox.
2302 - Regular expression which contains (non-shy) groups:
2303 Match links where the whole link, including \"::\", and
2304 anything after that, matches the regexp.
2305 In a custom command string, %1, %2, etc. are replaced with
2306 the parts of the link that were matched by the groups.
2307 For backwards compatibility, if a command string is given
2308 that does not use any of the group matches, this case is
2309 handled identically to the second one (i.e. match against
2310 file name only).
2311 In a custom function, you can access the group matches with
2312 (match-string n link).
2314 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2315 \"evince -p %1 %s\")
2316 to open [[file:document.pdf::5]] with evince at page 5.
2318 `directory' Matches a directory
2319 `remote' Matches a remote file, accessible through tramp or efs.
2320 Remote files most likely should be visited through Emacs
2321 because external applications cannot handle such paths.
2322 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2323 so all files Emacs knows how to handle. Using this with
2324 command `emacs' will open most files in Emacs. Beware that this
2325 will also open html files inside Emacs, unless you add
2326 (\"html\" . default) to the list as well.
2327 `system' The system command to open files, like `open' on Windows
2328 and macOS, and mailcap under GNU/Linux. This is the command
2329 that will be selected if you call `org-open-at-point' with a
2330 double prefix argument (`\\[universal-argument] \
2331 \\[universal-argument] \\[org-open-at-point]').
2332 t Default for files not matched by any of the other options.
2334 Possible values for the command are:
2336 `emacs' The file will be visited by the current Emacs process.
2337 `default' Use the default application for this file type, which is the
2338 association for t in the list, most likely in the system-specific
2339 part. This can be used to overrule an unwanted setting in the
2340 system-specific variable.
2341 `system' Use the system command for opening files, like \"open\".
2342 This command is specified by the entry whose car is `system'.
2343 Most likely, the system-specific version of this variable
2344 does define this command, but you can overrule/replace it
2345 here.
2346 `mailcap' Use command specified in the mailcaps.
2347 string A command to be executed by a shell; %s will be replaced
2348 by the path to the file.
2349 function A Lisp function, which will be called with two arguments:
2350 the file path and the original link string, without the
2351 \"file:\" prefix.
2353 For more examples, see the system specific constants
2354 `org-file-apps-defaults-macosx'
2355 `org-file-apps-defaults-windowsnt'
2356 `org-file-apps-defaults-gnu'."
2357 :group 'org-link-follow
2358 :type '(repeat
2359 (cons (choice :value ""
2360 (string :tag "Extension")
2361 (const :tag "System command to open files" system)
2362 (const :tag "Default for unrecognized files" t)
2363 (const :tag "Remote file" remote)
2364 (const :tag "Links to a directory" directory)
2365 (const :tag "Any files that have Emacs modes"
2366 auto-mode))
2367 (choice :value ""
2368 (const :tag "Visit with Emacs" emacs)
2369 (const :tag "Use default" default)
2370 (const :tag "Use the system command" system)
2371 (string :tag "Command")
2372 (function :tag "Function")))))
2374 (defcustom org-doi-server-url "http://dx.doi.org/"
2375 "The URL of the DOI server."
2376 :type 'string
2377 :version "24.3"
2378 :group 'org-link-follow)
2380 (defgroup org-refile nil
2381 "Options concerning refiling entries in Org mode."
2382 :tag "Org Refile"
2383 :group 'org)
2385 (defcustom org-directory "~/org"
2386 "Directory with Org files.
2387 This is just a default location to look for Org files. There is no need
2388 at all to put your files into this directory. It is used in the
2389 following situations:
2391 1. When a capture template specifies a target file that is not an
2392 absolute path. The path will then be interpreted relative to
2393 `org-directory'
2394 2. When the value of variable `org-agenda-files' is a single file, any
2395 relative paths in this file will be taken as relative to
2396 `org-directory'."
2397 :group 'org-refile
2398 :group 'org-capture
2399 :type 'directory)
2401 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2402 "Default target for storing notes.
2403 Used as a fall back file for org-capture.el, for templates that
2404 do not specify a target file."
2405 :group 'org-refile
2406 :group 'org-capture
2407 :type 'file)
2409 (defcustom org-goto-interface 'outline
2410 "The default interface to be used for `org-goto'.
2411 Allowed values are:
2412 outline The interface shows an outline of the relevant file
2413 and the correct heading is found by moving through
2414 the outline or by searching with incremental search.
2415 outline-path-completion Headlines in the current buffer are offered via
2416 completion. This is the interface also used by
2417 the refile command."
2418 :group 'org-refile
2419 :type '(choice
2420 (const :tag "Outline" outline)
2421 (const :tag "Outline-path-completion" outline-path-completion)))
2423 (defcustom org-goto-max-level 5
2424 "Maximum target level when running `org-goto' with refile interface."
2425 :group 'org-refile
2426 :type 'integer)
2428 (defcustom org-reverse-note-order nil
2429 "Non-nil means store new notes at the beginning of a file or entry.
2430 When nil, new notes will be filed to the end of a file or entry.
2431 This can also be a list with cons cells of regular expressions that
2432 are matched against file names, and values."
2433 :group 'org-capture
2434 :group 'org-refile
2435 :type '(choice
2436 (const :tag "Reverse always" t)
2437 (const :tag "Reverse never" nil)
2438 (repeat :tag "By file name regexp"
2439 (cons regexp boolean))))
2441 (defcustom org-log-refile nil
2442 "Information to record when a task is refiled.
2444 Possible values are:
2446 nil Don't add anything
2447 time Add a time stamp to the task
2448 note Prompt for a note and add it with template `org-log-note-headings'
2450 This option can also be set with on a per-file-basis with
2452 #+STARTUP: nologrefile
2453 #+STARTUP: logrefile
2454 #+STARTUP: lognoterefile
2456 You can have local logging settings for a subtree by setting the LOGGING
2457 property to one or more of these keywords.
2459 When bulk-refiling from the agenda, the value `note' is forbidden and
2460 will temporarily be changed to `time'."
2461 :group 'org-refile
2462 :group 'org-progress
2463 :version "24.1"
2464 :type '(choice
2465 (const :tag "No logging" nil)
2466 (const :tag "Record timestamp" time)
2467 (const :tag "Record timestamp with note." note)))
2469 (defcustom org-refile-targets nil
2470 "Targets for refiling entries with `\\[org-refile]'.
2471 This is a list of cons cells. Each cell contains:
2472 - a specification of the files to be considered, either a list of files,
2473 or a symbol whose function or variable value will be used to retrieve
2474 a file name or a list of file names. If you use `org-agenda-files' for
2475 that, all agenda files will be scanned for targets. Nil means consider
2476 headings in the current buffer.
2477 - A specification of how to find candidate refile targets. This may be
2478 any of:
2479 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2480 This tag has to be present in all target headlines, inheritance will
2481 not be considered.
2482 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2483 todo keyword.
2484 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2485 headlines that are refiling targets.
2486 - a cons cell (:level . N). Any headline of level N is considered a target.
2487 Note that, when `org-odd-levels-only' is set, level corresponds to
2488 order in hierarchy, not to the number of stars.
2489 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2490 Note that, when `org-odd-levels-only' is set, level corresponds to
2491 order in hierarchy, not to the number of stars.
2493 Each element of this list generates a set of possible targets.
2494 The union of these sets is presented (with completion) to
2495 the user by `org-refile'.
2497 You can set the variable `org-refile-target-verify-function' to a function
2498 to verify each headline found by the simple criteria above.
2500 When this variable is nil, all top-level headlines in the current buffer
2501 are used, equivalent to the value `((nil . (:level . 1))'."
2502 :group 'org-refile
2503 :type '(repeat
2504 (cons
2505 (choice :value org-agenda-files
2506 (const :tag "All agenda files" org-agenda-files)
2507 (const :tag "Current buffer" nil)
2508 (function) (variable) (file))
2509 (choice :tag "Identify target headline by"
2510 (cons :tag "Specific tag" (const :value :tag) (string))
2511 (cons :tag "TODO keyword" (const :value :todo) (string))
2512 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2513 (cons :tag "Level number" (const :value :level) (integer))
2514 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2516 (defcustom org-refile-target-verify-function nil
2517 "Function to verify if the headline at point should be a refile target.
2518 The function will be called without arguments, with point at the
2519 beginning of the headline. It should return t and leave point
2520 where it is if the headline is a valid target for refiling.
2522 If the target should not be selected, the function must return nil.
2523 In addition to this, it may move point to a place from where the search
2524 should be continued. For example, the function may decide that the entire
2525 subtree of the current entry should be excluded and move point to the end
2526 of the subtree."
2527 :group 'org-refile
2528 :type '(choice
2529 (const nil)
2530 (function)))
2532 (defcustom org-refile-use-cache nil
2533 "Non-nil means cache refile targets to speed up the process.
2534 \\<org-mode-map>\
2535 The cache for a particular file will be updated automatically when
2536 the buffer has been killed, or when any of the marker used for flagging
2537 refile targets no longer points at a live buffer.
2538 If you have added new entries to a buffer that might themselves be targets,
2539 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2540 if you find that easier, \
2541 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2542 \\[org-refile]'."
2543 :group 'org-refile
2544 :version "24.1"
2545 :type 'boolean)
2547 (defcustom org-refile-use-outline-path nil
2548 "Non-nil means provide refile targets as paths.
2549 So a level 3 headline will be available as level1/level2/level3.
2551 When the value is `file', also include the file name (without directory)
2552 into the path. In this case, you can also stop the completion after
2553 the file name, to get entries inserted as top level in the file.
2555 When `full-file-path', include the full file path."
2556 :group 'org-refile
2557 :type '(choice
2558 (const :tag "Not" nil)
2559 (const :tag "Yes" t)
2560 (const :tag "Start with file name" file)
2561 (const :tag "Start with full file path" full-file-path)))
2563 (defcustom org-outline-path-complete-in-steps t
2564 "Non-nil means complete the outline path in hierarchical steps.
2565 When Org uses the refile interface to select an outline path (see
2566 `org-refile-use-outline-path'), the completion of the path can be
2567 done in a single go, or it can be done in steps down the headline
2568 hierarchy. Going in steps is probably the best if you do not use
2569 a special completion package like `ido' or `icicles'. However,
2570 when using these packages, going in one step can be very fast,
2571 while still showing the whole path to the entry."
2572 :group 'org-refile
2573 :type 'boolean)
2575 (defcustom org-refile-allow-creating-parent-nodes nil
2576 "Non-nil means allow the creation of new nodes as refile targets.
2577 New nodes are then created by adding \"/new node name\" to the completion
2578 of an existing node. When the value of this variable is `confirm',
2579 new node creation must be confirmed by the user (recommended).
2580 When nil, the completion must match an existing entry.
2582 Note that, if the new heading is not seen by the criteria
2583 listed in `org-refile-targets', multiple instances of the same
2584 heading would be created by trying again to file under the new
2585 heading."
2586 :group 'org-refile
2587 :type '(choice
2588 (const :tag "Never" nil)
2589 (const :tag "Always" t)
2590 (const :tag "Prompt for confirmation" confirm)))
2592 (defcustom org-refile-active-region-within-subtree nil
2593 "Non-nil means also refile active region within a subtree.
2595 By default `org-refile' doesn't allow refiling regions if they
2596 don't contain a set of subtrees, but it might be convenient to
2597 do so sometimes: in that case, the first line of the region is
2598 converted to a headline before refiling."
2599 :group 'org-refile
2600 :version "24.1"
2601 :type 'boolean)
2603 (defgroup org-todo nil
2604 "Options concerning TODO items in Org mode."
2605 :tag "Org TODO"
2606 :group 'org)
2608 (defgroup org-progress nil
2609 "Options concerning Progress logging in Org mode."
2610 :tag "Org Progress"
2611 :group 'org-time)
2613 (defvar org-todo-interpretation-widgets
2614 '((:tag "Sequence (cycling hits every state)" sequence)
2615 (:tag "Type (cycling directly to DONE)" type))
2616 "The available interpretation symbols for customizing `org-todo-keywords'.
2617 Interested libraries should add to this list.")
2619 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2620 "List of TODO entry keyword sequences and their interpretation.
2621 \\<org-mode-map>This is a list of sequences.
2623 Each sequence starts with a symbol, either `sequence' or `type',
2624 indicating if the keywords should be interpreted as a sequence of
2625 action steps, or as different types of TODO items. The first
2626 keywords are states requiring action - these states will select a headline
2627 for inclusion into the global TODO list Org produces. If one of the
2628 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2629 signify that no further action is necessary. If \"|\" is not found,
2630 the last keyword is treated as the only DONE state of the sequence.
2632 The command `\\[org-todo]' cycles an entry through these states, and one
2633 additional state where no keyword is present. For details about this
2634 cycling, see the manual.
2636 TODO keywords and interpretation can also be set on a per-file basis with
2637 the special #+SEQ_TODO and #+TYP_TODO lines.
2639 Each keyword can optionally specify a character for fast state selection
2640 \(in combination with the variable `org-use-fast-todo-selection')
2641 and specifiers for state change logging, using the same syntax that
2642 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2643 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2644 indicates to record a time stamp each time this state is selected.
2646 Each keyword may also specify if a timestamp or a note should be
2647 recorded when entering or leaving the state, by adding additional
2648 characters in the parenthesis after the keyword. This looks like this:
2649 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2650 record only the time of the state change. With X and Y being either
2651 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2652 Y when leaving the state if and only if the *target* state does not
2653 define X. You may omit any of the fast-selection key or X or /Y,
2654 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2656 For backward compatibility, this variable may also be just a list
2657 of keywords. In this case the interpretation (sequence or type) will be
2658 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2659 :group 'org-todo
2660 :group 'org-keywords
2661 :type '(choice
2662 (repeat :tag "Old syntax, just keywords"
2663 (string :tag "Keyword"))
2664 (repeat :tag "New syntax"
2665 (cons
2666 (choice
2667 :tag "Interpretation"
2668 ;;Quick and dirty way to see
2669 ;;`org-todo-interpretations'. This takes the
2670 ;;place of item arguments
2671 :convert-widget
2672 (lambda (widget)
2673 (widget-put widget
2674 :args (mapcar
2675 (lambda (x)
2676 (widget-convert
2677 (cons 'const x)))
2678 org-todo-interpretation-widgets))
2679 widget))
2680 (repeat
2681 (string :tag "Keyword"))))))
2683 (defvar-local org-todo-keywords-1 nil
2684 "All TODO and DONE keywords active in a buffer.")
2685 (defvar org-todo-keywords-for-agenda nil)
2686 (defvar org-done-keywords-for-agenda nil)
2687 (defvar org-todo-keyword-alist-for-agenda nil)
2688 (defvar org-tag-alist-for-agenda nil
2689 "Alist of all tags from all agenda files.")
2690 (defvar org-tag-groups-alist-for-agenda nil
2691 "Alist of all groups tags from all current agenda files.")
2692 (defvar-local org-tag-groups-alist nil)
2693 (defvar org-agenda-contributing-files nil)
2694 (defvar-local org-current-tag-alist nil
2695 "Alist of all tag groups in current buffer.
2696 This variable takes into consideration `org-tag-alist',
2697 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2698 (defvar-local org-not-done-keywords nil)
2699 (defvar-local org-done-keywords nil)
2700 (defvar-local org-todo-heads nil)
2701 (defvar-local org-todo-sets nil)
2702 (defvar-local org-todo-log-states nil)
2703 (defvar-local org-todo-kwd-alist nil)
2704 (defvar-local org-todo-key-alist nil)
2705 (defvar-local org-todo-key-trigger nil)
2707 (defcustom org-todo-interpretation 'sequence
2708 "Controls how TODO keywords are interpreted.
2709 This variable is in principle obsolete and is only used for
2710 backward compatibility, if the interpretation of todo keywords is
2711 not given already in `org-todo-keywords'. See that variable for
2712 more information."
2713 :group 'org-todo
2714 :group 'org-keywords
2715 :type '(choice (const sequence)
2716 (const type)))
2718 (defcustom org-use-fast-todo-selection t
2719 "\\<org-mode-map>\
2720 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2721 This variable describes if and under what circumstances the cycling
2722 mechanism for TODO keywords will be replaced by a single-key, direct
2723 selection scheme.
2725 When nil, fast selection is never used.
2727 When the symbol `prefix', it will be used when `org-todo' is called
2728 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2729 in an Org buffer, and
2730 `\\[universal-argument] t' in an agenda buffer.
2732 When t, fast selection is used by default. In this case, the prefix
2733 argument forces cycling instead.
2735 In all cases, the special interface is only used if access keys have
2736 actually been assigned by the user, i.e. if keywords in the configuration
2737 are followed by a letter in parenthesis, like TODO(t)."
2738 :group 'org-todo
2739 :type '(choice
2740 (const :tag "Never" nil)
2741 (const :tag "By default" t)
2742 (const :tag "Only with C-u C-c C-t" prefix)))
2744 (defcustom org-provide-todo-statistics t
2745 "Non-nil means update todo statistics after insert and toggle.
2746 ALL-HEADLINES means update todo statistics by including headlines
2747 with no TODO keyword as well, counting them as not done.
2748 A list of TODO keywords means the same, but skip keywords that are
2749 not in this list.
2750 When set to a list of two lists, the first list contains keywords
2751 to consider as TODO keywords, the second list contains keywords
2752 to consider as DONE keywords.
2754 When this is set, todo statistics is updated in the parent of the
2755 current entry each time a todo state is changed."
2756 :group 'org-todo
2757 :type '(choice
2758 (const :tag "Yes, only for TODO entries" t)
2759 (const :tag "Yes, including all entries" all-headlines)
2760 (repeat :tag "Yes, for TODOs in this list"
2761 (string :tag "TODO keyword"))
2762 (list :tag "Yes, for TODOs and DONEs in these lists"
2763 (repeat (string :tag "TODO keyword"))
2764 (repeat (string :tag "DONE keyword")))
2765 (other :tag "No TODO statistics" nil)))
2767 (defcustom org-hierarchical-todo-statistics t
2768 "Non-nil means TODO statistics covers just direct children.
2769 When nil, all entries in the subtree are considered.
2770 This has only an effect if `org-provide-todo-statistics' is set.
2771 To set this to nil for only a single subtree, use a COOKIE_DATA
2772 property and include the word \"recursive\" into the value."
2773 :group 'org-todo
2774 :type 'boolean)
2776 (defcustom org-after-todo-state-change-hook nil
2777 "Hook which is run after the state of a TODO item was changed.
2778 The new state (a string with a TODO keyword, or nil) is available in the
2779 Lisp variable `org-state'."
2780 :group 'org-todo
2781 :type 'hook)
2783 (defvar org-blocker-hook nil
2784 "Hook for functions that are allowed to block a state change.
2786 Functions in this hook should not modify the buffer.
2787 Each function gets as its single argument a property list,
2788 see `org-trigger-hook' for more information about this list.
2790 If any of the functions in this hook returns nil, the state change
2791 is blocked.")
2793 (defvar org-trigger-hook nil
2794 "Hook for functions that are triggered by a state change.
2796 Each function gets as its single argument a property list with at
2797 least the following elements:
2799 (:type type-of-change :position pos-at-entry-start
2800 :from old-state :to new-state)
2802 Depending on the type, more properties may be present.
2804 This mechanism is currently implemented for:
2806 TODO state changes
2807 ------------------
2808 :type todo-state-change
2809 :from previous state (keyword as a string), or nil, or a symbol
2810 `todo' or `done', to indicate the general type of state.
2811 :to new state, like in :from")
2813 (defcustom org-enforce-todo-dependencies nil
2814 "Non-nil means undone TODO entries will block switching the parent to DONE.
2815 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2816 be blocked if any prior sibling is not yet done.
2817 Finally, if the parent is blocked because of ordered siblings of its own,
2818 the child will also be blocked."
2819 :set (lambda (var val)
2820 (set var val)
2821 (if val
2822 (add-hook 'org-blocker-hook
2823 'org-block-todo-from-children-or-siblings-or-parent)
2824 (remove-hook 'org-blocker-hook
2825 'org-block-todo-from-children-or-siblings-or-parent)))
2826 :group 'org-todo
2827 :type 'boolean)
2829 (defcustom org-enforce-todo-checkbox-dependencies nil
2830 "Non-nil means unchecked boxes will block switching the parent to DONE.
2831 When this is nil, checkboxes have no influence on switching TODO states.
2832 When non-nil, you first need to check off all check boxes before the TODO
2833 entry can be switched to DONE.
2834 This variable needs to be set before org.el is loaded, and you need to
2835 restart Emacs after a change to make the change effective. The only way
2836 to change is while Emacs is running is through the customize interface."
2837 :set (lambda (var val)
2838 (set var val)
2839 (if val
2840 (add-hook 'org-blocker-hook
2841 'org-block-todo-from-checkboxes)
2842 (remove-hook 'org-blocker-hook
2843 'org-block-todo-from-checkboxes)))
2844 :group 'org-todo
2845 :type 'boolean)
2847 (defcustom org-treat-insert-todo-heading-as-state-change nil
2848 "Non-nil means inserting a TODO heading is treated as state change.
2849 So when the command `\\[org-insert-todo-heading]' is used, state change
2850 logging will apply if appropriate. When nil, the new TODO item will
2851 be inserted directly, and no logging will take place."
2852 :group 'org-todo
2853 :type 'boolean)
2855 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2856 "Non-nil means switching TODO states with S-cursor counts as state change.
2857 This is the default behavior. However, setting this to nil allows a
2858 convenient way to select a TODO state and bypass any logging associated
2859 with that."
2860 :group 'org-todo
2861 :type 'boolean)
2863 (defcustom org-todo-state-tags-triggers nil
2864 "Tag changes that should be triggered by TODO state changes.
2865 This is a list. Each entry is
2867 (state-change (tag . flag) .......)
2869 State-change can be a string with a state, and empty string to indicate the
2870 state that has no TODO keyword, or it can be one of the symbols `todo'
2871 or `done', meaning any not-done or done state, respectively."
2872 :group 'org-todo
2873 :group 'org-tags
2874 :type '(repeat
2875 (cons (choice :tag "When changing to"
2876 (const :tag "Not-done state" todo)
2877 (const :tag "Done state" done)
2878 (string :tag "State"))
2879 (repeat
2880 (cons :tag "Tag action"
2881 (string :tag "Tag")
2882 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2884 (defcustom org-log-done nil
2885 "Information to record when a task moves to the DONE state.
2887 Possible values are:
2889 nil Don't add anything, just change the keyword
2890 time Add a time stamp to the task
2891 note Prompt for a note and add it with template `org-log-note-headings'
2893 This option can also be set with on a per-file-basis with
2895 #+STARTUP: nologdone
2896 #+STARTUP: logdone
2897 #+STARTUP: lognotedone
2899 You can have local logging settings for a subtree by setting the LOGGING
2900 property to one or more of these keywords."
2901 :group 'org-todo
2902 :group 'org-progress
2903 :type '(choice
2904 (const :tag "No logging" nil)
2905 (const :tag "Record CLOSED timestamp" time)
2906 (const :tag "Record CLOSED timestamp with note." note)))
2908 ;; Normalize old uses of org-log-done.
2909 (cond
2910 ((eq org-log-done t) (setq org-log-done 'time))
2911 ((and (listp org-log-done) (memq 'done org-log-done))
2912 (setq org-log-done 'note)))
2914 (defcustom org-log-reschedule nil
2915 "Information to record when the scheduling date of a tasks is modified.
2917 Possible values are:
2919 nil Don't add anything, just change the date
2920 time Add a time stamp to the task
2921 note Prompt for a note and add it with template `org-log-note-headings'
2923 This option can also be set with on a per-file-basis with
2925 #+STARTUP: nologreschedule
2926 #+STARTUP: logreschedule
2927 #+STARTUP: lognotereschedule"
2928 :group 'org-todo
2929 :group 'org-progress
2930 :type '(choice
2931 (const :tag "No logging" nil)
2932 (const :tag "Record timestamp" time)
2933 (const :tag "Record timestamp with note." note)))
2935 (defcustom org-log-redeadline nil
2936 "Information to record when the deadline date of a tasks is modified.
2938 Possible values are:
2940 nil Don't add anything, just change the date
2941 time Add a time stamp to the task
2942 note Prompt for a note and add it with template `org-log-note-headings'
2944 This option can also be set with on a per-file-basis with
2946 #+STARTUP: nologredeadline
2947 #+STARTUP: logredeadline
2948 #+STARTUP: lognoteredeadline
2950 You can have local logging settings for a subtree by setting the LOGGING
2951 property to one or more of these keywords."
2952 :group 'org-todo
2953 :group 'org-progress
2954 :type '(choice
2955 (const :tag "No logging" nil)
2956 (const :tag "Record timestamp" time)
2957 (const :tag "Record timestamp with note." note)))
2959 (defcustom org-log-note-clock-out nil
2960 "Non-nil means record a note when clocking out of an item.
2961 This can also be configured on a per-file basis by adding one of
2962 the following lines anywhere in the buffer:
2964 #+STARTUP: lognoteclock-out
2965 #+STARTUP: nolognoteclock-out"
2966 :group 'org-todo
2967 :group 'org-progress
2968 :type 'boolean)
2970 (defcustom org-log-done-with-time t
2971 "Non-nil means the CLOSED time stamp will contain date and time.
2972 When nil, only the date will be recorded."
2973 :group 'org-progress
2974 :type 'boolean)
2976 (defcustom org-log-note-headings
2977 '((done . "CLOSING NOTE %t")
2978 (state . "State %-12s from %-12S %t")
2979 (note . "Note taken on %t")
2980 (reschedule . "Rescheduled from %S on %t")
2981 (delschedule . "Not scheduled, was %S on %t")
2982 (redeadline . "New deadline from %S on %t")
2983 (deldeadline . "Removed deadline, was %S on %t")
2984 (refile . "Refiled on %t")
2985 (clock-out . ""))
2986 "Headings for notes added to entries.
2988 The value is an alist, with the car being a symbol indicating the
2989 note context, and the cdr is the heading to be used. The heading
2990 may also be the empty string. The following placeholders can be
2991 used:
2993 %t a time stamp.
2994 %T an active time stamp instead the default inactive one
2995 %d a short-format time stamp.
2996 %D an active short-format time stamp.
2997 %s the new TODO state or time stamp (inactive), in double quotes.
2998 %S the old TODO state or time stamp (inactive), in double quotes.
2999 %u the user name.
3000 %U full user name.
3002 In fact, it is not a good idea to change the `state' entry,
3003 because Agenda Log mode depends on the format of these entries."
3004 :group 'org-todo
3005 :group 'org-progress
3006 :type '(list :greedy t
3007 (cons (const :tag "Heading when closing an item" done) string)
3008 (cons (const :tag
3009 "Heading when changing todo state (todo sequence only)"
3010 state) string)
3011 (cons (const :tag "Heading when just taking a note" note) string)
3012 (cons (const :tag "Heading when rescheduling" reschedule) string)
3013 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3014 (cons (const :tag "Heading when changing deadline" redeadline) string)
3015 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3016 (cons (const :tag "Heading when refiling" refile) string)
3017 (cons (const :tag "Heading when clocking out" clock-out) string)))
3019 (unless (assq 'note org-log-note-headings)
3020 (push '(note . "%t") org-log-note-headings))
3022 (defcustom org-log-into-drawer nil
3023 "Non-nil means insert state change notes and time stamps into a drawer.
3024 When nil, state changes notes will be inserted after the headline and
3025 any scheduling and clock lines, but not inside a drawer.
3027 The value of this variable should be the name of the drawer to use.
3028 LOGBOOK is proposed as the default drawer for this purpose, you can
3029 also set this to a string to define the drawer of your choice.
3031 A value of t is also allowed, representing \"LOGBOOK\".
3033 A value of t or nil can also be set with on a per-file-basis with
3035 #+STARTUP: logdrawer
3036 #+STARTUP: nologdrawer
3038 If this variable is set, `org-log-state-notes-insert-after-drawers'
3039 will be ignored.
3041 You can set the property LOG_INTO_DRAWER to overrule this setting for
3042 a subtree.
3044 Do not check directly this variable in a Lisp program. Call
3045 function `org-log-into-drawer' instead."
3046 :group 'org-todo
3047 :group 'org-progress
3048 :type '(choice
3049 (const :tag "Not into a drawer" nil)
3050 (const :tag "LOGBOOK" t)
3051 (string :tag "Other")))
3053 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3055 (defun org-log-into-drawer ()
3056 "Name of the log drawer, as a string, or nil.
3057 This is the value of `org-log-into-drawer'. However, if the
3058 current entry has or inherits a LOG_INTO_DRAWER property, it will
3059 be used instead of the default value."
3060 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3061 (cond ((equal p "nil") nil)
3062 ((equal p "t") "LOGBOOK")
3063 ((stringp p) p)
3064 (p "LOGBOOK")
3065 ((stringp org-log-into-drawer) org-log-into-drawer)
3066 (org-log-into-drawer "LOGBOOK"))))
3068 (defcustom org-log-state-notes-insert-after-drawers nil
3069 "Non-nil means insert state change notes after any drawers in entry.
3070 Only the drawers that *immediately* follow the headline and the
3071 deadline/scheduled line are skipped.
3072 When nil, insert notes right after the heading and perhaps the line
3073 with deadline/scheduling if present.
3075 This variable will have no effect if `org-log-into-drawer' is
3076 set."
3077 :group 'org-todo
3078 :group 'org-progress
3079 :type 'boolean)
3081 (defcustom org-log-states-order-reversed t
3082 "Non-nil means the latest state note will be directly after heading.
3083 When nil, the state change notes will be ordered according to time.
3085 This option can also be set with on a per-file-basis with
3087 #+STARTUP: logstatesreversed
3088 #+STARTUP: nologstatesreversed"
3089 :group 'org-todo
3090 :group 'org-progress
3091 :type 'boolean)
3093 (defcustom org-todo-repeat-to-state nil
3094 "The TODO state to which a repeater should return the repeating task.
3095 By default this is the first task in a TODO sequence, or the previous state
3096 in a TODO_TYP set. But you can specify another task here.
3097 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3098 :group 'org-todo
3099 :version "24.1"
3100 :type '(choice (const :tag "Head of sequence" nil)
3101 (string :tag "Specific state")))
3103 (defcustom org-log-repeat 'time
3104 "Non-nil means record moving through the DONE state when triggering repeat.
3105 An auto-repeating task is immediately switched back to TODO when
3106 marked DONE. If you are not logging state changes (by adding \"@\"
3107 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3108 record a closing note, there will be no record of the task moving
3109 through DONE. This variable forces taking a note anyway.
3111 nil Don't force a record
3112 time Record a time stamp
3113 note Prompt for a note and add it with template `org-log-note-headings'
3115 This option can also be set with on a per-file-basis with
3117 #+STARTUP: nologrepeat
3118 #+STARTUP: logrepeat
3119 #+STARTUP: lognoterepeat
3121 You can have local logging settings for a subtree by setting the LOGGING
3122 property to one or more of these keywords."
3123 :group 'org-todo
3124 :group 'org-progress
3125 :type '(choice
3126 (const :tag "Don't force a record" nil)
3127 (const :tag "Force recording the DONE state" time)
3128 (const :tag "Force recording a note with the DONE state" note)))
3131 (defgroup org-priorities nil
3132 "Priorities in Org mode."
3133 :tag "Org Priorities"
3134 :group 'org-todo)
3136 (defcustom org-enable-priority-commands t
3137 "Non-nil means priority commands are active.
3138 When nil, these commands will be disabled, so that you never accidentally
3139 set a priority."
3140 :group 'org-priorities
3141 :type 'boolean)
3143 (defcustom org-highest-priority ?A
3144 "The highest priority of TODO items. A character like ?A, ?B etc.
3145 Must have a smaller ASCII number than `org-lowest-priority'."
3146 :group 'org-priorities
3147 :type 'character)
3149 (defcustom org-lowest-priority ?C
3150 "The lowest priority of TODO items. A character like ?A, ?B etc.
3151 Must have a larger ASCII number than `org-highest-priority'."
3152 :group 'org-priorities
3153 :type 'character)
3155 (defcustom org-default-priority ?B
3156 "The default priority of TODO items.
3157 This is the priority an item gets if no explicit priority is given.
3158 When starting to cycle on an empty priority the first step in the cycle
3159 depends on `org-priority-start-cycle-with-default'. The resulting first
3160 step priority must not exceed the range from `org-highest-priority' to
3161 `org-lowest-priority' which means that `org-default-priority' has to be
3162 in this range exclusive or inclusive the range boundaries. Else the
3163 first step refuses to set the default and the second will fall back
3164 to (depending on the command used) the highest or lowest priority."
3165 :group 'org-priorities
3166 :type 'character)
3168 (defcustom org-priority-start-cycle-with-default t
3169 "Non-nil means start with default priority when starting to cycle.
3170 When this is nil, the first step in the cycle will be (depending on the
3171 command used) one higher or lower than the default priority.
3172 See also `org-default-priority'."
3173 :group 'org-priorities
3174 :type 'boolean)
3176 (defcustom org-get-priority-function nil
3177 "Function to extract the priority from a string.
3178 The string is normally the headline. If this is nil Org computes the
3179 priority from the priority cookie like [#A] in the headline. It returns
3180 an integer, increasing by 1000 for each priority level.
3181 The user can set a different function here, which should take a string
3182 as an argument and return the numeric priority."
3183 :group 'org-priorities
3184 :version "24.1"
3185 :type '(choice
3186 (const nil)
3187 (function)))
3189 (defgroup org-time nil
3190 "Options concerning time stamps and deadlines in Org mode."
3191 :tag "Org Time"
3192 :group 'org)
3194 (defcustom org-time-stamp-rounding-minutes '(0 5)
3195 "Number of minutes to round time stamps to.
3196 \\<org-mode-map>\
3197 These are two values, the first applies when first creating a time stamp.
3198 The second applies when changing it with the commands `S-up' and `S-down'.
3199 When changing the time stamp, this means that it will change in steps
3200 of N minutes, as given by the second value.
3202 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3203 numbers should be factors of 60, so for example 5, 10, 15.
3205 When this is larger than 1, you can still force an exact time stamp by using
3206 a double prefix argument to a time stamp command like \
3207 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3208 and by using a prefix arg to `S-up/down' to specify the exact number
3209 of minutes to shift."
3210 :group 'org-time
3211 :get (lambda (var) ; Make sure both elements are there
3212 (if (integerp (default-value var))
3213 (list (default-value var) 5)
3214 (default-value var)))
3215 :type '(list
3216 (integer :tag "when inserting times")
3217 (integer :tag "when modifying times")))
3219 ;; Normalize old customizations of this variable.
3220 (when (integerp org-time-stamp-rounding-minutes)
3221 (setq org-time-stamp-rounding-minutes
3222 (list org-time-stamp-rounding-minutes
3223 org-time-stamp-rounding-minutes)))
3225 (defcustom org-display-custom-times nil
3226 "Non-nil means overlay custom formats over all time stamps.
3227 The formats are defined through the variable `org-time-stamp-custom-formats'.
3228 To turn this on on a per-file basis, insert anywhere in the file:
3229 #+STARTUP: customtime"
3230 :group 'org-time
3231 :set 'set-default
3232 :type 'sexp)
3233 (make-variable-buffer-local 'org-display-custom-times)
3235 (defcustom org-time-stamp-custom-formats
3236 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3237 "Custom formats for time stamps. See `format-time-string' for the syntax.
3238 These are overlaid over the default ISO format if the variable
3239 `org-display-custom-times' is set. Time like %H:%M should be at the
3240 end of the second format. The custom formats are also honored by export
3241 commands, if custom time display is turned on at the time of export."
3242 :group 'org-time
3243 :type 'sexp)
3245 (defun org-time-stamp-format (&optional long inactive)
3246 "Get the right format for a time string."
3247 (let ((f (if long (cdr org-time-stamp-formats)
3248 (car org-time-stamp-formats))))
3249 (if inactive
3250 (concat "[" (substring f 1 -1) "]")
3251 f)))
3253 (defcustom org-time-clocksum-format
3254 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3255 "The format string used when creating CLOCKSUM lines.
3256 This is also used when Org mode generates a time duration.
3258 The value can be a single format string containing two
3259 %-sequences, which will be filled with the number of hours and
3260 minutes in that order.
3262 Alternatively, the value can be a plist associating any of the
3263 keys :years, :months, :weeks, :days, :hours or :minutes with
3264 format strings. The time duration is formatted using only the
3265 time components that are needed and concatenating the results.
3266 If a time unit in absent, it falls back to the next smallest
3267 unit.
3269 The keys :require-years, :require-months, :require-days,
3270 :require-weeks, :require-hours, :require-minutes are also
3271 meaningful. A non-nil value for these keys indicates that the
3272 corresponding time component should always be included, even if
3273 its value is 0.
3276 For example,
3278 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3279 :require-minutes t)
3281 means durations longer than a day will be expressed in days,
3282 hours and minutes, and durations less than a day will always be
3283 expressed in hours and minutes (even for durations less than an
3284 hour).
3286 The value
3288 (:days \"%dd\" :minutes \"%dm\")
3290 means durations longer than a day will be expressed in days and
3291 minutes, and durations less than a day will be expressed entirely
3292 in minutes (even for durations longer than an hour)."
3293 :group 'org-time
3294 :group 'org-clock
3295 :version "24.4"
3296 :package-version '(Org . "8.0")
3297 :type '(choice (string :tag "Format string")
3298 (set :tag "Plist"
3299 (group :inline t (const :tag "Years" :years)
3300 (string :tag "Format string"))
3301 (group :inline t
3302 (const :tag "Always show years" :require-years)
3303 (const t))
3304 (group :inline t (const :tag "Months" :months)
3305 (string :tag "Format string"))
3306 (group :inline t
3307 (const :tag "Always show months" :require-months)
3308 (const t))
3309 (group :inline t (const :tag "Weeks" :weeks)
3310 (string :tag "Format string"))
3311 (group :inline t
3312 (const :tag "Always show weeks" :require-weeks)
3313 (const t))
3314 (group :inline t (const :tag "Days" :days)
3315 (string :tag "Format string"))
3316 (group :inline t
3317 (const :tag "Always show days" :require-days)
3318 (const t))
3319 (group :inline t (const :tag "Hours" :hours)
3320 (string :tag "Format string"))
3321 (group :inline t
3322 (const :tag "Always show hours" :require-hours)
3323 (const t))
3324 (group :inline t (const :tag "Minutes" :minutes)
3325 (string :tag "Format string"))
3326 (group :inline t
3327 (const :tag "Always show minutes" :require-minutes)
3328 (const t)))))
3330 (defcustom org-time-clocksum-use-fractional nil
3331 "When non-nil, `\\[org-clock-display]' uses fractional times.
3332 See `org-time-clocksum-format' for more on time clock formats."
3333 :group 'org-time
3334 :group 'org-clock
3335 :version "24.3"
3336 :type 'boolean)
3338 (defcustom org-time-clocksum-use-effort-durations nil
3339 "When non-nil, `\\[org-clock-display]' uses effort durations.
3340 E.g. by default, one day is considered to be a 8 hours effort,
3341 so a task that has been clocked for 16 hours will be displayed
3342 as during 2 days in the clock display or in the clocktable.
3344 See `org-effort-durations' on how to set effort durations
3345 and `org-time-clocksum-format' for more on time clock formats."
3346 :group 'org-time
3347 :group 'org-clock
3348 :version "24.4"
3349 :package-version '(Org . "8.0")
3350 :type 'boolean)
3352 (defcustom org-time-clocksum-fractional-format "%.2f"
3353 "The format string used when creating CLOCKSUM lines,
3354 or when Org mode generates a time duration, if
3355 `org-time-clocksum-use-fractional' is enabled.
3357 The value can be a single format string containing one
3358 %-sequence, which will be filled with the number of hours as
3359 a float.
3361 Alternatively, the value can be a plist associating any of the
3362 keys :years, :months, :weeks, :days, :hours or :minutes with
3363 a format string. The time duration is formatted using the
3364 largest time unit which gives a non-zero integer part. If all
3365 specified formats have zero integer part, the smallest time unit
3366 is used."
3367 :group 'org-time
3368 :type '(choice (string :tag "Format string")
3369 (set (group :inline t (const :tag "Years" :years)
3370 (string :tag "Format string"))
3371 (group :inline t (const :tag "Months" :months)
3372 (string :tag "Format string"))
3373 (group :inline t (const :tag "Weeks" :weeks)
3374 (string :tag "Format string"))
3375 (group :inline t (const :tag "Days" :days)
3376 (string :tag "Format string"))
3377 (group :inline t (const :tag "Hours" :hours)
3378 (string :tag "Format string"))
3379 (group :inline t (const :tag "Minutes" :minutes)
3380 (string :tag "Format string")))))
3382 (defcustom org-deadline-warning-days 14
3383 "Number of days before expiration during which a deadline becomes active.
3384 This variable governs the display in sparse trees and in the agenda.
3385 When 0 or negative, it means use this number (the absolute value of it)
3386 even if a deadline has a different individual lead time specified.
3388 Custom commands can set this variable in the options section."
3389 :group 'org-time
3390 :group 'org-agenda-daily/weekly
3391 :type 'integer)
3393 (defcustom org-scheduled-delay-days 0
3394 "Number of days before a scheduled item becomes active.
3395 This variable governs the display in sparse trees and in the agenda.
3396 The default value (i.e. 0) means: don't delay scheduled item.
3397 When negative, it means use this number (the absolute value of it)
3398 even if a scheduled item has a different individual delay time
3399 specified.
3401 Custom commands can set this variable in the options section."
3402 :group 'org-time
3403 :group 'org-agenda-daily/weekly
3404 :version "24.4"
3405 :package-version '(Org . "8.0")
3406 :type 'integer)
3408 (defcustom org-read-date-prefer-future t
3409 "Non-nil means assume future for incomplete date input from user.
3410 This affects the following situations:
3411 1. The user gives a month but not a year.
3412 For example, if it is April and you enter \"feb 2\", this will be read
3413 as Feb 2, *next* year. \"May 5\", however, will be this year.
3414 2. The user gives a day, but no month.
3415 For example, if today is the 15th, and you enter \"3\", Org will read
3416 this as the third of *next* month. However, if you enter \"17\",
3417 it will be considered as *this* month.
3419 If you set this variable to the symbol `time', then also the following
3420 will work:
3422 3. If the user gives a time.
3423 If the time is before now, it will be interpreted as tomorrow.
3425 Currently none of this works for ISO week specifications.
3427 When this option is nil, the current day, month and year will always be
3428 used as defaults.
3430 See also `org-agenda-jump-prefer-future'."
3431 :group 'org-time
3432 :type '(choice
3433 (const :tag "Never" nil)
3434 (const :tag "Check month and day" t)
3435 (const :tag "Check month, day, and time" time)))
3437 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3438 "Should the agenda jump command prefer the future for incomplete dates?
3439 The default is to do the same as configured in `org-read-date-prefer-future'.
3440 But you can also set a deviating value here.
3441 This may t or nil, or the symbol `org-read-date-prefer-future'."
3442 :group 'org-agenda
3443 :group 'org-time
3444 :version "24.1"
3445 :type '(choice
3446 (const :tag "Use org-read-date-prefer-future"
3447 org-read-date-prefer-future)
3448 (const :tag "Never" nil)
3449 (const :tag "Always" t)))
3451 (defcustom org-read-date-force-compatible-dates t
3452 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3454 Depending on the system Emacs is running on, certain dates cannot
3455 be represented with the type used internally to represent time.
3456 Dates between 1970-1-1 and 2038-1-1 can always be represented
3457 correctly. Some systems allow for earlier dates, some for later,
3458 some for both. One way to find out it to insert any date into an
3459 Org buffer, putting the cursor on the year and hitting S-up and
3460 S-down to test the range.
3462 When this variable is set to t, the date/time prompt will not let
3463 you specify dates outside the 1970-2037 range, so it is certain that
3464 these dates will work in whatever version of Emacs you are
3465 running, and also that you can move a file from one Emacs implementation
3466 to another. WHenever Org is forcing the year for you, it will display
3467 a message and beep.
3469 When this variable is nil, Org will check if the date is
3470 representable in the specific Emacs implementation you are using.
3471 If not, it will force a year, usually the current year, and beep
3472 to remind you. Currently this setting is not recommended because
3473 the likelihood that you will open your Org files in an Emacs that
3474 has limited date range is not negligible.
3476 A workaround for this problem is to use diary sexp dates for time
3477 stamps outside of this range."
3478 :group 'org-time
3479 :version "24.1"
3480 :type 'boolean)
3482 (defcustom org-read-date-display-live t
3483 "Non-nil means display current interpretation of date prompt live.
3484 This display will be in an overlay, in the minibuffer."
3485 :group 'org-time
3486 :type 'boolean)
3488 (defcustom org-read-date-popup-calendar t
3489 "Non-nil means pop up a calendar when prompting for a date.
3490 In the calendar, the date can be selected with mouse-1. However, the
3491 minibuffer will also be active, and you can simply enter the date as well.
3492 When nil, only the minibuffer will be available."
3493 :group 'org-time
3494 :type 'boolean)
3495 (defvaralias 'org-popup-calendar-for-date-prompt
3496 'org-read-date-popup-calendar)
3498 (defcustom org-extend-today-until 0
3499 "The hour when your day really ends. Must be an integer.
3500 This has influence for the following applications:
3501 - When switching the agenda to \"today\". It it is still earlier than
3502 the time given here, the day recognized as TODAY is actually yesterday.
3503 - When a date is read from the user and it is still before the time given
3504 here, the current date and time will be assumed to be yesterday, 23:59.
3505 Also, timestamps inserted in capture templates follow this rule.
3507 IMPORTANT: This is a feature whose implementation is and likely will
3508 remain incomplete. Really, it is only here because past midnight seems to
3509 be the favorite working time of John Wiegley :-)"
3510 :group 'org-time
3511 :type 'integer)
3513 (defcustom org-use-effective-time nil
3514 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3515 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3516 \"effective time\" of any timestamps between midnight and 8am will be
3517 23:59 of the previous day."
3518 :group 'org-time
3519 :version "24.1"
3520 :type 'boolean)
3522 (defcustom org-use-last-clock-out-time-as-effective-time nil
3523 "When non-nil, use the last clock out time for `org-todo'.
3524 Note that this option has precedence over the combined use of
3525 `org-use-effective-time' and `org-extend-today-until'."
3526 :group 'org-time
3527 :version "24.4"
3528 :package-version '(Org . "8.0")
3529 :type 'boolean)
3531 (defcustom org-edit-timestamp-down-means-later nil
3532 "Non-nil means S-down will increase the time in a time stamp.
3533 When nil, S-up will increase."
3534 :group 'org-time
3535 :type 'boolean)
3537 (defcustom org-calendar-follow-timestamp-change t
3538 "Non-nil means make the calendar window follow timestamp changes.
3539 When a timestamp is modified and the calendar window is visible, it will be
3540 moved to the new date."
3541 :group 'org-time
3542 :type 'boolean)
3544 (defgroup org-tags nil
3545 "Options concerning tags in Org mode."
3546 :tag "Org Tags"
3547 :group 'org)
3549 (defcustom org-tag-alist nil
3550 "Default tags available in Org files.
3552 The value of this variable is an alist. Associations either:
3554 (TAG)
3555 (TAG . SELECT)
3556 (SPECIAL)
3558 where TAG is a tag as a string, SELECT is character, used to
3559 select that tag through the fast tag selection interface, and
3560 SPECIAL is one of the following keywords: `:startgroup',
3561 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3562 `:newline'. These keywords are used to define a hierarchy of
3563 tags. See manual for details.
3565 When this variable is nil, Org mode bases tag input on what is
3566 already in the buffer. The value can be overridden locally by
3567 using a TAGS keyword, e.g.,
3569 #+TAGS: tag1 tag2
3571 See also `org-tag-persistent-alist' to sidestep this behavior."
3572 :group 'org-tags
3573 :type '(repeat
3574 (choice
3575 (cons (string :tag "Tag name")
3576 (character :tag "Access char"))
3577 (const :tag "Start radio group" (:startgroup))
3578 (const :tag "Start tag group, non distinct" (:startgrouptag))
3579 (const :tag "Group tags delimiter" (:grouptags))
3580 (const :tag "End radio group" (:endgroup))
3581 (const :tag "End tag group, non distinct" (:endgrouptag))
3582 (const :tag "New line" (:newline)))))
3584 (defcustom org-tag-persistent-alist nil
3585 "Tags always available in Org files.
3587 The value of this variable is an alist. Associations either:
3589 (TAG)
3590 (TAG . SELECT)
3591 (SPECIAL)
3593 where TAG is a tag as a string, SELECT is a character, used to
3594 select that tag through the fast tag selection interface, and
3595 SPECIAL is one of the following keywords: `:startgroup',
3596 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3597 `:newline'. These keywords are used to define a hierarchy of
3598 tags. See manual for details.
3600 Unlike to `org-tag-alist', tags defined in this variable do not
3601 depend on a local TAGS keyword. Instead, to disable these tags
3602 on a per-file basis, insert anywhere in the file:
3604 #+STARTUP: noptag"
3605 :group 'org-tags
3606 :type '(repeat
3607 (choice
3608 (cons (string :tag "Tag name")
3609 (character :tag "Access char"))
3610 (const :tag "Start radio group" (:startgroup))
3611 (const :tag "Start tag group, non distinct" (:startgrouptag))
3612 (const :tag "Group tags delimiter" (:grouptags))
3613 (const :tag "End radio group" (:endgroup))
3614 (const :tag "End tag group, non distinct" (:endgrouptag))
3615 (const :tag "New line" (:newline)))))
3617 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3618 "If non-nil, always offer completion for all tags of all agenda files.
3619 Instead of customizing this variable directly, you might want to
3620 set it locally for capture buffers, because there no list of
3621 tags in that file can be created dynamically (there are none).
3623 (add-hook \\='org-capture-mode-hook
3624 (lambda ()
3625 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3626 :group 'org-tags
3627 :version "24.1"
3628 :type 'boolean)
3630 (defvar org-file-tags nil
3631 "List of tags that can be inherited by all entries in the file.
3632 The tags will be inherited if the variable `org-use-tag-inheritance'
3633 says they should be.
3634 This variable is populated from #+FILETAGS lines.")
3636 (defcustom org-use-fast-tag-selection 'auto
3637 "Non-nil means use fast tag selection scheme.
3638 This is a special interface to select and deselect tags with single keys.
3639 When nil, fast selection is never used.
3640 When the symbol `auto', fast selection is used if and only if selection
3641 characters for tags have been configured, either through the variable
3642 `org-tag-alist' or through a #+TAGS line in the buffer.
3643 When t, fast selection is always used and selection keys are assigned
3644 automatically if necessary."
3645 :group 'org-tags
3646 :type '(choice
3647 (const :tag "Always" t)
3648 (const :tag "Never" nil)
3649 (const :tag "When selection characters are configured" auto)))
3651 (defcustom org-fast-tag-selection-single-key nil
3652 "Non-nil means fast tag selection exits after first change.
3653 When nil, you have to press RET to exit it.
3654 During fast tag selection, you can toggle this flag with `C-c'.
3655 This variable can also have the value `expert'. In this case, the window
3656 displaying the tags menu is not even shown, until you press C-c again."
3657 :group 'org-tags
3658 :type '(choice
3659 (const :tag "No" nil)
3660 (const :tag "Yes" t)
3661 (const :tag "Expert" expert)))
3663 (defvar org-fast-tag-selection-include-todo nil
3664 "Non-nil means fast tags selection interface will also offer TODO states.
3665 This is an undocumented feature, you should not rely on it.")
3667 (defcustom org-tags-column -77
3668 "The column to which tags should be indented in a headline.
3669 If this number is positive, it specifies the column. If it is negative,
3670 it means that the tags should be flushright to that column. For example,
3671 -80 works well for a normal 80 character screen.
3672 When 0, place tags directly after headline text, with only one space in
3673 between."
3674 :group 'org-tags
3675 :type 'integer)
3677 (defcustom org-auto-align-tags t
3678 "Non-nil keeps tags aligned when modifying headlines.
3679 Some operations (i.e. demoting) change the length of a headline and
3680 therefore shift the tags around. With this option turned on, after
3681 each such operation the tags are again aligned to `org-tags-column'."
3682 :group 'org-tags
3683 :type 'boolean)
3685 (defcustom org-use-tag-inheritance t
3686 "Non-nil means tags in levels apply also for sublevels.
3687 When nil, only the tags directly given in a specific line apply there.
3688 This may also be a list of tags that should be inherited, or a regexp that
3689 matches tags that should be inherited. Additional control is possible
3690 with the variable `org-tags-exclude-from-inheritance' which gives an
3691 explicit list of tags to be excluded from inheritance, even if the value of
3692 `org-use-tag-inheritance' would select it for inheritance.
3694 If this option is t, a match early-on in a tree can lead to a large
3695 number of matches in the subtree when constructing the agenda or creating
3696 a sparse tree. If you only want to see the first match in a tree during
3697 a search, check out the variable `org-tags-match-list-sublevels'."
3698 :group 'org-tags
3699 :type '(choice
3700 (const :tag "Not" nil)
3701 (const :tag "Always" t)
3702 (repeat :tag "Specific tags" (string :tag "Tag"))
3703 (regexp :tag "Tags matched by regexp")))
3705 (defcustom org-tags-exclude-from-inheritance nil
3706 "List of tags that should never be inherited.
3707 This is a way to exclude a few tags from inheritance. For way to do
3708 the opposite, to actively allow inheritance for selected tags,
3709 see the variable `org-use-tag-inheritance'."
3710 :group 'org-tags
3711 :type '(repeat (string :tag "Tag")))
3713 (defun org-tag-inherit-p (tag)
3714 "Check if TAG is one that should be inherited."
3715 (cond
3716 ((member tag org-tags-exclude-from-inheritance) nil)
3717 ((eq org-use-tag-inheritance t) t)
3718 ((not org-use-tag-inheritance) nil)
3719 ((stringp org-use-tag-inheritance)
3720 (string-match org-use-tag-inheritance tag))
3721 ((listp org-use-tag-inheritance)
3722 (member tag org-use-tag-inheritance))
3723 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3725 (defcustom org-tags-match-list-sublevels t
3726 "Non-nil means list also sublevels of headlines matching a search.
3727 This variable applies to tags/property searches, and also to stuck
3728 projects because this search is based on a tags match as well.
3730 When set to the symbol `indented', sublevels are indented with
3731 leading dots.
3733 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3734 the sublevels of a headline matching a tag search often also match
3735 the same search. Listing all of them can create very long lists.
3736 Setting this variable to nil causes subtrees of a match to be skipped.
3738 This variable is semi-obsolete and probably should always be true. It
3739 is better to limit inheritance to certain tags using the variables
3740 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3741 :group 'org-tags
3742 :type '(choice
3743 (const :tag "No, don't list them" nil)
3744 (const :tag "Yes, do list them" t)
3745 (const :tag "List them, indented with leading dots" indented)))
3747 (defcustom org-tags-sort-function nil
3748 "When set, tags are sorted using this function as a comparator."
3749 :group 'org-tags
3750 :type '(choice
3751 (const :tag "No sorting" nil)
3752 (const :tag "Alphabetical" string<)
3753 (const :tag "Reverse alphabetical" string>)
3754 (function :tag "Custom function" nil)))
3756 (defvar org-tags-history nil
3757 "History of minibuffer reads for tags.")
3758 (defvar org-last-tags-completion-table nil
3759 "The last used completion table for tags.")
3760 (defvar org-after-tags-change-hook nil
3761 "Hook that is run after the tags in a line have changed.")
3763 (defgroup org-properties nil
3764 "Options concerning properties in Org mode."
3765 :tag "Org Properties"
3766 :group 'org)
3768 (defcustom org-property-format "%-10s %s"
3769 "How property key/value pairs should be formatted by `indent-line'.
3770 When `indent-line' hits a property definition, it will format the line
3771 according to this format, mainly to make sure that the values are
3772 lined-up with respect to each other."
3773 :group 'org-properties
3774 :type 'string)
3776 (defcustom org-properties-postprocess-alist nil
3777 "Alist of properties and functions to adjust inserted values.
3778 Elements of this alist must be of the form
3780 ([string] [function])
3782 where [string] must be a property name and [function] must be a
3783 lambda expression: this lambda expression must take one argument,
3784 the value to adjust, and return the new value as a string.
3786 For example, this element will allow the property \"Remaining\"
3787 to be updated wrt the relation between the \"Effort\" property
3788 and the clock summary:
3790 ((\"Remaining\" (lambda(value)
3791 (let ((clocksum (org-clock-sum-current-item))
3792 (effort (org-duration-string-to-minutes
3793 (org-entry-get (point) \"Effort\"))))
3794 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3795 :group 'org-properties
3796 :version "24.1"
3797 :type '(alist :key-type (string :tag "Property")
3798 :value-type (function :tag "Function")))
3800 (defcustom org-use-property-inheritance nil
3801 "Non-nil means properties apply also for sublevels.
3803 This setting is chiefly used during property searches. Turning it on can
3804 cause significant overhead when doing a search, which is why it is not
3805 on by default.
3807 When nil, only the properties directly given in the current entry count.
3808 When t, every property is inherited. The value may also be a list of
3809 properties that should have inheritance, or a regular expression matching
3810 properties that should be inherited.
3812 However, note that some special properties use inheritance under special
3813 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3814 and the properties ending in \"_ALL\" when they are used as descriptor
3815 for valid values of a property.
3817 Note for programmers:
3818 When querying an entry with `org-entry-get', you can control if inheritance
3819 should be used. By default, `org-entry-get' looks only at the local
3820 properties. You can request inheritance by setting the inherit argument
3821 to t (to force inheritance) or to `selective' (to respect the setting
3822 in this variable)."
3823 :group 'org-properties
3824 :type '(choice
3825 (const :tag "Not" nil)
3826 (const :tag "Always" t)
3827 (repeat :tag "Specific properties" (string :tag "Property"))
3828 (regexp :tag "Properties matched by regexp")))
3830 (defun org-property-inherit-p (property)
3831 "Return a non-nil value if PROPERTY should be inherited."
3832 (cond
3833 ((eq org-use-property-inheritance t) t)
3834 ((not org-use-property-inheritance) nil)
3835 ((stringp org-use-property-inheritance)
3836 (string-match org-use-property-inheritance property))
3837 ((listp org-use-property-inheritance)
3838 (member-ignore-case property org-use-property-inheritance))
3839 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3841 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3842 "The default column format, if no other format has been defined.
3843 This variable can be set on the per-file basis by inserting a line
3845 #+COLUMNS: %25ITEM ....."
3846 :group 'org-properties
3847 :type 'string)
3849 (defcustom org-columns-ellipses ".."
3850 "The ellipses to be used when a field in column view is truncated.
3851 When this is the empty string, as many characters as possible are shown,
3852 but then there will be no visual indication that the field has been truncated.
3853 When this is a string of length N, the last N characters of a truncated
3854 field are replaced by this string. If the column is narrower than the
3855 ellipses string, only part of the ellipses string will be shown."
3856 :group 'org-properties
3857 :type 'string)
3859 (defconst org-global-properties-fixed
3860 '(("VISIBILITY_ALL" . "folded children content all")
3861 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3862 "List of property/value pairs that can be inherited by any entry.
3864 These are fixed values, for the preset properties. The user variable
3865 that can be used to add to this list is `org-global-properties'.
3867 The entries in this list are cons cells where the car is a property
3868 name and cdr is a string with the value. If the value represents
3869 multiple items like an \"_ALL\" property, separate the items by
3870 spaces.")
3872 (defcustom org-global-properties nil
3873 "List of property/value pairs that can be inherited by any entry.
3875 This list will be combined with the constant `org-global-properties-fixed'.
3877 The entries in this list are cons cells where the car is a property
3878 name and cdr is a string with the value.
3880 You can set buffer-local values for the same purpose in the variable
3881 `org-file-properties' this by adding lines like
3883 #+PROPERTY: NAME VALUE"
3884 :group 'org-properties
3885 :type '(repeat
3886 (cons (string :tag "Property")
3887 (string :tag "Value"))))
3889 (defvar-local org-file-properties nil
3890 "List of property/value pairs that can be inherited by any entry.
3891 Valid for the current buffer.
3892 This variable is populated from #+PROPERTY lines.")
3894 (defgroup org-agenda nil
3895 "Options concerning agenda views in Org mode."
3896 :tag "Org Agenda"
3897 :group 'org)
3899 (defvar-local org-category nil
3900 "Variable used by org files to set a category for agenda display.
3901 Such files should use a file variable to set it, for example
3903 # -*- mode: org; org-category: \"ELisp\"
3905 or contain a special line
3907 #+CATEGORY: ELisp
3909 If the file does not specify a category, then file's base name
3910 is used instead.")
3911 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3913 (defcustom org-agenda-files nil
3914 "The files to be used for agenda display.
3916 If an entry is a directory, all files in that directory that are matched
3917 by `org-agenda-file-regexp' will be part of the file list.
3919 If the value of the variable is not a list but a single file name, then
3920 the list of agenda files is actually stored and maintained in that file,
3921 one agenda file per line. In this file paths can be given relative to
3922 `org-directory'. Tilde expansion and environment variable substitution
3923 are also made.
3925 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3926 and removed with `\\[org-remove-file]'."
3927 :group 'org-agenda
3928 :type '(choice
3929 (repeat :tag "List of files and directories" file)
3930 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3932 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3933 "Regular expression to match files for `org-agenda-files'.
3934 If any element in the list in that variable contains a directory instead
3935 of a normal file, all files in that directory that are matched by this
3936 regular expression will be included."
3937 :group 'org-agenda
3938 :type 'regexp)
3940 (defcustom org-agenda-text-search-extra-files nil
3941 "List of extra files to be searched by text search commands.
3942 These files will be searched in addition to the agenda files by the
3943 commands `org-search-view' (`\\[org-agenda] s') \
3944 and `org-occur-in-agenda-files'.
3945 Note that these files will only be searched for text search commands,
3946 not for the other agenda views like todo lists, tag searches or the weekly
3947 agenda. This variable is intended to list notes and possibly archive files
3948 that should also be searched by these two commands.
3949 In fact, if the first element in the list is the symbol `agenda-archives',
3950 then all archive files of all agenda files will be added to the search
3951 scope."
3952 :group 'org-agenda
3953 :type '(set :greedy t
3954 (const :tag "Agenda Archives" agenda-archives)
3955 (repeat :inline t (file))))
3957 (defvaralias 'org-agenda-multi-occur-extra-files
3958 'org-agenda-text-search-extra-files)
3960 (defcustom org-agenda-skip-unavailable-files nil
3961 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3962 A nil value means to remove them, after a query, from the list."
3963 :group 'org-agenda
3964 :type 'boolean)
3966 (defcustom org-calendar-to-agenda-key [?c]
3967 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3968 The command `org-calendar-goto-agenda' will be bound to this key. The
3969 default is the character `c' because then `c' can be used to switch back and
3970 forth between agenda and calendar."
3971 :group 'org-agenda
3972 :type 'sexp)
3974 (defcustom org-calendar-insert-diary-entry-key [?i]
3975 "The key to be installed in `calendar-mode-map' for adding diary entries.
3976 This option is irrelevant until `org-agenda-diary-file' has been configured
3977 to point to an Org file. When that is the case, the command
3978 `org-agenda-diary-entry' will be bound to the key given here, by default
3979 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3980 if you want to continue doing this, you need to change this to a different
3981 key."
3982 :group 'org-agenda
3983 :type 'sexp)
3985 (defcustom org-agenda-diary-file 'diary-file
3986 "File to which to add new entries with the `i' key in agenda and calendar.
3987 When this is the symbol `diary-file', the functionality in the Emacs
3988 calendar will be used to add entries to the `diary-file'. But when this
3989 points to a file, `org-agenda-diary-entry' will be used instead."
3990 :group 'org-agenda
3991 :type '(choice
3992 (const :tag "The standard Emacs diary file" diary-file)
3993 (file :tag "Special Org file diary entries")))
3995 (eval-after-load "calendar"
3996 '(progn
3997 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3998 'org-calendar-goto-agenda)
3999 (add-hook 'calendar-mode-hook
4000 (lambda ()
4001 (unless (eq org-agenda-diary-file 'diary-file)
4002 (define-key calendar-mode-map
4003 org-calendar-insert-diary-entry-key
4004 'org-agenda-diary-entry))))))
4006 (defgroup org-latex nil
4007 "Options for embedding LaTeX code into Org mode."
4008 :tag "Org LaTeX"
4009 :group 'org)
4011 (defcustom org-format-latex-options
4012 '(:foreground default :background default :scale 1.0
4013 :html-foreground "Black" :html-background "Transparent"
4014 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
4015 "Options for creating images from LaTeX fragments.
4016 This is a property list with the following properties:
4017 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
4018 `default' means use the foreground of the default face.
4019 `auto' means use the foreground from the text face.
4020 :background the background color, or \"Transparent\".
4021 `default' means use the background of the default face.
4022 `auto' means use the background from the text face.
4023 :scale a scaling factor for the size of the images, to get more pixels
4024 :html-foreground, :html-background, :html-scale
4025 the same numbers for HTML export.
4026 :matchers a list indicating which matchers should be used to
4027 find LaTeX fragments. Valid members of this list are:
4028 \"begin\" find environments
4029 \"$1\" find single characters surrounded by $.$
4030 \"$\" find math expressions surrounded by $...$
4031 \"$$\" find math expressions surrounded by $$....$$
4032 \"\\(\" find math expressions surrounded by \\(...\\)
4033 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
4034 :group 'org-latex
4035 :type 'plist)
4037 (defcustom org-format-latex-signal-error t
4038 "Non-nil means signal an error when image creation of LaTeX snippets fails.
4039 When nil, just push out a message."
4040 :group 'org-latex
4041 :version "24.1"
4042 :type 'boolean)
4044 (defcustom org-latex-to-mathml-jar-file nil
4045 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
4046 Use this to specify additional executable file say a jar file.
4048 When using MathToWeb as the converter, specify the full-path to
4049 your mathtoweb.jar file."
4050 :group 'org-latex
4051 :version "24.1"
4052 :type '(choice
4053 (const :tag "None" nil)
4054 (file :tag "JAR file" :must-match t)))
4056 (defcustom org-latex-to-mathml-convert-command nil
4057 "Command to convert LaTeX fragments to MathML.
4058 Replace format-specifiers in the command as noted below and use
4059 `shell-command' to convert LaTeX to MathML.
4060 %j: Executable file in fully expanded form as specified by
4061 `org-latex-to-mathml-jar-file'.
4062 %I: Input LaTeX file in fully expanded form.
4063 %i: The latex fragment to be converted.
4064 %o: Output MathML file.
4066 This command is used by `org-create-math-formula'.
4068 When using MathToWeb as the converter, set this option to
4069 \"java -jar %j -unicode -force -df %o %I\".
4071 When using LaTeXML set this option to
4072 \"latexmlmath \"%i\" --presentationmathml=%o\"."
4073 :group 'org-latex
4074 :version "24.1"
4075 :type '(choice
4076 (const :tag "None" nil)
4077 (string :tag "\nShell command")))
4079 (defcustom org-preview-latex-default-process 'dvipng
4080 "The default process to convert LaTeX fragments to image files.
4081 All available processes and theirs documents can be found in
4082 `org-preview-latex-process-alist', which see."
4083 :group 'org-latex
4084 :version "26.1"
4085 :package-version '(Org . "9.0")
4086 :type 'symbol)
4088 (defcustom org-preview-latex-process-alist
4089 '((dvipng
4090 :programs ("latex" "dvipng")
4091 :description "dvi > png"
4092 :message "you need to install the programs: latex and dvipng."
4093 :image-input-type "dvi"
4094 :image-output-type "png"
4095 :image-size-adjust (1.0 . 1.0)
4096 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4097 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
4098 (dvisvgm
4099 :programs ("latex" "dvisvgm")
4100 :description "dvi > svg"
4101 :message "you need to install the programs: latex and dvisvgm."
4102 :use-xcolor t
4103 :image-input-type "dvi"
4104 :image-output-type "svg"
4105 :image-size-adjust (1.7 . 1.5)
4106 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4107 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
4108 (imagemagick
4109 :programs ("latex" "convert")
4110 :description "pdf > png"
4111 :message "you need to install the programs: latex and imagemagick."
4112 :use-xcolor t
4113 :image-input-type "pdf"
4114 :image-output-type "png"
4115 :image-size-adjust (1.0 . 1.0)
4116 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4117 :image-converter
4118 ("convert -density %D -trim -antialias %f -quality 100 %O")))
4119 "Definitions of external processes for LaTeX previewing.
4120 Org mode can use some external commands to generate TeX snippet's images for
4121 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4122 `org-create-formula-image' how to call them.
4124 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4125 PROPERTIES accepts the following attributes:
4127 :programs list of strings, required programs.
4128 :description string, describe the process.
4129 :message string, message it when required programs cannot be found.
4130 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4131 :image-output-type string, output file type of image converter (e.g., \"png\").
4132 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4133 deal with background and foreground color of image.
4134 Otherwise, dvipng style background and foregroud color
4135 format are generated. You may then refer to them in
4136 command options with \"%F\" and \"%B\".
4137 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4138 image size showed in buffer and the cdr element is for
4139 HTML file. This option is only useful for process
4140 developers, users should use variable
4141 `org-format-latex-options' instead.
4142 :post-clean list of strings, files matched are to be cleaned up once
4143 the image is generated. When nil, the files with \".dvi\",
4144 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4145 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4146 be cleaned up.
4147 :latex-header list of strings, the LaTeX header of the snippet file.
4148 When nil, the fallback value is used instead, which is
4149 controlled by `org-format-latex-header',
4150 `org-latex-default-packages-alist' and
4151 `org-latex-packages-alist', which see.
4152 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4153 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4154 replaced with values defined below.
4155 :image-converter list of image converter commands strings. Each of them is
4156 given to the shell and supports any of the following
4157 place-holders defined below.
4159 Place-holders used by `:image-converter' and `:latex-compiler':
4161 %f input file name
4162 %b base name of input file
4163 %o base directory of input file
4164 %O absolute output file name
4166 Place-holders only used by `:image-converter':
4168 %F foreground of image
4169 %B background of image
4170 %D dpi, which is used to adjust image size by some processing commands.
4171 %S the image size scale ratio, which is used to adjust image size by some
4172 processing commands."
4173 :group 'org-latex
4174 :version "26.1"
4175 :package-version '(Org . "9.0")
4176 :type '(alist :tag "LaTeX to image backends"
4177 :value-type (plist)))
4179 (defcustom org-preview-latex-image-directory "ltximg/"
4180 "Path to store latex preview images.
4181 A relative path here creates many directories relative to the
4182 processed org files paths. An absolute path puts all preview
4183 images at the same place."
4184 :group 'org-latex
4185 :version "26.1"
4186 :package-version '(Org . "9.0")
4187 :type 'string)
4189 (defun org-format-latex-mathml-available-p ()
4190 "Return t if `org-latex-to-mathml-convert-command' is usable."
4191 (save-match-data
4192 (when (and (boundp 'org-latex-to-mathml-convert-command)
4193 org-latex-to-mathml-convert-command)
4194 (let ((executable (car (split-string
4195 org-latex-to-mathml-convert-command))))
4196 (when (executable-find executable)
4197 (if (string-match
4198 "%j" org-latex-to-mathml-convert-command)
4199 (file-readable-p org-latex-to-mathml-jar-file)
4200 t))))))
4202 (defcustom org-format-latex-header "\\documentclass{article}
4203 \\usepackage[usenames]{color}
4204 \[PACKAGES]
4205 \[DEFAULT-PACKAGES]
4206 \\pagestyle{empty} % do not remove
4207 % The settings below are copied from fullpage.sty
4208 \\setlength{\\textwidth}{\\paperwidth}
4209 \\addtolength{\\textwidth}{-3cm}
4210 \\setlength{\\oddsidemargin}{1.5cm}
4211 \\addtolength{\\oddsidemargin}{-2.54cm}
4212 \\setlength{\\evensidemargin}{\\oddsidemargin}
4213 \\setlength{\\textheight}{\\paperheight}
4214 \\addtolength{\\textheight}{-\\headheight}
4215 \\addtolength{\\textheight}{-\\headsep}
4216 \\addtolength{\\textheight}{-\\footskip}
4217 \\addtolength{\\textheight}{-3cm}
4218 \\setlength{\\topmargin}{1.5cm}
4219 \\addtolength{\\topmargin}{-2.54cm}"
4220 "The document header used for processing LaTeX fragments.
4221 It is imperative that this header make sure that no page number
4222 appears on the page. The package defined in the variables
4223 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4224 will either replace the placeholder \"[PACKAGES]\" in this
4225 header, or they will be appended."
4226 :group 'org-latex
4227 :type 'string)
4229 (defun org-set-packages-alist (var val)
4230 "Set the packages alist and make sure it has 3 elements per entry."
4231 (set var (mapcar (lambda (x)
4232 (if (and (consp x) (= (length x) 2))
4233 (list (car x) (nth 1 x) t)
4235 val)))
4237 (defun org-get-packages-alist (var)
4238 "Get the packages alist and make sure it has 3 elements per entry."
4239 (mapcar (lambda (x)
4240 (if (and (consp x) (= (length x) 2))
4241 (list (car x) (nth 1 x) t)
4243 (default-value var)))
4245 (defcustom org-latex-default-packages-alist
4246 '(("AUTO" "inputenc" t ("pdflatex"))
4247 ("T1" "fontenc" t ("pdflatex"))
4248 ("" "graphicx" t)
4249 ("" "grffile" t)
4250 ("" "longtable" nil)
4251 ("" "wrapfig" nil)
4252 ("" "rotating" nil)
4253 ("normalem" "ulem" t)
4254 ("" "amsmath" t)
4255 ("" "textcomp" t)
4256 ("" "amssymb" t)
4257 ("" "capt-of" nil)
4258 ("" "hyperref" nil))
4259 "Alist of default packages to be inserted in the header.
4261 Change this only if one of the packages here causes an
4262 incompatibility with another package you are using.
4264 The packages in this list are needed by one part or another of
4265 Org mode to function properly:
4267 - inputenc, fontenc: for basic font and character selection
4268 - graphicx: for including images
4269 - grffile: allow periods and spaces in graphics file names
4270 - longtable: For multipage tables
4271 - wrapfig: for figure placement
4272 - rotating: for sideways figures and tables
4273 - ulem: for underline and strike-through
4274 - amsmath: for subscript and superscript and math environments
4275 - textcomp, amssymb: for various symbols used
4276 for interpreting the entities in `org-entities'. You can skip
4277 some of these packages if you don't use any of their symbols.
4278 - capt-of: for captions outside of floats
4279 - hyperref: for cross references
4281 Therefore you should not modify this variable unless you know
4282 what you are doing. The one reason to change it anyway is that
4283 you might be loading some other package that conflicts with one
4284 of the default packages. Each element is either a cell or
4285 a string.
4287 A cell is of the format
4289 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4291 If SNIPPET-FLAG is non-nil, the package also needs to be included
4292 when compiling LaTeX snippets into images for inclusion into
4293 non-LaTeX output. COMPILERS is a list of compilers that should
4294 include the package, see `org-latex-compiler'. If the document
4295 compiler is not in the list, and the list is non-nil, the package
4296 will not be inserted in the final document.
4298 A string will be inserted as-is in the header of the document."
4299 :group 'org-latex
4300 :group 'org-export-latex
4301 :set 'org-set-packages-alist
4302 :get 'org-get-packages-alist
4303 :version "26.1"
4304 :package-version '(Org . "8.3")
4305 :type '(repeat
4306 (choice
4307 (list :tag "options/package pair"
4308 (string :tag "options")
4309 (string :tag "package")
4310 (boolean :tag "Snippet"))
4311 (string :tag "A line of LaTeX"))))
4313 (defcustom org-latex-packages-alist nil
4314 "Alist of packages to be inserted in every LaTeX header.
4316 These will be inserted after `org-latex-default-packages-alist'.
4317 Each element is either a cell or a string.
4319 A cell is of the format:
4321 (\"options\" \"package\" SNIPPET-FLAG)
4323 SNIPPET-FLAG, when non-nil, indicates that this package is also
4324 needed when turning LaTeX snippets into images for inclusion into
4325 non-LaTeX output.
4327 A string will be inserted as-is in the header of the document.
4329 Make sure that you only list packages here which:
4331 - you want in every file;
4332 - do not conflict with the setup in `org-format-latex-header';
4333 - do not conflict with the default packages in
4334 `org-latex-default-packages-alist'."
4335 :group 'org-latex
4336 :group 'org-export-latex
4337 :set 'org-set-packages-alist
4338 :get 'org-get-packages-alist
4339 :type '(repeat
4340 (choice
4341 (list :tag "options/package pair"
4342 (string :tag "options")
4343 (string :tag "package")
4344 (boolean :tag "Snippet"))
4345 (string :tag "A line of LaTeX"))))
4347 (defgroup org-appearance nil
4348 "Settings for Org mode appearance."
4349 :tag "Org Appearance"
4350 :group 'org)
4352 (defcustom org-level-color-stars-only nil
4353 "Non-nil means fontify only the stars in each headline.
4354 When nil, the entire headline is fontified.
4355 Changing it requires restart of `font-lock-mode' to become effective
4356 also in regions already fontified."
4357 :group 'org-appearance
4358 :type 'boolean)
4360 (defcustom org-hide-leading-stars nil
4361 "Non-nil means hide the first N-1 stars in a headline.
4362 This works by using the face `org-hide' for these stars. This
4363 face is white for a light background, and black for a dark
4364 background. You may have to customize the face `org-hide' to
4365 make this work.
4366 Changing it requires restart of `font-lock-mode' to become effective
4367 also in regions already fontified.
4368 You may also set this on a per-file basis by adding one of the following
4369 lines to the buffer:
4371 #+STARTUP: hidestars
4372 #+STARTUP: showstars"
4373 :group 'org-appearance
4374 :type 'boolean)
4376 (defcustom org-hidden-keywords nil
4377 "List of symbols corresponding to keywords to be hidden the org buffer.
4378 For example, a value \\='(title) for this list will make the document's title
4379 appear in the buffer without the initial #+TITLE: keyword."
4380 :group 'org-appearance
4381 :version "24.1"
4382 :type '(set (const :tag "#+AUTHOR" author)
4383 (const :tag "#+DATE" date)
4384 (const :tag "#+EMAIL" email)
4385 (const :tag "#+TITLE" title)))
4387 (defcustom org-custom-properties nil
4388 "List of properties (as strings) with a special meaning.
4389 The default use of these custom properties is to let the user
4390 hide them with `org-toggle-custom-properties-visibility'."
4391 :group 'org-properties
4392 :group 'org-appearance
4393 :version "24.3"
4394 :type '(repeat (string :tag "Property Name")))
4396 (defcustom org-fontify-done-headline nil
4397 "Non-nil means change the face of a headline if it is marked DONE.
4398 Normally, only the TODO/DONE keyword indicates the state of a headline.
4399 When this is non-nil, the headline after the keyword is set to the
4400 `org-headline-done' as an additional indication."
4401 :group 'org-appearance
4402 :type 'boolean)
4404 (defcustom org-fontify-emphasized-text t
4405 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4406 Changing this variable requires a restart of Emacs to take effect."
4407 :group 'org-appearance
4408 :type 'boolean)
4410 (defcustom org-fontify-whole-heading-line nil
4411 "Non-nil means fontify the whole line for headings.
4412 This is useful when setting a background color for the
4413 org-level-* faces."
4414 :group 'org-appearance
4415 :type 'boolean)
4417 (defcustom org-highlight-latex-and-related nil
4418 "Non-nil means highlight LaTeX related syntax in the buffer.
4419 When non nil, the value should be a list containing any of the
4420 following symbols:
4421 `latex' Highlight LaTeX snippets and environments.
4422 `script' Highlight subscript and superscript.
4423 `entities' Highlight entities."
4424 :group 'org-appearance
4425 :version "24.4"
4426 :package-version '(Org . "8.0")
4427 :type '(choice
4428 (const :tag "No highlighting" nil)
4429 (set :greedy t :tag "Highlight"
4430 (const :tag "LaTeX snippets and environments" latex)
4431 (const :tag "Subscript and superscript" script)
4432 (const :tag "Entities" entities))))
4434 (defcustom org-hide-emphasis-markers nil
4435 "Non-nil mean font-lock should hide the emphasis marker characters."
4436 :group 'org-appearance
4437 :type 'boolean)
4439 (defcustom org-hide-macro-markers nil
4440 "Non-nil mean font-lock should hide the brackets marking macro calls."
4441 :group 'org-appearance
4442 :type 'boolean)
4444 (defcustom org-pretty-entities nil
4445 "Non-nil means show entities as UTF8 characters.
4446 When nil, the \\name form remains in the buffer."
4447 :group 'org-appearance
4448 :version "24.1"
4449 :type 'boolean)
4451 (defcustom org-pretty-entities-include-sub-superscripts t
4452 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4453 :group 'org-appearance
4454 :version "24.1"
4455 :type 'boolean)
4457 (defvar org-emph-re nil
4458 "Regular expression for matching emphasis.
4459 After a match, the match groups contain these elements:
4460 0 The match of the full regular expression, including the characters
4461 before and after the proper match
4462 1 The character before the proper match, or empty at beginning of line
4463 2 The proper match, including the leading and trailing markers
4464 3 The leading marker like * or /, indicating the type of highlighting
4465 4 The text between the emphasis markers, not including the markers
4466 5 The character after the match, empty at the end of a line")
4467 (defvar org-verbatim-re nil
4468 "Regular expression for matching verbatim text.")
4469 (defvar org-emphasis-regexp-components) ; defined just below
4470 (defvar org-emphasis-alist) ; defined just below
4471 (defun org-set-emph-re (var val)
4472 "Set variable and compute the emphasis regular expression."
4473 (set var val)
4474 (when (and (boundp 'org-emphasis-alist)
4475 (boundp 'org-emphasis-regexp-components)
4476 org-emphasis-alist org-emphasis-regexp-components)
4477 (let* ((e org-emphasis-regexp-components)
4478 (pre (car e))
4479 (post (nth 1 e))
4480 (border (nth 2 e))
4481 (body (nth 3 e))
4482 (nl (nth 4 e))
4483 (body1 (concat body "*?"))
4484 (markers (mapconcat 'car org-emphasis-alist ""))
4485 (vmarkers (mapconcat
4486 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4487 org-emphasis-alist "")))
4488 ;; make sure special characters appear at the right position in the class
4489 (if (string-match "\\^" markers)
4490 (setq markers (concat (replace-match "" t t markers) "^")))
4491 (if (string-match "-" markers)
4492 (setq markers (concat (replace-match "" t t markers) "-")))
4493 (if (string-match "\\^" vmarkers)
4494 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4495 (if (string-match "-" vmarkers)
4496 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4497 (if (> nl 0)
4498 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4499 (int-to-string nl) "\\}")))
4500 ;; Make the regexp
4501 (setq org-emph-re
4502 (concat "\\([" pre "]\\|^\\)"
4503 "\\("
4504 "\\([" markers "]\\)"
4505 "\\("
4506 "[^" border "]\\|"
4507 "[^" border "]"
4508 body1
4509 "[^" border "]"
4510 "\\)"
4511 "\\3\\)"
4512 "\\([" post "]\\|$\\)"))
4513 (setq org-verbatim-re
4514 (concat "\\([" pre "]\\|^\\)"
4515 "\\("
4516 "\\([" vmarkers "]\\)"
4517 "\\("
4518 "[^" border "]\\|"
4519 "[^" border "]"
4520 body1
4521 "[^" border "]"
4522 "\\)"
4523 "\\3\\)"
4524 "\\([" post "]\\|$\\)")))))
4526 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4527 ;; set this option proved cumbersome. See this message/thread:
4528 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4529 (defvar org-emphasis-regexp-components
4530 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4531 "Components used to build the regular expression for emphasis.
4532 This is a list with five entries. Terminology: In an emphasis string
4533 like \" *strong word* \", we call the initial space PREMATCH, the final
4534 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4535 and \"trong wor\" is the body. The different components in this variable
4536 specify what is allowed/forbidden in each part:
4538 pre Chars allowed as prematch. Beginning of line will be allowed too.
4539 post Chars allowed as postmatch. End of line will be allowed too.
4540 border The chars *forbidden* as border characters.
4541 body-regexp A regexp like \".\" to match a body character. Don't use
4542 non-shy groups here, and don't allow newline here.
4543 newline The maximum number of newlines allowed in an emphasis exp.
4545 You need to reload Org or to restart Emacs after customizing this.")
4547 (defcustom org-emphasis-alist
4548 '(("*" bold)
4549 ("/" italic)
4550 ("_" underline)
4551 ("=" org-verbatim verbatim)
4552 ("~" org-code verbatim)
4553 ("+" (:strike-through t)))
4554 "Alist of characters and faces to emphasize text.
4555 Text starting and ending with a special character will be emphasized,
4556 for example *bold*, _underlined_ and /italic/. This variable sets the
4557 marker characters and the face to be used by font-lock for highlighting
4558 in Org buffers.
4560 You need to reload Org or to restart Emacs after customizing this."
4561 :group 'org-appearance
4562 :set 'org-set-emph-re
4563 :version "24.4"
4564 :package-version '(Org . "8.0")
4565 :type '(repeat
4566 (list
4567 (string :tag "Marker character")
4568 (choice
4569 (face :tag "Font-lock-face")
4570 (plist :tag "Face property list"))
4571 (option (const verbatim)))))
4573 (defvar org-protecting-blocks '("src" "example" "export")
4574 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4575 This is needed for font-lock setup.")
4577 ;;; Functions and variables from their packages
4578 ;; Declared here to avoid compiler warnings
4579 (defvar mark-active)
4581 ;; Various packages
4582 (declare-function calc-eval "calc" (str &optional separator &rest args))
4583 (declare-function calendar-forward-day "cal-move" (arg))
4584 (declare-function calendar-goto-date "cal-move" (date))
4585 (declare-function calendar-goto-today "cal-move" ())
4586 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4587 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4588 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4589 (declare-function cdlatex-tab "ext:cdlatex" ())
4590 (declare-function dired-get-filename
4591 "dired"
4592 (&optional localp no-error-if-not-filep))
4593 (declare-function iswitchb-read-buffer
4594 "iswitchb"
4595 (prompt &optional
4596 default require-match _predicate start matches-set))
4597 (declare-function org-agenda-change-all-lines
4598 "org-agenda"
4599 (newhead hdmarker &optional fixface just-this))
4600 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4601 "org-agenda"
4602 (&optional end))
4603 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4604 (declare-function org-agenda-format-item
4605 "org-agenda"
4606 (extra txt &optional level category tags dotime
4607 remove-re habitp))
4608 (declare-function org-agenda-maybe-redo "org-agenda" ())
4609 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4610 (declare-function org-agenda-save-markers-for-cut-and-paste
4611 "org-agenda"
4612 (beg end))
4613 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4614 (declare-function org-agenda-skip "org-agenda" ())
4615 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4616 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4617 (declare-function org-indent-mode "org-indent" (&optional arg))
4618 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4619 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4620 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4621 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4622 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4623 (declare-function parse-time-string "parse-time" (string))
4624 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4626 (defvar align-mode-rules-list)
4627 (defvar calc-embedded-close-formula)
4628 (defvar calc-embedded-open-formula)
4629 (defvar calc-embedded-open-mode)
4630 (defvar font-lock-unfontify-region-function)
4631 (defvar iswitchb-temp-buflist)
4632 (defvar org-agenda-tags-todo-honor-ignore-options)
4633 (defvar remember-data-file)
4634 (defvar texmathp-why)
4636 ;;;###autoload
4637 (defun turn-on-orgtbl ()
4638 "Unconditionally turn on `orgtbl-mode'."
4639 (require 'org-table)
4640 (orgtbl-mode 1))
4642 (defun org-at-table-p (&optional table-type)
4643 "Non-nil if the cursor is inside an Org table.
4644 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4645 If `org-enable-table-editor' is nil, return nil unconditionally."
4646 (and
4647 org-enable-table-editor
4648 (save-excursion
4649 (beginning-of-line)
4650 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4651 (or (not (derived-mode-p 'org-mode))
4652 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4653 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4655 (defun org-at-table.el-p ()
4656 "Non-nil when point is at a table.el table."
4657 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4658 (let ((element (org-element-at-point)))
4659 (and (eq (org-element-type element) 'table)
4660 (eq (org-element-property :type element) 'table.el)))))
4662 (defun org-at-table-hline-p ()
4663 "Non-nil when point is inside a hline in a table.
4664 Assume point is already in a table. If `org-enable-table-editor'
4665 is nil, return nil unconditionally."
4666 (and org-enable-table-editor
4667 (save-excursion
4668 (beginning-of-line)
4669 (looking-at org-table-hline-regexp))))
4671 (defun org-table-map-tables (function &optional quietly)
4672 "Apply FUNCTION to the start of all tables in the buffer."
4673 (org-with-wide-buffer
4674 (goto-char (point-min))
4675 (while (re-search-forward org-table-any-line-regexp nil t)
4676 (unless quietly
4677 (message "Mapping tables: %d%%"
4678 (floor (* 100.0 (point)) (buffer-size))))
4679 (beginning-of-line 1)
4680 (when (and (looking-at org-table-line-regexp)
4681 ;; Exclude tables in src/example/verbatim/clocktable blocks
4682 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4683 (save-excursion (funcall function))
4684 (or (looking-at org-table-line-regexp)
4685 (forward-char 1)))
4686 (re-search-forward org-table-any-border-regexp nil 1)))
4687 (unless quietly (message "Mapping tables: done")))
4689 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4690 (declare-function org-clock-update-mode-line "org-clock" ())
4691 (declare-function org-resolve-clocks "org-clock"
4692 (&optional also-non-dangling-p prompt last-valid))
4694 (defun org-at-TBLFM-p (&optional pos)
4695 "Non-nil when point (or POS) is in #+TBLFM line."
4696 (save-excursion
4697 (goto-char (or pos (point)))
4698 (beginning-of-line)
4699 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4700 (eq (org-element-type (org-element-at-point)) 'table))))
4702 (defvar org-clock-start-time)
4703 (defvar org-clock-marker (make-marker)
4704 "Marker recording the last clock-in.")
4705 (defvar org-clock-hd-marker (make-marker)
4706 "Marker recording the last clock-in, but the headline position.")
4707 (defvar org-clock-heading ""
4708 "The heading of the current clock entry.")
4709 (defun org-clock-is-active ()
4710 "Return the buffer where the clock is currently running.
4711 Return nil if no clock is running."
4712 (marker-buffer org-clock-marker))
4714 (defun org-check-running-clock ()
4715 "Check if the current buffer contains the running clock.
4716 If yes, offer to stop it and to save the buffer with the changes."
4717 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4718 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4719 (buffer-name))))
4720 (org-clock-out)
4721 (when (y-or-n-p "Save changed buffer?")
4722 (save-buffer))))
4724 (defun org-clocktable-try-shift (dir n)
4725 "Check if this line starts a clock table, if yes, shift the time block."
4726 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4727 (org-clocktable-shift dir n)))
4729 ;;;###autoload
4730 (defun org-clock-persistence-insinuate ()
4731 "Set up hooks for clock persistence."
4732 (require 'org-clock)
4733 (add-hook 'org-mode-hook 'org-clock-load)
4734 (add-hook 'kill-emacs-hook 'org-clock-save))
4736 (defgroup org-archive nil
4737 "Options concerning archiving in Org mode."
4738 :tag "Org Archive"
4739 :group 'org-structure)
4741 (defcustom org-archive-location "%s_archive::"
4742 "The location where subtrees should be archived.
4744 The value of this variable is a string, consisting of two parts,
4745 separated by a double-colon. The first part is a filename and
4746 the second part is a headline.
4748 When the filename is omitted, archiving happens in the same file.
4749 %s in the filename will be replaced by the current file
4750 name (without the directory part). Archiving to a different file
4751 is useful to keep archived entries from contributing to the
4752 Org Agenda.
4754 The archived entries will be filed as subtrees of the specified
4755 headline. When the headline is omitted, the subtrees are simply
4756 filed away at the end of the file, as top-level entries. Also in
4757 the heading you can use %s to represent the file name, this can be
4758 useful when using the same archive for a number of different files.
4760 Here are a few examples:
4761 \"%s_archive::\"
4762 If the current file is Projects.org, archive in file
4763 Projects.org_archive, as top-level trees. This is the default.
4765 \"::* Archived Tasks\"
4766 Archive in the current file, under the top-level headline
4767 \"* Archived Tasks\".
4769 \"~/org/archive.org::\"
4770 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4772 \"~/org/archive.org::* From %s\"
4773 Archive in file ~/org/archive.org (absolute path), under headlines
4774 \"From FILENAME\" where file name is the current file name.
4776 \"~/org/datetree.org::datetree/* Finished Tasks\"
4777 The \"datetree/\" string is special, signifying to archive
4778 items to the datetree. Items are placed in either the CLOSED
4779 date of the item, or the current date if there is no CLOSED date.
4780 The heading will be a subentry to the current date. There doesn't
4781 need to be a heading, but there always needs to be a slash after
4782 datetree. For example, to store archived items directly in the
4783 datetree, use \"~/org/datetree.org::datetree/\".
4785 \"basement::** Finished Tasks\"
4786 Archive in file ./basement (relative path), as level 3 trees
4787 below the level 2 heading \"** Finished Tasks\".
4789 You may set this option on a per-file basis by adding to the buffer a
4790 line like
4792 #+ARCHIVE: basement::** Finished Tasks
4794 You may also define it locally for a subtree by setting an ARCHIVE property
4795 in the entry. If such a property is found in an entry, or anywhere up
4796 the hierarchy, it will be used."
4797 :group 'org-archive
4798 :type 'string)
4800 (defcustom org-agenda-skip-archived-trees t
4801 "Non-nil means the agenda will skip any items located in archived trees.
4802 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4803 variable is no longer recommended, you should leave it at the value t.
4804 Instead, use the key `v' to cycle the archives-mode in the agenda."
4805 :group 'org-archive
4806 :group 'org-agenda-skip
4807 :type 'boolean)
4809 (defcustom org-columns-skip-archived-trees t
4810 "Non-nil means ignore archived trees when creating column view."
4811 :group 'org-archive
4812 :group 'org-properties
4813 :type 'boolean)
4815 (defcustom org-cycle-open-archived-trees nil
4816 "Non-nil means `org-cycle' will open archived trees.
4817 An archived tree is a tree marked with the tag ARCHIVE.
4818 When nil, archived trees will stay folded. You can still open them with
4819 normal outline commands like `show-all', but not with the cycling commands."
4820 :group 'org-archive
4821 :group 'org-cycle
4822 :type 'boolean)
4824 (defcustom org-sparse-tree-open-archived-trees nil
4825 "Non-nil means sparse tree construction shows matches in archived trees.
4826 When nil, matches in these trees are highlighted, but the trees are kept in
4827 collapsed state."
4828 :group 'org-archive
4829 :group 'org-sparse-trees
4830 :type 'boolean)
4832 (defcustom org-sparse-tree-default-date-type nil
4833 "The default date type when building a sparse tree.
4834 When this is nil, a date is a scheduled or a deadline timestamp.
4835 Otherwise, these types are allowed:
4837 all: all timestamps
4838 active: only active timestamps (<...>)
4839 inactive: only inactive timestamps ([...])
4840 scheduled: only scheduled timestamps
4841 deadline: only deadline timestamps"
4842 :type '(choice (const :tag "Scheduled or deadline" nil)
4843 (const :tag "All timestamps" all)
4844 (const :tag "Only active timestamps" active)
4845 (const :tag "Only inactive timestamps" inactive)
4846 (const :tag "Only scheduled timestamps" scheduled)
4847 (const :tag "Only deadline timestamps" deadline)
4848 (const :tag "Only closed timestamps" closed))
4849 :version "26.1"
4850 :package-version '(Org . "8.3")
4851 :group 'org-sparse-trees)
4853 (defun org-cycle-hide-archived-subtrees (state)
4854 "Re-hide all archived subtrees after a visibility state change."
4855 (when (and (not org-cycle-open-archived-trees)
4856 (not (memq state '(overview folded))))
4857 (save-excursion
4858 (let* ((globalp (memq state '(contents all)))
4859 (beg (if globalp (point-min) (point)))
4860 (end (if globalp (point-max) (org-end-of-subtree t))))
4861 (org-hide-archived-subtrees beg end)
4862 (goto-char beg)
4863 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4864 (message "%s" (substitute-command-keys
4865 "Subtree is archived and stays closed. Use \
4866 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4868 (defun org-force-cycle-archived ()
4869 "Cycle subtree even if it is archived."
4870 (interactive)
4871 (setq this-command 'org-cycle)
4872 (let ((org-cycle-open-archived-trees t))
4873 (call-interactively 'org-cycle)))
4875 (defun org-hide-archived-subtrees (beg end)
4876 "Re-hide all archived subtrees after a visibility state change."
4877 (org-with-wide-buffer
4878 (let ((case-fold-search nil)
4879 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4880 (goto-char beg)
4881 ;; Include headline point is currently on.
4882 (beginning-of-line)
4883 (while (and (< (point) end) (re-search-forward re end t))
4884 (when (member org-archive-tag (org-get-tags))
4885 (org-flag-subtree t)
4886 (org-end-of-subtree t))))))
4888 (declare-function outline-end-of-heading "outline" ())
4889 (declare-function outline-flag-region "outline" (from to flag))
4890 (defun org-flag-subtree (flag)
4891 (save-excursion
4892 (org-back-to-heading t)
4893 (outline-end-of-heading)
4894 (outline-flag-region (point)
4895 (progn (org-end-of-subtree t) (point))
4896 flag)))
4898 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4900 ;; Declare Column View Code
4902 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4903 (declare-function org-columns-compute "org-colview" (property))
4905 ;; Declare ID code
4907 (declare-function org-id-store-link "org-id")
4908 (declare-function org-id-locations-load "org-id")
4909 (declare-function org-id-locations-save "org-id")
4910 (defvar org-id-track-globally)
4912 ;;; Variables for pre-computed regular expressions, all buffer local
4914 (defvar-local org-todo-regexp nil
4915 "Matches any of the TODO state keywords.
4916 Since TODO keywords are case-sensitive, `case-fold-search' is
4917 expected to be bound to nil when matching against this regexp.")
4919 (defvar-local org-not-done-regexp nil
4920 "Matches any of the TODO state keywords except the last one.
4921 Since TODO keywords are case-sensitive, `case-fold-search' is
4922 expected to be bound to nil when matching against this regexp.")
4924 (defvar-local org-not-done-heading-regexp nil
4925 "Matches a TODO headline that is not done.
4926 Since TODO keywords are case-sensitive, `case-fold-search' is
4927 expected to be bound to nil when matching against this regexp.")
4929 (defvar-local org-todo-line-regexp nil
4930 "Matches a headline and puts TODO state into group 2 if present.
4931 Since TODO keywords are case-sensitive, `case-fold-search' is
4932 expected to be bound to nil when matching against this regexp.")
4934 (defvar-local org-complex-heading-regexp nil
4935 "Matches a headline and puts everything into groups:
4937 group 1: Stars
4938 group 2: The TODO keyword, maybe
4939 group 3: Priority cookie
4940 group 4: True headline
4941 group 5: Tags
4943 Since TODO keywords are case-sensitive, `case-fold-search' is
4944 expected to be bound to nil when matching against this regexp.")
4946 (defvar-local org-complex-heading-regexp-format nil
4947 "Printf format to make regexp to match an exact headline.
4948 This regexp will match the headline of any node which has the
4949 exact headline text that is put into the format, but may have any
4950 TODO state, priority and tags.")
4952 (defvar-local org-todo-line-tags-regexp nil
4953 "Matches a headline and puts TODO state into group 2 if present.
4954 Also put tags into group 4 if tags are present.")
4956 (defconst org-plain-time-of-day-regexp
4957 (concat
4958 "\\(\\<[012]?[0-9]"
4959 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4960 "\\(--?"
4961 "\\(\\<[012]?[0-9]"
4962 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4963 "\\)?")
4964 "Regular expression to match a plain time or time range.
4965 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4966 groups carry important information:
4967 0 the full match
4968 1 the first time, range or not
4969 8 the second time, if it is a range.")
4971 (defconst org-plain-time-extension-regexp
4972 (concat
4973 "\\(\\<[012]?[0-9]"
4974 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4975 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4976 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4977 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4978 groups carry important information:
4979 0 the full match
4980 7 hours of duration
4981 9 minutes of duration")
4983 (defconst org-stamp-time-of-day-regexp
4984 (concat
4985 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4986 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4987 "\\(--?"
4988 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4989 "Regular expression to match a timestamp time or time range.
4990 After a match, the following groups carry important information:
4991 0 the full match
4992 1 date plus weekday, for back referencing to make sure both times are on the same day
4993 2 the first time, range or not
4994 4 the second time, if it is a range.")
4996 (defconst org-startup-options
4997 '(("fold" org-startup-folded t)
4998 ("overview" org-startup-folded t)
4999 ("nofold" org-startup-folded nil)
5000 ("showall" org-startup-folded nil)
5001 ("showeverything" org-startup-folded showeverything)
5002 ("content" org-startup-folded content)
5003 ("indent" org-startup-indented t)
5004 ("noindent" org-startup-indented nil)
5005 ("hidestars" org-hide-leading-stars t)
5006 ("showstars" org-hide-leading-stars nil)
5007 ("odd" org-odd-levels-only t)
5008 ("oddeven" org-odd-levels-only nil)
5009 ("align" org-startup-align-all-tables t)
5010 ("noalign" org-startup-align-all-tables nil)
5011 ("inlineimages" org-startup-with-inline-images t)
5012 ("noinlineimages" org-startup-with-inline-images nil)
5013 ("latexpreview" org-startup-with-latex-preview t)
5014 ("nolatexpreview" org-startup-with-latex-preview nil)
5015 ("customtime" org-display-custom-times t)
5016 ("logdone" org-log-done time)
5017 ("lognotedone" org-log-done note)
5018 ("nologdone" org-log-done nil)
5019 ("lognoteclock-out" org-log-note-clock-out t)
5020 ("nolognoteclock-out" org-log-note-clock-out nil)
5021 ("logrepeat" org-log-repeat state)
5022 ("lognoterepeat" org-log-repeat note)
5023 ("logdrawer" org-log-into-drawer t)
5024 ("nologdrawer" org-log-into-drawer nil)
5025 ("logstatesreversed" org-log-states-order-reversed t)
5026 ("nologstatesreversed" org-log-states-order-reversed nil)
5027 ("nologrepeat" org-log-repeat nil)
5028 ("logreschedule" org-log-reschedule time)
5029 ("lognotereschedule" org-log-reschedule note)
5030 ("nologreschedule" org-log-reschedule nil)
5031 ("logredeadline" org-log-redeadline time)
5032 ("lognoteredeadline" org-log-redeadline note)
5033 ("nologredeadline" org-log-redeadline nil)
5034 ("logrefile" org-log-refile time)
5035 ("lognoterefile" org-log-refile note)
5036 ("nologrefile" org-log-refile nil)
5037 ("fninline" org-footnote-define-inline t)
5038 ("nofninline" org-footnote-define-inline nil)
5039 ("fnlocal" org-footnote-section nil)
5040 ("fnauto" org-footnote-auto-label t)
5041 ("fnprompt" org-footnote-auto-label nil)
5042 ("fnconfirm" org-footnote-auto-label confirm)
5043 ("fnplain" org-footnote-auto-label plain)
5044 ("fnadjust" org-footnote-auto-adjust t)
5045 ("nofnadjust" org-footnote-auto-adjust nil)
5046 ("constcgs" constants-unit-system cgs)
5047 ("constSI" constants-unit-system SI)
5048 ("noptag" org-tag-persistent-alist nil)
5049 ("hideblocks" org-hide-block-startup t)
5050 ("nohideblocks" org-hide-block-startup nil)
5051 ("beamer" org-startup-with-beamer-mode t)
5052 ("entitiespretty" org-pretty-entities t)
5053 ("entitiesplain" org-pretty-entities nil))
5054 "Variable associated with STARTUP options for org-mode.
5055 Each element is a list of three items: the startup options (as written
5056 in the #+STARTUP line), the corresponding variable, and the value to set
5057 this variable to if the option is found. An optional forth element PUSH
5058 means to push this value onto the list in the variable.")
5060 (defcustom org-group-tags t
5061 "When non-nil (the default), use group tags.
5062 This can be turned on/off through `org-toggle-tags-groups'."
5063 :group 'org-tags
5064 :group 'org-startup
5065 :type 'boolean)
5067 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5069 (defun org-toggle-tags-groups ()
5070 "Toggle support for group tags.
5071 Support for group tags is controlled by the option
5072 `org-group-tags', which is non-nil by default."
5073 (interactive)
5074 (setq org-group-tags (not org-group-tags))
5075 (cond ((and (derived-mode-p 'org-agenda-mode)
5076 org-group-tags)
5077 (org-agenda-redo))
5078 ((derived-mode-p 'org-mode)
5079 (let ((org-inhibit-startup t)) (org-mode))))
5080 (message "Groups tags support has been turned %s"
5081 (if org-group-tags "on" "off")))
5083 (defun org-set-regexps-and-options (&optional tags-only)
5084 "Precompute regular expressions used in the current buffer.
5085 When optional argument TAGS-ONLY is non-nil, only compute tags
5086 related expressions."
5087 (when (derived-mode-p 'org-mode)
5088 (let ((alist (org--setup-collect-keywords
5089 (org-make-options-regexp
5090 (append '("FILETAGS" "TAGS" "SETUPFILE")
5091 (and (not tags-only)
5092 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
5093 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
5094 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
5095 ;; Startup options. Get this early since it does change
5096 ;; behavior for other options (e.g., tags).
5097 (let ((startup (cdr (assq 'startup alist))))
5098 (dolist (option startup)
5099 (let ((entry (assoc-string option org-startup-options t)))
5100 (when entry
5101 (let ((var (nth 1 entry))
5102 (val (nth 2 entry)))
5103 (if (not (nth 3 entry)) (set (make-local-variable var) val)
5104 (unless (listp (symbol-value var))
5105 (set (make-local-variable var) nil))
5106 (add-to-list var val)))))))
5107 (setq-local org-file-tags
5108 (mapcar #'org-add-prop-inherited
5109 (cdr (assq 'filetags alist))))
5110 (setq org-current-tag-alist
5111 (append org-tag-persistent-alist
5112 (let ((tags (cdr (assq 'tags alist))))
5113 (if tags (org-tag-string-to-alist tags)
5114 org-tag-alist))))
5115 (setq org-tag-groups-alist
5116 (org-tag-alist-to-groups org-current-tag-alist))
5117 (unless tags-only
5118 ;; File properties.
5119 (setq-local org-file-properties (cdr (assq 'property alist)))
5120 ;; Archive location.
5121 (let ((archive (cdr (assq 'archive alist))))
5122 (when archive (setq-local org-archive-location archive)))
5123 ;; Category.
5124 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
5125 (when cat
5126 (setq-local org-category (intern cat))
5127 (setq-local org-file-properties
5128 (org--update-property-plist
5129 "CATEGORY" cat org-file-properties))))
5130 ;; Columns.
5131 (let ((column (cdr (assq 'columns alist))))
5132 (when column (setq-local org-columns-default-format column)))
5133 ;; Constants.
5134 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
5135 ;; Link abbreviations.
5136 (let ((links (cdr (assq 'link alist))))
5137 (when links (setq org-link-abbrev-alist-local (nreverse links))))
5138 ;; Priorities.
5139 (let ((priorities (cdr (assq 'priorities alist))))
5140 (when priorities
5141 (setq-local org-highest-priority (nth 0 priorities))
5142 (setq-local org-lowest-priority (nth 1 priorities))
5143 (setq-local org-default-priority (nth 2 priorities))))
5144 ;; Scripts.
5145 (let ((scripts (assq 'scripts alist)))
5146 (when scripts
5147 (setq-local org-use-sub-superscripts (cdr scripts))))
5148 ;; TODO keywords.
5149 (setq-local org-todo-kwd-alist nil)
5150 (setq-local org-todo-key-alist nil)
5151 (setq-local org-todo-key-trigger nil)
5152 (setq-local org-todo-keywords-1 nil)
5153 (setq-local org-done-keywords nil)
5154 (setq-local org-todo-heads nil)
5155 (setq-local org-todo-sets nil)
5156 (setq-local org-todo-log-states nil)
5157 (let ((todo-sequences
5158 (or (nreverse (cdr (assq 'todo alist)))
5159 (let ((d (default-value 'org-todo-keywords)))
5160 (if (not (stringp (car d))) d
5161 ;; XXX: Backward compatibility code.
5162 (list (cons org-todo-interpretation d)))))))
5163 (dolist (sequence todo-sequences)
5164 (let* ((sequence (or (run-hook-with-args-until-success
5165 'org-todo-setup-filter-hook sequence)
5166 sequence))
5167 (sequence-type (car sequence))
5168 (keywords (cdr sequence))
5169 (sep (member "|" keywords))
5170 names alist)
5171 (dolist (k (remove "|" keywords))
5172 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5174 (error "Invalid TODO keyword %s" k))
5175 (let ((name (match-string 1 k))
5176 (key (match-string 2 k))
5177 (log (org-extract-log-state-settings k)))
5178 (push name names)
5179 (push (cons name (and key (string-to-char key))) alist)
5180 (when log (push log org-todo-log-states))))
5181 (let* ((names (nreverse names))
5182 (done (if sep (org-remove-keyword-keys (cdr sep))
5183 (last names)))
5184 (head (car names))
5185 (tail (list sequence-type head (car done) (org-last done))))
5186 (add-to-list 'org-todo-heads head 'append)
5187 (push names org-todo-sets)
5188 (setq org-done-keywords (append org-done-keywords done nil))
5189 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5190 (setq org-todo-key-alist
5191 (append org-todo-key-alist
5192 (and alist
5193 (append '((:startgroup))
5194 (nreverse alist)
5195 '((:endgroup))))))
5196 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5197 (setq org-todo-sets (nreverse org-todo-sets)
5198 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5199 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5200 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5201 ;; Compute the regular expressions and other local variables.
5202 ;; Using `org-outline-regexp-bol' would complicate them much,
5203 ;; because of the fixed white space at the end of that string.
5204 (unless org-done-keywords
5205 (setq org-done-keywords
5206 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5207 (setq org-not-done-keywords
5208 (org-delete-all org-done-keywords
5209 (copy-sequence org-todo-keywords-1))
5210 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5211 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5212 org-not-done-heading-regexp
5213 (format org-heading-keyword-regexp-format org-not-done-regexp)
5214 org-todo-line-regexp
5215 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5216 org-complex-heading-regexp
5217 (concat "^\\(\\*+\\)"
5218 "\\(?: +" org-todo-regexp "\\)?"
5219 "\\(?: +\\(\\[#.\\]\\)\\)?"
5220 "\\(?: +\\(.*?\\)\\)??"
5221 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5222 "[ \t]*$")
5223 org-complex-heading-regexp-format
5224 (concat "^\\(\\*+\\)"
5225 "\\(?: +" org-todo-regexp "\\)?"
5226 "\\(?: +\\(\\[#.\\]\\)\\)?"
5227 "\\(?: +"
5228 ;; Stats cookies can be stuck to body.
5229 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5230 "\\(%s\\)"
5231 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5232 "\\)"
5233 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5234 "[ \t]*$")
5235 org-todo-line-tags-regexp
5236 (concat "^\\(\\*+\\)"
5237 "\\(?: +" org-todo-regexp "\\)?"
5238 "\\(?: +\\(.*?\\)\\)??"
5239 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5240 "[ \t]*$"))
5241 (org-compute-latex-and-related-regexp)))))
5243 (defun org--setup-collect-keywords (regexp &optional files alist)
5244 "Return setup keywords values as an alist.
5246 REGEXP matches a subset of setup keywords. FILES is a list of
5247 file names already visited. It is used to avoid circular setup
5248 files. ALIST, when non-nil, is the alist computed so far.
5250 Return value contains the following keys: `archive', `category',
5251 `columns', `constants', `filetags', `link', `priorities',
5252 `property', `scripts', `startup', `tags' and `todo'."
5253 (org-with-wide-buffer
5254 (goto-char (point-min))
5255 (let ((case-fold-search t))
5256 (while (re-search-forward regexp nil t)
5257 (let ((element (org-element-at-point)))
5258 (when (eq (org-element-type element) 'keyword)
5259 (let ((key (org-element-property :key element))
5260 (value (org-element-property :value element)))
5261 (cond
5262 ((equal key "ARCHIVE")
5263 (when (org-string-nw-p value)
5264 (push (cons 'archive value) alist)))
5265 ((equal key "CATEGORY") (push (cons 'category value) alist))
5266 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5267 ((equal key "CONSTANTS")
5268 (let* ((constants (assq 'constants alist))
5269 (store (cdr constants)))
5270 (dolist (pair (org-split-string value))
5271 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5272 pair)
5273 (let* ((name (match-string 1 pair))
5274 (value (match-string 2 pair))
5275 (old (assoc name store)))
5276 (if old (setcdr old value)
5277 (push (cons name value) store)))))
5278 (if constants (setcdr constants store)
5279 (push (cons 'constants store) alist))))
5280 ((equal key "FILETAGS")
5281 (when (org-string-nw-p value)
5282 (let ((old (assq 'filetags alist))
5283 (new (apply #'nconc
5284 (mapcar (lambda (x) (org-split-string x ":"))
5285 (org-split-string value)))))
5286 (if old (setcdr old (append new (cdr old)))
5287 (push (cons 'filetags new) alist)))))
5288 ((equal key "LINK")
5289 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5290 (let ((links (assq 'link alist))
5291 (pair (cons (match-string-no-properties 1 value)
5292 (match-string-no-properties 2 value))))
5293 (if links (push pair (cdr links))
5294 (push (list 'link pair) alist)))))
5295 ((equal key "OPTIONS")
5296 (when (and (org-string-nw-p value)
5297 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5298 (push (cons 'scripts (read (match-string 1 value))) alist)))
5299 ((equal key "PRIORITIES")
5300 (push (cons 'priorities
5301 (let ((prio (org-split-string value)))
5302 (if (< (length prio) 3) '(?A ?C ?B)
5303 (mapcar #'string-to-char prio))))
5304 alist))
5305 ((equal key "PROPERTY")
5306 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5307 (let* ((property (assq 'property alist))
5308 (value (org--update-property-plist
5309 (match-string-no-properties 1 value)
5310 (match-string-no-properties 2 value)
5311 (cdr property))))
5312 (if property (setcdr property value)
5313 (push (cons 'property value) alist)))))
5314 ((equal key "STARTUP")
5315 (let ((startup (assq 'startup alist)))
5316 (if startup
5317 (setcdr startup
5318 (append (cdr startup) (org-split-string value)))
5319 (push (cons 'startup (org-split-string value)) alist))))
5320 ((equal key "TAGS")
5321 (let ((tag-cell (assq 'tags alist)))
5322 (if tag-cell
5323 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5324 (push (cons 'tags value) alist))))
5325 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5326 (let ((todo (assq 'todo alist))
5327 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5328 (org-split-string value))))
5329 (if todo (push value (cdr todo))
5330 (push (list 'todo value) alist))))
5331 ((equal key "SETUPFILE")
5332 (unless buffer-read-only ; Do not check in Gnus messages.
5333 (let ((f (and (org-string-nw-p value)
5334 (expand-file-name
5335 (org-unbracket-string "\"" "\"" value)))))
5336 (when (and f (file-readable-p f) (not (member f files)))
5337 (with-temp-buffer
5338 (setq default-directory (file-name-directory f))
5339 (insert-file-contents f)
5340 (setq alist
5341 ;; Fake Org mode to benefit from cache
5342 ;; without recurring needlessly.
5343 (let ((major-mode 'org-mode))
5344 (org--setup-collect-keywords
5345 regexp (cons f files) alist)))))))))))))))
5346 alist)
5348 (defun org-tag-string-to-alist (s)
5349 "Return tag alist associated to string S.
5350 S is a value for TAGS keyword or produced with
5351 `org-tag-alist-to-string'. Return value is an alist suitable for
5352 `org-tag-alist' or `org-tag-persistent-alist'."
5353 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5354 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5355 "\\|{.+?}\\)" ; regular expression
5356 "\\(?:(\\(.\\))\\)?\\'"))
5357 alist group-flag)
5358 (dolist (tokens lines (cdr (nreverse alist)))
5359 (push '(:newline) alist)
5360 (while tokens
5361 (let ((token (pop tokens)))
5362 (pcase token
5363 ("{"
5364 (push '(:startgroup) alist)
5365 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5366 ("}"
5367 (push '(:endgroup) alist)
5368 (setq group-flag nil))
5369 ("["
5370 (push '(:startgrouptag) alist)
5371 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5372 ("]"
5373 (push '(:endgrouptag) alist)
5374 (setq group-flag nil))
5375 (":"
5376 (push '(:grouptags) alist))
5377 ((guard (string-match tag-re token))
5378 (let ((tag (match-string 1 token))
5379 (key (and (match-beginning 2)
5380 (string-to-char (match-string 2 token)))))
5381 ;; Push all tags in groups, no matter if they already
5382 ;; appear somewhere else in the list.
5383 (when (or group-flag (not (assoc tag alist)))
5384 (push (cons tag key) alist))))))))))
5386 (defun org-tag-alist-to-string (alist &optional skip-key)
5387 "Return tag string associated to ALIST.
5389 ALIST is an alist, as defined in `org-tag-alist' or
5390 `org-tag-persistent-alist', or produced with
5391 `org-tag-string-to-alist'.
5393 Return value is a string suitable as a value for \"TAGS\"
5394 keyword.
5396 When optional argument SKIP-KEY is non-nil, skip selection keys
5397 next to tags."
5398 (mapconcat (lambda (token)
5399 (pcase token
5400 (`(:startgroup) "{")
5401 (`(:endgroup) "}")
5402 (`(:startgrouptag) "[")
5403 (`(:endgrouptag) "]")
5404 (`(:grouptags) ":")
5405 (`(:newline) "\\n")
5406 ((and
5407 (guard (not skip-key))
5408 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5409 (format "%s(%c)" tag key))
5410 (`(,(and tag (pred stringp)) . ,_) tag)
5411 (_ (user-error "Invalid tag token: %S" token))))
5412 alist
5413 " "))
5415 (defun org-tag-alist-to-groups (alist)
5416 "Return group alist from tag ALIST.
5417 ALIST is an alist, as defined in `org-tag-alist' or
5418 `org-tag-persistent-alist', or produced with
5419 `org-tag-string-to-alist'. Return value is an alist following
5420 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5421 a string, summarizing TAGS, as a list of strings."
5422 (let (groups group-status current-group)
5423 (dolist (token alist (nreverse groups))
5424 (pcase token
5425 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5426 (`(,(or :endgroup :endgrouptag))
5427 (when (eq group-status 'append)
5428 (push (nreverse current-group) groups))
5429 (setq group-status nil))
5430 (`(:grouptags) (setq group-status 'append))
5431 ((and `(,tag . ,_) (guard group-status))
5432 (if (eq group-status 'append) (push tag current-group)
5433 (setq current-group (list tag))))
5434 (_ nil)))))
5436 (defun org-file-contents (file &optional noerror)
5437 "Return the contents of FILE, as a string."
5438 (if (and file (file-readable-p file))
5439 (with-temp-buffer
5440 (insert-file-contents file)
5441 (buffer-string))
5442 (funcall (if noerror 'message 'error)
5443 "Cannot read file \"%s\"%s"
5444 file
5445 (let ((from (buffer-file-name (buffer-base-buffer))))
5446 (if from (concat " (referenced in file \"" from "\")") "")))))
5448 (defun org-extract-log-state-settings (x)
5449 "Extract the log state setting from a TODO keyword string.
5450 This will extract info from a string like \"WAIT(w@/!)\"."
5451 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5452 (let ((kw (match-string 1 x))
5453 (log1 (and (match-end 3) (match-string 3 x)))
5454 (log2 (and (match-end 4) (match-string 4 x))))
5455 (and (or log1 log2)
5456 (list kw
5457 (and log1 (if (equal log1 "!") 'time 'note))
5458 (and log2 (if (equal log2 "!") 'time 'note)))))))
5460 (defun org-remove-keyword-keys (list)
5461 "Remove a pair of parenthesis at the end of each string in LIST."
5462 (mapcar (lambda (x)
5463 (if (string-match "(.*)$" x)
5464 (substring x 0 (match-beginning 0))
5466 list))
5468 (defun org-assign-fast-keys (alist)
5469 "Assign fast keys to a keyword-key alist.
5470 Respect keys that are already there."
5471 (let (new e (alt ?0))
5472 (while (setq e (pop alist))
5473 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5474 (cdr e)) ;; Key already assigned.
5475 (push e new)
5476 (let ((clist (string-to-list (downcase (car e))))
5477 (used (append new alist)))
5478 (when (= (car clist) ?@)
5479 (pop clist))
5480 (while (and clist (rassoc (car clist) used))
5481 (pop clist))
5482 (unless clist
5483 (while (rassoc alt used)
5484 (cl-incf alt)))
5485 (push (cons (car e) (or (car clist) alt)) new))))
5486 (nreverse new)))
5488 ;;; Some variables used in various places
5490 (defvar org-window-configuration nil
5491 "Used in various places to store a window configuration.")
5492 (defvar org-selected-window nil
5493 "Used in various places to store a window configuration.")
5494 (defvar org-finish-function nil
5495 "Function to be called when `C-c C-c' is used.
5496 This is for getting out of special buffers like capture.")
5497 (defvar org-last-state)
5499 ;; Defined somewhere in this file, but used before definition.
5500 (defvar org-entities) ;; defined in org-entities.el
5501 (defvar org-struct-menu)
5502 (defvar org-org-menu)
5503 (defvar org-tbl-menu)
5505 ;;;; Define the Org mode
5507 ;; We use a before-change function to check if a table might need
5508 ;; an update.
5509 (defvar org-table-may-need-update t
5510 "Indicates that a table might need an update.
5511 This variable is set by `org-before-change-function'.
5512 `org-table-align' sets it back to nil.")
5513 (defun org-before-change-function (_beg _end)
5514 "Every change indicates that a table might need an update."
5515 (setq org-table-may-need-update t))
5516 (defvar org-mode-map)
5517 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5518 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5519 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5520 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5521 (defvar org-table-buffer-is-an nil)
5523 (defvar bidi-paragraph-direction)
5524 (defvar buffer-face-mode-face)
5526 (require 'outline)
5528 ;; Other stuff we need.
5529 (require 'time-date)
5530 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5531 (require 'easymenu)
5532 (autoload 'easy-menu-add "easymenu")
5533 (require 'overlay)
5535 ;; (require 'org-macs) moved higher up in the file before it is first used
5536 (require 'org-entities)
5537 ;; (require 'org-compat) moved higher up in the file before it is first used
5538 (require 'org-faces)
5539 (require 'org-list)
5540 (require 'org-pcomplete)
5541 (require 'org-src)
5542 (require 'org-footnote)
5543 (require 'org-macro)
5545 ;; babel
5546 (require 'ob)
5548 ;;;###autoload
5549 (define-derived-mode org-mode outline-mode "Org"
5550 "Outline-based notes management and organizer, alias
5551 \"Carsten's outline-mode for keeping track of everything.\"
5553 Org mode develops organizational tasks around a NOTES file which
5554 contains information about projects as plain text. Org mode is
5555 implemented on top of Outline mode, which is ideal to keep the content
5556 of large files well structured. It supports ToDo items, deadlines and
5557 time stamps, which magically appear in the diary listing of the Emacs
5558 calendar. Tables are easily created with a built-in table editor.
5559 Plain text URL-like links connect to websites, emails (VM), Usenet
5560 messages (Gnus), BBDB entries, and any files related to the project.
5561 For printing and sharing of notes, an Org file (or a part of it)
5562 can be exported as a structured ASCII or HTML file.
5564 The following commands are available:
5566 \\{org-mode-map}"
5568 ;; Get rid of Outline menus, they are not needed
5569 ;; Need to do this here because define-derived-mode sets up
5570 ;; the keymap so late. Still, it is a waste to call this each time
5571 ;; we switch another buffer into Org mode.
5572 (define-key org-mode-map [menu-bar headings] 'undefined)
5573 (define-key org-mode-map [menu-bar hide] 'undefined)
5574 (define-key org-mode-map [menu-bar show] 'undefined)
5576 (org-load-modules-maybe)
5577 (org-install-agenda-files-menu)
5578 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5579 (add-to-invisibility-spec '(org-cwidth))
5580 (add-to-invisibility-spec '(org-hide-block . t))
5581 (setq-local outline-regexp org-outline-regexp)
5582 (setq-local outline-level 'org-outline-level)
5583 (setq bidi-paragraph-direction 'left-to-right)
5584 (when (and org-ellipsis
5585 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5586 (fboundp 'make-glyph-code))
5587 (unless org-display-table
5588 (setq org-display-table (make-display-table)))
5589 (set-display-table-slot
5590 org-display-table 4
5591 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5592 (if (stringp org-ellipsis) org-ellipsis "..."))))
5593 (setq buffer-display-table org-display-table))
5594 (org-set-regexps-and-options)
5595 (org-set-font-lock-defaults)
5596 (when (and org-tag-faces (not org-tags-special-faces-re))
5597 ;; tag faces set outside customize.... force initialization.
5598 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5599 ;; Calc embedded
5600 (setq-local calc-embedded-open-mode "# ")
5601 ;; Modify a few syntax entries
5602 (modify-syntax-entry ?@ "w")
5603 (modify-syntax-entry ?\" "\"")
5604 (modify-syntax-entry ?\\ "_")
5605 (modify-syntax-entry ?~ "_")
5606 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5607 ;; Activate before-change-function
5608 (setq-local org-table-may-need-update t)
5609 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5610 ;; Check for running clock before killing a buffer
5611 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5612 ;; Initialize macros templates.
5613 (org-macro-initialize-templates)
5614 ;; Initialize radio targets.
5615 (org-update-radio-target-regexp)
5616 ;; Indentation.
5617 (setq-local indent-line-function 'org-indent-line)
5618 (setq-local indent-region-function 'org-indent-region)
5619 ;; Filling and auto-filling.
5620 (org-setup-filling)
5621 ;; Comments.
5622 (org-setup-comments-handling)
5623 ;; Initialize cache.
5624 (org-element-cache-reset)
5625 ;; Beginning/end of defun
5626 (setq-local beginning-of-defun-function 'org-backward-element)
5627 (setq-local end-of-defun-function
5628 (lambda ()
5629 (if (not (org-at-heading-p))
5630 (org-forward-element)
5631 (org-forward-element)
5632 (forward-char -1))))
5633 ;; Next error for sparse trees
5634 (setq-local next-error-function 'org-occur-next-match)
5635 ;; Make sure dependence stuff works reliably, even for users who set it
5636 ;; too late :-(
5637 (if org-enforce-todo-dependencies
5638 (add-hook 'org-blocker-hook
5639 'org-block-todo-from-children-or-siblings-or-parent)
5640 (remove-hook 'org-blocker-hook
5641 'org-block-todo-from-children-or-siblings-or-parent))
5642 (if org-enforce-todo-checkbox-dependencies
5643 (add-hook 'org-blocker-hook
5644 'org-block-todo-from-checkboxes)
5645 (remove-hook 'org-blocker-hook
5646 'org-block-todo-from-checkboxes))
5648 ;; Align options lines
5649 (setq-local
5650 align-mode-rules-list
5651 '((org-in-buffer-settings
5652 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5653 (modes . '(org-mode)))))
5655 ;; Imenu
5656 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5658 ;; Make isearch reveal context
5659 (setq-local outline-isearch-open-invisible-function
5660 (lambda (&rest _) (org-show-context 'isearch)))
5662 ;; Setup the pcomplete hooks
5663 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5664 (setq-local pcomplete-command-name-function 'org-command-at-point)
5665 (setq-local pcomplete-default-completion-function 'ignore)
5666 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5667 (setq-local pcomplete-termination-string "")
5668 (setq-local buffer-face-mode-face 'org-default)
5670 ;; If empty file that did not turn on Org mode automatically, make
5671 ;; it to.
5672 (when (and org-insert-mode-line-in-empty-file
5673 (called-interactively-p 'any)
5674 (= (point-min) (point-max)))
5675 (insert "# -*- mode: org -*-\n\n"))
5676 (unless org-inhibit-startup
5677 (org-unmodified
5678 (when org-startup-with-beamer-mode (org-beamer-mode))
5679 (when org-startup-align-all-tables
5680 (org-table-map-tables #'org-table-align t))
5681 (when org-startup-with-inline-images (org-display-inline-images))
5682 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5683 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5684 (when org-startup-truncated (setq truncate-lines t))
5685 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5686 (org-refresh-effort-properties)))
5687 ;; Try to set `org-hide' face correctly.
5688 (let ((foreground (org-find-invisible-foreground)))
5689 (when foreground
5690 (set-face-foreground 'org-hide foreground))))
5692 ;; Update `customize-package-emacs-version-alist'
5693 (add-to-list 'customize-package-emacs-version-alist
5694 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5695 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5696 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5697 ("9.0" . "26.1")))
5699 (defvar org-mode-transpose-word-syntax-table
5700 (let ((st (make-syntax-table text-mode-syntax-table)))
5701 (dolist (c org-emphasis-alist st)
5702 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5704 (when (fboundp 'abbrev-table-put)
5705 (abbrev-table-put org-mode-abbrev-table
5706 :parents (list text-mode-abbrev-table)))
5708 (defun org-find-invisible-foreground ()
5709 (let ((candidates (remove
5710 "unspecified-bg"
5711 (nconc
5712 (list (face-background 'default)
5713 (face-background 'org-default))
5714 (mapcar
5715 (lambda (alist)
5716 (when (boundp alist)
5717 (cdr (assq 'background-color (symbol-value alist)))))
5718 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5719 (list (face-foreground 'org-hide))))))
5720 (car (remove nil candidates))))
5722 (defun org-current-time (&optional rounding-minutes past)
5723 "Current time, possibly rounded to ROUNDING-MINUTES.
5724 When ROUNDING-MINUTES is not an integer, fall back on the car of
5725 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5726 the rounding returns a past time."
5727 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5728 (car org-time-stamp-rounding-minutes)))
5729 (time (decode-time)) res)
5730 (if (< r 1)
5731 (current-time)
5732 (setq res
5733 (apply 'encode-time
5734 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5735 (nthcdr 2 time))))
5736 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5737 (seconds-to-time (- (float-time res) (* r 60)))
5738 res))))
5740 (defun org-today ()
5741 "Return today date, considering `org-extend-today-until'."
5742 (time-to-days
5743 (time-subtract (current-time)
5744 (list 0 (* 3600 org-extend-today-until) 0))))
5746 ;;;; Font-Lock stuff, including the activators
5748 (defvar org-mouse-map (make-sparse-keymap))
5749 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5750 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5751 (when org-mouse-1-follows-link
5752 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5753 (when org-tab-follows-link
5754 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5755 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5757 (require 'font-lock)
5759 (defconst org-non-link-chars "]\t\n\r<>")
5760 (defvar org-link-types-re nil
5761 "Matches a link that has a url-like prefix like \"http:\"")
5762 (defvar org-link-re-with-space nil
5763 "Matches a link with spaces, optional angular brackets around it.")
5764 (defvar org-link-re-with-space2 nil
5765 "Matches a link with spaces, optional angular brackets around it.")
5766 (defvar org-link-re-with-space3 nil
5767 "Matches a link with spaces, only for internal part in bracket links.")
5768 (defvar org-angle-link-re nil
5769 "Matches link with angular brackets, spaces are allowed.")
5770 (defvar org-plain-link-re nil
5771 "Matches plain link, without spaces.")
5772 (defvar org-bracket-link-regexp nil
5773 "Matches a link in double brackets.")
5774 (defvar org-bracket-link-analytic-regexp nil
5775 "Regular expression used to analyze links.
5776 Here is what the match groups contain after a match:
5777 1: http:
5778 2: http
5779 3: path
5780 4: [desc]
5781 5: desc")
5782 (defvar org-bracket-link-analytic-regexp++ nil
5783 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5784 (defvar org-any-link-re nil
5785 "Regular expression matching any link.")
5787 (defconst org-match-sexp-depth 3
5788 "Number of stacked braces for sub/superscript matching.")
5790 (defun org-create-multibrace-regexp (left right n)
5791 "Create a regular expression which will match a balanced sexp.
5792 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5793 as single character strings.
5794 The regexp returned will match the entire expression including the
5795 delimiters. It will also define a single group which contains the
5796 match except for the outermost delimiters. The maximum depth of
5797 stacked delimiters is N. Escaping delimiters is not possible."
5798 (let* ((nothing (concat "[^" left right "]*?"))
5799 (or "\\|")
5800 (re nothing)
5801 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5802 (while (> n 1)
5803 (setq n (1- n)
5804 re (concat re or next)
5805 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5806 (concat left "\\(" re "\\)" right)))
5808 (defconst org-match-substring-regexp
5809 (concat
5810 "\\(\\S-\\)\\([_^]\\)\\("
5811 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5812 "\\|"
5813 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5814 "\\|"
5815 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5816 "The regular expression matching a sub- or superscript.")
5818 (defconst org-match-substring-with-braces-regexp
5819 (concat
5820 "\\(\\S-\\)\\([_^]\\)"
5821 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5822 "The regular expression matching a sub- or superscript, forcing braces.")
5824 (defun org-make-link-regexps ()
5825 "Update the link regular expressions.
5826 This should be called after the variable `org-link-parameters' has changed."
5827 (let ((types-re (regexp-opt (org-link-types) t)))
5828 (setq org-link-types-re
5829 (concat "\\`" types-re ":")
5830 org-link-re-with-space
5831 (concat "<?" types-re ":"
5832 "\\([^" org-non-link-chars " ]"
5833 "[^" org-non-link-chars "]*"
5834 "[^" org-non-link-chars " ]\\)>?")
5835 org-link-re-with-space2
5836 (concat "<?" types-re ":"
5837 "\\([^" org-non-link-chars " ]"
5838 "[^\t\n\r]*"
5839 "[^" org-non-link-chars " ]\\)>?")
5840 org-link-re-with-space3
5841 (concat "<?" types-re ":"
5842 "\\([^" org-non-link-chars " ]"
5843 "[^\t\n\r]*\\)")
5844 org-angle-link-re
5845 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5846 types-re)
5847 org-plain-link-re
5848 (concat
5849 "\\<" types-re ":"
5850 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5851 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5852 org-bracket-link-regexp
5853 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5854 org-bracket-link-analytic-regexp
5855 (concat
5856 "\\[\\["
5857 "\\(" types-re ":\\)?"
5858 "\\([^]]+\\)"
5859 "\\]"
5860 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5861 "\\]")
5862 org-bracket-link-analytic-regexp++
5863 (concat
5864 "\\[\\["
5865 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5866 "\\([^]]+\\)"
5867 "\\]"
5868 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5869 "\\]")
5870 org-any-link-re
5871 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5872 org-angle-link-re "\\)\\|\\("
5873 org-plain-link-re "\\)"))))
5875 (org-make-link-regexps)
5877 (defvar org-emph-face nil)
5879 (defun org-do-emphasis-faces (limit)
5880 "Run through the buffer and emphasize strings."
5881 (let (rtn a)
5882 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5883 (let* ((border (char-after (match-beginning 3)))
5884 (bre (regexp-quote (char-to-string border))))
5885 (when (and (not (= border (char-after (match-beginning 4))))
5886 (not (string-match-p (concat bre ".*" bre)
5887 (replace-regexp-in-string
5888 "\n" " "
5889 (substring (match-string 2) 1 -1)))))
5890 (setq rtn t)
5891 (setq a (assoc (match-string 3) org-emphasis-alist))
5892 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5893 'face
5894 (nth 1 a))
5895 (and (nth 2 a)
5896 (org-remove-flyspell-overlays-in
5897 (match-beginning 0) (match-end 0)))
5898 (add-text-properties (match-beginning 2) (match-end 2)
5899 '(font-lock-multiline t org-emphasis t))
5900 (when org-hide-emphasis-markers
5901 (add-text-properties (match-end 4) (match-beginning 5)
5902 '(invisible org-link))
5903 (add-text-properties (match-beginning 3) (match-end 3)
5904 '(invisible org-link)))))
5905 (goto-char (1+ (match-beginning 0))))
5906 rtn))
5908 (defun org-emphasize (&optional char)
5909 "Insert or change an emphasis, i.e. a font like bold or italic.
5910 If there is an active region, change that region to a new emphasis.
5911 If there is no region, just insert the marker characters and position
5912 the cursor between them.
5913 CHAR should be the marker character. If it is a space, it means to
5914 remove the emphasis of the selected region.
5915 If CHAR is not given (for example in an interactive call) it will be
5916 prompted for."
5917 (interactive)
5918 (let ((erc org-emphasis-regexp-components)
5919 (string "") beg end move s)
5920 (if (org-region-active-p)
5921 (setq beg (region-beginning)
5922 end (region-end)
5923 string (buffer-substring beg end))
5924 (setq move t))
5926 (unless char
5927 (message "Emphasis marker or tag: [%s]"
5928 (mapconcat #'car org-emphasis-alist ""))
5929 (setq char (read-char-exclusive)))
5930 (if (equal char ?\s)
5931 (setq s ""
5932 move nil)
5933 (unless (assoc (char-to-string char) org-emphasis-alist)
5934 (user-error "No such emphasis marker: \"%c\"" char))
5935 (setq s (char-to-string char)))
5936 (while (and (> (length string) 1)
5937 (equal (substring string 0 1) (substring string -1))
5938 (assoc (substring string 0 1) org-emphasis-alist))
5939 (setq string (substring string 1 -1)))
5940 (setq string (concat s string s))
5941 (when beg (delete-region beg end))
5942 (unless (or (bolp)
5943 (string-match (concat "[" (nth 0 erc) "\n]")
5944 (char-to-string (char-before (point)))))
5945 (insert " "))
5946 (unless (or (eobp)
5947 (string-match (concat "[" (nth 1 erc) "\n]")
5948 (char-to-string (char-after (point)))))
5949 (insert " ") (backward-char 1))
5950 (insert string)
5951 (and move (backward-char 1))))
5953 (defconst org-nonsticky-props
5954 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5956 (defsubst org-rear-nonsticky-at (pos)
5957 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5959 (defun org-activate-plain-links (limit)
5960 "Add link properties for plain links."
5961 (when (and (re-search-forward org-plain-link-re limit t)
5962 (not (org-in-src-block-p)))
5964 (let* ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5965 'face))
5966 (link (match-string-no-properties 0))
5967 (type (match-string-no-properties 1))
5968 (path (match-string-no-properties 2))
5969 (link-start (match-beginning 0))
5970 (link-end (match-end 0))
5971 (link-face (org-link-get-parameter type :face))
5972 (help-echo (org-link-get-parameter type :help-echo))
5973 (htmlize-link (org-link-get-parameter type :htmlize-link))
5974 (activate-func (org-link-get-parameter type :activate-func)))
5975 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5976 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5977 (add-text-properties (match-beginning 0) (match-end 0)
5978 (list
5979 'mouse-face (or (org-link-get-parameter type :mouse-face)
5980 'highlight)
5981 'face (cond
5982 ;; A function that returns a face
5983 ((functionp link-face)
5984 (funcall link-face path))
5985 ;; a face
5986 ((facep link-face)
5987 link-face)
5988 ;; An anonymous face
5989 ((consp link-face)
5990 link-face)
5991 ;; default
5993 'org-link))
5994 'help-echo (cond
5995 ((stringp help-echo)
5996 help-echo)
5997 ((functionp help-echo)
5998 help-echo)
6000 (concat "LINK: "
6001 (save-match-data
6002 (org-link-unescape link)))))
6003 'htmlize-link (cond
6004 ((functionp htmlize-link)
6005 (funcall htmlize-link path))
6007 `(:uri ,link)))
6008 'keymap (or (org-link-get-parameter type :keymap)
6009 org-mouse-map)
6010 'org-link-start (match-beginning 0)))
6011 (org-rear-nonsticky-at (match-end 0))
6012 (when activate-func
6013 (funcall activate-func link-start link-end path nil))
6014 t))))
6016 (defun org-activate-code (limit)
6017 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
6018 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6019 (remove-text-properties (match-beginning 0) (match-end 0)
6020 '(display t invisible t intangible t))
6023 (defcustom org-src-fontify-natively t
6024 "When non-nil, fontify code in code blocks.
6025 See also the `org-block' face."
6026 :type 'boolean
6027 :version "24.4"
6028 :package-version '(Org . "8.3")
6029 :group 'org-appearance
6030 :group 'org-babel)
6032 (defcustom org-allow-promoting-top-level-subtree nil
6033 "When non-nil, allow promoting a top level subtree.
6034 The leading star of the top level headline will be replaced
6035 by a #."
6036 :type 'boolean
6037 :version "24.1"
6038 :group 'org-appearance)
6040 (defun org-fontify-meta-lines-and-blocks (limit)
6041 (condition-case nil
6042 (org-fontify-meta-lines-and-blocks-1 limit)
6043 (error (message "org-mode fontification error in %S at %d"
6044 (current-buffer)
6045 (line-number-at-pos)))))
6047 (defun org-fontify-meta-lines-and-blocks-1 (limit)
6048 "Fontify #+ lines and blocks."
6049 (let ((case-fold-search t))
6050 (when (re-search-forward
6051 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
6052 limit t)
6053 (let ((beg (match-beginning 0))
6054 (block-start (match-end 0))
6055 (block-end nil)
6056 (lang (match-string 7))
6057 (beg1 (line-beginning-position 2))
6058 (dc1 (downcase (match-string 2)))
6059 (dc3 (downcase (match-string 3)))
6060 end end1 quoting block-type)
6061 (cond
6062 ((and (match-end 4) (equal dc3 "+begin"))
6063 ;; Truly a block
6064 (setq block-type (downcase (match-string 5))
6065 quoting (member block-type org-protecting-blocks))
6066 (when (re-search-forward
6067 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
6068 nil t) ;; on purpose, we look further than LIMIT
6069 (setq end (min (point-max) (match-end 0))
6070 end1 (min (point-max) (1- (match-beginning 0))))
6071 (setq block-end (match-beginning 0))
6072 (when quoting
6073 (org-remove-flyspell-overlays-in beg1 end1)
6074 (remove-text-properties beg end
6075 '(display t invisible t intangible t)))
6076 (add-text-properties
6077 beg end '(font-lock-fontified t font-lock-multiline t))
6078 (add-text-properties beg beg1 '(face org-meta-line))
6079 (org-remove-flyspell-overlays-in beg beg1)
6080 (add-text-properties ; For end_src
6081 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6082 (org-remove-flyspell-overlays-in end1 end)
6083 (cond
6084 ((and lang (not (string= lang "")) org-src-fontify-natively)
6085 (org-src-font-lock-fontify-block lang block-start block-end)
6086 (add-text-properties beg1 block-end '(src-block t)))
6087 (quoting
6088 (add-text-properties beg1 (min (point-max) (1+ end1))
6089 (list 'face
6090 (list :inherit
6091 (let ((face-name
6092 (intern (format "org-block-%s" lang))))
6093 (append (and (facep face-name) (list face-name))
6094 '(org-block))))))) ; end of source block
6095 ((not org-fontify-quote-and-verse-blocks))
6096 ((string= block-type "quote")
6097 (add-face-text-property
6098 beg1 (min (point-max) (1+ end1)) 'org-quote t))
6099 ((string= block-type "verse")
6100 (add-face-text-property
6101 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
6102 (add-text-properties beg beg1 '(face org-block-begin-line))
6103 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6104 '(face org-block-end-line))
6106 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6107 (org-remove-flyspell-overlays-in
6108 (match-beginning 0)
6109 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6110 (add-text-properties
6111 beg (match-end 3)
6112 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6113 '(font-lock-fontified t invisible t)
6114 '(font-lock-fontified t face org-document-info-keyword)))
6115 (add-text-properties
6116 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6117 (if (string-equal dc1 "+title:")
6118 '(font-lock-fontified t face org-document-title)
6119 '(font-lock-fontified t face org-document-info))))
6120 ((string-prefix-p "+caption" dc1)
6121 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6122 (remove-text-properties (match-beginning 0) (match-end 0)
6123 '(display t invisible t intangible t))
6124 ;; Handle short captions.
6125 (save-excursion
6126 (beginning-of-line)
6127 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6128 (add-text-properties (line-beginning-position) (match-end 1)
6129 '(font-lock-fontified t face org-meta-line))
6130 (add-text-properties (match-end 0) (line-end-position)
6131 '(font-lock-fontified t face org-block))
6133 ((member dc3 '(" " ""))
6134 (org-remove-flyspell-overlays-in beg (match-end 0))
6135 (add-text-properties
6136 beg (match-end 0)
6137 '(font-lock-fontified t face font-lock-comment-face)))
6138 (t ;; just any other in-buffer setting, but not indented
6139 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6140 (remove-text-properties (match-beginning 0) (match-end 0)
6141 '(display t invisible t intangible t))
6142 (add-text-properties beg (match-end 0)
6143 '(font-lock-fontified t face org-meta-line))
6144 t))))))
6146 (defun org-fontify-drawers (limit)
6147 "Fontify drawers."
6148 (when (re-search-forward org-drawer-regexp limit t)
6149 (add-text-properties
6150 (match-beginning 0) (match-end 0)
6151 '(font-lock-fontified t face org-special-keyword))
6152 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6155 (defun org-fontify-macros (limit)
6156 "Fontify macros."
6157 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6158 (add-text-properties
6159 (match-beginning 0) (match-end 0)
6160 '(font-lock-fontified t face org-macro))
6161 (when org-hide-macro-markers
6162 (add-text-properties (match-end 2) (match-beginning 2)
6163 '(invisible t))
6164 (add-text-properties (match-beginning 1) (match-end 1)
6165 '(invisible t)))
6166 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6169 (defun org-activate-angle-links (limit)
6170 "Add text properties for angle links."
6171 (when (and (re-search-forward org-angle-link-re limit t)
6172 (not (org-in-src-block-p)))
6173 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6174 (add-text-properties (match-beginning 0) (match-end 0)
6175 (list 'mouse-face 'highlight
6176 'keymap org-mouse-map
6177 'font-lock-multiline t))
6178 (org-rear-nonsticky-at (match-end 0))
6181 (defun org-activate-footnote-links (limit)
6182 "Add text properties for footnotes."
6183 (let ((fn (org-footnote-next-reference-or-definition limit)))
6184 (when fn
6185 (let* ((beg (nth 1 fn))
6186 (end (nth 2 fn))
6187 (label (car fn))
6188 (referencep (/= (line-beginning-position) beg)))
6189 (when (and referencep (nth 3 fn))
6190 (save-excursion
6191 (goto-char beg)
6192 (search-forward (or label "fn:"))
6193 (org-remove-flyspell-overlays-in beg (match-end 0))))
6194 (add-text-properties beg end
6195 (list 'mouse-face 'highlight
6196 'keymap org-mouse-map
6197 'help-echo
6198 (if referencep "Footnote reference"
6199 "Footnote definition")
6200 'font-lock-fontified t
6201 'font-lock-multiline t
6202 'face 'org-footnote))))))
6204 (defun org-activate-bracket-links (limit)
6205 "Add text properties for bracketed links."
6206 (when (and (re-search-forward org-bracket-link-regexp limit t)
6207 (not (org-in-src-block-p)))
6208 (let* ((hl (save-match-data
6209 (org-link-expand-abbrev (match-string-no-properties 1))))
6210 (type (save-match-data
6211 (and (string-match org-plain-link-re hl)
6212 (match-string-no-properties 1 hl))))
6213 (path (save-match-data
6214 (and (string-match org-plain-link-re hl)
6215 (match-string-no-properties 2 hl))))
6216 (link-start (match-beginning 0))
6217 (link-end (match-end 0))
6218 (bracketp t)
6219 (help-echo (org-link-get-parameter type :help-echo))
6220 (help (cond
6221 ((stringp help-echo)
6222 help-echo)
6223 ((functionp help-echo)
6224 help-echo)
6226 (concat "LINK: "
6227 (save-match-data
6228 (org-link-unescape hl))))))
6229 (link-face (org-link-get-parameter type :face))
6230 (face (cond
6231 ;; A function that returns a face
6232 ((functionp link-face)
6233 (funcall link-face path))
6234 ;; a face
6235 ((facep link-face)
6236 link-face)
6237 ;; An anonymous face
6238 ((consp link-face)
6239 link-face)
6240 ;; default
6242 'org-link)))
6243 (keymap (or (org-link-get-parameter type :keymap)
6244 org-mouse-map))
6245 (mouse-face (or (org-link-get-parameter type :mouse-face)
6246 'highlight))
6247 (htmlize (org-link-get-parameter type :htmlize-link))
6248 (htmlize-link (cond
6249 ((functionp htmlize)
6250 (funcall htmlize))
6252 `(:uri ,(format "%s:%s" type path)))))
6253 (activate-func (org-link-get-parameter type :activate-func))
6254 ;; invisible part
6255 (ip (list 'invisible (or
6256 (org-link-get-parameter type :display)
6257 'org-link)
6258 'face face
6259 'keymap keymap
6260 'mouse-face mouse-face
6261 'font-lock-multiline t
6262 'help-echo help
6263 'htmlize-link htmlize-link))
6264 ;; visible part
6265 (vp (list 'keymap keymap
6266 'face face
6267 'mouse-face mouse-face
6268 'font-lock-multiline t
6269 'help-echo help
6270 'htmlize-link htmlize-link)))
6271 ;; We need to remove the invisible property here. Table narrowing
6272 ;; may have made some of this invisible.
6273 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6274 (remove-text-properties (match-beginning 0) (match-end 0)
6275 '(invisible nil))
6276 (if (match-end 3)
6277 (progn
6278 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6279 (org-rear-nonsticky-at (match-beginning 3))
6280 (add-text-properties (match-beginning 3) (match-end 3) vp)
6281 (org-rear-nonsticky-at (match-end 3))
6282 (add-text-properties (match-end 3) (match-end 0) ip)
6283 (org-rear-nonsticky-at (match-end 0)))
6284 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6285 (org-rear-nonsticky-at (match-beginning 1))
6286 (add-text-properties (match-beginning 1) (match-end 1) vp)
6287 (org-rear-nonsticky-at (match-end 1))
6288 (add-text-properties (match-end 1) (match-end 0) ip)
6289 (org-rear-nonsticky-at (match-end 0)))
6290 (when activate-func
6291 (funcall activate-func link-start link-end path bracketp))
6292 t)))
6294 (defun org-activate-dates (limit)
6295 "Add text properties for dates."
6296 (when (and (re-search-forward org-tsr-regexp-both limit t)
6297 (not (equal (char-before (match-beginning 0)) 91)))
6298 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6299 (add-text-properties (match-beginning 0) (match-end 0)
6300 (list 'mouse-face 'highlight
6301 'keymap org-mouse-map))
6302 (org-rear-nonsticky-at (match-end 0))
6303 (when org-display-custom-times
6304 (if (match-end 3)
6305 (org-display-custom-time (match-beginning 3) (match-end 3))
6306 (org-display-custom-time (match-beginning 1) (match-end 1))))
6309 (defvar-local org-target-link-regexp nil
6310 "Regular expression matching radio targets in plain text.")
6312 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6313 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6314 border border border))
6315 "Regular expression matching a link target.")
6317 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6318 "Regular expression matching a radio target.")
6320 (defconst org-any-target-regexp
6321 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6322 "Regular expression matching any target.")
6324 (defun org-activate-target-links (limit)
6325 "Add text properties for target matches."
6326 (when org-target-link-regexp
6327 (let ((case-fold-search t))
6328 (when (re-search-forward org-target-link-regexp limit t)
6329 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6330 (add-text-properties (match-beginning 1) (match-end 1)
6331 (list 'mouse-face 'highlight
6332 'keymap org-mouse-map
6333 'help-echo "Radio target link"
6334 'org-linked-text t))
6335 (org-rear-nonsticky-at (match-end 1))
6336 t))))
6338 (defun org-update-radio-target-regexp ()
6339 "Find all radio targets in this file and update the regular expression.
6340 Also refresh fontification if needed."
6341 (interactive)
6342 (let ((old-regexp org-target-link-regexp)
6343 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6344 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6345 (targets
6346 (org-with-wide-buffer
6347 (goto-char (point-min))
6348 (let (rtn)
6349 (while (re-search-forward org-radio-target-regexp nil t)
6350 ;; Make sure point is really within the object.
6351 (backward-char)
6352 (let ((obj (org-element-context)))
6353 (when (eq (org-element-type obj) 'radio-target)
6354 (cl-pushnew (org-element-property :value obj) rtn
6355 :test #'equal))))
6356 rtn))))
6357 (setq org-target-link-regexp
6358 (and targets
6359 (concat before-re
6360 (mapconcat
6361 (lambda (x)
6362 (replace-regexp-in-string
6363 " +" "\\s-+" (regexp-quote x) t t))
6364 targets
6365 "\\|")
6366 after-re)))
6367 (unless (equal old-regexp org-target-link-regexp)
6368 ;; Clean-up cache.
6369 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6370 ((not org-target-link-regexp) old-regexp)
6372 (concat before-re
6373 (mapconcat
6374 (lambda (re)
6375 (substring re (length before-re)
6376 (- (length after-re))))
6377 (list old-regexp org-target-link-regexp)
6378 "\\|")
6379 after-re)))))
6380 (org-with-wide-buffer
6381 (goto-char (point-min))
6382 (while (re-search-forward regexp nil t)
6383 (org-element-cache-refresh (match-beginning 1)))))
6384 ;; Re fontify buffer.
6385 (when (memq 'radio org-highlight-links)
6386 (org-restart-font-lock)))))
6388 (defun org-hide-wide-columns (limit)
6389 (let (s e)
6390 (setq s (text-property-any (point) (or limit (point-max))
6391 'org-cwidth t))
6392 (when s
6393 (setq e (next-single-property-change s 'org-cwidth))
6394 (add-text-properties s e '(invisible org-cwidth))
6395 (goto-char e)
6396 t)))
6398 (defvar org-latex-and-related-regexp nil
6399 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6401 (defun org-compute-latex-and-related-regexp ()
6402 "Compute regular expression for LaTeX, entities and sub/superscript.
6403 Result depends on variable `org-highlight-latex-and-related'."
6404 (setq-local
6405 org-latex-and-related-regexp
6406 (let* ((re-sub
6407 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6408 ((eq org-use-sub-superscripts '{})
6409 (list org-match-substring-with-braces-regexp))
6410 (org-use-sub-superscripts (list org-match-substring-regexp))))
6411 (re-latex
6412 (when (memq 'latex org-highlight-latex-and-related)
6413 (let ((matchers (plist-get org-format-latex-options :matchers)))
6414 (delq nil
6415 (mapcar (lambda (x)
6416 (and (member (car x) matchers) (nth 1 x)))
6417 org-latex-regexps)))))
6418 (re-entities
6419 (when (memq 'entities org-highlight-latex-and-related)
6420 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6421 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6423 (defun org-do-latex-and-related (limit)
6424 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6425 LIMIT bounds the search for syntax to highlight. Stop at first
6426 highlighted object, if any. Return t if some highlighting was
6427 done, nil otherwise."
6428 (when (org-string-nw-p org-latex-and-related-regexp)
6429 (catch 'found
6430 (while (re-search-forward org-latex-and-related-regexp limit t)
6431 (unless
6432 (cl-some
6433 (lambda (f)
6434 (memq f '(org-code org-verbatim underline org-special-keyword)))
6435 (save-excursion
6436 (goto-char (1+ (match-beginning 0)))
6437 (face-at-point nil t)))
6438 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6439 '(?_ ?^))
6441 0)))
6442 (font-lock-prepend-text-property
6443 (+ offset (match-beginning 0)) (match-end 0)
6444 'face 'org-latex-and-related)
6445 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6446 '(font-lock-multiline t)))
6447 (throw 'found t)))
6448 nil)))
6450 (defun org-restart-font-lock ()
6451 "Restart `font-lock-mode', to force refontification."
6452 (when (and (boundp 'font-lock-mode) font-lock-mode)
6453 (font-lock-mode -1)
6454 (font-lock-mode 1)))
6456 (defun org-activate-tags (limit)
6457 (when (re-search-forward
6458 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6459 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6460 (add-text-properties (match-beginning 1) (match-end 1)
6461 (list 'mouse-face 'highlight
6462 'keymap org-mouse-map))
6463 (org-rear-nonsticky-at (match-end 1))
6466 (defun org-outline-level ()
6467 "Compute the outline level of the heading at point.
6469 If this is called at a normal headline, the level is the number
6470 of stars. Use `org-reduced-level' to remove the effect of
6471 `org-odd-levels'. Unlike to `org-current-level', this function
6472 takes into consideration inlinetasks."
6473 (org-with-wide-buffer
6474 (end-of-line)
6475 (if (re-search-backward org-outline-regexp-bol nil t)
6476 (1- (- (match-end 0) (match-beginning 0)))
6477 0)))
6479 (defvar org-font-lock-keywords nil)
6481 (defsubst org-re-property (property &optional literal allow-null value)
6482 "Return a regexp matching a PROPERTY line.
6484 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6485 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6486 non-nil, match properties even without a value.
6488 Match group 3 is set to the value when it exists. If there is no
6489 value and ALLOW-NULL is non-nil, it is set to the empty string.
6491 With optional argument VALUE, match only property lines with
6492 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6493 unless LITERAL is non-nil."
6494 (concat
6495 "^\\(?4:[ \t]*\\)"
6496 (format "\\(?1::\\(?2:%s\\):\\)"
6497 (if literal property (regexp-quote property)))
6498 (cond (value
6499 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6500 (if literal value (regexp-quote value))))
6501 (allow-null
6502 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6504 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6506 (defconst org-property-re
6507 (org-re-property "\\S-+" 'literal t)
6508 "Regular expression matching a property line.
6509 There are four matching groups:
6510 1: :PROPKEY: including the leading and trailing colon,
6511 2: PROPKEY without the leading and trailing colon,
6512 3: PROPVAL without leading or trailing spaces,
6513 4: the indentation of the current line,
6514 5: trailing whitespace.")
6516 (defvar org-font-lock-hook nil
6517 "Functions to be called for special font lock stuff.")
6519 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6521 (defvar org-font-lock-set-keywords-hook nil
6522 "Functions that can manipulate `org-font-lock-extra-keywords'.
6523 This is called after `org-font-lock-extra-keywords' is defined, but before
6524 it is installed to be used by font lock. This can be useful if something
6525 needs to be inserted at a specific position in the font-lock sequence.")
6527 (defun org-font-lock-hook (limit)
6528 "Run `org-font-lock-hook' within LIMIT."
6529 (run-hook-with-args 'org-font-lock-hook limit))
6531 (defun org-set-font-lock-defaults ()
6532 "Set font lock defaults for the current buffer."
6533 (let* ((em org-fontify-emphasized-text)
6534 (lk org-highlight-links)
6535 (org-font-lock-extra-keywords
6536 (list
6537 ;; Call the hook
6538 '(org-font-lock-hook)
6539 ;; Headlines
6540 `(,(if org-fontify-whole-heading-line
6541 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6542 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6543 (1 (org-get-level-face 1))
6544 (2 (org-get-level-face 2))
6545 (3 (org-get-level-face 3)))
6546 ;; Table lines
6547 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6548 (1 'org-table t))
6549 ;; Table internals
6550 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6551 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6552 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6553 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6554 ;; Drawers
6555 '(org-fontify-drawers)
6556 ;; Properties
6557 (list org-property-re
6558 '(1 'org-special-keyword t)
6559 '(3 'org-property-value t))
6560 ;; Links
6561 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6562 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6563 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link)))
6564 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link)))
6565 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6566 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6567 (when (memq 'footnote lk) '(org-activate-footnote-links))
6568 ;; Targets.
6569 (list org-any-target-regexp '(0 'org-target t))
6570 ;; Diary sexps.
6571 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6572 ;; Macro
6573 '(org-fontify-macros)
6574 '(org-hide-wide-columns (0 nil append))
6575 ;; TODO keyword
6576 (list (format org-heading-keyword-regexp-format
6577 org-todo-regexp)
6578 '(2 (org-get-todo-face 2) t))
6579 ;; DONE
6580 (if org-fontify-done-headline
6581 (list (format org-heading-keyword-regexp-format
6582 (concat
6583 "\\(?:"
6584 (mapconcat 'regexp-quote org-done-keywords "\\|")
6585 "\\)"))
6586 '(2 'org-headline-done t))
6587 nil)
6588 ;; Priorities
6589 '(org-font-lock-add-priority-faces)
6590 ;; Tags
6591 '(org-font-lock-add-tag-faces)
6592 ;; Tags groups
6593 (when (and org-group-tags org-tag-groups-alist)
6594 (list (concat org-outline-regexp-bol ".+\\(:"
6595 (regexp-opt (mapcar 'car org-tag-groups-alist))
6596 ":\\).*$")
6597 '(1 'org-tag-group prepend)))
6598 ;; Special keywords
6599 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6600 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6601 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6602 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6603 ;; Emphasis
6604 (when em '(org-do-emphasis-faces))
6605 ;; Checkboxes
6606 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6607 1 'org-checkbox prepend)
6608 (when (cdr (assq 'checkbox org-list-automatic-rules))
6609 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6610 (0 (org-get-checkbox-statistics-face) t)))
6611 ;; Description list items
6612 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6613 1 'org-list-dt prepend)
6614 ;; ARCHIVEd headings
6615 (list (concat
6616 org-outline-regexp-bol
6617 "\\(.*:" org-archive-tag ":.*\\)")
6618 '(1 'org-archived prepend))
6619 ;; Specials
6620 '(org-do-latex-and-related)
6621 '(org-fontify-entities)
6622 '(org-raise-scripts)
6623 ;; Code
6624 '(org-activate-code (1 'org-code t))
6625 ;; COMMENT
6626 (list (format
6627 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6628 org-todo-regexp
6629 org-comment-string)
6630 '(9 'org-special-keyword t))
6631 ;; Blocks and meta lines
6632 '(org-fontify-meta-lines-and-blocks))))
6633 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6634 (run-hooks 'org-font-lock-set-keywords-hook)
6635 ;; Now set the full font-lock-keywords
6636 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6637 (setq-local font-lock-defaults
6638 '(org-font-lock-keywords t nil nil backward-paragraph))
6639 (kill-local-variable 'font-lock-keywords)
6640 nil))
6642 (defun org-toggle-pretty-entities ()
6643 "Toggle the composition display of entities as UTF8 characters."
6644 (interactive)
6645 (setq-local org-pretty-entities (not org-pretty-entities))
6646 (org-restart-font-lock)
6647 (if org-pretty-entities
6648 (message "Entities are now displayed as UTF8 characters")
6649 (save-restriction
6650 (widen)
6651 (decompose-region (point-min) (point-max))
6652 (message "Entities are now displayed as plain text"))))
6654 (defvar-local org-custom-properties-overlays nil
6655 "List of overlays used for custom properties.")
6657 (defun org-toggle-custom-properties-visibility ()
6658 "Display or hide properties in `org-custom-properties'."
6659 (interactive)
6660 (if org-custom-properties-overlays
6661 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6662 (setq org-custom-properties-overlays nil))
6663 (when org-custom-properties
6664 (org-with-wide-buffer
6665 (goto-char (point-min))
6666 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6667 (while (re-search-forward regexp nil t)
6668 (let ((end (cdr (save-match-data (org-get-property-block)))))
6669 (when (and end (< (point) end))
6670 ;; Hide first custom property in current drawer.
6671 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6672 (overlay-put o 'invisible t)
6673 (overlay-put o 'org-custom-property t)
6674 (push o org-custom-properties-overlays))
6675 ;; Hide additional custom properties in the same drawer.
6676 (while (re-search-forward regexp end t)
6677 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6678 (overlay-put o 'invisible t)
6679 (overlay-put o 'org-custom-property t)
6680 (push o org-custom-properties-overlays)))))
6681 ;; Each entry is limited to a single property drawer.
6682 (outline-next-heading)))))))
6684 (defun org-fontify-entities (limit)
6685 "Find an entity to fontify."
6686 (let (ee)
6687 (when org-pretty-entities
6688 (catch 'match
6689 ;; "\_ "-family is left out on purpose. Only the first one,
6690 ;; i.e., "\_ ", could be fontified anyway, and it would be
6691 ;; confusing when adding a second white space character.
6692 (while (re-search-forward
6693 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6694 limit t)
6695 (when (and (not (org-at-comment-p))
6696 (setq ee (org-entity-get (match-string 1)))
6697 (= (length (nth 6 ee)) 1))
6698 (let* ((end (if (equal (match-string 2) "{}")
6699 (match-end 2)
6700 (match-end 1))))
6701 (add-text-properties
6702 (match-beginning 0) end
6703 (list 'font-lock-fontified t))
6704 (compose-region (match-beginning 0) end
6705 (nth 6 ee) nil)
6706 (backward-char 1)
6707 (throw 'match t))))
6708 nil))))
6710 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6711 "Fontify string S like in Org mode."
6712 (with-temp-buffer
6713 (insert s)
6714 (let ((org-odd-levels-only odd-levels))
6715 (org-mode)
6716 (org-font-lock-ensure)
6717 (buffer-string))))
6719 (defvar org-m nil)
6720 (defvar org-l nil)
6721 (defvar org-f nil)
6722 (defun org-get-level-face (n)
6723 "Get the right face for match N in font-lock matching of headlines."
6724 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6725 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6726 (if org-cycle-level-faces
6727 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6728 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6729 (cond
6730 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6731 ((eq n 2) org-f)
6732 (t (unless org-level-color-stars-only org-f))))
6734 (defun org-face-from-face-or-color (context inherit face-or-color)
6735 "Create a face list that inherits INHERIT, but sets the foreground color.
6736 When FACE-OR-COLOR is not a string, just return it."
6737 (if (stringp face-or-color)
6738 (list :inherit inherit
6739 (cdr (assoc context org-faces-easy-properties))
6740 face-or-color)
6741 face-or-color))
6743 (defun org-get-todo-face (kwd)
6744 "Get the right face for a TODO keyword KWD.
6745 If KWD is a number, get the corresponding match group."
6746 (when (numberp kwd) (setq kwd (match-string kwd)))
6747 (or (org-face-from-face-or-color
6748 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6749 (and (member kwd org-done-keywords) 'org-done)
6750 'org-todo))
6752 (defun org-get-priority-face (priority)
6753 "Get the right face for PRIORITY.
6754 PRIORITY is a character."
6755 (or (org-face-from-face-or-color
6756 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6757 'org-priority))
6759 (defun org-get-tag-face (tag)
6760 "Get the right face for TAG.
6761 If TAG is a number, get the corresponding match group."
6762 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6763 (or (org-face-from-face-or-color
6764 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6765 'org-tag)))
6767 (defun org-font-lock-add-priority-faces (limit)
6768 "Add the special priority faces."
6769 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6770 (add-text-properties
6771 (match-beginning 1) (match-end 1)
6772 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6773 'font-lock-fontified t))))
6775 (defun org-font-lock-add-tag-faces (limit)
6776 "Add the special tag faces."
6777 (when (and org-tag-faces org-tags-special-faces-re)
6778 (while (re-search-forward org-tags-special-faces-re limit t)
6779 (add-text-properties (match-beginning 1) (match-end 1)
6780 (list 'face (org-get-tag-face 1)
6781 'font-lock-fontified t))
6782 (backward-char 1))))
6784 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6785 "Remove fontification and activation overlays from links."
6786 (font-lock-default-unfontify-region beg end)
6787 (let* ((buffer-undo-list t)
6788 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6789 (inhibit-modification-hooks t)
6790 deactivate-mark buffer-file-name buffer-file-truename)
6791 (decompose-region beg end)
6792 (remove-text-properties beg end
6793 '(mouse-face t keymap t org-linked-text t
6794 invisible t intangible t
6795 org-emphasis t))
6796 (org-remove-font-lock-display-properties beg end)))
6798 (defconst org-script-display '(((raise -0.3) (height 0.7))
6799 ((raise 0.3) (height 0.7))
6800 ((raise -0.5))
6801 ((raise 0.5)))
6802 "Display properties for showing superscripts and subscripts.")
6804 (defun org-remove-font-lock-display-properties (beg end)
6805 "Remove specific display properties that have been added by font lock.
6806 The will remove the raise properties that are used to show superscripts
6807 and subscripts."
6808 (let (next prop)
6809 (while (< beg end)
6810 (setq next (next-single-property-change beg 'display nil end)
6811 prop (get-text-property beg 'display))
6812 (when (member prop org-script-display)
6813 (put-text-property beg next 'display nil))
6814 (setq beg next))))
6816 (defun org-raise-scripts (limit)
6817 "Add raise properties to sub/superscripts."
6818 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6819 (re-search-forward
6820 (if (eq org-use-sub-superscripts t)
6821 org-match-substring-regexp
6822 org-match-substring-with-braces-regexp)
6823 limit t))
6824 (let* ((pos (point)) table-p comment-p
6825 (mpos (match-beginning 3))
6826 (emph-p (get-text-property mpos 'org-emphasis))
6827 (link-p (get-text-property mpos 'mouse-face))
6828 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6829 (goto-char (point-at-bol))
6830 (setq table-p (looking-at-p org-table-dataline-regexp)
6831 comment-p (looking-at-p "^[ \t]*#[ +]"))
6832 (goto-char pos)
6833 ;; Handle a_b^c
6834 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6835 (unless (or comment-p emph-p link-p keyw-p)
6836 (put-text-property (match-beginning 3) (match-end 0)
6837 'display
6838 (if (equal (char-after (match-beginning 2)) ?^)
6839 (nth (if table-p 3 1) org-script-display)
6840 (nth (if table-p 2 0) org-script-display)))
6841 (add-text-properties (match-beginning 2) (match-end 2)
6842 (list 'invisible t
6843 'org-dwidth t 'org-dwidth-n 1))
6844 (if (and (eq (char-after (match-beginning 3)) ?{)
6845 (eq (char-before (match-end 3)) ?}))
6846 (progn
6847 (add-text-properties
6848 (match-beginning 3) (1+ (match-beginning 3))
6849 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6850 (add-text-properties
6851 (1- (match-end 3)) (match-end 3)
6852 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6853 t)))
6855 ;;;; Visibility cycling, including org-goto and indirect buffer
6857 ;;; Cycling
6859 (defvar-local org-cycle-global-status nil)
6860 (put 'org-cycle-global-status 'org-state t)
6861 (defvar-local org-cycle-subtree-status nil)
6862 (put 'org-cycle-subtree-status 'org-state t)
6864 (defvar org-inlinetask-min-level)
6866 (defun org-unlogged-message (&rest args)
6867 "Display a message, but avoid logging it in the *Messages* buffer."
6868 (let ((message-log-max nil))
6869 (apply 'message args)))
6871 ;;;###autoload
6872 (defun org-cycle (&optional arg)
6873 "TAB-action and visibility cycling for Org mode.
6875 This is the command invoked in Org mode by the `TAB' key. Its main
6876 purpose is outline visibility cycling, but it also invokes other actions
6877 in special contexts.
6879 When this function is called with a `\\[universal-argument]' prefix, rotate \
6880 the entire
6881 buffer through 3 states (global cycling)
6882 1. OVERVIEW: Show only top-level headlines.
6883 2. CONTENTS: Show all headlines of all levels, but no body text.
6884 3. SHOW ALL: Show everything.
6886 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6887 switch to the startup visibility,
6888 determined by the variable `org-startup-folded', and by any VISIBILITY
6889 properties in the buffer.
6891 With a `\\[universal-argument] \\[universal-argument] \
6892 \\[universal-argument]' prefix argument, show the entire buffer, including
6893 any drawers.
6895 When inside a table, re-align the table and move to the next field.
6897 When point is at the beginning of a headline, rotate the subtree started
6898 by this line through 3 different states (local cycling)
6899 1. FOLDED: Only the main headline is shown.
6900 2. CHILDREN: The main headline and the direct children are shown.
6901 From this state, you can move to one of the children
6902 and zoom in further.
6903 3. SUBTREE: Show the entire subtree, including body text.
6904 If there is no subtree, switch directly from CHILDREN to FOLDED.
6906 When point is at the beginning of an empty headline and the variable
6907 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6908 of the headline by demoting and promoting it to likely levels. This
6909 speeds up creation document structure by pressing `TAB' once or several
6910 times right after creating a new headline.
6912 When there is a numeric prefix, go up to a heading with level ARG, do
6913 a `show-subtree' and return to the previous cursor position. If ARG
6914 is negative, go up that many levels.
6916 When point is not at the beginning of a headline, execute the global
6917 binding for `TAB', which is re-indenting the line. See the option
6918 `org-cycle-emulate-tab' for details.
6920 As a special case, if point is at the beginning of the buffer and there is
6921 no headline in line 1, this function will act as if called with prefix arg
6922 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6923 prefix arg, but only
6924 if the variable `org-cycle-global-at-bob' is t."
6925 (interactive "P")
6926 (org-load-modules-maybe)
6927 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6928 (and org-cycle-level-after-item/entry-creation
6929 (or (org-cycle-level)
6930 (org-cycle-item-indentation))))
6931 (let* ((limit-level
6932 (or org-cycle-max-level
6933 (and (boundp 'org-inlinetask-min-level)
6934 org-inlinetask-min-level
6935 (1- org-inlinetask-min-level))))
6936 (nstars (and limit-level
6937 (if org-odd-levels-only
6938 (and limit-level (1- (* limit-level 2)))
6939 limit-level)))
6940 (org-outline-regexp
6941 (if (not (derived-mode-p 'org-mode))
6942 outline-regexp
6943 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6944 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6945 (not (looking-at org-outline-regexp))))
6946 (org-cycle-hook
6947 (if bob-special
6948 (delq 'org-optimize-window-after-visibility-change
6949 (copy-sequence org-cycle-hook))
6950 org-cycle-hook))
6951 (pos (point)))
6953 (cond
6955 ((equal arg '(16))
6956 (setq last-command 'dummy)
6957 (org-set-startup-visibility)
6958 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6960 ((equal arg '(64))
6961 (outline-show-all)
6962 (org-unlogged-message "Entire buffer visible, including drawers"))
6964 ((equal arg '(4)) (org-cycle-internal-global))
6966 ;; Try hiding block at point.
6967 ((org-hide-block-toggle-maybe))
6969 ;; Try cdlatex TAB completion
6970 ((org-try-cdlatex-tab))
6972 ;; Table: enter it or move to the next field.
6973 ((org-at-table-p 'any)
6974 (if (org-at-table.el-p)
6975 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6976 Use `\\[org-edit-special]' to edit table.el tables"))
6977 (if arg (org-table-edit-field t)
6978 (org-table-justify-field-maybe)
6979 (call-interactively 'org-table-next-field))))
6981 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6983 ;; Global cycling: delegate to `org-cycle-internal-global'.
6984 (bob-special (org-cycle-internal-global))
6986 ;; Drawers: delegate to `org-flag-drawer'.
6987 ((save-excursion
6988 (beginning-of-line 1)
6989 (looking-at org-drawer-regexp))
6990 (org-flag-drawer ; toggle block visibility
6991 (not (get-char-property (match-end 0) 'invisible))))
6993 ;; Show-subtree, ARG levels up from here.
6994 ((integerp arg)
6995 (save-excursion
6996 (org-back-to-heading)
6997 (outline-up-heading (if (< arg 0) (- arg)
6998 (- (funcall outline-level) arg)))
6999 (org-show-subtree)))
7001 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
7002 ((and (featurep 'org-inlinetask)
7003 (org-inlinetask-at-task-p)
7004 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
7005 (org-inlinetask-toggle-visibility))
7007 ;; At an item/headline: delegate to `org-cycle-internal-local'.
7008 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
7009 (save-excursion (move-beginning-of-line 1)
7010 (looking-at org-outline-regexp)))
7011 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
7012 (org-cycle-internal-local))
7014 ;; From there: TAB emulation and template completion.
7015 (buffer-read-only (org-back-to-heading))
7017 ((run-hook-with-args-until-success
7018 'org-tab-after-check-for-cycling-hook))
7020 ((org-try-structure-completion))
7022 ((run-hook-with-args-until-success
7023 'org-tab-before-tab-emulation-hook))
7025 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
7026 (or (not (bolp))
7027 (not (looking-at org-outline-regexp))))
7028 (call-interactively (global-key-binding "\t")))
7030 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
7031 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
7032 (or (and (eq org-cycle-emulate-tab 'white)
7033 (= (match-end 0) (point-at-eol)))
7034 (and (eq org-cycle-emulate-tab 'whitestart)
7035 (>= (match-end 0) pos))))
7037 (eq org-cycle-emulate-tab t))
7038 (call-interactively (global-key-binding "\t")))
7040 (t (save-excursion
7041 (org-back-to-heading)
7042 (org-cycle)))))))
7044 (defun org-cycle-internal-global ()
7045 "Do the global cycling action."
7046 ;; Hack to avoid display of messages for .org attachments in Gnus
7047 (let ((ga (string-match "\\*fontification" (buffer-name))))
7048 (cond
7049 ((and (eq last-command this-command)
7050 (eq org-cycle-global-status 'overview))
7051 ;; We just created the overview - now do table of contents
7052 ;; This can be slow in very large buffers, so indicate action
7053 (run-hook-with-args 'org-pre-cycle-hook 'contents)
7054 (unless ga (org-unlogged-message "CONTENTS..."))
7055 (org-content)
7056 (unless ga (org-unlogged-message "CONTENTS...done"))
7057 (setq org-cycle-global-status 'contents)
7058 (run-hook-with-args 'org-cycle-hook 'contents))
7060 ((and (eq last-command this-command)
7061 (eq org-cycle-global-status 'contents))
7062 ;; We just showed the table of contents - now show everything
7063 (run-hook-with-args 'org-pre-cycle-hook 'all)
7064 (outline-show-all)
7065 (unless ga (org-unlogged-message "SHOW ALL"))
7066 (setq org-cycle-global-status 'all)
7067 (run-hook-with-args 'org-cycle-hook 'all))
7070 ;; Default action: go to overview
7071 (run-hook-with-args 'org-pre-cycle-hook 'overview)
7072 (org-overview)
7073 (unless ga (org-unlogged-message "OVERVIEW"))
7074 (setq org-cycle-global-status 'overview)
7075 (run-hook-with-args 'org-cycle-hook 'overview)))))
7077 (defvar org-called-with-limited-levels nil
7078 "Non-nil when `org-with-limited-levels' is currently active.")
7080 (defun org-cycle-internal-local ()
7081 "Do the local cycling action."
7082 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
7083 ;; First, determine end of headline (EOH), end of subtree or item
7084 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
7085 (save-excursion
7086 (if (org-at-item-p)
7087 (progn
7088 (beginning-of-line)
7089 (setq struct (org-list-struct))
7090 (setq eoh (point-at-eol))
7091 (setq eos (org-list-get-item-end-before-blank (point) struct))
7092 (setq has-children (org-list-has-child-p (point) struct)))
7093 (org-back-to-heading)
7094 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7095 (setq eos (save-excursion (org-end-of-subtree t t)
7096 (when (bolp) (backward-char)) (point)))
7097 (setq has-children
7098 (or (save-excursion
7099 (let ((level (funcall outline-level)))
7100 (outline-next-heading)
7101 (and (org-at-heading-p t)
7102 (> (funcall outline-level) level))))
7103 (save-excursion
7104 (org-list-search-forward (org-item-beginning-re) eos t)))))
7105 ;; Determine end invisible part of buffer (EOL)
7106 (beginning-of-line 2)
7107 (while (and (not (eobp)) ;This is like `next-line'.
7108 (get-char-property (1- (point)) 'invisible))
7109 (goto-char (next-single-char-property-change (point) 'invisible))
7110 (and (eolp) (beginning-of-line 2)))
7111 (setq eol (point)))
7112 ;; Find out what to do next and set `this-command'
7113 (cond
7114 ((= eos eoh)
7115 ;; Nothing is hidden behind this heading
7116 (unless (org-before-first-heading-p)
7117 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7118 (org-unlogged-message "EMPTY ENTRY")
7119 (setq org-cycle-subtree-status nil)
7120 (save-excursion
7121 (goto-char eos)
7122 (outline-next-heading)
7123 (when (outline-invisible-p) (org-flag-heading nil))))
7124 ((and (or (>= eol eos)
7125 (not (string-match "\\S-" (buffer-substring eol eos))))
7126 (or has-children
7127 (not (setq children-skipped
7128 org-cycle-skip-children-state-if-no-children))))
7129 ;; Entire subtree is hidden in one line: children view
7130 (unless (org-before-first-heading-p)
7131 (run-hook-with-args 'org-pre-cycle-hook 'children))
7132 (if (org-at-item-p)
7133 (org-list-set-item-visibility (point-at-bol) struct 'children)
7134 (org-show-entry)
7135 (org-with-limited-levels (org-show-children))
7136 ;; FIXME: This slows down the func way too much.
7137 ;; How keep drawers hidden in subtree anyway?
7138 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
7139 ;; (org-cycle-hide-drawers 'subtree))
7141 ;; Fold every list in subtree to top-level items.
7142 (when (eq org-cycle-include-plain-lists 'integrate)
7143 (save-excursion
7144 (org-back-to-heading)
7145 (while (org-list-search-forward (org-item-beginning-re) eos t)
7146 (beginning-of-line 1)
7147 (let* ((struct (org-list-struct))
7148 (prevs (org-list-prevs-alist struct))
7149 (end (org-list-get-bottom-point struct)))
7150 (dolist (e (org-list-get-all-items (point) struct prevs))
7151 (org-list-set-item-visibility e struct 'folded))
7152 (goto-char (if (< end eos) end eos)))))))
7153 (org-unlogged-message "CHILDREN")
7154 (save-excursion
7155 (goto-char eos)
7156 (outline-next-heading)
7157 (when (outline-invisible-p) (org-flag-heading nil)))
7158 (setq org-cycle-subtree-status 'children)
7159 (unless (org-before-first-heading-p)
7160 (run-hook-with-args 'org-cycle-hook 'children)))
7161 ((or children-skipped
7162 (and (eq last-command this-command)
7163 (eq org-cycle-subtree-status 'children)))
7164 ;; We just showed the children, or no children are there,
7165 ;; now show everything.
7166 (unless (org-before-first-heading-p)
7167 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7168 (outline-flag-region eoh eos nil)
7169 (org-unlogged-message
7170 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7171 (setq org-cycle-subtree-status 'subtree)
7172 (unless (org-before-first-heading-p)
7173 (run-hook-with-args 'org-cycle-hook 'subtree)))
7175 ;; Default action: hide the subtree.
7176 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7177 (outline-flag-region eoh eos t)
7178 (org-unlogged-message "FOLDED")
7179 (setq org-cycle-subtree-status 'folded)
7180 (unless (org-before-first-heading-p)
7181 (run-hook-with-args 'org-cycle-hook 'folded))))))
7183 ;;;###autoload
7184 (defun org-global-cycle (&optional arg)
7185 "Cycle the global visibility. For details see `org-cycle'.
7186 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7187 With a numeric prefix, show all headlines up to that level."
7188 (interactive "P")
7189 (let ((org-cycle-include-plain-lists
7190 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7191 (cond
7192 ((integerp arg)
7193 (outline-show-all)
7194 (outline-hide-sublevels arg)
7195 (setq org-cycle-global-status 'contents))
7196 ((equal arg '(4))
7197 (org-set-startup-visibility)
7198 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7200 (org-cycle '(4))))))
7202 (defun org-set-startup-visibility ()
7203 "Set the visibility required by startup options and properties."
7204 (cond
7205 ((eq org-startup-folded t)
7206 (org-overview))
7207 ((eq org-startup-folded 'content)
7208 (org-content))
7209 ((or (eq org-startup-folded 'showeverything)
7210 (eq org-startup-folded nil))
7211 (outline-show-all)))
7212 (unless (eq org-startup-folded 'showeverything)
7213 (when org-hide-block-startup (org-hide-block-all))
7214 (org-set-visibility-according-to-property 'no-cleanup)
7215 (org-cycle-hide-archived-subtrees 'all)
7216 (org-cycle-hide-drawers 'all)
7217 (org-cycle-show-empty-lines t)))
7219 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7220 "Switch subtree visibilities according to :VISIBILITY: property."
7221 (interactive)
7222 (org-with-wide-buffer
7223 (goto-char (point-min))
7224 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7225 (if (not (org-at-property-p)) (outline-next-heading)
7226 (let ((state (match-string 3)))
7227 (save-excursion
7228 (org-back-to-heading t)
7229 (outline-hide-subtree)
7230 (org-reveal)
7231 (cond
7232 ((equal state "folded")
7233 (outline-hide-subtree))
7234 ((equal state "children")
7235 (org-show-hidden-entry)
7236 (org-show-children))
7237 ((equal state "content")
7238 (save-excursion
7239 (save-restriction
7240 (org-narrow-to-subtree)
7241 (org-content))))
7242 ((member state '("all" "showall"))
7243 (outline-show-subtree)))))))
7244 (unless no-cleanup
7245 (org-cycle-hide-archived-subtrees 'all)
7246 (org-cycle-hide-drawers 'all)
7247 (org-cycle-show-empty-lines 'all))))
7249 ;; This function uses outline-regexp instead of the more fundamental
7250 ;; org-outline-regexp so that org-cycle-global works outside of Org
7251 ;; buffers, where outline-regexp is needed.
7252 (defun org-overview ()
7253 "Switch to overview mode, showing only top-level headlines.
7254 This shows all headlines with a level equal or greater than the level
7255 of the first headline in the buffer. This is important, because if the
7256 first headline is not level one, then (hide-sublevels 1) gives confusing
7257 results."
7258 (interactive)
7259 (save-excursion
7260 (let ((level
7261 (save-excursion
7262 (goto-char (point-min))
7263 (when (re-search-forward (concat "^" outline-regexp) nil t)
7264 (goto-char (match-beginning 0))
7265 (funcall outline-level)))))
7266 (and level (outline-hide-sublevels level)))))
7268 (defun org-content (&optional arg)
7269 "Show all headlines in the buffer, like a table of contents.
7270 With numerical argument N, show content up to level N."
7271 (interactive "P")
7272 (org-overview)
7273 (save-excursion
7274 ;; Visit all headings and show their offspring
7275 (and (integerp arg) (org-overview))
7276 (goto-char (point-max))
7277 (catch 'exit
7278 (while (and (progn (condition-case nil
7279 (outline-previous-visible-heading 1)
7280 (error (goto-char (point-min))))
7282 (looking-at org-outline-regexp))
7283 (if (integerp arg)
7284 (org-show-children (1- arg))
7285 (outline-show-branches))
7286 (when (bobp) (throw 'exit nil))))))
7288 (defun org-optimize-window-after-visibility-change (state)
7289 "Adjust the window after a change in outline visibility.
7290 This function is the default value of the hook `org-cycle-hook'."
7291 (when (get-buffer-window (current-buffer))
7292 (cond
7293 ((eq state 'content) nil)
7294 ((eq state 'all) nil)
7295 ((eq state 'folded) nil)
7296 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7297 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7299 (defun org-remove-empty-overlays-at (pos)
7300 "Remove outline overlays that do not contain non-white stuff."
7301 (dolist (o (overlays-at pos))
7302 (and (eq 'outline (overlay-get o 'invisible))
7303 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7304 (overlay-end o))))
7305 (delete-overlay o))))
7307 (defun org-clean-visibility-after-subtree-move ()
7308 "Fix visibility issues after moving a subtree."
7309 ;; First, find a reasonable region to look at:
7310 ;; Start two siblings above, end three below
7311 (let* ((beg (save-excursion
7312 (and (org-get-last-sibling)
7313 (org-get-last-sibling))
7314 (point)))
7315 (end (save-excursion
7316 (and (org-get-next-sibling)
7317 (org-get-next-sibling)
7318 (org-get-next-sibling))
7319 (if (org-at-heading-p)
7320 (point-at-eol)
7321 (point))))
7322 (level (looking-at "\\*+"))
7323 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7324 (save-excursion
7325 (save-restriction
7326 (narrow-to-region beg end)
7327 (when re
7328 ;; Properly fold already folded siblings
7329 (goto-char (point-min))
7330 (while (re-search-forward re nil t)
7331 (when (and (not (outline-invisible-p))
7332 (save-excursion
7333 (goto-char (point-at-eol)) (outline-invisible-p)))
7334 (outline-hide-entry))))
7335 (org-cycle-show-empty-lines 'overview)
7336 (org-cycle-hide-drawers 'overview)))))
7338 (defun org-cycle-show-empty-lines (state)
7339 "Show empty lines above all visible headlines.
7340 The region to be covered depends on STATE when called through
7341 `org-cycle-hook'. Lisp program can use t for STATE to get the
7342 entire buffer covered. Note that an empty line is only shown if there
7343 are at least `org-cycle-separator-lines' empty lines before the headline."
7344 (when (/= org-cycle-separator-lines 0)
7345 (save-excursion
7346 (let* ((n (abs org-cycle-separator-lines))
7347 (re (cond
7348 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7349 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7350 (t (let ((ns (number-to-string (- n 2))))
7351 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7352 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7353 beg end)
7354 (cond
7355 ((memq state '(overview contents t))
7356 (setq beg (point-min) end (point-max)))
7357 ((memq state '(children folded))
7358 (setq beg (point)
7359 end (progn (org-end-of-subtree t t)
7360 (line-beginning-position 2)))))
7361 (when beg
7362 (goto-char beg)
7363 (while (re-search-forward re end t)
7364 (unless (get-char-property (match-end 1) 'invisible)
7365 (let ((e (match-end 1))
7366 (b (if (>= org-cycle-separator-lines 0)
7367 (match-beginning 1)
7368 (save-excursion
7369 (goto-char (match-beginning 0))
7370 (skip-chars-backward " \t\n")
7371 (line-end-position)))))
7372 (outline-flag-region b e nil))))))))
7373 ;; Never hide empty lines at the end of the file.
7374 (save-excursion
7375 (goto-char (point-max))
7376 (outline-previous-heading)
7377 (outline-end-of-heading)
7378 (when (and (looking-at "[ \t\n]+")
7379 (= (match-end 0) (point-max)))
7380 (outline-flag-region (point) (match-end 0) nil))))
7382 (defun org-show-empty-lines-in-parent ()
7383 "Move to the parent and re-show empty lines before visible headlines."
7384 (save-excursion
7385 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7386 (org-cycle-show-empty-lines context))))
7388 (defun org-files-list ()
7389 "Return `org-agenda-files' list, plus all open Org files.
7390 This is useful for operations that need to scan all of a user's
7391 open and agenda-wise Org files."
7392 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7393 (dolist (buf (buffer-list))
7394 (with-current-buffer buf
7395 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7396 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7397 files))
7399 (defsubst org-entry-beginning-position ()
7400 "Return the beginning position of the current entry."
7401 (save-excursion (org-back-to-heading t) (point)))
7403 (defsubst org-entry-end-position ()
7404 "Return the end position of the current entry."
7405 (save-excursion (outline-next-heading) (point)))
7407 (defun org-cycle-hide-drawers (state &optional exceptions)
7408 "Re-hide all drawers after a visibility state change.
7409 When non-nil, optional argument EXCEPTIONS is a list of strings
7410 specifying which drawers should not be hidden."
7411 (when (and (derived-mode-p 'org-mode)
7412 (not (memq state '(overview folded contents))))
7413 (save-excursion
7414 (let* ((globalp (memq state '(contents all)))
7415 (beg (if globalp (point-min) (point)))
7416 (end (if globalp (point-max)
7417 (if (eq state 'children)
7418 (save-excursion (outline-next-heading) (point))
7419 (org-end-of-subtree t)))))
7420 (goto-char beg)
7421 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7422 (unless (member-ignore-case (match-string 1) exceptions)
7423 (let ((drawer (org-element-at-point)))
7424 (when (memq (org-element-type drawer) '(drawer property-drawer))
7425 (org-flag-drawer t drawer)
7426 ;; Make sure to skip drawer entirely or we might flag
7427 ;; it another time when matching its ending line with
7428 ;; `org-drawer-regexp'.
7429 (goto-char (org-element-property :end drawer))))))))))
7431 (defun org-flag-drawer (flag &optional element)
7432 "When FLAG is non-nil, hide the drawer we are at.
7433 Otherwise make it visible. When optional argument ELEMENT is
7434 a parsed drawer, as returned by `org-element-at-point', hide or
7435 show that drawer instead."
7436 (let ((drawer (or element
7437 (and (save-excursion
7438 (beginning-of-line)
7439 (looking-at-p org-drawer-regexp))
7440 (org-element-at-point)))))
7441 (when (memq (org-element-type drawer) '(drawer property-drawer))
7442 (let ((post (org-element-property :post-affiliated drawer)))
7443 (save-excursion
7444 (outline-flag-region
7445 (progn (goto-char post) (line-end-position))
7446 (progn (goto-char (org-element-property :end drawer))
7447 (skip-chars-backward " \r\t\n")
7448 (line-end-position))
7449 flag))
7450 ;; When the drawer is hidden away, make sure point lies in
7451 ;; a visible part of the buffer.
7452 (when (and flag (> (line-beginning-position) post))
7453 (goto-char post))))))
7455 (defun org-subtree-end-visible-p ()
7456 "Is the end of the current subtree visible?"
7457 (pos-visible-in-window-p
7458 (save-excursion (org-end-of-subtree t) (point))))
7460 (defun org-first-headline-recenter ()
7461 "Move cursor to the first headline and recenter the headline."
7462 (let ((window (get-buffer-window)))
7463 (when window
7464 (goto-char (point-min))
7465 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7466 (set-window-start window (line-beginning-position))))))
7468 ;;; Saving and restoring visibility
7470 (defun org-outline-overlay-data (&optional use-markers)
7471 "Return a list of the locations of all outline overlays.
7472 These are overlays with the `invisible' property value `outline'.
7473 The return value is a list of cons cells, with start and stop
7474 positions for each overlay.
7475 If USE-MARKERS is set, return the positions as markers."
7476 (let (beg end)
7477 (org-with-wide-buffer
7478 (delq nil
7479 (mapcar (lambda (o)
7480 (when (eq (overlay-get o 'invisible) 'outline)
7481 (setq beg (overlay-start o)
7482 end (overlay-end o))
7483 (and beg end (> end beg)
7484 (if use-markers
7485 (cons (copy-marker beg)
7486 (copy-marker end t))
7487 (cons beg end)))))
7488 (overlays-in (point-min) (point-max)))))))
7490 (defun org-set-outline-overlay-data (data)
7491 "Create visibility overlays for all positions in DATA.
7492 DATA should have been made by `org-outline-overlay-data'."
7493 (org-with-wide-buffer
7494 (outline-show-all)
7495 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7497 ;;; Folding of blocks
7499 (defvar-local org-hide-block-overlays nil
7500 "Overlays hiding blocks.")
7502 (defun org-block-map (function &optional start end)
7503 "Call FUNCTION at the head of all source blocks in the current buffer.
7504 Optional arguments START and END can be used to limit the range."
7505 (let ((start (or start (point-min)))
7506 (end (or end (point-max))))
7507 (save-excursion
7508 (goto-char start)
7509 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7510 (save-excursion
7511 (save-match-data
7512 (goto-char (match-beginning 0))
7513 (funcall function)))))))
7515 (defun org-hide-block-toggle-all ()
7516 "Toggle the visibility of all blocks in the current buffer."
7517 (org-block-map 'org-hide-block-toggle))
7519 (defun org-hide-block-all ()
7520 "Fold all blocks in the current buffer."
7521 (interactive)
7522 (org-show-block-all)
7523 (org-block-map 'org-hide-block-toggle-maybe))
7525 (defun org-show-block-all ()
7526 "Unfold all blocks in the current buffer."
7527 (interactive)
7528 (mapc #'delete-overlay org-hide-block-overlays)
7529 (setq org-hide-block-overlays nil))
7531 (defun org-hide-block-toggle-maybe ()
7532 "Toggle visibility of block at point.
7533 Unlike to `org-hide-block-toggle', this function does not throw
7534 an error. Return a non-nil value when toggling is successful."
7535 (interactive)
7536 (ignore-errors (org-hide-block-toggle)))
7538 (defun org-hide-block-toggle (&optional force)
7539 "Toggle the visibility of the current block.
7540 When optional argument FORCE is `off', make block visible. If it
7541 is non-nil, hide it unconditionally. Throw an error when not at
7542 a block. Return a non-nil value when toggling is successful."
7543 (interactive)
7544 (let ((element (org-element-at-point)))
7545 (unless (memq (org-element-type element)
7546 '(center-block comment-block dynamic-block example-block
7547 export-block quote-block special-block
7548 src-block verse-block))
7549 (user-error "Not at a block"))
7550 (let* ((start (save-excursion
7551 (goto-char (org-element-property :post-affiliated element))
7552 (line-end-position)))
7553 (end (save-excursion
7554 (goto-char (org-element-property :end element))
7555 (skip-chars-backward " \r\t\n")
7556 (line-end-position)))
7557 (overlays (overlays-at start)))
7558 (cond
7559 ;; Do nothing when not before or at the block opening line or
7560 ;; at the block closing line.
7561 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7562 ((and (not (eq force 'off))
7563 (not (memq t (mapcar
7564 (lambda (o)
7565 (eq (overlay-get o 'invisible) 'org-hide-block))
7566 overlays))))
7567 (let ((ov (make-overlay start end)))
7568 (overlay-put ov 'invisible 'org-hide-block)
7569 ;; Make the block accessible to `isearch'.
7570 (overlay-put
7571 ov 'isearch-open-invisible
7572 (lambda (ov)
7573 (when (memq ov org-hide-block-overlays)
7574 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7575 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7576 (delete-overlay ov))))
7577 (push ov org-hide-block-overlays)
7578 ;; When the block is hidden away, make sure point is left in
7579 ;; a visible part of the buffer.
7580 (when (> (line-beginning-position) start)
7581 (goto-char start)
7582 (beginning-of-line))
7583 ;; Signal successful toggling.
7585 ((or (not force) (eq force 'off))
7586 (dolist (ov overlays t)
7587 (when (memq ov org-hide-block-overlays)
7588 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7589 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7590 (delete-overlay ov))))))))
7592 ;; Remove overlays when changing major mode
7593 (add-hook 'org-mode-hook
7594 (lambda () (add-hook 'change-major-mode-hook
7595 'org-show-block-all 'append 'local)))
7597 ;;; Org-goto
7599 (defvar org-goto-window-configuration nil)
7600 (defvar org-goto-marker nil)
7601 (defvar org-goto-map)
7602 (defun org-goto-map ()
7603 "Set the keymap `org-goto'."
7604 (setq org-goto-map
7605 (let ((map (make-sparse-keymap)))
7606 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7607 mouse-drag-region universal-argument org-occur)))
7608 (dolist (cmd cmds)
7609 (substitute-key-definition cmd cmd map global-map)))
7610 (suppress-keymap map)
7611 (org-defkey map "\C-m" 'org-goto-ret)
7612 (org-defkey map [(return)] 'org-goto-ret)
7613 (org-defkey map [(left)] 'org-goto-left)
7614 (org-defkey map [(right)] 'org-goto-right)
7615 (org-defkey map [(control ?g)] 'org-goto-quit)
7616 (org-defkey map "\C-i" 'org-cycle)
7617 (org-defkey map [(tab)] 'org-cycle)
7618 (org-defkey map [(down)] 'outline-next-visible-heading)
7619 (org-defkey map [(up)] 'outline-previous-visible-heading)
7620 (if org-goto-auto-isearch
7621 (if (fboundp 'define-key-after)
7622 (define-key-after map [t] 'org-goto-local-auto-isearch)
7623 nil)
7624 (org-defkey map "q" 'org-goto-quit)
7625 (org-defkey map "n" 'outline-next-visible-heading)
7626 (org-defkey map "p" 'outline-previous-visible-heading)
7627 (org-defkey map "f" 'outline-forward-same-level)
7628 (org-defkey map "b" 'outline-backward-same-level)
7629 (org-defkey map "u" 'outline-up-heading))
7630 (org-defkey map "/" 'org-occur)
7631 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7632 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7633 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7634 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7635 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7636 map)))
7638 (defconst org-goto-help
7639 "Browse buffer copy, to find location or copy text.%s
7640 RET=jump to location C-g=quit and return to previous location
7641 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7643 (defvar org-goto-start-pos) ; dynamically scoped parameter
7645 (defun org-goto (&optional alternative-interface)
7646 "Look up a different location in the current file, keeping current visibility.
7648 When you want look-up or go to a different location in a
7649 document, the fastest way is often to fold the entire buffer and
7650 then dive into the tree. This method has the disadvantage, that
7651 the previous location will be folded, which may not be what you
7652 want.
7654 This command works around this by showing a copy of the current
7655 buffer in an indirect buffer, in overview mode. You can dive
7656 into the tree in that copy, use org-occur and incremental search
7657 to find a location. When pressing RET or `Q', the command
7658 returns to the original buffer in which the visibility is still
7659 unchanged. After RET it will also jump to the location selected
7660 in the indirect buffer and expose the headline hierarchy above.
7662 With a prefix argument, use the alternative interface: e.g., if
7663 `org-goto-interface' is `outline' use `outline-path-completion'."
7664 (interactive "P")
7665 (org-goto-map)
7666 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7667 (org-refile-use-outline-path t)
7668 (org-refile-target-verify-function nil)
7669 (interface
7670 (if (not alternative-interface)
7671 org-goto-interface
7672 (if (eq org-goto-interface 'outline)
7673 'outline-path-completion
7674 'outline)))
7675 (org-goto-start-pos (point))
7676 (selected-point
7677 (if (eq interface 'outline)
7678 (car (org-get-location (current-buffer) org-goto-help))
7679 (let ((pa (org-refile-get-location "Goto")))
7680 (org-refile-check-position pa)
7681 (nth 3 pa)))))
7682 (if selected-point
7683 (progn
7684 (org-mark-ring-push org-goto-start-pos)
7685 (goto-char selected-point)
7686 (when (or (outline-invisible-p) (org-invisible-p2))
7687 (org-show-context 'org-goto)))
7688 (message "Quit"))))
7690 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7691 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7692 (defvar org-goto-local-auto-isearch-map) ; defined below
7694 (defun org-get-location (_buf help)
7695 "Let the user select a location in current buffer.
7696 This function uses a recursive edit. It returns the selected position
7697 or nil."
7698 (org-no-popups
7699 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7700 (isearch-hide-immediately nil)
7701 (isearch-search-fun-function
7702 (lambda () 'org-goto-local-search-headings))
7703 (org-goto-selected-point org-goto-exit-command))
7704 (save-excursion
7705 (save-window-excursion
7706 (delete-other-windows)
7707 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7708 (pop-to-buffer-same-window
7709 (condition-case nil
7710 (make-indirect-buffer (current-buffer) "*org-goto*")
7711 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7712 (with-output-to-temp-buffer "*Org Help*"
7713 (princ (format help (if org-goto-auto-isearch
7714 " Just type for auto-isearch."
7715 " n/p/f/b/u to navigate, q to quit."))))
7716 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7717 (setq buffer-read-only nil)
7718 (let ((org-startup-truncated t)
7719 (org-startup-folded nil)
7720 (org-startup-align-all-tables nil))
7721 (org-mode)
7722 (org-overview))
7723 (setq buffer-read-only t)
7724 (if (and (boundp 'org-goto-start-pos)
7725 (integer-or-marker-p org-goto-start-pos))
7726 (progn (goto-char org-goto-start-pos)
7727 (when (outline-invisible-p)
7728 (org-show-set-visibility 'lineage)))
7729 (goto-char (point-min)))
7730 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7731 (message "Select location and press RET")
7732 (use-local-map org-goto-map)
7733 (recursive-edit)))
7734 (kill-buffer "*org-goto*")
7735 (cons org-goto-selected-point org-goto-exit-command))))
7737 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7738 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7739 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7740 (if (fboundp 'isearch-other-control-char)
7741 (progn
7742 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7743 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7744 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7745 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7746 (define-key org-goto-local-auto-isearch-map [return] nil))
7748 (defun org-goto-local-search-headings (string bound noerror)
7749 "Search and make sure that any matches are in headlines."
7750 (catch 'return
7751 (while (if isearch-forward
7752 (search-forward string bound noerror)
7753 (search-backward string bound noerror))
7754 (when (save-match-data
7755 (and (save-excursion
7756 (beginning-of-line)
7757 (looking-at org-complex-heading-regexp))
7758 (or (not (match-beginning 5))
7759 (< (point) (match-beginning 5)))))
7760 (throw 'return (point))))))
7762 (defun org-goto-local-auto-isearch ()
7763 "Start isearch."
7764 (interactive)
7765 (goto-char (point-min))
7766 (let ((keys (this-command-keys)))
7767 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7768 (isearch-mode t)
7769 (isearch-process-search-char (string-to-char keys)))))
7771 (defun org-goto-ret (&optional _arg)
7772 "Finish `org-goto' by going to the new location."
7773 (interactive "P")
7774 (setq org-goto-selected-point (point))
7775 (setq org-goto-exit-command 'return)
7776 (throw 'exit nil))
7778 (defun org-goto-left ()
7779 "Finish `org-goto' by going to the new location."
7780 (interactive)
7781 (if (org-at-heading-p)
7782 (progn
7783 (beginning-of-line 1)
7784 (setq org-goto-selected-point (point)
7785 org-goto-exit-command 'left)
7786 (throw 'exit nil))
7787 (user-error "Not on a heading")))
7789 (defun org-goto-right ()
7790 "Finish `org-goto' by going to the new location."
7791 (interactive)
7792 (if (org-at-heading-p)
7793 (progn
7794 (setq org-goto-selected-point (point)
7795 org-goto-exit-command 'right)
7796 (throw 'exit nil))
7797 (user-error "Not on a heading")))
7799 (defun org-goto-quit ()
7800 "Finish `org-goto' without cursor motion."
7801 (interactive)
7802 (setq org-goto-selected-point nil)
7803 (setq org-goto-exit-command 'quit)
7804 (throw 'exit nil))
7806 ;;; Indirect buffer display of subtrees
7808 (defvar org-indirect-dedicated-frame nil
7809 "This is the frame being used for indirect tree display.")
7810 (defvar org-last-indirect-buffer nil)
7812 (defun org-tree-to-indirect-buffer (&optional arg)
7813 "Create indirect buffer and narrow it to current subtree.
7815 With a numerical prefix ARG, go up to this level and then take that tree.
7816 If ARG is negative, go up that many levels.
7818 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7819 indirect buffer previously made with this command, to avoid proliferation of
7820 indirect buffers. However, when you call the command with a \
7821 `\\[universal-argument]' prefix, or
7822 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7823 so that you can work with several indirect buffers at the same time. If
7824 `org-indirect-buffer-display' is `dedicated-frame', the \
7825 `\\[universal-argument]' prefix also
7826 requests that a new frame be made for the new buffer, so that the dedicated
7827 frame is not changed."
7828 (interactive "P")
7829 (let ((cbuf (current-buffer))
7830 (cwin (selected-window))
7831 (pos (point))
7832 beg end level heading ibuf)
7833 (save-excursion
7834 (org-back-to-heading t)
7835 (when (numberp arg)
7836 (setq level (org-outline-level))
7837 (when (< arg 0) (setq arg (+ level arg)))
7838 (while (> (setq level (org-outline-level)) arg)
7839 (org-up-heading-safe)))
7840 (setq beg (point)
7841 heading (org-get-heading 'no-tags))
7842 (org-end-of-subtree t t)
7843 (when (org-at-heading-p) (backward-char 1))
7844 (setq end (point)))
7845 (when (and (buffer-live-p org-last-indirect-buffer)
7846 (not (eq org-indirect-buffer-display 'new-frame))
7847 (not arg))
7848 (kill-buffer org-last-indirect-buffer))
7849 (setq ibuf (org-get-indirect-buffer cbuf heading)
7850 org-last-indirect-buffer ibuf)
7851 (cond
7852 ((or (eq org-indirect-buffer-display 'new-frame)
7853 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7854 (select-frame (make-frame))
7855 (delete-other-windows)
7856 (pop-to-buffer-same-window ibuf)
7857 (org-set-frame-title heading))
7858 ((eq org-indirect-buffer-display 'dedicated-frame)
7859 (raise-frame
7860 (select-frame (or (and org-indirect-dedicated-frame
7861 (frame-live-p org-indirect-dedicated-frame)
7862 org-indirect-dedicated-frame)
7863 (setq org-indirect-dedicated-frame (make-frame)))))
7864 (delete-other-windows)
7865 (pop-to-buffer-same-window ibuf)
7866 (org-set-frame-title (concat "Indirect: " heading)))
7867 ((eq org-indirect-buffer-display 'current-window)
7868 (pop-to-buffer-same-window ibuf))
7869 ((eq org-indirect-buffer-display 'other-window)
7870 (pop-to-buffer ibuf))
7871 (t (error "Invalid value")))
7872 (narrow-to-region beg end)
7873 (outline-show-all)
7874 (goto-char pos)
7875 (run-hook-with-args 'org-cycle-hook 'all)
7876 (and (window-live-p cwin) (select-window cwin))))
7878 (defun org-get-indirect-buffer (&optional buffer heading)
7879 (setq buffer (or buffer (current-buffer)))
7880 (let ((n 1) (base (buffer-name buffer)) bname)
7881 (while (buffer-live-p
7882 (get-buffer
7883 (setq bname
7884 (concat base "-"
7885 (if heading (concat heading "-" (number-to-string n))
7886 (number-to-string n))))))
7887 (setq n (1+ n)))
7888 (condition-case nil
7889 (make-indirect-buffer buffer bname 'clone)
7890 (error (make-indirect-buffer buffer bname)))))
7892 (defun org-set-frame-title (title)
7893 "Set the title of the current frame to the string TITLE."
7894 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7896 ;;;; Structure editing
7898 ;;; Inserting headlines
7900 (defun org--line-empty-p (n)
7901 "Is the Nth next line empty?
7903 Counts the current line as N = 1 and the previous line as N = 0;
7904 see `beginning-of-line'."
7905 (save-excursion
7906 (and (not (bobp))
7907 (or (beginning-of-line n) t)
7908 (save-match-data
7909 (looking-at "[ \t]*$")))))
7911 (defun org-previous-line-empty-p ()
7912 "Is the previous line a blank line?
7913 When NEXT is non-nil, check the next line instead."
7914 (org--line-empty-p 0))
7916 (defun org-next-line-empty-p ()
7917 "Is the previous line a blank line?
7918 When NEXT is non-nil, check the next line instead."
7919 (org--line-empty-p 2))
7921 (defun org-insert-heading (&optional arg invisible-ok top)
7922 "Insert a new heading or an item with the same depth at point.
7924 If point is at the beginning of a heading or a list item, insert
7925 a new heading or a new item above the current one. When at the
7926 beginning of a regular line of text, turn it into a heading.
7928 If point is in the middle of a line, split it and create a new
7929 headline/item with the text in the current line after point (see
7930 `org-M-RET-may-split-line' on how to modify this behavior). As
7931 a special case, on a headline, splitting can only happen on the
7932 title itself. E.g., this excludes breaking stars or tags.
7934 With a `\\[universal-argument]' prefix, set \
7935 `org-insert-heading-respect-content' to
7936 a non-nil value for the duration of the command. This forces the
7937 insertion of a heading after the current subtree, independently
7938 on the location of point.
7940 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7941 insert the heading at the end of the tree
7942 above the current heading. For example, if point is within a
7943 2nd-level heading, then it will insert a 2nd-level heading at
7944 the end of the 1st-level parent subtree.
7946 When INVISIBLE-OK is set, stop at invisible headlines when going
7947 back. This is important for non-interactive uses of the
7948 command.
7950 When optional argument TOP is non-nil, insert a level 1 heading,
7951 unconditionally."
7952 (interactive "P")
7953 (let ((itemp (and (not top) (org-in-item-p)))
7954 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7955 (respect-content (or org-insert-heading-respect-content
7956 (equal arg '(4))))
7957 (initial-content ""))
7959 (cond
7961 ((or (= (buffer-size) 0)
7962 (and (not (save-excursion
7963 (and (ignore-errors (org-back-to-heading invisible-ok))
7964 (org-at-heading-p))))
7965 (or arg (not itemp))))
7966 ;; At beginning of buffer or so high up that only a heading
7967 ;; makes sense.
7968 (cond ((and (bolp) (not respect-content)) (insert "* "))
7969 ((not respect-content)
7970 (unless may-split (end-of-line))
7971 (insert "\n* "))
7972 ((re-search-forward org-outline-regexp-bol nil t)
7973 (beginning-of-line)
7974 (insert "* \n")
7975 (backward-char))
7976 (t (goto-char (point-max))
7977 (insert "\n* ")))
7978 (run-hooks 'org-insert-heading-hook))
7980 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7983 ;; Maybe move at the end of the subtree
7984 (when (equal arg '(16))
7985 (org-up-heading-safe)
7986 (org-end-of-subtree t))
7987 ;; Insert a heading
7988 (save-restriction
7989 (widen)
7990 (let* ((level nil)
7991 (on-heading (org-at-heading-p))
7992 (empty-line-p (if on-heading
7993 (org-previous-line-empty-p)
7994 ;; We will decide later
7995 nil))
7996 ;; Get a level string to fall back on.
7997 (fix-level
7998 (if (org-before-first-heading-p) "*"
7999 (save-excursion
8000 (org-back-to-heading t)
8001 (when (org-previous-line-empty-p) (setq empty-line-p t))
8002 (looking-at org-outline-regexp)
8003 (make-string (1- (length (match-string 0))) ?*))))
8004 (stars
8005 (save-excursion
8006 (condition-case nil
8007 (if top "* "
8008 (org-back-to-heading invisible-ok)
8009 (when (and (not on-heading)
8010 (featurep 'org-inlinetask)
8011 (integerp org-inlinetask-min-level)
8012 (>= (length (match-string 0))
8013 org-inlinetask-min-level))
8014 ;; Find a heading level before the inline
8015 ;; task.
8016 (while (and (setq level (org-up-heading-safe))
8017 (>= level org-inlinetask-min-level)))
8018 (if (org-at-heading-p)
8019 (org-back-to-heading invisible-ok)
8020 (error "This should not happen")))
8021 (unless (and (save-excursion
8022 (save-match-data
8023 (org-backward-heading-same-level
8024 1 invisible-ok))
8025 (= (point) (match-beginning 0)))
8026 (not (org-next-line-empty-p)))
8027 (setq empty-line-p (or empty-line-p
8028 (org-previous-line-empty-p))))
8029 (match-string 0))
8030 (error (or fix-level "* ")))))
8031 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
8032 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
8034 ;; If we insert after content, move there and clean up
8035 ;; whitespace.
8036 (when respect-content
8037 (if (not (org-before-first-heading-p))
8038 (org-end-of-subtree nil t)
8039 (re-search-forward org-outline-regexp-bol)
8040 (beginning-of-line 0))
8041 (skip-chars-backward " \r\t\n")
8042 (and (not (looking-back "^\\*+" (line-beginning-position)))
8043 (looking-at "[ \t]+") (replace-match ""))
8044 (unless (eobp) (forward-char 1))
8045 (when (looking-at "^\\*")
8046 (unless (bobp) (backward-char 1))
8047 (insert "\n")))
8049 ;; If we are splitting, grab the text that should be moved
8050 ;; to the new headline.
8051 (when may-split
8052 (if (org-at-heading-p)
8053 ;; This is a heading: split intelligently (keeping
8054 ;; tags).
8055 (let ((pos (point)))
8056 (beginning-of-line)
8057 (let ((case-fold-search nil))
8058 (unless (looking-at org-complex-heading-regexp)
8059 (error "This should not happen")))
8060 (when (and (match-beginning 4)
8061 (> pos (match-beginning 4))
8062 (< pos (match-end 4)))
8063 (setq initial-content (buffer-substring pos (match-end 4)))
8064 (goto-char pos)
8065 (delete-region (point) (match-end 4))
8066 (if (looking-at "[ \t]*$")
8067 (replace-match "")
8068 (insert (make-string (length initial-content) ?\s)))
8069 (setq initial-content (org-trim initial-content)))
8070 (goto-char pos))
8071 ;; A normal line.
8072 (setq initial-content
8073 (org-trim
8074 (delete-and-extract-region (point) (line-end-position))))))
8076 ;; If we are at the beginning of the line, insert before it.
8077 ;; Otherwise, after it.
8078 (cond
8079 ((and (bolp) (looking-at "[ \t]*$")))
8080 ((bolp) (save-excursion (insert "\n")))
8081 (t (end-of-line)
8082 (insert "\n")))
8084 ;; Insert the new heading
8085 (insert stars)
8086 (just-one-space)
8087 (insert initial-content)
8088 (unless (and blank (org-previous-line-empty-p))
8089 (org-N-empty-lines-before-current (if blank 1 0)))
8090 ;; Adjust visibility, which may be messed up if we removed
8091 ;; blank lines while previous entry was hidden.
8092 (let ((bol (line-beginning-position)))
8093 (dolist (o (overlays-at (1- bol)))
8094 (when (and (eq (overlay-get o 'invisible) 'outline)
8095 (eq (overlay-end o) bol))
8096 (move-overlay o (overlay-start o) (1- bol)))))
8097 (run-hooks 'org-insert-heading-hook)))))))
8099 (defun org-N-empty-lines-before-current (N)
8100 "Make the number of empty lines before current exactly N.
8101 So this will delete or add empty lines."
8102 (save-excursion
8103 (beginning-of-line)
8104 (let ((p (point)))
8105 (skip-chars-backward " \r\t\n")
8106 (unless (bolp) (forward-line))
8107 (delete-region (point) p))
8108 (when (> N 0) (insert (make-string N ?\n)))))
8110 (defun org-get-heading (&optional no-tags no-todo)
8111 "Return the heading of the current entry, without the stars.
8112 When NO-TAGS is non-nil, don't include tags.
8113 When NO-TODO is non-nil, don't include TODO keywords."
8114 (save-excursion
8115 (org-back-to-heading t)
8116 (let ((case-fold-search nil))
8117 (cond
8118 ((and no-tags no-todo)
8119 (looking-at org-complex-heading-regexp)
8120 ;; Return value has to be a string, but match group 4 is
8121 ;; optional.
8122 (or (match-string 4) ""))
8123 (no-tags
8124 (looking-at (concat org-outline-regexp
8125 "\\(.*?\\)"
8126 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8127 (match-string 1))
8128 (no-todo
8129 (looking-at org-todo-line-regexp)
8130 (match-string 3))
8131 (t (looking-at org-heading-regexp)
8132 (match-string 2))))))
8134 (defvar orgstruct-mode) ; defined below
8136 (defun org-heading-components ()
8137 "Return the components of the current heading.
8138 This is a list with the following elements:
8139 - the level as an integer
8140 - the reduced level, different if `org-odd-levels-only' is set.
8141 - the TODO keyword, or nil
8142 - the priority character, like ?A, or nil if no priority is given
8143 - the headline text itself, or the tags string if no headline text
8144 - the tags string, or nil."
8145 (save-excursion
8146 (org-back-to-heading t)
8147 (when (let (case-fold-search)
8148 (looking-at
8149 (if orgstruct-mode
8150 org-heading-regexp
8151 org-complex-heading-regexp)))
8152 (if orgstruct-mode
8153 (list (length (match-string 1))
8154 (org-reduced-level (length (match-string 1)))
8157 (match-string 2)
8158 nil)
8159 (list (length (match-string 1))
8160 (org-reduced-level (length (match-string 1)))
8161 (match-string-no-properties 2)
8162 (and (match-end 3) (aref (match-string 3) 2))
8163 (match-string-no-properties 4)
8164 (match-string-no-properties 5))))))
8166 (defun org-get-entry ()
8167 "Get the entry text, after heading, entire subtree."
8168 (save-excursion
8169 (org-back-to-heading t)
8170 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8172 (defun org-edit-headline (&optional heading)
8173 "Edit the current headline.
8174 Set it to HEADING when provided."
8175 (interactive)
8176 (org-with-wide-buffer
8177 (org-back-to-heading t)
8178 (let ((case-fold-search nil))
8179 (when (looking-at org-complex-heading-regexp)
8180 (let* ((old (match-string-no-properties 4))
8181 (new (save-match-data
8182 (org-trim (or heading (read-string "Edit: " old))))))
8183 (unless (equal old new)
8184 (if old (replace-match new t t nil 4)
8185 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8186 (insert " " new))
8187 (org-set-tags nil t)
8188 (when (looking-at "[ \t]*$") (replace-match ""))))))))
8190 (defun org-insert-heading-after-current ()
8191 "Insert a new heading with same level as current, after current subtree."
8192 (interactive)
8193 (org-back-to-heading)
8194 (org-insert-heading)
8195 (org-move-subtree-down)
8196 (end-of-line 1))
8198 (defun org-insert-heading-respect-content (&optional invisible-ok)
8199 "Insert heading with `org-insert-heading-respect-content' set to t."
8200 (interactive)
8201 (org-insert-heading '(4) invisible-ok))
8203 (defun org-insert-todo-heading-respect-content (&optional force-state)
8204 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8205 (interactive)
8206 (org-insert-todo-heading force-state '(4)))
8208 (defun org-insert-todo-heading (arg &optional force-heading)
8209 "Insert a new heading with the same level and TODO state as current heading.
8211 If the heading has no TODO state, or if the state is DONE, use
8212 the first state (TODO by default). Also with one prefix arg,
8213 force first state. With two prefix args, force inserting at the
8214 end of the parent subtree.
8216 When called at a plain list item, insert a new item with an
8217 unchecked check box."
8218 (interactive "P")
8219 (when (or force-heading (not (org-insert-item 'checkbox)))
8220 (org-insert-heading (or (and (equal arg '(16)) '(16))
8221 force-heading))
8222 (save-excursion
8223 (org-back-to-heading)
8224 (outline-previous-heading)
8225 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
8226 (let* ((new-mark-x
8227 (if (or (equal arg '(4))
8228 (not (match-beginning 2))
8229 (member (match-string 2) org-done-keywords))
8230 (car org-todo-keywords-1)
8231 (match-string 2)))
8232 (new-mark
8234 (run-hook-with-args-until-success
8235 'org-todo-get-default-hook new-mark-x nil)
8236 new-mark-x)))
8237 (beginning-of-line 1)
8238 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8239 (if org-treat-insert-todo-heading-as-state-change
8240 (org-todo new-mark)
8241 (insert new-mark " "))))
8242 (when org-provide-todo-statistics
8243 (org-update-parent-todo-statistics))))
8245 (defun org-insert-subheading (arg)
8246 "Insert a new subheading and demote it.
8247 Works for outline headings and for plain lists alike."
8248 (interactive "P")
8249 (org-insert-heading arg)
8250 (cond
8251 ((org-at-heading-p) (org-do-demote))
8252 ((org-at-item-p) (org-indent-item))))
8254 (defun org-insert-todo-subheading (arg)
8255 "Insert a new subheading with TODO keyword or checkbox and demote it.
8256 Works for outline headings and for plain lists alike."
8257 (interactive "P")
8258 (org-insert-todo-heading arg)
8259 (cond
8260 ((org-at-heading-p) (org-do-demote))
8261 ((org-at-item-p) (org-indent-item))))
8263 ;;; Promotion and Demotion
8265 (defvar org-after-demote-entry-hook nil
8266 "Hook run after an entry has been demoted.
8267 The cursor will be at the beginning of the entry.
8268 When a subtree is being demoted, the hook will be called for each node.")
8270 (defvar org-after-promote-entry-hook nil
8271 "Hook run after an entry has been promoted.
8272 The cursor will be at the beginning of the entry.
8273 When a subtree is being promoted, the hook will be called for each node.")
8275 (defun org-promote-subtree ()
8276 "Promote the entire subtree.
8277 See also `org-promote'."
8278 (interactive)
8279 (save-excursion
8280 (org-with-limited-levels (org-map-tree 'org-promote)))
8281 (org-fix-position-after-promote))
8283 (defun org-demote-subtree ()
8284 "Demote the entire subtree.
8285 See `org-demote' and `org-promote'."
8286 (interactive)
8287 (save-excursion
8288 (org-with-limited-levels (org-map-tree 'org-demote)))
8289 (org-fix-position-after-promote))
8291 (defun org-do-promote ()
8292 "Promote the current heading higher up the tree.
8293 If the region is active in `transient-mark-mode', promote all
8294 headings in the region."
8295 (interactive)
8296 (save-excursion
8297 (if (org-region-active-p)
8298 (org-map-region 'org-promote (region-beginning) (region-end))
8299 (org-promote)))
8300 (org-fix-position-after-promote))
8302 (defun org-do-demote ()
8303 "Demote the current heading lower down the tree.
8304 If the region is active in `transient-mark-mode', demote all
8305 headings in the region."
8306 (interactive)
8307 (save-excursion
8308 (if (org-region-active-p)
8309 (org-map-region 'org-demote (region-beginning) (region-end))
8310 (org-demote)))
8311 (org-fix-position-after-promote))
8313 (defun org-fix-position-after-promote ()
8314 "Fix cursor position and indentation after demoting/promoting."
8315 (let ((pos (point)))
8316 (when (save-excursion
8317 (beginning-of-line)
8318 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8319 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8320 (cond ((eobp) (insert " "))
8321 ((eolp) (insert " "))
8322 ((equal (char-after) ?\s) (forward-char 1))))))
8324 (defun org-current-level ()
8325 "Return the level of the current entry, or nil if before the first headline.
8326 The level is the number of stars at the beginning of the
8327 headline. Use `org-reduced-level' to remove the effect of
8328 `org-odd-levels'. Unlike to `org-outline-level', this function
8329 ignores inlinetasks."
8330 (let ((level (org-with-limited-levels (org-outline-level))))
8331 (and (> level 0) level)))
8333 (defun org-get-previous-line-level ()
8334 "Return the outline depth of the last headline before the current line.
8335 Returns 0 for the first headline in the buffer, and nil if before the
8336 first headline."
8337 (and (org-current-level)
8338 (or (and (/= (line-beginning-position) (point-min))
8339 (save-excursion (beginning-of-line 0) (org-current-level)))
8340 0)))
8342 (defun org-reduced-level (l)
8343 "Compute the effective level of a heading.
8344 This takes into account the setting of `org-odd-levels-only'."
8345 (cond
8346 ((zerop l) 0)
8347 (org-odd-levels-only (1+ (floor (/ l 2))))
8348 (t l)))
8350 (defun org-level-increment ()
8351 "Return the number of stars that will be added or removed at a
8352 time to headlines when structure editing, based on the value of
8353 `org-odd-levels-only'."
8354 (if org-odd-levels-only 2 1))
8356 (defun org-get-valid-level (level &optional change)
8357 "Rectify a level change under the influence of `org-odd-levels-only'
8358 LEVEL is a current level, CHANGE is by how much the level should be
8359 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8360 even level numbers will become the next higher odd number."
8361 (if org-odd-levels-only
8362 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8363 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8364 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8365 (max 1 (+ level (or change 0)))))
8367 (defun org-promote ()
8368 "Promote the current heading higher up the tree."
8369 (org-with-wide-buffer
8370 (org-back-to-heading t)
8371 (let* ((after-change-functions (remq 'flyspell-after-change-function
8372 after-change-functions))
8373 (level (save-match-data (funcall outline-level)))
8374 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8375 (diff (abs (- level (length up-head) -1))))
8376 (cond
8377 ((and (= level 1) org-allow-promoting-top-level-subtree)
8378 (replace-match "# " nil t))
8379 ((= level 1)
8380 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8381 (t (replace-match up-head nil t)))
8382 (unless (= level 1)
8383 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8384 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8385 (run-hooks 'org-after-promote-entry-hook))))
8387 (defun org-demote ()
8388 "Demote the current heading lower down the tree."
8389 (org-with-wide-buffer
8390 (org-back-to-heading t)
8391 (let* ((after-change-functions (remq 'flyspell-after-change-function
8392 after-change-functions))
8393 (level (save-match-data (funcall outline-level)))
8394 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8395 (diff (abs (- level (length down-head) -1))))
8396 (replace-match down-head nil t)
8397 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8398 (when org-adapt-indentation (org-fixup-indentation diff))
8399 (run-hooks 'org-after-demote-entry-hook))))
8401 (defun org-cycle-level ()
8402 "Cycle the level of an empty headline through possible states.
8403 This goes first to child, then to parent, level, then up the hierarchy.
8404 After top level, it switches back to sibling level."
8405 (interactive)
8406 (let ((org-adapt-indentation nil))
8407 (when (org-point-at-end-of-empty-headline)
8408 (setq this-command 'org-cycle-level) ; Only needed for caching
8409 (let ((cur-level (org-current-level))
8410 (prev-level (org-get-previous-line-level)))
8411 (cond
8412 ;; If first headline in file, promote to top-level.
8413 ((= prev-level 0)
8414 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8415 do (org-do-promote)))
8416 ;; If same level as prev, demote one.
8417 ((= prev-level cur-level)
8418 (org-do-demote))
8419 ;; If parent is top-level, promote to top level if not already.
8420 ((= prev-level 1)
8421 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8422 do (org-do-promote)))
8423 ;; If top-level, return to prev-level.
8424 ((= cur-level 1)
8425 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8426 do (org-do-demote)))
8427 ;; If less than prev-level, promote one.
8428 ((< cur-level prev-level)
8429 (org-do-promote))
8430 ;; If deeper than prev-level, promote until higher than
8431 ;; prev-level.
8432 ((> cur-level prev-level)
8433 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8434 do (org-do-promote))))
8435 t))))
8437 (defun org-map-tree (fun)
8438 "Call FUN for every heading underneath the current one."
8439 (org-back-to-heading t)
8440 (let ((level (funcall outline-level)))
8441 (save-excursion
8442 (funcall fun)
8443 (while (and (progn
8444 (outline-next-heading)
8445 (> (funcall outline-level) level))
8446 (not (eobp)))
8447 (funcall fun)))))
8449 (defun org-map-region (fun beg end)
8450 "Call FUN for every heading between BEG and END."
8451 (let ((org-ignore-region t))
8452 (save-excursion
8453 (setq end (copy-marker end))
8454 (goto-char beg)
8455 (when (and (re-search-forward org-outline-regexp-bol nil t)
8456 (< (point) end))
8457 (funcall fun))
8458 (while (and (progn
8459 (outline-next-heading)
8460 (< (point) end))
8461 (not (eobp)))
8462 (funcall fun)))))
8464 (defun org-fixup-indentation (diff)
8465 "Change the indentation in the current entry by DIFF.
8467 DIFF is an integer. Indentation is done according to the
8468 following rules:
8470 - Planning information and property drawers are always indented
8471 according to the new level of the headline;
8473 - Footnote definitions and their contents are ignored;
8475 - Inlinetasks' boundaries are not shifted;
8477 - Empty lines are ignored;
8479 - Other lines' indentation are shifted by DIFF columns, unless
8480 it would introduce a structural change in the document, in
8481 which case no shifting is done at all.
8483 Assume point is at a heading or an inlinetask beginning."
8484 (org-with-wide-buffer
8485 (narrow-to-region (line-beginning-position)
8486 (save-excursion
8487 (if (org-with-limited-levels (org-at-heading-p))
8488 (org-with-limited-levels (outline-next-heading))
8489 (org-inlinetask-goto-end))
8490 (point)))
8491 (forward-line)
8492 ;; Indent properly planning info and property drawer.
8493 (when (looking-at-p org-planning-line-re)
8494 (org-indent-line)
8495 (forward-line))
8496 (when (looking-at org-property-drawer-re)
8497 (goto-char (match-end 0))
8498 (forward-line)
8499 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8500 (catch 'no-shift
8501 (when (zerop diff) (throw 'no-shift nil))
8502 ;; If DIFF is negative, first check if a shift is possible at all
8503 ;; (e.g., it doesn't break structure). This can only happen if
8504 ;; some contents are not properly indented.
8505 (let ((case-fold-search t))
8506 (when (< diff 0)
8507 (let ((diff (- diff))
8508 (forbidden-re (concat org-outline-regexp
8509 "\\|"
8510 (substring org-footnote-definition-re 1))))
8511 (save-excursion
8512 (while (not (eobp))
8513 (cond
8514 ((looking-at-p "[ \t]*$") (forward-line))
8515 ((and (looking-at-p org-footnote-definition-re)
8516 (let ((e (org-element-at-point)))
8517 (and (eq (org-element-type e) 'footnote-definition)
8518 (goto-char (org-element-property :end e))))))
8519 ((looking-at-p org-outline-regexp) (forward-line))
8520 ;; Give up if shifting would move before column 0 or
8521 ;; if it would introduce a headline or a footnote
8522 ;; definition.
8524 (skip-chars-forward " \t")
8525 (let ((ind (current-column)))
8526 (when (or (< ind diff)
8527 (and (= ind diff) (looking-at-p forbidden-re)))
8528 (throw 'no-shift nil)))
8529 ;; Ignore contents of example blocks and source
8530 ;; blocks if their indentation is meant to be
8531 ;; preserved. Jump to block's closing line.
8532 (beginning-of-line)
8533 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8534 (let ((e (org-element-at-point)))
8535 (and (memq (org-element-type e)
8536 '(example-block src-block))
8537 (or org-src-preserve-indentation
8538 (org-element-property :preserve-indent e))
8539 (goto-char (org-element-property :end e))
8540 (progn (skip-chars-backward " \r\t\n")
8541 (beginning-of-line)
8542 t))))
8543 (forward-line))))))))
8544 ;; Shift lines but footnote definitions, inlinetasks boundaries
8545 ;; by DIFF. Also skip contents of source or example blocks
8546 ;; when indentation is meant to be preserved.
8547 (while (not (eobp))
8548 (cond
8549 ((and (looking-at-p org-footnote-definition-re)
8550 (let ((e (org-element-at-point)))
8551 (and (eq (org-element-type e) 'footnote-definition)
8552 (goto-char (org-element-property :end e))))))
8553 ((looking-at-p org-outline-regexp) (forward-line))
8554 ((looking-at-p "[ \t]*$") (forward-line))
8556 (indent-line-to (+ (org-get-indentation) diff))
8557 (beginning-of-line)
8558 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8559 (let ((e (org-element-at-point)))
8560 (and (memq (org-element-type e)
8561 '(example-block src-block))
8562 (or org-src-preserve-indentation
8563 (org-element-property :preserve-indent e))
8564 (goto-char (org-element-property :end e))
8565 (progn (skip-chars-backward " \r\t\n")
8566 (beginning-of-line)
8567 t))))
8568 (forward-line)))))))))
8570 (defun org-convert-to-odd-levels ()
8571 "Convert an Org file with all levels allowed to one with odd levels.
8572 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8573 level 5 etc."
8574 (interactive)
8575 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8576 (let ((outline-level 'org-outline-level)
8577 (org-odd-levels-only nil) n)
8578 (save-excursion
8579 (goto-char (point-min))
8580 (while (re-search-forward "^\\*\\*+ " nil t)
8581 (setq n (- (length (match-string 0)) 2))
8582 (while (>= (setq n (1- n)) 0)
8583 (org-demote))
8584 (end-of-line 1))))))
8586 (defun org-convert-to-oddeven-levels ()
8587 "Convert an Org file with only odd levels to one with odd/even levels.
8588 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8589 file contains a section with an even level, conversion would
8590 destroy the structure of the file. An error is signaled in this
8591 case."
8592 (interactive)
8593 (goto-char (point-min))
8594 ;; First check if there are no even levels
8595 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8596 (org-show-set-visibility 'canonical)
8597 (error "Not all levels are odd in this file. Conversion not possible"))
8598 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8599 (let ((outline-regexp org-outline-regexp)
8600 (outline-level 'org-outline-level)
8601 (org-odd-levels-only nil) n)
8602 (save-excursion
8603 (goto-char (point-min))
8604 (while (re-search-forward "^\\*\\*+ " nil t)
8605 (setq n (/ (1- (length (match-string 0))) 2))
8606 (while (>= (setq n (1- n)) 0)
8607 (org-promote))
8608 (end-of-line 1))))))
8610 (defun org-tr-level (n)
8611 "Make N odd if required."
8612 (if org-odd-levels-only (1+ (/ n 2)) n))
8614 ;;; Vertical tree motion, cutting and pasting of subtrees
8616 (defun org-move-subtree-up (&optional arg)
8617 "Move the current subtree up past ARG headlines of the same level."
8618 (interactive "p")
8619 (org-move-subtree-down (- (prefix-numeric-value arg))))
8621 (defun org-move-subtree-down (&optional arg)
8622 "Move the current subtree down past ARG headlines of the same level."
8623 (interactive "p")
8624 (setq arg (prefix-numeric-value arg))
8625 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8626 'org-get-last-sibling))
8627 (ins-point (make-marker))
8628 (cnt (abs arg))
8629 (col (current-column))
8630 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8631 ;; Select the tree
8632 (org-back-to-heading)
8633 (setq beg0 (point))
8634 (save-excursion
8635 (setq ne-beg (org-back-over-empty-lines))
8636 (setq beg (point)))
8637 (save-match-data
8638 (save-excursion (outline-end-of-heading)
8639 (setq folded (outline-invisible-p)))
8640 (progn (org-end-of-subtree nil t)
8641 (unless (eobp) (backward-char))))
8642 (outline-next-heading)
8643 (setq ne-end (org-back-over-empty-lines))
8644 (setq end (point))
8645 (goto-char beg0)
8646 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8647 ;; include less whitespace
8648 (save-excursion
8649 (goto-char beg)
8650 (forward-line (- ne-beg ne-end))
8651 (setq beg (point))))
8652 ;; Find insertion point, with error handling
8653 (while (> cnt 0)
8654 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8655 (progn (goto-char beg0)
8656 (user-error "Cannot move past superior level or buffer limit")))
8657 (setq cnt (1- cnt)))
8658 (when (> arg 0)
8659 ;; Moving forward - still need to move over subtree
8660 (org-end-of-subtree t t)
8661 (save-excursion
8662 (org-back-over-empty-lines)
8663 (or (bolp) (newline))))
8664 (setq ne-ins (org-back-over-empty-lines))
8665 (move-marker ins-point (point))
8666 (setq txt (buffer-substring beg end))
8667 (org-save-markers-in-region beg end)
8668 (delete-region beg end)
8669 (org-remove-empty-overlays-at beg)
8670 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8671 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8672 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8673 (let ((bbb (point)))
8674 (insert-before-markers txt)
8675 (org-reinstall-markers-in-region bbb)
8676 (move-marker ins-point bbb))
8677 (or (bolp) (insert "\n"))
8678 (setq ins-end (point))
8679 (goto-char ins-point)
8680 (org-skip-whitespace)
8681 (when (and (< arg 0)
8682 (org-first-sibling-p)
8683 (> ne-ins ne-beg))
8684 ;; Move whitespace back to beginning
8685 (save-excursion
8686 (goto-char ins-end)
8687 (let ((kill-whole-line t))
8688 (kill-line (- ne-ins ne-beg)) (point)))
8689 (insert (make-string (- ne-ins ne-beg) ?\n)))
8690 (move-marker ins-point nil)
8691 (if folded
8692 (outline-hide-subtree)
8693 (org-show-entry)
8694 (org-show-children)
8695 (org-cycle-hide-drawers 'children))
8696 (org-clean-visibility-after-subtree-move)
8697 ;; move back to the initial column we were at
8698 (move-to-column col)))
8700 (defvar org-subtree-clip ""
8701 "Clipboard for cut and paste of subtrees.
8702 This is actually only a copy of the kill, because we use the normal kill
8703 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8705 (defvar org-subtree-clip-folded nil
8706 "Was the last copied subtree folded?
8707 This is used to fold the tree back after pasting.")
8709 (defun org-cut-subtree (&optional n)
8710 "Cut the current subtree into the clipboard.
8711 With prefix arg N, cut this many sequential subtrees.
8712 This is a short-hand for marking the subtree and then cutting it."
8713 (interactive "p")
8714 (org-copy-subtree n 'cut))
8716 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8717 "Copy the current subtree it in the clipboard.
8718 With prefix arg N, copy this many sequential subtrees.
8719 This is a short-hand for marking the subtree and then copying it.
8720 If CUT is non-nil, actually cut the subtree.
8721 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8722 of some markers in the region, even if CUT is non-nil. This is
8723 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8724 (interactive "p")
8725 (let (beg end folded (beg0 (point)))
8726 (if (called-interactively-p 'any)
8727 (org-back-to-heading nil) ; take what looks like a subtree
8728 (org-back-to-heading t)) ; take what is really there
8729 (setq beg (point))
8730 (skip-chars-forward " \t\r\n")
8731 (save-match-data
8732 (if nosubtrees
8733 (outline-next-heading)
8734 (save-excursion (outline-end-of-heading)
8735 (setq folded (outline-invisible-p)))
8736 (ignore-errors (org-forward-heading-same-level (1- n) t))
8737 (org-end-of-subtree t t)))
8738 ;; Include the end of an inlinetask
8739 (when (and (featurep 'org-inlinetask)
8740 (looking-at-p (concat (org-inlinetask-outline-regexp)
8741 "END[ \t]*$")))
8742 (end-of-line))
8743 (setq end (point))
8744 (goto-char beg0)
8745 (when (> end beg)
8746 (setq org-subtree-clip-folded folded)
8747 (when (or cut force-store-markers)
8748 (org-save-markers-in-region beg end))
8749 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8750 (setq org-subtree-clip (current-kill 0))
8751 (message "%s: Subtree(s) with %d characters"
8752 (if cut "Cut" "Copied")
8753 (length org-subtree-clip)))))
8755 (defun org-paste-subtree (&optional level tree for-yank remove)
8756 "Paste the clipboard as a subtree, with modification of headline level.
8757 The entire subtree is promoted or demoted in order to match a new headline
8758 level.
8760 If the cursor is at the beginning of a headline, the same level as
8761 that headline is used to paste the tree.
8763 If not, the new level is derived from the *visible* headings
8764 before and after the insertion point, and taken to be the inferior headline
8765 level of the two. So if the previous visible heading is level 3 and the
8766 next is level 4 (or vice versa), level 4 will be used for insertion.
8767 This makes sure that the subtree remains an independent subtree and does
8768 not swallow low level entries.
8770 You can also force a different level, either by using a numeric prefix
8771 argument, or by inserting the heading marker by hand. For example, if the
8772 cursor is after \"*****\", then the tree will be shifted to level 5.
8774 If optional TREE is given, use this text instead of the kill ring.
8776 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8777 move back over whitespace before inserting, and move point to the end of
8778 the inserted text when done.
8780 When REMOVE is non-nil, remove the subtree from the clipboard."
8781 (interactive "P")
8782 (setq tree (or tree (and kill-ring (current-kill 0))))
8783 (unless (org-kill-is-subtree-p tree)
8784 (user-error "%s"
8785 (substitute-command-keys
8786 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8787 (org-with-limited-levels
8788 (let* ((visp (not (outline-invisible-p)))
8789 (txt tree)
8790 (^re_ "\\(\\*+\\)[ \t]*")
8791 (old-level (if (string-match org-outline-regexp-bol txt)
8792 (- (match-end 0) (match-beginning 0) 1)
8793 -1))
8794 (force-level (cond (level (prefix-numeric-value level))
8795 ((and (looking-at "[ \t]*$")
8796 (string-match
8797 "^\\*+$" (buffer-substring
8798 (point-at-bol) (point))))
8799 (- (match-end 0) (match-beginning 0)))
8800 ((and (bolp)
8801 (looking-at org-outline-regexp))
8802 (- (match-end 0) (point) 1))))
8803 (previous-level (save-excursion
8804 (condition-case nil
8805 (progn
8806 (outline-previous-visible-heading 1)
8807 (if (looking-at ^re_)
8808 (- (match-end 0) (match-beginning 0) 1)
8810 (error 1))))
8811 (next-level (save-excursion
8812 (condition-case nil
8813 (progn
8814 (or (looking-at org-outline-regexp)
8815 (outline-next-visible-heading 1))
8816 (if (looking-at ^re_)
8817 (- (match-end 0) (match-beginning 0) 1)
8819 (error 1))))
8820 (new-level (or force-level (max previous-level next-level)))
8821 (shift (if (or (= old-level -1)
8822 (= new-level -1)
8823 (= old-level new-level))
8825 (- new-level old-level)))
8826 (delta (if (> shift 0) -1 1))
8827 (func (if (> shift 0) 'org-demote 'org-promote))
8828 (org-odd-levels-only nil)
8829 beg end newend)
8830 ;; Remove the forced level indicator
8831 (when force-level
8832 (delete-region (point-at-bol) (point)))
8833 ;; Paste
8834 (beginning-of-line (if (bolp) 1 2))
8835 (setq beg (point))
8836 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8837 (insert-before-markers txt)
8838 (unless (string-suffix-p "\n" txt) (insert "\n"))
8839 (setq newend (point))
8840 (org-reinstall-markers-in-region beg)
8841 (setq end (point))
8842 (goto-char beg)
8843 (skip-chars-forward " \t\n\r")
8844 (setq beg (point))
8845 (when (and (outline-invisible-p) visp)
8846 (save-excursion (outline-show-heading)))
8847 ;; Shift if necessary
8848 (unless (= shift 0)
8849 (save-restriction
8850 (narrow-to-region beg end)
8851 (while (not (= shift 0))
8852 (org-map-region func (point-min) (point-max))
8853 (setq shift (+ delta shift)))
8854 (goto-char (point-min))
8855 (setq newend (point-max))))
8856 (when (or (called-interactively-p 'interactive) for-yank)
8857 (message "Clipboard pasted as level %d subtree" new-level))
8858 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8859 kill-ring
8860 (eq org-subtree-clip (current-kill 0))
8861 org-subtree-clip-folded)
8862 ;; The tree was folded before it was killed/copied
8863 (outline-hide-subtree))
8864 (and for-yank (goto-char newend))
8865 (and remove (setq kill-ring (cdr kill-ring))))))
8867 (defun org-kill-is-subtree-p (&optional txt)
8868 "Check if the current kill is an outline subtree, or a set of trees.
8869 Returns nil if kill does not start with a headline, or if the first
8870 headline level is not the largest headline level in the tree.
8871 So this will actually accept several entries of equal levels as well,
8872 which is OK for `org-paste-subtree'.
8873 If optional TXT is given, check this string instead of the current kill."
8874 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8875 (re (org-get-limited-outline-regexp))
8876 (^re (concat "^" re))
8877 (start-level (and kill
8878 (string-match
8879 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8880 kill)
8881 (- (match-end 2) (match-beginning 2) 1)))
8882 (start (1+ (or (match-beginning 2) -1))))
8883 (if (not start-level)
8884 (progn
8885 nil) ;; does not even start with a heading
8886 (catch 'exit
8887 (while (setq start (string-match ^re kill (1+ start)))
8888 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8889 (throw 'exit nil)))
8890 t))))
8892 (defvar org-markers-to-move nil
8893 "Markers that should be moved with a cut-and-paste operation.
8894 Those markers are stored together with their positions relative to
8895 the start of the region.")
8897 (defun org-save-markers-in-region (beg end)
8898 "Check markers in region.
8899 If these markers are between BEG and END, record their position relative
8900 to BEG, so that after moving the block of text, we can put the markers back
8901 into place.
8902 This function gets called just before an entry or tree gets cut from the
8903 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8904 called immediately, to move the markers with the entries."
8905 (setq org-markers-to-move nil)
8906 (when (featurep 'org-clock)
8907 (org-clock-save-markers-for-cut-and-paste beg end))
8908 (when (featurep 'org-agenda)
8909 (org-agenda-save-markers-for-cut-and-paste beg end)))
8911 (defun org-check-and-save-marker (marker beg end)
8912 "Check if MARKER is between BEG and END.
8913 If yes, remember the marker and the distance to BEG."
8914 (when (and (marker-buffer marker)
8915 (equal (marker-buffer marker) (current-buffer))
8916 (>= marker beg) (< marker end))
8917 (push (cons marker (- marker beg)) org-markers-to-move)))
8919 (defun org-reinstall-markers-in-region (beg)
8920 "Move all remembered markers to their position relative to BEG."
8921 (dolist (x org-markers-to-move)
8922 (move-marker (car x) (+ beg (cdr x))))
8923 (setq org-markers-to-move nil))
8925 (defun org-narrow-to-subtree ()
8926 "Narrow buffer to the current subtree."
8927 (interactive)
8928 (save-excursion
8929 (save-match-data
8930 (org-with-limited-levels
8931 (narrow-to-region
8932 (progn (org-back-to-heading t) (point))
8933 (progn (org-end-of-subtree t t)
8934 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8935 (point)))))))
8937 (defun org-narrow-to-block ()
8938 "Narrow buffer to the current block."
8939 (interactive)
8940 (let* ((case-fold-search t)
8941 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8942 "^[ \t]*#\\+end_.*")))
8943 (if blockp
8944 (narrow-to-region (car blockp) (cdr blockp))
8945 (user-error "Not in a block"))))
8947 (defun org-clone-subtree-with-time-shift (n &optional shift)
8948 "Clone the task (subtree) at point N times.
8949 The clones will be inserted as siblings.
8951 In interactive use, the user will be prompted for the number of
8952 clones to be produced. If the entry has a timestamp, the user
8953 will also be prompted for a time shift, which may be a repeater
8954 as used in time stamps, for example `+3d'. To disable this,
8955 you can call the function with a universal prefix argument.
8957 When a valid repeater is given and the entry contains any time
8958 stamps, the clones will become a sequence in time, with time
8959 stamps in the subtree shifted for each clone produced. If SHIFT
8960 is nil or the empty string, time stamps will be left alone. The
8961 ID property of the original subtree is removed.
8963 In each clone, all the CLOCK entries will be removed. This
8964 prevents Org from considering that the clocked times overlap.
8966 If the original subtree did contain time stamps with a repeater,
8967 the following will happen:
8968 - the repeater will be removed in each clone
8969 - an additional clone will be produced, with the current, unshifted
8970 date(s) in the entry.
8971 - the original entry will be placed *after* all the clones, with
8972 repeater intact.
8973 - the start days in the repeater in the original entry will be shifted
8974 to past the last clone.
8975 In this way you can spell out a number of instances of a repeating task,
8976 and still retain the repeater to cover future instances of the task.
8978 As described above, N+1 clones are produced when the original
8979 subtree has a repeater. Setting N to 0, then, can be used to
8980 remove the repeater from a subtree and create a shifted clone
8981 with the original repeater."
8982 (interactive "nNumber of clones to produce: ")
8983 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8984 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8985 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8986 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8987 (shift
8988 (or shift
8989 (if (and (not (equal current-prefix-arg '(4)))
8990 (save-excursion
8991 (goto-char beg)
8992 (re-search-forward org-ts-regexp-both end-of-tree t)))
8993 (read-from-minibuffer
8994 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8995 ""))) ;No time shift
8996 (doshift
8997 (and (org-string-nw-p shift)
8998 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8999 shift)
9000 (user-error "Invalid shift specification %s" shift)))))
9001 (goto-char end-of-tree)
9002 (unless (bolp) (insert "\n"))
9003 (let* ((end (point))
9004 (template (buffer-substring beg end))
9005 (shift-n (and doshift (string-to-number (match-string 1 shift))))
9006 (shift-what (pcase (and doshift (match-string 2 shift))
9007 (`nil nil)
9008 ("d" 'day)
9009 ("w" (setq shift-n (* 7 shift-n)) 'day)
9010 ("m" 'month)
9011 ("y" 'year)
9012 (_ (error "Unsupported time unit"))))
9013 (nmin 1)
9014 (nmax n)
9015 (n-no-remove -1)
9016 (idprop (org-entry-get nil "ID")))
9017 (when (and doshift
9018 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
9019 template))
9020 (delete-region beg end)
9021 (setq end beg)
9022 (setq nmin 0)
9023 (setq nmax (1+ nmax))
9024 (setq n-no-remove nmax))
9025 (goto-char end)
9026 (cl-loop for n from nmin to nmax do
9027 (insert
9028 ;; Prepare clone.
9029 (with-temp-buffer
9030 (insert template)
9031 (org-mode)
9032 (goto-char (point-min))
9033 (org-show-subtree)
9034 (and idprop (if org-clone-delete-id
9035 (org-entry-delete nil "ID")
9036 (org-id-get-create t)))
9037 (unless (= n 0)
9038 (while (re-search-forward org-clock-line-re nil t)
9039 (delete-region (line-beginning-position)
9040 (line-beginning-position 2)))
9041 (goto-char (point-min))
9042 (while (re-search-forward org-drawer-regexp nil t)
9043 (org-remove-empty-drawer-at (point))))
9044 (goto-char (point-min))
9045 (when doshift
9046 (while (re-search-forward org-ts-regexp-both nil t)
9047 (org-timestamp-change (* n shift-n) shift-what))
9048 (unless (= n n-no-remove)
9049 (goto-char (point-min))
9050 (while (re-search-forward org-ts-regexp nil t)
9051 (save-excursion
9052 (goto-char (match-beginning 0))
9053 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
9054 (delete-region (match-beginning 1) (match-end 1)))))))
9055 (buffer-string)))))
9056 (goto-char beg)))
9058 ;;; Outline Sorting
9060 (defun org-sort (with-case)
9061 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
9062 Optional argument WITH-CASE means sort case-sensitively."
9063 (interactive "P")
9064 (cond
9065 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
9066 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
9068 (org-call-with-arg 'org-sort-entries with-case))))
9070 (defun org-sort-remove-invisible (s)
9071 "Remove invisible links from string S."
9072 (remove-text-properties 0 (length s) org-rm-props s)
9073 (while (string-match org-bracket-link-regexp s)
9074 (setq s (replace-match (if (match-end 2)
9075 (match-string 3 s)
9076 (match-string 1 s))
9077 t t s)))
9078 (let ((st (format " %s " s)))
9079 (while (string-match org-emph-re st)
9080 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
9081 (setq s (substring st 1 -1)))
9084 (defvar org-priority-regexp) ; defined later in the file
9086 (defvar org-after-sorting-entries-or-items-hook nil
9087 "Hook that is run after a bunch of entries or items have been sorted.
9088 When children are sorted, the cursor is in the parent line when this
9089 hook gets called. When a region or a plain list is sorted, the cursor
9090 will be in the first entry of the sorted region/list.")
9092 (defun org-sort-entries
9093 (&optional with-case sorting-type getkey-func compare-func property
9094 interactive?)
9095 "Sort entries on a certain level of an outline tree.
9096 If there is an active region, the entries in the region are sorted.
9097 Else, if the cursor is before the first entry, sort the top-level items.
9098 Else, the children of the entry at point are sorted.
9100 Sorting can be alphabetically, numerically, by date/time as given by
9101 a time stamp, by a property, by priority order, or by a custom function.
9103 The command prompts for the sorting type unless it has been given to the
9104 function through the SORTING-TYPE argument, which needs to be a character,
9105 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9106 the precise meaning of each character:
9108 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9109 c By creation time, which is assumed to be the first inactive time stamp
9110 at the beginning of a line.
9111 d By deadline date/time.
9112 k By clocking time.
9113 n Numerically, by converting the beginning of the entry/item to a number.
9114 o By order of TODO keywords.
9115 p By priority according to the cookie.
9116 r By the value of a property.
9117 s By scheduled date/time.
9118 t By date/time, either the first active time stamp in the entry, or, if
9119 none exist, by the first inactive one.
9121 Capital letters will reverse the sort order.
9123 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9124 called with point at the beginning of the record. It must return a
9125 value that is compatible with COMPARE-FUNC, the function used to
9126 compare entries.
9128 Comparing entries ignores case by default. However, with an optional argument
9129 WITH-CASE, the sorting considers case as well.
9131 Sorting is done against the visible part of the headlines, it ignores hidden
9132 links.
9134 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
9136 A non-nil value for INTERACTIVE? is used to signal that this
9137 function is being called interactively."
9138 (interactive (list current-prefix-arg nil nil nil nil t))
9139 (let ((case-func (if with-case 'identity 'downcase))
9140 (cmstr
9141 ;; The clock marker is lost when using `sort-subr', let's
9142 ;; store the clocking string.
9143 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9144 (save-excursion
9145 (goto-char org-clock-marker)
9146 (buffer-substring-no-properties (line-beginning-position)
9147 (point)))))
9148 start beg end stars re re2
9149 txt what tmp)
9150 ;; Find beginning and end of region to sort
9151 (cond
9152 ((org-region-active-p)
9153 ;; we will sort the region
9154 (setq end (region-end)
9155 what "region")
9156 (goto-char (region-beginning))
9157 (unless (org-at-heading-p) (outline-next-heading))
9158 (setq start (point)))
9159 ((or (org-at-heading-p)
9160 (ignore-errors (progn (org-back-to-heading) t)))
9161 ;; we will sort the children of the current headline
9162 (org-back-to-heading)
9163 (setq start (point)
9164 end (progn (org-end-of-subtree t t)
9165 (or (bolp) (insert "\n"))
9166 (when (>= (org-back-over-empty-lines) 1)
9167 (forward-line 1))
9168 (point))
9169 what "children")
9170 (goto-char start)
9171 (outline-show-subtree)
9172 (outline-next-heading))
9174 ;; we will sort the top-level entries in this file
9175 (goto-char (point-min))
9176 (or (org-at-heading-p) (outline-next-heading))
9177 (setq start (point))
9178 (goto-char (point-max))
9179 (beginning-of-line 1)
9180 (when (looking-at ".*?\\S-")
9181 ;; File ends in a non-white line
9182 (end-of-line 1)
9183 (insert "\n"))
9184 (setq end (point-max))
9185 (setq what "top-level")
9186 (goto-char start)
9187 (outline-show-all)))
9189 (setq beg (point))
9190 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9192 (looking-at "\\(\\*+\\)")
9193 (setq stars (match-string 1)
9194 re (concat "^" (regexp-quote stars) " +")
9195 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9196 txt (buffer-substring beg end))
9197 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9198 (when (and (not (equal stars "*")) (string-match re2 txt))
9199 (user-error "Region to sort contains a level above the first entry"))
9201 (unless sorting-type
9202 (message
9203 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9204 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9205 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9206 what)
9207 (setq sorting-type (read-char-exclusive)))
9209 (unless getkey-func
9210 (and (= (downcase sorting-type) ?f)
9211 (setq getkey-func
9212 (or (and interactive?
9213 (org-read-function
9214 "Function for extracting keys: "))
9215 (error "Missing key extractor")))))
9217 (and (= (downcase sorting-type) ?r)
9218 (not property)
9219 (setq property
9220 (completing-read "Property: "
9221 (mapcar #'list (org-buffer-property-keys t))
9222 nil t)))
9224 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9225 (message "Sorting entries...")
9227 (save-restriction
9228 (narrow-to-region start end)
9229 (let ((dcst (downcase sorting-type))
9230 (case-fold-search nil)
9231 (now (current-time)))
9232 (sort-subr
9233 (/= dcst sorting-type)
9234 ;; This function moves to the beginning character of the "record" to
9235 ;; be sorted.
9236 (lambda nil
9237 (if (re-search-forward re nil t)
9238 (goto-char (match-beginning 0))
9239 (goto-char (point-max))))
9240 ;; This function moves to the last character of the "record" being
9241 ;; sorted.
9242 (lambda nil
9243 (save-match-data
9244 (condition-case nil
9245 (outline-forward-same-level 1)
9246 (error
9247 (goto-char (point-max))))))
9248 ;; This function returns the value that gets sorted against.
9249 (lambda nil
9250 (cond
9251 ((= dcst ?n)
9252 (if (looking-at org-complex-heading-regexp)
9253 (string-to-number (org-sort-remove-invisible (match-string 4)))
9254 nil))
9255 ((= dcst ?a)
9256 (if (looking-at org-complex-heading-regexp)
9257 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9258 nil))
9259 ((= dcst ?k)
9260 (or (get-text-property (point) :org-clock-minutes) 0))
9261 ((= dcst ?t)
9262 (let ((end (save-excursion (outline-next-heading) (point))))
9263 (if (or (re-search-forward org-ts-regexp end t)
9264 (re-search-forward org-ts-regexp-both end t))
9265 (org-time-string-to-seconds (match-string 0))
9266 (float-time now))))
9267 ((= dcst ?c)
9268 (let ((end (save-excursion (outline-next-heading) (point))))
9269 (if (re-search-forward
9270 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9271 end t)
9272 (org-time-string-to-seconds (match-string 0))
9273 (float-time now))))
9274 ((= dcst ?s)
9275 (let ((end (save-excursion (outline-next-heading) (point))))
9276 (if (re-search-forward org-scheduled-time-regexp end t)
9277 (org-time-string-to-seconds (match-string 1))
9278 (float-time now))))
9279 ((= dcst ?d)
9280 (let ((end (save-excursion (outline-next-heading) (point))))
9281 (if (re-search-forward org-deadline-time-regexp end t)
9282 (org-time-string-to-seconds (match-string 1))
9283 (float-time now))))
9284 ((= dcst ?p)
9285 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9286 (string-to-char (match-string 2))
9287 org-default-priority))
9288 ((= dcst ?r)
9289 (or (org-entry-get nil property) ""))
9290 ((= dcst ?o)
9291 (when (looking-at org-complex-heading-regexp)
9292 (let* ((m (match-string 2))
9293 (s (if (member m org-done-keywords) '- '+)))
9294 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9295 ((= dcst ?f)
9296 (if getkey-func
9297 (progn
9298 (setq tmp (funcall getkey-func))
9299 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9300 tmp)
9301 (error "Invalid key function `%s'" getkey-func)))
9302 (t (error "Invalid sorting type `%c'" sorting-type))))
9304 (cond
9305 ((= dcst ?a) 'string<)
9306 ((= dcst ?f)
9307 (or compare-func
9308 (and interactive?
9309 (org-read-function
9310 (concat "Function for comparing keys "
9311 "(empty for default `sort-subr' predicate): ")
9312 'allow-empty))))
9313 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9314 (run-hooks 'org-after-sorting-entries-or-items-hook)
9315 ;; Reset the clock marker if needed
9316 (when cmstr
9317 (save-excursion
9318 (goto-char start)
9319 (search-forward cmstr nil t)
9320 (move-marker org-clock-marker (point))))
9321 (message "Sorting entries...done")))
9323 ;;; The orgstruct minor mode
9325 ;; Define a minor mode which can be used in other modes in order to
9326 ;; integrate the Org mode structure editing commands.
9328 ;; This is really a hack, because the Org mode structure commands use
9329 ;; keys which normally belong to the major mode. Here is how it
9330 ;; works: The minor mode defines all the keys necessary to operate the
9331 ;; structure commands, but wraps the commands into a function which
9332 ;; tests if the cursor is currently at a headline or a plain list
9333 ;; item. If that is the case, the structure command is used,
9334 ;; temporarily setting many Org mode variables like regular
9335 ;; expressions for filling etc. However, when any of those keys is
9336 ;; used at a different location, function uses `key-binding' to look
9337 ;; up if the key has an associated command in another currently active
9338 ;; keymap (minor modes, major mode, global), and executes that
9339 ;; command. There might be problems if any of the keys is otherwise
9340 ;; used as a prefix key.
9342 (defcustom orgstruct-heading-prefix-regexp ""
9343 "Regexp that matches the custom prefix of Org headlines in
9344 orgstruct(++)-mode."
9345 :group 'org
9346 :version "24.4"
9347 :package-version '(Org . "8.3")
9348 :type 'regexp)
9349 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9351 (defcustom orgstruct-setup-hook nil
9352 "Hook run after orgstruct-mode-map is filled."
9353 :group 'org
9354 :version "24.4"
9355 :package-version '(Org . "8.0")
9356 :type 'hook)
9358 (defvar orgstruct-initialized nil)
9360 (defvar org-local-vars nil
9361 "List of local variables, for use by `orgstruct-mode'.")
9363 ;;;###autoload
9364 (define-minor-mode orgstruct-mode
9365 "Toggle the minor mode `orgstruct-mode'.
9366 This mode is for using Org mode structure commands in other
9367 modes. The following keys behave as if Org mode were active, if
9368 the cursor is on a headline, or on a plain list item (both as
9369 defined by Org mode)."
9370 nil " OrgStruct" (make-sparse-keymap)
9371 (funcall (if orgstruct-mode
9372 'add-to-invisibility-spec
9373 'remove-from-invisibility-spec)
9374 '(outline . t))
9375 (when orgstruct-mode
9376 (org-load-modules-maybe)
9377 (unless orgstruct-initialized
9378 (orgstruct-setup)
9379 (setq orgstruct-initialized t))))
9381 ;;;###autoload
9382 (defun turn-on-orgstruct ()
9383 "Unconditionally turn on `orgstruct-mode'."
9384 (orgstruct-mode 1))
9386 (defvar-local orgstruct-is-++ nil
9387 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9388 (defvar-local org-fb-vars nil)
9389 (defun orgstruct++-mode (&optional arg)
9390 "Toggle `orgstruct-mode', the enhanced version of it.
9391 In addition to setting orgstruct-mode, this also exports all
9392 indentation and autofilling variables from Org mode into the
9393 buffer. It will also recognize item context in multiline items."
9394 (interactive "P")
9395 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9396 (if (< arg 1)
9397 (progn (orgstruct-mode -1)
9398 (dolist (v org-fb-vars)
9399 (set (make-local-variable (car v))
9400 (if (eq (car-safe (cadr v)) 'quote)
9401 (cl-cadadr v)
9402 (nth 1 v)))))
9403 (orgstruct-mode 1)
9404 (setq org-fb-vars nil)
9405 (unless org-local-vars
9406 (setq org-local-vars (org-get-local-variables)))
9407 (let (var val)
9408 (dolist (x org-local-vars)
9409 (when (string-match
9410 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9411 \\|fill-prefix\\|indent-\\)"
9412 (symbol-name (car x)))
9413 (setq var (car x) val (nth 1 x))
9414 (push (list var `(quote ,(eval var))) org-fb-vars)
9415 (set (make-local-variable var)
9416 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9417 (setq-local orgstruct-is-++ t))))
9419 ;;;###autoload
9420 (defun turn-on-orgstruct++ ()
9421 "Unconditionally turn on `orgstruct++-mode'."
9422 (orgstruct++-mode 1))
9424 (defun orgstruct-error ()
9425 "Error when there is no default binding for a structure key."
9426 (interactive)
9427 (funcall (if (fboundp 'user-error)
9428 'user-error
9429 'error)
9430 "This key has no function outside structure elements"))
9432 (defun orgstruct-setup ()
9433 "Setup orgstruct keymap."
9434 (dolist (cell '((org-demote . t)
9435 (org-metaleft . t)
9436 (org-metaright . t)
9437 (org-promote . t)
9438 (org-shiftmetaleft . t)
9439 (org-shiftmetaright . t)
9440 org-backward-element
9441 org-backward-heading-same-level
9442 org-ctrl-c-ret
9443 org-ctrl-c-minus
9444 org-ctrl-c-star
9445 org-cycle
9446 org-force-cycle-archived
9447 org-forward-heading-same-level
9448 org-insert-heading
9449 org-insert-heading-respect-content
9450 org-kill-note-or-show-branches
9451 org-mark-subtree
9452 org-meta-return
9453 org-metadown
9454 org-metaup
9455 org-narrow-to-subtree
9456 org-promote-subtree
9457 org-reveal
9458 org-shiftdown
9459 org-shiftleft
9460 org-shiftmetadown
9461 org-shiftmetaup
9462 org-shiftright
9463 org-shifttab
9464 org-shifttab
9465 org-shiftup
9466 org-show-children
9467 org-show-subtree
9468 org-sort
9469 org-up-element
9470 outline-demote
9471 outline-next-visible-heading
9472 outline-previous-visible-heading
9473 outline-promote
9474 outline-up-heading))
9475 (let ((f (or (car-safe cell) cell))
9476 (disable-when-heading-prefix (cdr-safe cell)))
9477 (when (fboundp f)
9478 (let ((new-bindings))
9479 (dolist (binding (nconc (where-is-internal f org-mode-map)
9480 (where-is-internal f outline-mode-map)))
9481 (push binding new-bindings)
9482 ;; TODO use local-function-key-map
9483 (dolist (rep '(("<tab>" . "TAB")
9484 ("<return>" . "RET")
9485 ("<escape>" . "ESC")
9486 ("<delete>" . "DEL")))
9487 (setq binding (read-kbd-macro
9488 (let ((case-fold-search))
9489 (replace-regexp-in-string
9490 (regexp-quote (cdr rep))
9491 (car rep)
9492 (key-description binding)))))
9493 (cl-pushnew binding new-bindings :test 'equal)))
9494 (dolist (binding new-bindings)
9495 (let ((key (lookup-key orgstruct-mode-map binding)))
9496 (when (or (not key) (numberp key))
9497 (ignore-errors
9498 (org-defkey orgstruct-mode-map
9499 binding
9500 (orgstruct-make-binding
9501 f binding disable-when-heading-prefix))))))))))
9502 (run-hooks 'orgstruct-setup-hook))
9504 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9505 "Create a function for binding in the structure minor mode.
9506 FUN is the command to call inside a table. KEY is the key that
9507 should be checked in for a command to execute outside of tables.
9508 Non-nil `disable-when-heading-prefix' means to disable the command
9509 if `orgstruct-heading-prefix-regexp' is not empty."
9510 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9511 (let ((nname name)
9512 (i 0))
9513 (while (fboundp (intern nname))
9514 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9515 (setq name (intern nname)))
9516 (eval
9517 (let ((bindings '((org-heading-regexp
9518 (concat "^"
9519 orgstruct-heading-prefix-regexp
9520 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9521 (org-outline-regexp
9522 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9523 (org-outline-regexp-bol
9524 (concat "^" org-outline-regexp))
9525 (outline-regexp org-outline-regexp)
9526 (outline-heading-end-regexp "\n")
9527 (outline-level 'org-outline-level)
9528 (outline-heading-alist))))
9529 `(defun ,name (arg)
9530 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9531 "Outside of structure, run the binding of `"
9532 (key-description key) "'."
9533 (when disable-when-heading-prefix
9534 (concat
9535 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9536 "back to the default binding due to limitations of Org's implementation of\n"
9537 "`" (symbol-name fun) "'.")))
9538 (interactive "p")
9539 (let* ((disable
9540 ,(and disable-when-heading-prefix
9541 '(not (string= orgstruct-heading-prefix-regexp ""))))
9542 (fallback
9543 (or disable
9544 (not
9545 (let* ,bindings
9546 (org-context-p 'headline 'item
9547 ,(when (memq fun
9548 '(org-insert-heading
9549 org-insert-heading-respect-content
9550 org-meta-return))
9551 '(when orgstruct-is-++
9552 'item-body))))))))
9553 (if fallback
9554 (let* ((orgstruct-mode)
9555 (binding
9556 (let ((key ,key))
9557 (catch 'exit
9558 (dolist
9559 (rep
9560 '(nil
9561 ("<\\([^>]*\\)tab>" . "\\1TAB")
9562 ("<\\([^>]*\\)return>" . "\\1RET")
9563 ("<\\([^>]*\\)escape>" . "\\1ESC")
9564 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9565 nil)
9566 (when rep
9567 (setq key (read-kbd-macro
9568 (let ((case-fold-search))
9569 (replace-regexp-in-string
9570 (car rep)
9571 (cdr rep)
9572 (key-description key))))))
9573 (when (key-binding key)
9574 (throw 'exit (key-binding key))))))))
9575 (if (keymapp binding)
9576 (org-set-transient-map binding)
9577 (let ((func (or binding
9578 (unless disable
9579 'orgstruct-error))))
9580 (when func
9581 (call-interactively func)))))
9582 (org-run-like-in-org-mode
9583 (lambda ()
9584 (interactive)
9585 (let* ,bindings
9586 (call-interactively ',fun)))))))))
9587 name))
9589 (defun org-contextualize-keys (alist contexts)
9590 "Return valid elements in ALIST depending on CONTEXTS.
9592 `org-agenda-custom-commands' or `org-capture-templates' are the
9593 values used for ALIST, and `org-agenda-custom-commands-contexts'
9594 or `org-capture-templates-contexts' are the associated contexts
9595 definitions."
9596 (let ((contexts
9597 ;; normalize contexts
9598 (mapcar
9599 (lambda(c) (cond ((listp (cadr c))
9600 (list (car c) (car c) (nth 1 c)))
9601 ((string= "" (cadr c))
9602 (list (car c) (car c) (nth 2 c)))
9603 (t c)))
9604 contexts))
9605 (a alist) r s)
9606 ;; loop over all commands or templates
9607 (dolist (c a)
9608 (let (vrules repl)
9609 (cond
9610 ((not (assoc (car c) contexts))
9611 (push c r))
9612 ((and (assoc (car c) contexts)
9613 (setq vrules (org-contextualize-validate-key
9614 (car c) contexts)))
9615 (mapc (lambda (vr)
9616 (unless (equal (car vr) (cadr vr))
9617 (setq repl vr)))
9618 vrules)
9619 (if (not repl) (push c r)
9620 (push (cadr repl) s)
9621 (push
9622 (cons (car c)
9623 (cdr (or (assoc (cadr repl) alist)
9624 (error "Undefined key `%s' as contextual replacement for `%s'"
9625 (cadr repl) (car c)))))
9626 r))))))
9627 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9628 (delq
9630 (delete-dups
9631 (mapcar (lambda (x)
9632 (let ((tpl (car x)))
9633 (unless (delq
9635 (mapcar (lambda (y)
9636 (equal y tpl))
9638 x)))
9639 (reverse r))))))
9641 (defun org-contextualize-validate-key (key contexts)
9642 "Check CONTEXTS for agenda or capture KEY."
9643 (let (res)
9644 (dolist (r contexts)
9645 (dolist (rr (car (last r)))
9646 (when
9647 (and (equal key (car r))
9648 (if (functionp rr) (funcall rr)
9649 (or (and (eq (car rr) 'in-file)
9650 (buffer-file-name)
9651 (string-match (cdr rr) (buffer-file-name)))
9652 (and (eq (car rr) 'in-mode)
9653 (string-match (cdr rr) (symbol-name major-mode)))
9654 (and (eq (car rr) 'in-buffer)
9655 (string-match (cdr rr) (buffer-name)))
9656 (when (and (eq (car rr) 'not-in-file)
9657 (buffer-file-name))
9658 (not (string-match (cdr rr) (buffer-file-name))))
9659 (when (eq (car rr) 'not-in-mode)
9660 (not (string-match (cdr rr) (symbol-name major-mode))))
9661 (when (eq (car rr) 'not-in-buffer)
9662 (not (string-match (cdr rr) (buffer-name)))))))
9663 (push r res))))
9664 (delete-dups (delq nil res))))
9666 (defun org-context-p (&rest contexts)
9667 "Check if local context is any of CONTEXTS.
9668 Possible values in the list of contexts are `table', `headline', and `item'."
9669 (let ((pos (point)))
9670 (goto-char (point-at-bol))
9671 (prog1 (or (and (memq 'table contexts)
9672 (looking-at "[ \t]*|"))
9673 (and (memq 'headline contexts)
9674 (looking-at org-outline-regexp))
9675 (and (memq 'item contexts)
9676 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9677 (and (memq 'item-body contexts)
9678 (org-in-item-p)))
9679 (goto-char pos))))
9681 (defconst org-unique-local-variables
9682 '(org-element--cache
9683 org-element--cache-objects
9684 org-element--cache-sync-keys
9685 org-element--cache-sync-requests
9686 org-element--cache-sync-timer)
9687 "List of local variables that cannot be transferred to another buffer.")
9689 (defun org-get-local-variables ()
9690 "Return a list of all local variables in an Org mode buffer."
9691 (delq nil
9692 (mapcar
9693 (lambda (x)
9694 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9695 (name (car binding)))
9696 (and (not (get name 'org-state))
9697 (not (memq name org-unique-local-variables))
9698 (string-match-p
9699 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9700 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9701 (symbol-name name))
9702 binding)))
9703 (with-temp-buffer
9704 (org-mode)
9705 (buffer-local-variables)))))
9707 (defun org-clone-local-variables (from-buffer &optional regexp)
9708 "Clone local variables from FROM-BUFFER.
9709 Optional argument REGEXP selects variables to clone."
9710 (dolist (pair (buffer-local-variables from-buffer))
9711 (let ((name (car pair)))
9712 (when (and (symbolp name)
9713 (not (memq name org-unique-local-variables))
9714 (or (null regexp) (string-match regexp (symbol-name name))))
9715 (set (make-local-variable name) (cdr pair))))))
9717 ;;;###autoload
9718 (defun org-run-like-in-org-mode (cmd)
9719 "Run a command, pretending that the current buffer is in Org mode.
9720 This will temporarily bind local variables that are typically bound in
9721 Org mode to the values they have in Org mode, and then interactively
9722 call CMD."
9723 (org-load-modules-maybe)
9724 (unless org-local-vars
9725 (setq org-local-vars (org-get-local-variables)))
9726 (let (binds)
9727 (dolist (var org-local-vars)
9728 (when (or (not (boundp (car var)))
9729 (eq (symbol-value (car var))
9730 (default-value (car var))))
9731 (push (list (car var) `(quote ,(cadr var))) binds)))
9732 (eval `(let ,binds
9733 (call-interactively (quote ,cmd))))))
9735 (defun org-get-category (&optional pos force-refresh)
9736 "Get the category applying to position POS."
9737 (save-match-data
9738 (when force-refresh (org-refresh-category-properties))
9739 (let ((pos (or pos (point))))
9740 (or (get-text-property pos 'org-category)
9741 (progn (org-refresh-category-properties)
9742 (get-text-property pos 'org-category))))))
9744 ;;; Refresh properties
9746 (defun org-refresh-properties (dprop tprop)
9747 "Refresh buffer text properties.
9748 DPROP is the drawer property and TPROP is either the
9749 corresponding text property to set, or an alist with each element
9750 being a text property (as a symbol) and a function to apply to
9751 the value of the drawer property."
9752 (let* ((case-fold-search t)
9753 (inhibit-read-only t)
9754 (inherit? (org-property-inherit-p dprop))
9755 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9756 (global (and inherit? (org--property-global-value dprop nil))))
9757 (org-with-silent-modifications
9758 (org-with-point-at 1
9759 ;; Set global values (e.g., values defined through
9760 ;; "#+PROPERTY:" keywords) to the whole buffer.
9761 (when global (put-text-property (point-min) (point-max) tprop global))
9762 ;; Set local values.
9763 (while (re-search-forward property-re nil t)
9764 (when (org-at-property-p)
9765 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9766 (outline-next-heading))))))
9768 (defun org-refresh-property (tprop p &optional inherit)
9769 "Refresh the buffer text property TPROP from the drawer property P.
9770 The refresh happens only for the current headline, or the whole
9771 sub-tree if optional argument INHERIT is non-nil."
9772 (unless (org-before-first-heading-p)
9773 (save-excursion
9774 (org-back-to-heading t)
9775 (let ((start (point))
9776 (end (save-excursion
9777 (if inherit (org-end-of-subtree t t)
9778 (or (outline-next-heading) (point-max))))))
9779 (if (symbolp tprop)
9780 ;; TPROP is a text property symbol.
9781 (put-text-property start end tprop p)
9782 ;; TPROP is an alist with (property . function) elements.
9783 (pcase-dolist (`(,prop . ,f) tprop)
9784 (put-text-property start end prop (funcall f p))))))))
9786 (defun org-refresh-category-properties ()
9787 "Refresh category text properties in the buffer."
9788 (let ((case-fold-search t)
9789 (inhibit-read-only t)
9790 (default-category
9791 (cond ((null org-category)
9792 (if buffer-file-name
9793 (file-name-sans-extension
9794 (file-name-nondirectory buffer-file-name))
9795 "???"))
9796 ((symbolp org-category) (symbol-name org-category))
9797 (t org-category))))
9798 (org-with-silent-modifications
9799 (org-with-wide-buffer
9800 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9801 ;; This is the default category for the buffer. If none is
9802 ;; found, fall-back to `org-category' or buffer file name.
9803 (put-text-property
9804 (point-min) (point-max)
9805 'org-category
9806 (catch 'buffer-category
9807 (goto-char (point-max))
9808 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9809 (let ((element (org-element-at-point)))
9810 (when (eq (org-element-type element) 'keyword)
9811 (throw 'buffer-category
9812 (org-element-property :value element)))))
9813 default-category))
9814 ;; Set sub-tree specific categories.
9815 (goto-char (point-min))
9816 (let ((regexp (org-re-property "CATEGORY")))
9817 (while (re-search-forward regexp nil t)
9818 (let ((value (match-string-no-properties 3)))
9819 (when (org-at-property-p)
9820 (put-text-property
9821 (save-excursion (org-back-to-heading t) (point))
9822 (save-excursion (org-end-of-subtree t t) (point))
9823 'org-category
9824 value)))))))))
9826 (defun org-refresh-stats-properties ()
9827 "Refresh stats text properties in the buffer."
9828 (org-with-silent-modifications
9829 (org-with-point-at 1
9830 (let ((regexp (concat org-outline-regexp-bol
9831 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9832 (while (re-search-forward regexp nil t)
9833 (let* ((numerator (string-to-number (match-string 1)))
9834 (denominator (and (match-end 2)
9835 (string-to-number (match-string 2))))
9836 (stats (cond ((not denominator) numerator) ;percent
9837 ((= denominator 0) 0)
9838 (t (/ (* numerator 100) denominator)))))
9839 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9840 'org-stats stats)))))))
9842 (defun org-refresh-effort-properties ()
9843 "Refresh effort properties"
9844 (org-refresh-properties
9845 org-effort-property
9846 '((effort . identity)
9847 (effort-minutes . org-duration-string-to-minutes))))
9849 ;;;; Link Stuff
9851 ;;; Link abbreviations
9853 (defun org-link-expand-abbrev (link)
9854 "Apply replacements as defined in `org-link-abbrev-alist'."
9855 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9856 (let* ((key (match-string 1 link))
9857 (as (or (assoc key org-link-abbrev-alist-local)
9858 (assoc key org-link-abbrev-alist)))
9859 (tag (and (match-end 2) (match-string 3 link)))
9860 rpl)
9861 (if (not as)
9862 link
9863 (setq rpl (cdr as))
9864 (cond
9865 ((symbolp rpl) (funcall rpl tag))
9866 ((string-match "%(\\([^)]+\\))" rpl)
9867 (replace-match
9868 (save-match-data
9869 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9870 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9871 ((string-match "%h" rpl)
9872 (replace-match (url-hexify-string (or tag "")) t t rpl))
9873 (t (concat rpl tag)))))
9874 link))
9876 ;;; Storing and inserting links
9878 (defvar org-insert-link-history nil
9879 "Minibuffer history for links inserted with `org-insert-link'.")
9881 (defvar org-stored-links nil
9882 "Contains the links stored with `org-store-link'.")
9884 (defvar org-store-link-plist nil
9885 "Plist with info about the most recently link created with `org-store-link'.")
9887 (defun org-store-link-functions ()
9888 "Return a list of functions that are called to create and store a link.
9889 The functions defined in the :store property of
9890 `org-link-parameters'.
9892 Each function will be called in turn until one returns a non-nil
9893 value. Each function should check if it is responsible for
9894 creating this link (for example by looking at the major mode).
9895 If not, it must exit and return nil. If yes, it should return
9896 a non-nil value after calling `org-store-link-props' with a list
9897 of properties and values. Special properties are:
9899 :type The link prefix, like \"http\". This must be given.
9900 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9901 This is obligatory as well.
9902 :description Optional default description for the second pair
9903 of brackets in an Org mode link. The user can still change
9904 this when inserting this link into an Org mode buffer.
9906 In addition to these, any additional properties can be specified
9907 and then used in capture templates."
9908 (cl-loop for link in org-link-parameters
9909 with store-func
9910 do (setq store-func (org-link-get-parameter (car link) :store))
9911 if store-func
9912 collect store-func))
9914 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9915 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9917 ;;;###autoload
9918 (defun org-store-link (arg)
9919 "Store an org-link to the current location.
9920 \\<org-mode-map>
9921 This link is added to `org-stored-links' and can later be inserted
9922 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9924 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9925 A single
9926 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9927 `org-gnus-prefer-web-links' for links to Usenet articles.
9929 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9930 skipping storing functions that are not
9931 part of Org core.
9933 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9934 prefix ARG forces storing a link for each line in the
9935 active region."
9936 (interactive "P")
9937 (org-load-modules-maybe)
9938 (if (and (equal arg '(64)) (org-region-active-p))
9939 (save-excursion
9940 (let ((end (region-end)))
9941 (goto-char (region-beginning))
9942 (set-mark (point))
9943 (while (< (point-at-eol) end)
9944 (move-end-of-line 1) (activate-mark)
9945 (let (current-prefix-arg)
9946 (call-interactively 'org-store-link))
9947 (move-beginning-of-line 2)
9948 (set-mark (point)))))
9949 (setq org-store-link-plist nil)
9950 (let (link cpltxt desc description search
9951 txt custom-id agenda-link sfuns sfunsn)
9952 (cond
9954 ;; Store a link using an external link type
9955 ((and (not (equal arg '(16)))
9956 (setq sfuns
9957 (delq
9958 nil (mapcar (lambda (f)
9959 (let (fs) (if (funcall f) (push f fs))))
9960 (org-store-link-functions)))
9961 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9962 (or (and (cdr sfuns)
9963 (funcall (intern
9964 (completing-read
9965 "Which function for creating the link? "
9966 sfunsn nil t (car sfunsn)))))
9967 (funcall (caar sfuns)))
9968 (setq link (plist-get org-store-link-plist :link)
9969 desc (or (plist-get org-store-link-plist
9970 :description)
9971 link))))
9973 ;; Store a link from a source code buffer.
9974 ((org-src-edit-buffer-p)
9975 (let ((coderef-format (org-src-coderef-format)))
9976 (cond ((save-excursion
9977 (beginning-of-line)
9978 (looking-at (org-src-coderef-regexp coderef-format)))
9979 (setq link (format "(%s)" (match-string-no-properties 3))))
9980 ((called-interactively-p 'any)
9981 (let ((label (read-string "Code line label: ")))
9982 (end-of-line)
9983 (setq link (format coderef-format label))
9984 (let ((gc (- 79 (length link))))
9985 (if (< (current-column) gc)
9986 (org-move-to-column gc t)
9987 (insert " ")))
9988 (insert link)
9989 (setq link (concat "(" label ")"))
9990 (setq desc nil)))
9991 (t (setq link nil)))))
9993 ;; We are in the agenda, link to referenced location
9994 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9995 (let ((m (or (get-text-property (point) 'org-hd-marker)
9996 (get-text-property (point) 'org-marker))))
9997 (when m
9998 (org-with-point-at m
9999 (setq agenda-link
10000 (if (called-interactively-p 'any)
10001 (call-interactively 'org-store-link)
10002 (org-store-link nil)))))))
10004 ((eq major-mode 'calendar-mode)
10005 (let ((cd (calendar-cursor-to-date)))
10006 (setq link
10007 (format-time-string
10008 (car org-time-stamp-formats)
10009 (apply 'encode-time
10010 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
10011 nil nil nil))))
10012 (org-store-link-props :type "calendar" :date cd)))
10014 ((eq major-mode 'help-mode)
10015 (setq link (concat "help:" (save-excursion
10016 (goto-char (point-min))
10017 (looking-at "^[^ ]+")
10018 (match-string 0))))
10019 (org-store-link-props :type "help"))
10021 ((eq major-mode 'w3-mode)
10022 (setq cpltxt (if (and (buffer-name)
10023 (not (string-match "Untitled" (buffer-name))))
10024 (buffer-name)
10025 (url-view-url t))
10026 link (url-view-url t))
10027 (org-store-link-props :type "w3" :url (url-view-url t)))
10029 ((eq major-mode 'image-mode)
10030 (setq cpltxt (concat "file:"
10031 (abbreviate-file-name buffer-file-name))
10032 link cpltxt)
10033 (org-store-link-props :type "image" :file buffer-file-name))
10035 ;; In dired, store a link to the file of the current line
10036 ((derived-mode-p 'dired-mode)
10037 (let ((file (dired-get-filename nil t)))
10038 (setq file (if file
10039 (abbreviate-file-name
10040 (expand-file-name (dired-get-filename nil t)))
10041 ;; otherwise, no file so use current directory.
10042 default-directory))
10043 (setq cpltxt (concat "file:" file)
10044 link cpltxt)))
10046 ((setq search (run-hook-with-args-until-success
10047 'org-create-file-search-functions))
10048 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
10049 "::" search))
10050 (setq cpltxt (or description link)))
10052 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
10053 (org-with-limited-levels
10054 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
10055 (cond
10056 ;; Store a link using the target at point
10057 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
10058 (setq cpltxt
10059 (concat "file:"
10060 (abbreviate-file-name
10061 (buffer-file-name (buffer-base-buffer)))
10062 "::" (match-string 1))
10063 link cpltxt))
10064 ((and (featurep 'org-id)
10065 (or (eq org-id-link-to-org-use-id t)
10066 (and (called-interactively-p 'any)
10067 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
10068 (and (eq org-id-link-to-org-use-id
10069 'create-if-interactive-and-no-custom-id)
10070 (not custom-id))))
10071 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
10072 ;; Store a link using the ID at point
10073 (setq link (condition-case nil
10074 (prog1 (org-id-store-link)
10075 (setq desc (or (plist-get org-store-link-plist
10076 :description)
10077 "")))
10078 (error
10079 ;; Probably before first headline, link only to file
10080 (concat "file:"
10081 (abbreviate-file-name
10082 (buffer-file-name (buffer-base-buffer))))))))
10084 ;; Just link to current headline
10085 (setq cpltxt (concat "file:"
10086 (abbreviate-file-name
10087 (buffer-file-name (buffer-base-buffer)))))
10088 ;; Add a context search string
10089 (when (org-xor org-context-in-file-links
10090 (equal arg '(4)))
10091 (let* ((element (org-element-at-point))
10092 (name (org-element-property :name element)))
10093 (setq txt (cond
10094 ((org-at-heading-p) nil)
10095 (name)
10096 ((org-region-active-p)
10097 (buffer-substring (region-beginning) (region-end)))))
10098 (when (or (null txt) (string-match "\\S-" txt))
10099 (setq cpltxt
10100 (concat cpltxt "::"
10101 (condition-case nil
10102 (org-make-org-heading-search-string txt)
10103 (error "")))
10104 desc (or name
10105 (nth 4 (ignore-errors (org-heading-components)))
10106 "NONE")))))
10107 (when (string-match "::\\'" cpltxt)
10108 (setq cpltxt (substring cpltxt 0 -2)))
10109 (setq link cpltxt)))))
10111 ((buffer-file-name (buffer-base-buffer))
10112 ;; Just link to this file here.
10113 (setq cpltxt (concat "file:"
10114 (abbreviate-file-name
10115 (buffer-file-name (buffer-base-buffer)))))
10116 ;; Add a context string.
10117 (when (org-xor org-context-in-file-links
10118 (equal arg '(4)))
10119 (setq txt (if (org-region-active-p)
10120 (buffer-substring (region-beginning) (region-end))
10121 (buffer-substring (point-at-bol) (point-at-eol))))
10122 ;; Only use search option if there is some text.
10123 (when (string-match "\\S-" txt)
10124 (setq cpltxt
10125 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10126 desc "NONE")))
10127 (setq link cpltxt))
10129 ((called-interactively-p 'interactive)
10130 (user-error "No method for storing a link from this buffer"))
10132 (t (setq link nil)))
10134 ;; We're done setting link and desc, clean up
10135 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10136 (setq link (or link cpltxt)
10137 desc (or desc cpltxt))
10138 (cond ((not desc))
10139 ((equal desc "NONE") (setq desc nil))
10140 (t (setq desc
10141 (replace-regexp-in-string
10142 org-bracket-link-analytic-regexp
10143 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10144 desc))))
10145 ;; Return the link
10146 (if (not (and (or (called-interactively-p 'any)
10147 executing-kbd-macro)
10148 link))
10149 (or agenda-link (and link (org-make-link-string link desc)))
10150 (push (list link desc) org-stored-links)
10151 (message "Stored: %s" (or desc link))
10152 (when custom-id
10153 (setq link (concat "file:" (abbreviate-file-name
10154 (buffer-file-name)) "::#" custom-id))
10155 (push (list link desc) org-stored-links))
10156 (car org-stored-links)))))
10158 (defun org-store-link-props (&rest plist)
10159 "Store link properties, extract names, addresses and dates."
10160 (let ((x (plist-get plist :from)))
10161 (when x
10162 (let ((adr (mail-extract-address-components x)))
10163 (setq plist (plist-put plist :fromname (car adr)))
10164 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10165 (let ((x (plist-get plist :to)))
10166 (when x
10167 (let ((adr (mail-extract-address-components x)))
10168 (setq plist (plist-put plist :toname (car adr)))
10169 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10170 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10171 (when x
10172 (setq plist (plist-put plist :date-timestamp
10173 (format-time-string
10174 (org-time-stamp-format t) x)))
10175 (setq plist (plist-put plist :date-timestamp-inactive
10176 (format-time-string
10177 (org-time-stamp-format t t) x)))))
10178 (let ((from (plist-get plist :from))
10179 (to (plist-get plist :to)))
10180 (when (and from to org-from-is-user-regexp)
10181 (setq plist
10182 (plist-put plist :fromto
10183 (if (string-match org-from-is-user-regexp from)
10184 (concat "to %t")
10185 (concat "from %f"))))))
10186 (setq org-store-link-plist plist))
10188 (defun org-add-link-props (&rest plist)
10189 "Add these properties to the link property list."
10190 (let (key value)
10191 (while plist
10192 (setq key (pop plist) value (pop plist))
10193 (setq org-store-link-plist
10194 (plist-put org-store-link-plist key value)))))
10196 (defun org-email-link-description (&optional fmt)
10197 "Return the description part of an email link.
10198 This takes information from `org-store-link-plist' and formats it
10199 according to FMT (default from `org-email-link-description-format')."
10200 (setq fmt (or fmt org-email-link-description-format))
10201 (let* ((p org-store-link-plist)
10202 (to (plist-get p :toaddress))
10203 (from (plist-get p :fromaddress))
10204 (table
10205 (list
10206 (cons "%c" (plist-get p :fromto))
10207 (cons "%F" (plist-get p :from))
10208 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10209 (cons "%T" (plist-get p :to))
10210 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10211 (cons "%s" (plist-get p :subject))
10212 (cons "%d" (plist-get p :date))
10213 (cons "%m" (plist-get p :message-id)))))
10214 (when (string-match "%c" fmt)
10215 ;; Check if the user wrote this message
10216 (if (and org-from-is-user-regexp from to
10217 (save-match-data (string-match org-from-is-user-regexp from)))
10218 (setq fmt (replace-match "to %t" t t fmt))
10219 (setq fmt (replace-match "from %f" t t fmt))))
10220 (org-replace-escapes fmt table)))
10222 (defun org-make-org-heading-search-string (&optional string)
10223 "Make search string for the current headline or STRING."
10224 (let ((s (or string
10225 (and (derived-mode-p 'org-mode)
10226 (save-excursion
10227 (org-back-to-heading t)
10228 (org-element-property :raw-value (org-element-at-point))))))
10229 (lines org-context-in-file-links))
10230 (or string (setq s (concat "*" s))) ; Add * for headlines
10231 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10232 (when (and string (integerp lines) (> lines 0))
10233 (let ((slines (org-split-string s "\n")))
10234 (when (< lines (length slines))
10235 (setq s (mapconcat
10236 'identity
10237 (reverse (nthcdr (- (length slines) lines)
10238 (reverse slines))) "\n")))))
10239 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10241 (defun org-make-link-string (link &optional description)
10242 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10243 (unless (org-string-nw-p link) (error "Empty link"))
10244 (let ((uri (cond ((string-match org-link-types-re link)
10245 (concat (match-string 1 link)
10246 (org-link-escape (substring link (match-end 1)))))
10247 ;; For readability, url-encode internal links only
10248 ;; when absolutely needed (i.e, when they contain
10249 ;; square brackets). File links however, are
10250 ;; encoded since, e.g., spaces are significant.
10251 ((or (file-name-absolute-p link)
10252 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10253 (org-link-escape link))
10254 (t link)))
10255 (description
10256 (and (org-string-nw-p description)
10257 ;; Remove brackets from description, as they are fatal.
10258 (replace-regexp-in-string
10259 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10260 (org-trim description)))))
10261 (format "[[%s]%s]"
10263 (if description (format "[%s]" description) ""))))
10265 (defconst org-link-escape-chars
10266 ;;%20 %5B %5D %25
10267 '(?\s ?\[ ?\] ?%)
10268 "List of characters that should be escaped in a link when stored to Org.
10269 This is the list that is used for internal purposes.")
10271 (defun org-link-escape (text &optional table merge)
10272 "Return percent escaped representation of TEXT.
10273 TEXT is a string with the text to escape.
10274 Optional argument TABLE is a list with characters that should be
10275 escaped. When nil, `org-link-escape-chars' is used.
10276 If optional argument MERGE is set, merge TABLE into
10277 `org-link-escape-chars'."
10278 (let ((characters-to-encode
10279 (cond ((null table) org-link-escape-chars)
10280 (merge (append org-link-escape-chars table))
10281 (t table))))
10282 (mapconcat
10283 (lambda (c)
10284 (if (or (memq c characters-to-encode)
10285 (and org-url-hexify-p (or (< c 32) (> c 126))))
10286 (mapconcat (lambda (e) (format "%%%.2X" e))
10287 (or (encode-coding-char c 'utf-8)
10288 (error "Unable to percent escape character: %c" c))
10290 (char-to-string c)))
10291 text "")))
10293 (defun org-link-unescape (str)
10294 "Unhex hexified Unicode parts in string STR.
10295 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10296 reciprocal of `org-link-escape', which see."
10297 (if (org-string-nw-p str)
10298 (replace-regexp-in-string
10299 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10300 str))
10302 (defun org-link-unescape-compound (hex)
10303 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10304 Note: this function also decodes single byte encodings like
10305 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10306 (save-match-data
10307 (let* ((bytes (cdr (split-string hex "%")))
10308 (ret "")
10309 (eat 0)
10310 (sum 0))
10311 (while bytes
10312 (let* ((val (string-to-number (pop bytes) 16))
10313 (shift-xor
10314 (if (= 0 eat)
10315 (cond
10316 ((>= val 252) (cons 6 252))
10317 ((>= val 248) (cons 5 248))
10318 ((>= val 240) (cons 4 240))
10319 ((>= val 224) (cons 3 224))
10320 ((>= val 192) (cons 2 192))
10321 (t (cons 0 0)))
10322 (cons 6 128))))
10323 (when (>= val 192) (setq eat (car shift-xor)))
10324 (setq val (logxor val (cdr shift-xor)))
10325 (setq sum (+ (lsh sum (car shift-xor)) val))
10326 (when (> eat 0) (setq eat (- eat 1)))
10327 (cond
10328 ((= 0 eat) ;multi byte
10329 (setq ret (concat ret (char-to-string sum)))
10330 (setq sum 0))
10331 ((not bytes) ; single byte(s)
10332 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10333 ret)))
10335 (defun org-link-unescape-single-byte-sequence (hex)
10336 "Unhexify hex-encoded single byte character sequences."
10337 (mapconcat (lambda (byte)
10338 (char-to-string (string-to-number byte 16)))
10339 (cdr (split-string hex "%")) ""))
10341 (defun org-xor (a b)
10342 "Exclusive or."
10343 (if a (not b) b))
10345 (defun org-fixup-message-id-for-http (s)
10346 "Replace special characters in a message id, so it can be used in an http query."
10347 (when (string-match "%" s)
10348 (setq s (mapconcat (lambda (c)
10349 (if (eq c ?%)
10350 "%25"
10351 (char-to-string c)))
10352 s "")))
10353 (while (string-match "<" s)
10354 (setq s (replace-match "%3C" t t s)))
10355 (while (string-match ">" s)
10356 (setq s (replace-match "%3E" t t s)))
10357 (while (string-match "@" s)
10358 (setq s (replace-match "%40" t t s)))
10361 (defun org-link-prettify (link)
10362 "Return a human-readable representation of LINK.
10363 The car of LINK must be a raw link.
10364 The cdr of LINK must be either a link description or nil."
10365 (let ((desc (or (cadr link) "<no description>")))
10366 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10367 "<" (car link) ">")))
10369 ;;;###autoload
10370 (defun org-insert-link-global ()
10371 "Insert a link like Org mode does.
10372 This command can be called in any mode to insert a link in Org syntax."
10373 (interactive)
10374 (org-load-modules-maybe)
10375 (org-run-like-in-org-mode 'org-insert-link))
10377 (defun org-insert-all-links (arg &optional pre post)
10378 "Insert all links in `org-stored-links'.
10379 When a universal prefix, do not delete the links from `org-stored-links'.
10380 When `ARG' is a number, insert the last N link(s).
10381 `PRE' and `POST' are optional arguments to define a string to
10382 prepend or to append."
10383 (interactive "P")
10384 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10385 (links (copy-sequence org-stored-links))
10386 (pr (or pre "- "))
10387 (po (or post "\n"))
10388 (cnt 1) l)
10389 (if (null org-stored-links)
10390 (message "No link to insert")
10391 (while (and (or (listp arg) (>= arg cnt))
10392 (setq l (if (listp arg)
10393 (pop links)
10394 (pop org-stored-links))))
10395 (setq cnt (1+ cnt))
10396 (insert pr)
10397 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10398 (insert po)))))
10400 (defun org-insert-last-stored-link (arg)
10401 "Insert the last link stored in `org-stored-links'."
10402 (interactive "p")
10403 (org-insert-all-links arg "" "\n"))
10405 (defun org-link-fontify-links-to-this-file ()
10406 "Fontify links to the current file in `org-stored-links'."
10407 (let ((f (buffer-file-name)) a b)
10408 (setq a (mapcar (lambda(l)
10409 (let ((ll (car l)))
10410 (when (and (string-match "^file:\\(.+\\)::" ll)
10411 (equal f (expand-file-name (match-string 1 ll))))
10412 ll)))
10413 org-stored-links))
10414 (when (featurep 'org-id)
10415 (setq b (mapcar (lambda(l)
10416 (let ((ll (car l)))
10417 (when (and (string-match "^id:\\(.+\\)$" ll)
10418 (equal f (expand-file-name
10419 (or (org-id-find-id-file
10420 (match-string 1 ll)) ""))))
10421 ll)))
10422 org-stored-links)))
10423 (mapcar (lambda(l)
10424 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10425 (delq nil (append a b)))))
10427 (defvar org--links-history nil)
10428 (defun org-insert-link (&optional complete-file link-location default-description)
10429 "Insert a link. At the prompt, enter the link.
10431 Completion can be used to insert any of the link protocol prefixes in use.
10433 The history can be used to select a link previously stored with
10434 `org-store-link'. When the empty string is entered (i.e. if you just
10435 press `RET' at the prompt), the link defaults to the most recently
10436 stored link. As `SPC' triggers completion in the minibuffer, you need to
10437 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10439 You will also be prompted for a description, and if one is given, it will
10440 be displayed in the buffer instead of the link.
10442 If there is already a link at point, this command will allow you to edit
10443 link and description parts.
10445 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10446 file name can be
10447 selected using completion. The path to the file will be relative to the
10448 current directory if the file is in the current directory or a subdirectory.
10449 Otherwise, the link will be the absolute path as completed in the minibuffer
10450 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10451 option `org-link-file-path-type'.
10453 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10454 absolute path even if the file is in
10455 the current directory or below.
10457 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10458 prefix negates `org-keep-stored-link-after-insertion'.
10460 If `org-make-link-description-function' is non-nil, this function will be
10461 called with the link target, and the result will be the default
10462 link description.
10464 If the LINK-LOCATION parameter is non-nil, this value will be used as
10465 the link location instead of reading one interactively.
10467 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10468 as the default description."
10469 (interactive "P")
10470 (let* ((wcf (current-window-configuration))
10471 (origbuf (current-buffer))
10472 (region (when (org-region-active-p)
10473 (buffer-substring (region-beginning) (region-end))))
10474 (remove (and region (list (region-beginning) (region-end))))
10475 (desc region)
10476 (link link-location)
10477 (abbrevs org-link-abbrev-alist-local)
10478 entry all-prefixes auto-desc)
10479 (cond
10480 (link-location) ; specified by arg, just use it.
10481 ((org-in-regexp org-bracket-link-regexp 1)
10482 ;; We do have a link at point, and we are going to edit it.
10483 (setq remove (list (match-beginning 0) (match-end 0)))
10484 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10485 (setq link (read-string "Link: "
10486 (org-link-unescape
10487 (match-string-no-properties 1)))))
10488 ((or (org-in-regexp org-angle-link-re)
10489 (org-in-regexp org-plain-link-re))
10490 ;; Convert to bracket link
10491 (setq remove (list (match-beginning 0) (match-end 0))
10492 link (read-string "Link: "
10493 (org-unbracket-string "<" ">" (match-string 0)))))
10494 ((member complete-file '((4) (16)))
10495 ;; Completing read for file names.
10496 (setq link (org-file-complete-link complete-file)))
10498 ;; Read link, with completion for stored links.
10499 (org-link-fontify-links-to-this-file)
10500 (org-switch-to-buffer-other-window "*Org Links*")
10501 (with-current-buffer "*Org Links*"
10502 (erase-buffer)
10503 (insert "Insert a link.
10504 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10505 (when org-stored-links
10506 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10507 (insert (mapconcat 'org-link-prettify
10508 (reverse org-stored-links) "\n")))
10509 (goto-char (point-min)))
10510 (let ((cw (selected-window)))
10511 (select-window (get-buffer-window "*Org Links*" 'visible))
10512 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10513 (unless (pos-visible-in-window-p (point-max))
10514 (org-fit-window-to-buffer))
10515 (and (window-live-p cw) (select-window cw)))
10516 (setq all-prefixes (append (mapcar 'car abbrevs)
10517 (mapcar 'car org-link-abbrev-alist)
10518 (org-link-types)))
10519 (unwind-protect
10520 ;; Fake a link history, containing the stored links.
10521 (let ((org--links-history
10522 (append (mapcar #'car org-stored-links)
10523 org-insert-link-history)))
10524 (setq link
10525 (org-completing-read
10526 "Link: "
10527 (append
10528 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10529 (mapcar #'car org-stored-links))
10530 nil nil nil
10531 'org--links-history
10532 (caar org-stored-links)))
10533 (unless (org-string-nw-p link) (user-error "No link selected"))
10534 (dolist (l org-stored-links)
10535 (when (equal link (cadr l))
10536 (setq link (car l))
10537 (setq auto-desc t)))
10538 (when (or (member link all-prefixes)
10539 (and (equal ":" (substring link -1))
10540 (member (substring link 0 -1) all-prefixes)
10541 (setq link (substring link 0 -1))))
10542 (setq link (with-current-buffer origbuf
10543 (org-link-try-special-completion link)))))
10544 (set-window-configuration wcf)
10545 (kill-buffer "*Org Links*"))
10546 (setq entry (assoc link org-stored-links))
10547 (or entry (push link org-insert-link-history))
10548 (setq desc (or desc (nth 1 entry)))))
10550 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10551 (not org-keep-stored-link-after-insertion))
10552 (setq org-stored-links (delq (assoc link org-stored-links)
10553 org-stored-links)))
10555 (when (and (string-match org-plain-link-re link)
10556 (not (string-match org-ts-regexp link)))
10557 ;; URL-like link, normalize the use of angular brackets.
10558 (setq link (org-unbracket-string "<" ">" link)))
10560 ;; Check if we are linking to the current file with a search
10561 ;; option If yes, simplify the link by using only the search
10562 ;; option.
10563 (when (and buffer-file-name
10564 (let ((case-fold-search nil))
10565 (string-match "\\`file:\\(.+?\\)::" link)))
10566 (let ((path (match-string-no-properties 1 link))
10567 (search (substring-no-properties link (match-end 0))))
10568 (save-match-data
10569 (when (equal (file-truename buffer-file-name) (file-truename path))
10570 ;; We are linking to this same file, with a search option
10571 (setq link search)))))
10573 ;; Check if we can/should use a relative path. If yes, simplify the link
10574 (let ((case-fold-search nil))
10575 (when (string-match "\\`\\(file\\|docview\\):" link)
10576 (let* ((type (match-string-no-properties 0 link))
10577 (path (substring-no-properties link (match-end 0)))
10578 (origpath path))
10579 (cond
10580 ((or (eq org-link-file-path-type 'absolute)
10581 (equal complete-file '(16)))
10582 (setq path (abbreviate-file-name (expand-file-name path))))
10583 ((eq org-link-file-path-type 'noabbrev)
10584 (setq path (expand-file-name path)))
10585 ((eq org-link-file-path-type 'relative)
10586 (setq path (file-relative-name path)))
10588 (save-match-data
10589 (if (string-match (concat "^" (regexp-quote
10590 (expand-file-name
10591 (file-name-as-directory
10592 default-directory))))
10593 (expand-file-name path))
10594 ;; We are linking a file with relative path name.
10595 (setq path (substring (expand-file-name path)
10596 (match-end 0)))
10597 (setq path (abbreviate-file-name (expand-file-name path)))))))
10598 (setq link (concat type path))
10599 (when (equal desc origpath)
10600 (setq desc path)))))
10602 (if org-make-link-description-function
10603 (setq desc
10604 (or (condition-case nil
10605 (funcall org-make-link-description-function link desc)
10606 (error (progn (message "Can't get link description from `%s'"
10607 (symbol-name org-make-link-description-function))
10608 (sit-for 2) nil)))
10609 (read-string "Description: " default-description)))
10610 (if default-description (setq desc default-description)
10611 (setq desc (or (and auto-desc desc)
10612 (read-string "Description: " desc)))))
10614 (unless (string-match "\\S-" desc) (setq desc nil))
10615 (when remove (apply 'delete-region remove))
10616 (insert (org-make-link-string link desc))
10617 ;; Redisplay so as the new link has proper invisible characters.
10618 (sit-for 0)))
10620 (defun org-link-try-special-completion (type)
10621 "If there is completion support for link type TYPE, offer it."
10622 (let ((fun (org-link-get-parameter type :complete)))
10623 (if (functionp fun)
10624 (funcall fun)
10625 (read-string "Link (no completion support): " (concat type ":")))))
10627 (defun org-file-complete-link (&optional arg)
10628 "Create a file link using completion."
10629 (let ((file (read-file-name "File: "))
10630 (pwd (file-name-as-directory (expand-file-name ".")))
10631 (pwd1 (file-name-as-directory (abbreviate-file-name
10632 (expand-file-name ".")))))
10633 (cond ((equal arg '(16))
10634 (concat "file:"
10635 (abbreviate-file-name (expand-file-name file))))
10636 ((string-match
10637 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10638 (concat "file:" (match-string 1 file)))
10639 ((string-match
10640 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10641 (expand-file-name file))
10642 (concat "file:"
10643 (match-string 1 (expand-file-name file))))
10644 (t (concat "file:" file)))))
10646 (defun org-completing-read (&rest args)
10647 "Completing-read with SPACE being a normal character."
10648 (let ((enable-recursive-minibuffers t)
10649 (minibuffer-local-completion-map
10650 (copy-keymap minibuffer-local-completion-map)))
10651 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10652 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10653 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10654 'org-time-stamp-inactive)
10655 (apply #'completing-read args)))
10657 ;;; Opening/following a link
10659 (defvar org-link-search-failed nil)
10661 (defvar org-open-link-functions nil
10662 "Hook for functions finding a plain text link.
10663 These functions must take a single argument, the link content.
10664 They will be called for links that look like [[link text][description]]
10665 when LINK TEXT does not have a protocol like \"http:\" and does not look
10666 like a filename (e.g. \"./blue.png\").
10668 These functions will be called *before* Org attempts to resolve the
10669 link by doing text searches in the current buffer - so if you want a
10670 link \"[[target]]\" to still find \"<<target>>\", your function should
10671 handle this as a special case.
10673 When the function does handle the link, it must return a non-nil value.
10674 If it decides that it is not responsible for this link, it must return
10675 nil to indicate that that Org can continue with other options like
10676 exact and fuzzy text search.")
10678 (defun org-next-link (&optional search-backward)
10679 "Move forward to the next link.
10680 If the link is in hidden text, expose it."
10681 (interactive "P")
10682 (when (and org-link-search-failed (eq this-command last-command))
10683 (goto-char (point-min))
10684 (message "Link search wrapped back to beginning of buffer"))
10685 (setq org-link-search-failed nil)
10686 (let* ((pos (point))
10687 (ct (org-context))
10688 (a (assq :link ct))
10689 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10690 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10691 ((looking-at org-any-link-re)
10692 ;; Don't stay stuck at link without an org-link face
10693 (forward-char (if search-backward -1 1))))
10694 (if (funcall srch-fun org-any-link-re nil t)
10695 (progn
10696 (goto-char (match-beginning 0))
10697 (when (outline-invisible-p) (org-show-context)))
10698 (goto-char pos)
10699 (setq org-link-search-failed t)
10700 (message "No further link found"))))
10702 (defun org-previous-link ()
10703 "Move backward to the previous link.
10704 If the link is in hidden text, expose it."
10705 (interactive)
10706 (funcall 'org-next-link t))
10708 (defun org-translate-link (s)
10709 "Translate a link string if a translation function has been defined."
10710 (with-temp-buffer
10711 (insert (org-trim s))
10712 (org-trim (org-element-interpret-data (org-element-context)))))
10714 (defun org-translate-link-from-planner (type path)
10715 "Translate a link from Emacs Planner syntax so that Org can follow it.
10716 This is still an experimental function, your mileage may vary."
10717 (cond
10718 ((member type '("http" "https" "news" "ftp"))
10719 ;; standard Internet links are the same.
10720 nil)
10721 ((and (equal type "irc") (string-match "^//" path))
10722 ;; Planner has two / at the beginning of an irc link, we have 1.
10723 ;; We should have zero, actually....
10724 (setq path (substring path 1)))
10725 ((and (equal type "lisp") (string-match "^/" path))
10726 ;; Planner has a slash, we do not.
10727 (setq type "elisp" path (substring path 1)))
10728 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10729 ;; A typical message link. Planner has the id after the final slash,
10730 ;; we separate it with a hash mark
10731 (setq path (concat (match-string 1 path) "#"
10732 (org-unbracket-string "<" ">" (match-string 2 path))))))
10733 (cons type path))
10735 (defun org-find-file-at-mouse (ev)
10736 "Open file link or URL at mouse."
10737 (interactive "e")
10738 (mouse-set-point ev)
10739 (org-open-at-point 'in-emacs))
10741 (defun org-open-at-mouse (ev)
10742 "Open file link or URL at mouse.
10743 See the docstring of `org-open-file' for details."
10744 (interactive "e")
10745 (mouse-set-point ev)
10746 (when (eq major-mode 'org-agenda-mode)
10747 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10748 (org-open-at-point))
10750 (defvar org-window-config-before-follow-link nil
10751 "The window configuration before following a link.
10752 This is saved in case the need arises to restore it.")
10754 ;;;###autoload
10755 (defun org-open-at-point-global ()
10756 "Follow a link or time-stamp like Org mode does.
10757 This command can be called in any mode to follow an external link
10758 or a time-stamp that has Org mode syntax. Its behavior is
10759 undefined when called on internal links (e.g., fuzzy links).
10760 Raise an error when there is nothing to follow. "
10761 (interactive)
10762 (cond ((org-in-regexp org-any-link-re)
10763 (org-open-link-from-string (match-string-no-properties 0)))
10764 ((or (org-in-regexp org-ts-regexp-both nil t)
10765 (org-in-regexp org-tsr-regexp-both nil t))
10766 (org-follow-timestamp-link))
10767 (t (user-error "No link found"))))
10769 ;;;###autoload
10770 (defun org-open-link-from-string (s &optional arg reference-buffer)
10771 "Open a link in the string S, as if it was in Org mode."
10772 (interactive "sLink: \nP")
10773 (let ((reference-buffer (or reference-buffer (current-buffer))))
10774 (with-temp-buffer
10775 (let ((org-inhibit-startup (not reference-buffer)))
10776 (org-mode)
10777 (insert s)
10778 (goto-char (point-min))
10779 (when reference-buffer
10780 (setq org-link-abbrev-alist-local
10781 (with-current-buffer reference-buffer
10782 org-link-abbrev-alist-local)))
10783 (org-open-at-point arg reference-buffer)))))
10785 (defvar org-open-at-point-functions nil
10786 "Hook that is run when following a link at point.
10788 Functions in this hook must return t if they identify and follow
10789 a link at point. If they don't find anything interesting at point,
10790 they must return nil.")
10792 (defvar org-link-search-inhibit-query nil)
10793 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10794 (defun org--open-doi-link (path)
10795 "Open a \"doi\" type link.
10796 PATH is a the path to search for, as a string."
10797 (browse-url (url-encode-url (concat org-doi-server-url path))))
10799 (defun org--open-elisp-link (path)
10800 "Open a \"elisp\" type link.
10801 PATH is the sexp to evaluate, as a string."
10802 (let ((cmd path))
10803 (if (or (and (org-string-nw-p
10804 org-confirm-elisp-link-not-regexp)
10805 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10806 (not org-confirm-elisp-link-function)
10807 (funcall org-confirm-elisp-link-function
10808 (format "Execute \"%s\" as elisp? "
10809 (org-add-props cmd nil 'face 'org-warning))))
10810 (message "%s => %s" cmd
10811 (if (eq (string-to-char cmd) ?\()
10812 (eval (read cmd))
10813 (call-interactively (read cmd))))
10814 (user-error "Abort"))))
10816 (defun org--open-help-link (path)
10817 "Open a \"help\" type link.
10818 PATH is a symbol name, as a string."
10819 (pcase (intern path)
10820 ((and (pred fboundp) variable) (describe-function variable))
10821 ((and (pred boundp) function) (describe-variable function))
10822 (name (user-error "Unknown function or variable: %s" name))))
10824 (defun org--open-shell-link (path)
10825 "Open a \"shell\" type link.
10826 PATH is the command to execute, as a string."
10827 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10828 (cmd path))
10829 (if (or (and (org-string-nw-p
10830 org-confirm-shell-link-not-regexp)
10831 (string-match
10832 org-confirm-shell-link-not-regexp cmd))
10833 (not org-confirm-shell-link-function)
10834 (funcall org-confirm-shell-link-function
10835 (format "Execute \"%s\" in shell? "
10836 (org-add-props cmd nil
10837 'face 'org-warning))))
10838 (progn
10839 (message "Executing %s" cmd)
10840 (shell-command cmd buf)
10841 (when (featurep 'midnight)
10842 (setq clean-buffer-list-kill-buffer-names
10843 (cons (buffer-name buf)
10844 clean-buffer-list-kill-buffer-names))))
10845 (user-error "Abort"))))
10847 (defun org-open-at-point (&optional arg reference-buffer)
10848 "Open link, timestamp, footnote or tags at point.
10850 When point is on a link, follow it. Normally, files will be
10851 opened by an appropriate application. If the optional prefix
10852 argument ARG is non-nil, Emacs will visit the file. With
10853 a double prefix argument, try to open outside of Emacs, in the
10854 application the system uses for this file type.
10856 When point is on a timestamp, open the agenda at the day
10857 specified.
10859 When point is a footnote definition, move to the first reference
10860 found. If it is on a reference, move to the associated
10861 definition.
10863 When point is on a headline, display a list of every link in the
10864 entry, so it is possible to pick one, or all, of them. If point
10865 is on a tag, call `org-tags-view' instead.
10867 When optional argument REFERENCE-BUFFER is non-nil, it should
10868 specify a buffer from where the link search should happen. This
10869 is used internally by `org-open-link-from-string'.
10871 On top of syntactically correct links, this function will open
10872 the link at point in comments or comment blocks and the first
10873 link in a property drawer line."
10874 (interactive "P")
10875 ;; On a code block, open block's results.
10876 (unless (call-interactively 'org-babel-open-src-block-result)
10877 (org-load-modules-maybe)
10878 (setq org-window-config-before-follow-link (current-window-configuration))
10879 (org-remove-occur-highlights nil nil t)
10880 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10881 (let* ((context
10882 ;; Only consider supported types, even if they are not
10883 ;; the closest one.
10884 (org-element-lineage
10885 (org-element-context)
10886 '(clock comment comment-block footnote-definition
10887 footnote-reference headline inlinetask keyword link
10888 node-property timestamp)
10890 (type (org-element-type context))
10891 (value (org-element-property :value context)))
10892 (cond
10893 ((not context) (user-error "No link found"))
10894 ;; Exception: open timestamps and links in properties
10895 ;; drawers, keywords and comments.
10896 ((memq type '(comment comment-block keyword node-property))
10897 (call-interactively #'org-open-at-point-global))
10898 ;; On a headline or an inlinetask, but not on a timestamp,
10899 ;; a link, a footnote reference or on tags.
10900 ((and (memq type '(headline inlinetask))
10901 ;; Not on tags.
10902 (let ((case-fold-search nil))
10903 (save-excursion
10904 (beginning-of-line)
10905 (looking-at org-complex-heading-regexp))
10906 (or (not (match-beginning 5))
10907 (< (point) (match-beginning 5)))))
10908 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10909 (links (car data))
10910 (links-end (cdr data)))
10911 (if links
10912 (dolist (link (if (stringp links) (list links) links))
10913 (search-forward link nil links-end)
10914 (goto-char (match-beginning 0))
10915 (org-open-at-point))
10916 (require 'org-attach)
10917 (org-attach-reveal 'if-exists))))
10918 ;; On a clock line, make sure point is on the timestamp
10919 ;; before opening it.
10920 ((and (eq type 'clock)
10921 value
10922 (>= (point) (org-element-property :begin value))
10923 (<= (point) (org-element-property :end value)))
10924 (org-follow-timestamp-link))
10925 ;; Do nothing on white spaces after an object.
10926 ((>= (point)
10927 (save-excursion
10928 (goto-char (org-element-property :end context))
10929 (skip-chars-backward " \t")
10930 (point)))
10931 (user-error "No link found"))
10932 ((eq type 'timestamp) (org-follow-timestamp-link))
10933 ;; On tags within a headline or an inlinetask.
10934 ((and (memq type '(headline inlinetask))
10935 (let ((case-fold-search nil))
10936 (save-excursion (beginning-of-line)
10937 (looking-at org-complex-heading-regexp))
10938 (and (match-beginning 5)
10939 (>= (point) (match-beginning 5)))))
10940 (org-tags-view arg (substring (match-string 5) 0 -1)))
10941 ((eq type 'link)
10942 ;; When link is located within the description of another
10943 ;; link (e.g., an inline image), always open the parent
10944 ;; link.
10945 (let* ((link (let ((up (org-element-property :parent context)))
10946 (if (eq (org-element-type up) 'link) up context)))
10947 (type (org-element-property :type link))
10948 (path (org-link-unescape (org-element-property :path link))))
10949 ;; Switch back to REFERENCE-BUFFER needed when called in
10950 ;; a temporary buffer through `org-open-link-from-string'.
10951 (with-current-buffer (or reference-buffer (current-buffer))
10952 (cond
10953 ((equal type "file")
10954 (if (string-match "[*?{]" (file-name-nondirectory path))
10955 (dired path)
10956 ;; Look into `org-link-parameters' in order to find
10957 ;; a DEDICATED-FUNCTION to open file. The function
10958 ;; will be applied on raw link instead of parsed
10959 ;; link due to the limitation in `org-add-link-type'
10960 ;; ("open" function called with a single argument).
10961 ;; If no such function is found, fallback to
10962 ;; `org-open-file'.
10963 (let* ((option (org-element-property :search-option link))
10964 (app (org-element-property :application link))
10965 (dedicated-function
10966 (org-link-get-parameter
10967 (if app (concat type "+" app) type)
10968 :follow)))
10969 (if dedicated-function
10970 (funcall dedicated-function
10971 (concat path
10972 (and option (concat "::" option))))
10973 (apply #'org-open-file
10974 path
10975 (cond (arg)
10976 ((equal app "emacs") 'emacs)
10977 ((equal app "sys") 'system))
10978 (cond ((not option) nil)
10979 ((string-match-p "\\`[0-9]+\\'" option)
10980 (list (string-to-number option)))
10981 (t (list nil
10982 (org-link-unescape option)))))))))
10983 ((functionp (org-link-get-parameter type :follow))
10984 (funcall (org-link-get-parameter type :follow) path))
10985 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10986 (unless (run-hook-with-args-until-success
10987 'org-open-link-functions path)
10988 (if (not arg) (org-mark-ring-push)
10989 (switch-to-buffer-other-window
10990 (org-get-buffer-for-internal-link (current-buffer))))
10991 (let ((destination
10992 (org-with-wide-buffer
10993 (if (equal type "radio")
10994 (org-search-radio-target
10995 (org-element-property :path link))
10996 (org-link-search
10997 (if (member type '("custom-id" "coderef"))
10998 (org-element-property :raw-link link)
10999 path)
11000 ;; Prevent fuzzy links from matching
11001 ;; themselves.
11002 (and (equal type "fuzzy")
11003 (+ 2 (org-element-property :begin link)))))
11004 (point))))
11005 (unless (and (<= (point-min) destination)
11006 (>= (point-max) destination))
11007 (widen))
11008 (goto-char destination))))
11009 (t (browse-url-at-point))))))
11010 ;; On a footnote reference or at a footnote definition's label.
11011 ((or (eq type 'footnote-reference)
11012 (and (eq type 'footnote-definition)
11013 (save-excursion
11014 ;; Do not validate action when point is on the
11015 ;; spaces right after the footnote label, in
11016 ;; order to be on par with behaviour on links.
11017 (skip-chars-forward " \t")
11018 (let ((begin
11019 (org-element-property :contents-begin context)))
11020 (if begin (< (point) begin)
11021 (= (org-element-property :post-affiliated context)
11022 (line-beginning-position)))))))
11023 (org-footnote-action))
11024 (t (user-error "No link found")))))
11025 (run-hook-with-args 'org-follow-link-hook)))
11027 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
11028 "Offer links in the current entry and return the selected link.
11029 If there is only one link, return it.
11030 If NTH is an integer, return the NTH link found.
11031 If ZERO is a string, check also this string for a link, and if
11032 there is one, return it."
11033 (with-current-buffer buffer
11034 (org-with-wide-buffer
11035 (goto-char marker)
11036 (let ((cnt ?0)
11037 have-zero end links link c)
11038 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
11039 (push (match-string 0 zero) links)
11040 (setq cnt (1- cnt) have-zero t))
11041 (save-excursion
11042 (org-back-to-heading t)
11043 (setq end (save-excursion (outline-next-heading) (point)))
11044 (while (re-search-forward org-any-link-re end t)
11045 (push (match-string 0) links))
11046 (setq links (org-uniquify (reverse links))))
11047 (cond
11048 ((null links)
11049 (message "No links"))
11050 ((equal (length links) 1)
11051 (setq link (car links)))
11052 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
11053 (setq link (nth (if have-zero nth (1- nth)) links)))
11054 (t ; we have to select a link
11055 (save-excursion
11056 (save-window-excursion
11057 (delete-other-windows)
11058 (with-output-to-temp-buffer "*Select Link*"
11059 (dolist (l links)
11060 (cond
11061 ((not (string-match org-bracket-link-regexp l))
11062 (princ (format "[%c] %s\n" (cl-incf cnt)
11063 (org-unbracket-string "<" ">" l))))
11064 ((match-end 3)
11065 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
11066 (match-string 3 l) (match-string 1 l))))
11067 (t (princ (format "[%c] %s\n" (cl-incf cnt)
11068 (match-string 1 l)))))))
11069 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
11070 (message "Select link to open, RET to open all:")
11071 (setq c (read-char-exclusive))
11072 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
11073 (when (equal c ?q) (user-error "Abort"))
11074 (if (equal c ?\C-m)
11075 (setq link links)
11076 (setq nth (- c ?0))
11077 (when have-zero (setq nth (1+ nth)))
11078 (unless (and (integerp nth) (>= (length links) nth))
11079 (user-error "Invalid link selection"))
11080 (setq link (nth (1- nth) links)))))
11081 (cons link end)))))
11083 ;; TODO: These functions are deprecated since `org-open-at-point'
11084 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
11085 (defun org-open-file-with-system (path)
11086 "Open file at PATH using the system way of opening it."
11087 (org-open-file path 'system))
11088 (defun org-open-file-with-emacs (path)
11089 "Open file at PATH in Emacs."
11090 (org-open-file path 'emacs))
11093 ;;; File search
11095 (defvar org-create-file-search-functions nil
11096 "List of functions to construct the right search string for a file link.
11097 These functions are called in turn with point at the location to
11098 which the link should point.
11100 A function in the hook should first test if it would like to
11101 handle this file type, for example by checking the `major-mode'
11102 or the file extension. If it decides not to handle this file, it
11103 should just return nil to give other functions a chance. If it
11104 does handle the file, it must return the search string to be used
11105 when following the link. The search string will be part of the
11106 file link, given after a double colon, and `org-open-at-point'
11107 will automatically search for it. If special measures must be
11108 taken to make the search successful, another function should be
11109 added to the companion hook `org-execute-file-search-functions',
11110 which see.
11112 A function in this hook may also use `setq' to set the variable
11113 `description' to provide a suggestion for the descriptive text to
11114 be used for this link when it gets inserted into an Org buffer
11115 with \\[org-insert-link].")
11117 (defvar org-execute-file-search-functions nil
11118 "List of functions to execute a file search triggered by a link.
11120 Functions added to this hook must accept a single argument, the
11121 search string that was part of the file link, the part after the
11122 double colon. The function must first check if it would like to
11123 handle this search, for example by checking the `major-mode' or
11124 the file extension. If it decides not to handle this search, it
11125 should just return nil to give other functions a chance. If it
11126 does handle the search, it must return a non-nil value to keep
11127 other functions from trying.
11129 Each function can access the current prefix argument through the
11130 variable `current-prefix-arg'. Note that a single prefix is used
11131 to force opening a link in Emacs, so it may be good to only use a
11132 numeric or double prefix to guide the search function.
11134 In case this is needed, a function in this hook can also restore
11135 the window configuration before `org-open-at-point' was called using:
11137 (set-window-configuration org-window-config-before-follow-link)")
11139 (defun org-search-radio-target (target)
11140 "Search a radio target matching TARGET in current buffer.
11141 White spaces are not significant."
11142 (let ((re (format "<<<%s>>>"
11143 (mapconcat #'regexp-quote
11144 (org-split-string target "[ \t\n]+")
11145 "[ \t]+\\(?:\n[ \t]*\\)?")))
11146 (origin (point)))
11147 (goto-char (point-min))
11148 (catch :radio-match
11149 (while (re-search-forward re nil t)
11150 (backward-char)
11151 (let ((object (org-element-context)))
11152 (when (eq (org-element-type object) 'radio-target)
11153 (goto-char (org-element-property :begin object))
11154 (org-show-context 'link-search)
11155 (throw :radio-match nil))))
11156 (goto-char origin)
11157 (user-error "No match for radio target: %s" target))))
11159 (defun org-link-search (s &optional avoid-pos stealth)
11160 "Search for a search string S.
11162 If S starts with \"#\", it triggers a custom ID search.
11164 If S is enclosed within parenthesis, it initiates a coderef
11165 search.
11167 If S is surrounded by forward slashes, it is interpreted as
11168 a regular expression. In Org mode files, this will create an
11169 `org-occur' sparse tree. In ordinary files, `occur' will be used
11170 to list matches. If the current buffer is in `dired-mode', grep
11171 will be used to search in all files.
11173 When AVOID-POS is given, ignore matches near that position.
11175 When optional argument STEALTH is non-nil, do not modify
11176 visibility around point, thus ignoring `org-show-context-detail'
11177 variable.
11179 Search is case-insensitive and ignores white spaces. Return type
11180 of matched result, which is either `dedicated' or `fuzzy'."
11181 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11182 (let* ((case-fold-search t)
11183 (origin (point))
11184 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11185 (starred (eq (string-to-char normalized) ?*))
11186 (words (split-string (if starred (substring s 1) s)))
11187 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
11188 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11189 type)
11190 (cond
11191 ;; Check if there are any special search functions.
11192 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11193 ((eq (string-to-char s) ?#)
11194 ;; Look for a custom ID S if S starts with "#".
11195 (let* ((id (substring normalized 1))
11196 (match (org-find-property "CUSTOM_ID" id)))
11197 (if match (progn (goto-char match) (setf type 'dedicated))
11198 (error "No match for custom ID: %s" id))))
11199 ((string-match "\\`(\\(.*\\))\\'" normalized)
11200 ;; Look for coderef targets if S is enclosed within parenthesis.
11201 (let ((coderef (match-string-no-properties 1 normalized))
11202 (re (substring s-single-re 1 -1)))
11203 (goto-char (point-min))
11204 (catch :coderef-match
11205 (while (re-search-forward re nil t)
11206 (let ((element (org-element-at-point)))
11207 (when (and (memq (org-element-type element)
11208 '(example-block src-block))
11209 ;; Build proper regexp according to current
11210 ;; block's label format.
11211 (let ((label-fmt
11212 (regexp-quote
11213 (or (org-element-property :label-fmt element)
11214 org-coderef-label-format))))
11215 (save-excursion
11216 (beginning-of-line)
11217 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11218 (format label-fmt coderef))))))
11219 (setq type 'dedicated)
11220 (goto-char (match-beginning 1))
11221 (throw :coderef-match nil))))
11222 (goto-char origin)
11223 (error "No match for coderef: %s" coderef))))
11224 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11225 ;; Look for a regular expression.
11226 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11227 (match-string 1 s)))
11228 ;; From here, we handle fuzzy links.
11230 ;; Look for targets, only if not in a headline search.
11231 ((and (not starred)
11232 (let ((target (format "<<%s>>" s-multi-re)))
11233 (catch :target-match
11234 (goto-char (point-min))
11235 (while (re-search-forward target nil t)
11236 (backward-char)
11237 (let ((context (org-element-context)))
11238 (when (eq (org-element-type context) 'target)
11239 (setq type 'dedicated)
11240 (goto-char (org-element-property :begin context))
11241 (throw :target-match t))))
11242 nil))))
11243 ;; Look for elements named after S, only if not in a headline
11244 ;; search.
11245 ((and (not starred)
11246 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11247 (catch :name-match
11248 (goto-char (point-min))
11249 (while (re-search-forward name nil t)
11250 (let ((element (org-element-at-point)))
11251 (when (equal words
11252 (split-string
11253 (org-element-property :name element)))
11254 (setq type 'dedicated)
11255 (beginning-of-line)
11256 (throw :name-match t))))
11257 nil))))
11258 ;; Regular text search. Prefer headlines in Org mode buffers.
11259 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
11260 ;; statistics cookies and tags.
11261 ((and (derived-mode-p 'org-mode)
11262 (let ((title-re
11263 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
11264 org-outline-regexp-bol
11265 org-comment-string
11266 (mapconcat #'regexp-quote words ".+")))
11267 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
11268 (comment-re (format "\\`%s[ \t]+" org-comment-string)))
11269 (goto-char (point-min))
11270 (catch :found
11271 (while (re-search-forward title-re nil t)
11272 (when (equal words
11273 (split-string
11274 (replace-regexp-in-string
11275 cookie-re ""
11276 (replace-regexp-in-string
11277 comment-re "" (org-get-heading t t)))))
11278 (throw :found t)))
11279 nil)))
11280 (beginning-of-line)
11281 (setq type 'dedicated))
11282 ;; Offer to create non-existent headline depending on
11283 ;; `org-link-search-must-match-exact-headline'.
11284 ((and (derived-mode-p 'org-mode)
11285 (not org-link-search-inhibit-query)
11286 (eq org-link-search-must-match-exact-headline 'query-to-create)
11287 (yes-or-no-p "No match - create this as a new heading? "))
11288 (goto-char (point-max))
11289 (unless (bolp) (newline))
11290 (org-insert-heading nil t t)
11291 (insert s "\n")
11292 (beginning-of-line 0))
11293 ;; Only headlines are looked after. No need to process
11294 ;; further: throw an error.
11295 ((and (derived-mode-p 'org-mode)
11296 (or starred org-link-search-must-match-exact-headline))
11297 (goto-char origin)
11298 (error "No match for fuzzy expression: %s" normalized))
11299 ;; Regular text search.
11300 ((catch :fuzzy-match
11301 (goto-char (point-min))
11302 (while (re-search-forward s-multi-re nil t)
11303 ;; Skip match if it contains AVOID-POS or it is included in
11304 ;; a link with a description but outside the description.
11305 (unless (or (and avoid-pos
11306 (<= (match-beginning 0) avoid-pos)
11307 (> (match-end 0) avoid-pos))
11308 (and (save-match-data
11309 (org-in-regexp org-bracket-link-regexp))
11310 (match-beginning 3)
11311 (or (> (match-beginning 3) (point))
11312 (<= (match-end 3) (point)))
11313 (org-element-lineage
11314 (save-match-data (org-element-context))
11315 '(link) t)))
11316 (goto-char (match-beginning 0))
11317 (setq type 'fuzzy)
11318 (throw :fuzzy-match t)))
11319 nil))
11320 ;; All failed. Throw an error.
11321 (t (goto-char origin)
11322 (error "No match for fuzzy expression: %s" normalized)))
11323 ;; Disclose surroundings of match, if appropriate.
11324 (when (and (derived-mode-p 'org-mode) (not stealth))
11325 (org-show-context 'link-search))
11326 type))
11328 (defun org-get-buffer-for-internal-link (buffer)
11329 "Return a buffer to be used for displaying the link target of internal links."
11330 (cond
11331 ((not org-display-internal-link-with-indirect-buffer)
11332 buffer)
11333 ((string-suffix-p "(Clone)" (buffer-name buffer))
11334 (message "Buffer is already a clone, not making another one")
11335 ;; we also do not modify visibility in this case
11336 buffer)
11337 (t ; make a new indirect buffer for displaying the link
11338 (let* ((bn (buffer-name buffer))
11339 (ibn (concat bn "(Clone)"))
11340 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11341 (with-current-buffer ib (org-overview))
11342 ib))))
11344 (defun org-do-occur (regexp &optional cleanup)
11345 "Call the Emacs command `occur'.
11346 If CLEANUP is non-nil, remove the printout of the regular expression
11347 in the *Occur* buffer. This is useful if the regex is long and not useful
11348 to read."
11349 (occur regexp)
11350 (when cleanup
11351 (let ((cwin (selected-window)) win beg end)
11352 (when (setq win (get-buffer-window "*Occur*"))
11353 (select-window win))
11354 (goto-char (point-min))
11355 (when (re-search-forward "match[a-z]+" nil t)
11356 (setq beg (match-end 0))
11357 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11358 (setq end (1- (match-beginning 0)))))
11359 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11360 (goto-char (point-min))
11361 (select-window cwin))))
11363 ;;; The mark ring for links jumps
11365 (defvar org-mark-ring nil
11366 "Mark ring for positions before jumps in Org mode.")
11367 (defvar org-mark-ring-last-goto nil
11368 "Last position in the mark ring used to go back.")
11369 ;; Fill and close the ring
11370 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11371 (dotimes (_ org-mark-ring-length)
11372 (push (make-marker) org-mark-ring))
11373 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11374 org-mark-ring)
11376 (defun org-mark-ring-push (&optional pos buffer)
11377 "Put the current position or POS into the mark ring and rotate it."
11378 (interactive)
11379 (setq pos (or pos (point)))
11380 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11381 (move-marker (car org-mark-ring)
11382 (or pos (point))
11383 (or buffer (current-buffer)))
11384 (message "%s"
11385 (substitute-command-keys
11386 "Position saved to mark ring, go back with \
11387 `\\[org-mark-ring-goto]'.")))
11389 (defun org-mark-ring-goto (&optional n)
11390 "Jump to the previous position in the mark ring.
11391 With prefix arg N, jump back that many stored positions. When
11392 called several times in succession, walk through the entire ring.
11393 Org mode commands jumping to a different position in the current file,
11394 or to another Org file, automatically push the old position onto the ring."
11395 (interactive "p")
11396 (let (p m)
11397 (if (eq last-command this-command)
11398 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11399 (setq p org-mark-ring))
11400 (setq org-mark-ring-last-goto p)
11401 (setq m (car p))
11402 (pop-to-buffer-same-window (marker-buffer m))
11403 (goto-char m)
11404 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11406 (defun org-add-angle-brackets (s)
11407 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11408 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11411 ;;; Following specific links
11413 (defvar org-agenda-buffer-tmp-name)
11414 (defvar org-agenda-start-on-weekday)
11415 (defun org-follow-timestamp-link ()
11416 "Open an agenda view for the time-stamp date/range at point."
11417 (cond
11418 ((org-at-date-range-p t)
11419 (let ((org-agenda-start-on-weekday)
11420 (t1 (match-string 1))
11421 (t2 (match-string 2)) tt1 tt2)
11422 (setq tt1 (time-to-days (org-time-string-to-time t1))
11423 tt2 (time-to-days (org-time-string-to-time t2)))
11424 (let ((org-agenda-buffer-tmp-name
11425 (format "*Org Agenda(a:%s)"
11426 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11427 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11428 ((org-at-timestamp-p t)
11429 (let ((org-agenda-buffer-tmp-name
11430 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11431 (org-agenda-list nil (time-to-days (org-time-string-to-time
11432 (substring (match-string 1) 0 10)))
11433 1)))
11434 (t (error "This should not happen"))))
11437 ;;; Following file links
11438 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11439 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11440 (declare-function mailcap-mime-info
11441 "mailcap" (string &optional request no-decode))
11442 (defvar org-wait nil)
11443 (defun org-open-file (path &optional in-emacs line search)
11444 "Open the file at PATH.
11445 First, this expands any special file name abbreviations. Then the
11446 configuration variable `org-file-apps' is checked if it contains an
11447 entry for this file type, and if yes, the corresponding command is launched.
11449 If no application is found, Emacs simply visits the file.
11451 With optional prefix argument IN-EMACS, Emacs will visit the file.
11452 With a double \\[universal-argument] \\[universal-argument] \
11453 prefix arg, Org tries to avoid opening in Emacs
11454 and to use an external application to visit the file.
11456 Optional LINE specifies a line to go to, optional SEARCH a string
11457 to search for. If LINE or SEARCH is given, the file will be
11458 opened in Emacs, unless an entry from org-file-apps that makes
11459 use of groups in a regexp matches.
11461 If you want to change the way frames are used when following a
11462 link, please customize `org-link-frame-setup'.
11464 If the file does not exist, an error is thrown."
11465 (let* ((file (if (equal path "")
11466 buffer-file-name
11467 (substitute-in-file-name (expand-file-name path))))
11468 (file-apps (append org-file-apps (org-default-apps)))
11469 (apps (cl-remove-if
11470 'org-file-apps-entry-match-against-dlink-p file-apps))
11471 (apps-dlink (cl-remove-if-not
11472 'org-file-apps-entry-match-against-dlink-p file-apps))
11473 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11474 (dirp (unless remp (file-directory-p file)))
11475 (file (if (and dirp org-open-directory-means-index-dot-org)
11476 (concat (file-name-as-directory file) "index.org")
11477 file))
11478 (a-m-a-p (assq 'auto-mode apps))
11479 (dfile (downcase file))
11480 ;; Reconstruct the original link from the PATH, LINE and
11481 ;; SEARCH args.
11482 (link (cond (line (concat file "::" (number-to-string line)))
11483 (search (concat file "::" search))
11484 (t file)))
11485 (dlink (downcase link))
11486 (old-buffer (current-buffer))
11487 (old-pos (point))
11488 (old-mode major-mode)
11489 (ext
11490 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11491 (match-string 1 dfile)))
11492 cmd link-match-data)
11493 (cond
11494 ((member in-emacs '((16) system))
11495 (setq cmd (cdr (assq 'system apps))))
11496 (in-emacs (setq cmd 'emacs))
11498 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11499 (and dirp (cdr (assq 'directory apps)))
11500 ;; First, try matching against apps-dlink if we
11501 ;; get a match here, store the match data for
11502 ;; later.
11503 (let ((match (assoc-default dlink apps-dlink
11504 'string-match)))
11505 (if match
11506 (progn (setq link-match-data (match-data))
11507 match)
11508 (progn (setq in-emacs (or in-emacs line search))
11509 nil))) ; if we have no match in apps-dlink,
11510 ; always open the file in emacs if line or search
11511 ; is given (for backwards compatibility)
11512 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11513 'string-match)
11514 (cdr (assoc ext apps))
11515 (cdr (assq t apps))))))
11516 (when (eq cmd 'system)
11517 (setq cmd (cdr (assq 'system apps))))
11518 (when (eq cmd 'default)
11519 (setq cmd (cdr (assoc t apps))))
11520 (when (eq cmd 'mailcap)
11521 (require 'mailcap)
11522 (mailcap-parse-mailcaps)
11523 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11524 (command (mailcap-mime-info mime-type)))
11525 (if (stringp command)
11526 (setq cmd command)
11527 (setq cmd 'emacs))))
11528 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11529 (not (file-exists-p file))
11530 (not org-open-non-existing-files))
11531 (user-error "No such file: %s" file))
11532 (cond
11533 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11534 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11535 (while (string-match "['\"]%s['\"]" cmd)
11536 (setq cmd (replace-match "%s" t t cmd)))
11537 (setq cmd (replace-regexp-in-string
11538 "%s"
11539 (shell-quote-argument (convert-standard-filename file))
11541 nil t))
11543 ;; Replace "%1", "%2" etc. in command with group matches from regex
11544 (save-match-data
11545 (let ((match-index 1)
11546 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11547 (set-match-data link-match-data)
11548 (while (<= match-index number-of-groups)
11549 (let ((regex (concat "%" (number-to-string match-index)))
11550 (replace-with (match-string match-index dlink)))
11551 (while (string-match regex cmd)
11552 (setq cmd (replace-match replace-with t t cmd))))
11553 (setq match-index (+ match-index 1)))))
11555 (save-window-excursion
11556 (message "Running %s...done" cmd)
11557 (start-process-shell-command cmd nil cmd)
11558 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11559 ((or (stringp cmd)
11560 (eq cmd 'emacs))
11561 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11562 (widen)
11563 (cond (line (org-goto-line line)
11564 (when (derived-mode-p 'org-mode) (org-reveal)))
11565 (search (org-link-search search))))
11566 ((functionp cmd)
11567 (save-match-data
11568 (set-match-data link-match-data)
11569 (condition-case nil
11570 (funcall cmd file link)
11571 ;; FIXME: Remove this check when most default installations
11572 ;; of Emacs have at least Org 9.0.
11573 ((debug wrong-number-of-arguments wrong-type-argument
11574 invalid-function)
11575 (user-error "Please see Org News for version 9.0 about \
11576 `org-file-apps'--Lisp error: %S" cmd)))))
11577 ((consp cmd)
11578 ;; FIXME: Remove this check when most default installations of
11579 ;; Emacs have at least Org 9.0.
11580 ;; Heads-up instead of silently fall back to
11581 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11582 ;; with sexp instead of a function for `cmd'.
11583 (user-error "Please see Org News for version 9.0 about \
11584 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11585 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11586 (and (derived-mode-p 'org-mode)
11587 (eq old-mode 'org-mode)
11588 (or (not (eq old-buffer (current-buffer)))
11589 (not (eq old-pos (point))))
11590 (org-mark-ring-push old-pos old-buffer))))
11592 (defun org-file-apps-entry-match-against-dlink-p (entry)
11593 "This function returns non-nil if `entry' uses a regular
11594 expression which should be matched against the whole link by
11595 org-open-file.
11597 It assumes that is the case when the entry uses a regular
11598 expression which has at least one grouping construct and the
11599 action is either a lisp form or a command string containing
11600 `%1', i.e. using at least one subexpression match as a
11601 parameter."
11602 (let ((selector (car entry))
11603 (action (cdr entry)))
11604 (if (stringp selector)
11605 (and (> (regexp-opt-depth selector) 0)
11606 (or (and (stringp action)
11607 (string-match "%[0-9]" action))
11608 (consp action)))
11609 nil)))
11611 (defun org-default-apps ()
11612 "Return the default applications for this operating system."
11613 (cond
11614 ((eq system-type 'darwin)
11615 org-file-apps-defaults-macosx)
11616 ((eq system-type 'windows-nt)
11617 org-file-apps-defaults-windowsnt)
11618 (t org-file-apps-defaults-gnu)))
11620 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11621 "Convert extensions to regular expressions in the cars of LIST.
11622 Also, weed out any non-string entries, because the return value is used
11623 only for regexp matching.
11624 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11625 point to the symbol `emacs', indicating that the file should
11626 be opened in Emacs."
11627 (append
11628 (delq nil
11629 (mapcar (lambda (x)
11630 (unless (not (stringp (car x)))
11631 (if (string-match "\\W" (car x))
11633 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11634 list))
11635 (when add-auto-mode
11636 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11638 (defvar ange-ftp-name-format)
11639 (defun org-file-remote-p (file)
11640 "Test whether FILE specifies a location on a remote system.
11641 Return non-nil if the location is indeed remote.
11643 For example, the filename \"/user@host:/foo\" specifies a location
11644 on the system \"/user@host:\"."
11645 (cond ((fboundp 'file-remote-p)
11646 (file-remote-p file))
11647 ((fboundp 'tramp-handle-file-remote-p)
11648 (tramp-handle-file-remote-p file))
11649 ((and (boundp 'ange-ftp-name-format)
11650 (string-match (car ange-ftp-name-format) file))
11651 t)))
11654 ;;;; Refiling
11656 (defun org-get-org-file ()
11657 "Read a filename, with default directory `org-directory'."
11658 (let ((default (or org-default-notes-file remember-data-file)))
11659 (read-file-name (format "File name [%s]: " default)
11660 (file-name-as-directory org-directory)
11661 default)))
11663 (defun org-notes-order-reversed-p ()
11664 "Check if the current file should receive notes in reversed order."
11665 (cond
11666 ((not org-reverse-note-order) nil)
11667 ((eq t org-reverse-note-order) t)
11668 ((not (listp org-reverse-note-order)) nil)
11669 (t (catch 'exit
11670 (dolist (entry org-reverse-note-order)
11671 (when (string-match (car entry) buffer-file-name)
11672 (throw 'exit (cdr entry))))))))
11674 (defvar org-refile-target-table nil
11675 "The list of refile targets, created by `org-refile'.")
11677 (defvar org-agenda-new-buffers nil
11678 "Buffers created to visit agenda files.")
11680 (defvar org-refile-cache nil
11681 "Cache for refile targets.")
11683 (defvar org-refile-markers nil
11684 "All the markers used for caching refile locations.")
11686 (defun org-refile-marker (pos)
11687 "Get a new refile marker, but only if caching is in use."
11688 (if (not org-refile-use-cache)
11690 (let ((m (make-marker)))
11691 (move-marker m pos)
11692 (push m org-refile-markers)
11693 m)))
11695 (defun org-refile-cache-clear ()
11696 "Clear the refile cache and disable all the markers."
11697 (dolist (m org-refile-markers) (move-marker m nil))
11698 (setq org-refile-markers nil)
11699 (setq org-refile-cache nil)
11700 (message "Refile cache has been cleared"))
11702 (defun org-refile-cache-check-set (set)
11703 "Check if all the markers in the cache still have live buffers."
11704 (let (marker)
11705 (catch 'exit
11706 (while (and set (setq marker (nth 3 (pop set))))
11707 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11708 (when (and marker (null (marker-buffer marker)))
11709 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11710 (sit-for 3)
11711 (throw 'exit nil)))
11712 t)))
11714 (defun org-refile-cache-put (set &rest identifiers)
11715 "Push the refile targets SET into the cache, under IDENTIFIERS."
11716 (let* ((key (sha1 (prin1-to-string identifiers)))
11717 (entry (assoc key org-refile-cache)))
11718 (if entry
11719 (setcdr entry set)
11720 (push (cons key set) org-refile-cache))))
11722 (defun org-refile-cache-get (&rest identifiers)
11723 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11724 (cond
11725 ((not org-refile-cache) nil)
11726 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11728 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11729 org-refile-cache))))
11730 (and set (org-refile-cache-check-set set) set)))))
11732 (defvar org-outline-path-cache nil
11733 "Alist between buffer positions and outline paths.
11734 It value is an alist (POSITION . PATH) where POSITION is the
11735 buffer position at the beginning of an entry and PATH is a list
11736 of strings describing the outline path for that entry, in reverse
11737 order.")
11739 (defun org-refile-get-targets (&optional default-buffer)
11740 "Produce a table with refile targets."
11741 (let ((case-fold-search nil)
11742 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11743 (entries (or org-refile-targets '((nil . (:level . 1)))))
11744 targets tgs files desc descre)
11745 (message "Getting targets...")
11746 (with-current-buffer (or default-buffer (current-buffer))
11747 (dolist (entry entries)
11748 (setq files (car entry) desc (cdr entry))
11749 (cond
11750 ((null files) (setq files (list (current-buffer))))
11751 ((eq files 'org-agenda-files)
11752 (setq files (org-agenda-files 'unrestricted)))
11753 ((and (symbolp files) (fboundp files))
11754 (setq files (funcall files)))
11755 ((and (symbolp files) (boundp files))
11756 (setq files (symbol-value files))))
11757 (when (stringp files) (setq files (list files)))
11758 (cond
11759 ((eq (car desc) :tag)
11760 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11761 ((eq (car desc) :todo)
11762 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11763 ((eq (car desc) :regexp)
11764 (setq descre (cdr desc)))
11765 ((eq (car desc) :level)
11766 (setq descre (concat "^\\*\\{" (number-to-string
11767 (if org-odd-levels-only
11768 (1- (* 2 (cdr desc)))
11769 (cdr desc)))
11770 "\\}[ \t]")))
11771 ((eq (car desc) :maxlevel)
11772 (setq descre (concat "^\\*\\{1," (number-to-string
11773 (if org-odd-levels-only
11774 (1- (* 2 (cdr desc)))
11775 (cdr desc)))
11776 "\\}[ \t]")))
11777 (t (error "Bad refiling target description %s" desc)))
11778 (dolist (f files)
11779 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11781 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11782 (progn
11783 (when (bufferp f)
11784 (setq f (buffer-file-name (buffer-base-buffer f))))
11785 (setq f (and f (expand-file-name f)))
11786 (when (eq org-refile-use-outline-path 'file)
11787 (push (list (file-name-nondirectory f) f nil nil) tgs))
11788 (org-with-wide-buffer
11789 (goto-char (point-min))
11790 (setq org-outline-path-cache nil)
11791 (while (re-search-forward descre nil t)
11792 (beginning-of-line)
11793 (let ((case-fold-search nil))
11794 (looking-at org-complex-heading-regexp))
11795 (let ((begin (point))
11796 (heading (match-string-no-properties 4)))
11797 (unless (or (and
11798 org-refile-target-verify-function
11799 (not
11800 (funcall org-refile-target-verify-function)))
11801 (not heading))
11802 (let ((re (format org-complex-heading-regexp-format
11803 (regexp-quote heading)))
11804 (target
11805 (if (not org-refile-use-outline-path) heading
11806 (mapconcat
11807 #'org-protect-slash
11808 (append
11809 (pcase org-refile-use-outline-path
11810 (`file (list (file-name-nondirectory
11811 (buffer-file-name
11812 (buffer-base-buffer)))))
11813 (`full-file-path
11814 (list (buffer-file-name
11815 (buffer-base-buffer))))
11816 (_ nil))
11817 (org-get-outline-path t t))
11818 "/"))))
11819 (push (list target f re (org-refile-marker (point)))
11820 tgs)))
11821 (when (= (point) begin)
11822 ;; Verification function has not moved point.
11823 (end-of-line)))))))
11824 (when org-refile-use-cache
11825 (org-refile-cache-put tgs (buffer-file-name) descre))
11826 (setq targets (append tgs targets))))))
11827 (message "Getting targets...done")
11828 (delete-dups (nreverse targets))))
11830 (defun org-protect-slash (s)
11831 (replace-regexp-in-string "/" "\\/" s nil t))
11833 (defun org--get-outline-path-1 (&optional use-cache)
11834 "Return outline path to current headline.
11836 Outline path is a list of strings, in reverse order. When
11837 optional argument USE-CACHE is non-nil, make use of a cache. See
11838 `org-get-outline-path' for details.
11840 Assume buffer is widened and point is on a headline."
11841 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11842 (let ((p (point))
11843 (heading (let ((case-fold-search nil))
11844 (looking-at org-complex-heading-regexp)
11845 (if (not (match-end 4)) ""
11846 ;; Remove statistics cookies.
11847 (org-trim
11848 (org-link-display-format
11849 (replace-regexp-in-string
11850 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11851 (match-string-no-properties 4))))))))
11852 (if (org-up-heading-safe)
11853 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11854 (when use-cache
11855 (push (cons p path) org-outline-path-cache))
11856 path)
11857 ;; This is a new root node. Since we assume we are moving
11858 ;; forward, we can drop previous cache so as to limit number
11859 ;; of associations there.
11860 (let ((path (list heading)))
11861 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11862 path)))))
11864 (defun org-get-outline-path (&optional with-self use-cache)
11865 "Return the outline path to the current entry.
11867 An outline path is a list of ancestors for current headline, as
11868 a list of strings. Statistics cookies are removed and links are
11869 replaced with their description, if any, or their path otherwise.
11871 When optional argument WITH-SELF is non-nil, the path also
11872 includes the current headline.
11874 When optional argument USE-CACHE is non-nil, cache outline paths
11875 between calls to this function so as to avoid backtracking. This
11876 argument is useful when planning to find more than one outline
11877 path in the same document. In that case, there are two
11878 conditions to satisfy:
11879 - `org-outline-path-cache' is set to nil before starting the
11880 process;
11881 - outline paths are computed by increasing buffer positions."
11882 (org-with-wide-buffer
11883 (and (or (and with-self (org-back-to-heading t))
11884 (org-up-heading-safe))
11885 (reverse (org--get-outline-path-1 use-cache)))))
11887 (defun org-format-outline-path (path &optional width prefix separator)
11888 "Format the outline path PATH for display.
11889 WIDTH is the maximum number of characters that is available.
11890 PREFIX is a prefix to be included in the returned string,
11891 such as the file name.
11892 SEPARATOR is inserted between the different parts of the path,
11893 the default is \"/\"."
11894 (setq width (or width 79))
11895 (setq path (delq nil path))
11896 (unless (> width 0)
11897 (user-error "Argument `width' must be positive"))
11898 (setq separator (or separator "/"))
11899 (let* ((org-odd-levels-only nil)
11900 (fpath (concat
11901 prefix (and prefix path separator)
11902 (mapconcat
11903 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11904 (cl-loop for head in path
11905 for n from 0
11906 collect (org-add-props
11907 head nil 'face
11908 (nth (% n org-n-level-faces) org-level-faces)))
11909 separator))))
11910 (when (> (length fpath) width)
11911 (if (< width 7)
11912 ;; It's unlikely that `width' will be this small, but don't
11913 ;; waste characters by adding ".." if it is.
11914 (setq fpath (substring fpath 0 width))
11915 (setf (substring fpath (- width 2)) "..")))
11916 fpath))
11918 (defun org-display-outline-path (&optional file current separator just-return-string)
11919 "Display the current outline path in the echo area.
11921 If FILE is non-nil, prepend the output with the file name.
11922 If CURRENT is non-nil, append the current heading to the output.
11923 SEPARATOR is passed through to `org-format-outline-path'. It separates
11924 the different parts of the path and defaults to \"/\".
11925 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11926 (interactive "P")
11927 (let* (case-fold-search
11928 (bfn (buffer-file-name (buffer-base-buffer)))
11929 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11930 res)
11931 (when current (setq path (append path
11932 (save-excursion
11933 (org-back-to-heading t)
11934 (when (looking-at org-complex-heading-regexp)
11935 (list (match-string 4)))))))
11936 (setq res
11937 (org-format-outline-path
11938 path
11939 (1- (frame-width))
11940 (and file bfn (concat (file-name-nondirectory bfn) separator))
11941 separator))
11942 (if just-return-string
11943 (org-no-properties res)
11944 (org-unlogged-message "%s" res))))
11946 (defvar org-refile-history nil
11947 "History for refiling operations.")
11949 (defvar org-after-refile-insert-hook nil
11950 "Hook run after `org-refile' has inserted its stuff at the new location.
11951 Note that this is still *before* the stuff will be removed from
11952 the *old* location.")
11954 (defvar org-capture-last-stored-marker)
11955 (defvar org-refile-keep nil
11956 "Non-nil means `org-refile' will copy instead of refile.")
11958 (defun org-copy ()
11959 "Like `org-refile', but copy."
11960 (interactive)
11961 (let ((org-refile-keep t))
11962 (funcall 'org-refile nil nil nil "Copy")))
11964 (defun org-refile (&optional arg default-buffer rfloc msg)
11965 "Move the entry or entries at point to another heading.
11967 The list of target headings is compiled using the information in
11968 `org-refile-targets', which see.
11970 At the target location, the entry is filed as a subitem of the
11971 target heading. Depending on `org-reverse-note-order', the new
11972 subitem will either be the first or the last subitem.
11974 If there is an active region, all entries in that region will be
11975 refiled. However, the region must fulfill the requirement that
11976 the first heading sets the top-level of the moved text.
11978 With a `\\[universal-argument]' ARG, the command will only visit the target \
11979 location
11980 and not actually move anything.
11982 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11983 location where the last
11984 refiling operation has put the subtree.
11986 With a numeric prefix argument of `2', refile to the running clock.
11988 With a numeric prefix argument of `3', emulate `org-refile-keep'
11989 being set to t and copy to the target location, don't move it.
11990 Beware that keeping refiled entries may result in duplicated ID
11991 properties.
11993 RFLOC can be a refile location obtained in a different way.
11995 MSG is a string to replace \"Refile\" in the default prompt with
11996 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11998 See also `org-refile-use-outline-path'.
12000 If you are using target caching (see `org-refile-use-cache'), you
12001 have to clear the target cache in order to find new targets.
12002 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
12003 prefix argument (`C-u C-u C-u C-c C-w')."
12004 (interactive "P")
12005 (if (member arg '(0 (64)))
12006 (org-refile-cache-clear)
12007 (let* ((actionmsg (cond (msg msg)
12008 ((equal arg 3) "Refile (and keep)")
12009 (t "Refile")))
12010 (regionp (org-region-active-p))
12011 (region-start (and regionp (region-beginning)))
12012 (region-end (and regionp (region-end)))
12013 (org-refile-keep (if (equal arg 3) t org-refile-keep))
12014 pos it nbuf file level reversed)
12015 (setq last-command nil)
12016 (when regionp
12017 (goto-char region-start)
12018 (or (bolp) (goto-char (point-at-bol)))
12019 (setq region-start (point))
12020 (unless (or (org-kill-is-subtree-p
12021 (buffer-substring region-start region-end))
12022 (prog1 org-refile-active-region-within-subtree
12023 (let ((s (point-at-eol)))
12024 (org-toggle-heading)
12025 (setq region-end (+ (- (point-at-eol) s) region-end)))))
12026 (user-error "The region is not a (sequence of) subtree(s)")))
12027 (if (equal arg '(16))
12028 (org-refile-goto-last-stored)
12029 (when (or
12030 (and (equal arg 2)
12031 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
12032 (prog1
12033 (setq it (list (or org-clock-heading "running clock")
12034 (buffer-file-name
12035 (marker-buffer org-clock-hd-marker))
12037 (marker-position org-clock-hd-marker)))
12038 (setq arg nil)))
12039 (setq it
12040 (or rfloc
12041 (let (heading-text)
12042 (save-excursion
12043 (unless (and arg (listp arg))
12044 (org-back-to-heading t)
12045 (setq heading-text
12046 (replace-regexp-in-string
12047 org-bracket-link-regexp
12048 "\\3"
12049 (or (nth 4 (org-heading-components))
12050 ""))))
12051 (org-refile-get-location
12052 (cond ((and arg (listp arg)) "Goto")
12053 (regionp (concat actionmsg " region to"))
12054 (t (concat actionmsg " subtree \""
12055 heading-text "\" to")))
12056 default-buffer
12057 (and (not (equal '(4) arg))
12058 org-refile-allow-creating-parent-nodes)))))))
12059 (setq file (nth 1 it)
12060 pos (nth 3 it))
12061 (when (and (not arg)
12063 (equal (buffer-file-name) file)
12064 (if regionp
12065 (and (>= pos region-start)
12066 (<= pos region-end))
12067 (and (>= pos (point))
12068 (< pos (save-excursion
12069 (org-end-of-subtree t t))))))
12070 (error "Cannot refile to position inside the tree or region"))
12071 (setq nbuf (or (find-buffer-visiting file)
12072 (find-file-noselect file)))
12073 (if (and arg (not (equal arg 3)))
12074 (progn
12075 (pop-to-buffer-same-window nbuf)
12076 (goto-char pos)
12077 (org-show-context 'org-goto))
12078 (if regionp
12079 (progn
12080 (org-kill-new (buffer-substring region-start region-end))
12081 (org-save-markers-in-region region-start region-end))
12082 (org-copy-subtree 1 nil t))
12083 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
12084 (find-file-noselect file)))
12085 (setq reversed (org-notes-order-reversed-p))
12086 (org-with-wide-buffer
12087 (if pos
12088 (progn
12089 (goto-char pos)
12090 (looking-at org-outline-regexp)
12091 (setq level (org-get-valid-level (funcall outline-level) 1))
12092 (goto-char
12093 (if reversed
12094 (or (outline-next-heading) (point-max))
12095 (or (save-excursion (org-get-next-sibling))
12096 (org-end-of-subtree t t)
12097 (point-max)))))
12098 (setq level 1)
12099 (if (not reversed)
12100 (goto-char (point-max))
12101 (goto-char (point-min))
12102 (or (outline-next-heading) (goto-char (point-max)))))
12103 (unless (bolp) (newline))
12104 (org-paste-subtree level nil nil t)
12105 (when org-log-refile
12106 (org-add-log-setup 'refile nil nil org-log-refile)
12107 (unless (eq org-log-refile 'note)
12108 (save-excursion (org-add-log-note))))
12109 (and org-auto-align-tags
12110 (let ((org-loop-over-headlines-in-active-region nil))
12111 (org-set-tags nil t)))
12112 (let ((bookmark-name (plist-get org-bookmark-names-plist
12113 :last-refile)))
12114 (when bookmark-name
12115 (with-demoted-errors
12116 (bookmark-set bookmark-name))))
12117 ;; If we are refiling for capture, make sure that the
12118 ;; last-capture pointers point here
12119 (when (bound-and-true-p org-capture-is-refiling)
12120 (let ((bookmark-name (plist-get org-bookmark-names-plist
12121 :last-capture-marker)))
12122 (when bookmark-name
12123 (with-demoted-errors
12124 (bookmark-set bookmark-name))))
12125 (move-marker org-capture-last-stored-marker (point)))
12126 (when (fboundp 'deactivate-mark) (deactivate-mark))
12127 (run-hooks 'org-after-refile-insert-hook)))
12128 (unless org-refile-keep
12129 (if regionp
12130 (delete-region (point) (+ (point) (- region-end region-start)))
12131 (delete-region
12132 (and (org-back-to-heading t) (point))
12133 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12134 (when (featurep 'org-inlinetask)
12135 (org-inlinetask-remove-END-maybe))
12136 (setq org-markers-to-move nil)
12137 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12139 (defun org-refile-goto-last-stored ()
12140 "Go to the location where the last refile was stored."
12141 (interactive)
12142 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12143 (message "This is the location of the last refile"))
12145 (defun org-refile--get-location (refloc tbl)
12146 "When user refile to REFLOC, find the associated target in TBL.
12147 Also check `org-refile-target-table'."
12148 (car (delq
12150 (mapcar
12151 (lambda (r) (or (assoc r tbl)
12152 (assoc r org-refile-target-table)))
12153 (list (replace-regexp-in-string "/$" "" refloc)
12154 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12156 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12157 "Prompt the user for a refile location, using PROMPT.
12158 PROMPT should not be suffixed with a colon and a space, because
12159 this function appends the default value from
12160 `org-refile-history' automatically, if that is not empty."
12161 (let ((org-refile-targets org-refile-targets)
12162 (org-refile-use-outline-path org-refile-use-outline-path))
12163 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12164 (unless org-refile-target-table
12165 (user-error "No refile targets"))
12166 (let* ((cbuf (current-buffer))
12167 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12168 (cfunc (if (and org-refile-use-outline-path
12169 org-outline-path-complete-in-steps)
12170 #'org-olpath-completing-read
12171 #'completing-read))
12172 (extra (if org-refile-use-outline-path "/" ""))
12173 (cbnex (concat (buffer-name) extra))
12174 (filename (and cfn (expand-file-name cfn)))
12175 (tbl (mapcar
12176 (lambda (x)
12177 (if (and (not (member org-refile-use-outline-path
12178 '(file full-file-path)))
12179 (not (equal filename (nth 1 x))))
12180 (cons (concat (car x) extra " ("
12181 (file-name-nondirectory (nth 1 x)) ")")
12182 (cdr x))
12183 (cons (concat (car x) extra) (cdr x))))
12184 org-refile-target-table))
12185 (completion-ignore-case t)
12186 cdef
12187 (prompt (concat prompt
12188 (or (and (car org-refile-history)
12189 (concat " (default " (car org-refile-history) ")"))
12190 (and (assoc cbnex tbl) (setq cdef cbnex)
12191 (concat " (default " cbnex ")"))) ": "))
12192 pa answ parent-target child parent old-hist)
12193 (setq old-hist org-refile-history)
12194 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12195 nil 'org-refile-history (or cdef (car org-refile-history))))
12196 (if (setq pa (org-refile--get-location answ tbl))
12197 (progn
12198 (org-refile-check-position pa)
12199 (when (or (not org-refile-history)
12200 (not (eq old-hist org-refile-history))
12201 (not (equal (car pa) (car org-refile-history))))
12202 (setq org-refile-history
12203 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12204 org-refile-history
12205 (cdr org-refile-history))))
12206 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12207 (pop org-refile-history)))
12209 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12210 (progn
12211 (setq parent (match-string 1 answ)
12212 child (match-string 2 answ))
12213 (setq parent-target (org-refile--get-location parent tbl))
12214 (when (and parent-target
12215 (or (eq new-nodes t)
12216 (and (eq new-nodes 'confirm)
12217 (y-or-n-p (format "Create new node \"%s\"? "
12218 child)))))
12219 (org-refile-new-child parent-target child)))
12220 (user-error "Invalid target location")))))
12222 (declare-function org-string-nw-p "org-macs" (s))
12223 (defun org-refile-check-position (refile-pointer)
12224 "Check if the refile pointer matches the headline to which it points."
12225 (let* ((file (nth 1 refile-pointer))
12226 (re (nth 2 refile-pointer))
12227 (pos (nth 3 refile-pointer))
12228 buffer)
12229 (if (and (not (markerp pos)) (not file))
12230 (user-error "Please indicate a target file in the refile path")
12231 (when (org-string-nw-p re)
12232 (setq buffer (if (markerp pos)
12233 (marker-buffer pos)
12234 (or (find-buffer-visiting file)
12235 (find-file-noselect file))))
12236 (with-current-buffer buffer
12237 (org-with-wide-buffer
12238 (goto-char pos)
12239 (beginning-of-line 1)
12240 (unless (looking-at-p re)
12241 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12243 (defun org-refile-new-child (parent-target child)
12244 "Use refile target PARENT-TARGET to add new CHILD below it."
12245 (unless parent-target
12246 (error "Cannot find parent for new node"))
12247 (let ((file (nth 1 parent-target))
12248 (pos (nth 3 parent-target))
12249 level)
12250 (with-current-buffer (or (find-buffer-visiting file)
12251 (find-file-noselect file))
12252 (org-with-wide-buffer
12253 (if pos
12254 (goto-char pos)
12255 (goto-char (point-max))
12256 (unless (bolp) (newline)))
12257 (when (looking-at org-outline-regexp)
12258 (setq level (funcall outline-level))
12259 (org-end-of-subtree t t))
12260 (org-back-over-empty-lines)
12261 (insert "\n" (make-string
12262 (if pos (org-get-valid-level level 1) 1) ?*)
12263 " " child "\n")
12264 (beginning-of-line 0)
12265 (list (concat (car parent-target) "/" child) file "" (point))))))
12267 (defun org-olpath-completing-read (prompt collection &rest args)
12268 "Read an outline path like a file name."
12269 (let ((thetable collection))
12270 (apply #'completing-read
12271 prompt
12272 (lambda (string predicate &optional flag)
12273 (cond
12274 ((eq flag nil) (try-completion string thetable))
12275 ((eq flag t)
12276 (let ((l (length string)))
12277 (mapcar (lambda (x)
12278 (let ((r (substring x l))
12279 (f (if (string-match " ([^)]*)$" x)
12280 (match-string 0 x)
12281 "")))
12282 (if (string-match "/" r)
12283 (concat string (substring r 0 (match-end 0)) f)
12284 x)))
12285 (all-completions string thetable predicate))))
12286 ;; Exact match?
12287 ((eq flag 'lambda) (assoc string thetable))))
12288 args)))
12290 ;;;; Dynamic blocks
12292 (defun org-find-dblock (name)
12293 "Find the first dynamic block with name NAME in the buffer.
12294 If not found, stay at current position and return nil."
12295 (let ((case-fold-search t) pos)
12296 (save-excursion
12297 (goto-char (point-min))
12298 (setq pos (and (re-search-forward
12299 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12300 (match-beginning 0))))
12301 (when pos (goto-char pos))
12302 pos))
12304 (defun org-create-dblock (plist)
12305 "Create a dynamic block section, with parameters taken from PLIST.
12306 PLIST must contain a :name entry which is used as the name of the block."
12307 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12308 (end-of-line 1)
12309 (newline))
12310 (let ((col (current-column))
12311 (name (plist-get plist :name)))
12312 (insert "#+BEGIN: " name)
12313 (while plist
12314 (if (eq (car plist) :name)
12315 (setq plist (cddr plist))
12316 (insert " " (prin1-to-string (pop plist)))))
12317 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12318 (beginning-of-line -2)))
12320 (defun org-prepare-dblock ()
12321 "Prepare dynamic block for refresh.
12322 This empties the block, puts the cursor at the insert position and returns
12323 the property list including an extra property :name with the block name."
12324 (unless (looking-at org-dblock-start-re)
12325 (user-error "Not at a dynamic block"))
12326 (let* ((begdel (1+ (match-end 0)))
12327 (name (org-no-properties (match-string 1)))
12328 (params (append (list :name name)
12329 (read (concat "(" (match-string 3) ")")))))
12330 (save-excursion
12331 (beginning-of-line 1)
12332 (skip-chars-forward " \t")
12333 (setq params (plist-put params :indentation-column (current-column))))
12334 (unless (re-search-forward org-dblock-end-re nil t)
12335 (error "Dynamic block not terminated"))
12336 (setq params
12337 (append params
12338 (list :content (buffer-substring
12339 begdel (match-beginning 0)))))
12340 (delete-region begdel (match-beginning 0))
12341 (goto-char begdel)
12342 (open-line 1)
12343 params))
12345 (defun org-map-dblocks (&optional command)
12346 "Apply COMMAND to all dynamic blocks in the current buffer.
12347 If COMMAND is not given, use `org-update-dblock'."
12348 (let ((cmd (or command 'org-update-dblock)))
12349 (save-excursion
12350 (goto-char (point-min))
12351 (while (re-search-forward org-dblock-start-re nil t)
12352 (goto-char (match-beginning 0))
12353 (save-excursion
12354 (condition-case nil
12355 (funcall cmd)
12356 (error (message "Error during update of dynamic block"))))
12357 (unless (re-search-forward org-dblock-end-re nil t)
12358 (error "Dynamic block not terminated"))))))
12360 (defun org-dblock-update (&optional arg)
12361 "User command for updating dynamic blocks.
12362 Update the dynamic block at point. With prefix ARG, update all dynamic
12363 blocks in the buffer."
12364 (interactive "P")
12365 (if arg
12366 (org-update-all-dblocks)
12367 (or (looking-at org-dblock-start-re)
12368 (org-beginning-of-dblock))
12369 (org-update-dblock)))
12371 (defun org-update-dblock ()
12372 "Update the dynamic block at point.
12373 This means to empty the block, parse for parameters and then call
12374 the correct writing function."
12375 (interactive)
12376 (save-excursion
12377 (let* ((win (selected-window))
12378 (pos (point))
12379 (line (org-current-line))
12380 (params (org-prepare-dblock))
12381 (name (plist-get params :name))
12382 (indent (plist-get params :indentation-column))
12383 (cmd (intern (concat "org-dblock-write:" name))))
12384 (message "Updating dynamic block `%s' at line %d..." name line)
12385 (funcall cmd params)
12386 (message "Updating dynamic block `%s' at line %d...done" name line)
12387 (goto-char pos)
12388 (when (and indent (> indent 0))
12389 (setq indent (make-string indent ?\ ))
12390 (save-excursion
12391 (select-window win)
12392 (org-beginning-of-dblock)
12393 (forward-line 1)
12394 (while (not (looking-at org-dblock-end-re))
12395 (insert indent)
12396 (beginning-of-line 2))
12397 (when (looking-at org-dblock-end-re)
12398 (and (looking-at "[ \t]+")
12399 (replace-match ""))
12400 (insert indent)))))))
12402 (defun org-beginning-of-dblock ()
12403 "Find the beginning of the dynamic block at point.
12404 Error if there is no such block at point."
12405 (let ((pos (point))
12406 beg)
12407 (end-of-line 1)
12408 (if (and (re-search-backward org-dblock-start-re nil t)
12409 (setq beg (match-beginning 0))
12410 (re-search-forward org-dblock-end-re nil t)
12411 (> (match-end 0) pos))
12412 (goto-char beg)
12413 (goto-char pos)
12414 (error "Not in a dynamic block"))))
12416 (defun org-update-all-dblocks ()
12417 "Update all dynamic blocks in the buffer.
12418 This function can be used in a hook."
12419 (interactive)
12420 (when (derived-mode-p 'org-mode)
12421 (org-map-dblocks 'org-update-dblock)))
12424 ;;;; Completion
12426 (declare-function org-export-backend-options "ox" (cl-x) t)
12427 (defun org-get-export-keywords ()
12428 "Return a list of all currently understood export keywords.
12429 Export keywords include options, block names, attributes and
12430 keywords relative to each registered export back-end."
12431 (let (keywords)
12432 (dolist (backend
12433 (bound-and-true-p org-export-registered-backends)
12434 (delq nil keywords))
12435 ;; Back-end name (for keywords, like #+LATEX:)
12436 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12437 (dolist (option-entry (org-export-backend-options backend))
12438 ;; Back-end options.
12439 (push (nth 1 option-entry) keywords)))))
12441 (defconst org-options-keywords
12442 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12443 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12444 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12445 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12446 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12448 (defcustom org-structure-template-alist
12449 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12450 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12451 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12452 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12453 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12454 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12455 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12456 ("L" "#+LaTeX: ")
12457 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12458 ("H" "#+HTML: ")
12459 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12460 ("A" "#+ASCII: ")
12461 ("i" "#+INDEX: ?")
12462 ("I" "#+INCLUDE: %file ?"))
12463 "Structure completion elements.
12464 This is a list of abbreviation keys and values. The value gets inserted
12465 if you type `<' followed by the key and then press the completion key,
12466 usually `TAB'. %file will be replaced by a file name after prompting
12467 for the file using completion. The cursor will be placed at the position
12468 of the `?' in the template.
12469 There are two templates for each key, the first uses the original Org syntax,
12470 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12471 the default when the /org-mtags.el/ module has been loaded. See also the
12472 variable `org-mtags-prefer-muse-templates'."
12473 :group 'org-completion
12474 :type '(repeat
12475 (list
12476 (string :tag "Key")
12477 (string :tag "Template")))
12478 :version "26.1"
12479 :package-version '(Org . "8.3"))
12481 (defun org-try-structure-completion ()
12482 "Try to complete a structure template before point.
12483 This looks for strings like \"<e\" on an otherwise empty line and
12484 expands them."
12485 (let ((l (buffer-substring (point-at-bol) (point)))
12487 (when (and (looking-at "[ \t]*$")
12488 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12489 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12490 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12491 (match-beginning 1)) a)
12492 t)))
12494 (defun org-complete-expand-structure-template (start cell)
12495 "Expand a structure template."
12496 (let ((rpl (nth 1 cell))
12497 (ind ""))
12498 (delete-region start (point))
12499 (when (string-match "\\`[ \t]*#\\+" rpl)
12500 (cond
12501 ((bolp))
12502 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12503 (setq ind (buffer-substring (point-at-bol) (point))))
12504 (t (newline))))
12505 (setq start (point))
12506 (when (string-match "%file" rpl)
12507 (setq rpl (replace-match
12508 (concat
12509 "\""
12510 (save-match-data
12511 (abbreviate-file-name (read-file-name "Include file: ")))
12512 "\"")
12513 t t rpl)))
12514 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12515 (concat "\n" ind)))
12516 (insert rpl)
12517 (when (re-search-backward "\\?" start t) (delete-char 1))))
12519 ;;;; TODO, DEADLINE, Comments
12521 (defun org-toggle-comment ()
12522 "Change the COMMENT state of an entry."
12523 (interactive)
12524 (save-excursion
12525 (org-back-to-heading)
12526 (let ((case-fold-search nil))
12527 (looking-at org-complex-heading-regexp))
12528 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12529 (skip-chars-forward " \t")
12530 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12531 (if (org-in-commented-heading-p t)
12532 (delete-region (point)
12533 (progn (search-forward " " (line-end-position) 'move)
12534 (skip-chars-forward " \t")
12535 (point)))
12536 (insert org-comment-string)
12537 (unless (eolp) (insert " ")))))
12539 (defvar org-last-todo-state-is-todo nil
12540 "This is non-nil when the last TODO state change led to a TODO state.
12541 If the last change removed the TODO tag or switched to DONE, then
12542 this is nil.")
12544 (defvar org-setting-tags nil) ; dynamically skipped
12546 (defvar org-todo-setup-filter-hook nil
12547 "Hook for functions that pre-filter todo specs.
12548 Each function takes a todo spec and returns either nil or the spec
12549 transformed into canonical form." )
12551 (defvar org-todo-get-default-hook nil
12552 "Hook for functions that get a default item for todo.
12553 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12554 nil or a string to be used for the todo mark." )
12556 (defvar org-agenda-headline-snapshot-before-repeat)
12558 (defun org-current-effective-time ()
12559 "Return current time adjusted for `org-extend-today-until' variable."
12560 (let* ((ct (org-current-time))
12561 (dct (decode-time ct))
12562 (ct1
12563 (cond
12564 (org-use-last-clock-out-time-as-effective-time
12565 (or (org-clock-get-last-clock-out-time) ct))
12566 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12567 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12568 (t ct))))
12569 ct1))
12571 (defun org-todo-yesterday (&optional arg)
12572 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12573 (interactive "P")
12574 (if (eq major-mode 'org-agenda-mode)
12575 (apply 'org-agenda-todo-yesterday arg)
12576 (let* ((org-use-effective-time t)
12577 (hour (nth 2 (decode-time (org-current-time))))
12578 (org-extend-today-until (1+ hour)))
12579 (org-todo arg))))
12581 (defvar org-block-entry-blocking ""
12582 "First entry preventing the TODO state change.")
12584 (defun org-cancel-repeater ()
12585 "Cancel a repeater by setting its numeric value to zero."
12586 (interactive)
12587 (save-excursion
12588 (org-back-to-heading t)
12589 (let ((bound1 (point))
12590 (bound0 (save-excursion (outline-next-heading) (point))))
12591 (when (and (re-search-forward
12592 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12593 org-deadline-time-regexp "\\)\\|\\("
12594 org-ts-regexp "\\)")
12595 bound0 t)
12596 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12597 bound1 t))
12598 (replace-match "0" t nil nil 1)))))
12600 (defvar org-state)
12601 (defvar org-blocked-by-checkboxes)
12602 (defun org-todo (&optional arg)
12603 "Change the TODO state of an item.
12605 The state of an item is given by a keyword at the start of the heading,
12606 like
12607 *** TODO Write paper
12608 *** DONE Call mom
12610 The different keywords are specified in the variable `org-todo-keywords'.
12611 By default the available states are \"TODO\" and \"DONE\". So, for this
12612 example: when the item starts with TODO, it is changed to DONE.
12613 When it starts with DONE, the DONE is removed. And when neither TODO nor
12614 DONE are present, add TODO at the beginning of the heading.
12616 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12617 state.
12618 With numeric prefix ARG, switch to that state.
12619 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12620 next set of TODO \
12621 keywords (nextset).
12622 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12623 prefix, circumvent any state blocking.
12624 With a numeric prefix arg of 0, inhibit note taking for the change.
12625 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12627 When called through ELisp, arg is also interpreted in the following way:
12628 `none' -> empty state
12629 \"\" -> switch to empty state
12630 `done' -> switch to DONE
12631 `nextset' -> switch to the next set of keywords
12632 `previousset' -> switch to the previous set of keywords
12633 \"WAITING\" -> switch to the specified keyword, but only if it
12634 really is a member of `org-todo-keywords'."
12635 (interactive "P")
12636 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12637 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12638 'region-start-level 'region))
12639 org-loop-over-headlines-in-active-region)
12640 (org-map-entries
12641 `(org-todo ,arg)
12642 org-loop-over-headlines-in-active-region
12643 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12644 (when (equal arg '(16)) (setq arg 'nextset))
12645 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12646 (let ((org-blocker-hook org-blocker-hook)
12647 commentp
12648 case-fold-search)
12649 (when (equal arg '(64))
12650 (setq arg nil org-blocker-hook nil))
12651 (when (and org-blocker-hook
12652 (or org-inhibit-blocking
12653 (org-entry-get nil "NOBLOCKING")))
12654 (setq org-blocker-hook nil))
12655 (save-excursion
12656 (catch 'exit
12657 (org-back-to-heading t)
12658 (when (org-in-commented-heading-p t)
12659 (org-toggle-comment)
12660 (setq commentp t))
12661 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12662 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12663 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12664 (let* ((match-data (match-data))
12665 (startpos (point-at-bol))
12666 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12667 (org-log-done org-log-done)
12668 (org-log-repeat org-log-repeat)
12669 (org-todo-log-states org-todo-log-states)
12670 (org-inhibit-logging
12671 (if (equal arg 0)
12672 (progn (setq arg nil) 'note) org-inhibit-logging))
12673 (this (match-string 1))
12674 (hl-pos (match-beginning 0))
12675 (head (org-get-todo-sequence-head this))
12676 (ass (assoc head org-todo-kwd-alist))
12677 (interpret (nth 1 ass))
12678 (done-word (nth 3 ass))
12679 (final-done-word (nth 4 ass))
12680 (org-last-state (or this ""))
12681 (completion-ignore-case t)
12682 (member (member this org-todo-keywords-1))
12683 (tail (cdr member))
12684 (org-state (cond
12685 ((and org-todo-key-trigger
12686 (or (and (equal arg '(4))
12687 (eq org-use-fast-todo-selection 'prefix))
12688 (and (not arg) org-use-fast-todo-selection
12689 (not (eq org-use-fast-todo-selection
12690 'prefix)))))
12691 ;; Use fast selection.
12692 (org-fast-todo-selection))
12693 ((and (equal arg '(4))
12694 (or (not org-use-fast-todo-selection)
12695 (not org-todo-key-trigger)))
12696 ;; Read a state with completion.
12697 (completing-read
12698 "State: " (mapcar #'list org-todo-keywords-1)
12699 nil t))
12700 ((eq arg 'right)
12701 (if this
12702 (if tail (car tail) nil)
12703 (car org-todo-keywords-1)))
12704 ((eq arg 'left)
12705 (unless (equal member org-todo-keywords-1)
12706 (if this
12707 (nth (- (length org-todo-keywords-1)
12708 (length tail) 2)
12709 org-todo-keywords-1)
12710 (org-last org-todo-keywords-1))))
12711 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12712 (setq arg nil))) ;hack to fall back to cycling
12713 (arg
12714 ;; User or caller requests a specific state.
12715 (cond
12716 ((equal arg "") nil)
12717 ((eq arg 'none) nil)
12718 ((eq arg 'done) (or done-word (car org-done-keywords)))
12719 ((eq arg 'nextset)
12720 (or (car (cdr (member head org-todo-heads)))
12721 (car org-todo-heads)))
12722 ((eq arg 'previousset)
12723 (let ((org-todo-heads (reverse org-todo-heads)))
12724 (or (car (cdr (member head org-todo-heads)))
12725 (car org-todo-heads))))
12726 ((car (member arg org-todo-keywords-1)))
12727 ((stringp arg)
12728 (user-error "State `%s' not valid in this file" arg))
12729 ((nth (1- (prefix-numeric-value arg))
12730 org-todo-keywords-1))))
12731 ((null member) (or head (car org-todo-keywords-1)))
12732 ((equal this final-done-word) nil) ;-> make empty
12733 ((null tail) nil) ;-> first entry
12734 ((memq interpret '(type priority))
12735 (if (eq this-command last-command)
12736 (car tail)
12737 (if (> (length tail) 0)
12738 (or done-word (car org-done-keywords))
12739 nil)))
12741 (car tail))))
12742 (org-state (or
12743 (run-hook-with-args-until-success
12744 'org-todo-get-default-hook org-state org-last-state)
12745 org-state))
12746 (next (if org-state (concat " " org-state " ") " "))
12747 (change-plist (list :type 'todo-state-change :from this :to org-state
12748 :position startpos))
12749 dolog now-done-p)
12750 (when org-blocker-hook
12751 (let (org-blocked-by-checkboxes block-reason)
12752 (setq org-last-todo-state-is-todo
12753 (not (member this org-done-keywords)))
12754 (unless (save-excursion
12755 (save-match-data
12756 (org-with-wide-buffer
12757 (run-hook-with-args-until-failure
12758 'org-blocker-hook change-plist))))
12759 (setq block-reason (if org-blocked-by-checkboxes
12760 "contained checkboxes"
12761 (format "\"%s\"" org-block-entry-blocking)))
12762 (if (called-interactively-p 'interactive)
12763 (user-error "TODO state change from %s to %s blocked (by %s)"
12764 this org-state block-reason)
12765 ;; Fail silently.
12766 (message "TODO state change from %s to %s blocked (by %s)"
12767 this org-state block-reason)
12768 (throw 'exit nil)))))
12769 (store-match-data match-data)
12770 (replace-match next t t)
12771 (cond ((equal this org-state)
12772 (message "TODO state was already %s" (org-trim next)))
12773 ((pos-visible-in-window-p hl-pos)
12774 (message "TODO state changed to %s" (org-trim next))))
12775 (unless head
12776 (setq head (org-get-todo-sequence-head org-state)
12777 ass (assoc head org-todo-kwd-alist)
12778 interpret (nth 1 ass)
12779 done-word (nth 3 ass)
12780 final-done-word (nth 4 ass)))
12781 (when (memq arg '(nextset previousset))
12782 (message "Keyword-Set %d/%d: %s"
12783 (- (length org-todo-sets) -1
12784 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12785 (length org-todo-sets)
12786 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12787 (setq org-last-todo-state-is-todo
12788 (not (member org-state org-done-keywords)))
12789 (setq now-done-p (and (member org-state org-done-keywords)
12790 (not (member this org-done-keywords))))
12791 (and logging (org-local-logging logging))
12792 (when (and (or org-todo-log-states org-log-done)
12793 (not (eq org-inhibit-logging t))
12794 (not (memq arg '(nextset previousset))))
12795 ;; We need to look at recording a time and note.
12796 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12797 (nth 2 (assoc this org-todo-log-states))))
12798 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12799 (setq dolog 'time))
12800 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12801 (and org-state
12802 (member org-state org-not-done-keywords)
12803 (not (member this org-not-done-keywords))))
12804 ;; This is now a todo state and was not one before
12805 ;; If there was a CLOSED time stamp, get rid of it.
12806 (org-add-planning-info nil nil 'closed))
12807 (when (and now-done-p org-log-done)
12808 ;; It is now done, and it was not done before.
12809 (org-add-planning-info 'closed (org-current-effective-time))
12810 (when (and (not dolog) (eq 'note org-log-done))
12811 (org-add-log-setup 'done org-state this 'note)))
12812 (when (and org-state dolog)
12813 ;; This is a non-nil state, and we need to log it.
12814 (org-add-log-setup 'state org-state this dolog)))
12815 ;; Fixup tag positioning.
12816 (org-todo-trigger-tag-changes org-state)
12817 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12818 (when org-provide-todo-statistics
12819 (org-update-parent-todo-statistics))
12820 (run-hooks 'org-after-todo-state-change-hook)
12821 (when (and arg (not (member org-state org-done-keywords)))
12822 (setq head (org-get-todo-sequence-head org-state)))
12823 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12824 ;; Do we need to trigger a repeat?
12825 (when now-done-p
12826 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12827 ;; This is for the agenda, take a snapshot of the headline.
12828 (save-match-data
12829 (setq org-agenda-headline-snapshot-before-repeat
12830 (org-get-heading))))
12831 (org-auto-repeat-maybe org-state))
12832 ;; Fixup cursor location if close to the keyword.
12833 (when (and (outline-on-heading-p)
12834 (not (bolp))
12835 (save-excursion (beginning-of-line 1)
12836 (looking-at org-todo-line-regexp))
12837 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12838 (goto-char (or (match-end 2) (match-end 1)))
12839 (and (looking-at " ") (just-one-space)))
12840 (when org-trigger-hook
12841 (save-excursion
12842 (run-hook-with-args 'org-trigger-hook change-plist)))
12843 (when commentp (org-toggle-comment))))))))
12845 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12846 "Block turning an entry into a TODO, using the hierarchy.
12847 This checks whether the current task should be blocked from state
12848 changes. Such blocking occurs when:
12850 1. The task has children which are not all in a completed state.
12852 2. A task has a parent with the property :ORDERED:, and there
12853 are siblings prior to the current task with incomplete
12854 status.
12856 3. The parent of the task is blocked because it has siblings that should
12857 be done first, or is child of a block grandparent TODO entry."
12859 (if (not org-enforce-todo-dependencies)
12860 t ; if locally turned off don't block
12861 (catch 'dont-block
12862 ;; If this is not a todo state change, or if this entry is already DONE,
12863 ;; do not block
12864 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12865 (member (plist-get change-plist :from)
12866 (cons 'done org-done-keywords))
12867 (member (plist-get change-plist :to)
12868 (cons 'todo org-not-done-keywords))
12869 (not (plist-get change-plist :to)))
12870 (throw 'dont-block t))
12871 ;; If this task has children, and any are undone, it's blocked
12872 (save-excursion
12873 (org-back-to-heading t)
12874 (let ((this-level (funcall outline-level)))
12875 (outline-next-heading)
12876 (let ((child-level (funcall outline-level)))
12877 (while (and (not (eobp))
12878 (> child-level this-level))
12879 ;; this todo has children, check whether they are all
12880 ;; completed
12881 (when (and (not (org-entry-is-done-p))
12882 (org-entry-is-todo-p))
12883 (setq org-block-entry-blocking (org-get-heading))
12884 (throw 'dont-block nil))
12885 (outline-next-heading)
12886 (setq child-level (funcall outline-level))))))
12887 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12888 ;; any previous siblings are undone, it's blocked
12889 (save-excursion
12890 (org-back-to-heading t)
12891 (let* ((pos (point))
12892 (parent-pos (and (org-up-heading-safe) (point)))
12893 (case-fold-search nil))
12894 (unless parent-pos (throw 'dont-block t)) ; no parent
12895 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12896 (forward-line 1)
12897 (re-search-forward org-not-done-heading-regexp pos t))
12898 (setq org-block-entry-blocking (match-string 0))
12899 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12900 ;; Search further up the hierarchy, to see if an ancestor is blocked
12901 (while t
12902 (goto-char parent-pos)
12903 (unless (looking-at org-not-done-heading-regexp)
12904 (throw 'dont-block t)) ; do not block, parent is not a TODO
12905 (setq pos (point))
12906 (setq parent-pos (and (org-up-heading-safe) (point)))
12907 (unless parent-pos (throw 'dont-block t)) ; no parent
12908 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12909 (forward-line 1)
12910 (re-search-forward org-not-done-heading-regexp pos t)
12911 (setq org-block-entry-blocking (org-get-heading)))
12912 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12914 (defcustom org-track-ordered-property-with-tag nil
12915 "Should the ORDERED property also be shown as a tag?
12916 The ORDERED property decides if an entry should require subtasks to be
12917 completed in sequence. Since a property is not very visible, setting
12918 this option means that toggling the ORDERED property with the command
12919 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12920 not relevant for the behavior, but it makes things more visible.
12922 Note that toggling the tag with tags commands will not change the property
12923 and therefore not influence behavior!
12925 This can be t, meaning the tag ORDERED should be used, It can also be a
12926 string to select a different tag for this task."
12927 :group 'org-todo
12928 :type '(choice
12929 (const :tag "No tracking" nil)
12930 (const :tag "Track with ORDERED tag" t)
12931 (string :tag "Use other tag")))
12933 (defun org-toggle-ordered-property ()
12934 "Toggle the ORDERED property of the current entry.
12935 For better visibility, you can track the value of this property with a tag.
12936 See variable `org-track-ordered-property-with-tag'."
12937 (interactive)
12938 (let* ((t1 org-track-ordered-property-with-tag)
12939 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12940 (save-excursion
12941 (org-back-to-heading)
12942 (if (org-entry-get nil "ORDERED")
12943 (progn
12944 (org-delete-property "ORDERED")
12945 (and tag (org-toggle-tag tag 'off))
12946 (message "Subtasks can be completed in arbitrary order"))
12947 (org-entry-put nil "ORDERED" "t")
12948 (and tag (org-toggle-tag tag 'on))
12949 (message "Subtasks must be completed in sequence")))))
12951 (defun org-block-todo-from-checkboxes (change-plist)
12952 "Block turning an entry into a TODO, using checkboxes.
12953 This checks whether the current task should be blocked from state
12954 changes because there are unchecked boxes in this entry."
12955 (if (not org-enforce-todo-checkbox-dependencies)
12956 t ; if locally turned off don't block
12957 (catch 'dont-block
12958 ;; If this is not a todo state change, or if this entry is already DONE,
12959 ;; do not block
12960 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12961 (member (plist-get change-plist :from)
12962 (cons 'done org-done-keywords))
12963 (member (plist-get change-plist :to)
12964 (cons 'todo org-not-done-keywords))
12965 (not (plist-get change-plist :to)))
12966 (throw 'dont-block t))
12967 ;; If this task has checkboxes that are not checked, it's blocked
12968 (save-excursion
12969 (org-back-to-heading t)
12970 (let ((beg (point)) end)
12971 (outline-next-heading)
12972 (setq end (point))
12973 (goto-char beg)
12974 (when (org-list-search-forward
12975 (concat (org-item-beginning-re)
12976 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12977 "\\[[- ]\\]")
12978 end t)
12979 (when (boundp 'org-blocked-by-checkboxes)
12980 (setq org-blocked-by-checkboxes t))
12981 (throw 'dont-block nil))))
12982 t))) ; do not block
12984 (defun org-entry-blocked-p ()
12985 "Non-nil if entry at point is blocked."
12986 (and (not (org-entry-get nil "NOBLOCKING"))
12987 (member (org-entry-get nil "TODO") org-not-done-keywords)
12988 (not (run-hook-with-args-until-failure
12989 'org-blocker-hook
12990 (list :type 'todo-state-change
12991 :position (point)
12992 :from 'todo
12993 :to 'done)))))
12995 (defun org-update-statistics-cookies (all)
12996 "Update the statistics cookie, either from TODO or from checkboxes.
12997 This should be called with the cursor in a line with a statistics
12998 cookie. When called with a \\[universal-argument] prefix, update
12999 all statistics cookies in the buffer."
13000 (interactive "P")
13001 (if all
13002 (progn
13003 (org-update-checkbox-count 'all)
13004 (org-map-entries 'org-update-parent-todo-statistics))
13005 (if (not (org-at-heading-p))
13006 (org-update-checkbox-count)
13007 (let ((pos (point-marker))
13008 end l1 l2)
13009 (ignore-errors (org-back-to-heading t))
13010 (if (not (org-at-heading-p))
13011 (org-update-checkbox-count)
13012 (setq l1 (org-outline-level))
13013 (setq end (save-excursion
13014 (outline-next-heading)
13015 (when (org-at-heading-p) (setq l2 (org-outline-level)))
13016 (point)))
13017 (if (and (save-excursion
13018 (re-search-forward
13019 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
13020 (not (save-excursion (re-search-forward
13021 ":COOKIE_DATA:.*\\<todo\\>" end t))))
13022 (org-update-checkbox-count)
13023 (if (and l2 (> l2 l1))
13024 (progn
13025 (goto-char end)
13026 (org-update-parent-todo-statistics))
13027 (goto-char pos)
13028 (beginning-of-line 1)
13029 (while (re-search-forward
13030 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
13031 (point-at-eol) t)
13032 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
13033 (goto-char pos)
13034 (move-marker pos nil)))))
13036 (defvar org-entry-property-inherited-from) ;; defined below
13037 (defun org-update-parent-todo-statistics ()
13038 "Update any statistics cookie in the parent of the current headline.
13039 When `org-hierarchical-todo-statistics' is nil, statistics will cover
13040 the entire subtree and this will travel up the hierarchy and update
13041 statistics everywhere."
13042 (let* ((prop (save-excursion (org-up-heading-safe)
13043 (org-entry-get nil "COOKIE_DATA" 'inherit)))
13044 (recursive (or (not org-hierarchical-todo-statistics)
13045 (and prop (string-match "\\<recursive\\>" prop))))
13046 (lim (or (and prop (marker-position org-entry-property-inherited-from))
13048 (first t)
13049 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
13050 level ltoggle l1 new ndel
13051 (cnt-all 0) (cnt-done 0) is-percent kwd
13052 checkbox-beg cookie-present)
13053 (catch 'exit
13054 (save-excursion
13055 (beginning-of-line 1)
13056 (setq ltoggle (funcall outline-level))
13057 ;; Three situations are to consider:
13059 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
13060 ;; to the top-level ancestor on the headline;
13062 ;; 2. If parent has "recursive" property, repeat up to the
13063 ;; headline setting that property, taking inheritance into
13064 ;; account;
13066 ;; 3. Else, move up to direct parent and proceed only once.
13067 (while (and (setq level (org-up-heading-safe))
13068 (or recursive first)
13069 (>= (point) lim))
13070 (setq first nil cookie-present nil)
13071 (unless (and level
13072 (not (string-match
13073 "\\<checkbox\\>"
13074 (downcase (or (org-entry-get nil "COOKIE_DATA")
13075 "")))))
13076 (throw 'exit nil))
13077 (while (re-search-forward box-re (point-at-eol) t)
13078 (setq cnt-all 0 cnt-done 0 cookie-present t)
13079 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
13080 (save-match-data
13081 (unless (outline-next-heading) (throw 'exit nil))
13082 (while (and (looking-at org-complex-heading-regexp)
13083 (> (setq l1 (length (match-string 1))) level))
13084 (setq kwd (and (or recursive (= l1 ltoggle))
13085 (match-string 2)))
13086 (if (or (eq org-provide-todo-statistics 'all-headlines)
13087 (and (eq org-provide-todo-statistics t)
13088 (or (member kwd org-done-keywords)))
13089 (and (listp org-provide-todo-statistics)
13090 (stringp (car org-provide-todo-statistics))
13091 (or (member kwd org-provide-todo-statistics)
13092 (member kwd org-done-keywords)))
13093 (and (listp org-provide-todo-statistics)
13094 (listp (car org-provide-todo-statistics))
13095 (or (member kwd (car org-provide-todo-statistics))
13096 (and (member kwd org-done-keywords)
13097 (member kwd (cadr org-provide-todo-statistics))))))
13098 (setq cnt-all (1+ cnt-all))
13099 (and (eq org-provide-todo-statistics t)
13101 (setq cnt-all (1+ cnt-all))))
13102 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
13103 (member kwd org-done-keywords))
13104 (and (listp org-provide-todo-statistics)
13105 (listp (car org-provide-todo-statistics))
13106 (member kwd org-done-keywords)
13107 (member kwd (cadr org-provide-todo-statistics)))
13108 (and (listp org-provide-todo-statistics)
13109 (stringp (car org-provide-todo-statistics))
13110 (member kwd org-done-keywords)))
13111 (setq cnt-done (1+ cnt-done)))
13112 (outline-next-heading)))
13113 (setq new
13114 (if is-percent
13115 (format "[%d%%]" (floor (* 100.0 cnt-done)
13116 (max 1 cnt-all)))
13117 (format "[%d/%d]" cnt-done cnt-all))
13118 ndel (- (match-end 0) checkbox-beg))
13119 (goto-char checkbox-beg)
13120 (insert new)
13121 (delete-region (point) (+ (point) ndel))
13122 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
13123 (when cookie-present
13124 (run-hook-with-args 'org-after-todo-statistics-hook
13125 cnt-done (- cnt-all cnt-done))))))
13126 (run-hooks 'org-todo-statistics-hook)))
13128 (defvar org-after-todo-statistics-hook nil
13129 "Hook that is called after a TODO statistics cookie has been updated.
13130 Each function is called with two arguments: the number of not-done entries
13131 and the number of done entries.
13133 For example, the following function, when added to this hook, will switch
13134 an entry to DONE when all children are done, and back to TODO when new
13135 entries are set to a TODO status. Note that this hook is only called
13136 when there is a statistics cookie in the headline!
13138 (defun org-summary-todo (n-done n-not-done)
13139 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13140 (let (org-log-done org-log-states) ; turn off logging
13141 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13144 (defvar org-todo-statistics-hook nil
13145 "Hook that is run whenever Org thinks TODO statistics should be updated.
13146 This hook runs even if there is no statistics cookie present, in which case
13147 `org-after-todo-statistics-hook' would not run.")
13149 (defun org-todo-trigger-tag-changes (state)
13150 "Apply the changes defined in `org-todo-state-tags-triggers'."
13151 (let ((l org-todo-state-tags-triggers)
13152 changes)
13153 (when (or (not state) (equal state ""))
13154 (setq changes (append changes (cdr (assoc "" l)))))
13155 (when (and (stringp state) (> (length state) 0))
13156 (setq changes (append changes (cdr (assoc state l)))))
13157 (when (member state org-not-done-keywords)
13158 (setq changes (append changes (cdr (assq 'todo l)))))
13159 (when (member state org-done-keywords)
13160 (setq changes (append changes (cdr (assq 'done l)))))
13161 (dolist (c changes)
13162 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13164 (defun org-local-logging (value)
13165 "Get logging settings from a property VALUE."
13166 ;; Directly set the variables, they are already local.
13167 (setq org-log-done nil
13168 org-log-repeat nil
13169 org-todo-log-states nil)
13170 (dolist (w (org-split-string value))
13171 (let (a)
13172 (cond
13173 ((setq a (assoc w org-startup-options))
13174 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13175 (set (nth 1 a) (nth 2 a))))
13176 ((setq a (org-extract-log-state-settings w))
13177 (and (member (car a) org-todo-keywords-1)
13178 (push a org-todo-log-states)))))))
13180 (defun org-get-todo-sequence-head (kwd)
13181 "Return the head of the TODO sequence to which KWD belongs.
13182 If KWD is not set, check if there is a text property remembering the
13183 right sequence."
13184 (let (p)
13185 (cond
13186 ((not kwd)
13187 (or (get-text-property (point-at-bol) 'org-todo-head)
13188 (progn
13189 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13190 nil (point-at-eol)))
13191 (get-text-property p 'org-todo-head))))
13192 ((not (member kwd org-todo-keywords-1))
13193 (car org-todo-keywords-1))
13194 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13196 (defun org-fast-todo-selection ()
13197 "Fast TODO keyword selection with single keys.
13198 Returns the new TODO keyword, or nil if no state change should occur."
13199 (let* ((fulltable org-todo-key-alist)
13200 (done-keywords org-done-keywords) ;; needed for the faces.
13201 (maxlen (apply 'max (mapcar
13202 (lambda (x)
13203 (if (stringp (car x)) (string-width (car x)) 0))
13204 fulltable)))
13205 (expert nil)
13206 (fwidth (+ maxlen 3 1 3))
13207 (ncol (/ (- (window-width) 4) fwidth))
13208 tg cnt e c tbl
13209 groups ingroup)
13210 (save-excursion
13211 (save-window-excursion
13212 (if expert
13213 (set-buffer (get-buffer-create " *Org todo*"))
13214 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13215 (erase-buffer)
13216 (setq-local org-done-keywords done-keywords)
13217 (setq tbl fulltable cnt 0)
13218 (while (setq e (pop tbl))
13219 (cond
13220 ((equal e '(:startgroup))
13221 (push '() groups) (setq ingroup t)
13222 (unless (= cnt 0)
13223 (setq cnt 0)
13224 (insert "\n"))
13225 (insert "{ "))
13226 ((equal e '(:endgroup))
13227 (setq ingroup nil cnt 0)
13228 (insert "}\n"))
13229 ((equal e '(:newline))
13230 (unless (= cnt 0)
13231 (setq cnt 0)
13232 (insert "\n")
13233 (setq e (car tbl))
13234 (while (equal (car tbl) '(:newline))
13235 (insert "\n")
13236 (setq tbl (cdr tbl)))))
13238 (setq tg (car e) c (cdr e))
13239 (when ingroup (push tg (car groups)))
13240 (setq tg (org-add-props tg nil 'face
13241 (org-get-todo-face tg)))
13242 (when (and (= cnt 0) (not ingroup)) (insert " "))
13243 (insert "[" c "] " tg (make-string
13244 (- fwidth 4 (length tg)) ?\ ))
13245 (when (= (setq cnt (1+ cnt)) ncol)
13246 (insert "\n")
13247 (when ingroup (insert " "))
13248 (setq cnt 0)))))
13249 (insert "\n")
13250 (goto-char (point-min))
13251 (unless expert (org-fit-window-to-buffer))
13252 (message "[a-z..]:Set [SPC]:clear")
13253 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13254 (cond
13255 ((or (= c ?\C-g)
13256 (and (= c ?q) (not (rassoc c fulltable))))
13257 (setq quit-flag t))
13258 ((= c ?\ ) nil)
13259 ((setq e (rassoc c fulltable) tg (car e))
13261 (t (setq quit-flag t)))))))
13263 (defun org-entry-is-todo-p ()
13264 (member (org-get-todo-state) org-not-done-keywords))
13266 (defun org-entry-is-done-p ()
13267 (member (org-get-todo-state) org-done-keywords))
13269 (defun org-get-todo-state ()
13270 "Return the TODO keyword of the current subtree."
13271 (save-excursion
13272 (org-back-to-heading t)
13273 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13274 (match-end 2)
13275 (match-string 2))))
13277 (defun org-at-date-range-p (&optional inactive-ok)
13278 "Non-nil if point is inside a date range.
13280 When optional argument INACTIVE-OK is non-nil, also consider
13281 inactive time ranges.
13283 When this function returns a non-nil value, match data is set
13284 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13285 on INACTIVE-OK."
13286 (interactive)
13287 (save-excursion
13288 (catch 'exit
13289 (let ((pos (point)))
13290 (skip-chars-backward "^[<\r\n")
13291 (skip-chars-backward "<[")
13292 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13293 (>= (match-end 0) pos)
13294 (throw 'exit t))
13295 (skip-chars-backward "^<[\r\n")
13296 (skip-chars-backward "<[")
13297 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13298 (>= (match-end 0) pos)
13299 (throw 'exit t)))
13300 nil)))
13302 (defun org-get-repeat (&optional tagline)
13303 "Check if there is a deadline/schedule with repeater in this entry."
13304 (save-match-data
13305 (save-excursion
13306 (org-back-to-heading t)
13307 (and (re-search-forward (if tagline
13308 (concat tagline "\\s-*" org-repeat-re)
13309 org-repeat-re)
13310 (org-entry-end-position) t)
13311 (match-string-no-properties 1)))))
13313 (defvar org-last-changed-timestamp)
13314 (defvar org-last-inserted-timestamp)
13315 (defvar org-log-post-message)
13316 (defvar org-log-note-purpose)
13317 (defvar org-log-note-how nil)
13318 (defvar org-log-note-extra)
13319 (defun org-auto-repeat-maybe (done-word)
13320 "Check if the current headline contains a repeated time-stamp.
13322 If yes, set TODO state back to what it was and change the base date
13323 of repeating deadline/scheduled time stamps to new date.
13325 This function is run automatically after each state change to a DONE state."
13326 (let* ((repeat (org-get-repeat))
13327 (aa (assoc org-last-state org-todo-kwd-alist))
13328 (interpret (nth 1 aa))
13329 (head (nth 2 aa))
13330 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13331 (msg "Entry repeats: ")
13332 (org-log-done nil)
13333 (org-todo-log-states nil))
13334 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13335 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13336 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13337 org-todo-repeat-to-state)))
13338 (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
13339 to-state)
13340 ((eq interpret 'type) org-last-state)
13341 (head)
13342 (t 'none))))
13343 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13344 (org-entry-put nil "LAST_REPEAT" (format-time-string
13345 (org-time-stamp-format t t))))
13346 (when org-log-repeat
13347 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13348 (memq 'org-add-log-note post-command-hook))
13349 ;; We are already setup for some record.
13350 (when (eq org-log-repeat 'note)
13351 ;; Make sure we take a note, not only a time stamp.
13352 (setq org-log-note-how 'note))
13353 ;; Set up for taking a record.
13354 (org-add-log-setup 'state
13355 (or done-word (car org-done-keywords))
13356 org-last-state
13357 org-log-repeat)))
13358 (org-back-to-heading t)
13359 (org-add-planning-info nil nil 'closed)
13360 (let ((end (save-excursion (outline-next-heading) (point)))
13361 (planning-re (regexp-opt
13362 (list org-scheduled-string org-deadline-string))))
13363 (while (re-search-forward org-ts-regexp end t)
13364 (let* ((ts (match-string 0))
13365 (planning? (org-at-planning-p))
13366 (type (if (not planning?) "Plain:"
13367 (save-excursion
13368 (re-search-backward
13369 planning-re (line-beginning-position) t)
13370 (match-string 0)))))
13371 (cond
13372 ;; Ignore fake time-stamps (e.g., within comments).
13373 ((and (not planning?)
13374 (not (org-at-property-p))
13375 (not (eq 'timestamp
13376 (org-element-type (save-excursion
13377 (backward-char)
13378 (org-element-context)))))))
13379 ;; Time-stamps without a repeater are usually skipped.
13380 ;; However, a SCHEDULED time-stamp without one is
13381 ;; removed, as it is considered as no longer relevant.
13382 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13383 (when (equal type org-scheduled-string)
13384 (org-remove-timestamp-with-keyword type)))
13386 (let ((n (string-to-number (match-string 2 ts)))
13387 (what (match-string 3 ts)))
13388 (when (equal what "w") (setq n (* n 7) what "d"))
13389 (when (and (equal what "h")
13390 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13391 ts)))
13392 (user-error
13393 "Cannot repeat in Repeat in %d hour(s) because no hour \
13394 has been set"
13396 ;; Preparation, see if we need to modify the start
13397 ;; date for the change.
13398 (when (match-end 1)
13399 (let ((time (save-match-data (org-time-string-to-time ts))))
13400 (cond
13401 ((equal (match-string 1 ts) ".")
13402 ;; Shift starting date to today
13403 (org-timestamp-change
13404 (- (org-today) (time-to-days time))
13405 'day))
13406 ((equal (match-string 1 ts) "+")
13407 (let ((nshiftmax 10)
13408 (nshift 0))
13409 (while (or (= nshift 0)
13410 (not (time-less-p (current-time) time)))
13411 (when (= (cl-incf nshift) nshiftmax)
13412 (or (y-or-n-p
13413 (format "%d repeater intervals were not \
13414 enough to shift date past today. Continue? "
13415 nshift))
13416 (user-error "Abort")))
13417 (org-timestamp-change n (cdr (assoc what whata)))
13418 (org-at-timestamp-p t)
13419 (setq ts (match-string 1))
13420 (setq time
13421 (save-match-data
13422 (org-time-string-to-time ts)))))
13423 (org-timestamp-change (- n) (cdr (assoc what whata)))
13424 ;; Rematch, so that we have everything in place
13425 ;; for the real shift.
13426 (org-at-timestamp-p t)
13427 (setq ts (match-string 1))
13428 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13429 ts)))))
13430 (save-excursion
13431 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13432 (setq msg
13433 (concat
13434 msg type " " org-last-changed-timestamp " "))))))))
13435 (setq org-log-post-message msg)
13436 (message "%s" msg))))
13438 (defun org-show-todo-tree (arg)
13439 "Make a compact tree which shows all headlines marked with TODO.
13440 The tree will show the lines where the regexp matches, and all higher
13441 headlines above the match.
13442 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13443 With a numeric prefix N, construct a sparse tree for the Nth element
13444 of `org-todo-keywords-1'."
13445 (interactive "P")
13446 (let ((case-fold-search nil)
13447 (kwd-re
13448 (cond ((null arg) org-not-done-regexp)
13449 ((equal arg '(4))
13450 (let ((kwd
13451 (completing-read "Keyword (or KWD1|KWD2|...): "
13452 (mapcar #'list org-todo-keywords-1))))
13453 (concat "\\("
13454 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13455 "\\)\\>")))
13456 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13457 (regexp-quote (nth (1- (prefix-numeric-value arg))
13458 org-todo-keywords-1)))
13459 (t (user-error "Invalid prefix argument: %s" arg)))))
13460 (message "%d TODO entries found"
13461 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13463 (defun org--deadline-or-schedule (arg type time)
13464 "Insert DEADLINE or SCHEDULE information in current entry.
13465 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13466 `org-schedule' for information about ARG and TIME arguments."
13467 (let* ((deadline? (eq type 'deadline))
13468 (keyword (if deadline? org-deadline-string org-scheduled-string))
13469 (log (if deadline? org-log-redeadline org-log-reschedule))
13470 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13471 (old-date-time (and old-date (org-time-string-to-time old-date)))
13472 ;; Save repeater cookie from either TIME or current scheduled
13473 ;; time stamp. We are going to insert it back at the end of
13474 ;; the process.
13475 (repeater (or (and (org-string-nw-p time)
13476 ;; We use `org-repeat-re' because we need
13477 ;; to tell the difference between a real
13478 ;; repeater and a time delta, e.g. "+2d".
13479 (string-match org-repeat-re time)
13480 (match-string 1 time))
13481 (and (org-string-nw-p old-date)
13482 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13483 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13484 old-date)
13485 (match-string 1 old-date)))))
13486 (pcase arg
13487 (`(4)
13488 (when (and old-date log)
13489 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13490 nil old-date log))
13491 (org-remove-timestamp-with-keyword keyword)
13492 (message (if deadline? "Item no longer has a deadline."
13493 "Item is no longer scheduled.")))
13494 (`(16)
13495 (save-excursion
13496 (org-back-to-heading t)
13497 (let ((regexp (if deadline? org-deadline-time-regexp
13498 org-scheduled-time-regexp)))
13499 (if (not (re-search-forward regexp (line-end-position 2) t))
13500 (user-error (if deadline? "No deadline information to update"
13501 "No scheduled information to update"))
13502 (let* ((rpl0 (match-string 1))
13503 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13504 (msg (if deadline? "Warn starting from" "Delay until")))
13505 (replace-match
13506 (concat keyword
13507 " <" rpl
13508 (format " -%dd"
13509 (abs (- (time-to-days
13510 (save-match-data
13511 (org-read-date
13512 nil t nil msg old-date-time)))
13513 (time-to-days old-date-time))))
13514 ">") t t))))))
13516 (org-add-planning-info type time 'closed)
13517 (when (and old-date
13519 (not (equal old-date org-last-inserted-timestamp)))
13520 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13521 org-last-inserted-timestamp
13522 old-date
13523 log))
13524 (when repeater
13525 (save-excursion
13526 (org-back-to-heading t)
13527 (when (re-search-forward
13528 (concat keyword " " org-last-inserted-timestamp)
13529 (line-end-position 2)
13531 (goto-char (1- (match-end 0)))
13532 (insert " " repeater)
13533 (setq org-last-inserted-timestamp
13534 (concat (substring org-last-inserted-timestamp 0 -1)
13535 " " repeater
13536 (substring org-last-inserted-timestamp -1))))))
13537 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13538 org-last-inserted-timestamp)))))
13540 (defun org-deadline (arg &optional time)
13541 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13542 With one universal prefix argument, remove any deadline from the item.
13543 With two universal prefix arguments, prompt for a warning delay.
13544 With argument TIME, set the deadline at the corresponding date. TIME
13545 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13546 (interactive "P")
13547 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13548 (org-map-entries
13549 (lambda () (org--deadline-or-schedule arg 'deadline time))
13551 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13552 'region-start-level
13553 'region)
13554 (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
13555 (org--deadline-or-schedule arg 'deadline time)))
13557 (defun org-schedule (arg &optional time)
13558 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13559 With one universal prefix argument, remove any scheduling date from the item.
13560 With two universal prefix arguments, prompt for a delay cookie.
13561 With argument TIME, scheduled at the corresponding date. TIME can
13562 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13563 (interactive "P")
13564 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13565 (org-map-entries
13566 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13568 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13569 'region-start-level
13570 'region)
13571 (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
13572 (org--deadline-or-schedule arg 'scheduled time)))
13574 (defun org-get-scheduled-time (pom &optional inherit)
13575 "Get the scheduled time as a time tuple, of a format suitable
13576 for calling org-schedule with, or if there is no scheduling,
13577 returns nil."
13578 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13579 (when time
13580 (apply 'encode-time (org-parse-time-string time)))))
13582 (defun org-get-deadline-time (pom &optional inherit)
13583 "Get the deadline as a time tuple, of a format suitable for
13584 calling org-deadline with, or if there is no scheduling, returns
13585 nil."
13586 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13587 (when time
13588 (apply 'encode-time (org-parse-time-string time)))))
13590 (defun org-remove-timestamp-with-keyword (keyword)
13591 "Remove all time stamps with KEYWORD in the current entry."
13592 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13593 beg)
13594 (save-excursion
13595 (org-back-to-heading t)
13596 (setq beg (point))
13597 (outline-next-heading)
13598 (while (re-search-backward re beg t)
13599 (replace-match "")
13600 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13601 (equal (char-before) ?\ ))
13602 (backward-delete-char 1)
13603 (when (string-match "^[ \t]*$" (buffer-substring
13604 (point-at-bol) (point-at-eol)))
13605 (delete-region (point-at-bol)
13606 (min (point-max) (1+ (point-at-eol))))))))))
13608 (defvar org-time-was-given) ; dynamically scoped parameter
13609 (defvar org-end-time-was-given) ; dynamically scoped parameter
13611 (defun org-at-planning-p ()
13612 "Non-nil when point is on a planning info line."
13613 ;; This is as accurate and faster than `org-element-at-point' since
13614 ;; planning info location is fixed in the section.
13615 (org-with-wide-buffer
13616 (beginning-of-line)
13617 (and (looking-at-p org-planning-line-re)
13618 (eq (point)
13619 (ignore-errors
13620 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13621 (org-back-to-heading t)
13622 (org-with-limited-levels (org-back-to-heading t)))
13623 (line-beginning-position 2))))))
13625 (defun org-add-planning-info (what &optional time &rest remove)
13626 "Insert new timestamp with keyword in the planning line.
13627 WHAT indicates what kind of time stamp to add. It is a symbol
13628 among `closed', `deadline', `scheduled' and nil. TIME indicates
13629 the time to use. If none is given, the user is prompted for
13630 a date. REMOVE indicates what kind of entries to remove. An old
13631 WHAT entry will also be removed."
13632 (let (org-time-was-given org-end-time-was-given default-time default-input)
13633 (catch 'exit
13634 (when (and (memq what '(scheduled deadline))
13635 (or (not time)
13636 (and (stringp time)
13637 (string-match "^[-+]+[0-9]" time))))
13638 ;; Try to get a default date/time from existing timestamp
13639 (save-excursion
13640 (org-back-to-heading t)
13641 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13642 (when (re-search-forward (if (eq what 'scheduled)
13643 org-scheduled-time-regexp
13644 org-deadline-time-regexp)
13645 end t)
13646 (setq ts (match-string 1)
13647 default-time (apply 'encode-time (org-parse-time-string ts))
13648 default-input (and ts (org-get-compact-tod ts)))))))
13649 (when what
13650 (setq time
13651 (if (stringp time)
13652 ;; This is a string (relative or absolute), set
13653 ;; proper date.
13654 (apply #'encode-time
13655 (org-read-date-analyze
13656 time default-time (decode-time default-time)))
13657 ;; If necessary, get the time from the user
13658 (or time (org-read-date nil 'to-time nil nil
13659 default-time default-input)))))
13661 (org-with-wide-buffer
13662 (org-back-to-heading t)
13663 (forward-line)
13664 (unless (bolp) (insert "\n"))
13665 (cond ((looking-at-p org-planning-line-re)
13666 ;; Move to current indentation.
13667 (skip-chars-forward " \t")
13668 ;; Check if we have to remove something.
13669 (dolist (type (if what (cons what remove) remove))
13670 (save-excursion
13671 (when (re-search-forward
13672 (cl-case type
13673 (closed org-closed-time-regexp)
13674 (deadline org-deadline-time-regexp)
13675 (scheduled org-scheduled-time-regexp)
13676 (otherwise
13677 (error "Invalid planning type: %s" type)))
13678 (line-end-position) t)
13679 ;; Delete until next keyword or end of line.
13680 (delete-region
13681 (match-beginning 0)
13682 (if (re-search-forward org-keyword-time-not-clock-regexp
13683 (line-end-position)
13685 (match-beginning 0)
13686 (line-end-position))))))
13687 ;; If there is nothing more to add and no more keyword
13688 ;; is left, remove the line completely.
13689 (if (and (looking-at-p "[ \t]*$") (not what))
13690 (delete-region (line-beginning-position)
13691 (line-beginning-position 2))
13692 ;; If we removed last keyword, do not leave trailing
13693 ;; white space at the end of line.
13694 (let ((p (point)))
13695 (save-excursion
13696 (end-of-line)
13697 (unless (= (skip-chars-backward " \t" p) 0)
13698 (delete-region (point) (line-end-position)))))))
13699 ((not what) (throw 'exit nil)) ; Nothing to do.
13700 (t (insert-before-markers "\n")
13701 (backward-char 1)
13702 (when org-adapt-indentation
13703 (indent-to-column (1+ (org-outline-level))))))
13704 (when what
13705 ;; Insert planning keyword.
13706 (insert (cl-case what
13707 (closed org-closed-string)
13708 (deadline org-deadline-string)
13709 (scheduled org-scheduled-string)
13710 (otherwise (error "Invalid planning type: %s" what)))
13711 " ")
13712 ;; Insert associated timestamp.
13713 (let ((ts (org-insert-time-stamp
13714 time
13715 (or org-time-was-given
13716 (and (eq what 'closed) org-log-done-with-time))
13717 (eq what 'closed)
13718 nil nil (list org-end-time-was-given))))
13719 (unless (eolp) (insert " "))
13720 ts))))))
13722 (defvar org-log-note-marker (make-marker)
13723 "Marker pointing at the entry where the note is to be inserted.")
13724 (defvar org-log-note-purpose nil)
13725 (defvar org-log-note-state nil)
13726 (defvar org-log-note-previous-state nil)
13727 (defvar org-log-note-extra nil)
13728 (defvar org-log-note-window-configuration nil)
13729 (defvar org-log-note-return-to (make-marker))
13730 (defvar org-log-note-effective-time nil
13731 "Remembered current time so that dynamically scoped
13732 `org-extend-today-until' affects timestamps in state change log")
13734 (defvar org-log-post-message nil
13735 "Message to be displayed after a log note has been stored.
13736 The auto-repeater uses this.")
13738 (defun org-add-note ()
13739 "Add a note to the current entry.
13740 This is done in the same way as adding a state change note."
13741 (interactive)
13742 (org-add-log-setup 'note))
13744 (defun org-log-beginning (&optional create)
13745 "Return expected start of log notes in current entry.
13746 When optional argument CREATE is non-nil, the function creates
13747 a drawer to store notes, if necessary. Returned position ignores
13748 narrowing."
13749 (org-with-wide-buffer
13750 (let ((drawer (org-log-into-drawer)))
13751 (cond
13752 (drawer
13753 (org-end-of-meta-data)
13754 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13755 (end (if (org-at-heading-p) (point)
13756 (save-excursion (outline-next-heading) (point))))
13757 (case-fold-search t))
13758 (catch 'exit
13759 ;; Try to find existing drawer.
13760 (while (re-search-forward regexp end t)
13761 (let ((element (org-element-at-point)))
13762 (when (eq (org-element-type element) 'drawer)
13763 (let ((cend (org-element-property :contents-end element)))
13764 (when (and (not org-log-states-order-reversed) cend)
13765 (goto-char cend)))
13766 (throw 'exit nil))))
13767 ;; No drawer found. Create one, if permitted.
13768 (when create
13769 (unless (bolp) (insert "\n"))
13770 (let ((beg (point)))
13771 (insert ":" drawer ":\n:END:\n")
13772 (org-indent-region beg (point)))
13773 (end-of-line -1)))))
13775 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13776 (skip-chars-forward " \t\n")
13777 (beginning-of-line)
13778 (unless org-log-states-order-reversed
13779 (org-skip-over-state-notes)
13780 (skip-chars-backward " \t\n")
13781 (forward-line)))))
13782 (if (bolp) (point) (line-beginning-position 2))))
13784 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13785 "Set up the post command hook to take a note.
13786 If this is about to TODO state change, the new state is expected in STATE.
13787 HOW is an indicator what kind of note should be created.
13788 EXTRA is additional text that will be inserted into the notes buffer."
13789 (move-marker org-log-note-marker (point))
13790 (setq org-log-note-purpose purpose
13791 org-log-note-state state
13792 org-log-note-previous-state prev-state
13793 org-log-note-how how
13794 org-log-note-extra extra
13795 org-log-note-effective-time (org-current-effective-time))
13796 (add-hook 'post-command-hook 'org-add-log-note 'append))
13798 (defun org-skip-over-state-notes ()
13799 "Skip past the list of State notes in an entry."
13800 (when (ignore-errors (goto-char (org-in-item-p)))
13801 (let* ((struct (org-list-struct))
13802 (prevs (org-list-prevs-alist struct))
13803 (regexp
13804 (concat "[ \t]*- +"
13805 (replace-regexp-in-string
13806 " +" " +"
13807 (org-replace-escapes
13808 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13809 `(("%d" . ,org-ts-regexp-inactive)
13810 ("%D" . ,org-ts-regexp)
13811 ("%s" . "\"\\S-+\"")
13812 ("%S" . "\"\\S-+\"")
13813 ("%t" . ,org-ts-regexp-inactive)
13814 ("%T" . ,org-ts-regexp)
13815 ("%u" . ".*?")
13816 ("%U" . ".*?")))))))
13817 (while (looking-at-p regexp)
13818 (goto-char (or (org-list-get-next-item (point) struct prevs)
13819 (org-list-get-item-end (point) struct)))))))
13821 (defun org-add-log-note (&optional _purpose)
13822 "Pop up a window for taking a note, and add this note later."
13823 (remove-hook 'post-command-hook 'org-add-log-note)
13824 (setq org-log-note-window-configuration (current-window-configuration))
13825 (delete-other-windows)
13826 (move-marker org-log-note-return-to (point))
13827 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13828 (goto-char org-log-note-marker)
13829 (org-switch-to-buffer-other-window "*Org Note*")
13830 (erase-buffer)
13831 (if (memq org-log-note-how '(time state))
13832 (let (current-prefix-arg) (org-store-log-note))
13833 (let ((org-inhibit-startup t)) (org-mode))
13834 (insert (format "# Insert note for %s.
13835 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13836 (cond
13837 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13838 ((eq org-log-note-purpose 'done) "closed todo item")
13839 ((eq org-log-note-purpose 'state)
13840 (format "state change from \"%s\" to \"%s\""
13841 (or org-log-note-previous-state "")
13842 (or org-log-note-state "")))
13843 ((eq org-log-note-purpose 'reschedule)
13844 "rescheduling")
13845 ((eq org-log-note-purpose 'delschedule)
13846 "no longer scheduled")
13847 ((eq org-log-note-purpose 'redeadline)
13848 "changing deadline")
13849 ((eq org-log-note-purpose 'deldeadline)
13850 "removing deadline")
13851 ((eq org-log-note-purpose 'refile)
13852 "refiling")
13853 ((eq org-log-note-purpose 'note)
13854 "this entry")
13855 (t (error "This should not happen")))))
13856 (when org-log-note-extra (insert org-log-note-extra))
13857 (setq-local org-finish-function 'org-store-log-note)
13858 (run-hooks 'org-log-buffer-setup-hook)))
13860 (defvar org-note-abort nil) ; dynamically scoped
13861 (defun org-store-log-note ()
13862 "Finish taking a log note, and insert it to where it belongs."
13863 (let ((txt (prog1 (buffer-string)
13864 (kill-buffer)))
13865 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13866 lines)
13867 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13868 (setq txt (replace-match "" t t txt)))
13869 (when (string-match "\\s-+\\'" txt)
13870 (setq txt (replace-match "" t t txt)))
13871 (setq lines (org-split-string txt "\n"))
13872 (when (org-string-nw-p note)
13873 (setq note
13874 (org-replace-escapes
13875 note
13876 (list (cons "%u" (user-login-name))
13877 (cons "%U" user-full-name)
13878 (cons "%t" (format-time-string
13879 (org-time-stamp-format 'long 'inactive)
13880 org-log-note-effective-time))
13881 (cons "%T" (format-time-string
13882 (org-time-stamp-format 'long nil)
13883 org-log-note-effective-time))
13884 (cons "%d" (format-time-string
13885 (org-time-stamp-format nil 'inactive)
13886 org-log-note-effective-time))
13887 (cons "%D" (format-time-string
13888 (org-time-stamp-format nil nil)
13889 org-log-note-effective-time))
13890 (cons "%s" (cond
13891 ((not org-log-note-state) "")
13892 ((string-match-p org-ts-regexp
13893 org-log-note-state)
13894 (format "\"[%s]\""
13895 (substring org-log-note-state 1 -1)))
13896 (t (format "\"%s\"" org-log-note-state))))
13897 (cons "%S"
13898 (cond
13899 ((not org-log-note-previous-state) "")
13900 ((string-match-p org-ts-regexp
13901 org-log-note-previous-state)
13902 (format "\"[%s]\""
13903 (substring
13904 org-log-note-previous-state 1 -1)))
13905 (t (format "\"%s\""
13906 org-log-note-previous-state)))))))
13907 (when lines (setq note (concat note " \\\\")))
13908 (push note lines))
13909 (when (and lines (not (or current-prefix-arg org-note-abort)))
13910 (with-current-buffer (marker-buffer org-log-note-marker)
13911 (org-with-wide-buffer
13912 ;; Find location for the new note.
13913 (goto-char org-log-note-marker)
13914 (set-marker org-log-note-marker nil)
13915 ;; Note associated to a clock is to be located right after
13916 ;; the clock. Do not move point.
13917 (unless (eq org-log-note-purpose 'clock-out)
13918 (goto-char (org-log-beginning t)))
13919 ;; Make sure point is at the beginning of an empty line.
13920 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13921 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13922 ;; In an existing list, add a new item at the top level.
13923 ;; Otherwise, indent line like a regular one.
13924 (let ((itemp (org-in-item-p)))
13925 (if itemp
13926 (indent-line-to
13927 (let ((struct (save-excursion
13928 (goto-char itemp) (org-list-struct))))
13929 (org-list-get-ind (org-list-get-top-point struct) struct)))
13930 (org-indent-line)))
13931 (insert (org-list-bullet-string "-") (pop lines))
13932 (let ((ind (org-list-item-body-column (line-beginning-position))))
13933 (dolist (line lines)
13934 (insert "\n")
13935 (indent-line-to ind)
13936 (insert line)))
13937 (message "Note stored")
13938 (org-back-to-heading t)
13939 (org-cycle-hide-drawers 'children))
13940 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13941 ;; from within `org-add-log-note' because `buffer-undo-list'
13942 ;; is then modified outside of `org-with-remote-undo'.
13943 (when (eq this-command 'org-agenda-todo)
13944 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13945 ;; Don't add undo information when called from `org-agenda-todo'.
13946 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13947 (set-window-configuration org-log-note-window-configuration)
13948 (with-current-buffer (marker-buffer org-log-note-return-to)
13949 (goto-char org-log-note-return-to))
13950 (move-marker org-log-note-return-to nil)
13951 (when org-log-post-message (message "%s" org-log-post-message))))
13953 (defun org-remove-empty-drawer-at (pos)
13954 "Remove an empty drawer at position POS.
13955 POS may also be a marker."
13956 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13957 (org-with-wide-buffer
13958 (goto-char pos)
13959 (let ((drawer (org-element-at-point)))
13960 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13961 (not (org-element-property :contents-begin drawer)))
13962 (delete-region (org-element-property :begin drawer)
13963 (progn (goto-char (org-element-property :end drawer))
13964 (skip-chars-backward " \r\t\n")
13965 (forward-line)
13966 (point))))))))
13968 (defvar org-ts-type nil)
13969 (defun org-sparse-tree (&optional arg type)
13970 "Create a sparse tree, prompt for the details.
13971 This command can create sparse trees. You first need to select the type
13972 of match used to create the tree:
13974 t Show all TODO entries.
13975 T Show entries with a specific TODO keyword.
13976 m Show entries selected by a tags/property match.
13977 p Enter a property name and its value (both with completion on existing
13978 names/values) and show entries with that property.
13979 r Show entries matching a regular expression (`/' can be used as well).
13980 b Show deadlines and scheduled items before a date.
13981 a Show deadlines and scheduled items after a date.
13982 d Show deadlines due within `org-deadline-warning-days'.
13983 D Show deadlines and scheduled items between a date range."
13984 (interactive "P")
13985 (setq type (or type org-sparse-tree-default-date-type))
13986 (setq org-ts-type type)
13987 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13988 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13989 \[c]ycle through date types: %s"
13990 (cl-case type
13991 (all "all timestamps")
13992 (scheduled "only scheduled")
13993 (deadline "only deadline")
13994 (active "only active timestamps")
13995 (inactive "only inactive timestamps")
13996 (closed "with a closed time-stamp")
13997 (otherwise "scheduled/deadline")))
13998 (let ((answer (read-char-exclusive)))
13999 (cl-case answer
14001 (org-sparse-tree
14003 (cadr
14004 (memq type '(nil all scheduled deadline active inactive closed)))))
14005 (?d (call-interactively 'org-check-deadlines))
14006 (?b (call-interactively 'org-check-before-date))
14007 (?a (call-interactively 'org-check-after-date))
14008 (?D (call-interactively 'org-check-dates-range))
14009 (?t (call-interactively 'org-show-todo-tree))
14010 (?T (org-show-todo-tree '(4)))
14011 (?m (call-interactively 'org-match-sparse-tree))
14012 ((?p ?P)
14013 (let* ((kwd (completing-read
14014 "Property: " (mapcar #'list (org-buffer-property-keys))))
14015 (value (completing-read
14016 "Value: " (mapcar #'list (org-property-values kwd)))))
14017 (unless (string-match "\\`{.*}\\'" value)
14018 (setq value (concat "\"" value "\"")))
14019 (org-match-sparse-tree arg (concat kwd "=" value))))
14020 ((?r ?R ?/) (call-interactively 'org-occur))
14021 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
14023 (defvar-local org-occur-highlights nil
14024 "List of overlays used for occur matches.")
14025 (defvar-local org-occur-parameters nil
14026 "Parameters of the active org-occur calls.
14027 This is a list, each call to org-occur pushes as cons cell,
14028 containing the regular expression and the callback, onto the list.
14029 The list can contain several entries if `org-occur' has been called
14030 several time with the KEEP-PREVIOUS argument. Otherwise, this list
14031 will only contain one set of parameters. When the highlights are
14032 removed (for example with `C-c C-c', or with the next edit (depending
14033 on `org-remove-highlights-with-change'), this variable is emptied
14034 as well.")
14036 (defun org-occur (regexp &optional keep-previous callback)
14037 "Make a compact tree which shows all matches of REGEXP.
14039 The tree will show the lines where the regexp matches, and any other context
14040 defined in `org-show-context-detail', which see.
14042 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
14043 done by a previous call to `org-occur' will be kept, to allow stacking of
14044 calls to this command.
14046 Optional argument CALLBACK can be a function of no argument. In this case,
14047 it is called with point at the end of the match, match data being set
14048 accordingly. Current match is shown only if the return value is non-nil.
14049 The function must neither move point nor alter narrowing."
14050 (interactive "sRegexp: \nP")
14051 (when (equal regexp "")
14052 (user-error "Regexp cannot be empty"))
14053 (unless keep-previous
14054 (org-remove-occur-highlights nil nil t))
14055 (push (cons regexp callback) org-occur-parameters)
14056 (let ((cnt 0))
14057 (save-excursion
14058 (goto-char (point-min))
14059 (when (or (not keep-previous) ; do not want to keep
14060 (not org-occur-highlights)) ; no previous matches
14061 ;; hide everything
14062 (org-overview))
14063 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
14064 (isearch-no-upper-case-p regexp t)
14065 org-occur-case-fold-search)))
14066 (while (re-search-forward regexp nil t)
14067 (when (or (not callback)
14068 (save-match-data (funcall callback)))
14069 (setq cnt (1+ cnt))
14070 (when org-highlight-sparse-tree-matches
14071 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14072 (org-show-context 'occur-tree)))))
14073 (when org-remove-highlights-with-change
14074 (add-hook 'before-change-functions 'org-remove-occur-highlights
14075 nil 'local))
14076 (unless org-sparse-tree-open-archived-trees
14077 (org-hide-archived-subtrees (point-min) (point-max)))
14078 (run-hooks 'org-occur-hook)
14079 (when (called-interactively-p 'interactive)
14080 (message "%d match(es) for regexp %s" cnt regexp))
14081 cnt))
14083 (defun org-occur-next-match (&optional n _reset)
14084 "Function for `next-error-function' to find sparse tree matches.
14085 N is the number of matches to move, when negative move backwards.
14086 This function always goes back to the starting point when no
14087 match is found."
14088 (let* ((limit (if (< n 0) (point-min) (point-max)))
14089 (search-func (if (< n 0)
14090 'previous-single-char-property-change
14091 'next-single-char-property-change))
14092 (n (abs n))
14093 (pos (point))
14095 (catch 'exit
14096 (while (setq p1 (funcall search-func (point) 'org-type))
14097 (when (equal p1 limit)
14098 (goto-char pos)
14099 (user-error "No more matches"))
14100 (when (equal (get-char-property p1 'org-type) 'org-occur)
14101 (setq n (1- n))
14102 (when (= n 0)
14103 (goto-char p1)
14104 (throw 'exit (point))))
14105 (goto-char p1))
14106 (goto-char p1)
14107 (user-error "No more matches"))))
14109 (defun org-show-context (&optional key)
14110 "Make sure point and context are visible.
14111 Optional argument KEY, when non-nil, is a symbol. See
14112 `org-show-context-detail' for allowed values and how much is to
14113 be shown."
14114 (org-show-set-visibility
14115 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14116 ((cdr (assq key org-show-context-detail)))
14117 (t (cdr (assq 'default org-show-context-detail))))))
14119 (defun org-show-set-visibility (detail)
14120 "Set visibility around point according to DETAIL.
14121 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14122 `tree', `canonical' or t. See `org-show-context-detail' for more
14123 information."
14124 ;; Show current heading and possibly its entry, following headline
14125 ;; or all children.
14126 (if (and (org-at-heading-p) (not (eq detail 'local)))
14127 (org-flag-heading nil)
14128 (org-show-entry)
14129 ;; If point is hidden within a drawer or a block, make sure to
14130 ;; expose it.
14131 (dolist (o (overlays-at (point)))
14132 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14133 (delete-overlay o)))
14134 (unless (org-before-first-heading-p)
14135 (org-with-limited-levels
14136 (cl-case detail
14137 ((tree canonical t) (org-show-children))
14138 ((nil minimal ancestors))
14139 (t (save-excursion
14140 (outline-next-heading)
14141 (org-flag-heading nil)))))))
14142 ;; Show all siblings.
14143 (when (eq detail 'lineage) (org-show-siblings))
14144 ;; Show ancestors, possibly with their children.
14145 (when (memq detail '(ancestors lineage tree canonical t))
14146 (save-excursion
14147 (while (org-up-heading-safe)
14148 (org-flag-heading nil)
14149 (when (memq detail '(canonical t)) (org-show-entry))
14150 (when (memq detail '(tree canonical t)) (org-show-children))))))
14152 (defvar org-reveal-start-hook nil
14153 "Hook run before revealing a location.")
14155 (defun org-reveal (&optional siblings)
14156 "Show current entry, hierarchy above it, and the following headline.
14158 This can be used to show a consistent set of context around
14159 locations exposed with `org-show-context'.
14161 With optional argument SIBLINGS, on each level of the hierarchy all
14162 siblings are shown. This repairs the tree structure to what it would
14163 look like when opened with hierarchical calls to `org-cycle'.
14165 With a \\[universal-argument] \\[universal-argument] prefix, \
14166 go to the parent and show the entire tree."
14167 (interactive "P")
14168 (run-hooks 'org-reveal-start-hook)
14169 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14170 ((equal siblings '(16))
14171 (save-excursion
14172 (when (org-up-heading-safe)
14173 (org-show-subtree)
14174 (run-hook-with-args 'org-cycle-hook 'subtree))))
14175 (t (org-show-set-visibility 'lineage))))
14177 (defun org-highlight-new-match (beg end)
14178 "Highlight from BEG to END and mark the highlight is an occur headline."
14179 (let ((ov (make-overlay beg end)))
14180 (overlay-put ov 'face 'secondary-selection)
14181 (overlay-put ov 'org-type 'org-occur)
14182 (push ov org-occur-highlights)))
14184 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14185 "Remove the occur highlights from the buffer.
14186 BEG and END are ignored. If NOREMOVE is nil, remove this function
14187 from the `before-change-functions' in the current buffer."
14188 (interactive)
14189 (unless org-inhibit-highlight-removal
14190 (mapc #'delete-overlay org-occur-highlights)
14191 (setq org-occur-highlights nil)
14192 (setq org-occur-parameters nil)
14193 (unless noremove
14194 (remove-hook 'before-change-functions
14195 'org-remove-occur-highlights 'local))))
14197 ;;;; Priorities
14199 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14200 "Regular expression matching the priority indicator.")
14202 (defvar org-remove-priority-next-time nil)
14204 (defun org-priority-up ()
14205 "Increase the priority of the current item."
14206 (interactive)
14207 (org-priority 'up))
14209 (defun org-priority-down ()
14210 "Decrease the priority of the current item."
14211 (interactive)
14212 (org-priority 'down))
14214 (defun org-priority (&optional action _show)
14215 "Change the priority of an item.
14216 ACTION can be `set', `up', `down', or a character."
14217 (interactive "P")
14218 (if (equal action '(4))
14219 (org-show-priority)
14220 (unless org-enable-priority-commands
14221 (user-error "Priority commands are disabled"))
14222 (setq action (or action 'set))
14223 (let (current new news have remove)
14224 (save-excursion
14225 (org-back-to-heading t)
14226 (when (looking-at org-priority-regexp)
14227 (setq current (string-to-char (match-string 2))
14228 have t))
14229 (cond
14230 ((eq action 'remove)
14231 (setq remove t new ?\ ))
14232 ((or (eq action 'set)
14233 (integerp action))
14234 (if (not (eq action 'set))
14235 (setq new action)
14236 (message "Priority %c-%c, SPC to remove: "
14237 org-highest-priority org-lowest-priority)
14238 (save-match-data
14239 (setq new (read-char-exclusive))))
14240 (when (and (= (upcase org-highest-priority) org-highest-priority)
14241 (= (upcase org-lowest-priority) org-lowest-priority))
14242 (setq new (upcase new)))
14243 (cond ((equal new ?\ ) (setq remove t))
14244 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14245 (user-error "Priority must be between `%c' and `%c'"
14246 org-highest-priority org-lowest-priority))))
14247 ((eq action 'up)
14248 (setq new (if have
14249 (1- current) ; normal cycling
14250 ;; last priority was empty
14251 (if (eq last-command this-command)
14252 org-lowest-priority ; wrap around empty to lowest
14253 ;; default
14254 (if org-priority-start-cycle-with-default
14255 org-default-priority
14256 (1- org-default-priority))))))
14257 ((eq action 'down)
14258 (setq new (if have
14259 (1+ current) ; normal cycling
14260 ;; last priority was empty
14261 (if (eq last-command this-command)
14262 org-highest-priority ; wrap around empty to highest
14263 ;; default
14264 (if org-priority-start-cycle-with-default
14265 org-default-priority
14266 (1+ org-default-priority))))))
14267 (t (user-error "Invalid action")))
14268 (when (or (< (upcase new) org-highest-priority)
14269 (> (upcase new) org-lowest-priority))
14270 (if (and (memq action '(up down))
14271 (not have) (not (eq last-command this-command)))
14272 ;; `new' is from default priority
14273 (error
14274 "The default can not be set, see `org-default-priority' why")
14275 ;; normal cycling: `new' is beyond highest/lowest priority
14276 ;; and is wrapped around to the empty priority
14277 (setq remove t)))
14278 (setq news (format "%c" new))
14279 (if have
14280 (if remove
14281 (replace-match "" t t nil 1)
14282 (replace-match news t t nil 2))
14283 (if remove
14284 (user-error "No priority cookie found in line")
14285 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14286 (if (match-end 2)
14287 (progn
14288 (goto-char (match-end 2))
14289 (insert " [#" news "]"))
14290 (goto-char (match-beginning 3))
14291 (insert "[#" news "] "))))
14292 (org-set-tags nil 'align))
14293 (if remove
14294 (message "Priority removed")
14295 (message "Priority of current item set to %s" news)))))
14297 (defun org-show-priority ()
14298 "Show the priority of the current item.
14299 This priority is composed of the main priority given with the [#A] cookies,
14300 and by additional input from the age of a schedules or deadline entry."
14301 (interactive)
14302 (let ((pri (if (eq major-mode 'org-agenda-mode)
14303 (org-get-at-bol 'priority)
14304 (save-excursion
14305 (save-match-data
14306 (beginning-of-line)
14307 (and (looking-at org-heading-regexp)
14308 (org-get-priority (match-string 0))))))))
14309 (message "Priority is %d" (if pri pri -1000))))
14311 (defun org-get-priority (s)
14312 "Find priority cookie and return priority."
14313 (save-match-data
14314 (if (functionp org-get-priority-function)
14315 (funcall org-get-priority-function)
14316 (if (not (string-match org-priority-regexp s))
14317 (* 1000 (- org-lowest-priority org-default-priority))
14318 (* 1000 (- org-lowest-priority
14319 (string-to-char (match-string 2 s))))))))
14321 ;;;; Tags
14323 (defvar org-agenda-archives-mode)
14324 (defvar org-map-continue-from nil
14325 "Position from where mapping should continue.
14326 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14328 (defvar org-scanner-tags nil
14329 "The current tag list while the tags scanner is running.")
14331 (defvar org-trust-scanner-tags nil
14332 "Should `org-get-tags-at' use the tags for the scanner.
14333 This is for internal dynamical scoping only.
14334 When this is non-nil, the function `org-get-tags-at' will return the value
14335 of `org-scanner-tags' instead of building the list by itself. This
14336 can lead to large speed-ups when the tags scanner is used in a file with
14337 many entries, and when the list of tags is retrieved, for example to
14338 obtain a list of properties. Building the tags list for each entry in such
14339 a file becomes an N^2 operation - but with this variable set, it scales
14340 as N.")
14342 (defvar org--matcher-tags-todo-only nil)
14344 (defun org-scan-tags (action matcher todo-only &optional start-level)
14345 "Scan headline tags with inheritance and produce output ACTION.
14347 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14348 or `agenda' to produce an entry list for an agenda view. It can also be
14349 a Lisp form or a function that should be called at each matched headline, in
14350 this case the return value is a list of all return values from these calls.
14352 MATCHER is a function accepting three arguments, returning
14353 a non-nil value whenever a given set of tags qualifies a headline
14354 for inclusion. See `org-make-tags-matcher' for more information.
14355 As a special case, it can also be set to t (respectively nil) in
14356 order to match all (respectively none) headline.
14358 When TODO-ONLY is non-nil, only lines with a not-done TODO
14359 keyword are included in the output.
14361 START-LEVEL can be a string with asterisks, reducing the scope to
14362 headlines matching this string."
14363 (require 'org-agenda)
14364 (let* ((re (concat "^"
14365 (if start-level
14366 ;; Get the correct level to match
14367 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14368 org-outline-regexp)
14369 " *\\(\\<\\("
14370 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14371 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14372 (props (list 'face 'default
14373 'done-face 'org-agenda-done
14374 'undone-face 'default
14375 'mouse-face 'highlight
14376 'org-not-done-regexp org-not-done-regexp
14377 'org-todo-regexp org-todo-regexp
14378 'org-complex-heading-regexp org-complex-heading-regexp
14379 'help-echo
14380 (format "mouse-2 or RET jump to org file %s"
14381 (abbreviate-file-name
14382 (or (buffer-file-name (buffer-base-buffer))
14383 (buffer-name (buffer-base-buffer)))))))
14384 (org-map-continue-from nil)
14385 lspos tags tags-list
14386 (tags-alist (list (cons 0 org-file-tags)))
14387 (llast 0) rtn rtn1 level category i txt
14388 todo marker entry priority
14389 ts-date ts-date-type ts-date-pair)
14390 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14391 (setq action (list 'lambda nil action)))
14392 (save-excursion
14393 (goto-char (point-min))
14394 (when (eq action 'sparse-tree)
14395 (org-overview)
14396 (org-remove-occur-highlights))
14397 (while (let (case-fold-search)
14398 (re-search-forward re nil t))
14399 (setq org-map-continue-from nil)
14400 (catch :skip
14401 (setq todo
14402 ;; TODO: is the 1-2 difference a bug?
14403 (when (match-end 1) (match-string-no-properties 2))
14404 tags (when (match-end 4) (match-string-no-properties 4)))
14405 (goto-char (setq lspos (match-beginning 0)))
14406 (setq level (org-reduced-level (org-outline-level))
14407 category (org-get-category))
14408 (when (eq action 'agenda)
14409 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14410 ts-date (car ts-date-pair)
14411 ts-date-type (cdr ts-date-pair)))
14412 (setq i llast llast level)
14413 ;; remove tag lists from same and sublevels
14414 (while (>= i level)
14415 (when (setq entry (assoc i tags-alist))
14416 (setq tags-alist (delete entry tags-alist)))
14417 (setq i (1- i)))
14418 ;; add the next tags
14419 (when tags
14420 (setq tags (org-split-string tags ":")
14421 tags-alist
14422 (cons (cons level tags) tags-alist)))
14423 ;; compile tags for current headline
14424 (setq tags-list
14425 (if org-use-tag-inheritance
14426 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14427 tags)
14428 org-scanner-tags tags-list)
14429 (when org-use-tag-inheritance
14430 (setcdr (car tags-alist)
14431 (mapcar (lambda (x)
14432 (setq x (copy-sequence x))
14433 (org-add-prop-inherited x))
14434 (cdar tags-alist))))
14435 (when (and tags org-use-tag-inheritance
14436 (or (not (eq t org-use-tag-inheritance))
14437 org-tags-exclude-from-inheritance))
14438 ;; Selective inheritance, remove uninherited ones.
14439 (setcdr (car tags-alist)
14440 (org-remove-uninherited-tags (cdar tags-alist))))
14441 (when (and
14443 ;; eval matcher only when the todo condition is OK
14444 (and (or (not todo-only) (member todo org-not-done-keywords))
14445 (if (functionp matcher)
14446 (let ((case-fold-search t) (org-trust-scanner-tags t))
14447 (funcall matcher todo tags-list level))
14448 matcher))
14450 ;; Call the skipper, but return t if it does not
14451 ;; skip, so that the `and' form continues evaluating.
14452 (progn
14453 (unless (eq action 'sparse-tree) (org-agenda-skip))
14456 ;; Check if timestamps are deselecting this entry
14457 (or (not todo-only)
14458 (and (member todo org-not-done-keywords)
14459 (or (not org-agenda-tags-todo-honor-ignore-options)
14460 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14462 ;; select this headline
14463 (cond
14464 ((eq action 'sparse-tree)
14465 (and org-highlight-sparse-tree-matches
14466 (org-get-heading) (match-end 0)
14467 (org-highlight-new-match
14468 (match-beginning 1) (match-end 1)))
14469 (org-show-context 'tags-tree))
14470 ((eq action 'agenda)
14471 (setq txt (org-agenda-format-item
14473 (concat
14474 (if (eq org-tags-match-list-sublevels 'indented)
14475 (make-string (1- level) ?.) "")
14476 (org-get-heading))
14477 (make-string level ?\s)
14478 category
14479 tags-list)
14480 priority (org-get-priority txt))
14481 (goto-char lspos)
14482 (setq marker (org-agenda-new-marker))
14483 (org-add-props txt props
14484 'org-marker marker 'org-hd-marker marker 'org-category category
14485 'todo-state todo
14486 'ts-date ts-date
14487 'priority priority
14488 'type (concat "tagsmatch" ts-date-type))
14489 (push txt rtn))
14490 ((functionp action)
14491 (setq org-map-continue-from nil)
14492 (save-excursion
14493 (setq rtn1 (funcall action))
14494 (push rtn1 rtn)))
14495 (t (user-error "Invalid action")))
14497 ;; if we are to skip sublevels, jump to end of subtree
14498 (unless org-tags-match-list-sublevels
14499 (org-end-of-subtree t)
14500 (backward-char 1))))
14501 ;; Get the correct position from where to continue
14502 (if org-map-continue-from
14503 (goto-char org-map-continue-from)
14504 (and (= (point) lspos) (end-of-line 1)))))
14505 (when (and (eq action 'sparse-tree)
14506 (not org-sparse-tree-open-archived-trees))
14507 (org-hide-archived-subtrees (point-min) (point-max)))
14508 (nreverse rtn)))
14510 (defun org-remove-uninherited-tags (tags)
14511 "Remove all tags that are not inherited from the list TAGS."
14512 (cond
14513 ((eq org-use-tag-inheritance t)
14514 (if org-tags-exclude-from-inheritance
14515 (org-delete-all org-tags-exclude-from-inheritance tags)
14516 tags))
14517 ((not org-use-tag-inheritance) nil)
14518 ((stringp org-use-tag-inheritance)
14519 (delq nil (mapcar
14520 (lambda (x)
14521 (if (and (string-match org-use-tag-inheritance x)
14522 (not (member x org-tags-exclude-from-inheritance)))
14523 x nil))
14524 tags)))
14525 ((listp org-use-tag-inheritance)
14526 (delq nil (mapcar
14527 (lambda (x)
14528 (if (member x org-use-tag-inheritance) x nil))
14529 tags)))))
14531 (defun org-match-sparse-tree (&optional todo-only match)
14532 "Create a sparse tree according to tags string MATCH.
14534 MATCH is a string with match syntax. It can contain a selection
14535 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14536 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14537 those. See the manual for details.
14539 If optional argument TODO-ONLY is non-nil, only select lines that
14540 are also TODO tasks."
14541 (interactive "P")
14542 (org-agenda-prepare-buffers (list (current-buffer)))
14543 (let ((org--matcher-tags-todo-only todo-only))
14544 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14545 org--matcher-tags-todo-only)))
14547 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14549 (defvar org-cached-props nil)
14550 (defun org-cached-entry-get (pom property)
14551 (if (or (eq t org-use-property-inheritance)
14552 (and (stringp org-use-property-inheritance)
14553 (let ((case-fold-search t))
14554 (string-match-p org-use-property-inheritance property)))
14555 (and (listp org-use-property-inheritance)
14556 (member-ignore-case property org-use-property-inheritance)))
14557 ;; Caching is not possible, check it directly.
14558 (org-entry-get pom property 'inherit)
14559 ;; Get all properties, so we can do complicated checks easily.
14560 (cdr (assoc-string property
14561 (or org-cached-props
14562 (setq org-cached-props (org-entry-properties pom)))
14563 t))))
14565 (defun org-global-tags-completion-table (&optional files)
14566 "Return the list of all tags in all agenda buffer/files.
14567 Optional FILES argument is a list of files which can be used
14568 instead of the agenda files."
14569 (save-excursion
14570 (org-uniquify
14571 (delq nil
14572 (apply #'append
14573 (mapcar
14574 (lambda (file)
14575 (set-buffer (find-file-noselect file))
14576 (mapcar (lambda (x)
14577 (and (stringp (car-safe x))
14578 (list (car-safe x))))
14579 (or org-current-tag-alist (org-get-buffer-tags))))
14580 (if (car-safe files) files
14581 (org-agenda-files))))))))
14583 (defun org-make-tags-matcher (match)
14584 "Create the TAGS/TODO matcher form for the selection string MATCH.
14586 Returns a cons of the selection string MATCH and a function
14587 implementing the matcher.
14589 The matcher is to be called at an Org entry, with point on the
14590 headline, and returns non-nil if the entry matches the selection
14591 string MATCH. It must be called with three arguments: the TODO
14592 keyword at the entry (or nil if none), the list of all tags at
14593 the entry including inherited ones and the reduced level of the
14594 headline. Additionally, the category of the entry, if any, must
14595 be specified as the text property `org-category' on the headline.
14597 This function sets the variable `org--matcher-tags-todo-only' to
14598 a non-nil value if the matcher restricts matching to TODO
14599 entries, otherwise it is not touched.
14601 See also `org-scan-tags'."
14602 (unless match
14603 ;; Get a new match request, with completion against the global
14604 ;; tags table and the local tags in current buffer.
14605 (let ((org-last-tags-completion-table
14606 (org-uniquify
14607 (delq nil (append (org-get-buffer-tags)
14608 (org-global-tags-completion-table))))))
14609 (setq match
14610 (completing-read
14611 "Match: "
14612 'org-tags-completion-function nil nil nil 'org-tags-history))))
14614 (let ((match0 match)
14615 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14616 (start 0)
14617 tagsmatch todomatch tagsmatcher todomatcher)
14619 ;; Expand group tags.
14620 (setq match (org-tags-expand match))
14622 ;; Check if there is a TODO part of this match, which would be the
14623 ;; part after a "/". To make sure that this slash is not part of
14624 ;; a property value to be matched against, we also check that
14625 ;; there is no / after that slash. First, find the last slash.
14626 (let ((s 0))
14627 (while (string-match "/+" match s)
14628 (setq start (match-beginning 0))
14629 (setq s (match-end 0))))
14630 (if (and (string-match "/+" match start)
14631 (not (string-match-p "\"" match start)))
14632 ;; Match contains also a TODO-matching request.
14633 (progn
14634 (setq tagsmatch (substring match 0 (match-beginning 0)))
14635 (setq todomatch (substring match (match-end 0)))
14636 (when (string-prefix-p "!" todomatch)
14637 (setq org--matcher-tags-todo-only t)
14638 (setq todomatch (substring todomatch 1)))
14639 (when (string-match "\\`\\s-*\\'" todomatch)
14640 (setq todomatch nil)))
14641 ;; Only matching tags.
14642 (setq tagsmatch match)
14643 (setq todomatch nil))
14645 ;; Make the tags matcher.
14646 (when (org-string-nw-p tagsmatch)
14647 (let ((orlist nil)
14648 (orterms (org-split-string tagsmatch "|"))
14649 term)
14650 (while (setq term (pop orterms))
14651 (while (and (equal (substring term -1) "\\") orterms)
14652 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14653 (while (string-match re term)
14654 (let* ((rest (substring term (match-end 0)))
14655 (minus (and (match-end 1)
14656 (equal (match-string 1 term) "-")))
14657 (tag (save-match-data
14658 (replace-regexp-in-string
14659 "\\\\-" "-" (match-string 2 term))))
14660 (regexp (eq (string-to-char tag) ?{))
14661 (levelp (match-end 4))
14662 (propp (match-end 5))
14664 (cond
14665 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14666 (levelp
14667 `(,(org-op-to-function (match-string 3 term))
14668 level
14669 ,(string-to-number (match-string 4 term))))
14670 (propp
14671 (let* ((gv (pcase (upcase (match-string 5 term))
14672 ("CATEGORY"
14673 '(get-text-property (point) 'org-category))
14674 ("TODO" 'todo)
14675 (p `(org-cached-entry-get nil ,p))))
14676 (pv (match-string 7 term))
14677 (regexp (eq (string-to-char pv) ?{))
14678 (strp (eq (string-to-char pv) ?\"))
14679 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14680 (po (org-op-to-function (match-string 6 term)
14681 (if timep 'time strp))))
14682 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14683 (when timep (setq pv (org-matcher-time pv)))
14684 (cond ((and regexp (eq po 'org<>))
14685 `(not (string-match ,pv (or ,gv ""))))
14686 (regexp `(string-match ,pv (or ,gv "")))
14687 (strp `(,po (or ,gv "") ,pv))
14689 `(,po
14690 (string-to-number (or ,gv ""))
14691 ,(string-to-number pv))))))
14692 (t `(member ,tag tags-list)))))
14693 (push (if minus `(not ,mm) mm) tagsmatcher)
14694 (setq term rest)))
14695 (push `(and ,@tagsmatcher) orlist)
14696 (setq tagsmatcher nil))
14697 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14699 ;; Make the TODO matcher.
14700 (when (org-string-nw-p todomatch)
14701 (let ((orlist nil))
14702 (dolist (term (org-split-string todomatch "|"))
14703 (while (string-match re term)
14704 (let* ((minus (and (match-end 1)
14705 (equal (match-string 1 term) "-")))
14706 (kwd (match-string 2 term))
14707 (regexp (eq (string-to-char kwd) ?{))
14708 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14709 `(equal todo ,kwd))))
14710 (push (if minus `(not ,mm) mm) todomatcher))
14711 (setq term (substring term (match-end 0))))
14712 (push (if (> (length todomatcher) 1)
14713 (cons 'and todomatcher)
14714 (car todomatcher))
14715 orlist)
14716 (setq todomatcher nil))
14717 (setq todomatcher (cons 'or orlist))))
14719 ;; Return the string and function of the matcher. If no
14720 ;; tags-specific or todo-specific matcher exists, match
14721 ;; everything.
14722 (let ((matcher (if (and tagsmatcher todomatcher)
14723 `(and ,tagsmatcher ,todomatcher)
14724 (or tagsmatcher todomatcher t))))
14725 (when org--matcher-tags-todo-only
14726 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14727 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14729 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14730 "Expand group tags in MATCH.
14732 This replaces every group tag in MATCH with a regexp tag search.
14733 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14734 will be replaced like this:
14736 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14737 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14738 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14740 Replacing by a regexp preserves the structure of the match.
14741 E.g., this expansion
14743 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14745 will match anything tagged with \"Lab\" and \"Home\", or tagged
14746 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14748 A group tag in MATCH can contain regular expressions of its own.
14749 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14750 will be replaced like this:
14752 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14754 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14755 assumed to be a single group tag, and the function will return
14756 the list of tags in this group.
14758 When DOWNCASE is non-nil, expand downcased TAGS."
14759 (if org-group-tags
14760 (let* ((case-fold-search t)
14761 (stable org-mode-syntax-table)
14762 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14763 (taggroups (if downcased
14764 (mapcar (lambda (tg) (mapcar #'downcase tg))
14765 taggroups)
14766 taggroups))
14767 (taggroups-keys (mapcar #'car taggroups))
14768 (return-match (if downcased (downcase match) match))
14769 (count 0)
14770 (work-already-expanded tags-already-expanded)
14771 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14772 ;; @ and _ are allowed as word-components in tags.
14773 (modify-syntax-entry ?@ "w" stable)
14774 (modify-syntax-entry ?_ "w" stable)
14775 ;; Temporarily replace regexp-expressions in the match-expression.
14776 (while (string-match "{.+?}" return-match)
14777 (cl-incf count)
14778 (push (match-string 0 return-match) regexps-in-match)
14779 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14780 (while (and taggroups-keys
14781 (with-syntax-table stable
14782 (string-match
14783 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14784 (regexp-opt taggroups-keys) "\\>\\)")
14785 return-match)))
14786 (let* ((dir (match-string 1 return-match))
14787 (tag (match-string 2 return-match))
14788 (tag (if downcased (downcase tag) tag)))
14789 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14790 (member tag work-already-expanded))
14791 (setq tags-in-group (assoc tag taggroups))
14792 (push tag work-already-expanded)
14793 ;; Recursively expand each tag in the group, if the tag hasn't
14794 ;; already been expanded. Restore the match-data after all recursive calls.
14795 (save-match-data
14796 (let (tags-expanded)
14797 (dolist (x (cdr tags-in-group))
14798 (if (and (member x taggroups-keys)
14799 (not (member x work-already-expanded)))
14800 (setq tags-expanded
14801 (delete-dups
14802 (append
14803 (org-tags-expand x t downcased
14804 work-already-expanded)
14805 tags-expanded)))
14806 (setq tags-expanded
14807 (append (list x) tags-expanded)))
14808 (setq work-already-expanded
14809 (delete-dups
14810 (append tags-expanded
14811 work-already-expanded))))
14812 (setq tags-in-group
14813 (delete-dups (cons (car tags-in-group)
14814 tags-expanded)))))
14815 ;; Filter tag-regexps from tags.
14816 (setq regexp-in-group-escaped
14817 (delq nil (mapcar (lambda (x)
14818 (if (stringp x)
14819 (and (equal "{" (substring x 0 1))
14820 (equal "}" (substring x -1))
14823 tags-in-group))
14824 regexp-in-group
14825 (mapcar (lambda (x)
14826 (substring x 1 -1))
14827 regexp-in-group-escaped)
14828 tags-in-group
14829 (delq nil (mapcar (lambda (x)
14830 (if (stringp x)
14831 (and (not (equal "{" (substring x 0 1)))
14832 (not (equal "}" (substring x -1)))
14835 tags-in-group)))
14836 ;; If single-as-list, do no more in the while-loop.
14837 (if (not single-as-list)
14838 (progn
14839 (when regexp-in-group
14840 (setq regexp-in-group
14841 (concat "\\|"
14842 (mapconcat 'identity regexp-in-group
14843 "\\|"))))
14844 (setq tags-in-group
14845 (concat dir
14846 "{\\<"
14847 (regexp-opt tags-in-group)
14848 "\\>"
14849 regexp-in-group
14850 "}"))
14851 (when (stringp tags-in-group)
14852 (org-add-props tags-in-group '(grouptag t)))
14853 (setq return-match
14854 (replace-match tags-in-group t t return-match)))
14855 (setq tags-in-group
14856 (append regexp-in-group-escaped tags-in-group))))
14857 (setq taggroups-keys (delete tag taggroups-keys))))
14858 ;; Add the regular expressions back into the match-expression again.
14859 (while regexps-in-match
14860 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14861 (pop regexps-in-match)
14862 return-match t t))
14863 (cl-decf count))
14864 (if single-as-list
14865 (if tags-in-group tags-in-group (list return-match))
14866 return-match))
14867 (if single-as-list
14868 (list (if downcased (downcase match) match))
14869 match)))
14871 (defun org-op-to-function (op &optional stringp)
14872 "Turn an operator into the appropriate function."
14873 (setq op
14874 (cond
14875 ((equal op "<" ) '(< string< org-time<))
14876 ((equal op ">" ) '(> org-string> org-time>))
14877 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14878 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14879 ((member op '("=" "==")) '(= string= org-time=))
14880 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14881 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14883 (defun org<> (a b) (not (= a b)))
14884 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14885 (defun org-string>= (a b) (not (string< a b)))
14886 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14887 (defun org-string<> (a b) (not (string= a b)))
14888 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14889 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14890 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14891 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14892 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14893 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14894 (defun org-2ft (s)
14895 "Convert S to a floating point time.
14896 If S is already a number, just return it. If it is a string, parse
14897 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14898 (cond
14899 ((numberp s) s)
14900 ((stringp s)
14901 (condition-case nil
14902 (float-time (apply 'encode-time (org-parse-time-string s)))
14903 (error 0.)))
14904 (t 0.)))
14906 (defun org-time-today ()
14907 "Time in seconds today at 0:00.
14908 Returns the float number of seconds since the beginning of the
14909 epoch to the beginning of today (00:00)."
14910 (float-time (apply 'encode-time
14911 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14913 (defun org-matcher-time (s)
14914 "Interpret a time comparison value."
14915 (save-match-data
14916 (cond
14917 ((string= s "<now>") (float-time))
14918 ((string= s "<today>") (org-time-today))
14919 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14920 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14921 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14922 (+ (org-time-today)
14923 (* (string-to-number (match-string 1 s))
14924 (cdr (assoc (match-string 2 s)
14925 '(("d" . 86400.0) ("w" . 604800.0)
14926 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14927 (t (org-2ft s)))))
14929 (defun org-match-any-p (re list)
14930 "Does re match any element of list?"
14931 (setq list (mapcar (lambda (x) (string-match re x)) list))
14932 (delq nil list))
14934 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14935 (defvar org-tags-overlay (make-overlay 1 1))
14936 (delete-overlay org-tags-overlay)
14938 (defun org-get-local-tags-at (&optional pos)
14939 "Get a list of tags defined in the current headline."
14940 (org-get-tags-at pos 'local))
14942 (defun org-get-local-tags ()
14943 "Get a list of tags defined in the current headline."
14944 (org-get-tags-at nil 'local))
14946 (defun org-get-tags-at (&optional pos local)
14947 "Get a list of all headline tags applicable at POS.
14948 POS defaults to point. If tags are inherited, the list contains
14949 the targets in the same sequence as the headlines appear, i.e.
14950 the tags of the current headline come last.
14951 When LOCAL is non-nil, only return tags from the current headline,
14952 ignore inherited ones."
14953 (interactive)
14954 (if (and org-trust-scanner-tags
14955 (or (not pos) (equal pos (point)))
14956 (not local))
14957 org-scanner-tags
14958 (let (tags ltags lastpos parent)
14959 (save-excursion
14960 (save-restriction
14961 (widen)
14962 (goto-char (or pos (point)))
14963 (save-match-data
14964 (catch 'done
14965 (condition-case nil
14966 (progn
14967 (org-back-to-heading t)
14968 (while (not (equal lastpos (point)))
14969 (setq lastpos (point))
14970 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14971 (setq ltags (org-split-string
14972 (match-string-no-properties 1) ":"))
14973 (when parent
14974 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14975 (setq tags (append
14976 (if parent
14977 (org-remove-uninherited-tags ltags)
14978 ltags)
14979 tags)))
14980 (or org-use-tag-inheritance (throw 'done t))
14981 (when local (throw 'done t))
14982 (or (org-up-heading-safe) (error nil))
14983 (setq parent t)))
14984 (error nil)))))
14985 (if local
14986 tags
14987 (reverse (delete-dups
14988 (reverse (append
14989 (org-remove-uninherited-tags
14990 org-file-tags)
14991 tags)))))))))
14993 (defun org-add-prop-inherited (s)
14994 (add-text-properties 0 (length s) '(inherited t) s)
14997 (defun org-toggle-tag (tag &optional onoff)
14998 "Toggle the tag TAG for the current line.
14999 If ONOFF is `on' or `off', don't toggle but set to this state."
15000 (let (res current)
15001 (save-excursion
15002 (org-back-to-heading t)
15003 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
15004 (point-at-eol) t)
15005 (progn
15006 (setq current (match-string 1))
15007 (replace-match ""))
15008 (setq current ""))
15009 (setq current (nreverse (org-split-string current ":")))
15010 (cond
15011 ((eq onoff 'on)
15012 (setq res t)
15013 (or (member tag current) (push tag current)))
15014 ((eq onoff 'off)
15015 (or (not (member tag current)) (setq current (delete tag current))))
15016 (t (if (member tag current)
15017 (setq current (delete tag current))
15018 (setq res t)
15019 (push tag current))))
15020 (end-of-line 1)
15021 (if current
15022 (progn
15023 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
15024 (org-set-tags nil t))
15025 (delete-horizontal-space))
15026 (run-hooks 'org-after-tags-change-hook))
15027 res))
15029 (defun org--align-tags-here (to-col)
15030 "Align tags on the current headline to TO-COL.
15031 Assume point is on a headline."
15032 (let ((pos (point)))
15033 (beginning-of-line)
15034 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15035 (>= pos (match-beginning 2)))
15036 ;; No tags or point within tags: do not align.
15037 (goto-char pos)
15038 (goto-char (match-beginning 1))
15039 (let ((shift (max (- (if (>= to-col 0) to-col
15040 (- (abs to-col) (string-width (match-string 2))))
15041 (current-column))
15042 1)))
15043 (replace-match (make-string shift ?\s) nil nil nil 1)
15044 ;; Preserve initial position, if possible. In any case, stop
15045 ;; before tags.
15046 (when (< pos (point)) (goto-char pos))))))
15048 (defun org-set-tags-command (&optional arg just-align)
15049 "Call the set-tags command for the current entry."
15050 (interactive "P")
15051 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
15052 (org-set-tags arg just-align)
15053 (save-excursion
15054 (unless (and (org-region-active-p)
15055 org-loop-over-headlines-in-active-region)
15056 (org-back-to-heading t))
15057 (org-set-tags arg just-align))))
15059 (defun org-set-tags-to (data)
15060 "Set the tags of the current entry to DATA, replacing the current tags.
15061 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
15062 If DATA is nil or the empty string, any tags will be removed."
15063 (interactive "sTags: ")
15064 (setq data
15065 (cond
15066 ((eq data nil) "")
15067 ((equal data "") "")
15068 ((stringp data)
15069 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
15070 ":"))
15071 ((listp data)
15072 (concat ":" (mapconcat 'identity data ":") ":"))))
15073 (when data
15074 (save-excursion
15075 (org-back-to-heading t)
15076 (when (let ((case-fold-search nil))
15077 (looking-at org-complex-heading-regexp))
15078 (if (match-end 5)
15079 (progn
15080 (goto-char (match-beginning 5))
15081 (insert data)
15082 (delete-region (point) (point-at-eol))
15083 (org-set-tags nil 'align))
15084 (goto-char (point-at-eol))
15085 (insert " " data)
15086 (org-set-tags nil 'align)))
15087 (beginning-of-line 1)
15088 (when (looking-at ".*?\\([ \t]+\\)$")
15089 (delete-region (match-beginning 1) (match-end 1))))))
15091 (defun org-align-all-tags ()
15092 "Align the tags in all headings."
15093 (interactive)
15094 (save-excursion
15095 (or (ignore-errors (org-back-to-heading t))
15096 (outline-next-heading))
15097 (if (org-at-heading-p)
15098 (org-set-tags t)
15099 (message "No headings"))))
15101 (defvar org-indent-indentation-per-level)
15102 (defun org-set-tags (&optional arg just-align)
15103 "Set the tags for the current headline.
15104 With prefix ARG, realign all tags in headings in the current buffer.
15105 When JUST-ALIGN is non-nil, only align tags."
15106 (interactive "P")
15107 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15108 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15109 'region-start-level
15110 'region))
15111 org-loop-over-headlines-in-active-region)
15112 (org-map-entries
15113 ;; We don't use ARG and JUST-ALIGN here because these args
15114 ;; are not useful when looping over headlines.
15115 #'org-set-tags
15116 org-loop-over-headlines-in-active-region
15118 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15119 (let ((org-setting-tags t))
15120 (if arg
15121 (save-excursion
15122 (goto-char (point-min))
15123 (while (re-search-forward org-outline-regexp-bol nil t)
15124 (org-set-tags nil t)
15125 (end-of-line))
15126 (message "All tags realigned to column %d" org-tags-column))
15127 (let* ((current (org-get-tags-string))
15128 (tags
15129 (if just-align current
15130 ;; Get a new set of tags from the user.
15131 (save-excursion
15132 (let* ((seen)
15133 (table
15134 (setq
15135 org-last-tags-completion-table
15136 ;; Uniquify tags in alists, yet preserve
15137 ;; structure (i.e., keywords).
15138 (delq nil
15139 (mapcar
15140 (lambda (pair)
15141 (let ((head (car pair)))
15142 (cond ((symbolp head) pair)
15143 ((member head seen) nil)
15144 (t (push head seen)
15145 pair))))
15146 (append
15147 (or org-current-tag-alist
15148 (org-get-buffer-tags))
15149 (and
15150 org-complete-tags-always-offer-all-agenda-tags
15151 (org-global-tags-completion-table
15152 (org-agenda-files))))))))
15153 (current-tags (org-split-string current ":"))
15154 (inherited-tags
15155 (nreverse (nthcdr (length current-tags)
15156 (nreverse (org-get-tags-at))))))
15157 (replace-regexp-in-string
15158 "\\([-+&]+\\|,\\)"
15160 (if (or (eq t org-use-fast-tag-selection)
15161 (and org-use-fast-tag-selection
15162 (delq nil (mapcar #'cdr table))))
15163 (org-fast-tag-selection
15164 current-tags inherited-tags table
15165 (and org-fast-tag-selection-include-todo
15166 org-todo-key-alist))
15167 (let ((org-add-colon-after-tag-completion
15168 (< 1 (length table))))
15169 (org-trim
15170 (completing-read
15171 "Tags: "
15172 #'org-tags-completion-function
15173 nil nil current 'org-tags-history))))))))))
15175 (when org-tags-sort-function
15176 (setq tags
15177 (mapconcat
15178 #'identity
15179 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15180 org-tags-sort-function)
15181 ":")))
15183 (if (or (string= ":" tags)
15184 (string= "::" tags))
15185 (setq tags ""))
15186 (if (not (org-string-nw-p tags)) (setq tags "")
15187 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
15188 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
15190 ;; Insert new tags at the correct column.
15191 (unless (equal current tags)
15192 (save-excursion
15193 (beginning-of-line)
15194 (let ((case-fold-search nil))
15195 (looking-at org-complex-heading-regexp))
15196 ;; Remove current tags, if any.
15197 (when (match-end 5) (replace-match "" nil nil nil 5))
15198 ;; Insert new tags, if any. Otherwise, remove trailing
15199 ;; white spaces.
15200 (end-of-line)
15201 (if (not (equal tags ""))
15202 ;; When text is being inserted on an invisible
15203 ;; region boundary, it can be inadvertently sucked
15204 ;; into invisibility.
15205 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
15206 (skip-chars-backward " \t")
15207 (delete-region (point) (line-end-position)))))
15208 ;; Align tags, if any. Fix tags column if `org-indent-mode'
15209 ;; is on.
15210 (unless (equal tags "")
15211 (let* ((level (save-excursion
15212 (beginning-of-line)
15213 (skip-chars-forward "\\*")))
15214 (offset (if (bound-and-true-p org-indent-mode)
15215 (* (1- org-indent-indentation-per-level)
15216 (1- level))
15218 (tags-column
15219 (+ org-tags-column
15220 (if (> org-tags-column 0) (- offset) offset))))
15221 (org--align-tags-here tags-column))))
15222 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15224 (defun org-change-tag-in-region (beg end tag off)
15225 "Add or remove TAG for each entry in the region.
15226 This works in the agenda, and also in an Org buffer."
15227 (interactive
15228 (list (region-beginning) (region-end)
15229 (let ((org-last-tags-completion-table
15230 (if (derived-mode-p 'org-mode)
15231 (org-uniquify
15232 (delq nil (append (org-get-buffer-tags)
15233 (org-global-tags-completion-table))))
15234 (org-global-tags-completion-table))))
15235 (completing-read
15236 "Tag: " 'org-tags-completion-function nil nil nil
15237 'org-tags-history))
15238 (progn
15239 (message "[s]et or [r]emove? ")
15240 (equal (read-char-exclusive) ?r))))
15241 (when (fboundp 'deactivate-mark) (deactivate-mark))
15242 (let ((agendap (equal major-mode 'org-agenda-mode))
15243 l1 l2 m buf pos newhead (cnt 0))
15244 (goto-char end)
15245 (setq l2 (1- (org-current-line)))
15246 (goto-char beg)
15247 (setq l1 (org-current-line))
15248 (cl-loop for l from l1 to l2 do
15249 (org-goto-line l)
15250 (setq m (get-text-property (point) 'org-hd-marker))
15251 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15252 (and agendap m))
15253 (setq buf (if agendap (marker-buffer m) (current-buffer))
15254 pos (if agendap m (point)))
15255 (with-current-buffer buf
15256 (save-excursion
15257 (save-restriction
15258 (goto-char pos)
15259 (setq cnt (1+ cnt))
15260 (org-toggle-tag tag (if off 'off 'on))
15261 (setq newhead (org-get-heading)))))
15262 (and agendap (org-agenda-change-all-lines newhead m))))
15263 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15265 (defun org-tags-completion-function (string _predicate &optional flag)
15266 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15267 (confirm (lambda (x) (stringp (car x)))))
15268 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15269 (setq s1 (match-string 1 string)
15270 s2 (match-string 2 string))
15271 (setq s1 "" s2 string))
15272 (cond
15273 ((eq flag nil)
15274 ;; try completion
15275 (setq rtn (try-completion s2 ctable confirm))
15276 (when (stringp rtn)
15277 (setq rtn
15278 (concat s1 s2 (substring rtn (length s2))
15279 (if (and org-add-colon-after-tag-completion
15280 (assoc rtn ctable))
15281 ":" ""))))
15282 rtn)
15283 ((eq flag t)
15284 ;; all-completions
15285 (all-completions s2 ctable confirm))
15286 ((eq flag 'lambda)
15287 ;; exact match?
15288 (assoc s2 ctable)))))
15290 (defun org-fast-tag-insert (kwd tags face &optional end)
15291 "Insert KDW, and the TAGS, the latter with face FACE.
15292 Also insert END."
15293 (insert (format "%-12s" (concat kwd ":"))
15294 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15295 (or end "")))
15297 (defun org-fast-tag-show-exit (flag)
15298 (save-excursion
15299 (org-goto-line 3)
15300 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15301 (replace-match ""))
15302 (when flag
15303 (end-of-line 1)
15304 (org-move-to-column (- (window-width) 19) t)
15305 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15307 (defun org-set-current-tags-overlay (current prefix)
15308 "Add an overlay to CURRENT tag with PREFIX."
15309 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15310 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15311 (org-overlay-display org-tags-overlay (concat prefix s))))
15313 (defvar org-last-tag-selection-key nil)
15314 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15315 "Fast tag selection with single keys.
15316 CURRENT is the current list of tags in the headline, INHERITED is the
15317 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15318 possibly with grouping information. TODO-TABLE is a similar table with
15319 TODO keywords, should these have keys assigned to them.
15320 If the keys are nil, a-z are automatically assigned.
15321 Returns the new tags string, or nil to not change the current settings."
15322 (let* ((fulltable (append table todo-table))
15323 (maxlen (apply 'max (mapcar
15324 (lambda (x)
15325 (if (stringp (car x)) (string-width (car x)) 0))
15326 fulltable)))
15327 (buf (current-buffer))
15328 (expert (eq org-fast-tag-selection-single-key 'expert))
15329 (buffer-tags nil)
15330 (fwidth (+ maxlen 3 1 3))
15331 (ncol (/ (- (window-width) 4) fwidth))
15332 (i-face 'org-done)
15333 (c-face 'org-todo)
15334 tg cnt e c char c1 c2 ntable tbl rtn
15335 ov-start ov-end ov-prefix
15336 (exit-after-next org-fast-tag-selection-single-key)
15337 (done-keywords org-done-keywords)
15338 groups ingroup intaggroup)
15339 (save-excursion
15340 (beginning-of-line 1)
15341 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15342 (setq ov-start (match-beginning 1)
15343 ov-end (match-end 1)
15344 ov-prefix "")
15345 (setq ov-start (1- (point-at-eol))
15346 ov-end (1+ ov-start))
15347 (skip-chars-forward "^\n\r")
15348 (setq ov-prefix
15349 (concat
15350 (buffer-substring (1- (point)) (point))
15351 (if (> (current-column) org-tags-column)
15353 (make-string (- org-tags-column (current-column)) ?\ ))))))
15354 (move-overlay org-tags-overlay ov-start ov-end)
15355 (save-window-excursion
15356 (if expert
15357 (set-buffer (get-buffer-create " *Org tags*"))
15358 (delete-other-windows)
15359 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15360 (org-switch-to-buffer-other-window " *Org tags*"))
15361 (erase-buffer)
15362 (setq-local org-done-keywords done-keywords)
15363 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15364 (org-fast-tag-insert "Current" current c-face "\n\n")
15365 (org-fast-tag-show-exit exit-after-next)
15366 (org-set-current-tags-overlay current ov-prefix)
15367 (setq tbl fulltable char ?a cnt 0)
15368 (while (setq e (pop tbl))
15369 (cond
15370 ((eq (car e) :startgroup)
15371 (push '() groups) (setq ingroup t)
15372 (unless (zerop cnt)
15373 (setq cnt 0)
15374 (insert "\n"))
15375 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15376 ((eq (car e) :endgroup)
15377 (setq ingroup nil cnt 0)
15378 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15379 ((eq (car e) :startgrouptag)
15380 (setq intaggroup t)
15381 (unless (zerop cnt)
15382 (setq cnt 0)
15383 (insert "\n"))
15384 (insert "[ "))
15385 ((eq (car e) :endgrouptag)
15386 (setq intaggroup nil cnt 0)
15387 (insert "]\n"))
15388 ((equal e '(:newline))
15389 (unless (zerop cnt)
15390 (setq cnt 0)
15391 (insert "\n")
15392 (setq e (car tbl))
15393 (while (equal (car tbl) '(:newline))
15394 (insert "\n")
15395 (setq tbl (cdr tbl)))))
15396 ((equal e '(:grouptags)) (insert " : "))
15398 (setq tg (copy-sequence (car e)) c2 nil)
15399 (if (cdr e)
15400 (setq c (cdr e))
15401 ;; automatically assign a character.
15402 (setq c1 (string-to-char
15403 (downcase (substring
15404 tg (if (= (string-to-char tg) ?@) 1 0)))))
15405 (if (or (rassoc c1 ntable) (rassoc c1 table))
15406 (while (or (rassoc char ntable) (rassoc char table))
15407 (setq char (1+ char)))
15408 (setq c2 c1))
15409 (setq c (or c2 char)))
15410 (when ingroup (push tg (car groups)))
15411 (setq tg (org-add-props tg nil 'face
15412 (cond
15413 ((not (assoc tg table))
15414 (org-get-todo-face tg))
15415 ((member tg current) c-face)
15416 ((member tg inherited) i-face))))
15417 (when (equal (caar tbl) :grouptags)
15418 (org-add-props tg nil 'face 'org-tag-group))
15419 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15420 (insert "[" c "] " tg (make-string
15421 (- fwidth 4 (length tg)) ?\ ))
15422 (push (cons tg c) ntable)
15423 (when (= (cl-incf cnt) ncol)
15424 (insert "\n")
15425 (when (or ingroup intaggroup) (insert " "))
15426 (setq cnt 0)))))
15427 (setq ntable (nreverse ntable))
15428 (insert "\n")
15429 (goto-char (point-min))
15430 (unless expert (org-fit-window-to-buffer))
15431 (setq rtn
15432 (catch 'exit
15433 (while t
15434 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15435 (if (not groups) "no " "")
15436 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15437 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15438 (setq org-last-tag-selection-key c)
15439 (cond
15440 ((= c ?\r) (throw 'exit t))
15441 ((= c ?!)
15442 (setq groups (not groups))
15443 (goto-char (point-min))
15444 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15445 ((= c ?\C-c)
15446 (if (not expert)
15447 (org-fast-tag-show-exit
15448 (setq exit-after-next (not exit-after-next)))
15449 (setq expert nil)
15450 (delete-other-windows)
15451 (set-window-buffer (split-window-vertically) " *Org tags*")
15452 (org-switch-to-buffer-other-window " *Org tags*")
15453 (org-fit-window-to-buffer)))
15454 ((or (= c ?\C-g)
15455 (and (= c ?q) (not (rassoc c ntable))))
15456 (delete-overlay org-tags-overlay)
15457 (setq quit-flag t))
15458 ((= c ?\ )
15459 (setq current nil)
15460 (when exit-after-next (setq exit-after-next 'now)))
15461 ((= c ?\t)
15462 (condition-case nil
15463 (setq tg (completing-read
15464 "Tag: "
15465 (or buffer-tags
15466 (with-current-buffer buf
15467 (setq buffer-tags
15468 (org-get-buffer-tags))))))
15469 (quit (setq tg "")))
15470 (when (string-match "\\S-" tg)
15471 (cl-pushnew (list tg) buffer-tags :test #'equal)
15472 (if (member tg current)
15473 (setq current (delete tg current))
15474 (push tg current)))
15475 (when exit-after-next (setq exit-after-next 'now)))
15476 ((setq e (rassoc c todo-table) tg (car e))
15477 (with-current-buffer buf
15478 (save-excursion (org-todo tg)))
15479 (when exit-after-next (setq exit-after-next 'now)))
15480 ((setq e (rassoc c ntable) tg (car e))
15481 (if (member tg current)
15482 (setq current (delete tg current))
15483 (cl-loop for g in groups do
15484 (when (member tg g)
15485 (dolist (x g) (setq current (delete x current)))))
15486 (push tg current))
15487 (when exit-after-next (setq exit-after-next 'now))))
15489 ;; Create a sorted list
15490 (setq current
15491 (sort current
15492 (lambda (a b)
15493 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15494 (when (eq exit-after-next 'now) (throw 'exit t))
15495 (goto-char (point-min))
15496 (beginning-of-line 2)
15497 (delete-region (point) (point-at-eol))
15498 (org-fast-tag-insert "Current" current c-face)
15499 (org-set-current-tags-overlay current ov-prefix)
15500 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15501 (setq tg (match-string 1))
15502 (add-text-properties
15503 (match-beginning 1) (match-end 1)
15504 (list 'face
15505 (cond
15506 ((member tg current) c-face)
15507 ((member tg inherited) i-face)
15508 (t (get-text-property (match-beginning 1) 'face))))))
15509 (goto-char (point-min)))))
15510 (delete-overlay org-tags-overlay)
15511 (if rtn
15512 (mapconcat 'identity current ":")
15513 nil))))
15515 (defun org-get-tags-string ()
15516 "Get the TAGS string in the current headline."
15517 (unless (org-at-heading-p t)
15518 (user-error "Not on a heading"))
15519 (save-excursion
15520 (beginning-of-line 1)
15521 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15522 (match-string-no-properties 1)
15523 "")))
15525 (defun org-get-tags ()
15526 "Get the list of tags specified in the current headline."
15527 (org-split-string (org-get-tags-string) ":"))
15529 (defun org-get-buffer-tags ()
15530 "Get a table of all tags used in the buffer, for completion."
15531 (org-with-wide-buffer
15532 (goto-char (point-min))
15533 (let ((tag-re (concat org-outline-regexp-bol
15534 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15535 tags)
15536 (while (re-search-forward tag-re nil t)
15537 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15538 (push tag tags)))
15539 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15541 ;;;; The mapping API
15543 (defvar org-agenda-skip-comment-trees)
15544 (defvar org-agenda-skip-function)
15545 (defun org-map-entries (func &optional match scope &rest skip)
15546 "Call FUNC at each headline selected by MATCH in SCOPE.
15548 FUNC is a function or a lisp form. The function will be called without
15549 arguments, with the cursor positioned at the beginning of the headline.
15550 The return values of all calls to the function will be collected and
15551 returned as a list.
15553 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15554 does not need to preserve point. After evaluation, the cursor will be
15555 moved to the end of the line (presumably of the headline of the
15556 processed entry) and search continues from there. Under some
15557 circumstances, this may not produce the wanted results. For example,
15558 if you have removed (e.g. archived) the current (sub)tree it could
15559 mean that the next entry will be skipped entirely. In such cases, you
15560 can specify the position from where search should continue by making
15561 FUNC set the variable `org-map-continue-from' to the desired buffer
15562 position.
15564 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15565 Only headlines that are matched by this query will be considered during
15566 the iteration. When MATCH is nil or t, all headlines will be
15567 visited by the iteration.
15569 SCOPE determines the scope of this command. It can be any of:
15571 nil The current buffer, respecting the restriction if any
15572 tree The subtree started with the entry at point
15573 region The entries within the active region, if any
15574 region-start-level
15575 The entries within the active region, but only those at
15576 the same level than the first one.
15577 file The current buffer, without restriction
15578 file-with-archives
15579 The current buffer, and any archives associated with it
15580 agenda All agenda files
15581 agenda-with-archives
15582 All agenda files with any archive files associated with them
15583 \(file1 file2 ...)
15584 If this is a list, all files in the list will be scanned
15586 The remaining args are treated as settings for the skipping facilities of
15587 the scanner. The following items can be given here:
15589 archive skip trees with the archive tag
15590 comment skip trees with the COMMENT keyword
15591 function or Emacs Lisp form:
15592 will be used as value for `org-agenda-skip-function', so
15593 whenever the function returns a position, FUNC will not be
15594 called for that entry and search will continue from the
15595 position returned
15597 If your function needs to retrieve the tags including inherited tags
15598 at the *current* entry, you can use the value of the variable
15599 `org-scanner-tags' which will be much faster than getting the value
15600 with `org-get-tags-at'. If your function gets properties with
15601 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15602 to t around the call to `org-entry-properties' to get the same speedup.
15603 Note that if your function moves around to retrieve tags and properties at
15604 a *different* entry, you cannot use these techniques."
15605 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15606 (not (org-region-active-p)))
15607 (let* ((org-agenda-archives-mode nil) ; just to make sure
15608 (org-agenda-skip-archived-trees (memq 'archive skip))
15609 (org-agenda-skip-comment-trees (memq 'comment skip))
15610 (org-agenda-skip-function
15611 (car (org-delete-all '(comment archive) skip)))
15612 (org-tags-match-list-sublevels t)
15613 (start-level (eq scope 'region-start-level))
15614 matcher res
15615 org-todo-keywords-for-agenda
15616 org-done-keywords-for-agenda
15617 org-todo-keyword-alist-for-agenda
15618 org-tag-alist-for-agenda
15619 org--matcher-tags-todo-only)
15621 (cond
15622 ((eq match t) (setq matcher t))
15623 ((eq match nil) (setq matcher t))
15624 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15626 (save-excursion
15627 (save-restriction
15628 (cond ((eq scope 'tree)
15629 (org-back-to-heading t)
15630 (org-narrow-to-subtree)
15631 (setq scope nil))
15632 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15633 (org-region-active-p))
15634 ;; If needed, set start-level to a string like "2"
15635 (when start-level
15636 (save-excursion
15637 (goto-char (region-beginning))
15638 (unless (org-at-heading-p) (outline-next-heading))
15639 (setq start-level (org-current-level))))
15640 (narrow-to-region (region-beginning)
15641 (save-excursion
15642 (goto-char (region-end))
15643 (unless (and (bolp) (org-at-heading-p))
15644 (outline-next-heading))
15645 (point)))
15646 (setq scope nil)))
15648 (if (not scope)
15649 (progn
15650 (org-agenda-prepare-buffers
15651 (and buffer-file-name (list buffer-file-name)))
15652 (setq res
15653 (org-scan-tags
15654 func matcher org--matcher-tags-todo-only start-level)))
15655 ;; Get the right scope
15656 (cond
15657 ((and scope (listp scope) (symbolp (car scope)))
15658 (setq scope (eval scope)))
15659 ((eq scope 'agenda)
15660 (setq scope (org-agenda-files t)))
15661 ((eq scope 'agenda-with-archives)
15662 (setq scope (org-agenda-files t))
15663 (setq scope (org-add-archive-files scope)))
15664 ((eq scope 'file)
15665 (setq scope (and buffer-file-name (list buffer-file-name))))
15666 ((eq scope 'file-with-archives)
15667 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15668 (org-agenda-prepare-buffers scope)
15669 (dolist (file scope)
15670 (with-current-buffer (org-find-base-buffer-visiting file)
15671 (org-with-wide-buffer
15672 (goto-char (point-min))
15673 (setq res
15674 (append
15676 (org-scan-tags
15677 func matcher org--matcher-tags-todo-only)))))))))
15678 res)))
15680 ;;; Properties API
15682 (defconst org-special-properties
15683 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15684 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15685 "The special properties valid in Org mode.
15686 These are properties that are not defined in the property drawer,
15687 but in some other way.")
15689 (defconst org-default-properties
15690 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15691 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15692 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15693 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15694 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15695 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15696 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15697 "Some properties that are used by Org mode for various purposes.
15698 Being in this list makes sure that they are offered for completion.")
15700 (defun org--valid-property-p (property)
15701 "Non nil when string PROPERTY is a valid property name."
15702 (not
15703 (or (equal property "")
15704 (string-match-p "\\s-" property))))
15706 (defun org--update-property-plist (key val props)
15707 "Associate KEY to VAL in alist PROPS.
15708 Modifications are made by side-effect. Return new alist."
15709 (let* ((appending (string= (substring key -1) "+"))
15710 (key (if appending (substring key 0 -1) key))
15711 (old (assoc-string key props t)))
15712 (if (not old) (cons (cons key val) props)
15713 (setcdr old (if appending (concat (cdr old) " " val) val))
15714 props)))
15716 (defun org-get-property-block (&optional beg force)
15717 "Return the (beg . end) range of the body of the property drawer.
15718 BEG is the beginning of the current subtree, or of the part
15719 before the first headline. If it is not given, it will be found.
15720 If the drawer does not exist, create it if FORCE is non-nil, or
15721 return nil."
15722 (org-with-wide-buffer
15723 (when beg (goto-char beg))
15724 (unless (org-before-first-heading-p)
15725 (let ((beg (cond (beg)
15726 ((or (not (featurep 'org-inlinetask))
15727 (org-inlinetask-in-task-p))
15728 (org-back-to-heading t))
15729 (t (org-with-limited-levels (org-back-to-heading t))))))
15730 (forward-line)
15731 (when (looking-at-p org-planning-line-re) (forward-line))
15732 (cond ((looking-at org-property-drawer-re)
15733 (forward-line)
15734 (cons (point) (progn (goto-char (match-end 0))
15735 (line-beginning-position))))
15736 (force
15737 (goto-char beg)
15738 (org-insert-property-drawer)
15739 (let ((pos (save-excursion (search-forward ":END:")
15740 (line-beginning-position))))
15741 (cons pos pos))))))))
15743 (defun org-at-property-p ()
15744 "Non-nil when point is inside a property drawer.
15745 See `org-property-re' for match data, if applicable."
15746 (save-excursion
15747 (beginning-of-line)
15748 (and (looking-at org-property-re)
15749 (let ((property-drawer (save-match-data (org-get-property-block))))
15750 (and property-drawer
15751 (>= (point) (car property-drawer))
15752 (< (point) (cdr property-drawer)))))))
15754 (defun org-property-action ()
15755 "Do an action on properties."
15756 (interactive)
15757 (unless (org-at-property-p) (user-error "Not at a property"))
15758 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15759 (let ((c (read-char-exclusive)))
15760 (cl-case c
15761 (?s (call-interactively #'org-set-property))
15762 (?d (call-interactively #'org-delete-property))
15763 (?D (call-interactively #'org-delete-property-globally))
15764 (?c (call-interactively #'org-compute-property-at-point))
15765 (otherwise (user-error "No such property action %c" c)))))
15767 (defun org-inc-effort ()
15768 "Increment the value of the effort property in the current entry."
15769 (interactive)
15770 (org-set-effort nil t))
15772 (defvar org-clock-effort) ; Defined in org-clock.el.
15773 (defvar org-clock-current-task) ; Defined in org-clock.el.
15774 (defun org-set-effort (&optional value increment)
15775 "Set the effort property of the current entry.
15776 With numerical prefix arg, use the nth allowed value, 0 stands for the
15777 10th allowed value.
15779 When INCREMENT is non-nil, set the property to the next allowed value."
15780 (interactive "P")
15781 (when (equal value 0) (setq value 10))
15782 (let* ((completion-ignore-case t)
15783 (prop org-effort-property)
15784 (cur (org-entry-get nil prop))
15785 (allowed (org-property-get-allowed-values nil prop 'table))
15786 (existing (mapcar 'list (org-property-values prop)))
15787 (heading (nth 4 (org-heading-components)))
15789 (val (cond
15790 ((stringp value) value)
15791 ((and allowed (integerp value))
15792 (or (car (nth (1- value) allowed))
15793 (car (org-last allowed))))
15794 ((and allowed increment)
15795 (or (cl-caadr (member (list cur) allowed))
15796 (user-error "Allowed effort values are not set")))
15797 (allowed
15798 (message "Select 1-9,0, [RET%s]: %s"
15799 (if cur (concat "=" cur) "")
15800 (mapconcat 'car allowed " "))
15801 (setq rpl (read-char-exclusive))
15802 (if (equal rpl ?\r)
15804 (setq rpl (- rpl ?0))
15805 (when (equal rpl 0) (setq rpl 10))
15806 (if (and (> rpl 0) (<= rpl (length allowed)))
15807 (car (nth (1- rpl) allowed))
15808 (org-completing-read "Effort: " allowed nil))))
15810 (org-completing-read
15811 (concat "Effort" (and cur (string-match "\\S-" cur)
15812 (concat " [" cur "]"))
15813 ": ")
15814 existing nil nil "" nil cur)))))
15815 (unless (equal (org-entry-get nil prop) val)
15816 (org-entry-put nil prop val))
15817 (org-refresh-property
15818 '((effort . identity)
15819 (effort-minutes . org-duration-string-to-minutes))
15820 val)
15821 (when (equal heading (bound-and-true-p org-clock-current-task))
15822 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15823 (org-clock-update-mode-line))
15824 (message "%s is now %s" prop val)))
15826 (defun org-entry-properties (&optional pom which)
15827 "Get all properties of the current entry.
15829 When POM is a buffer position, get all properties from the entry
15830 there instead.
15832 This includes the TODO keyword, the tags, time strings for
15833 deadline, scheduled, and clocking, and any additional properties
15834 defined in the entry.
15836 If WHICH is nil or `all', get all properties. If WHICH is
15837 `special' or `standard', only get that subclass. If WHICH is
15838 a string, only get that property.
15840 Return value is an alist. Keys are properties, as upcased
15841 strings."
15842 (org-with-point-at pom
15843 (when (and (derived-mode-p 'org-mode)
15844 (ignore-errors (org-back-to-heading t)))
15845 (catch 'exit
15846 (let* ((beg (point))
15847 (specific (and (stringp which) (upcase which)))
15848 (which (cond ((not specific) which)
15849 ((member specific org-special-properties) 'special)
15850 (t 'standard)))
15851 props)
15852 ;; Get the special properties, like TODO and TAGS.
15853 (when (memq which '(nil all special))
15854 (when (or (not specific) (string= specific "CLOCKSUM"))
15855 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15856 (when clocksum
15857 (push (cons "CLOCKSUM"
15858 (org-minutes-to-clocksum-string clocksum))
15859 props)))
15860 (when specific (throw 'exit props)))
15861 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15862 (let ((clocksumt (get-text-property (point)
15863 :org-clock-minutes-today)))
15864 (when clocksumt
15865 (push (cons "CLOCKSUM_T"
15866 (org-minutes-to-clocksum-string clocksumt))
15867 props)))
15868 (when specific (throw 'exit props)))
15869 (when (or (not specific) (string= specific "ITEM"))
15870 (let ((case-fold-search nil))
15871 (when (looking-at org-complex-heading-regexp)
15872 (push (cons "ITEM"
15873 (let ((title (match-string-no-properties 4)))
15874 (if (org-string-nw-p title)
15875 (org-remove-tabs title)
15876 "")))
15877 props)))
15878 (when specific (throw 'exit props)))
15879 (when (or (not specific) (string= specific "TODO"))
15880 (let ((case-fold-search nil))
15881 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15882 (push (cons "TODO" (match-string-no-properties 2)) props)))
15883 (when specific (throw 'exit props)))
15884 (when (or (not specific) (string= specific "PRIORITY"))
15885 (push (cons "PRIORITY"
15886 (if (looking-at org-priority-regexp)
15887 (match-string-no-properties 2)
15888 (char-to-string org-default-priority)))
15889 props)
15890 (when specific (throw 'exit props)))
15891 (when (or (not specific) (string= specific "FILE"))
15892 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15893 props)
15894 (when specific (throw 'exit props)))
15895 (when (or (not specific) (string= specific "TAGS"))
15896 (let ((value (org-string-nw-p (org-get-tags-string))))
15897 (when value (push (cons "TAGS" value) props)))
15898 (when specific (throw 'exit props)))
15899 (when (or (not specific) (string= specific "ALLTAGS"))
15900 (let ((value (org-get-tags-at)))
15901 (when value
15902 (push (cons "ALLTAGS"
15903 (format ":%s:" (mapconcat #'identity value ":")))
15904 props)))
15905 (when specific (throw 'exit props)))
15906 (when (or (not specific) (string= specific "BLOCKED"))
15907 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15908 (when specific (throw 'exit props)))
15909 (when (or (not specific)
15910 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15911 (forward-line)
15912 (when (looking-at-p org-planning-line-re)
15913 (end-of-line)
15914 (let ((bol (line-beginning-position))
15915 ;; Backward compatibility: time keywords used to
15916 ;; be configurable (before 8.3). Make sure we
15917 ;; get the correct keyword.
15918 (key-assoc `(("CLOSED" . ,org-closed-string)
15919 ("DEADLINE" . ,org-deadline-string)
15920 ("SCHEDULED" . ,org-scheduled-string))))
15921 (dolist (pair (if specific (list (assoc specific key-assoc))
15922 key-assoc))
15923 (save-excursion
15924 (when (search-backward (cdr pair) bol t)
15925 (goto-char (match-end 0))
15926 (skip-chars-forward " \t")
15927 (and (looking-at org-ts-regexp-both)
15928 (push (cons (car pair)
15929 (match-string-no-properties 0))
15930 props)))))))
15931 (when specific (throw 'exit props)))
15932 (when (or (not specific)
15933 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15934 (let ((find-ts
15935 (lambda (end ts)
15936 ;; Fix next time-stamp before END. TS is the
15937 ;; list of time-stamps found so far.
15938 (let ((ts ts)
15939 (regexp (cond
15940 ((string= specific "TIMESTAMP")
15941 org-ts-regexp)
15942 ((string= specific "TIMESTAMP_IA")
15943 org-ts-regexp-inactive)
15944 ((assoc "TIMESTAMP_IA" ts)
15945 org-ts-regexp)
15946 ((assoc "TIMESTAMP" ts)
15947 org-ts-regexp-inactive)
15948 (t org-ts-regexp-both))))
15949 (catch 'next
15950 (while (re-search-forward regexp end t)
15951 (backward-char)
15952 (let ((object (org-element-context)))
15953 ;; Accept to match timestamps in node
15954 ;; properties, too.
15955 (when (memq (org-element-type object)
15956 '(node-property timestamp))
15957 (let ((type
15958 (org-element-property :type object)))
15959 (cond
15960 ((and (memq type '(active active-range))
15961 (not (equal specific "TIMESTAMP_IA")))
15962 (unless (assoc "TIMESTAMP" ts)
15963 (push (cons "TIMESTAMP"
15964 (org-element-property
15965 :raw-value object))
15967 (when specific (throw 'exit ts))))
15968 ((and (memq type '(inactive inactive-range))
15969 (not (string= specific "TIMESTAMP")))
15970 (unless (assoc "TIMESTAMP_IA" ts)
15971 (push (cons "TIMESTAMP_IA"
15972 (org-element-property
15973 :raw-value object))
15975 (when specific (throw 'exit ts))))))
15976 ;; Both timestamp types are found,
15977 ;; move to next part.
15978 (when (= (length ts) 2) (throw 'next ts)))))
15979 ts)))))
15980 (goto-char beg)
15981 ;; First look for timestamps within headline.
15982 (let ((ts (funcall find-ts (line-end-position) nil)))
15983 (if (= (length ts) 2) (setq props (nconc ts props))
15984 ;; Then find timestamps in the section, skipping
15985 ;; planning line.
15986 (let ((end (save-excursion (outline-next-heading))))
15987 (forward-line)
15988 (when (looking-at-p org-planning-line-re) (forward-line))
15989 (setq props (nconc (funcall find-ts end ts) props))))))))
15990 ;; Get the standard properties, like :PROP:.
15991 (when (memq which '(nil all standard))
15992 ;; If we are looking after a specific property, delegate
15993 ;; to `org-entry-get', which is faster. However, make an
15994 ;; exception for "CATEGORY", since it can be also set
15995 ;; through keywords (i.e. #+CATEGORY).
15996 (if (and specific (not (equal specific "CATEGORY")))
15997 (let ((value (org-entry-get beg specific nil t)))
15998 (throw 'exit (and value (list (cons specific value)))))
15999 (let ((range (org-get-property-block beg)))
16000 (when range
16001 (let ((end (cdr range)) seen-base)
16002 (goto-char (car range))
16003 ;; Unlike to `org--update-property-plist', we
16004 ;; handle the case where base values is found
16005 ;; after its extension. We also forbid standard
16006 ;; properties to be named as special properties.
16007 (while (re-search-forward org-property-re end t)
16008 (let* ((key (upcase (match-string-no-properties 2)))
16009 (extendp (string-match-p "\\+\\'" key))
16010 (key-base (if extendp (substring key 0 -1) key))
16011 (value (match-string-no-properties 3)))
16012 (cond
16013 ((member-ignore-case key-base org-special-properties))
16014 (extendp
16015 (setq props
16016 (org--update-property-plist key value props)))
16017 ((member key seen-base))
16018 (t (push key seen-base)
16019 (let ((p (assoc-string key props t)))
16020 (if p (setcdr p (concat value " " (cdr p)))
16021 (push (cons key value) props))))))))))))
16022 (unless (assoc "CATEGORY" props)
16023 (push (cons "CATEGORY" (org-get-category beg)) props)
16024 (when (string= specific "CATEGORY") (throw 'exit props)))
16025 ;; Return value.
16026 props)))))
16028 (defun org--property-local-values (property literal-nil)
16029 "Return value for PROPERTY in current entry.
16030 Value is a list whose car is the base value for PROPERTY and cdr
16031 a list of accumulated values. Return nil if neither is found in
16032 the entry. Also return nil when PROPERTY is set to \"nil\",
16033 unless LITERAL-NIL is non-nil."
16034 (let ((range (org-get-property-block)))
16035 (when range
16036 (goto-char (car range))
16037 (let* ((case-fold-search t)
16038 (end (cdr range))
16039 (value
16040 ;; Base value.
16041 (save-excursion
16042 (let ((v (and (re-search-forward
16043 (org-re-property property nil t) end t)
16044 (match-string-no-properties 3))))
16045 (list (if literal-nil v (org-not-nil v)))))))
16046 ;; Find additional values.
16047 (let* ((property+ (org-re-property (concat property "+") nil t)))
16048 (while (re-search-forward property+ end t)
16049 (push (match-string-no-properties 3) value)))
16050 ;; Return final values.
16051 (and (not (equal value '(nil))) (nreverse value))))))
16053 (defun org--property-global-value (property literal-nil)
16054 "Return value for PROPERTY in current buffer.
16055 Return value is a string. Return nil if property is not set
16056 globally. Also return nil when PROPERTY is set to \"nil\",
16057 unless LITERAL-NIL is non-nil."
16058 (let ((global
16059 (cdr (or (assoc-string property org-file-properties t)
16060 (assoc-string property org-global-properties t)
16061 (assoc-string property org-global-properties-fixed t)))))
16062 (if literal-nil global (org-not-nil global))))
16064 (defun org-entry-get (pom property &optional inherit literal-nil)
16065 "Get value of PROPERTY for entry or content at point-or-marker POM.
16067 If INHERIT is non-nil and the entry does not have the property,
16068 then also check higher levels of the hierarchy. If INHERIT is
16069 the symbol `selective', use inheritance only if the setting in
16070 `org-use-property-inheritance' selects PROPERTY for inheritance.
16072 If the property is present but empty, the return value is the
16073 empty string. If the property is not present at all, nil is
16074 returned. In any other case, return the value as a string.
16075 Search is case-insensitive.
16077 If LITERAL-NIL is set, return the string value \"nil\" as
16078 a string, do not interpret it as the list atom nil. This is used
16079 for inheritance when a \"nil\" value can supersede a non-nil
16080 value higher up the hierarchy."
16081 (org-with-point-at pom
16082 (cond
16083 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
16084 ;; We need a special property. Use `org-entry-properties' to
16085 ;; retrieve it, but specify the wanted property.
16086 (cdr (assoc-string property (org-entry-properties nil property))))
16087 ((and inherit
16088 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
16089 (org-entry-get-with-inheritance property literal-nil))
16091 (let* ((local (org--property-local-values property literal-nil))
16092 (value (and local (mapconcat #'identity (delq nil local) " "))))
16093 (if literal-nil value (org-not-nil value)))))))
16095 (defun org-property-or-variable-value (var &optional inherit)
16096 "Check if there is a property fixing the value of VAR.
16097 If yes, return this value. If not, return the current value of the variable."
16098 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
16099 (if (and prop (stringp prop) (string-match "\\S-" prop))
16100 (read prop)
16101 (symbol-value var))))
16103 (defun org-entry-delete (pom property)
16104 "Delete PROPERTY from entry at point-or-marker POM.
16105 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16106 non-nil when a property was removed."
16107 (org-with-point-at pom
16108 (pcase (org-get-property-block)
16109 (`(,begin . ,origin)
16110 (let* ((end (copy-marker origin))
16111 (re (org-re-property
16112 (concat (regexp-quote property) "\\+?") t t)))
16113 (goto-char begin)
16114 (while (re-search-forward re end t)
16115 (delete-region (match-beginning 0) (line-beginning-position 2)))
16116 ;; If drawer is empty, remove it altogether.
16117 (when (= begin end)
16118 (delete-region (line-beginning-position 0)
16119 (line-beginning-position 2)))
16120 ;; Return non-nil if some property was removed.
16121 (prog1 (/= end origin) (set-marker end nil))))
16122 (_ nil))))
16124 ;; Multi-values properties are properties that contain multiple values
16125 ;; These values are assumed to be single words, separated by whitespace.
16126 (defun org-entry-add-to-multivalued-property (pom property value)
16127 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16128 (let* ((old (org-entry-get pom property))
16129 (values (and old (org-split-string old "[ \t]"))))
16130 (setq value (org-entry-protect-space value))
16131 (unless (member value values)
16132 (setq values (append values (list value)))
16133 (org-entry-put pom property
16134 (mapconcat 'identity values " ")))))
16136 (defun org-entry-remove-from-multivalued-property (pom property value)
16137 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16138 (let* ((old (org-entry-get pom property))
16139 (values (and old (org-split-string old "[ \t]"))))
16140 (setq value (org-entry-protect-space value))
16141 (when (member value values)
16142 (setq values (delete value values))
16143 (org-entry-put pom property
16144 (mapconcat 'identity values " ")))))
16146 (defun org-entry-member-in-multivalued-property (pom property value)
16147 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16148 (let* ((old (org-entry-get pom property))
16149 (values (and old (org-split-string old "[ \t]"))))
16150 (setq value (org-entry-protect-space value))
16151 (member value values)))
16153 (defun org-entry-get-multivalued-property (pom property)
16154 "Return a list of values in a multivalued property."
16155 (let* ((value (org-entry-get pom property))
16156 (values (and value (org-split-string value "[ \t]"))))
16157 (mapcar 'org-entry-restore-space values)))
16159 (defun org-entry-put-multivalued-property (pom property &rest values)
16160 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16161 VALUES should be a list of strings. Spaces will be protected."
16162 (org-entry-put pom property
16163 (mapconcat 'org-entry-protect-space values " "))
16164 (let* ((value (org-entry-get pom property))
16165 (values (and value (org-split-string value "[ \t]"))))
16166 (mapcar 'org-entry-restore-space values)))
16168 (defun org-entry-protect-space (s)
16169 "Protect spaces and newline in string S."
16170 (while (string-match " " s)
16171 (setq s (replace-match "%20" t t s)))
16172 (while (string-match "\n" s)
16173 (setq s (replace-match "%0A" t t s)))
16176 (defun org-entry-restore-space (s)
16177 "Restore spaces and newline in string S."
16178 (while (string-match "%20" s)
16179 (setq s (replace-match " " t t s)))
16180 (while (string-match "%0A" s)
16181 (setq s (replace-match "\n" t t s)))
16184 (defvar org-entry-property-inherited-from (make-marker)
16185 "Marker pointing to the entry from where a property was inherited.
16186 Each call to `org-entry-get-with-inheritance' will set this marker to the
16187 location of the entry where the inheritance search matched. If there was
16188 no match, the marker will point nowhere.
16189 Note that also `org-entry-get' calls this function, if the INHERIT flag
16190 is set.")
16192 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16193 "Get PROPERTY of entry or content at point, search higher levels if needed.
16194 The search will stop at the first ancestor which has the property defined.
16195 If the value found is \"nil\", return nil to show that the property
16196 should be considered as undefined (this is the meaning of nil here).
16197 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16198 (move-marker org-entry-property-inherited-from nil)
16199 (org-with-wide-buffer
16200 (let (value)
16201 (catch 'exit
16202 (while t
16203 (let ((v (org--property-local-values property literal-nil)))
16204 (when v
16205 (setq value
16206 (concat (mapconcat #'identity (delq nil v) " ")
16207 (and value " ")
16208 value)))
16209 (cond
16210 ((car v)
16211 (org-back-to-heading t)
16212 (move-marker org-entry-property-inherited-from (point))
16213 (throw 'exit nil))
16214 ((org-up-heading-safe))
16216 (let ((global (org--property-global-value property literal-nil)))
16217 (cond ((not global))
16218 (value (setq value (concat global " " value)))
16219 (t (setq value global))))
16220 (throw 'exit nil))))))
16221 (if literal-nil value (org-not-nil value)))))
16223 (defvar org-property-changed-functions nil
16224 "Hook called when the value of a property has changed.
16225 Each hook function should accept two arguments, the name of the property
16226 and the new value.")
16228 (defun org-entry-put (pom property value)
16229 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16231 If the value is nil, it is converted to the empty string. If it
16232 is not a string, an error is raised. Also raise an error on
16233 invalid property names.
16235 PROPERTY can be any regular property (see
16236 `org-special-properties'). It can also be \"TODO\",
16237 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16239 For the last two properties, VALUE may have any of the special
16240 values \"earlier\" and \"later\". The function then increases or
16241 decreases scheduled or deadline date by one day."
16242 (cond ((null value) (setq value ""))
16243 ((not (stringp value)) (error "Properties values should be strings"))
16244 ((not (org--valid-property-p property))
16245 (user-error "Invalid property name: \"%s\"" property)))
16246 (org-with-point-at pom
16247 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16248 (org-back-to-heading t)
16249 (org-with-limited-levels (org-back-to-heading t)))
16250 (let ((beg (point)))
16251 (cond
16252 ((equal property "TODO")
16253 (cond ((not (org-string-nw-p value)) (setq value 'none))
16254 ((not (member value org-todo-keywords-1))
16255 (user-error "\"%s\" is not a valid TODO state" value)))
16256 (org-todo value)
16257 (org-set-tags nil 'align))
16258 ((equal property "PRIORITY")
16259 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16260 (org-set-tags nil 'align))
16261 ((equal property "SCHEDULED")
16262 (forward-line)
16263 (if (and (looking-at-p org-planning-line-re)
16264 (re-search-forward
16265 org-scheduled-time-regexp (line-end-position) t))
16266 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16267 ((string= value "later") (org-timestamp-change 1 'day))
16268 ((string= value "") (org-schedule '(4)))
16269 (t (org-schedule nil value)))
16270 (if (member value '("earlier" "later" ""))
16271 (call-interactively #'org-schedule)
16272 (org-schedule nil value))))
16273 ((equal property "DEADLINE")
16274 (forward-line)
16275 (if (and (looking-at-p org-planning-line-re)
16276 (re-search-forward
16277 org-deadline-time-regexp (line-end-position) t))
16278 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16279 ((string= value "later") (org-timestamp-change 1 'day))
16280 ((string= value "") (org-deadline '(4)))
16281 (t (org-deadline nil value)))
16282 (if (member value '("earlier" "later" ""))
16283 (call-interactively #'org-deadline)
16284 (org-deadline nil value))))
16285 ((member property org-special-properties)
16286 (error "The %s property cannot be set with `org-entry-put'" property))
16288 (let* ((range (org-get-property-block beg 'force))
16289 (end (cdr range))
16290 (case-fold-search t))
16291 (goto-char (car range))
16292 (if (re-search-forward (org-re-property property nil t) end t)
16293 (progn (delete-region (match-beginning 0) (match-end 0))
16294 (goto-char (match-beginning 0)))
16295 (goto-char end)
16296 (insert "\n")
16297 (backward-char))
16298 (insert ":" property ":")
16299 (when value (insert " " value))
16300 (org-indent-line)))))
16301 (run-hook-with-args 'org-property-changed-functions property value)))
16303 (defun org-buffer-property-keys
16304 (&optional specials defaults columns ignore-malformed)
16305 "Get all property keys in the current buffer.
16307 When SPECIALS is non-nil, also list the special properties that
16308 reflect things like tags and TODO state.
16310 When DEFAULTS is non-nil, also include properties that has
16311 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16312 DESCRIPTION, LOCATION, and LOGGING and others.
16314 When COLUMNS in non-nil, also include property names given in
16315 COLUMN formats in the current buffer.
16317 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16318 automatically performed, such drawers will be silently ignored."
16319 (let ((case-fold-search t)
16320 (props (append
16321 (and specials org-special-properties)
16322 (and defaults (cons org-effort-property org-default-properties))
16323 nil)))
16324 (org-with-wide-buffer
16325 (goto-char (point-min))
16326 (while (re-search-forward org-property-start-re nil t)
16327 (let ((range (org-get-property-block)))
16328 (catch 'skip
16329 (unless range
16330 (when (and (not ignore-malformed)
16331 (not (org-before-first-heading-p))
16332 (y-or-n-p (format "Malformed drawer at %d, repair?"
16333 (line-beginning-position))))
16334 (org-get-property-block nil t))
16335 (throw 'skip nil))
16336 (goto-char (car range))
16337 (let ((begin (car range))
16338 (end (cdr range)))
16339 ;; Make sure that found property block is not located
16340 ;; before current point, as it would generate an infloop.
16341 ;; It can happen, for example, in the following
16342 ;; situation:
16344 ;; * Headline
16345 ;; :PROPERTIES:
16346 ;; ...
16347 ;; :END:
16348 ;; *************** Inlinetask
16349 ;; #+BEGIN_EXAMPLE
16350 ;; :PROPERTIES:
16351 ;; #+END_EXAMPLE
16353 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16354 (while (< (point) end)
16355 (let ((p (progn (looking-at org-property-re)
16356 (match-string-no-properties 2))))
16357 ;; Only add true property name, not extension symbol.
16358 (push (if (not (string-match-p "\\+\\'" p)) p
16359 (substring p 0 -1))
16360 props))
16361 (forward-line))))
16362 (outline-next-heading)))
16363 (when columns
16364 (goto-char (point-min))
16365 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16366 (let ((element (org-element-at-point)))
16367 (when (memq (org-element-type element) '(keyword node-property))
16368 (let ((value (org-element-property :value element))
16369 (start 0))
16370 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16371 (setq start (match-end 0))
16372 (let ((p (match-string-no-properties 1 value)))
16373 (unless (member-ignore-case p org-special-properties)
16374 (push p props))))))))))
16375 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16377 (defun org-property-values (key)
16378 "List all non-nil values of property KEY in current buffer."
16379 (org-with-wide-buffer
16380 (goto-char (point-min))
16381 (let ((case-fold-search t)
16382 (re (org-re-property key))
16383 values)
16384 (while (re-search-forward re nil t)
16385 (push (org-entry-get (point) key) values))
16386 (delete-dups values))))
16388 (defun org-insert-property-drawer ()
16389 "Insert a property drawer into the current entry."
16390 (org-with-wide-buffer
16391 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16392 (org-back-to-heading t)
16393 (org-with-limited-levels (org-back-to-heading t)))
16394 (forward-line)
16395 (when (looking-at-p org-planning-line-re) (forward-line))
16396 (unless (looking-at-p org-property-drawer-re)
16397 ;; Make sure we start editing a line from current entry, not from
16398 ;; next one. It prevents extending text properties or overlays
16399 ;; belonging to the latter.
16400 (when (bolp) (backward-char))
16401 (let ((begin (1+ (point)))
16402 (inhibit-read-only t))
16403 (insert "\n:PROPERTIES:\n:END:")
16404 (when (eobp) (insert "\n"))
16405 (org-indent-region begin (point))))))
16407 (defun org-insert-drawer (&optional arg drawer)
16408 "Insert a drawer at point.
16410 When optional argument ARG is non-nil, insert a property drawer.
16412 Optional argument DRAWER, when non-nil, is a string representing
16413 drawer's name. Otherwise, the user is prompted for a name.
16415 If a region is active, insert the drawer around that region
16416 instead.
16418 Point is left between drawer's boundaries."
16419 (interactive "P")
16420 (let* ((drawer (if arg "PROPERTIES"
16421 (or drawer (read-from-minibuffer "Drawer: ")))))
16422 (cond
16423 ;; With C-u, fall back on `org-insert-property-drawer'
16424 (arg (org-insert-property-drawer))
16425 ;; Check validity of suggested drawer's name.
16426 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16427 (user-error "Invalid drawer name"))
16428 ;; With an active region, insert a drawer at point.
16429 ((not (org-region-active-p))
16430 (progn
16431 (unless (bolp) (insert "\n"))
16432 (insert (format ":%s:\n\n:END:\n" drawer))
16433 (forward-line -2)))
16434 ;; Otherwise, insert the drawer at point
16436 (let ((rbeg (region-beginning))
16437 (rend (copy-marker (region-end))))
16438 (unwind-protect
16439 (progn
16440 (goto-char rbeg)
16441 (beginning-of-line)
16442 (when (save-excursion
16443 (re-search-forward org-outline-regexp-bol rend t))
16444 (user-error "Drawers cannot contain headlines"))
16445 ;; Position point at the beginning of the first
16446 ;; non-blank line in region. Insert drawer's opening
16447 ;; there, then indent it.
16448 (org-skip-whitespace)
16449 (beginning-of-line)
16450 (insert ":" drawer ":\n")
16451 (forward-line -1)
16452 (indent-for-tab-command)
16453 ;; Move point to the beginning of the first blank line
16454 ;; after the last non-blank line in region. Insert
16455 ;; drawer's closing, then indent it.
16456 (goto-char rend)
16457 (skip-chars-backward " \r\t\n")
16458 (insert "\n:END:")
16459 (deactivate-mark t)
16460 (indent-for-tab-command)
16461 (unless (eolp) (insert "\n")))
16462 ;; Clear marker, whatever the outcome of insertion is.
16463 (set-marker rend nil)))))))
16465 (defvar org-property-set-functions-alist nil
16466 "Property set function alist.
16467 Each entry should have the following format:
16469 (PROPERTY . READ-FUNCTION)
16471 The read function will be called with the same argument as
16472 `org-completing-read'.")
16474 (defun org-set-property-function (property)
16475 "Get the function that should be used to set PROPERTY.
16476 This is computed according to `org-property-set-functions-alist'."
16477 (or (cdr (assoc property org-property-set-functions-alist))
16478 'org-completing-read))
16480 (defun org-read-property-value (property)
16481 "Read PROPERTY value from user."
16482 (let* ((completion-ignore-case t)
16483 (allowed (org-property-get-allowed-values nil property 'table))
16484 (cur (org-entry-get nil property))
16485 (prompt (concat property " value"
16486 (if (and cur (string-match "\\S-" cur))
16487 (concat " [" cur "]") "") ": "))
16488 (set-function (org-set-property-function property))
16489 (val (if allowed
16490 (funcall set-function prompt allowed nil
16491 (not (get-text-property 0 'org-unrestricted
16492 (caar allowed))))
16493 (funcall set-function prompt
16494 (mapcar 'list (org-property-values property))
16495 nil nil "" nil cur))))
16496 (org-trim val)))
16498 (defvar org-last-set-property nil)
16499 (defvar org-last-set-property-value nil)
16500 (defun org-read-property-name ()
16501 "Read a property name."
16502 (let ((completion-ignore-case t)
16503 (default-prop (or (and (org-at-property-p)
16504 (match-string-no-properties 2))
16505 org-last-set-property)))
16506 (org-completing-read
16507 (concat "Property"
16508 (if default-prop (concat " [" default-prop "]") "")
16509 ": ")
16510 (mapcar #'list (org-buffer-property-keys nil t t))
16511 nil nil nil nil default-prop)))
16513 (defun org-set-property-and-value (use-last)
16514 "Allow to set [PROPERTY]: [value] direction from prompt.
16515 When use-default, don't even ask, just use the last
16516 \"[PROPERTY]: [value]\" string from the history."
16517 (interactive "P")
16518 (let* ((completion-ignore-case t)
16519 (pv (or (and use-last org-last-set-property-value)
16520 (org-completing-read
16521 "Enter a \"[Property]: [value]\" pair: "
16522 nil nil nil nil nil
16523 org-last-set-property-value)))
16524 prop val)
16525 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16526 (setq prop (match-string 1 pv)
16527 val (match-string 2 pv))
16528 (org-set-property prop val))))
16530 (defun org-set-property (property value)
16531 "In the current entry, set PROPERTY to VALUE.
16533 When called interactively, this will prompt for a property name, offering
16534 completion on existing and default properties. And then it will prompt
16535 for a value, offering completion either on allowed values (via an inherited
16536 xxx_ALL property) or on existing values in other instances of this property
16537 in the current file.
16539 Throw an error when trying to set a property with an invalid name."
16540 (interactive (list nil nil))
16541 (let ((property (or property (org-read-property-name))))
16542 ;; `org-entry-put' also makes the following check, but this one
16543 ;; avoids polluting `org-last-set-property' and
16544 ;; `org-last-set-property-value' needlessly.
16545 (unless (org--valid-property-p property)
16546 (user-error "Invalid property name: \"%s\"" property))
16547 (let ((value (or value (org-read-property-value property)))
16548 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16549 (setq org-last-set-property property)
16550 (setq org-last-set-property-value (concat property ": " value))
16551 ;; Possibly postprocess the inserted value:
16552 (when fn (setq value (funcall fn value)))
16553 (unless (equal (org-entry-get nil property) value)
16554 (org-entry-put nil property value)))))
16556 (defun org-find-property (property &optional value)
16557 "Find first entry in buffer that sets PROPERTY.
16559 When optional argument VALUE is non-nil, only consider an entry
16560 if it contains PROPERTY set to this value. If PROPERTY should be
16561 explicitly set to nil, use string \"nil\" for VALUE.
16563 Return position where the entry begins, or nil if there is no
16564 such entry. If narrowing is in effect, only search the visible
16565 part of the buffer."
16566 (save-excursion
16567 (goto-char (point-min))
16568 (let ((case-fold-search t)
16569 (re (org-re-property property nil (not value) value)))
16570 (catch 'exit
16571 (while (re-search-forward re nil t)
16572 (when (if value (org-at-property-p)
16573 (org-entry-get (point) property nil t))
16574 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16576 (defun org-delete-property (property)
16577 "In the current entry, delete PROPERTY."
16578 (interactive
16579 (let* ((completion-ignore-case t)
16580 (cat (org-entry-get (point) "CATEGORY"))
16581 (props0 (org-entry-properties nil 'standard))
16582 (props (if cat props0
16583 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16584 (prop (if (< 1 (length props))
16585 (completing-read "Property: " props nil t)
16586 (caar props))))
16587 (list prop)))
16588 (if (not property)
16589 (message "No property to delete in this entry")
16590 (org-entry-delete nil property)
16591 (message "Property \"%s\" deleted" property)))
16593 (defun org-delete-property-globally (property)
16594 "Remove PROPERTY globally, from all entries.
16595 This function ignores narrowing, if any."
16596 (interactive
16597 (let* ((completion-ignore-case t)
16598 (prop (completing-read
16599 "Globally remove property: "
16600 (mapcar #'list (org-buffer-property-keys)))))
16601 (list prop)))
16602 (org-with-wide-buffer
16603 (goto-char (point-min))
16604 (let ((count 0)
16605 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16606 (while (re-search-forward re nil t)
16607 (when (org-entry-delete (point) property) (cl-incf count)))
16608 (message "Property \"%s\" removed from %d entries" property count))))
16610 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16612 (defun org-compute-property-at-point ()
16613 "Compute the property at point.
16614 This looks for an enclosing column format, extracts the operator and
16615 then applies it to the property in the column format's scope."
16616 (interactive)
16617 (unless (org-at-property-p)
16618 (user-error "Not at a property"))
16619 (let ((prop (match-string-no-properties 2)))
16620 (org-columns-get-format-and-top-level)
16621 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16622 (user-error "No operator defined for property %s" prop))
16623 (org-columns-compute prop)))
16625 (defvar org-property-allowed-value-functions nil
16626 "Hook for functions supplying allowed values for a specific property.
16627 The functions must take a single argument, the name of the property, and
16628 return a flat list of allowed values. If \":ETC\" is one of
16629 the values, this means that these values are intended as defaults for
16630 completion, but that other values should be allowed too.
16631 The functions must return nil if they are not responsible for this
16632 property.")
16634 (defun org-property-get-allowed-values (pom property &optional table)
16635 "Get allowed values for the property PROPERTY.
16636 When TABLE is non-nil, return an alist that can directly be used for
16637 completion."
16638 (let (vals)
16639 (cond
16640 ((equal property "TODO")
16641 (setq vals (org-with-point-at pom
16642 (append org-todo-keywords-1 '("")))))
16643 ((equal property "PRIORITY")
16644 (let ((n org-lowest-priority))
16645 (while (>= n org-highest-priority)
16646 (push (char-to-string n) vals)
16647 (setq n (1- n)))))
16648 ((equal property "CATEGORY"))
16649 ((member property org-special-properties))
16650 ((setq vals (run-hook-with-args-until-success
16651 'org-property-allowed-value-functions property)))
16653 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16654 (when (and vals (string-match "\\S-" vals))
16655 (setq vals (car (read-from-string (concat "(" vals ")"))))
16656 (setq vals (mapcar (lambda (x)
16657 (cond ((stringp x) x)
16658 ((numberp x) (number-to-string x))
16659 ((symbolp x) (symbol-name x))
16660 (t "???")))
16661 vals)))))
16662 (when (member ":ETC" vals)
16663 (setq vals (remove ":ETC" vals))
16664 (org-add-props (car vals) '(org-unrestricted t)))
16665 (if table (mapcar 'list vals) vals)))
16667 (defun org-property-previous-allowed-value (&optional _previous)
16668 "Switch to the next allowed value for this property."
16669 (interactive)
16670 (org-property-next-allowed-value t))
16672 (defun org-property-next-allowed-value (&optional previous)
16673 "Switch to the next allowed value for this property."
16674 (interactive)
16675 (unless (org-at-property-p)
16676 (user-error "Not at a property"))
16677 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16678 (key (match-string 2))
16679 (value (match-string 3))
16680 (allowed (or (org-property-get-allowed-values (point) key)
16681 (and (member value '("[ ]" "[-]" "[X]"))
16682 '("[ ]" "[X]"))))
16683 (heading (save-match-data (nth 4 (org-heading-components))))
16684 nval)
16685 (unless allowed
16686 (user-error "Allowed values for this property have not been defined"))
16687 (when previous (setq allowed (reverse allowed)))
16688 (when (member value allowed)
16689 (setq nval (car (cdr (member value allowed)))))
16690 (setq nval (or nval (car allowed)))
16691 (when (equal nval value)
16692 (user-error "Only one allowed value for this property"))
16693 (org-at-property-p)
16694 (replace-match (concat " :" key ": " nval) t t)
16695 (org-indent-line)
16696 (beginning-of-line 1)
16697 (skip-chars-forward " \t")
16698 (when (equal prop org-effort-property)
16699 (org-refresh-property
16700 '((effort . identity)
16701 (effort-minutes . org-duration-string-to-minutes))
16702 nval)
16703 (when (string= org-clock-current-task heading)
16704 (setq org-clock-effort nval)
16705 (org-clock-update-mode-line)))
16706 (run-hook-with-args 'org-property-changed-functions key nval)))
16708 (defun org-find-olp (path &optional this-buffer)
16709 "Return a marker pointing to the entry at outline path OLP.
16710 If anything goes wrong, throw an error.
16711 You can wrap this call to catch the error like this:
16713 (condition-case msg
16714 (org-mobile-locate-entry (match-string 4))
16715 (error (nth 1 msg)))
16717 The return value will then be either a string with the error message,
16718 or a marker if everything is OK.
16720 If THIS-BUFFER is set, the outline path does not contain a file,
16721 only headings."
16722 (let* ((file (if this-buffer buffer-file-name (pop path)))
16723 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16724 (level 1)
16725 (lmin 1)
16726 (lmax 1)
16727 end found flevel)
16728 (unless buffer (error "File not found :%s" file))
16729 (with-current-buffer buffer
16730 (org-with-wide-buffer
16731 (goto-char (point-min))
16732 (dolist (heading path)
16733 (let ((re (format org-complex-heading-regexp-format
16734 (regexp-quote heading)))
16735 (cnt 0))
16736 (while (re-search-forward re end t)
16737 (setq level (- (match-end 1) (match-beginning 1)))
16738 (when (and (>= level lmin) (<= level lmax))
16739 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16740 (when (= cnt 0)
16741 (error "Heading not found on level %d: %s" lmax heading))
16742 (when (> cnt 1)
16743 (error "Heading not unique on level %d: %s" lmax heading))
16744 (goto-char found)
16745 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16746 (setq end (save-excursion (org-end-of-subtree t t)))))
16747 (when (org-at-heading-p)
16748 (point-marker))))))
16750 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16751 "Find node HEADING in BUFFER.
16752 Return a marker to the heading if it was found, or nil if not.
16753 If POS-ONLY is set, return just the position instead of a marker.
16755 The heading text must match exact, but it may have a TODO keyword,
16756 a priority cookie and tags in the standard locations."
16757 (with-current-buffer (or buffer (current-buffer))
16758 (org-with-wide-buffer
16759 (goto-char (point-min))
16760 (let (case-fold-search)
16761 (when (re-search-forward
16762 (format org-complex-heading-regexp-format
16763 (regexp-quote heading)) nil t)
16764 (if pos-only
16765 (match-beginning 0)
16766 (move-marker (make-marker) (match-beginning 0))))))))
16768 (defun org-find-exact-heading-in-directory (heading &optional dir)
16769 "Find Org node headline HEADING in all .org files in directory DIR.
16770 When the target headline is found, return a marker to this location."
16771 (let ((files (directory-files (or dir default-directory)
16772 t "\\`[^.#].*\\.org\\'"))
16773 visiting m buffer)
16774 (catch 'found
16775 (dolist (file files)
16776 (message "trying %s" file)
16777 (setq visiting (org-find-base-buffer-visiting file))
16778 (setq buffer (or visiting (find-file-noselect file)))
16779 (setq m (org-find-exact-headline-in-buffer
16780 heading buffer))
16781 (when (and (not m) (not visiting)) (kill-buffer buffer))
16782 (and m (throw 'found m))))))
16784 (defun org-find-entry-with-id (ident)
16785 "Locate the entry that contains the ID property with exact value IDENT.
16786 IDENT can be a string, a symbol or a number, this function will search for
16787 the string representation of it.
16788 Return the position where this entry starts, or nil if there is no such entry."
16789 (interactive "sID: ")
16790 (let ((id (cond
16791 ((stringp ident) ident)
16792 ((symbolp ident) (symbol-name ident))
16793 ((numberp ident) (number-to-string ident))
16794 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16795 (org-with-wide-buffer (org-find-property "ID" id))))
16797 ;;;; Timestamps
16799 (defvar org-last-changed-timestamp nil)
16800 (defvar org-last-inserted-timestamp nil
16801 "The last time stamp inserted with `org-insert-time-stamp'.")
16802 (defvar org-ts-what) ; dynamically scoped parameter
16804 (defun org-time-stamp (arg &optional inactive)
16805 "Prompt for a date/time and insert a time stamp.
16807 If the user specifies a time like HH:MM or if this command is
16808 called with at least one prefix argument, the time stamp contains
16809 the date and the time. Otherwise, only the date is included.
16811 All parts of a date not specified by the user are filled in from
16812 the timestamp at point, if any, or the current date/time
16813 otherwise.
16815 If there is already a timestamp at the cursor, it is replaced.
16817 With two universal prefix arguments, insert an active timestamp
16818 with the current time without prompting the user.
16820 When called from lisp, the timestamp is inactive if INACTIVE is
16821 non-nil."
16822 (interactive "P")
16823 (let* ((ts (cond
16824 ((org-at-date-range-p t)
16825 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16826 ((org-at-timestamp-p t) (match-string 0))))
16827 ;; Default time is either the timestamp at point or today.
16828 ;; When entering a range, only the range start is considered.
16829 (default-time (if (not ts) (current-time)
16830 (apply #'encode-time (org-parse-time-string ts))))
16831 (default-input (and ts (org-get-compact-tod ts)))
16832 (repeater (and ts
16833 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16834 (match-string 0 ts)))
16835 org-time-was-given
16836 org-end-time-was-given
16837 (time
16838 (and (if (equal arg '(16)) (current-time)
16839 ;; Preserve `this-command' and `last-command'.
16840 (let ((this-command this-command)
16841 (last-command last-command))
16842 (org-read-date
16843 arg 'totime nil nil default-time default-input
16844 inactive))))))
16845 (cond
16846 ((and ts
16847 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16848 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16849 (insert "--")
16850 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16852 ;; Make sure we're on a timestamp. When in the middle of a date
16853 ;; range, move arbitrarily to range end.
16854 (unless (org-at-timestamp-p t)
16855 (skip-chars-forward "-")
16856 (org-at-timestamp-p t))
16857 (replace-match "")
16858 (setq org-last-changed-timestamp
16859 (org-insert-time-stamp
16860 time (or org-time-was-given arg)
16861 inactive nil nil (list org-end-time-was-given)))
16862 (when repeater
16863 (backward-char)
16864 (insert " " repeater)
16865 (setq org-last-changed-timestamp
16866 (concat (substring org-last-inserted-timestamp 0 -1)
16867 " " repeater ">")))
16868 (message "Timestamp updated"))
16869 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16870 (t (org-insert-time-stamp
16871 time (or org-time-was-given arg) inactive nil nil
16872 (list org-end-time-was-given))))))
16874 ;; FIXME: can we use this for something else, like computing time differences?
16875 (defun org-get-compact-tod (s)
16876 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16877 (let* ((t1 (match-string 1 s))
16878 (h1 (string-to-number (match-string 2 s)))
16879 (m1 (string-to-number (match-string 3 s)))
16880 (t2 (and (match-end 4) (match-string 5 s)))
16881 (h2 (and t2 (string-to-number (match-string 6 s))))
16882 (m2 (and t2 (string-to-number (match-string 7 s))))
16883 dh dm)
16884 (if (not t2)
16886 (setq dh (- h2 h1) dm (- m2 m1))
16887 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16888 (concat t1 "+" (number-to-string dh)
16889 (and (/= 0 dm) (format ":%02d" dm)))))))
16891 (defun org-time-stamp-inactive (&optional arg)
16892 "Insert an inactive time stamp.
16893 An inactive time stamp is enclosed in square brackets instead of angle
16894 brackets. It is inactive in the sense that it does not trigger agenda entries,
16895 does not link to the calendar and cannot be changed with the S-cursor keys.
16896 So these are more for recording a certain time/date."
16897 (interactive "P")
16898 (org-time-stamp arg 'inactive))
16900 (defvar org-date-ovl (make-overlay 1 1))
16901 (overlay-put org-date-ovl 'face 'org-date-selected)
16902 (delete-overlay org-date-ovl)
16904 (defvar org-ans1) ; dynamically scoped parameter
16905 (defvar org-ans2) ; dynamically scoped parameter
16907 (defvar org-plain-time-of-day-regexp) ; defined below
16909 (defvar org-overriding-default-time nil) ; dynamically scoped
16910 (defvar org-read-date-overlay nil)
16911 (defvar org-dcst nil) ; dynamically scoped
16912 (defvar org-read-date-history nil)
16913 (defvar org-read-date-final-answer nil)
16914 (defvar org-read-date-analyze-futurep nil)
16915 (defvar org-read-date-analyze-forced-year nil)
16916 (defvar org-read-date-inactive)
16918 (defvar org-read-date-minibuffer-local-map
16919 (let* ((map (make-sparse-keymap)))
16920 (set-keymap-parent map minibuffer-local-map)
16921 (org-defkey map (kbd ".")
16922 (lambda () (interactive)
16923 ;; Are we at the beginning of the prompt?
16924 (if (looking-back "^[^:]+: "
16925 (let ((inhibit-field-text-motion t))
16926 (line-beginning-position)))
16927 (org-eval-in-calendar '(calendar-goto-today))
16928 (insert "."))))
16929 (org-defkey map (kbd "C-.")
16930 (lambda () (interactive)
16931 (org-eval-in-calendar '(calendar-goto-today))))
16932 (org-defkey map [(meta shift left)]
16933 (lambda () (interactive)
16934 (org-eval-in-calendar '(calendar-backward-month 1))))
16935 (org-defkey map [(meta shift right)]
16936 (lambda () (interactive)
16937 (org-eval-in-calendar '(calendar-forward-month 1))))
16938 (org-defkey map [(meta shift up)]
16939 (lambda () (interactive)
16940 (org-eval-in-calendar '(calendar-backward-year 1))))
16941 (org-defkey map [(meta shift down)]
16942 (lambda () (interactive)
16943 (org-eval-in-calendar '(calendar-forward-year 1))))
16944 (org-defkey map [?\e (shift left)]
16945 (lambda () (interactive)
16946 (org-eval-in-calendar '(calendar-backward-month 1))))
16947 (org-defkey map [?\e (shift right)]
16948 (lambda () (interactive)
16949 (org-eval-in-calendar '(calendar-forward-month 1))))
16950 (org-defkey map [?\e (shift up)]
16951 (lambda () (interactive)
16952 (org-eval-in-calendar '(calendar-backward-year 1))))
16953 (org-defkey map [?\e (shift down)]
16954 (lambda () (interactive)
16955 (org-eval-in-calendar '(calendar-forward-year 1))))
16956 (org-defkey map [(shift up)]
16957 (lambda () (interactive)
16958 (org-eval-in-calendar '(calendar-backward-week 1))))
16959 (org-defkey map [(shift down)]
16960 (lambda () (interactive)
16961 (org-eval-in-calendar '(calendar-forward-week 1))))
16962 (org-defkey map [(shift left)]
16963 (lambda () (interactive)
16964 (org-eval-in-calendar '(calendar-backward-day 1))))
16965 (org-defkey map [(shift right)]
16966 (lambda () (interactive)
16967 (org-eval-in-calendar '(calendar-forward-day 1))))
16968 (org-defkey map "!"
16969 (lambda () (interactive)
16970 (org-eval-in-calendar '(diary-view-entries))
16971 (message "")))
16972 (org-defkey map ">"
16973 (lambda () (interactive)
16974 (org-eval-in-calendar '(calendar-scroll-left 1))))
16975 (org-defkey map "<"
16976 (lambda () (interactive)
16977 (org-eval-in-calendar '(calendar-scroll-right 1))))
16978 (org-defkey map "\C-v"
16979 (lambda () (interactive)
16980 (org-eval-in-calendar
16981 '(calendar-scroll-left-three-months 1))))
16982 (org-defkey map "\M-v"
16983 (lambda () (interactive)
16984 (org-eval-in-calendar
16985 '(calendar-scroll-right-three-months 1))))
16986 map)
16987 "Keymap for minibuffer commands when using `org-read-date'.")
16989 (defvar org-def)
16990 (defvar org-defdecode)
16991 (defvar org-with-time)
16993 (defvar calendar-setup) ; Dynamically scoped.
16994 (defun org-read-date (&optional with-time to-time from-string prompt
16995 default-time default-input inactive)
16996 "Read a date, possibly a time, and make things smooth for the user.
16997 The prompt will suggest to enter an ISO date, but you can also enter anything
16998 which will at least partially be understood by `parse-time-string'.
16999 Unrecognized parts of the date will default to the current day, month, year,
17000 hour and minute. If this command is called to replace a timestamp at point,
17001 or to enter the second timestamp of a range, the default time is taken
17002 from the existing stamp. Furthermore, the command prefers the future,
17003 so if you are giving a date where the year is not given, and the day-month
17004 combination is already past in the current year, it will assume you
17005 mean next year. For details, see the manual. A few examples:
17007 3-2-5 --> 2003-02-05
17008 feb 15 --> currentyear-02-15
17009 2/15 --> currentyear-02-15
17010 sep 12 9 --> 2009-09-12
17011 12:45 --> today 12:45
17012 22 sept 0:34 --> currentyear-09-22 0:34
17013 12 --> currentyear-currentmonth-12
17014 Fri --> nearest Friday after today
17015 -Tue --> last Tuesday
17016 etc.
17018 Furthermore you can specify a relative date by giving, as the *first* thing
17019 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
17020 change in days weeks, months, years.
17021 With a single plus or minus, the date is relative to today. With a double
17022 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17023 +4d --> four days from today
17024 +4 --> same as above
17025 +2w --> two weeks from today
17026 ++5 --> five days from default date
17028 The function understands only English month and weekday abbreviations.
17030 While prompting, a calendar is popped up - you can also select the
17031 date with the mouse (button 1). The calendar shows a period of three
17032 months. To scroll it to other months, use the keys `>' and `<'.
17033 If you don't like the calendar, turn it off with
17034 (setq org-read-date-popup-calendar nil)
17036 With optional argument TO-TIME, the date will immediately be converted
17037 to an internal time.
17038 With an optional argument WITH-TIME, the prompt will suggest to
17039 also insert a time. Note that when WITH-TIME is not set, you can
17040 still enter a time, and this function will inform the calling routine
17041 about this change. The calling routine may then choose to change the
17042 format used to insert the time stamp into the buffer to include the time.
17043 With optional argument FROM-STRING, read from this string instead from
17044 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17045 the time/date that is used for everything that is not specified by the
17046 user."
17047 (require 'parse-time)
17048 (let* ((org-with-time with-time)
17049 (org-time-stamp-rounding-minutes
17050 (if (equal org-with-time '(16))
17051 '(0 0)
17052 org-time-stamp-rounding-minutes))
17053 (org-dcst org-display-custom-times)
17054 (ct (org-current-time))
17055 (org-def (or org-overriding-default-time default-time ct))
17056 (org-defdecode (decode-time org-def))
17057 (cur-frame (selected-frame))
17058 (mouse-autoselect-window nil) ; Don't let the mouse jump
17059 (calendar-setup
17060 (and (eq calendar-setup 'calendar-only) 'calendar-only))
17061 (calendar-move-hook nil)
17062 (calendar-view-diary-initially-flag nil)
17063 (calendar-view-holidays-initially-flag nil)
17064 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
17065 ;; Rationalize `org-def' and `org-defdecode', if required.
17066 (when (< (nth 2 org-defdecode) org-extend-today-until)
17067 (setf (nth 2 org-defdecode) -1)
17068 (setf (nth 1 org-defdecode) 59)
17069 (setq org-def (apply #'encode-time org-defdecode))
17070 (setq org-defdecode (decode-time org-def)))
17071 (let* ((timestr (format-time-string
17072 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
17073 org-def))
17074 (prompt (concat (if prompt (concat prompt " ") "")
17075 (format "Date+time [%s]: " timestr))))
17076 (cond
17077 (from-string (setq ans from-string))
17078 (org-read-date-popup-calendar
17079 (save-excursion
17080 (save-window-excursion
17081 (calendar)
17082 (when (eq calendar-setup 'calendar-only)
17083 (setq cal-frame
17084 (window-frame (get-buffer-window "*Calendar*" 'visible)))
17085 (select-frame cal-frame))
17086 (org-eval-in-calendar '(setq cursor-type nil) t)
17087 (unwind-protect
17088 (progn
17089 (calendar-forward-day (- (time-to-days org-def)
17090 (calendar-absolute-from-gregorian
17091 (calendar-current-date))))
17092 (org-eval-in-calendar nil t)
17093 (let* ((old-map (current-local-map))
17094 (map (copy-keymap calendar-mode-map))
17095 (minibuffer-local-map
17096 (copy-keymap org-read-date-minibuffer-local-map)))
17097 (org-defkey map (kbd "RET") 'org-calendar-select)
17098 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17099 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17100 (unwind-protect
17101 (progn
17102 (use-local-map map)
17103 (setq org-read-date-inactive inactive)
17104 (add-hook 'post-command-hook 'org-read-date-display)
17105 (setq org-ans0
17106 (read-string prompt
17107 default-input
17108 'org-read-date-history
17109 nil))
17110 ;; org-ans0: from prompt
17111 ;; org-ans1: from mouse click
17112 ;; org-ans2: from calendar motion
17113 (setq ans
17114 (concat org-ans0 " " (or org-ans1 org-ans2))))
17115 (remove-hook 'post-command-hook 'org-read-date-display)
17116 (use-local-map old-map)
17117 (when org-read-date-overlay
17118 (delete-overlay org-read-date-overlay)
17119 (setq org-read-date-overlay nil)))))
17120 (bury-buffer "*Calendar*")
17121 (when cal-frame
17122 (delete-frame cal-frame)
17123 (select-frame-set-input-focus cur-frame))))))
17125 (t ; Naked prompt only
17126 (unwind-protect
17127 (setq ans (read-string prompt default-input
17128 'org-read-date-history timestr))
17129 (when org-read-date-overlay
17130 (delete-overlay org-read-date-overlay)
17131 (setq org-read-date-overlay nil))))))
17133 (setq final (org-read-date-analyze ans org-def org-defdecode))
17135 (when org-read-date-analyze-forced-year
17136 (message "Year was forced into %s"
17137 (if org-read-date-force-compatible-dates
17138 "compatible range (1970-2037)"
17139 "range representable on this machine"))
17140 (ding))
17142 ;; One round trip to get rid of 34th of August and stuff like that....
17143 (setq final (decode-time (apply 'encode-time final)))
17145 (setq org-read-date-final-answer ans)
17147 (if to-time
17148 (apply 'encode-time final)
17149 (if (and (boundp 'org-time-was-given) org-time-was-given)
17150 (format "%04d-%02d-%02d %02d:%02d"
17151 (nth 5 final) (nth 4 final) (nth 3 final)
17152 (nth 2 final) (nth 1 final))
17153 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17155 (defun org-read-date-display ()
17156 "Display the current date prompt interpretation in the minibuffer."
17157 (when org-read-date-display-live
17158 (when org-read-date-overlay
17159 (delete-overlay org-read-date-overlay))
17160 (when (minibufferp (current-buffer))
17161 (save-excursion
17162 (end-of-line 1)
17163 (while (not (equal (buffer-substring
17164 (max (point-min) (- (point) 4)) (point))
17165 " "))
17166 (insert " ")))
17167 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17168 " " (or org-ans1 org-ans2)))
17169 (org-end-time-was-given nil)
17170 (f (org-read-date-analyze ans org-def org-defdecode))
17171 (fmts (if org-dcst
17172 org-time-stamp-custom-formats
17173 org-time-stamp-formats))
17174 (fmt (if (or org-with-time
17175 (and (boundp 'org-time-was-given) org-time-was-given))
17176 (cdr fmts)
17177 (car fmts)))
17178 (txt (format-time-string fmt (apply 'encode-time f)))
17179 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17180 (txt (concat "=> " txt)))
17181 (when (and org-end-time-was-given
17182 (string-match org-plain-time-of-day-regexp txt))
17183 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17184 org-end-time-was-given
17185 (substring txt (match-end 0)))))
17186 (when org-read-date-analyze-futurep
17187 (setq txt (concat txt " (=>F)")))
17188 (setq org-read-date-overlay
17189 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17190 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17192 (defun org-read-date-analyze (ans def defdecode)
17193 "Analyze the combined answer of the date prompt."
17194 ;; FIXME: cleanup and comment
17195 ;; Pass `current-time' result to `decode-time' (instead of calling
17196 ;; without arguments) so that only `current-time' has to be
17197 ;; overriden in tests.
17198 (let ((org-def def)
17199 (org-defdecode defdecode)
17200 (nowdecode (decode-time (current-time)))
17201 delta deltan deltaw deltadef year month day
17202 hour minute second wday pm h2 m2 tl wday1
17203 iso-year iso-weekday iso-week iso-date futurep kill-year)
17204 (setq org-read-date-analyze-futurep nil
17205 org-read-date-analyze-forced-year nil)
17206 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17207 (setq ans "+0"))
17209 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17210 (setq ans (replace-match "" t t ans)
17211 deltan (car delta)
17212 deltaw (nth 1 delta)
17213 deltadef (nth 2 delta)))
17215 ;; Check if there is an iso week date in there. If yes, store the
17216 ;; info and postpone interpreting it until the rest of the parsing
17217 ;; is done.
17218 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17219 (setq iso-year (when (match-end 1)
17220 (org-small-year-to-year
17221 (string-to-number (match-string 1 ans))))
17222 iso-weekday (when (match-end 3)
17223 (string-to-number (match-string 3 ans)))
17224 iso-week (string-to-number (match-string 2 ans)))
17225 (setq ans (replace-match "" t t ans)))
17227 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17228 (when (string-match
17229 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17230 (setq year (if (match-end 2)
17231 (string-to-number (match-string 2 ans))
17232 (progn (setq kill-year t)
17233 (string-to-number (format-time-string "%Y"))))
17234 month (string-to-number (match-string 3 ans))
17235 day (string-to-number (match-string 4 ans)))
17236 (setq year (org-small-year-to-year year))
17237 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17238 t nil ans)))
17240 ;; Help matching dotted european dates
17241 (when (string-match
17242 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17243 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17244 (setq kill-year t)
17245 (string-to-number (format-time-string "%Y")))
17246 day (string-to-number (match-string 1 ans))
17247 month (string-to-number (match-string 2 ans))
17248 ans (replace-match (format "%04d-%02d-%02d" year month day)
17249 t nil ans)))
17251 ;; Help matching american dates, like 5/30 or 5/30/7
17252 (when (string-match
17253 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17254 (setq year (if (match-end 4)
17255 (string-to-number (match-string 4 ans))
17256 (progn (setq kill-year t)
17257 (string-to-number (format-time-string "%Y"))))
17258 month (string-to-number (match-string 1 ans))
17259 day (string-to-number (match-string 2 ans)))
17260 (setq year (org-small-year-to-year year))
17261 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17262 t nil ans)))
17263 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17264 ;; If there is a time with am/pm, and *no* time without it, we convert
17265 ;; so that matching will be successful.
17266 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17267 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17268 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17269 (setq hour (string-to-number (match-string 1 ans))
17270 minute (if (match-end 3)
17271 (string-to-number (match-string 3 ans))
17273 pm (equal ?p
17274 (string-to-char (downcase (match-string 4 ans)))))
17275 (if (and (= hour 12) (not pm))
17276 (setq hour 0)
17277 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17278 (setq ans (replace-match (format "%02d:%02d" hour minute)
17279 t t ans))))
17281 ;; Check if a time range is given as a duration
17282 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17283 (setq hour (string-to-number (match-string 1 ans))
17284 h2 (+ hour (string-to-number (match-string 3 ans)))
17285 minute (string-to-number (match-string 2 ans))
17286 m2 (+ minute (if (match-end 5) (string-to-number
17287 (match-string 5 ans))0)))
17288 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17289 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17290 t t ans)))
17292 ;; Check if there is a time range
17293 (when (boundp 'org-end-time-was-given)
17294 (setq org-time-was-given nil)
17295 (when (and (string-match org-plain-time-of-day-regexp ans)
17296 (match-end 8))
17297 (setq org-end-time-was-given (match-string 8 ans))
17298 (setq ans (concat (substring ans 0 (match-beginning 7))
17299 (substring ans (match-end 7))))))
17301 (setq tl (parse-time-string ans)
17302 day (or (nth 3 tl) (nth 3 org-defdecode))
17303 month
17304 (cond ((nth 4 tl))
17305 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17306 ;; Day was specified. Make sure DAY+MONTH
17307 ;; combination happens in the future.
17308 ((nth 3 tl)
17309 (setq futurep t)
17310 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17311 (nth 4 nowdecode)))
17312 (t (nth 4 org-defdecode)))
17313 year
17314 (cond ((and (not kill-year) (nth 5 tl)))
17315 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17316 ;; Month was guessed in the future and is at least
17317 ;; equal to NOWDECODE's. Fix year accordingly.
17318 (futurep
17319 (if (or (> month (nth 4 nowdecode))
17320 (>= day (nth 3 nowdecode)))
17321 (nth 5 nowdecode)
17322 (1+ (nth 5 nowdecode))))
17323 ;; Month was specified. Make sure MONTH+YEAR
17324 ;; combination happens in the future.
17325 ((nth 4 tl)
17326 (setq futurep t)
17327 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17328 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17329 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17330 (t (nth 5 nowdecode))))
17331 (t (nth 5 org-defdecode)))
17332 hour (or (nth 2 tl) (nth 2 org-defdecode))
17333 minute (or (nth 1 tl) (nth 1 org-defdecode))
17334 second (or (nth 0 tl) 0)
17335 wday (nth 6 tl))
17337 (when (and (eq org-read-date-prefer-future 'time)
17338 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17339 (equal day (nth 3 nowdecode))
17340 (equal month (nth 4 nowdecode))
17341 (equal year (nth 5 nowdecode))
17342 (nth 2 tl)
17343 (or (< (nth 2 tl) (nth 2 nowdecode))
17344 (and (= (nth 2 tl) (nth 2 nowdecode))
17345 (nth 1 tl)
17346 (< (nth 1 tl) (nth 1 nowdecode)))))
17347 (setq day (1+ day)
17348 futurep t))
17350 ;; Special date definitions below
17351 (cond
17352 (iso-week
17353 ;; There was an iso week
17354 (require 'cal-iso)
17355 (setq futurep nil)
17356 (setq year (or iso-year year)
17357 day (or iso-weekday wday 1)
17358 wday nil ; to make sure that the trigger below does not match
17359 iso-date (calendar-gregorian-from-absolute
17360 (calendar-iso-to-absolute
17361 (list iso-week day year))))
17362 ; FIXME: Should we also push ISO weeks into the future?
17363 ; (when (and org-read-date-prefer-future
17364 ; (not iso-year)
17365 ; (< (calendar-absolute-from-gregorian iso-date)
17366 ; (time-to-days (current-time))))
17367 ; (setq year (1+ year)
17368 ; iso-date (calendar-gregorian-from-absolute
17369 ; (calendar-iso-to-absolute
17370 ; (list iso-week day year)))))
17371 (setq month (car iso-date)
17372 year (nth 2 iso-date)
17373 day (nth 1 iso-date)))
17374 (deltan
17375 (setq futurep nil)
17376 (unless deltadef
17377 ;; Pass `current-time' result to `decode-time' (instead of
17378 ;; calling without arguments) so that only `current-time' has
17379 ;; to be overriden in tests.
17380 (let ((now (decode-time (current-time))))
17381 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17382 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17383 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17384 ((equal deltaw "m") (setq month (+ month deltan)))
17385 ((equal deltaw "y") (setq year (+ year deltan)))))
17386 ((and wday (not (nth 3 tl)))
17387 ;; Weekday was given, but no day, so pick that day in the week
17388 ;; on or after the derived date.
17389 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17390 (unless (equal wday wday1)
17391 (setq day (+ day (% (- wday wday1 -7) 7))))))
17392 (when (and (boundp 'org-time-was-given)
17393 (nth 2 tl))
17394 (setq org-time-was-given t))
17395 (when (< year 100) (setq year (+ 2000 year)))
17396 ;; Check of the date is representable
17397 (if org-read-date-force-compatible-dates
17398 (progn
17399 (when (< year 1970)
17400 (setq year 1970 org-read-date-analyze-forced-year t))
17401 (when (> year 2037)
17402 (setq year 2037 org-read-date-analyze-forced-year t)))
17403 (condition-case nil
17404 (ignore (encode-time second minute hour day month year))
17405 (error
17406 (setq year (nth 5 org-defdecode))
17407 (setq org-read-date-analyze-forced-year t))))
17408 (setq org-read-date-analyze-futurep futurep)
17409 (list second minute hour day month year)))
17411 (defvar parse-time-weekdays)
17412 (defun org-read-date-get-relative (s today default)
17413 "Check string S for special relative date string.
17414 TODAY and DEFAULT are internal times, for today and for a default.
17415 Return shift list (N what def-flag)
17416 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17417 N is the number of WHATs to shift.
17418 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17419 the DEFAULT date rather than TODAY."
17420 (require 'parse-time)
17421 (when (and
17422 (string-match
17423 (concat
17424 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17425 "\\([0-9]+\\)?"
17426 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17427 "\\([ \t]\\|$\\)") s)
17428 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17429 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17430 (string-to-char (substring (match-string 1 s) -1))
17431 ?+))
17432 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17433 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17434 (what (if (match-end 3) (match-string 3 s) "d"))
17435 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17436 (date (if rel default today))
17437 (wday (nth 6 (decode-time date)))
17438 delta)
17439 (if wday1
17440 (progn
17441 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17442 (when (= delta 0) (setq delta 7))
17443 (when (= dir ?-)
17444 (setq delta (- delta 7))
17445 (when (= delta 0) (setq delta -7)))
17446 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17447 (list delta "d" rel))
17448 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17450 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17451 "Turn a user-specified date into the internal representation.
17452 The internal representation needed by the calendar is (month day year).
17453 This is a wrapper to handle the brain-dead convention in calendar that
17454 user function argument order change dependent on argument order."
17455 (pcase calendar-date-style
17456 (`american (list arg1 arg2 arg3))
17457 (`european (list arg2 arg1 arg3))
17458 (`iso (list arg2 arg3 arg1))))
17460 (defun org-eval-in-calendar (form &optional keepdate)
17461 "Eval FORM in the calendar window and return to current window.
17462 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17463 (let ((sf (selected-frame))
17464 (sw (selected-window)))
17465 (select-window (get-buffer-window "*Calendar*" t))
17466 (eval form)
17467 (when (and (not keepdate) (calendar-cursor-to-date))
17468 (let* ((date (calendar-cursor-to-date))
17469 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17470 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17471 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17472 (select-window sw)
17473 (select-frame-set-input-focus sf)))
17475 (defun org-calendar-select ()
17476 "Return to `org-read-date' with the date currently selected.
17477 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17478 (interactive)
17479 (when (calendar-cursor-to-date)
17480 (let* ((date (calendar-cursor-to-date))
17481 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17482 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17483 (when (active-minibuffer-window) (exit-minibuffer))))
17485 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17486 "Insert a date stamp for the date given by the internal TIME.
17487 See `format-time-string' for the format of TIME.
17488 WITH-HM means use the stamp format that includes the time of the day.
17489 INACTIVE means use square brackets instead of angular ones, so that the
17490 stamp will not contribute to the agenda.
17491 PRE and POST are optional strings to be inserted before and after the
17492 stamp.
17493 The command returns the inserted time stamp."
17494 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17495 stamp)
17496 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17497 (insert-before-markers (or pre ""))
17498 (when (listp extra)
17499 (setq extra (car extra))
17500 (if (and (stringp extra)
17501 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17502 (setq extra (format "-%02d:%02d"
17503 (string-to-number (match-string 1 extra))
17504 (string-to-number (match-string 2 extra))))
17505 (setq extra nil)))
17506 (when extra
17507 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17508 (insert-before-markers (setq stamp (format-time-string fmt time)))
17509 (insert-before-markers (or post ""))
17510 (setq org-last-inserted-timestamp stamp)))
17512 (defun org-toggle-time-stamp-overlays ()
17513 "Toggle the use of custom time stamp formats."
17514 (interactive)
17515 (setq org-display-custom-times (not org-display-custom-times))
17516 (unless org-display-custom-times
17517 (let ((p (point-min)) (bmp (buffer-modified-p)))
17518 (while (setq p (next-single-property-change p 'display))
17519 (when (and (get-text-property p 'display)
17520 (eq (get-text-property p 'face) 'org-date))
17521 (remove-text-properties
17522 p (setq p (next-single-property-change p 'display))
17523 '(display t))))
17524 (set-buffer-modified-p bmp)))
17525 (org-restart-font-lock)
17526 (setq org-table-may-need-update t)
17527 (if org-display-custom-times
17528 (message "Time stamps are overlaid with custom format")
17529 (message "Time stamp overlays removed")))
17531 (defun org-display-custom-time (beg end)
17532 "Overlay modified time stamp format over timestamp between BEG and END."
17533 (let* ((ts (buffer-substring beg end))
17534 t1 w1 with-hm tf time str w2 (off 0))
17535 (save-match-data
17536 (setq t1 (org-parse-time-string ts t))
17537 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17538 (setq off (- (match-end 0) (match-beginning 0)))))
17539 (setq end (- end off))
17540 (setq w1 (- end beg)
17541 with-hm (and (nth 1 t1) (nth 2 t1))
17542 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17543 time (org-fix-decoded-time t1)
17544 str (org-add-props
17545 (format-time-string
17546 (substring tf 1 -1) (apply 'encode-time time))
17547 nil 'mouse-face 'highlight)
17548 w2 (length str))
17549 (unless (= w2 w1)
17550 (add-text-properties (1+ beg) (+ 2 beg)
17551 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17552 (put-text-property beg end 'display str)))
17554 (defun org-fix-decoded-time (time)
17555 "Set 0 instead of nil for the first 6 elements of time.
17556 Don't touch the rest."
17557 (let ((n 0))
17558 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17560 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17561 "Difference between TIMESTAMP-STRING and now in days.
17562 If SECONDS is non-nil, return the difference in seconds."
17563 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17564 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17565 (funcall fdiff (current-time)))))
17567 (defun org-deadline-close-p (timestamp-string &optional ndays)
17568 "Is the time in TIMESTAMP-STRING close to the current date?"
17569 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17570 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17571 (not (org-entry-is-done-p))))
17573 (defun org-get-wdays (ts &optional delay zero-delay)
17574 "Get the deadline lead time appropriate for timestring TS.
17575 When DELAY is non-nil, get the delay time for scheduled items
17576 instead of the deadline lead time. When ZERO-DELAY is non-nil
17577 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17578 don't try to find the delay cookie in the scheduled timestamp."
17579 (let ((tv (if delay org-scheduled-delay-days
17580 org-deadline-warning-days)))
17581 (cond
17582 ((or (and delay (< tv 0))
17583 (and delay zero-delay (<= tv 0))
17584 (and (not delay) (<= tv 0)))
17585 ;; Enforce this value no matter what
17586 (- tv))
17587 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17588 ;; lead time is specified.
17589 (floor (* (string-to-number (match-string 1 ts))
17590 (cdr (assoc (match-string 2 ts)
17591 '(("d" . 1) ("w" . 7)
17592 ("m" . 30.4) ("y" . 365.25)
17593 ("h" . 0.041667)))))))
17594 ;; go for the default.
17595 (t tv))))
17597 (defun org-calendar-select-mouse (ev)
17598 "Return to `org-read-date' with the date currently selected.
17599 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17600 (interactive "e")
17601 (mouse-set-point ev)
17602 (when (calendar-cursor-to-date)
17603 (let* ((date (calendar-cursor-to-date))
17604 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17605 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17606 (when (active-minibuffer-window) (exit-minibuffer))))
17608 (defun org-check-deadlines (ndays)
17609 "Check if there are any deadlines due or past due.
17610 A deadline is considered due if it happens within `org-deadline-warning-days'
17611 days from today's date. If the deadline appears in an entry marked DONE,
17612 it is not shown. A numeric prefix argument NDAYS can be used to test that
17613 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17614 are shown."
17615 (interactive "P")
17616 (let* ((org-warn-days
17617 (cond
17618 ((equal ndays '(4)) 100000)
17619 (ndays (prefix-numeric-value ndays))
17620 (t (abs org-deadline-warning-days))))
17621 (case-fold-search nil)
17622 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17623 (callback
17624 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17625 (message "%d deadlines past-due or due within %d days"
17626 (org-occur regexp nil callback)
17627 org-warn-days)))
17629 (defsubst org-re-timestamp (type)
17630 "Return a regexp for timestamp TYPE.
17631 Allowed values for TYPE are:
17633 all: all timestamps
17634 active: only active timestamps (<...>)
17635 inactive: only inactive timestamps ([...])
17636 scheduled: only scheduled timestamps
17637 deadline: only deadline timestamps
17638 closed: only closed time-stamps
17640 When TYPE is nil, fall back on returning a regexp that matches
17641 both scheduled and deadline timestamps."
17642 (cl-case type
17643 (all org-ts-regexp-both)
17644 (active org-ts-regexp)
17645 (inactive org-ts-regexp-inactive)
17646 (scheduled org-scheduled-time-regexp)
17647 (deadline org-deadline-time-regexp)
17648 (closed org-closed-time-regexp)
17649 (otherwise
17650 (concat "\\<"
17651 (regexp-opt (list org-deadline-string org-scheduled-string))
17652 " *<\\([^>]+\\)>"))))
17654 (defun org-check-before-date (d)
17655 "Check if there are deadlines or scheduled entries before date D."
17656 (interactive (list (org-read-date)))
17657 (let* ((case-fold-search nil)
17658 (regexp (org-re-timestamp org-ts-type))
17659 (ts-type org-ts-type)
17660 (callback
17661 (lambda ()
17662 (let ((match (match-string 1)))
17663 (and (if (memq ts-type '(active inactive all))
17664 (eq (org-element-type (save-excursion
17665 (backward-char)
17666 (org-element-context)))
17667 'timestamp)
17668 (org-at-planning-p))
17669 (time-less-p
17670 (org-time-string-to-time match)
17671 (org-time-string-to-time d)))))))
17672 (message "%d entries before %s"
17673 (org-occur regexp nil callback)
17674 d)))
17676 (defun org-check-after-date (d)
17677 "Check if there are deadlines or scheduled entries after date D."
17678 (interactive (list (org-read-date)))
17679 (let* ((case-fold-search nil)
17680 (regexp (org-re-timestamp org-ts-type))
17681 (ts-type org-ts-type)
17682 (callback
17683 (lambda ()
17684 (let ((match (match-string 1)))
17685 (and (if (memq ts-type '(active inactive all))
17686 (eq (org-element-type (save-excursion
17687 (backward-char)
17688 (org-element-context)))
17689 'timestamp)
17690 (org-at-planning-p))
17691 (not (time-less-p
17692 (org-time-string-to-time match)
17693 (org-time-string-to-time d))))))))
17694 (message "%d entries after %s"
17695 (org-occur regexp nil callback)
17696 d)))
17698 (defun org-check-dates-range (start-date end-date)
17699 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17700 (interactive (list (org-read-date nil nil nil "Range starts")
17701 (org-read-date nil nil nil "Range end")))
17702 (let ((case-fold-search nil)
17703 (regexp (org-re-timestamp org-ts-type))
17704 (callback
17705 (let ((type org-ts-type))
17706 (lambda ()
17707 (let ((match (match-string 1)))
17708 (and
17709 (if (memq type '(active inactive all))
17710 (eq (org-element-type (save-excursion
17711 (backward-char)
17712 (org-element-context)))
17713 'timestamp)
17714 (org-at-planning-p))
17715 (not (time-less-p
17716 (org-time-string-to-time match)
17717 (org-time-string-to-time start-date)))
17718 (time-less-p
17719 (org-time-string-to-time match)
17720 (org-time-string-to-time end-date))))))))
17721 (message "%d entries between %s and %s"
17722 (org-occur regexp nil callback) start-date end-date)))
17724 (defun org-evaluate-time-range (&optional to-buffer)
17725 "Evaluate a time range by computing the difference between start and end.
17726 Normally the result is just printed in the echo area, but with prefix arg
17727 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17728 If the time range is actually in a table, the result is inserted into the
17729 next column.
17730 For time difference computation, a year is assumed to be exactly 365
17731 days in order to avoid rounding problems."
17732 (interactive "P")
17734 (org-clock-update-time-maybe)
17735 (save-excursion
17736 (unless (org-at-date-range-p t)
17737 (goto-char (point-at-bol))
17738 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17739 (unless (org-at-date-range-p t)
17740 (user-error "Not at a time-stamp range, and none found in current line")))
17741 (let* ((ts1 (match-string 1))
17742 (ts2 (match-string 2))
17743 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17744 (match-end (match-end 0))
17745 (time1 (org-time-string-to-time ts1))
17746 (time2 (org-time-string-to-time ts2))
17747 (t1 (float-time time1))
17748 (t2 (float-time time2))
17749 (diff (abs (- t2 t1)))
17750 (negative (< (- t2 t1) 0))
17751 ;; (ys (floor (* 365 24 60 60)))
17752 (ds (* 24 60 60))
17753 (hs (* 60 60))
17754 (fy "%dy %dd %02d:%02d")
17755 (fy1 "%dy %dd")
17756 (fd "%dd %02d:%02d")
17757 (fd1 "%dd")
17758 (fh "%02d:%02d")
17759 y d h m align)
17760 (if havetime
17761 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17763 d (floor (/ diff ds)) diff (mod diff ds)
17764 h (floor (/ diff hs)) diff (mod diff hs)
17765 m (floor (/ diff 60)))
17766 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17768 d (floor (+ (/ diff ds) 0.5))
17769 h 0 m 0))
17770 (if (not to-buffer)
17771 (message "%s" (org-make-tdiff-string y d h m))
17772 (if (org-at-table-p)
17773 (progn
17774 (goto-char match-end)
17775 (setq align t)
17776 (and (looking-at " *|") (goto-char (match-end 0))))
17777 (goto-char match-end))
17778 (when (looking-at
17779 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17780 (replace-match ""))
17781 (when negative (insert " -"))
17782 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17783 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17784 (insert " " (format fh h m))))
17785 (when align (org-table-align))
17786 (message "Time difference inserted")))))
17788 (defun org-make-tdiff-string (y d h m)
17789 (let ((fmt "")
17790 (l nil))
17791 (when (> y 0)
17792 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17793 (push y l))
17794 (when (> d 0)
17795 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17796 (push d l))
17797 (when (> h 0)
17798 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17799 (push h l))
17800 (when (> m 0)
17801 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17802 (push m l))
17803 (apply 'format fmt (nreverse l))))
17805 (defun org-time-string-to-time (s &optional buffer pos)
17806 "Convert a timestamp string into internal time."
17807 (condition-case errdata
17808 (apply 'encode-time (org-parse-time-string s))
17809 (error (error "Bad timestamp `%s'%s\nError was: %s"
17810 s (if (not (and buffer pos))
17812 (format-message " at %d in buffer `%s'" pos buffer))
17813 (cdr errdata)))))
17815 (defun org-time-string-to-seconds (s)
17816 "Convert a timestamp string to a number of seconds."
17817 (float-time (org-time-string-to-time s)))
17819 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17821 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17822 "Convert time stamp S to an absolute day number.
17824 If DAYNR in non-nil, and there is a specifier for a cyclic time
17825 stamp, get the closest date to DAYNR. If PREFER is
17826 `past' (respectively `future') return a date past (respectively
17827 after) or equal to DAYNR.
17829 POS is the location of time stamp S, as a buffer position in
17830 BUFFER.
17832 Diary sexp timestamps are matched against DAYNR, when non-nil.
17833 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17834 signalled."
17835 (cond
17836 ((string-match "\\`%%\\((.*)\\)" s)
17837 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17838 ;; only able to match individual dates. If it fails, raise an
17839 ;; error.
17840 (if (and daynr
17841 (org-diary-sexp-entry
17842 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17843 daynr
17844 (signal 'org-diary-sexp-no-match (list s))))
17845 (daynr (org-closest-date s daynr prefer))
17846 (t (time-to-days
17847 (condition-case errdata
17848 (apply #'encode-time (org-parse-time-string s))
17849 (error (error "Bad timestamp `%s'%s\nError was: %s"
17851 (if (not (and buffer pos)) ""
17852 (format-message " at %d in buffer `%s'" pos buffer))
17853 (cdr errdata))))))))
17855 (defun org-days-to-iso-week (days)
17856 "Return the iso week number."
17857 (require 'cal-iso)
17858 (car (calendar-iso-from-absolute days)))
17860 (defun org-small-year-to-year (year)
17861 "Convert 2-digit years into 4-digit years.
17862 YEAR is expanded into one of the 30 next years, if possible, or
17863 into a past one. Any year larger than 99 is returned unchanged."
17864 (if (>= year 100) year
17865 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17866 (century (/ current 100))
17867 (offset (- year (% current 100))))
17868 (cond ((> offset 30) (+ (* (1- century) 100) year))
17869 ((> offset -70) (+ (* century 100) year))
17870 (t (+ (* (1+ century) 100) year))))))
17872 (defun org-time-from-absolute (d)
17873 "Return the time corresponding to date D.
17874 D may be an absolute day number, or a calendar-type list (month day year)."
17875 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17876 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17878 (defvar org-agenda-current-date)
17879 (defun org-calendar-holiday ()
17880 "List of holidays, for Diary display in Org mode."
17881 (require 'holidays)
17882 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17883 (and hl (mapconcat #'identity hl "; "))))
17885 (defun org-diary-sexp-entry (sexp entry d)
17886 "Process a SEXP diary ENTRY for date D."
17887 (require 'diary-lib)
17888 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17889 ;; dynamically.
17890 (let* ((sexp `(let ((entry ,entry)
17891 (date ',d))
17892 ,(car (read-from-string sexp))))
17893 (result (if calendar-debug-sexp (eval sexp)
17894 (condition-case nil
17895 (eval sexp)
17896 (error
17897 (beep)
17898 (message "Bad sexp at line %d in %s: %s"
17899 (org-current-line)
17900 (buffer-file-name) sexp)
17901 (sleep-for 2))))))
17902 (cond ((stringp result) (split-string result "; "))
17903 ((and (consp result)
17904 (not (consp (cdr result)))
17905 (stringp (cdr result))) (cdr result))
17906 ((and (consp result)
17907 (stringp (car result))) result)
17908 (result entry))))
17910 (defun org-diary-to-ical-string (frombuf)
17911 "Get iCalendar entries from diary entries in buffer FROMBUF.
17912 This uses the icalendar.el library."
17913 (let* ((tmpdir temporary-file-directory)
17914 (tmpfile (make-temp-name
17915 (expand-file-name "orgics" tmpdir)))
17916 buf rtn b e)
17917 (with-current-buffer frombuf
17918 (icalendar-export-region (point-min) (point-max) tmpfile)
17919 (setq buf (find-buffer-visiting tmpfile))
17920 (set-buffer buf)
17921 (goto-char (point-min))
17922 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17923 (setq b (match-beginning 0)))
17924 (goto-char (point-max))
17925 (when (re-search-backward "^END:VEVENT" nil t)
17926 (setq e (match-end 0)))
17927 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17928 (kill-buffer buf)
17929 (delete-file tmpfile)
17930 rtn))
17932 (defun org-closest-date (start current prefer)
17933 "Return closest date to CURRENT starting from START.
17935 CURRENT and START are both time stamps.
17937 When PREFER is `past', return a date that is either CURRENT or
17938 past. When PREFER is `future', return a date that is either
17939 CURRENT or future.
17941 Only time stamps with a repeater are modified. Any other time
17942 stamp stay unchanged. In any case, return value is an absolute
17943 day number."
17944 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17945 ;; No repeater. Do not shift time stamp.
17946 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17947 (let ((value (string-to-number (match-string 1 start)))
17948 (type (match-string 2 start)))
17949 (if (= 0 value)
17950 ;; Repeater with a 0-value is considered as void.
17951 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17952 (let* ((base (org-date-to-gregorian start))
17953 (target (org-date-to-gregorian current))
17954 (sday (calendar-absolute-from-gregorian base))
17955 (cday (calendar-absolute-from-gregorian target))
17956 n1 n2)
17957 ;; If START is already past CURRENT, just return START.
17958 (if (<= cday sday) sday
17959 ;; Compute closest date before (N1) and closest date past
17960 ;; (N2) CURRENT.
17961 (pcase type
17962 ("h"
17963 (let ((missing-hours
17964 (mod (+ (- (* 24 (- cday sday))
17965 (nth 2 (org-parse-time-string start)))
17966 org-extend-today-until)
17967 value)))
17968 (setf n1 (if (= missing-hours 0) cday
17969 (- cday (1+ (/ missing-hours 24)))))
17970 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17971 ((or "d" "w")
17972 (let ((value (if (equal type "w") (* 7 value) value)))
17973 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17974 (setf n2 (+ n1 value))))
17975 ("m"
17976 (let* ((add-months
17977 (lambda (d n)
17978 ;; Add N months to gregorian date D, i.e.,
17979 ;; a list (MONTH DAY YEAR). Return a valid
17980 ;; gregorian date.
17981 (let ((m (+ (nth 0 d) n)))
17982 (list (mod m 12)
17983 (nth 1 d)
17984 (+ (/ m 12) (nth 2 d))))))
17985 (months ; Complete months to TARGET.
17986 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17987 (- (nth 0 target) (nth 0 base))
17988 ;; If START's day is greater than
17989 ;; TARGET's, remove incomplete month.
17990 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17991 value)
17992 value))
17993 (before (funcall add-months base months)))
17994 (setf n1 (calendar-absolute-from-gregorian before))
17995 (setf n2
17996 (calendar-absolute-from-gregorian
17997 (funcall add-months before value)))))
17999 (let* ((d (nth 1 base))
18000 (m (nth 0 base))
18001 (y (nth 2 base))
18002 (years ; Complete years to TARGET.
18003 (* (/ (- (nth 2 target)
18005 ;; If START's month and day are
18006 ;; greater than TARGET's, remove
18007 ;; incomplete year.
18008 (if (or (> (nth 0 target) m)
18009 (and (= (nth 0 target) m)
18010 (> (nth 1 target) d)))
18013 value)
18014 value))
18015 (before (list m d (+ y years))))
18016 (setf n1 (calendar-absolute-from-gregorian before))
18017 (setf n2 (calendar-absolute-from-gregorian
18018 (list m d (+ (nth 2 before) value)))))))
18019 ;; Handle PREFER parameter, if any.
18020 (cond
18021 ((eq prefer 'past) (if (= cday n2) n2 n1))
18022 ((eq prefer 'future) (if (= cday n1) n1 n2))
18023 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
18025 (defun org-date-to-gregorian (d)
18026 "Turn any specification of date D into a Gregorian date for the calendar."
18027 (cond ((integerp d) (calendar-gregorian-from-absolute d))
18028 ((and (listp d) (= (length d) 3)) d)
18029 ((stringp d)
18030 (let ((d (org-parse-time-string d)))
18031 (list (nth 4 d) (nth 3 d) (nth 5 d))))
18032 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
18034 (defun org-parse-time-string (s &optional nodefault)
18035 "Parse the standard Org time string.
18036 This should be a lot faster than the normal `parse-time-string'.
18037 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18038 hour and minute fields will be nil if not given."
18039 (cond ((string-match org-ts-regexp0 s)
18040 (list 0
18041 (when (or (match-beginning 8) (not nodefault))
18042 (string-to-number (or (match-string 8 s) "0")))
18043 (when (or (match-beginning 7) (not nodefault))
18044 (string-to-number (or (match-string 7 s) "0")))
18045 (string-to-number (match-string 4 s))
18046 (string-to-number (match-string 3 s))
18047 (string-to-number (match-string 2 s))
18048 nil nil nil))
18049 ((string-match "^<[^>]+>$" s)
18050 (decode-time (seconds-to-time (org-matcher-time s))))
18051 (t (error "Not a standard Org time string: %s" s))))
18053 (defun org-timestamp-up (&optional arg)
18054 "Increase the date item at the cursor by one.
18055 If the cursor is on the year, change the year. If it is on the month,
18056 the day or the time, change that.
18057 With prefix ARG, change by that many units."
18058 (interactive "p")
18059 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
18061 (defun org-timestamp-down (&optional arg)
18062 "Decrease the date item at the cursor by one.
18063 If the cursor is on the year, change the year. If it is on the month,
18064 the day or the time, change that.
18065 With prefix ARG, change by that many units."
18066 (interactive "p")
18067 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
18069 (defun org-timestamp-up-day (&optional arg)
18070 "Increase the date in the time stamp by one day.
18071 With prefix ARG, change that many days."
18072 (interactive "p")
18073 (if (and (not (org-at-timestamp-p t))
18074 (org-at-heading-p))
18075 (org-todo 'up)
18076 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
18078 (defun org-timestamp-down-day (&optional arg)
18079 "Decrease the date in the time stamp by one day.
18080 With prefix ARG, change that many days."
18081 (interactive "p")
18082 (if (and (not (org-at-timestamp-p t))
18083 (org-at-heading-p))
18084 (org-todo 'down)
18085 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
18087 (defun org-at-timestamp-p (&optional inactive-ok)
18088 "Non-nil if point is inside a timestamp.
18090 When optional argument INACTIVE-OK is non-nil, also consider
18091 inactive timestamps.
18093 When this function returns a non-nil value, match data is set
18094 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18095 INACTIVE-OK."
18096 (interactive)
18097 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18098 (pos (point))
18099 (ans (or (looking-at tsr)
18100 (save-excursion
18101 (skip-chars-backward "^[<\n\r\t")
18102 (when (> (point) (point-min)) (backward-char 1))
18103 (and (looking-at tsr)
18104 (> (- (match-end 0) pos) -1))))))
18105 (and ans
18106 (boundp 'org-ts-what)
18107 (setq org-ts-what
18108 (cond
18109 ((= pos (match-beginning 0)) 'bracket)
18110 ;; Point is considered to be "on the bracket" whether
18111 ;; it's really on it or right after it.
18112 ((= pos (1- (match-end 0))) 'bracket)
18113 ((= pos (match-end 0)) 'after)
18114 ((org-pos-in-match-range pos 2) 'year)
18115 ((org-pos-in-match-range pos 3) 'month)
18116 ((org-pos-in-match-range pos 7) 'hour)
18117 ((org-pos-in-match-range pos 8) 'minute)
18118 ((or (org-pos-in-match-range pos 4)
18119 (org-pos-in-match-range pos 5)) 'day)
18120 ((and (> pos (or (match-end 8) (match-end 5)))
18121 (< pos (match-end 0)))
18122 (- pos (or (match-end 8) (match-end 5))))
18123 (t 'day))))
18124 ans))
18126 (defun org-toggle-timestamp-type ()
18127 "Toggle the type (<active> or [inactive]) of a time stamp."
18128 (interactive)
18129 (when (org-at-timestamp-p t)
18130 (let ((beg (match-beginning 0)) (end (match-end 0))
18131 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18132 (save-excursion
18133 (goto-char beg)
18134 (while (re-search-forward "[][<>]" end t)
18135 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18136 t t)))
18137 (message "Timestamp is now %sactive"
18138 (if (equal (char-after beg) ?<) "" "in")))))
18140 (defun org-at-clock-log-p nil
18141 "Is the cursor on the clock log line?"
18142 (save-excursion
18143 (beginning-of-line)
18144 (looking-at org-clock-line-re)))
18146 (defvar org-clock-history) ; defined in org-clock.el
18147 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18148 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18149 "Change the date in the time stamp at point.
18150 The date will be changed by N times WHAT. WHAT can be `day', `month',
18151 `year', `minute', `second'. If WHAT is not given, the cursor position
18152 in the timestamp determines what will be changed.
18153 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18154 (let ((origin (point)) origin-cat
18155 with-hm inactive
18156 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18157 org-ts-what
18158 extra rem
18159 ts time time0 fixnext clrgx)
18160 (unless (org-at-timestamp-p t)
18161 (user-error "Not at a timestamp"))
18162 (if (and (not what) (eq org-ts-what 'bracket))
18163 (org-toggle-timestamp-type)
18164 ;; Point isn't on brackets. Remember the part of the time-stamp
18165 ;; the point was in. Indeed, size of time-stamps may change,
18166 ;; but point must be kept in the same category nonetheless.
18167 (setq origin-cat org-ts-what)
18168 (when (and (not what) (not (eq org-ts-what 'day))
18169 org-display-custom-times
18170 (get-text-property (point) 'display)
18171 (not (get-text-property (1- (point)) 'display)))
18172 (setq org-ts-what 'day))
18173 (setq org-ts-what (or what org-ts-what)
18174 inactive (= (char-after (match-beginning 0)) ?\[)
18175 ts (match-string 0))
18176 (replace-match "")
18177 (when (string-match
18178 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18180 (setq extra (match-string 1 ts))
18181 (when suppress-tmp-delay
18182 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18183 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18184 (setq with-hm t))
18185 (setq time0 (org-parse-time-string ts))
18186 (when (and updown
18187 (eq org-ts-what 'minute)
18188 (not current-prefix-arg))
18189 ;; This looks like s-up and s-down. Change by one rounding step.
18190 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18191 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18192 (setcar (cdr time0) (+ (nth 1 time0)
18193 (if (> n 0) (- rem) (- dm rem))))))
18194 (setq time
18195 (apply #'encode-time
18196 (or (car time0) 0)
18197 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18198 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18199 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18200 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18201 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18202 (nthcdr 6 time0)))
18203 (when (and (member org-ts-what '(hour minute))
18204 extra
18205 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18206 (setq extra (org-modify-ts-extra
18207 extra
18208 (if (eq org-ts-what 'hour) 2 5)
18209 n dm)))
18210 (when (integerp org-ts-what)
18211 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18212 (when (eq what 'calendar)
18213 (let ((cal-date (org-get-date-from-calendar)))
18214 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18215 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18216 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18217 (setcar time0 (or (car time0) 0))
18218 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18219 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18220 (setq time (apply 'encode-time time0))))
18221 ;; Insert the new time-stamp, and ensure point stays in the same
18222 ;; category as before (i.e. not after the last position in that
18223 ;; category).
18224 (let ((pos (point)))
18225 ;; Stay before inserted string. `save-excursion' is of no use.
18226 (setq org-last-changed-timestamp
18227 (org-insert-time-stamp time with-hm inactive nil nil extra))
18228 (goto-char pos))
18229 (save-match-data
18230 (looking-at org-ts-regexp3)
18231 (goto-char
18232 (pcase origin-cat
18233 ;; `day' category ends before `hour' if any, or at the end
18234 ;; of the day name.
18235 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18236 (`hour (min (match-end 7) origin))
18237 (`minute (min (1- (match-end 8)) origin))
18238 ((pred integerp) (min (1- (match-end 0)) origin))
18239 ;; Point was right after the time-stamp. However, the
18240 ;; time-stamp length might have changed, so refer to
18241 ;; (match-end 0) instead.
18242 (`after (match-end 0))
18243 ;; `year' and `month' have both fixed size: point couldn't
18244 ;; have moved into another part.
18245 (_ origin))))
18246 ;; Update clock if on a CLOCK line.
18247 (org-clock-update-time-maybe)
18248 ;; Maybe adjust the closest clock in `org-clock-history'
18249 (when org-clock-adjust-closest
18250 (if (not (and (org-at-clock-log-p)
18251 (< 1 (length (delq nil (mapcar 'marker-position
18252 org-clock-history))))))
18253 (message "No clock to adjust")
18254 (cond ((save-excursion ; fix previous clock?
18255 (re-search-backward org-ts-regexp0 nil t)
18256 (looking-back (concat org-clock-string " \\[")
18257 (line-beginning-position)))
18258 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18259 ((save-excursion ; fix next clock?
18260 (re-search-backward org-ts-regexp0 nil t)
18261 (looking-at (concat org-ts-regexp0 "\\] =>")))
18262 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18263 (save-window-excursion
18264 ;; Find closest clock to point, adjust the previous/next one in history
18265 (let* ((p (save-excursion (org-back-to-heading t)))
18266 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18267 (clfixnth
18268 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18269 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18270 (if (not clfixpos)
18271 (message "No clock to adjust")
18272 (save-excursion
18273 (org-goto-marker-or-bmk clfixpos)
18274 (org-show-subtree)
18275 (when (re-search-forward clrgx nil t)
18276 (goto-char (match-beginning 1))
18277 (let (org-clock-adjust-closest)
18278 (org-timestamp-change n org-ts-what updown))
18279 (message "Clock adjusted in %s for heading: %s"
18280 (file-name-nondirectory (buffer-file-name))
18281 (org-get-heading t t)))))))))
18282 ;; Try to recenter the calendar window, if any.
18283 (when (and org-calendar-follow-timestamp-change
18284 (get-buffer-window "*Calendar*" t)
18285 (memq org-ts-what '(day month year)))
18286 (org-recenter-calendar (time-to-days time))))))
18288 (defun org-modify-ts-extra (s pos n dm)
18289 "Change the different parts of the lead-time and repeat fields in timestamp."
18290 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18291 ng h m new rem)
18292 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18293 (cond
18294 ((or (org-pos-in-match-range pos 2)
18295 (org-pos-in-match-range pos 3))
18296 (setq m (string-to-number (match-string 3 s))
18297 h (string-to-number (match-string 2 s)))
18298 (if (org-pos-in-match-range pos 2)
18299 (setq h (+ h n))
18300 (setq n (* dm (with-no-warnings (signum n))))
18301 (unless (= 0 (setq rem (% m dm)))
18302 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18303 (setq m (+ m n)))
18304 (when (< m 0) (setq m (+ m 60) h (1- h)))
18305 (when (> m 59) (setq m (- m 60) h (1+ h)))
18306 (setq h (mod h 24))
18307 (setq ng 1 new (format "-%02d:%02d" h m)))
18308 ((org-pos-in-match-range pos 6)
18309 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18310 ((org-pos-in-match-range pos 5)
18311 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18313 ((org-pos-in-match-range pos 9)
18314 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18315 ((org-pos-in-match-range pos 8)
18316 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18318 (when ng
18319 (setq s (concat
18320 (substring s 0 (match-beginning ng))
18322 (substring s (match-end ng))))))
18325 (defun org-recenter-calendar (d)
18326 "If the calendar is visible, recenter it to date D."
18327 (let ((cwin (get-buffer-window "*Calendar*" t)))
18328 (when cwin
18329 (let ((calendar-move-hook nil))
18330 (with-selected-window cwin
18331 (calendar-goto-date
18332 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18334 (defun org-goto-calendar (&optional arg)
18335 "Go to the Emacs calendar at the current date.
18336 If there is a time stamp in the current line, go to that date.
18337 A prefix ARG can be used to force the current date."
18338 (interactive "P")
18339 (let ((tsr org-ts-regexp) diff
18340 (calendar-move-hook nil)
18341 (calendar-view-holidays-initially-flag nil)
18342 (calendar-view-diary-initially-flag nil))
18343 (when (or (org-at-timestamp-p)
18344 (save-excursion
18345 (beginning-of-line 1)
18346 (looking-at (concat ".*" tsr))))
18347 (let ((d1 (time-to-days (current-time)))
18348 (d2 (time-to-days
18349 (org-time-string-to-time (match-string 1)))))
18350 (setq diff (- d2 d1))))
18351 (calendar)
18352 (calendar-goto-today)
18353 (when (and diff (not arg)) (calendar-forward-day diff))))
18355 (defun org-get-date-from-calendar ()
18356 "Return a list (month day year) of date at point in calendar."
18357 (with-current-buffer "*Calendar*"
18358 (save-match-data
18359 (calendar-cursor-to-date))))
18361 (defun org-date-from-calendar ()
18362 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18363 If there is already a time stamp at the cursor position, update it."
18364 (interactive)
18365 (if (org-at-timestamp-p t)
18366 (org-timestamp-change 0 'calendar)
18367 (let ((cal-date (org-get-date-from-calendar)))
18368 (org-insert-time-stamp
18369 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18371 (defcustom org-effort-durations
18372 `(("min" . 1)
18373 ("h" . 60)
18374 ("d" . ,(* 60 8))
18375 ("w" . ,(* 60 8 5))
18376 ("m" . ,(* 60 8 5 4))
18377 ("y" . ,(* 60 8 5 40)))
18378 "Conversion factor to minutes for an effort modifier.
18380 Each entry has the form (MODIFIER . MINUTES).
18382 In an effort string, a number followed by MODIFIER is multiplied
18383 by the specified number of MINUTES to obtain an effort in
18384 minutes.
18386 For example, if the value of this variable is ((\"hours\" . 60)), then an
18387 effort string \"2hours\" is equivalent to 120 minutes."
18388 :group 'org-agenda
18389 :version "26.1"
18390 :package-version '(Org . "8.3")
18391 :type '(alist :key-type (string :tag "Modifier")
18392 :value-type (number :tag "Minutes")))
18394 (defun org-minutes-to-clocksum-string (m)
18395 "Format number of minutes as a clocksum string.
18396 The format is determined by `org-time-clocksum-format',
18397 `org-time-clocksum-use-fractional' and
18398 `org-time-clocksum-fractional-format' and
18399 `org-time-clocksum-use-effort-durations'."
18400 (let ((clocksum "")
18401 (m (round m)) ; Don't allow fractions of minutes
18402 h d w mo y fmt n)
18403 (setq h (if org-time-clocksum-use-effort-durations
18404 (cdr (assoc "h" org-effort-durations)) 60)
18405 d (if org-time-clocksum-use-effort-durations
18406 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18407 w (if org-time-clocksum-use-effort-durations
18408 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18409 mo (if org-time-clocksum-use-effort-durations
18410 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18411 y (if org-time-clocksum-use-effort-durations
18412 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18413 ;; fractional format
18414 (if org-time-clocksum-use-fractional
18415 (cond
18416 ;; single format string
18417 ((stringp org-time-clocksum-fractional-format)
18418 (format org-time-clocksum-fractional-format (/ m (float h))))
18419 ;; choice of fractional formats for different time units
18420 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18421 (> (/ (truncate m) (* y d h)) 0))
18422 (format fmt (/ m (* y d (float h)))))
18423 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18424 (> (/ (truncate m) (* mo d h)) 0))
18425 (format fmt (/ m (* mo d (float h)))))
18426 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18427 (> (/ (truncate m) (* w d h)) 0))
18428 (format fmt (/ m (* w d (float h)))))
18429 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18430 (> (/ (truncate m) (* d h)) 0))
18431 (format fmt (/ m (* d (float h)))))
18432 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18433 (> (/ (truncate m) h) 0))
18434 (format fmt (/ m (float h))))
18435 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18436 (format fmt m))
18437 ;; fall back to smallest time unit with a format
18438 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18439 (format fmt (/ m (float h))))
18440 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18441 (format fmt (/ m (* d (float h)))))
18442 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18443 (format fmt (/ m (* w d (float h)))))
18444 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18445 (format fmt (/ m (* mo d (float h)))))
18446 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18447 (format fmt (/ m (* y d (float h))))))
18448 ;; standard (non-fractional) format, with single format string
18449 (if (stringp org-time-clocksum-format)
18450 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18451 ;; separate formats components
18452 (and (setq fmt (plist-get org-time-clocksum-format :years))
18453 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18454 (plist-get org-time-clocksum-format :require-years))
18455 (setq clocksum (concat clocksum (format fmt n))
18456 m (- m (* n y d h))))
18457 (and (setq fmt (plist-get org-time-clocksum-format :months))
18458 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18459 (plist-get org-time-clocksum-format :require-months))
18460 (setq clocksum (concat clocksum (format fmt n))
18461 m (- m (* n mo d h))))
18462 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18463 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18464 (plist-get org-time-clocksum-format :require-weeks))
18465 (setq clocksum (concat clocksum (format fmt n))
18466 m (- m (* n w d h))))
18467 (and (setq fmt (plist-get org-time-clocksum-format :days))
18468 (or (> (setq n (/ (truncate m) (* d h))) 0)
18469 (plist-get org-time-clocksum-format :require-days))
18470 (setq clocksum (concat clocksum (format fmt n))
18471 m (- m (* n d h))))
18472 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18473 (or (> (setq n (/ (truncate m) h)) 0)
18474 (plist-get org-time-clocksum-format :require-hours))
18475 (setq clocksum (concat clocksum (format fmt n))
18476 m (- m (* n h))))
18477 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18478 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18479 (setq clocksum (concat clocksum (format fmt m))))
18480 ;; return formatted time duration
18481 clocksum))))
18483 (defun org-hours-to-clocksum-string (n)
18484 (org-minutes-to-clocksum-string (* n 60)))
18486 (defun org-hh:mm-string-to-minutes (s)
18487 "Convert a string H:MM to a number of minutes.
18488 If the string is just a number, interpret it as minutes.
18489 In fact, the first hh:mm or number in the string will be taken,
18490 there can be extra stuff in the string.
18491 If no number is found, the return value is 0."
18492 (cond
18493 ((integerp s) s)
18494 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18495 (+ (* (string-to-number (match-string 1 s)) 60)
18496 (string-to-number (match-string 2 s))))
18497 ((string-match "\\([0-9]+\\)" s)
18498 (string-to-number (match-string 1 s)))
18499 (t 0)))
18501 (defcustom org-image-actual-width t
18502 "Should we use the actual width of images when inlining them?
18504 When set to t, always use the image width.
18506 When set to a number, use imagemagick (when available) to set
18507 the image's width to this value.
18509 When set to a number in a list, try to get the width from any
18510 #+ATTR.* keyword if it matches a width specification like
18512 #+ATTR_HTML: :width 300px
18514 and fall back on that number if none is found.
18516 When set to nil, try to get the width from an #+ATTR.* keyword
18517 and fall back on the original width if none is found.
18519 This requires Emacs >= 24.1, build with imagemagick support."
18520 :group 'org-appearance
18521 :version "24.4"
18522 :package-version '(Org . "8.0")
18523 :type '(choice
18524 (const :tag "Use the image width" t)
18525 (integer :tag "Use a number of pixels")
18526 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18527 (const :tag "Use #+ATTR* or don't resize" nil)))
18529 (defcustom org-agenda-inhibit-startup nil
18530 "Inhibit startup when preparing agenda buffers.
18531 When this variable is t, the initialization of the Org agenda
18532 buffers is inhibited: e.g. the visibility state is not set, the
18533 tables are not re-aligned, etc."
18534 :type 'boolean
18535 :version "24.3"
18536 :group 'org-agenda)
18538 (defcustom org-agenda-ignore-properties nil
18539 "Avoid updating text properties when building the agenda.
18540 Properties are used to prepare buffers for effort estimates,
18541 appointments, statistics and subtree-local categories.
18542 If you don't use these in the agenda, you can add them to this
18543 list and agenda building will be a bit faster.
18544 The value is a list, with zero or more of the symbols `effort', `appt',
18545 `stats' or `category'."
18546 :type '(set :greedy t
18547 (const effort)
18548 (const appt)
18549 (const stats)
18550 (const category))
18551 :version "26.1"
18552 :package-version '(Org . "8.3")
18553 :group 'org-agenda)
18555 (defun org-duration-string-to-minutes (s &optional output-to-string)
18556 "Convert a duration string S to minutes.
18558 A bare number is interpreted as minutes, modifiers can be set by
18559 customizing `org-effort-durations' (which see).
18561 Entries containing a colon are interpreted as H:MM by
18562 `org-hh:mm-string-to-minutes'."
18563 (let ((result 0)
18564 (re (concat "\\([0-9.]+\\) *\\("
18565 (regexp-opt (mapcar 'car org-effort-durations))
18566 "\\)")))
18567 (while (string-match re s)
18568 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18569 (string-to-number (match-string 1 s))))
18570 (setq s (replace-match "" nil t s)))
18571 (setq result (floor result))
18572 (cl-incf result (org-hh:mm-string-to-minutes s))
18573 (if output-to-string (number-to-string result) result)))
18575 ;;;; Files
18577 (defun org-save-all-org-buffers ()
18578 "Save all Org buffers without user confirmation."
18579 (interactive)
18580 (message "Saving all Org buffers...")
18581 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18582 (when (featurep 'org-id) (org-id-locations-save))
18583 (message "Saving all Org buffers... done"))
18585 (defun org-revert-all-org-buffers ()
18586 "Revert all Org buffers.
18587 Prompt for confirmation when there are unsaved changes.
18588 Be sure you know what you are doing before letting this function
18589 overwrite your changes.
18591 This function is useful in a setup where one tracks org files
18592 with a version control system, to revert on one machine after pulling
18593 changes from another. I believe the procedure must be like this:
18595 1. M-x org-save-all-org-buffers
18596 2. Pull changes from the other machine, resolve conflicts
18597 3. M-x org-revert-all-org-buffers"
18598 (interactive)
18599 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18600 (user-error "Abort"))
18601 (save-excursion
18602 (save-window-excursion
18603 (dolist (b (buffer-list))
18604 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18605 (with-current-buffer b buffer-file-name))
18606 (pop-to-buffer-same-window b)
18607 (revert-buffer t 'no-confirm)))
18608 (when (and (featurep 'org-id) org-id-track-globally)
18609 (org-id-locations-load)))))
18611 ;;;; Agenda files
18613 ;;;###autoload
18614 (defun org-switchb (&optional arg)
18615 "Switch between Org buffers.
18617 With `\\[universal-argument]' prefix, restrict available buffers to files.
18619 With `\\[universal-argument] \\[universal-argument]' \
18620 prefix, restrict available buffers to agenda files."
18621 (interactive "P")
18622 (let ((blist (org-buffer-list
18623 (cond ((equal arg '(4)) 'files)
18624 ((equal arg '(16)) 'agenda)))))
18625 (pop-to-buffer-same-window
18626 (completing-read "Org buffer: "
18627 (mapcar #'list (mapcar #'buffer-name blist))
18628 nil t))))
18630 (defun org-buffer-list (&optional predicate exclude-tmp)
18631 "Return a list of Org buffers.
18632 PREDICATE can be `export', `files' or `agenda'.
18634 export restrict the list to Export buffers.
18635 files restrict the list to buffers visiting Org files.
18636 agenda restrict the list to buffers visiting agenda files.
18638 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18639 (let* ((bfn nil)
18640 (agenda-files (and (eq predicate 'agenda)
18641 (mapcar 'file-truename (org-agenda-files t))))
18642 (filter
18643 (cond
18644 ((eq predicate 'files)
18645 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18646 ((eq predicate 'export)
18647 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18648 ((eq predicate 'agenda)
18649 (lambda (b)
18650 (with-current-buffer b
18651 (and (derived-mode-p 'org-mode)
18652 (setq bfn (buffer-file-name b))
18653 (member (file-truename bfn) agenda-files)))))
18654 (t (lambda (b) (with-current-buffer b
18655 (or (derived-mode-p 'org-mode)
18656 (string-match "\\*Org .*Export"
18657 (buffer-name b)))))))))
18658 (delq nil
18659 (mapcar
18660 (lambda(b)
18661 (if (and (funcall filter b)
18662 (or (not exclude-tmp)
18663 (not (string-match "tmp" (buffer-name b)))))
18665 nil))
18666 (buffer-list)))))
18668 (defun org-agenda-files (&optional unrestricted archives)
18669 "Get the list of agenda files.
18670 Optional UNRESTRICTED means return the full list even if a restriction
18671 is currently in place.
18672 When ARCHIVES is t, include all archive files that are really being
18673 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18674 `org-agenda-archives-mode' is t."
18675 (let ((files
18676 (cond
18677 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18678 ((stringp org-agenda-files) (org-read-agenda-file-list))
18679 ((listp org-agenda-files) org-agenda-files)
18680 (t (error "Invalid value of `org-agenda-files'")))))
18681 (setq files (apply 'append
18682 (mapcar (lambda (f)
18683 (if (file-directory-p f)
18684 (directory-files
18685 f t org-agenda-file-regexp)
18686 (list f)))
18687 files)))
18688 (when org-agenda-skip-unavailable-files
18689 (setq files (delq nil
18690 (mapcar (function
18691 (lambda (file)
18692 (and (file-readable-p file) file)))
18693 files))))
18694 (when (or (eq archives t)
18695 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18696 (setq files (org-add-archive-files files)))
18697 files))
18699 (defun org-agenda-file-p (&optional file)
18700 "Return non-nil, if FILE is an agenda file.
18701 If FILE is omitted, use the file associated with the current
18702 buffer."
18703 (let ((fname (or file (buffer-file-name))))
18704 (and fname
18705 (member (file-truename fname)
18706 (mapcar #'file-truename (org-agenda-files t))))))
18708 (defun org-edit-agenda-file-list ()
18709 "Edit the list of agenda files.
18710 Depending on setup, this either uses customize to edit the variable
18711 `org-agenda-files', or it visits the file that is holding the list. In the
18712 latter case, the buffer is set up in a way that saving it automatically kills
18713 the buffer and restores the previous window configuration."
18714 (interactive)
18715 (if (stringp org-agenda-files)
18716 (let ((cw (current-window-configuration)))
18717 (find-file org-agenda-files)
18718 (setq-local org-window-configuration cw)
18719 (add-hook 'after-save-hook
18720 (lambda ()
18721 (set-window-configuration
18722 (prog1 org-window-configuration
18723 (kill-buffer (current-buffer))))
18724 (org-install-agenda-files-menu)
18725 (message "New agenda file list installed"))
18726 nil 'local)
18727 (message "%s" (substitute-command-keys
18728 "Edit list and finish with \\[save-buffer]")))
18729 (customize-variable 'org-agenda-files)))
18731 (defun org-store-new-agenda-file-list (list)
18732 "Set new value for the agenda file list and save it correctly."
18733 (if (stringp org-agenda-files)
18734 (let ((fe (org-read-agenda-file-list t)) b u)
18735 (while (setq b (find-buffer-visiting org-agenda-files))
18736 (kill-buffer b))
18737 (with-temp-file org-agenda-files
18738 (insert
18739 (mapconcat
18740 (lambda (f) ;; Keep un-expanded entries.
18741 (if (setq u (assoc f fe))
18742 (cdr u)
18744 list "\n")
18745 "\n")))
18746 (let ((org-mode-hook nil) (org-inhibit-startup t)
18747 (org-insert-mode-line-in-empty-file nil))
18748 (setq org-agenda-files list)
18749 (customize-save-variable 'org-agenda-files org-agenda-files))))
18751 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18752 "Read the list of agenda files from a file.
18753 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18754 filenames, used by `org-store-new-agenda-file-list' to write back
18755 un-expanded file names."
18756 (when (file-directory-p org-agenda-files)
18757 (error "`org-agenda-files' cannot be a single directory"))
18758 (when (stringp org-agenda-files)
18759 (with-temp-buffer
18760 (insert-file-contents org-agenda-files)
18761 (mapcar
18762 (lambda (f)
18763 (let ((e (expand-file-name (substitute-in-file-name f)
18764 org-directory)))
18765 (if pair-with-expansion
18766 (cons e f)
18767 e)))
18768 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18770 ;;;###autoload
18771 (defun org-cycle-agenda-files ()
18772 "Cycle through the files in `org-agenda-files'.
18773 If the current buffer visits an agenda file, find the next one in the list.
18774 If the current buffer does not, find the first agenda file."
18775 (interactive)
18776 (let* ((fs (or (org-agenda-files t)
18777 (user-error "No agenda files")))
18778 (files (copy-sequence fs))
18779 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18780 file)
18781 (when tcf
18782 (while (and (setq file (pop files))
18783 (not (equal (file-truename file) tcf)))))
18784 (find-file (car (or files fs)))
18785 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18787 (defun org-agenda-file-to-front (&optional to-end)
18788 "Move/add the current file to the top of the agenda file list.
18789 If the file is not present in the list, it is added to the front. If it is
18790 present, it is moved there. With optional argument TO-END, add/move to the
18791 end of the list."
18792 (interactive "P")
18793 (let ((org-agenda-skip-unavailable-files nil)
18794 (file-alist (mapcar (lambda (x)
18795 (cons (file-truename x) x))
18796 (org-agenda-files t)))
18797 (ctf (file-truename
18798 (or buffer-file-name
18799 (user-error "Please save the current buffer to a file"))))
18800 x had)
18801 (setq x (assoc ctf file-alist) had x)
18803 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18804 (if to-end
18805 (setq file-alist (append (delq x file-alist) (list x)))
18806 (setq file-alist (cons x (delq x file-alist))))
18807 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18808 (org-install-agenda-files-menu)
18809 (message "File %s to %s of agenda file list"
18810 (if had "moved" "added") (if to-end "end" "front"))))
18812 (defun org-remove-file (&optional file)
18813 "Remove current file from the list of files in variable `org-agenda-files'.
18814 These are the files which are being checked for agenda entries.
18815 Optional argument FILE means use this file instead of the current."
18816 (interactive)
18817 (let* ((org-agenda-skip-unavailable-files nil)
18818 (file (or file buffer-file-name
18819 (user-error "Current buffer does not visit a file")))
18820 (true-file (file-truename file))
18821 (afile (abbreviate-file-name file))
18822 (files (delq nil (mapcar
18823 (lambda (x)
18824 (unless (equal true-file
18825 (file-truename x))
18827 (org-agenda-files t)))))
18828 (if (not (= (length files) (length (org-agenda-files t))))
18829 (progn
18830 (org-store-new-agenda-file-list files)
18831 (org-install-agenda-files-menu)
18832 (message "Removed from Org Agenda list: %s" afile))
18833 (message "File was not in list: %s (not removed)" afile))))
18835 (defun org-file-menu-entry (file)
18836 (vector file (list 'find-file file) t))
18838 (defun org-check-agenda-file (file)
18839 "Make sure FILE exists. If not, ask user what to do."
18840 (unless (file-exists-p file)
18841 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18842 (abbreviate-file-name file))
18843 (let ((r (downcase (read-char-exclusive))))
18844 (cond
18845 ((equal r ?r)
18846 (org-remove-file file)
18847 (throw 'nextfile t))
18848 (t (user-error "Abort"))))))
18850 (defun org-get-agenda-file-buffer (file)
18851 "Get an agenda buffer visiting FILE.
18852 If the buffer needs to be created, add it to the list of buffers
18853 which might be released later."
18854 (let ((buf (org-find-base-buffer-visiting file)))
18855 (if buf
18856 buf ; just return it
18857 ;; Make a new buffer and remember it
18858 (setq buf (find-file-noselect file))
18859 (when buf (push buf org-agenda-new-buffers))
18860 buf)))
18862 (defun org-release-buffers (blist)
18863 "Release all buffers in list, asking the user for confirmation when needed.
18864 When a buffer is unmodified, it is just killed. When modified, it is saved
18865 \(if the user agrees) and then killed."
18866 (let (file)
18867 (dolist (buf blist)
18868 (setq file (buffer-file-name buf))
18869 (when (and (buffer-modified-p buf)
18870 file
18871 (y-or-n-p (format "Save file %s? " file)))
18872 (with-current-buffer buf (save-buffer)))
18873 (kill-buffer buf))))
18875 (defun org-agenda-prepare-buffers (files)
18876 "Create buffers for all agenda files, protect archived trees and comments."
18877 (interactive)
18878 (let ((pa '(:org-archived t))
18879 (pc '(:org-comment t))
18880 (pall '(:org-archived t :org-comment t))
18881 (inhibit-read-only t)
18882 (org-inhibit-startup org-agenda-inhibit-startup)
18883 (rea (concat ":" org-archive-tag ":"))
18884 re pos)
18885 (setq org-tag-alist-for-agenda nil
18886 org-tag-groups-alist-for-agenda nil)
18887 (save-excursion
18888 (save-restriction
18889 (dolist (file files)
18890 (catch 'nextfile
18891 (if (bufferp file)
18892 (set-buffer file)
18893 (org-check-agenda-file file)
18894 (set-buffer (org-get-agenda-file-buffer file)))
18895 (widen)
18896 (org-set-regexps-and-options 'tags-only)
18897 (setq pos (point))
18898 (or (memq 'category org-agenda-ignore-properties)
18899 (org-refresh-category-properties))
18900 (or (memq 'stats org-agenda-ignore-properties)
18901 (org-refresh-stats-properties))
18902 (or (memq 'effort org-agenda-ignore-properties)
18903 (org-refresh-effort-properties))
18904 (or (memq 'appt org-agenda-ignore-properties)
18905 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18906 (setq org-todo-keywords-for-agenda
18907 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18908 (setq org-done-keywords-for-agenda
18909 (append org-done-keywords-for-agenda org-done-keywords))
18910 (setq org-todo-keyword-alist-for-agenda
18911 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18912 (setq org-tag-alist-for-agenda
18913 (org-uniquify
18914 (append org-tag-alist-for-agenda
18915 org-current-tag-alist)))
18916 ;; Merge current file's tag groups into global
18917 ;; `org-tag-groups-alist-for-agenda'.
18918 (when org-group-tags
18919 (dolist (alist org-tag-groups-alist)
18920 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18921 (if old
18922 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18923 (push alist org-tag-groups-alist-for-agenda)))))
18924 (org-with-silent-modifications
18925 (save-excursion
18926 (remove-text-properties (point-min) (point-max) pall)
18927 (when org-agenda-skip-archived-trees
18928 (goto-char (point-min))
18929 (while (re-search-forward rea nil t)
18930 (when (org-at-heading-p t)
18931 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18932 (goto-char (point-min))
18933 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18934 (while (re-search-forward re nil t)
18935 (when (save-match-data (org-in-commented-heading-p t))
18936 (add-text-properties
18937 (match-beginning 0) (org-end-of-subtree t) pc)))))
18938 (goto-char pos)))))
18939 (setq org-todo-keywords-for-agenda
18940 (org-uniquify org-todo-keywords-for-agenda))
18941 (setq org-todo-keyword-alist-for-agenda
18942 (org-uniquify org-todo-keyword-alist-for-agenda))))
18945 ;;;; CDLaTeX minor mode
18947 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18948 "Keymap for the minor `org-cdlatex-mode'.")
18950 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18951 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18952 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18953 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18954 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18956 (defvar org-cdlatex-texmathp-advice-is-done nil
18957 "Flag remembering if we have applied the advice to texmathp already.")
18959 (define-minor-mode org-cdlatex-mode
18960 "Toggle the minor `org-cdlatex-mode'.
18961 This mode supports entering LaTeX environment and math in LaTeX fragments
18962 in Org mode.
18963 \\{org-cdlatex-mode-map}"
18964 nil " OCDL" nil
18965 (when org-cdlatex-mode
18966 (require 'cdlatex)
18967 (run-hooks 'cdlatex-mode-hook)
18968 (cdlatex-compute-tables))
18969 (unless org-cdlatex-texmathp-advice-is-done
18970 (setq org-cdlatex-texmathp-advice-is-done t)
18971 (defadvice texmathp (around org-math-always-on activate)
18972 "Always return t in Org buffers.
18973 This is because we want to insert math symbols without dollars even outside
18974 the LaTeX math segments. If Org mode thinks that point is actually inside
18975 an embedded LaTeX fragment, let `texmathp' do its job.
18976 `\\[org-cdlatex-mode-map]'"
18977 (interactive)
18978 (let (p)
18979 (cond
18980 ((not (derived-mode-p 'org-mode)) ad-do-it)
18981 ((eq this-command 'cdlatex-math-symbol)
18982 (setq ad-return-value t
18983 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18985 (let ((p (org-inside-LaTeX-fragment-p)))
18986 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18987 (setq ad-return-value t
18988 texmathp-why '("Org mode embedded math" . 0))
18989 (when p ad-do-it)))))))))
18991 (defun turn-on-org-cdlatex ()
18992 "Unconditionally turn on `org-cdlatex-mode'."
18993 (org-cdlatex-mode 1))
18995 (defun org-try-cdlatex-tab ()
18996 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18997 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18998 - inside a LaTeX fragment, or
18999 - after the first word in a line, where an abbreviation expansion could
19000 insert a LaTeX environment."
19001 (when org-cdlatex-mode
19002 (cond
19003 ;; Before any word on the line: No expansion possible.
19004 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
19005 ;; Just after first word on the line: Expand it. Make sure it
19006 ;; cannot happen on headlines, though.
19007 ((save-excursion
19008 (skip-chars-backward "a-zA-Z0-9*")
19009 (skip-chars-backward " \t")
19010 (and (bolp) (not (org-at-heading-p))))
19011 (cdlatex-tab) t)
19012 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
19014 (defun org-cdlatex-underscore-caret (&optional _arg)
19015 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
19016 Revert to the normal definition outside of these fragments."
19017 (interactive "P")
19018 (if (org-inside-LaTeX-fragment-p)
19019 (call-interactively 'cdlatex-sub-superscript)
19020 (let (org-cdlatex-mode)
19021 (call-interactively (key-binding (vector last-input-event))))))
19023 (defun org-cdlatex-math-modify (&optional _arg)
19024 "Execute `cdlatex-math-modify' in LaTeX fragments.
19025 Revert to the normal definition outside of these fragments."
19026 (interactive "P")
19027 (if (org-inside-LaTeX-fragment-p)
19028 (call-interactively 'cdlatex-math-modify)
19029 (let (org-cdlatex-mode)
19030 (call-interactively (key-binding (vector last-input-event))))))
19032 (defun org-cdlatex-environment-indent (&optional environment item)
19033 "Execute `cdlatex-environment' and indent the inserted environment.
19035 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
19037 The inserted environment is indented to current indentation
19038 unless point is at the beginning of the line, in which the
19039 environment remains unintended."
19040 (interactive)
19041 ;; cdlatex-environment always return nil. Therefore, capture output
19042 ;; first and determine if an environment was selected.
19043 (let* ((beg (point-marker))
19044 (end (copy-marker (point) t))
19045 (inserted (progn
19046 (ignore-errors (cdlatex-environment environment item))
19047 (< beg end)))
19048 ;; Figure out how many lines to move forward after the
19049 ;; environment has been inserted.
19050 (lines (when inserted
19051 (save-excursion
19052 (- (cl-loop while (< beg (point))
19053 with x = 0
19054 do (forward-line -1)
19055 (cl-incf x)
19056 finally return x)
19057 (if (progn (goto-char beg)
19058 (and (progn (skip-chars-forward " \t") (eolp))
19059 (progn (skip-chars-backward " \t") (bolp))))
19060 1 0)))))
19061 (env (org-trim (delete-and-extract-region beg end))))
19062 (when inserted
19063 ;; Get indentation of next line unless at column 0.
19064 (let ((ind (if (bolp) 0
19065 (save-excursion
19066 (org-return-indent)
19067 (prog1 (org-get-indentation)
19068 (when (progn (skip-chars-forward " \t") (eolp))
19069 (delete-region beg (point)))))))
19070 (bol (progn (skip-chars-backward " \t") (bolp))))
19071 ;; Insert a newline before environment unless at column zero
19072 ;; to "escape" the current line. Insert a newline if
19073 ;; something is one the same line as \end{ENVIRONMENT}.
19074 (insert
19075 (concat (unless bol "\n") env
19076 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
19077 (unless (zerop ind)
19078 (save-excursion
19079 (goto-char beg)
19080 (while (< (point) end)
19081 (unless (eolp) (indent-line-to ind))
19082 (forward-line))))
19083 (goto-char beg)
19084 (forward-line lines)
19085 (indent-line-to ind)))
19086 (set-marker beg nil)
19087 (set-marker end nil)))
19090 ;;;; LaTeX fragments
19092 (defun org-inside-LaTeX-fragment-p ()
19093 "Test if point is inside a LaTeX fragment.
19094 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19095 sequence appearing also before point.
19096 Even though the matchers for math are configurable, this function assumes
19097 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19098 delimiters are skipped when they have been removed by customization.
19099 The return value is nil, or a cons cell with the delimiter and the
19100 position of this delimiter.
19102 This function does a reasonably good job, but can locally be fooled by
19103 for example currency specifications. For example it will assume being in
19104 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19105 fragments that are properly closed, but during editing, we have to live
19106 with the uncertainty caused by missing closing delimiters. This function
19107 looks only before point, not after."
19108 (catch 'exit
19109 (let ((pos (point))
19110 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19111 (lim (progn
19112 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19113 (point)))
19114 dd-on str (start 0) m re)
19115 (goto-char pos)
19116 (when dodollar
19117 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19118 re (nth 1 (assoc "$" org-latex-regexps)))
19119 (while (string-match re str start)
19120 (cond
19121 ((= (match-end 0) (length str))
19122 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19123 ((= (match-end 0) (- (length str) 5))
19124 (throw 'exit nil))
19125 (t (setq start (match-end 0))))))
19126 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19127 (goto-char pos)
19128 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19129 (and (match-beginning 2) (throw 'exit nil))
19130 ;; count $$
19131 (while (re-search-backward "\\$\\$" lim t)
19132 (setq dd-on (not dd-on)))
19133 (goto-char pos)
19134 (when dd-on (cons "$$" m))))))
19136 (defun org-inside-latex-macro-p ()
19137 "Is point inside a LaTeX macro or its arguments?"
19138 (save-match-data
19139 (org-in-regexp
19140 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19142 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19143 "Build an overlay between BEG and END using IMAGE file.
19144 Argument IMAGETYPE is the extension of the displayed image,
19145 as a string. It defaults to \"png\"."
19146 (let ((ov (make-overlay beg end))
19147 (imagetype (or (intern imagetype) 'png)))
19148 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19149 (overlay-put ov 'evaporate t)
19150 (overlay-put ov
19151 'modification-hooks
19152 (list (lambda (o _flag _beg _end &optional _l)
19153 (delete-overlay o))))
19154 (overlay-put ov
19155 'display
19156 (list 'image :type imagetype :file image :ascent 'center))))
19158 (defun org--list-latex-overlays (&optional beg end)
19159 "List all Org LaTeX overlays in current buffer.
19160 Limit to overlays between BEG and END when those are provided."
19161 (cl-remove-if-not
19162 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19163 (overlays-in (or beg (point-min)) (or end (point-max)))))
19165 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19166 "Remove all overlays with LaTeX fragment images in current buffer.
19167 When optional arguments BEG and END are non-nil, remove all
19168 overlays between them instead. Return a non-nil value when some
19169 overlays were removed, nil otherwise."
19170 (let ((overlays (org--list-latex-overlays beg end)))
19171 (mapc #'delete-overlay overlays)
19172 overlays))
19174 (defun org-toggle-latex-fragment (&optional arg)
19175 "Preview the LaTeX fragment at point, or all locally or globally.
19177 If the cursor is on a LaTeX fragment, create the image and overlay
19178 it over the source code, if there is none. Remove it otherwise.
19179 If there is no fragment at point, display all fragments in the
19180 current section.
19182 With prefix ARG, preview or clear image for all fragments in the
19183 current subtree or in the whole buffer when used before the first
19184 headline. With a prefix ARG `\\[universal-argument] \
19185 \\[universal-argument]' preview or clear images
19186 for all fragments in the buffer."
19187 (interactive "P")
19188 (when (display-graphic-p)
19189 (catch 'exit
19190 (save-excursion
19191 (let (beg end msg)
19192 (cond
19193 ((or (equal arg '(16))
19194 (and (equal arg '(4))
19195 (org-with-limited-levels (org-before-first-heading-p))))
19196 (if (org-remove-latex-fragment-image-overlays)
19197 (progn (message "LaTeX fragments images removed from buffer")
19198 (throw 'exit nil))
19199 (setq msg "Creating images for buffer...")))
19200 ((equal arg '(4))
19201 (org-with-limited-levels (org-back-to-heading t))
19202 (setq beg (point))
19203 (setq end (progn (org-end-of-subtree t) (point)))
19204 (if (org-remove-latex-fragment-image-overlays beg end)
19205 (progn
19206 (message "LaTeX fragment images removed from subtree")
19207 (throw 'exit nil))
19208 (setq msg "Creating images for subtree...")))
19209 ((let ((datum (org-element-context)))
19210 (when (memq (org-element-type datum)
19211 '(latex-environment latex-fragment))
19212 (setq beg (org-element-property :begin datum))
19213 (setq end (org-element-property :end datum))
19214 (if (org-remove-latex-fragment-image-overlays beg end)
19215 (progn (message "LaTeX fragment image removed")
19216 (throw 'exit nil))
19217 (setq msg "Creating image...")))))
19219 (org-with-limited-levels
19220 (setq beg (if (org-at-heading-p) (line-beginning-position)
19221 (outline-previous-heading)
19222 (point)))
19223 (setq end (progn (outline-next-heading) (point)))
19224 (if (org-remove-latex-fragment-image-overlays beg end)
19225 (progn
19226 (message "LaTeX fragment images removed from section")
19227 (throw 'exit nil))
19228 (setq msg "Creating images for section...")))))
19229 (let ((file (buffer-file-name (buffer-base-buffer))))
19230 (org-format-latex
19231 (concat org-preview-latex-image-directory "org-ltximg")
19232 beg end
19233 ;; Emacs cannot overlay images from remote hosts. Create
19234 ;; it in `temporary-file-directory' instead.
19235 (if (or (not file) (file-remote-p file))
19236 temporary-file-directory
19237 default-directory)
19238 'overlays msg 'forbuffer org-preview-latex-default-process))
19239 (message (concat msg "done")))))))
19241 (defun org-format-latex
19242 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19243 "Replace LaTeX fragments with links to an image.
19245 The function takes care of creating the replacement image.
19247 Only consider fragments between BEG and END when those are
19248 provided.
19250 When optional argument OVERLAYS is non-nil, display the image on
19251 top of the fragment instead of replacing it.
19253 PROCESSING-TYPE is the conversion method to use, as a symbol.
19255 Some of the options can be changed using the variable
19256 `org-format-latex-options', which see."
19257 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19258 (unless (eq processing-type 'verbatim)
19259 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19260 (cnt 0)
19261 checkdir-flag)
19262 (goto-char (or beg (point-min)))
19263 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19264 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19265 (overlay-recenter (or end (point-max))))
19266 (while (re-search-forward math-regexp end t)
19267 (unless (and overlays
19268 (eq (get-char-property (point) 'org-overlay-type)
19269 'org-latex-overlay))
19270 (let* ((context (org-element-context))
19271 (type (org-element-type context)))
19272 (when (memq type '(latex-environment latex-fragment))
19273 (let ((block-type (eq type 'latex-environment))
19274 (value (org-element-property :value context))
19275 (beg (org-element-property :begin context))
19276 (end (save-excursion
19277 (goto-char (org-element-property :end context))
19278 (skip-chars-backward " \r\t\n")
19279 (point))))
19280 (cond
19281 ((eq processing-type 'mathjax)
19282 ;; Prepare for MathJax processing.
19283 (if (not (string-match "\\`\\$\\$?" value))
19284 (goto-char end)
19285 (delete-region beg end)
19286 (if (string= (match-string 0 value) "$$")
19287 (insert "\\[" (substring value 2 -2) "\\]")
19288 (insert "\\(" (substring value 1 -1) "\\)"))))
19289 ((assq processing-type org-preview-latex-process-alist)
19290 ;; Process to an image.
19291 (cl-incf cnt)
19292 (goto-char beg)
19293 (let* ((processing-info
19294 (cdr (assq processing-type org-preview-latex-process-alist)))
19295 (face (face-at-point))
19296 ;; Get the colors from the face at point.
19298 (let ((color (plist-get org-format-latex-options
19299 :foreground)))
19300 (if (and forbuffer (eq color 'auto))
19301 (face-attribute face :foreground nil 'default)
19302 color)))
19304 (let ((color (plist-get org-format-latex-options
19305 :background)))
19306 (if (and forbuffer (eq color 'auto))
19307 (face-attribute face :background nil 'default)
19308 color)))
19309 (hash (sha1 (prin1-to-string
19310 (list org-format-latex-header
19311 org-latex-default-packages-alist
19312 org-latex-packages-alist
19313 org-format-latex-options
19314 forbuffer value fg bg))))
19315 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19316 (absprefix (expand-file-name prefix dir))
19317 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19318 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19319 (sep (and block-type "\n\n"))
19320 (link (concat sep "[[file:" linkfile "]]" sep))
19321 (options
19322 (org-combine-plists
19323 org-format-latex-options
19324 `(:foreground ,fg :background ,bg))))
19325 (when msg (message msg cnt))
19326 (unless checkdir-flag ; Ensure the directory exists.
19327 (setq checkdir-flag t)
19328 (let ((todir (file-name-directory absprefix)))
19329 (unless (file-directory-p todir)
19330 (make-directory todir t))))
19331 (unless (file-exists-p movefile)
19332 (org-create-formula-image
19333 value movefile options forbuffer processing-type))
19334 (if overlays
19335 (progn
19336 (dolist (o (overlays-in beg end))
19337 (when (eq (overlay-get o 'org-overlay-type)
19338 'org-latex-overlay)
19339 (delete-overlay o)))
19340 (org--format-latex-make-overlay beg end movefile imagetype)
19341 (goto-char end))
19342 (delete-region beg end)
19343 (insert
19344 (org-add-props link
19345 (list 'org-latex-src
19346 (replace-regexp-in-string "\"" "" value)
19347 'org-latex-src-embed-type
19348 (if block-type 'paragraph 'character)))))))
19349 ((eq processing-type 'mathml)
19350 ;; Process to MathML.
19351 (unless (org-format-latex-mathml-available-p)
19352 (user-error "LaTeX to MathML converter not configured"))
19353 (cl-incf cnt)
19354 (when msg (message msg cnt))
19355 (goto-char beg)
19356 (delete-region beg end)
19357 (insert (org-format-latex-as-mathml
19358 value block-type prefix dir)))
19360 (error "Unknown conversion process %s for LaTeX fragments"
19361 processing-type)))))))))))
19363 (defun org-create-math-formula (latex-frag &optional mathml-file)
19364 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19365 Use `org-latex-to-mathml-convert-command'. If the conversion is
19366 sucessful, return the portion between \"<math...> </math>\"
19367 elements otherwise return nil. When MATHML-FILE is specified,
19368 write the results in to that file. When invoked as an
19369 interactive command, prompt for LATEX-FRAG, with initial value
19370 set to the current active region and echo the results for user
19371 inspection."
19372 (interactive (list (let ((frag (when (org-region-active-p)
19373 (buffer-substring-no-properties
19374 (region-beginning) (region-end)))))
19375 (read-string "LaTeX Fragment: " frag nil frag))))
19376 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19377 (let* ((tmp-in-file
19378 (let ((file (file-relative-name
19379 (make-temp-name (expand-file-name "ltxmathml-in")))))
19380 (write-region latex-frag nil file)
19381 file))
19382 (tmp-out-file (file-relative-name
19383 (make-temp-name (expand-file-name "ltxmathml-out"))))
19384 (cmd (format-spec
19385 org-latex-to-mathml-convert-command
19386 `((?j . ,(and org-latex-to-mathml-jar-file
19387 (shell-quote-argument
19388 (expand-file-name
19389 org-latex-to-mathml-jar-file))))
19390 (?I . ,(shell-quote-argument tmp-in-file))
19391 (?i . ,latex-frag)
19392 (?o . ,(shell-quote-argument tmp-out-file)))))
19393 mathml shell-command-output)
19394 (when (called-interactively-p 'any)
19395 (unless (org-format-latex-mathml-available-p)
19396 (user-error "LaTeX to MathML converter not configured")))
19397 (message "Running %s" cmd)
19398 (setq shell-command-output (shell-command-to-string cmd))
19399 (setq mathml
19400 (when (file-readable-p tmp-out-file)
19401 (with-current-buffer (find-file-noselect tmp-out-file t)
19402 (goto-char (point-min))
19403 (when (re-search-forward
19404 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19405 (regexp-quote
19406 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19407 nil t)
19408 (prog1 (match-string 0) (kill-buffer))))))
19409 (cond
19410 (mathml
19411 (setq mathml
19412 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19413 (when mathml-file
19414 (write-region mathml nil mathml-file))
19415 (when (called-interactively-p 'any)
19416 (message mathml)))
19417 ((message "LaTeX to MathML conversion failed")
19418 (message shell-command-output)))
19419 (delete-file tmp-in-file)
19420 (when (file-exists-p tmp-out-file)
19421 (delete-file tmp-out-file))
19422 mathml))
19424 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19425 prefix &optional dir)
19426 "Use `org-create-math-formula' but check local cache first."
19427 (let* ((absprefix (expand-file-name prefix dir))
19428 (print-length nil) (print-level nil)
19429 (formula-id (concat
19430 "formula-"
19431 (sha1
19432 (prin1-to-string
19433 (list latex-frag
19434 org-latex-to-mathml-convert-command)))))
19435 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19436 (formula-cache-dir (file-name-directory formula-cache)))
19438 (unless (file-directory-p formula-cache-dir)
19439 (make-directory formula-cache-dir t))
19441 (unless (file-exists-p formula-cache)
19442 (org-create-math-formula latex-frag formula-cache))
19444 (if (file-exists-p formula-cache)
19445 ;; Successful conversion. Return the link to MathML file.
19446 (org-add-props
19447 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19448 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19449 'org-latex-src-embed-type (if latex-frag-type
19450 'paragraph 'character)))
19451 ;; Failed conversion. Return the LaTeX fragment verbatim
19452 latex-frag)))
19454 (defun org--get-display-dpi ()
19455 "Get the DPI of the display.
19456 The function assumes that the display has the same pixel width in
19457 the horizontal and vertical directions."
19458 (if (display-graphic-p)
19459 (round (/ (display-pixel-height)
19460 (/ (display-mm-height) 25.4)))
19461 (error "Attempt to calculate the dpi of a non-graphic display")))
19463 (defun org-create-formula-image
19464 (string tofile options buffer &optional processing-type)
19465 "Create an image from LaTeX source using external processes.
19467 The LaTeX STRING is saved to a temporary LaTeX file, then
19468 converted to an image file by process PROCESSING-TYPE defined in
19469 `org-preview-latex-process-alist'. A nil value defaults to
19470 `org-preview-latex-default-process'.
19472 The generated image file is eventually moved to TOFILE.
19474 The OPTIONS argument controls the size, foreground color and
19475 background color of the generated image.
19477 When BUFFER non-nil, this function is used for LaTeX previewing.
19478 Otherwise, it is used to deal with LaTeX snippets showed in
19479 a HTML file."
19480 (let* ((processing-type (or processing-type
19481 org-preview-latex-default-process))
19482 (processing-info
19483 (cdr (assq processing-type org-preview-latex-process-alist)))
19484 (programs (plist-get processing-info :programs))
19485 (error-message (or (plist-get processing-info :message) ""))
19486 (use-xcolor (plist-get processing-info :use-xcolor))
19487 (image-input-type (plist-get processing-info :image-input-type))
19488 (image-output-type (plist-get processing-info :image-output-type))
19489 (post-clean (or (plist-get processing-info :post-clean)
19490 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19491 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19492 (latex-header
19493 (or (plist-get processing-info :latex-header)
19494 (org-latex-make-preamble
19495 (org-export-get-environment (org-export-get-backend 'latex))
19496 org-format-latex-header
19497 'snippet)))
19498 (latex-compiler (plist-get processing-info :latex-compiler))
19499 (image-converter (plist-get processing-info :image-converter))
19500 (tmpdir temporary-file-directory)
19501 (texfilebase (make-temp-name
19502 (expand-file-name "orgtex" tmpdir)))
19503 (texfile (concat texfilebase ".tex"))
19504 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19505 '(1.0 . 1.0)))
19506 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19507 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19508 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19509 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19510 "Black"))
19511 (bg (or (plist-get options (if buffer :background :html-background))
19512 "Transparent"))
19513 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19514 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19515 (dolist (program programs)
19516 (org-check-external-command program error-message))
19517 (if use-xcolor
19518 (progn (if (eq fg 'default)
19519 (setq fg (org-latex-color :foreground))
19520 (setq fg (org-latex-color-format fg)))
19521 (if (eq bg 'default)
19522 (setq bg (org-latex-color :background))
19523 (setq bg (org-latex-color-format
19524 (if (string= bg "Transparent") "white" bg))))
19525 (with-temp-file texfile
19526 (insert latex-header)
19527 (insert "\n\\begin{document}\n"
19528 "\\definecolor{fg}{rgb}{" fg "}\n"
19529 "\\definecolor{bg}{rgb}{" bg "}\n"
19530 "\n\\pagecolor{bg}\n"
19531 "\n{\\color{fg}\n"
19532 string
19533 "\n}\n"
19534 "\n\\end{document}\n")))
19535 (if (eq fg 'default)
19536 (setq fg (org-dvipng-color :foreground))
19537 (unless (string= fg "Transparent")
19538 (setq fg (org-dvipng-color-format fg))))
19539 (if (eq bg 'default)
19540 (setq bg (org-dvipng-color :background))
19541 (unless (string= bg "Transparent")
19542 (setq bg (org-dvipng-color-format bg))))
19543 (with-temp-file texfile
19544 (insert latex-header)
19545 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19547 (let* ((err-msg (format "Please adjust '%s' part of \
19548 `org-preview-latex-process-alist'."
19549 processing-type))
19550 (image-input-file
19551 (org-compile-file
19552 texfile latex-compiler image-input-type err-msg log-buf))
19553 (image-output-file
19554 (org-compile-file
19555 image-input-file image-converter image-output-type err-msg log-buf
19556 `((?F . ,(shell-quote-argument fg))
19557 (?B . ,(shell-quote-argument bg))
19558 (?D . ,(shell-quote-argument (format "%s" dpi)))
19559 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19560 (copy-file image-output-file tofile 'replace)
19561 (dolist (e post-clean)
19562 (when (file-exists-p (concat texfilebase e))
19563 (delete-file (concat texfilebase e))))
19564 image-output-file)))
19566 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19567 "Fill a LaTeX header template TPL.
19568 In the template, the following place holders will be recognized:
19570 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19571 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19572 [PACKAGES] \\usepackage statements for PKG
19573 [NO-PACKAGES] do not include PKG
19574 [EXTRA] the string EXTRA
19575 [NO-EXTRA] do not include EXTRA
19577 For backward compatibility, if both the positive and the negative place
19578 holder is missing, the positive one (without the \"NO-\") will be
19579 assumed to be present at the end of the template.
19580 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19581 EXTRA is a string.
19582 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19583 (let (rpl (end ""))
19584 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19585 (setq rpl (if (or (match-end 1) (not def-pkg))
19586 "" (org-latex-packages-to-string def-pkg snippets-p t))
19587 tpl (replace-match rpl t t tpl))
19588 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19590 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19591 (setq rpl (if (or (match-end 1) (not pkg))
19592 "" (org-latex-packages-to-string pkg snippets-p t))
19593 tpl (replace-match rpl t t tpl))
19594 (when pkg (setq end
19595 (concat end "\n"
19596 (org-latex-packages-to-string pkg snippets-p)))))
19598 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19599 (setq rpl (if (or (match-end 1) (not extra))
19600 "" (concat extra "\n"))
19601 tpl (replace-match rpl t t tpl))
19602 (when (and extra (string-match "\\S-" extra))
19603 (setq end (concat end "\n" extra))))
19605 (if (string-match "\\S-" end)
19606 (concat tpl "\n" end)
19607 tpl)))
19609 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19610 "Turn an alist of packages into a string with the \\usepackage macros."
19611 (setq pkg (mapconcat (lambda(p)
19612 (cond
19613 ((stringp p) p)
19614 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19615 (format "%% Package %s omitted" (cadr p)))
19616 ((equal "" (car p))
19617 (format "\\usepackage{%s}" (cadr p)))
19619 (format "\\usepackage[%s]{%s}"
19620 (car p) (cadr p)))))
19622 "\n"))
19623 (if newline (concat pkg "\n") pkg))
19625 (defun org-dvipng-color (attr)
19626 "Return a RGB color specification for dvipng."
19627 (org-dvipng-color-format (face-attribute 'default attr nil)))
19629 (defun org-dvipng-color-format (color-name)
19630 "Convert COLOR-NAME to a RGB color value for dvipng."
19631 (apply #'format "rgb %s %s %s"
19632 (mapcar 'org-normalize-color
19633 (color-values color-name))))
19635 (defun org-latex-color (attr)
19636 "Return a RGB color for the LaTeX color package."
19637 (org-latex-color-format (face-attribute 'default attr nil)))
19639 (defun org-latex-color-format (color-name)
19640 "Convert COLOR-NAME to a RGB color value."
19641 (apply #'format "%s,%s,%s"
19642 (mapcar 'org-normalize-color
19643 (color-values color-name))))
19645 (defun org-normalize-color (value)
19646 "Return string to be used as color value for an RGB component."
19647 (format "%g" (/ value 65535.0)))
19651 ;; Image display
19653 (defvar-local org-inline-image-overlays nil)
19655 (defun org-toggle-inline-images (&optional include-linked)
19656 "Toggle the display of inline images.
19657 INCLUDE-LINKED is passed to `org-display-inline-images'."
19658 (interactive "P")
19659 (if org-inline-image-overlays
19660 (progn
19661 (org-remove-inline-images)
19662 (when (called-interactively-p 'interactive)
19663 (message "Inline image display turned off")))
19664 (org-display-inline-images include-linked)
19665 (when (called-interactively-p 'interactive)
19666 (message (if org-inline-image-overlays
19667 (format "%d images displayed inline"
19668 (length org-inline-image-overlays))
19669 "No images to display inline")))))
19671 (defun org-redisplay-inline-images ()
19672 "Refresh the display of inline images."
19673 (interactive)
19674 (if (not org-inline-image-overlays)
19675 (org-toggle-inline-images)
19676 (org-toggle-inline-images)
19677 (org-toggle-inline-images)))
19679 (defun org-display-inline-images (&optional include-linked refresh beg end)
19680 "Display inline images.
19682 An inline image is a link which follows either of these
19683 conventions:
19685 1. Its path is a file with an extension matching return value
19686 from `image-file-name-regexp' and it has no contents.
19688 2. Its description consists in a single link of the previous
19689 type.
19691 When optional argument INCLUDE-LINKED is non-nil, also links with
19692 a text description part will be inlined. This can be nice for
19693 a quick look at those images, but it does not reflect what
19694 exported files will look like.
19696 When optional argument REFRESH is non-nil, refresh existing
19697 images between BEG and END. This will create new image displays
19698 only if necessary. BEG and END default to the buffer
19699 boundaries."
19700 (interactive "P")
19701 (when (display-graphic-p)
19702 (unless refresh
19703 (org-remove-inline-images)
19704 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19705 (org-with-wide-buffer
19706 (goto-char (or beg (point-min)))
19707 (let ((case-fold-search t)
19708 (file-extension-re (image-file-name-regexp)))
19709 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19710 (let ((link (save-match-data (org-element-context))))
19711 ;; Check if we're at an inline image.
19712 (when (and (equal (org-element-property :type link) "file")
19713 (or include-linked
19714 (not (org-element-property :contents-begin link)))
19715 (let ((parent (org-element-property :parent link)))
19716 (or (not (eq (org-element-type parent) 'link))
19717 (not (cdr (org-element-contents parent)))))
19718 (string-match-p file-extension-re
19719 (org-element-property :path link)))
19720 (let ((file (expand-file-name
19721 (org-link-unescape
19722 (org-element-property :path link)))))
19723 (when (file-exists-p file)
19724 (let ((width
19725 ;; Apply `org-image-actual-width' specifications.
19726 (cond
19727 ((not (image-type-available-p 'imagemagick)) nil)
19728 ((eq org-image-actual-width t) nil)
19729 ((listp org-image-actual-width)
19731 ;; First try to find a width among
19732 ;; attributes associated to the paragraph
19733 ;; containing link.
19734 (let ((paragraph
19735 (let ((e link))
19736 (while (and (setq e (org-element-property
19737 :parent e))
19738 (not (eq (org-element-type e)
19739 'paragraph))))
19740 e)))
19741 (when paragraph
19742 (save-excursion
19743 (goto-char (org-element-property :begin paragraph))
19744 (when
19745 (re-search-forward
19746 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19747 (org-element-property
19748 :post-affiliated paragraph)
19750 (string-to-number (match-string 1))))))
19751 ;; Otherwise, fall-back to provided number.
19752 (car org-image-actual-width)))
19753 ((numberp org-image-actual-width)
19754 org-image-actual-width)))
19755 (old (get-char-property-and-overlay
19756 (org-element-property :begin link)
19757 'org-image-overlay)))
19758 (if (and (car-safe old) refresh)
19759 (image-refresh (overlay-get (cdr old) 'display))
19760 (let ((image (create-image file
19761 (and width 'imagemagick)
19763 :width width)))
19764 (when image
19765 (let* ((link
19766 ;; If inline image is the description
19767 ;; of another link, be sure to
19768 ;; consider the latter as the one to
19769 ;; apply the overlay on.
19770 (let ((parent
19771 (org-element-property :parent link)))
19772 (if (eq (org-element-type parent) 'link)
19773 parent
19774 link)))
19775 (ov (make-overlay
19776 (org-element-property :begin link)
19777 (progn
19778 (goto-char
19779 (org-element-property :end link))
19780 (skip-chars-backward " \t")
19781 (point)))))
19782 (overlay-put ov 'display image)
19783 (overlay-put ov 'face 'default)
19784 (overlay-put ov 'org-image-overlay t)
19785 (overlay-put
19786 ov 'modification-hooks
19787 (list 'org-display-inline-remove-overlay))
19788 (push ov org-inline-image-overlays)))))))))))))))
19790 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19791 "Remove inline-display overlay if a corresponding region is modified."
19792 (let ((inhibit-modification-hooks t))
19793 (when (and ov after)
19794 (delete ov org-inline-image-overlays)
19795 (delete-overlay ov))))
19797 (defun org-remove-inline-images ()
19798 "Remove inline display of images."
19799 (interactive)
19800 (mapc #'delete-overlay org-inline-image-overlays)
19801 (setq org-inline-image-overlays nil))
19803 ;;;; Key bindings
19805 ;; Outline functions from `outline-mode-prefix-map'
19806 ;; that can be remapped in Org:
19807 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19808 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19809 (define-key org-mode-map [remap outline-forward-same-level]
19810 'org-forward-heading-same-level)
19811 (define-key org-mode-map [remap outline-backward-same-level]
19812 'org-backward-heading-same-level)
19813 (define-key org-mode-map [remap outline-show-branches]
19814 'org-kill-note-or-show-branches)
19815 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19816 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19817 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19818 (define-key org-mode-map [remap outline-next-visible-heading]
19819 'org-next-visible-heading)
19820 (define-key org-mode-map [remap outline-previous-visible-heading]
19821 'org-previous-visible-heading)
19822 (define-key org-mode-map [remap show-children] 'org-show-children)
19824 ;; Outline functions from `outline-mode-prefix-map' that can not
19825 ;; be remapped in Org:
19827 ;; - the column "key binding" shows whether the Outline function is still
19828 ;; available in Org mode on the same key that it has been bound to in
19829 ;; Outline mode:
19830 ;; - "overridden": key used for a different functionality in Org mode
19831 ;; - else: key still bound to the same Outline function in Org mode
19833 ;; | Outline function | key binding | Org replacement |
19834 ;; |------------------------------------+-------------+--------------------------|
19835 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19836 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19837 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19838 ;; | `show-entry' | overridden | no replacement |
19839 ;; | `show-branches' | `C-c C-k' | still same function |
19840 ;; | `show-subtree' | overridden | visibility cycling |
19841 ;; | `show-all' | overridden | no replacement |
19842 ;; | `hide-subtree' | overridden | visibility cycling |
19843 ;; | `hide-body' | overridden | no replacement |
19844 ;; | `hide-entry' | overridden | visibility cycling |
19845 ;; | `hide-leaves' | overridden | no replacement |
19846 ;; | `hide-sublevels' | overridden | no replacement |
19847 ;; | `hide-other' | overridden | no replacement |
19849 ;; Make `C-c C-x' a prefix key
19850 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19852 ;; TAB key with modifiers
19853 (org-defkey org-mode-map "\C-i" 'org-cycle)
19854 (org-defkey org-mode-map [(tab)] 'org-cycle)
19855 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19856 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19857 ;; The following line is necessary under Suse GNU/Linux
19858 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19859 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19860 (define-key org-mode-map [backtab] 'org-shifttab)
19862 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19863 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19864 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19866 ;; Cursor keys with modifiers
19867 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19868 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19869 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19870 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19872 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19873 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19874 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19875 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19876 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19877 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19879 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19880 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19881 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19882 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19884 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19885 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19886 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19887 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19889 ;; Babel keys
19890 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19891 (dolist (pair org-babel-key-bindings)
19892 (define-key org-babel-map (car pair) (cdr pair)))
19894 ;;; Extra keys for tty access.
19895 ;; We only set them when really needed because otherwise the
19896 ;; menus don't show the simple keys
19898 (when (or org-use-extra-keys (not window-system))
19899 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19900 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19901 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19902 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19903 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19904 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19905 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19906 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19907 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19908 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19909 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19910 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19911 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19912 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19913 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19914 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19915 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19916 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19917 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19918 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19919 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19920 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19921 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19922 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19923 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19924 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19925 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19926 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19928 ;; All the other keys
19930 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19931 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19932 (if (boundp 'narrow-map)
19933 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19934 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19935 (if (boundp 'narrow-map)
19936 (org-defkey narrow-map "b" 'org-narrow-to-block)
19937 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19938 (if (boundp 'narrow-map)
19939 (org-defkey narrow-map "e" 'org-narrow-to-element)
19940 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19941 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19942 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19943 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19944 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19945 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19946 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19947 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19948 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19949 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19950 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19951 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19952 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19953 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19954 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19955 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19956 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19957 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19958 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19959 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19960 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19961 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19962 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19963 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19964 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19965 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19966 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19967 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19968 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19969 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19970 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19971 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19972 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19973 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19974 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19975 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19976 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19977 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19978 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19979 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19980 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19981 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19982 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19983 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19984 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19985 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19986 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19987 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19988 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19989 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19990 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19991 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19992 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19993 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19994 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19995 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19996 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19997 (org-defkey org-mode-map "\C-c^" 'org-sort)
19998 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19999 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
20000 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
20001 (org-defkey org-mode-map [remap open-line] 'org-open-line)
20002 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
20003 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
20004 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
20005 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
20006 (org-defkey org-mode-map "\C-m" 'org-return)
20007 (org-defkey org-mode-map "\C-j" 'org-return-indent)
20008 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
20009 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
20010 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
20011 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
20012 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
20013 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
20014 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
20015 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
20016 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
20017 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
20018 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
20019 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
20020 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
20021 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
20022 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
20023 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
20024 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
20025 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
20026 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
20027 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
20028 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
20029 (org-defkey org-mode-map "\M-h" 'org-mark-element)
20030 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
20031 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
20033 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
20034 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
20035 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
20037 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
20038 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
20039 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
20040 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
20041 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
20042 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
20043 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
20044 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
20045 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
20046 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
20047 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
20048 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
20049 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
20050 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
20051 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
20052 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
20053 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
20054 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
20055 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
20056 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
20057 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
20058 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
20060 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
20061 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
20062 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
20063 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
20064 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
20066 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
20068 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
20070 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
20071 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
20073 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20076 (defconst org-speed-commands-default
20078 ("Outline Navigation")
20079 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20080 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20081 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20082 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20083 ("F" . org-next-block)
20084 ("B" . org-previous-block)
20085 ("u" . (org-speed-move-safe 'outline-up-heading))
20086 ("j" . org-goto)
20087 ("g" . (org-refile t))
20088 ("Outline Visibility")
20089 ("c" . org-cycle)
20090 ("C" . org-shifttab)
20091 (" " . org-display-outline-path)
20092 ("s" . org-narrow-to-subtree)
20093 ("=" . org-columns)
20094 ("Outline Structure Editing")
20095 ("U" . org-metaup)
20096 ("D" . org-metadown)
20097 ("r" . org-metaright)
20098 ("l" . org-metaleft)
20099 ("R" . org-shiftmetaright)
20100 ("L" . org-shiftmetaleft)
20101 ("i" . (progn (forward-char 1) (call-interactively
20102 'org-insert-heading-respect-content)))
20103 ("^" . org-sort)
20104 ("w" . org-refile)
20105 ("a" . org-archive-subtree-default-with-confirmation)
20106 ("@" . org-mark-subtree)
20107 ("#" . org-toggle-comment)
20108 ("Clock Commands")
20109 ("I" . org-clock-in)
20110 ("O" . org-clock-out)
20111 ("Meta Data Editing")
20112 ("t" . org-todo)
20113 ("," . (org-priority))
20114 ("0" . (org-priority ?\ ))
20115 ("1" . (org-priority ?A))
20116 ("2" . (org-priority ?B))
20117 ("3" . (org-priority ?C))
20118 (":" . org-set-tags-command)
20119 ("e" . org-set-effort)
20120 ("E" . org-inc-effort)
20121 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20122 (org-entry-put (point) "APPT_WARNTIME" m)))
20123 ("Agenda Views etc")
20124 ("v" . org-agenda)
20125 ("/" . org-sparse-tree)
20126 ("Misc")
20127 ("o" . org-open-at-point)
20128 ("?" . org-speed-command-help)
20129 ("<" . (org-agenda-set-restriction-lock 'subtree))
20130 (">" . (org-agenda-remove-restriction-lock))
20132 "The default speed commands.")
20134 (defun org-print-speed-command (e)
20135 (if (> (length (car e)) 1)
20136 (progn
20137 (princ "\n")
20138 (princ (car e))
20139 (princ "\n")
20140 (princ (make-string (length (car e)) ?-))
20141 (princ "\n"))
20142 (princ (car e))
20143 (princ " ")
20144 (if (symbolp (cdr e))
20145 (princ (symbol-name (cdr e)))
20146 (prin1 (cdr e)))
20147 (princ "\n")))
20149 (defun org-speed-command-help ()
20150 "Show the available speed commands."
20151 (interactive)
20152 (if (not org-use-speed-commands)
20153 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20154 (with-output-to-temp-buffer "*Help*"
20155 (princ "User-defined Speed commands\n===========================\n")
20156 (mapc #'org-print-speed-command org-speed-commands-user)
20157 (princ "\n")
20158 (princ "Built-in Speed commands\n=======================\n")
20159 (mapc #'org-print-speed-command org-speed-commands-default))
20160 (with-current-buffer "*Help*"
20161 (setq truncate-lines t))))
20163 (defun org-speed-move-safe (cmd)
20164 "Execute CMD, but make sure that the cursor always ends up in a headline.
20165 If not, return to the original position and throw an error."
20166 (interactive)
20167 (let ((pos (point)))
20168 (call-interactively cmd)
20169 (unless (and (bolp) (org-at-heading-p))
20170 (goto-char pos)
20171 (error "Boundary reached while executing %s" cmd))))
20173 (defvar org-self-insert-command-undo-counter 0)
20175 (defvar org-table-auto-blank-field) ; defined in org-table.el
20176 (defvar org-speed-command nil)
20178 (defun org-speed-command-activate (keys)
20179 "Hook for activating single-letter speed commands.
20180 `org-speed-commands-default' specifies a minimal command set.
20181 Use `org-speed-commands-user' for further customization."
20182 (when (or (and (bolp) (looking-at org-outline-regexp))
20183 (and (functionp org-use-speed-commands)
20184 (funcall org-use-speed-commands)))
20185 (cdr (assoc keys (append org-speed-commands-user
20186 org-speed-commands-default)))))
20188 (defun org-babel-speed-command-activate (keys)
20189 "Hook for activating single-letter code block commands."
20190 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20191 (cdr (assoc keys org-babel-key-bindings))))
20193 (defcustom org-speed-command-hook
20194 '(org-speed-command-default-hook org-babel-speed-command-hook)
20195 "Hook for activating speed commands at strategic locations.
20196 Hook functions are called in sequence until a valid handler is
20197 found.
20199 Each hook takes a single argument, a user-pressed command key
20200 which is also a `self-insert-command' from the global map.
20202 Within the hook, examine the cursor position and the command key
20203 and return nil or a valid handler as appropriate. Handler could
20204 be one of an interactive command, a function, or a form.
20206 Set `org-use-speed-commands' to non-nil value to enable this
20207 hook. The default setting is `org-speed-command-activate'."
20208 :group 'org-structure
20209 :version "24.1"
20210 :type 'hook)
20212 (defun org-self-insert-command (N)
20213 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20214 If the cursor is in a table looking at whitespace, the whitespace is
20215 overwritten, and the table is not marked as requiring realignment."
20216 (interactive "p")
20217 (org-check-before-invisible-edit 'insert)
20218 (cond
20219 ((and org-use-speed-commands
20220 (let ((kv (this-command-keys-vector)))
20221 (setq org-speed-command
20222 (run-hook-with-args-until-success
20223 'org-speed-command-hook
20224 (make-string 1 (aref kv (1- (length kv))))))))
20225 (cond
20226 ((commandp org-speed-command)
20227 (setq this-command org-speed-command)
20228 (call-interactively org-speed-command))
20229 ((functionp org-speed-command)
20230 (funcall org-speed-command))
20231 ((and org-speed-command (listp org-speed-command))
20232 (eval org-speed-command))
20233 (t (let (org-use-speed-commands)
20234 (call-interactively 'org-self-insert-command)))))
20235 ((and
20236 (org-at-table-p)
20237 (progn
20238 ;; Check if we blank the field, and if that triggers align.
20239 (and (featurep 'org-table) org-table-auto-blank-field
20240 (memq last-command
20241 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20242 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20243 ;; Got extra space, this field does not determine
20244 ;; column width.
20245 (let (org-table-may-need-update) (org-table-blank-field))
20246 ;; No extra space, this field may determine column
20247 ;; width.
20248 (org-table-blank-field)))
20250 (eq N 1)
20251 (looking-at "[^|\n]* \\( \\)|"))
20252 ;; There is room for insertion without re-aligning the table.
20253 (delete-region (match-beginning 1) (match-end 1))
20254 (self-insert-command N))
20256 (setq org-table-may-need-update t)
20257 (self-insert-command N)
20258 (org-fix-tags-on-the-fly)
20259 (when org-self-insert-cluster-for-undo
20260 (if (not (eq last-command 'org-self-insert-command))
20261 (setq org-self-insert-command-undo-counter 1)
20262 (if (>= org-self-insert-command-undo-counter 20)
20263 (setq org-self-insert-command-undo-counter 1)
20264 (and (> org-self-insert-command-undo-counter 0)
20265 buffer-undo-list (listp buffer-undo-list)
20266 (not (cadr buffer-undo-list)) ; remove nil entry
20267 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20268 (setq org-self-insert-command-undo-counter
20269 (1+ org-self-insert-command-undo-counter))))))))
20271 (defun org-check-before-invisible-edit (kind)
20272 "Check is editing if kind KIND would be dangerous with invisible text around.
20273 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20274 ;; First, try to get out of here as quickly as possible, to reduce overhead
20275 (when (and org-catch-invisible-edits
20276 (or (not (boundp 'visible-mode)) (not visible-mode))
20277 (or (get-char-property (point) 'invisible)
20278 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20279 ;; OK, we need to take a closer look
20280 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20281 (invisible-before-point (unless (bobp) (get-char-property
20282 (1- (point)) 'invisible)))
20283 (border-and-ok-direction
20285 ;; Check if we are acting predictably before invisible text
20286 (and invisible-at-point (not invisible-before-point)
20287 (memq kind '(insert delete-backward)))
20288 ;; Check if we are acting predictably after invisible text
20289 ;; This works not well, and I have turned it off. It seems
20290 ;; better to always show and stop after invisible text.
20291 ;; (and (not invisible-at-point) invisible-before-point
20292 ;; (memq kind '(insert delete)))
20294 (when (or (memq invisible-at-point '(outline org-hide-block t))
20295 (memq invisible-before-point '(outline org-hide-block t)))
20296 (when (eq org-catch-invisible-edits 'error)
20297 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20298 (if (and org-custom-properties-overlays
20299 (y-or-n-p "Display invisible properties in this buffer? "))
20300 (org-toggle-custom-properties-visibility)
20301 ;; Make the area visible
20302 (save-excursion
20303 (when invisible-before-point
20304 (goto-char (previous-single-char-property-change
20305 (point) 'invisible)))
20306 (outline-show-subtree))
20307 (cond
20308 ((eq org-catch-invisible-edits 'show)
20309 ;; That's it, we do the edit after showing
20310 (message
20311 "Unfolding invisible region around point before editing")
20312 (sit-for 1))
20313 ((and (eq org-catch-invisible-edits 'smart)
20314 border-and-ok-direction)
20315 (message "Unfolding invisible region around point before editing"))
20317 ;; Don't do the edit, make the user repeat it in full visibility
20318 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20320 (defun org-fix-tags-on-the-fly ()
20321 "Align tags in headline at point.
20322 Unlike to `org-set-tags', it ignores region and sorting."
20323 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
20324 (org-at-heading-p))
20325 (let ((org-ignore-region t)
20326 (org-tags-sort-function nil))
20327 (org-set-tags nil t))))
20329 (defun org-delete-backward-char (N)
20330 "Like `delete-backward-char', insert whitespace at field end in tables.
20331 When deleting backwards, in tables this function will insert whitespace in
20332 front of the next \"|\" separator, to keep the table aligned. The table will
20333 still be marked for re-alignment if the field did fill the entire column,
20334 because, in this case the deletion might narrow the column."
20335 (interactive "p")
20336 (save-match-data
20337 (org-check-before-invisible-edit 'delete-backward)
20338 (if (and (org-at-table-p)
20339 (eq N 1)
20340 (string-match "|" (buffer-substring (point-at-bol) (point)))
20341 (looking-at ".*?|"))
20342 (let ((pos (point))
20343 (noalign (looking-at "[^|\n\r]* |"))
20344 (c org-table-may-need-update))
20345 (backward-delete-char N)
20346 (unless overwrite-mode
20347 (skip-chars-forward "^|")
20348 (insert " ")
20349 (goto-char (1- pos)))
20350 ;; noalign: if there were two spaces at the end, this field
20351 ;; does not determine the width of the column.
20352 (when noalign (setq org-table-may-need-update c)))
20353 (backward-delete-char N)
20354 (org-fix-tags-on-the-fly))))
20356 (defun org-delete-char (N)
20357 "Like `delete-char', but insert whitespace at field end in tables.
20358 When deleting characters, in tables this function will insert whitespace in
20359 front of the next \"|\" separator, to keep the table aligned. The table will
20360 still be marked for re-alignment if the field did fill the entire column,
20361 because, in this case the deletion might narrow the column."
20362 (interactive "p")
20363 (save-match-data
20364 (org-check-before-invisible-edit 'delete)
20365 (if (and (org-at-table-p)
20366 (not (bolp))
20367 (not (= (char-after) ?|))
20368 (eq N 1))
20369 (if (looking-at ".*?|")
20370 (let ((pos (point))
20371 (noalign (looking-at "[^|\n\r]* |"))
20372 (c org-table-may-need-update))
20373 (replace-match
20374 (concat (substring (match-string 0) 1 -1) " |") nil t)
20375 (goto-char pos)
20376 ;; noalign: if there were two spaces at the end, this field
20377 ;; does not determine the width of the column.
20378 (when noalign (setq org-table-may-need-update c)))
20379 (delete-char N))
20380 (delete-char N)
20381 (org-fix-tags-on-the-fly))))
20383 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20384 (put 'org-self-insert-command 'delete-selection
20385 (lambda ()
20386 (not (run-hook-with-args-until-success
20387 'self-insert-uses-region-functions))))
20388 (put 'orgtbl-self-insert-command 'delete-selection
20389 (lambda ()
20390 (not (run-hook-with-args-until-success
20391 'self-insert-uses-region-functions))))
20392 (put 'org-delete-char 'delete-selection 'supersede)
20393 (put 'org-delete-backward-char 'delete-selection 'supersede)
20394 (put 'org-yank 'delete-selection 'yank)
20396 ;; Make `flyspell-mode' delay after some commands
20397 (put 'org-self-insert-command 'flyspell-delayed t)
20398 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20399 (put 'org-delete-char 'flyspell-delayed t)
20400 (put 'org-delete-backward-char 'flyspell-delayed t)
20402 ;; Make pabbrev-mode expand after Org mode commands
20403 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20404 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20406 (defun org-remap (map &rest commands)
20407 "In MAP, remap the functions given in COMMANDS.
20408 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20409 (let (new old)
20410 (while commands
20411 (setq old (pop commands) new (pop commands))
20412 (org-defkey map (vector 'remap old) new))))
20414 (defun org-transpose-words ()
20415 "Transpose words for Org.
20416 This uses the `org-mode-transpose-word-syntax-table' syntax
20417 table, which interprets characters in `org-emphasis-alist' as
20418 word constituents."
20419 (interactive)
20420 (with-syntax-table org-mode-transpose-word-syntax-table
20421 (call-interactively 'transpose-words)))
20422 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20424 (when (eq org-enable-table-editor 'optimized)
20425 ;; If the user wants maximum table support, we need to hijack
20426 ;; some standard editing functions
20427 (org-remap org-mode-map
20428 'self-insert-command 'org-self-insert-command
20429 'delete-char 'org-delete-char
20430 'delete-backward-char 'org-delete-backward-char)
20431 (org-defkey org-mode-map "|" 'org-force-self-insert))
20433 (defvar org-ctrl-c-ctrl-c-hook nil
20434 "Hook for functions attaching themselves to `C-c C-c'.
20436 This can be used to add additional functionality to the C-c C-c
20437 key which executes context-dependent commands. This hook is run
20438 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20439 run after the last test.
20441 Each function will be called with no arguments. The function
20442 must check if the context is appropriate for it to act. If yes,
20443 it should do its thing and then return a non-nil value. If the
20444 context is wrong, just do nothing and return nil.")
20446 (defvar org-ctrl-c-ctrl-c-final-hook nil
20447 "Hook for functions attaching themselves to `C-c C-c'.
20449 This can be used to add additional functionality to the C-c C-c
20450 key which executes context-dependent commands. This hook is run
20451 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20452 before the first test.
20454 Each function will be called with no arguments. The function
20455 must check if the context is appropriate for it to act. If yes,
20456 it should do its thing and then return a non-nil value. If the
20457 context is wrong, just do nothing and return nil.")
20459 (defvar org-tab-first-hook nil
20460 "Hook for functions to attach themselves to TAB.
20461 See `org-ctrl-c-ctrl-c-hook' for more information.
20462 This hook runs as the first action when TAB is pressed, even before
20463 `org-cycle' messes around with the `outline-regexp' to cater for
20464 inline tasks and plain list item folding.
20465 If any function in this hook returns t, any other actions that
20466 would have been caused by TAB (such as table field motion or visibility
20467 cycling) will not occur.")
20469 (defvar org-tab-after-check-for-table-hook nil
20470 "Hook for functions to attach themselves to TAB.
20471 See `org-ctrl-c-ctrl-c-hook' for more information.
20472 This hook runs after it has been established that the cursor is not in a
20473 table, but before checking if the cursor is in a headline or if global cycling
20474 should be done.
20475 If any function in this hook returns t, not other actions like visibility
20476 cycling will be done.")
20478 (defvar org-tab-after-check-for-cycling-hook nil
20479 "Hook for functions to attach themselves to TAB.
20480 See `org-ctrl-c-ctrl-c-hook' for more information.
20481 This hook runs after it has been established that not table field motion and
20482 not visibility should be done because of current context. This is probably
20483 the place where a package like yasnippets can hook in.")
20485 (defvar org-tab-before-tab-emulation-hook nil
20486 "Hook for functions to attach themselves to TAB.
20487 See `org-ctrl-c-ctrl-c-hook' for more information.
20488 This hook runs after every other options for TAB have been exhausted, but
20489 before indentation and \t insertion takes place.")
20491 (defvar org-metaleft-hook nil
20492 "Hook for functions attaching themselves to `M-left'.
20493 See `org-ctrl-c-ctrl-c-hook' for more information.")
20494 (defvar org-metaright-hook nil
20495 "Hook for functions attaching themselves to `M-right'.
20496 See `org-ctrl-c-ctrl-c-hook' for more information.")
20497 (defvar org-metaup-hook nil
20498 "Hook for functions attaching themselves to `M-up'.
20499 See `org-ctrl-c-ctrl-c-hook' for more information.")
20500 (defvar org-metadown-hook nil
20501 "Hook for functions attaching themselves to `M-down'.
20502 See `org-ctrl-c-ctrl-c-hook' for more information.")
20503 (defvar org-shiftmetaleft-hook nil
20504 "Hook for functions attaching themselves to `M-S-left'.
20505 See `org-ctrl-c-ctrl-c-hook' for more information.")
20506 (defvar org-shiftmetaright-hook nil
20507 "Hook for functions attaching themselves to `M-S-right'.
20508 See `org-ctrl-c-ctrl-c-hook' for more information.")
20509 (defvar org-shiftmetaup-hook nil
20510 "Hook for functions attaching themselves to `M-S-up'.
20511 See `org-ctrl-c-ctrl-c-hook' for more information.")
20512 (defvar org-shiftmetadown-hook nil
20513 "Hook for functions attaching themselves to `M-S-down'.
20514 See `org-ctrl-c-ctrl-c-hook' for more information.")
20515 (defvar org-metareturn-hook nil
20516 "Hook for functions attaching themselves to `M-RET'.
20517 See `org-ctrl-c-ctrl-c-hook' for more information.")
20518 (defvar org-shiftup-hook nil
20519 "Hook for functions attaching themselves to `S-up'.
20520 See `org-ctrl-c-ctrl-c-hook' for more information.")
20521 (defvar org-shiftup-final-hook nil
20522 "Hook for functions attaching themselves to `S-up'.
20523 This one runs after all other options except shift-select have been excluded.
20524 See `org-ctrl-c-ctrl-c-hook' for more information.")
20525 (defvar org-shiftdown-hook nil
20526 "Hook for functions attaching themselves to `S-down'.
20527 See `org-ctrl-c-ctrl-c-hook' for more information.")
20528 (defvar org-shiftdown-final-hook nil
20529 "Hook for functions attaching themselves to `S-down'.
20530 This one runs after all other options except shift-select have been excluded.
20531 See `org-ctrl-c-ctrl-c-hook' for more information.")
20532 (defvar org-shiftleft-hook nil
20533 "Hook for functions attaching themselves to `S-left'.
20534 See `org-ctrl-c-ctrl-c-hook' for more information.")
20535 (defvar org-shiftleft-final-hook nil
20536 "Hook for functions attaching themselves to `S-left'.
20537 This one runs after all other options except shift-select have been excluded.
20538 See `org-ctrl-c-ctrl-c-hook' for more information.")
20539 (defvar org-shiftright-hook nil
20540 "Hook for functions attaching themselves to `S-right'.
20541 See `org-ctrl-c-ctrl-c-hook' for more information.")
20542 (defvar org-shiftright-final-hook nil
20543 "Hook for functions attaching themselves to `S-right'.
20544 This one runs after all other options except shift-select have been excluded.
20545 See `org-ctrl-c-ctrl-c-hook' for more information.")
20547 (defun org-modifier-cursor-error ()
20548 "Throw an error, a modified cursor command was applied in wrong context."
20549 (user-error "This command is active in special context like tables, headlines or items"))
20551 (defun org-shiftselect-error ()
20552 "Throw an error because Shift-Cursor command was applied in wrong context."
20553 (if (and (boundp 'shift-select-mode) shift-select-mode)
20554 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20555 (user-error "This command works only in special context like headlines or timestamps")))
20557 (defun org-call-for-shift-select (cmd)
20558 (let ((this-command-keys-shift-translated t))
20559 (call-interactively cmd)))
20561 (defun org-shifttab (&optional arg)
20562 "Global visibility cycling or move to previous table field.
20563 Call `org-table-previous-field' within a table.
20564 When ARG is nil, cycle globally through visibility states.
20565 When ARG is a numeric prefix, show contents of this level."
20566 (interactive "P")
20567 (cond
20568 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20569 ((integerp arg)
20570 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20571 (message "Content view to level: %d" arg)
20572 (org-content (prefix-numeric-value arg2))
20573 (org-cycle-show-empty-lines t)
20574 (setq org-cycle-global-status 'overview)))
20575 (t (call-interactively 'org-global-cycle))))
20577 (defun org-shiftmetaleft ()
20578 "Promote subtree or delete table column.
20579 Calls `org-promote-subtree', `org-outdent-item-tree', or
20580 `org-table-delete-column', depending on context. See the
20581 individual commands for more information."
20582 (interactive)
20583 (cond
20584 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20585 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20586 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20587 ((if (not (org-region-active-p)) (org-at-item-p)
20588 (save-excursion (goto-char (region-beginning))
20589 (org-at-item-p)))
20590 (call-interactively 'org-outdent-item-tree))
20591 (t (org-modifier-cursor-error))))
20593 (defun org-shiftmetaright ()
20594 "Demote subtree or insert table column.
20595 Calls `org-demote-subtree', `org-indent-item-tree', or
20596 `org-table-insert-column', depending on context. See the
20597 individual commands for more information."
20598 (interactive)
20599 (cond
20600 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20601 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20602 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20603 ((if (not (org-region-active-p)) (org-at-item-p)
20604 (save-excursion (goto-char (region-beginning))
20605 (org-at-item-p)))
20606 (call-interactively 'org-indent-item-tree))
20607 (t (org-modifier-cursor-error))))
20609 (defun org-shiftmetaup (&optional _arg)
20610 "Drag the line at point up.
20611 In a table, kill the current row.
20612 On a clock timestamp, update the value of the timestamp like `S-<up>'
20613 but also adjust the previous clocked item in the clock history.
20614 Everywhere else, drag the line at point up."
20615 (interactive "P")
20616 (cond
20617 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20618 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20619 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20620 (call-interactively 'org-timestamp-up)))
20621 (t (call-interactively 'org-drag-line-backward))))
20623 (defun org-shiftmetadown (&optional _arg)
20624 "Drag the line at point down.
20625 In a table, insert an empty row at the current line.
20626 On a clock timestamp, update the value of the timestamp like `S-<down>'
20627 but also adjust the previous clocked item in the clock history.
20628 Everywhere else, drag the line at point down."
20629 (interactive "P")
20630 (cond
20631 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20632 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20633 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20634 (call-interactively 'org-timestamp-down)))
20635 (t (call-interactively 'org-drag-line-forward))))
20637 (defsubst org-hidden-tree-error ()
20638 (user-error
20639 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20641 (defun org-metaleft (&optional _arg)
20642 "Promote heading, list item at point or move table column left.
20644 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20645 depending on context. With no specific context, calls the Emacs
20646 default `backward-word'. See the individual commands for more
20647 information.
20649 This function runs the hook `org-metaleft-hook' as a first step,
20650 and returns at first non-nil value."
20651 (interactive "P")
20652 (cond
20653 ((run-hook-with-args-until-success 'org-metaleft-hook))
20654 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20655 ((org-with-limited-levels
20656 (or (org-at-heading-p)
20657 (and (org-region-active-p)
20658 (save-excursion
20659 (goto-char (region-beginning))
20660 (org-at-heading-p)))))
20661 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20662 (call-interactively 'org-do-promote))
20663 ;; At an inline task.
20664 ((org-at-heading-p)
20665 (call-interactively 'org-inlinetask-promote))
20666 ((or (org-at-item-p)
20667 (and (org-region-active-p)
20668 (save-excursion
20669 (goto-char (region-beginning))
20670 (org-at-item-p))))
20671 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20672 (call-interactively 'org-outdent-item))
20673 (t (call-interactively 'backward-word))))
20675 (defun org-metaright (&optional _arg)
20676 "Demote heading, list item at point or move table column right.
20678 In front of a drawer or a block keyword, indent it correctly.
20680 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20681 `org-indent-drawer' or `org-indent-block' depending on context.
20682 With no specific context, calls the Emacs default `forward-word'.
20683 See the individual commands for more information.
20685 This function runs the hook `org-metaright-hook' as a first step,
20686 and returns at first non-nil value."
20687 (interactive "P")
20688 (cond
20689 ((run-hook-with-args-until-success 'org-metaright-hook))
20690 ((org-at-table-p) (call-interactively 'org-table-move-column))
20691 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20692 ((org-at-block-p) (call-interactively 'org-indent-block))
20693 ((org-with-limited-levels
20694 (or (org-at-heading-p)
20695 (and (org-region-active-p)
20696 (save-excursion
20697 (goto-char (region-beginning))
20698 (org-at-heading-p)))))
20699 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20700 (call-interactively 'org-do-demote))
20701 ;; At an inline task.
20702 ((org-at-heading-p)
20703 (call-interactively 'org-inlinetask-demote))
20704 ((or (org-at-item-p)
20705 (and (org-region-active-p)
20706 (save-excursion
20707 (goto-char (region-beginning))
20708 (org-at-item-p))))
20709 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20710 (call-interactively 'org-indent-item))
20711 (t (call-interactively 'forward-word))))
20713 (defun org-check-for-hidden (what)
20714 "Check if there are hidden headlines/items in the current visual line.
20715 WHAT can be either `headlines' or `items'. If the current line is
20716 an outline or item heading and it has a folded subtree below it,
20717 this function returns t, nil otherwise."
20718 (let ((re (cond
20719 ((eq what 'headlines) org-outline-regexp-bol)
20720 ((eq what 'items) (org-item-beginning-re))
20721 (t (error "This should not happen"))))
20722 beg end)
20723 (save-excursion
20724 (catch 'exit
20725 (unless (org-region-active-p)
20726 (setq beg (point-at-bol))
20727 (beginning-of-line 2)
20728 (while (and (not (eobp)) ;; this is like `next-line'
20729 (get-char-property (1- (point)) 'invisible))
20730 (beginning-of-line 2))
20731 (setq end (point))
20732 (goto-char beg)
20733 (goto-char (point-at-eol))
20734 (setq end (max end (point)))
20735 (while (re-search-forward re end t)
20736 (when (get-char-property (match-beginning 0) 'invisible)
20737 (throw 'exit t))))
20738 nil))))
20740 (defun org-metaup (&optional _arg)
20741 "Move subtree up or move table row up.
20742 Calls `org-move-subtree-up' or `org-table-move-row' or
20743 `org-move-item-up', depending on context. See the individual commands
20744 for more information."
20745 (interactive "P")
20746 (cond
20747 ((run-hook-with-args-until-success 'org-metaup-hook))
20748 ((org-region-active-p)
20749 (let* ((a (min (region-beginning) (region-end)))
20750 (b (1- (max (region-beginning) (region-end))))
20751 (c (save-excursion (goto-char a)
20752 (move-beginning-of-line 0)))
20753 (d (save-excursion (goto-char a)
20754 (move-end-of-line 0) (point))))
20755 (transpose-regions a b c d)
20756 (goto-char c)))
20757 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20758 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20759 ((org-at-item-p) (call-interactively 'org-move-item-up))
20760 (t (org-drag-element-backward))))
20762 (defun org-metadown (&optional _arg)
20763 "Move subtree down or move table row down.
20764 Calls `org-move-subtree-down' or `org-table-move-row' or
20765 `org-move-item-down', depending on context. See the individual
20766 commands for more information."
20767 (interactive "P")
20768 (cond
20769 ((run-hook-with-args-until-success 'org-metadown-hook))
20770 ((org-region-active-p)
20771 (let* ((a (min (region-beginning) (region-end)))
20772 (b (max (region-beginning) (region-end)))
20773 (c (save-excursion (goto-char b)
20774 (move-beginning-of-line 1)))
20775 (d (save-excursion (goto-char b)
20776 (move-end-of-line 1) (1+ (point)))))
20777 (transpose-regions a b c d)
20778 (goto-char d)))
20779 ((org-at-table-p) (call-interactively 'org-table-move-row))
20780 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20781 ((org-at-item-p) (call-interactively 'org-move-item-down))
20782 (t (org-drag-element-forward))))
20784 (defun org-shiftup (&optional arg)
20785 "Increase item in timestamp or increase priority of current headline.
20786 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20787 depending on context. See the individual commands for more information."
20788 (interactive "P")
20789 (cond
20790 ((run-hook-with-args-until-success 'org-shiftup-hook))
20791 ((and org-support-shift-select (org-region-active-p))
20792 (org-call-for-shift-select 'previous-line))
20793 ((org-at-timestamp-p t)
20794 (call-interactively (if org-edit-timestamp-down-means-later
20795 'org-timestamp-down 'org-timestamp-up)))
20796 ((and (not (eq org-support-shift-select 'always))
20797 org-enable-priority-commands
20798 (org-at-heading-p))
20799 (call-interactively 'org-priority-up))
20800 ((and (not org-support-shift-select) (org-at-item-p))
20801 (call-interactively 'org-previous-item))
20802 ((org-clocktable-try-shift 'up arg))
20803 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20804 (org-support-shift-select
20805 (org-call-for-shift-select 'previous-line))
20806 (t (org-shiftselect-error))))
20808 (defun org-shiftdown (&optional arg)
20809 "Decrease item in timestamp or decrease priority of current headline.
20810 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20811 depending on context. See the individual commands for more information."
20812 (interactive "P")
20813 (cond
20814 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20815 ((and org-support-shift-select (org-region-active-p))
20816 (org-call-for-shift-select 'next-line))
20817 ((org-at-timestamp-p t)
20818 (call-interactively (if org-edit-timestamp-down-means-later
20819 'org-timestamp-up 'org-timestamp-down)))
20820 ((and (not (eq org-support-shift-select 'always))
20821 org-enable-priority-commands
20822 (org-at-heading-p))
20823 (call-interactively 'org-priority-down))
20824 ((and (not org-support-shift-select) (org-at-item-p))
20825 (call-interactively 'org-next-item))
20826 ((org-clocktable-try-shift 'down arg))
20827 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20828 (org-support-shift-select
20829 (org-call-for-shift-select 'next-line))
20830 (t (org-shiftselect-error))))
20832 (defun org-shiftright (&optional arg)
20833 "Cycle the thing at point or in the current line, depending on context.
20834 Depending on context, this does one of the following:
20836 - switch a timestamp at point one day into the future
20837 - on a headline, switch to the next TODO keyword.
20838 - on an item, switch entire list to the next bullet type
20839 - on a property line, switch to the next allowed value
20840 - on a clocktable definition line, move time block into the future"
20841 (interactive "P")
20842 (cond
20843 ((run-hook-with-args-until-success 'org-shiftright-hook))
20844 ((and org-support-shift-select (org-region-active-p))
20845 (org-call-for-shift-select 'forward-char))
20846 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20847 ((and (not (eq org-support-shift-select 'always))
20848 (org-at-heading-p))
20849 (let ((org-inhibit-logging
20850 (not org-treat-S-cursor-todo-selection-as-state-change))
20851 (org-inhibit-blocking
20852 (not org-treat-S-cursor-todo-selection-as-state-change)))
20853 (org-call-with-arg 'org-todo 'right)))
20854 ((or (and org-support-shift-select
20855 (not (eq org-support-shift-select 'always))
20856 (org-at-item-bullet-p))
20857 (and (not org-support-shift-select) (org-at-item-p)))
20858 (org-call-with-arg 'org-cycle-list-bullet nil))
20859 ((and (not (eq org-support-shift-select 'always))
20860 (org-at-property-p))
20861 (call-interactively 'org-property-next-allowed-value))
20862 ((org-clocktable-try-shift 'right arg))
20863 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20864 (org-support-shift-select
20865 (org-call-for-shift-select 'forward-char))
20866 (t (org-shiftselect-error))))
20868 (defun org-shiftleft (&optional arg)
20869 "Cycle the thing at point or in the current line, depending on context.
20870 Depending on context, this does one of the following:
20872 - switch a timestamp at point one day into the past
20873 - on a headline, switch to the previous TODO keyword.
20874 - on an item, switch entire list to the previous bullet type
20875 - on a property line, switch to the previous allowed value
20876 - on a clocktable definition line, move time block into the past"
20877 (interactive "P")
20878 (cond
20879 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20880 ((and org-support-shift-select (org-region-active-p))
20881 (org-call-for-shift-select 'backward-char))
20882 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20883 ((and (not (eq org-support-shift-select 'always))
20884 (org-at-heading-p))
20885 (let ((org-inhibit-logging
20886 (not org-treat-S-cursor-todo-selection-as-state-change))
20887 (org-inhibit-blocking
20888 (not org-treat-S-cursor-todo-selection-as-state-change)))
20889 (org-call-with-arg 'org-todo 'left)))
20890 ((or (and org-support-shift-select
20891 (not (eq org-support-shift-select 'always))
20892 (org-at-item-bullet-p))
20893 (and (not org-support-shift-select) (org-at-item-p)))
20894 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20895 ((and (not (eq org-support-shift-select 'always))
20896 (org-at-property-p))
20897 (call-interactively 'org-property-previous-allowed-value))
20898 ((org-clocktable-try-shift 'left arg))
20899 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20900 (org-support-shift-select
20901 (org-call-for-shift-select 'backward-char))
20902 (t (org-shiftselect-error))))
20904 (defun org-shiftcontrolright ()
20905 "Switch to next TODO set."
20906 (interactive)
20907 (cond
20908 ((and org-support-shift-select (org-region-active-p))
20909 (org-call-for-shift-select 'forward-word))
20910 ((and (not (eq org-support-shift-select 'always))
20911 (org-at-heading-p))
20912 (org-call-with-arg 'org-todo 'nextset))
20913 (org-support-shift-select
20914 (org-call-for-shift-select 'forward-word))
20915 (t (org-shiftselect-error))))
20917 (defun org-shiftcontrolleft ()
20918 "Switch to previous TODO set."
20919 (interactive)
20920 (cond
20921 ((and org-support-shift-select (org-region-active-p))
20922 (org-call-for-shift-select 'backward-word))
20923 ((and (not (eq org-support-shift-select 'always))
20924 (org-at-heading-p))
20925 (org-call-with-arg 'org-todo 'previousset))
20926 (org-support-shift-select
20927 (org-call-for-shift-select 'backward-word))
20928 (t (org-shiftselect-error))))
20930 (defun org-shiftcontrolup (&optional n)
20931 "Change timestamps synchronously up in CLOCK log lines.
20932 Optional argument N tells to change by that many units."
20933 (interactive "P")
20934 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20935 (let (org-support-shift-select)
20936 (org-clock-timestamps-up n))
20937 (user-error "Not at a clock log")))
20939 (defun org-shiftcontroldown (&optional n)
20940 "Change timestamps synchronously down in CLOCK log lines.
20941 Optional argument N tells to change by that many units."
20942 (interactive "P")
20943 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20944 (let (org-support-shift-select)
20945 (org-clock-timestamps-down n))
20946 (user-error "Not at a clock log")))
20948 (defun org-increase-number-at-point (&optional inc)
20949 "Increment the number at point.
20950 With an optional prefix numeric argument INC, increment using
20951 this numeric value."
20952 (interactive "p")
20953 (if (not (number-at-point))
20954 (user-error "Not on a number")
20955 (unless inc (setq inc 1))
20956 (let ((pos (point))
20957 (beg (skip-chars-backward "-+^/*0-9eE."))
20958 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20959 (setq nap (buffer-substring-no-properties
20960 (+ pos beg) (+ pos beg end)))
20961 (delete-region (+ pos beg) (+ pos beg end))
20962 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20963 (when (org-at-table-p)
20964 (org-table-align)
20965 (org-table-end-of-field 1))))
20967 (defun org-decrease-number-at-point (&optional inc)
20968 "Decrement the number at point.
20969 With an optional prefix numeric argument INC, decrement using
20970 this numeric value."
20971 (interactive "p")
20972 (org-increase-number-at-point (- (or inc 1))))
20974 (defun org-ctrl-c-ret ()
20975 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20976 (interactive)
20977 (cond
20978 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20979 (t (call-interactively 'org-insert-heading))))
20981 (defun org-find-visible ()
20982 (let ((s (point)))
20983 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20984 (get-char-property s 'invisible)))
20986 (defun org-find-invisible ()
20987 (let ((s (point)))
20988 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20989 (not (get-char-property s 'invisible))))
20992 (defun org-copy-visible (beg end)
20993 "Copy the visible parts of the region."
20994 (interactive "r")
20995 (let (snippets s)
20996 (save-excursion
20997 (save-restriction
20998 (narrow-to-region beg end)
20999 (setq s (goto-char (point-min)))
21000 (while (not (= (point) (point-max)))
21001 (goto-char (org-find-invisible))
21002 (push (buffer-substring s (point)) snippets)
21003 (setq s (goto-char (org-find-visible))))))
21004 (kill-new (apply 'concat (nreverse snippets)))))
21006 (defun org-copy-special ()
21007 "Copy region in table or copy current subtree.
21008 Calls `org-table-copy-region' or `org-copy-subtree', depending on
21009 context. See the individual commands for more information."
21010 (interactive)
21011 (call-interactively
21012 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
21014 (defun org-cut-special ()
21015 "Cut region in table or cut current subtree.
21016 Calls `org-table-cut-region' or `org-cut-subtree', depending on
21017 context. See the individual commands for more information."
21018 (interactive)
21019 (call-interactively
21020 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
21022 (defun org-paste-special (arg)
21023 "Paste rectangular region into table, or past subtree relative to level.
21024 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
21025 See the individual commands for more information."
21026 (interactive "P")
21027 (if (org-at-table-p)
21028 (org-table-paste-rectangle)
21029 (org-paste-subtree arg)))
21031 (defun org-edit-special (&optional arg)
21032 "Call a special editor for the element at point.
21033 When at a table, call the formula editor with `org-table-edit-formulas'.
21034 When in a source code block, call `org-edit-src-code'.
21035 When in a fixed-width region, call `org-edit-fixed-width-region'.
21036 When in an export block, call `org-edit-export-block'.
21037 When at an #+INCLUDE keyword, visit the included file.
21038 When at a footnote reference, call `org-edit-footnote-reference'
21039 On a link, call `ffap' to visit the link at point.
21040 Otherwise, return a user error."
21041 (interactive "P")
21042 (let ((element (org-element-at-point)))
21043 (barf-if-buffer-read-only)
21044 (pcase (org-element-type element)
21045 (`src-block
21046 (if (not arg) (org-edit-src-code)
21047 (let* ((info (org-babel-get-src-block-info))
21048 (lang (nth 0 info))
21049 (params (nth 2 info))
21050 (session (cdr (assq :session params))))
21051 (if (not session) (org-edit-src-code)
21052 ;; At a src-block with a session and function called with
21053 ;; an ARG: switch to the buffer related to the inferior
21054 ;; process.
21055 (switch-to-buffer
21056 (funcall (intern (concat "org-babel-prep-session:" lang))
21057 session params))))))
21058 (`keyword
21059 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
21060 (org-open-link-from-string
21061 (format "[[%s]]"
21062 (expand-file-name
21063 (let ((value (org-element-property :value element)))
21064 (cond ((not (org-string-nw-p value))
21065 (user-error "No file to edit"))
21066 ((string-match "\\`\"\\(.*?\\)\"" value)
21067 (match-string 1 value))
21068 ((string-match "\\`[^ \t\"]\\S-*" value)
21069 (match-string 0 value))
21070 (t (user-error "No valid file specified")))))))
21071 (user-error "No special environment to edit here")))
21072 (`table
21073 (if (eq (org-element-property :type element) 'table.el)
21074 (org-edit-table.el)
21075 (call-interactively 'org-table-edit-formulas)))
21076 ;; Only Org tables contain `table-row' type elements.
21077 (`table-row (call-interactively 'org-table-edit-formulas))
21078 (`example-block (org-edit-src-code))
21079 (`export-block (org-edit-export-block))
21080 (`fixed-width (org-edit-fixed-width-region))
21082 ;; No notable element at point. Though, we may be at a link or
21083 ;; a footnote reference, which are objects. Thus, scan deeper.
21084 (let ((context (org-element-context element)))
21085 (pcase (org-element-type context)
21086 (`footnote-reference (org-edit-footnote-reference))
21087 (`inline-src-block (org-edit-inline-src-code))
21088 (`link (call-interactively #'ffap))
21089 (_ (user-error "No special environment to edit here"))))))))
21091 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21092 (defun org-ctrl-c-ctrl-c (&optional arg)
21093 "Set tags in headline, or update according to changed information at point.
21095 This command does many different things, depending on context:
21097 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21098 this is what we do.
21100 - If the cursor is on a statistics cookie, update it.
21102 - If the cursor is in a headline, prompt for tags and insert them
21103 into the current line, aligned to `org-tags-column'. When called
21104 with prefix arg, realign all tags in the current buffer.
21106 - If the cursor is in one of the special #+KEYWORD lines, this
21107 triggers scanning the buffer for these lines and updating the
21108 information.
21110 - If the cursor is inside a table, realign the table. This command
21111 works even if the automatic table editor has been turned off.
21113 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21114 the entire table.
21116 - If the cursor is at a footnote reference or definition, jump to
21117 the corresponding definition or references, respectively.
21119 - If the cursor is a the beginning of a dynamic block, update it.
21121 - If the current buffer is a capture buffer, close note and file it.
21123 - If the cursor is on a <<<target>>>, update radio targets and
21124 corresponding links in this buffer.
21126 - If the cursor is on a numbered item in a plain list, renumber the
21127 ordered list.
21129 - If the cursor is on a checkbox, toggle it.
21131 - If the cursor is on a code block, evaluate it. The variable
21132 `org-confirm-babel-evaluate' can be used to control prompting
21133 before code block evaluation, by default every code block
21134 evaluation requires confirmation. Code block evaluation can be
21135 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21136 (interactive "P")
21137 (cond
21138 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
21139 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21140 (org-remove-occur-highlights)
21141 (message "Temporary highlights/overlays removed from current buffer"))
21142 ((and (local-variable-p 'org-finish-function)
21143 (fboundp org-finish-function))
21144 (funcall org-finish-function))
21145 ((org-babel-hash-at-point))
21146 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21148 (let* ((context
21149 (org-element-lineage
21150 (org-element-context)
21151 ;; Limit to supported contexts.
21152 '(babel-call clock dynamic-block footnote-definition
21153 footnote-reference inline-babel-call inline-src-block
21154 inlinetask item keyword node-property paragraph
21155 plain-list property-drawer radio-target src-block
21156 statistics-cookie table table-cell table-row
21157 timestamp)
21159 (type (org-element-type context)))
21160 ;; For convenience: at the first line of a paragraph on the same
21161 ;; line as an item, apply function on that item instead.
21162 (when (eq type 'paragraph)
21163 (let ((parent (org-element-property :parent context)))
21164 (when (and (eq (org-element-type parent) 'item)
21165 (= (line-beginning-position)
21166 (org-element-property :begin parent)))
21167 (setq context parent)
21168 (setq type 'item))))
21169 ;; Act according to type of element or object at point.
21171 ;; Do nothing on a blank line, except if it is contained in
21172 ;; a src block. Hence, we first check if point is in such
21173 ;; a block and then if it is at a blank line.
21174 (pcase type
21175 ((or `inline-src-block `src-block)
21176 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
21177 (org-babel-eval-wipe-error-buffer)
21178 (org-babel-execute-src-block
21179 current-prefix-arg (org-babel-get-src-block-info nil context))))
21180 ((guard (org-match-line "[ \t]*$"))
21181 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21182 (user-error
21183 (substitute-command-keys
21184 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
21185 ((or `babel-call `inline-babel-call)
21186 (let ((info (org-babel-lob-get-info context)))
21187 (when info (org-babel-execute-src-block nil info))))
21188 (`clock (org-clock-update-time-maybe))
21189 (`dynamic-block
21190 (save-excursion
21191 (goto-char (org-element-property :post-affiliated context))
21192 (org-update-dblock)))
21193 (`footnote-definition
21194 (goto-char (org-element-property :post-affiliated context))
21195 (call-interactively 'org-footnote-action))
21196 (`footnote-reference (call-interactively #'org-footnote-action))
21197 ((or `headline `inlinetask)
21198 (save-excursion (goto-char (org-element-property :begin context))
21199 (call-interactively #'org-set-tags)))
21200 (`item
21201 ;; At an item: `C-u C-u' sets checkbox to "[-]"
21202 ;; unconditionally, whereas `C-u' will toggle its presence.
21203 ;; Without a universal argument, if the item has a checkbox,
21204 ;; toggle it. Otherwise repair the list.
21205 (let* ((box (org-element-property :checkbox context))
21206 (struct (org-element-property :structure context))
21207 (old-struct (copy-tree struct))
21208 (parents (org-list-parents-alist struct))
21209 (prevs (org-list-prevs-alist struct))
21210 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21211 (org-list-set-checkbox
21212 (org-element-property :begin context) struct
21213 (cond ((equal arg '(16)) "[-]")
21214 ((and (not box) (equal arg '(4))) "[ ]")
21215 ((or (not box) (equal arg '(4))) nil)
21216 ((eq box 'on) "[ ]")
21217 (t "[X]")))
21218 ;; Mimic `org-list-write-struct' but with grabbing a return
21219 ;; value from `org-list-struct-fix-box'.
21220 (org-list-struct-fix-ind struct parents 2)
21221 (org-list-struct-fix-item-end struct)
21222 (org-list-struct-fix-bul struct prevs)
21223 (org-list-struct-fix-ind struct parents)
21224 (let ((block-item
21225 (org-list-struct-fix-box struct parents prevs orderedp)))
21226 (if (and box (equal struct old-struct))
21227 (if (equal arg '(16))
21228 (message "Checkboxes already reset")
21229 (user-error "Cannot toggle this checkbox: %s"
21230 (if (eq box 'on)
21231 "all subitems checked"
21232 "unchecked subitems")))
21233 (org-list-struct-apply-struct struct old-struct)
21234 (org-update-checkbox-count-maybe))
21235 (when block-item
21236 (message "Checkboxes were removed due to empty box at line %d"
21237 (org-current-line block-item))))))
21238 (`keyword
21239 (let ((org-inhibit-startup-visibility-stuff t)
21240 (org-startup-align-all-tables nil))
21241 (when (boundp 'org-table-coordinate-overlays)
21242 (mapc #'delete-overlay org-table-coordinate-overlays)
21243 (setq org-table-coordinate-overlays nil))
21244 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21245 (message "Local setup has been refreshed"))
21246 (`plain-list
21247 ;; At a plain list, with a double C-u argument, set
21248 ;; checkboxes of each item to "[-]", whereas a single one
21249 ;; will toggle their presence according to the state of the
21250 ;; first item in the list. Without an argument, repair the
21251 ;; list.
21252 (let* ((begin (org-element-property :contents-begin context))
21253 (beginm (move-marker (make-marker) begin))
21254 (struct (org-element-property :structure context))
21255 (old-struct (copy-tree struct))
21256 (first-box (save-excursion
21257 (goto-char begin)
21258 (looking-at org-list-full-item-re)
21259 (match-string-no-properties 3)))
21260 (new-box (cond ((equal arg '(16)) "[-]")
21261 ((equal arg '(4)) (unless first-box "[ ]"))
21262 ((equal first-box "[X]") "[ ]")
21263 (t "[X]"))))
21264 (cond
21265 (arg
21266 (dolist (pos
21267 (org-list-get-all-items
21268 begin struct (org-list-prevs-alist struct)))
21269 (org-list-set-checkbox pos struct new-box)))
21270 ((and first-box (eq (point) begin))
21271 ;; For convenience, when point is at bol on the first
21272 ;; item of the list and no argument is provided, simply
21273 ;; toggle checkbox of that item, if any.
21274 (org-list-set-checkbox begin struct new-box)))
21275 (org-list-write-struct
21276 struct (org-list-parents-alist struct) old-struct)
21277 (org-update-checkbox-count-maybe)
21278 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21279 ((or `property-drawer `node-property)
21280 (call-interactively #'org-property-action))
21281 (`radio-target
21282 (call-interactively #'org-update-radio-target-regexp))
21283 (`statistics-cookie
21284 (call-interactively #'org-update-statistics-cookies))
21285 ((or `table `table-cell `table-row)
21286 ;; At a table, recalculate every field and align it. Also
21287 ;; send the table if necessary. If the table has
21288 ;; a `table.el' type, just give up. At a table row or cell,
21289 ;; maybe recalculate line but always align table.
21290 (if (eq (org-element-property :type context) 'table.el)
21291 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21292 Use `\\[org-edit-special]' to edit table.el tables"))
21293 (let ((org-enable-table-editor t))
21294 (if (or (eq type 'table)
21295 ;; Check if point is at a TBLFM line.
21296 (and (eq type 'table-row)
21297 (= (point) (org-element-property :end context))))
21298 (save-excursion
21299 (if (org-at-TBLFM-p)
21300 (progn (require 'org-table)
21301 (org-table-calc-current-TBLFM))
21302 (goto-char (org-element-property :contents-begin context))
21303 (org-call-with-arg 'org-table-recalculate (or arg t))
21304 (orgtbl-send-table 'maybe)))
21305 (org-table-maybe-eval-formula)
21306 (cond (arg (call-interactively #'org-table-recalculate))
21307 ((org-table-maybe-recalculate-line))
21308 (t (org-table-align)))))))
21309 (`timestamp (org-timestamp-change 0 'day))
21310 ((and `nil (guard (org-at-heading-p)))
21311 ;; When point is on an unsupported object type, we can miss
21312 ;; the fact that it also is at a heading. Handle it here.
21313 (call-interactively #'org-set-tags))
21314 ((guard
21315 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
21317 (user-error
21318 (substitute-command-keys
21319 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
21321 (defun org-mode-restart ()
21322 (interactive)
21323 (let ((indent-status (bound-and-true-p org-indent-mode)))
21324 (funcall major-mode)
21325 (hack-local-variables)
21326 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21327 (org-indent-mode -1)))
21328 (message "%s restarted" major-mode))
21330 (defun org-kill-note-or-show-branches ()
21331 "Abort storing current note, or call `outline-show-branches'."
21332 (interactive)
21333 (if (not org-finish-function)
21334 (progn
21335 (outline-hide-subtree)
21336 (call-interactively 'outline-show-branches))
21337 (let ((org-note-abort t))
21338 (funcall org-finish-function))))
21340 (defun org-delete-indentation (&optional arg)
21341 "Join current line to previous and fix whitespace at join.
21343 If previous line is a headline add to headline title. Otherwise
21344 the function calls `delete-indentation'.
21346 With a non-nil optional argument, join it to the following one."
21347 (interactive "*P")
21348 (if (save-excursion
21349 (beginning-of-line (if arg 1 0))
21350 (let ((case-fold-search nil))
21351 (looking-at org-complex-heading-regexp)))
21352 ;; At headline.
21353 (let ((tags-column (when (match-beginning 5)
21354 (save-excursion (goto-char (match-beginning 5))
21355 (current-column))))
21356 (string (concat " " (progn (when arg (forward-line 1))
21357 (org-trim (delete-and-extract-region
21358 (line-beginning-position)
21359 (line-end-position)))))))
21360 (unless (bobp) (delete-region (point) (1- (point))))
21361 (goto-char (or (match-end 4)
21362 (match-beginning 5)
21363 (match-end 0)))
21364 (skip-chars-backward " \t")
21365 (save-excursion (insert string))
21366 ;; Adjust alignment of tags.
21367 (cond
21368 ((not tags-column)) ;no tags
21369 (org-auto-align-tags (org-set-tags nil t))
21370 (t (org--align-tags-here tags-column)))) ;preserve tags column
21371 (delete-indentation arg)))
21373 (defun org-open-line (n)
21374 "Insert a new row in tables, call `open-line' elsewhere.
21375 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21376 As a special case, when a document starts with a table, allow to
21377 call `open-line' on the very first character."
21378 (interactive "*p")
21379 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21380 (org-table-insert-row)
21381 (open-line n)))
21383 (defun org-return (&optional indent)
21384 "Goto next table row or insert a newline.
21386 Calls `org-table-next-row' or `newline', depending on context.
21388 When optional INDENT argument is non-nil, call
21389 `newline-and-indent' instead of `newline'.
21391 When `org-return-follows-link' is non-nil and point is on
21392 a timestamp or a link, call `org-open-at-point'. However, it
21393 will not happen if point is in a table or on a \"dead\"
21394 object (e.g., within a comment). In these case, you need to use
21395 `org-open-at-point' directly."
21396 (interactive)
21397 (let ((context (if org-return-follows-link (org-element-context)
21398 (org-element-at-point))))
21399 (cond
21400 ;; In a table, call `org-table-next-row'.
21401 ((or (and (eq (org-element-type context) 'table)
21402 (>= (point) (org-element-property :contents-begin context))
21403 (< (point) (org-element-property :contents-end context)))
21404 (org-element-lineage context '(table-row table-cell) t))
21405 (org-table-justify-field-maybe)
21406 (call-interactively #'org-table-next-row))
21407 ;; On a link or a timestamp, call `org-open-at-point' if
21408 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21409 ;; locations, e.g., in a comment, as `org-open-at-point'.
21410 ((and org-return-follows-link
21411 (or (org-in-regexp org-ts-regexp-both nil t)
21412 (org-in-regexp org-tsr-regexp-both nil t)
21413 (org-in-regexp org-any-link-re nil t)))
21414 (call-interactively #'org-open-at-point))
21415 ;; Insert newline in heading, but preserve tags.
21416 ((and (not (bolp))
21417 (save-excursion (beginning-of-line)
21418 (let ((case-fold-search nil))
21419 (looking-at org-complex-heading-regexp))))
21420 ;; At headline. Split line. However, if point is on keyword,
21421 ;; priority cookie or tags, do not break any of them: add
21422 ;; a newline after the headline instead.
21423 (let ((tags-column (and (match-beginning 5)
21424 (save-excursion (goto-char (match-beginning 5))
21425 (current-column))))
21426 (string
21427 (when (and (match-end 4) (org-point-in-group (point) 4))
21428 (delete-and-extract-region (point) (match-end 4)))))
21429 ;; Adjust tag alignment.
21430 (cond
21431 ((not (and tags-column string)))
21432 (org-auto-align-tags (org-set-tags nil t))
21433 (t (org--align-tags-here tags-column))) ;preserve tags column
21434 (end-of-line)
21435 (org-show-entry)
21436 (if indent (newline-and-indent) (newline))
21437 (when string (save-excursion (insert (org-trim string))))))
21438 ;; In a list, make sure indenting keeps trailing text within.
21439 ((and indent
21440 (not (eolp))
21441 (org-element-lineage context '(item)))
21442 (let ((trailing-data
21443 (delete-and-extract-region (point) (line-end-position))))
21444 (newline-and-indent)
21445 (save-excursion (insert trailing-data))))
21446 (t (if indent (newline-and-indent) (newline))))))
21448 (defun org-return-indent ()
21449 "Goto next table row or insert a newline and indent.
21450 Calls `org-table-next-row' or `newline-and-indent', depending on
21451 context. See the individual commands for more information."
21452 (interactive)
21453 (org-return t))
21455 (defun org-ctrl-c-star ()
21456 "Compute table, or change heading status of lines.
21457 Calls `org-table-recalculate' or `org-toggle-heading',
21458 depending on context."
21459 (interactive)
21460 (cond
21461 ((org-at-table-p)
21462 (call-interactively 'org-table-recalculate))
21464 ;; Convert all lines in region to list items
21465 (call-interactively 'org-toggle-heading))))
21467 (defun org-ctrl-c-minus ()
21468 "Insert separator line in table or modify bullet status of line.
21469 Also turns a plain line or a region of lines into list items.
21470 Calls `org-table-insert-hline', `org-toggle-item', or
21471 `org-cycle-list-bullet', depending on context."
21472 (interactive)
21473 (cond
21474 ((org-at-table-p)
21475 (call-interactively 'org-table-insert-hline))
21476 ((org-region-active-p)
21477 (call-interactively 'org-toggle-item))
21478 ((org-in-item-p)
21479 (call-interactively 'org-cycle-list-bullet))
21481 (call-interactively 'org-toggle-item))))
21483 (defun org-toggle-heading (&optional nstars)
21484 "Convert headings to normal text, or items or text to headings.
21485 If there is no active region, only convert the current line.
21487 With a `\\[universal-argument]' prefix, convert the whole list at
21488 point into heading.
21490 In a region:
21492 - If the first non blank line is a headline, remove the stars
21493 from all headlines in the region.
21495 - If it is a normal line, turn each and every normal line (i.e.,
21496 not an heading or an item) in the region into headings. If you
21497 want to convert only the first line of this region, use one
21498 universal prefix argument.
21500 - If it is a plain list item, turn all plain list items into headings.
21502 When converting a line into a heading, the number of stars is chosen
21503 such that the lines become children of the current entry. However,
21504 when a numeric prefix argument is given, its value determines the
21505 number of stars to add."
21506 (interactive "P")
21507 (let ((skip-blanks
21508 (function
21509 ;; Return beginning of first non-blank line, starting from
21510 ;; line at POS.
21511 (lambda (pos)
21512 (save-excursion
21513 (goto-char pos)
21514 (while (org-at-comment-p) (forward-line))
21515 (skip-chars-forward " \r\t\n")
21516 (point-at-bol)))))
21517 beg end toggled)
21518 ;; Determine boundaries of changes. If a universal prefix has
21519 ;; been given, put the list in a region. If region ends at a bol,
21520 ;; do not consider the last line to be in the region.
21522 (when (and current-prefix-arg (org-at-item-p))
21523 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21524 (org-mark-element))
21526 (if (org-region-active-p)
21527 (setq beg (funcall skip-blanks (region-beginning))
21528 end (copy-marker (save-excursion
21529 (goto-char (region-end))
21530 (if (bolp) (point) (point-at-eol)))))
21531 (setq beg (funcall skip-blanks (point-at-bol))
21532 end (copy-marker (point-at-eol))))
21533 ;; Ensure inline tasks don't count as headings.
21534 (org-with-limited-levels
21535 (save-excursion
21536 (goto-char beg)
21537 (cond
21538 ;; Case 1. Started at an heading: de-star headings.
21539 ((org-at-heading-p)
21540 (while (< (point) end)
21541 (when (org-at-heading-p t)
21542 (looking-at org-outline-regexp) (replace-match "")
21543 (setq toggled t))
21544 (forward-line)))
21545 ;; Case 2. Started at an item: change items into headlines.
21546 ;; One star will be added by `org-list-to-subtree'.
21547 ((org-at-item-p)
21548 (while (< (point) end)
21549 (when (org-at-item-p)
21550 ;; Pay attention to cases when region ends before list.
21551 (let* ((struct (org-list-struct))
21552 (list-end
21553 (min (org-list-get-bottom-point struct) (1+ end))))
21554 (save-restriction
21555 (narrow-to-region (point) list-end)
21556 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21557 (setq toggled t))
21558 (forward-line)))
21559 ;; Case 3. Started at normal text: make every line an heading,
21560 ;; skipping headlines and items.
21561 (t (let* ((stars
21562 (make-string
21563 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21564 (add-stars
21565 (cond (nstars "") ; stars from prefix only
21566 ((equal stars "") "*") ; before first heading
21567 (org-odd-levels-only "**") ; inside heading, odd
21568 (t "*"))) ; inside heading, oddeven
21569 (rpl (concat stars add-stars " "))
21570 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21571 (while (< (point) (if (equal nstars '(4)) lend end))
21572 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21573 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21574 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21575 (forward-line)))))))
21576 (unless toggled (message "Cannot toggle heading from here"))))
21578 (defun org-meta-return (&optional _arg)
21579 "Insert a new heading or wrap a region in a table.
21580 Calls `org-insert-heading' or `org-table-wrap-region', depending
21581 on context. See the individual commands for more information."
21582 (interactive)
21583 (org-check-before-invisible-edit 'insert)
21584 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21585 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21586 #'org-insert-heading))))
21588 ;;; Menu entries
21590 (defsubst org-in-subtree-not-table-p ()
21591 "Are we in a subtree and not in a table?"
21592 (and (not (org-before-first-heading-p))
21593 (not (org-at-table-p))))
21595 ;; Define the Org mode menus
21596 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21597 '("Tbl"
21598 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21599 ["Next Field" org-cycle (org-at-table-p)]
21600 ["Previous Field" org-shifttab (org-at-table-p)]
21601 ["Next Row" org-return (org-at-table-p)]
21602 "--"
21603 ["Blank Field" org-table-blank-field (org-at-table-p)]
21604 ["Edit Field" org-table-edit-field (org-at-table-p)]
21605 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21606 "--"
21607 ("Column"
21608 ["Move Column Left" org-metaleft (org-at-table-p)]
21609 ["Move Column Right" org-metaright (org-at-table-p)]
21610 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21611 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21612 ("Row"
21613 ["Move Row Up" org-metaup (org-at-table-p)]
21614 ["Move Row Down" org-metadown (org-at-table-p)]
21615 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21616 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21617 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21618 "--"
21619 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21620 ("Rectangle"
21621 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21622 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21623 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21624 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21625 "--"
21626 ("Calculate"
21627 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21628 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21629 ["Edit Formulas" org-edit-special (org-at-table-p)]
21630 "--"
21631 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21632 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21633 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21634 "--"
21635 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21636 "--"
21637 ["Sum Column/Rectangle" org-table-sum
21638 (or (org-at-table-p) (org-region-active-p))]
21639 ["Which Column?" org-table-current-column (org-at-table-p)])
21640 ["Debug Formulas"
21641 org-table-toggle-formula-debugger
21642 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21643 ["Show Col/Row Numbers"
21644 org-table-toggle-coordinate-overlays
21645 :style toggle
21646 :selected (bound-and-true-p org-table-overlay-coordinates)]
21647 "--"
21648 ["Create" org-table-create (and (not (org-at-table-p))
21649 org-enable-table-editor)]
21650 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21651 ["Import from File" org-table-import (not (org-at-table-p))]
21652 ["Export to File" org-table-export (org-at-table-p)]
21653 "--"
21654 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21655 "--"
21656 ("Plot"
21657 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21658 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21660 (easy-menu-define org-org-menu org-mode-map "Org menu"
21661 '("Org"
21662 ("Show/Hide"
21663 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21664 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21665 ["Sparse Tree..." org-sparse-tree t]
21666 ["Reveal Context" org-reveal t]
21667 ["Show All" outline-show-all t]
21668 "--"
21669 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21670 "--"
21671 ["New Heading" org-insert-heading t]
21672 ("Navigate Headings"
21673 ["Up" outline-up-heading t]
21674 ["Next" outline-next-visible-heading t]
21675 ["Previous" outline-previous-visible-heading t]
21676 ["Next Same Level" outline-forward-same-level t]
21677 ["Previous Same Level" outline-backward-same-level t]
21678 "--"
21679 ["Jump" org-goto t])
21680 ("Edit Structure"
21681 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21682 "--"
21683 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21684 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21685 "--"
21686 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21687 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21688 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21689 "--"
21690 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21691 "--"
21692 ["Copy visible text" org-copy-visible t]
21693 "--"
21694 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21695 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21696 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21697 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21698 "--"
21699 ["Sort Region/Children" org-sort t]
21700 "--"
21701 ["Convert to odd levels" org-convert-to-odd-levels t]
21702 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21703 ("Editing"
21704 ["Emphasis..." org-emphasize t]
21705 ["Edit Source Example" org-edit-special t]
21706 "--"
21707 ["Footnote new/jump" org-footnote-action t]
21708 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21709 ("Archive"
21710 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21711 "--"
21712 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21713 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21714 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21716 "--"
21717 ("Hyperlinks"
21718 ["Store Link (Global)" org-store-link t]
21719 ["Find existing link to here" org-occur-link-in-agenda-files t]
21720 ["Insert Link" org-insert-link t]
21721 ["Follow Link" org-open-at-point t]
21722 "--"
21723 ["Next link" org-next-link t]
21724 ["Previous link" org-previous-link t]
21725 "--"
21726 ["Descriptive Links"
21727 org-toggle-link-display
21728 :style radio
21729 :selected org-descriptive-links
21731 ["Literal Links"
21732 org-toggle-link-display
21733 :style radio
21734 :selected (not org-descriptive-links)])
21735 "--"
21736 ("TODO Lists"
21737 ["TODO/DONE/-" org-todo t]
21738 ("Select keyword"
21739 ["Next keyword" org-shiftright (org-at-heading-p)]
21740 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21741 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21742 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21743 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21744 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21745 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21746 "--"
21747 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21748 :selected org-enforce-todo-dependencies :style toggle :active t]
21749 "Settings for tree at point"
21750 ["Do Children sequentially" org-toggle-ordered-property :style radio
21751 :selected (org-entry-get nil "ORDERED")
21752 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21753 ["Do Children parallel" org-toggle-ordered-property :style radio
21754 :selected (not (org-entry-get nil "ORDERED"))
21755 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21756 "--"
21757 ["Set Priority" org-priority t]
21758 ["Priority Up" org-shiftup t]
21759 ["Priority Down" org-shiftdown t]
21760 "--"
21761 ["Get news from all feeds" org-feed-update-all t]
21762 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21763 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21764 ("TAGS and Properties"
21765 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21766 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21767 "--"
21768 ["Set property" org-set-property (not (org-before-first-heading-p))]
21769 ["Column view of properties" org-columns t]
21770 ["Insert Column View DBlock" org-columns-insert-dblock t])
21771 ("Dates and Scheduling"
21772 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21773 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21774 ("Change Date"
21775 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21776 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21777 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21778 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21779 ["Compute Time Range" org-evaluate-time-range t]
21780 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21781 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21782 "--"
21783 ["Custom time format" org-toggle-time-stamp-overlays
21784 :style radio :selected org-display-custom-times]
21785 "--"
21786 ["Goto Calendar" org-goto-calendar t]
21787 ["Date from Calendar" org-date-from-calendar t]
21788 "--"
21789 ["Start/Restart Timer" org-timer-start t]
21790 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21791 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21792 ["Insert Timer String" org-timer t]
21793 ["Insert Timer Item" org-timer-item t])
21794 ("Logging work"
21795 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21796 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21797 ["Clock out" org-clock-out t]
21798 ["Clock cancel" org-clock-cancel t]
21799 "--"
21800 ["Mark as default task" org-clock-mark-default-task t]
21801 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21802 ["Goto running clock" org-clock-goto t]
21803 "--"
21804 ["Display times" org-clock-display t]
21805 ["Create clock table" org-clock-report t]
21806 "--"
21807 ["Record DONE time"
21808 (progn (setq org-log-done (not org-log-done))
21809 (message "Switching to %s will %s record a timestamp"
21810 (car org-done-keywords)
21811 (if org-log-done "automatically" "not")))
21812 :style toggle :selected org-log-done])
21813 "--"
21814 ["Agenda Command..." org-agenda t]
21815 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21816 ("File List for Agenda")
21817 ("Special views current file"
21818 ["TODO Tree" org-show-todo-tree t]
21819 ["Check Deadlines" org-check-deadlines t]
21820 ["Timeline" org-timeline t]
21821 ["Tags/Property tree" org-match-sparse-tree t])
21822 "--"
21823 ["Export/Publish..." org-export-dispatch t]
21824 ("LaTeX"
21825 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21826 :selected org-cdlatex-mode]
21827 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21828 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21829 ["Modify math symbol" org-cdlatex-math-modify
21830 (org-inside-LaTeX-fragment-p)]
21831 ["Insert citation" org-reftex-citation t])
21832 "--"
21833 ("MobileOrg"
21834 ["Push Files and Views" org-mobile-push t]
21835 ["Get Captured and Flagged" org-mobile-pull t]
21836 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21837 "--"
21838 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21839 "--"
21840 ("Documentation"
21841 ["Show Version" org-version t]
21842 ["Info Documentation" org-info t])
21843 ("Customize"
21844 ["Browse Org Group" org-customize t]
21845 "--"
21846 ["Expand This Menu" org-create-customize-menu
21847 (fboundp 'customize-menu-create)])
21848 ["Send bug report" org-submit-bug-report t]
21849 "--"
21850 ("Refresh/Reload"
21851 ["Refresh setup current buffer" org-mode-restart t]
21852 ["Reload Org (after update)" org-reload t]
21853 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21856 (defun org-info (&optional node)
21857 "Read documentation for Org in the info system.
21858 With optional NODE, go directly to that node."
21859 (interactive)
21860 (info (format "(org)%s" (or node ""))))
21862 ;;;###autoload
21863 (defun org-submit-bug-report ()
21864 "Submit a bug report on Org via mail.
21866 Don't hesitate to report any problems or inaccurate documentation.
21868 If you don't have setup sending mail from (X)Emacs, please copy the
21869 output buffer into your mail program, as it gives us important
21870 information about your Org version and configuration."
21871 (interactive)
21872 (require 'reporter)
21873 (defvar reporter-prompt-for-summary-p)
21874 (org-load-modules-maybe)
21875 (org-require-autoloaded-modules)
21876 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21877 (reporter-submit-bug-report
21878 "emacs-orgmode@gnu.org"
21879 (org-version nil 'full)
21880 (let (list)
21881 (save-window-excursion
21882 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21883 (delete-other-windows)
21884 (erase-buffer)
21885 (insert "You are about to submit a bug report to the Org mailing list.
21887 We would like to add your full Org and Outline configuration to the
21888 bug report. This greatly simplifies the work of the maintainer and
21889 other experts on the mailing list.
21891 HOWEVER, some variables you have customized may contain private
21892 information. The names of customers, colleagues, or friends, might
21893 appear in the form of file names, tags, todo states, or search strings.
21894 If you answer yes to the prompt, you might want to check and remove
21895 such private information before sending the email.")
21896 (add-text-properties (point-min) (point-max) '(face org-warning))
21897 (when (yes-or-no-p "Include your Org configuration ")
21898 (mapatoms
21899 (lambda (v)
21900 (and (boundp v)
21901 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21902 (or (and (symbol-value v)
21903 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21904 (and
21905 (get v 'custom-type) (get v 'standard-value)
21906 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21907 (push v list)))))
21908 (kill-buffer (get-buffer "*Warn about privacy*"))
21909 list))
21910 nil nil
21911 "Remember to cover the basics, that is, what you expected to happen and
21912 what in fact did happen. You don't know how to make a good report? See
21914 http://orgmode.org/manual/Feedback.html#Feedback
21916 Your bug report will be posted to the Org mailing list.
21917 ------------------------------------------------------------------------")
21918 (save-excursion
21919 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21920 (replace-match "\\1Bug: \\3 [\\2]")))))
21923 (defun org-install-agenda-files-menu ()
21924 (let ((bl (buffer-list)))
21925 (save-excursion
21926 (while bl
21927 (set-buffer (pop bl))
21928 (when (derived-mode-p 'org-mode) (setq bl nil)))
21929 (when (derived-mode-p 'org-mode)
21930 (easy-menu-change
21931 '("Org") "File List for Agenda"
21932 (append
21933 (list
21934 ["Edit File List" (org-edit-agenda-file-list) t]
21935 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21936 ["Remove Current File from List" org-remove-file t]
21937 ["Cycle through agenda files" org-cycle-agenda-files t]
21938 ["Occur in all agenda files" org-occur-in-agenda-files t]
21939 "--")
21940 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21942 ;;;; Documentation
21944 (defun org-require-autoloaded-modules ()
21945 (interactive)
21946 (mapc #'require
21947 '(org-agenda org-archive org-attach org-clock org-colview org-id
21948 org-table org-timer)))
21950 ;;;###autoload
21951 (defun org-reload (&optional uncompiled)
21952 "Reload all org lisp files.
21953 With prefix arg UNCOMPILED, load the uncompiled versions."
21954 (interactive "P")
21955 (require 'loadhist)
21956 (let* ((org-dir (org-find-library-dir "org"))
21957 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21958 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21959 (remove-re (format "\\`%s\\'"
21960 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21961 (feats (delete-dups
21962 (mapcar 'file-name-sans-extension
21963 (mapcar 'file-name-nondirectory
21964 (delq nil
21965 (mapcar 'feature-file
21966 features))))))
21967 (lfeat (append
21968 (sort
21969 (setq feats
21970 (delq nil (mapcar
21971 (lambda (f)
21972 (if (and (string-match feature-re f)
21973 (not (string-match remove-re f)))
21974 f nil))
21975 feats)))
21976 'string-lessp)
21977 (list "org-version" "org")))
21978 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21979 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21980 load-uncore load-misses)
21981 (setq load-misses
21982 (delq 't
21983 (mapcar (lambda (f)
21984 (or (org-load-noerror-mustsuffix (concat org-dir f))
21985 (and (string= org-dir contrib-dir)
21986 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21987 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21988 (add-to-list 'load-uncore f 'append)
21991 lfeat)))
21992 (when load-uncore
21993 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21994 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21995 (if load-misses
21996 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21997 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21998 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
22000 ;;;###autoload
22001 (defun org-customize ()
22002 "Call the customize function with org as argument."
22003 (interactive)
22004 (org-load-modules-maybe)
22005 (org-require-autoloaded-modules)
22006 (customize-browse 'org))
22008 (defun org-create-customize-menu ()
22009 "Create a full customization menu for Org mode, insert it into the menu."
22010 (interactive)
22011 (org-load-modules-maybe)
22012 (org-require-autoloaded-modules)
22013 (if (fboundp 'customize-menu-create)
22014 (progn
22015 (easy-menu-change
22016 '("Org") "Customize"
22017 `(["Browse Org group" org-customize t]
22018 "--"
22019 ,(customize-menu-create 'org)
22020 ["Set" Custom-set t]
22021 ["Save" Custom-save t]
22022 ["Reset to Current" Custom-reset-current t]
22023 ["Reset to Saved" Custom-reset-saved t]
22024 ["Reset to Standard Settings" Custom-reset-standard t]))
22025 (message "\"Org\"-menu now contains full customization menu"))
22026 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22028 ;;;; Miscellaneous stuff
22030 ;;; Generally useful functions
22032 (defun org-get-at-eol (property n)
22033 "Get text property PROPERTY at the end of line less N characters."
22034 (get-text-property (- (point-at-eol) n) property))
22036 (defun org-find-text-property-in-string (prop s)
22037 "Return the first non-nil value of property PROP in string S."
22038 (or (get-text-property 0 prop s)
22039 (get-text-property (or (next-single-property-change 0 prop s) 0)
22040 prop s)))
22042 (defun org-display-warning (message)
22043 "Display the given MESSAGE as a warning."
22044 (display-warning 'org message :warning))
22046 (defun org-eval (form)
22047 "Eval FORM and return result."
22048 (condition-case error
22049 (eval form)
22050 (error (format "%%![Error: %s]" error))))
22052 (defun org-in-clocktable-p ()
22053 "Check if the cursor is in a clocktable."
22054 (let ((pos (point)) start)
22055 (save-excursion
22056 (end-of-line 1)
22057 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22058 (setq start (match-beginning 0))
22059 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22060 (>= (match-end 0) pos)
22061 start))))
22063 (defun org-in-verbatim-emphasis ()
22064 (save-match-data
22065 (and (org-in-regexp org-emph-re 2)
22066 (>= (point) (match-beginning 3))
22067 (<= (point) (match-end 4))
22068 (member (match-string 3) '("=" "~")))))
22070 (defun org-overlay-display (ovl text &optional face evap)
22071 "Make overlay OVL display TEXT with face FACE."
22072 (overlay-put ovl 'display text)
22073 (if face (overlay-put ovl 'face face))
22074 (if evap (overlay-put ovl 'evaporate t)))
22076 (defun org-overlay-before-string (ovl text &optional face evap)
22077 "Make overlay OVL display TEXT with face FACE."
22078 (if face (org-add-props text nil 'face face))
22079 (overlay-put ovl 'before-string text)
22080 (if evap (overlay-put ovl 'evaporate t)))
22082 (defun org-find-overlays (prop &optional pos delete)
22083 "Find all overlays specifying PROP at POS or point.
22084 If DELETE is non-nil, delete all those overlays."
22085 (let (found)
22086 (dolist (ov (overlays-at (or pos (point))) found)
22087 (cond ((not (overlay-get ov prop)))
22088 (delete (delete-overlay ov))
22089 (t (push ov found))))))
22091 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22092 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22093 (if (and marker (marker-buffer marker)
22094 (buffer-live-p (marker-buffer marker)))
22095 (progn
22096 (pop-to-buffer-same-window (marker-buffer marker))
22097 (when (or (> marker (point-max)) (< marker (point-min)))
22098 (widen))
22099 (goto-char marker)
22100 (org-show-context 'org-goto))
22101 (if bookmark
22102 (bookmark-jump bookmark)
22103 (error "Cannot find location"))))
22105 (defun org-quote-csv-field (s)
22106 "Quote field for inclusion in CSV material."
22107 (if (string-match "[\",]" s)
22108 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22111 (defun org-force-self-insert (N)
22112 "Needed to enforce self-insert under remapping."
22113 (interactive "p")
22114 (self-insert-command N))
22116 (defun org-string-width (s)
22117 "Compute width of string, ignoring invisible characters.
22118 This ignores character with invisibility property `org-link', and also
22119 characters with property `org-cwidth', because these will become invisible
22120 upon the next fontification round."
22121 (let (b l)
22122 (when (or (eq t buffer-invisibility-spec)
22123 (assq 'org-link buffer-invisibility-spec))
22124 (while (setq b (text-property-any 0 (length s)
22125 'invisible 'org-link s))
22126 (setq s (concat (substring s 0 b)
22127 (substring s (or (next-single-property-change
22128 b 'invisible s)
22129 (length s)))))))
22130 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22131 (setq s (concat (substring s 0 b)
22132 (substring s (or (next-single-property-change
22133 b 'org-cwidth s)
22134 (length s))))))
22135 (setq l (string-width s) b -1)
22136 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22137 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22140 (defun org-shorten-string (s maxlength)
22141 "Shorten string S so that it is no longer than MAXLENGTH characters.
22142 If the string is shorter or has length MAXLENGTH, just return the
22143 original string. If it is longer, the functions finds a space in the
22144 string, breaks this string off at that locations and adds three dots
22145 as ellipsis. Including the ellipsis, the string will not be longer
22146 than MAXLENGTH. If finding a good breaking point in the string does
22147 not work, the string is just chopped off in the middle of a word
22148 if necessary."
22149 (if (<= (length s) maxlength)
22151 (let* ((n (max (- maxlength 4) 1))
22152 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22153 (if (string-match re s)
22154 (concat (match-string 1 s) "...")
22155 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22157 (defun org-get-indentation (&optional line)
22158 "Get the indentation of the current line, interpreting tabs.
22159 When LINE is given, assume it represents a line and compute its indentation."
22160 (if line
22161 (when (string-match "^ *" (org-remove-tabs line))
22162 (match-end 0))
22163 (save-excursion
22164 (beginning-of-line 1)
22165 (skip-chars-forward " \t")
22166 (current-column))))
22168 (defun org-get-string-indentation (s)
22169 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22170 (let ((n -1) (i 0) (w tab-width) c)
22171 (catch 'exit
22172 (while (< (setq n (1+ n)) (length s))
22173 (setq c (aref s n))
22174 (cond ((= c ?\ ) (setq i (1+ i)))
22175 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22176 (t (throw 'exit t)))))
22179 (defun org-remove-tabs (s &optional width)
22180 "Replace tabulators in S with spaces.
22181 Assumes that s is a single line, starting in column 0."
22182 (setq width (or width tab-width))
22183 (while (string-match "\t" s)
22184 (setq s (replace-match
22185 (make-string
22186 (- (* width (/ (+ (match-beginning 0) width) width))
22187 (match-beginning 0)) ?\ )
22188 t t s)))
22191 (defun org-fix-indentation (line ind)
22192 "Fix indentation in LINE.
22193 IND is a cons cell with target and minimum indentation.
22194 If the current indentation in LINE is smaller than the minimum,
22195 leave it alone. If it is larger than ind, set it to the target."
22196 (let* ((l (org-remove-tabs line))
22197 (i (org-get-indentation l))
22198 (i1 (car ind)) (i2 (cdr ind)))
22199 (when (>= i i2) (setq l (substring line i2)))
22200 (if (> i1 0)
22201 (concat (make-string i1 ?\ ) l)
22202 l)))
22204 (defun org-remove-indentation (code &optional n)
22205 "Remove maximum common indentation in string CODE and return it.
22206 N may optionally be the number of columns to remove. Return CODE
22207 as-is if removal failed."
22208 (with-temp-buffer
22209 (insert code)
22210 (if (org-do-remove-indentation n) (buffer-string) code)))
22212 (defun org-do-remove-indentation (&optional n)
22213 "Remove the maximum common indentation from the buffer.
22214 When optional argument N is a positive integer, remove exactly
22215 that much characters from indentation, if possible. Return nil
22216 if it fails."
22217 (catch :exit
22218 (goto-char (point-min))
22219 ;; Find maximum common indentation, if not specified.
22220 (let ((n (or n
22221 (let ((min-ind (point-max)))
22222 (save-excursion
22223 (while (re-search-forward "^[ \t]*\\S-" nil t)
22224 (let ((ind (1- (current-column))))
22225 (if (zerop ind) (throw :exit nil)
22226 (setq min-ind (min min-ind ind))))))
22227 min-ind))))
22228 (if (zerop n) (throw :exit nil)
22229 ;; Remove exactly N indentation, but give up if not possible.
22230 (while (not (eobp))
22231 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22232 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22233 ((< ind n) (throw :exit nil))
22234 (t (indent-line-to (- ind n))))
22235 (forward-line)))
22236 ;; Signal success.
22237 t))))
22239 (defun org-fill-template (template alist)
22240 "Find each %key of ALIST in TEMPLATE and replace it."
22241 (let ((case-fold-search nil))
22242 (dolist (entry (sort (copy-sequence alist)
22243 (lambda (a b) (< (length (car a)) (length (car b))))))
22244 (setq template
22245 (replace-regexp-in-string
22246 (concat "%" (regexp-quote (car entry)))
22247 (or (cdr entry) "") template t t)))
22248 template))
22250 (defun org-base-buffer (buffer)
22251 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22252 (if (not buffer)
22253 buffer
22254 (or (buffer-base-buffer buffer)
22255 buffer)))
22257 (defun org-wrap (string &optional width lines)
22258 "Wrap string to either a number of lines, or a width in characters.
22259 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22260 that costs. If there is a word longer than WIDTH, the text is actually
22261 wrapped to the length of that word.
22262 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22263 many lines, whatever width that takes.
22264 The return value is a list of lines, without newlines at the end."
22265 (let* ((words (org-split-string string "[ \t\n]+"))
22266 (maxword (apply 'max (mapcar 'org-string-width words)))
22267 w ll)
22268 (cond (width
22269 (org-do-wrap words (max maxword width)))
22270 (lines
22271 (setq w maxword)
22272 (setq ll (org-do-wrap words maxword))
22273 (if (<= (length ll) lines)
22275 (setq ll words)
22276 (while (> (length ll) lines)
22277 (setq w (1+ w))
22278 (setq ll (org-do-wrap words w)))
22279 ll))
22280 (t (error "Cannot wrap this")))))
22282 (defun org-do-wrap (words width)
22283 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22284 (let (lines line)
22285 (while words
22286 (setq line (pop words))
22287 (while (and words (< (+ (length line) (length (car words))) width))
22288 (setq line (concat line " " (pop words))))
22289 (setq lines (push line lines)))
22290 (nreverse lines)))
22292 (defun org-split-string (string &optional separators)
22293 "Splits STRING into substrings at SEPARATORS.
22294 SEPARATORS is a regular expression.
22295 No empty strings are returned if there are matches at the beginning
22296 and end of string."
22297 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22298 (let ((start 0) notfirst list)
22299 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22300 (if (and notfirst
22301 (= start (match-beginning 0))
22302 (< start (length string)))
22303 (1+ start) start))
22304 (< (match-beginning 0) (length string)))
22305 (setq notfirst t)
22306 (or (eq (match-beginning 0) 0)
22307 (and (eq (match-beginning 0) (match-end 0))
22308 (eq (match-beginning 0) start))
22309 (push (substring string start (match-beginning 0)) list))
22310 (setq start (match-end 0)))
22311 (or (eq start (length string))
22312 (push (substring string start) list))
22313 (nreverse list)))
22315 (defun org-quote-vert (s)
22316 "Replace \"|\" with \"\\vert\"."
22317 (while (string-match "|" s)
22318 (setq s (replace-match "\\vert" t t s)))
22321 (defun org-uuidgen-p (s)
22322 "Is S an ID created by UUIDGEN?"
22323 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22325 (defun org-in-src-block-p (&optional inside)
22326 "Whether point is in a code source block.
22327 When INSIDE is non-nil, don't consider we are within a src block
22328 when point is at #+BEGIN_SRC or #+END_SRC."
22329 (let ((case-fold-search t))
22330 (or (and (eq (get-char-property (point) 'src-block) t))
22331 (and (not inside)
22332 (save-match-data
22333 (save-excursion
22334 (beginning-of-line)
22335 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22337 (defun org-context ()
22338 "Return a list of contexts of the current cursor position.
22339 If several contexts apply, all are returned.
22340 Each context entry is a list with a symbol naming the context, and
22341 two positions indicating start and end of the context. Possible
22342 contexts are:
22344 :headline anywhere in a headline
22345 :headline-stars on the leading stars in a headline
22346 :todo-keyword on a TODO keyword (including DONE) in a headline
22347 :tags on the TAGS in a headline
22348 :priority on the priority cookie in a headline
22349 :item on the first line of a plain list item
22350 :item-bullet on the bullet/number of a plain list item
22351 :checkbox on the checkbox in a plain list item
22352 :table in an Org table
22353 :table-special on a special filed in a table
22354 :table-table in a table.el table
22355 :clocktable in a clocktable
22356 :src-block in a source block
22357 :link on a hyperlink
22358 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22359 :target on a <<target>>
22360 :radio-target on a <<<radio-target>>>
22361 :latex-fragment on a LaTeX fragment
22362 :latex-preview on a LaTeX fragment with overlaid preview image
22364 This function expects the position to be visible because it uses font-lock
22365 faces as a help to recognize the following contexts: :table-special, :link,
22366 and :keyword."
22367 (let* ((f (get-text-property (point) 'face))
22368 (faces (if (listp f) f (list f)))
22369 (case-fold-search t)
22370 (p (point)) clist o)
22371 ;; First the large context
22372 (cond
22373 ((org-at-heading-p t)
22374 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22375 (when (progn
22376 (beginning-of-line 1)
22377 (looking-at org-todo-line-tags-regexp))
22378 (push (org-point-in-group p 1 :headline-stars) clist)
22379 (push (org-point-in-group p 2 :todo-keyword) clist)
22380 (push (org-point-in-group p 4 :tags) clist))
22381 (goto-char p)
22382 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22383 (when (looking-at "\\[#[A-Z0-9]\\]")
22384 (push (org-point-in-group p 0 :priority) clist)))
22386 ((org-at-item-p)
22387 (push (org-point-in-group p 2 :item-bullet) clist)
22388 (push (list :item (point-at-bol)
22389 (save-excursion (org-end-of-item) (point)))
22390 clist)
22391 (and (org-at-item-checkbox-p)
22392 (push (org-point-in-group p 0 :checkbox) clist)))
22394 ((org-at-table-p)
22395 (push (list :table (org-table-begin) (org-table-end)) clist)
22396 (when (memq 'org-formula faces)
22397 (push (list :table-special
22398 (previous-single-property-change p 'face)
22399 (next-single-property-change p 'face)) clist)))
22400 ((org-at-table-p 'any)
22401 (push (list :table-table) clist)))
22402 (goto-char p)
22404 (let ((case-fold-search t))
22405 ;; New the "medium" contexts: clocktables, source blocks
22406 (cond ((org-in-clocktable-p)
22407 (push (list :clocktable
22408 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22409 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22410 (match-beginning 1))
22411 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22412 (match-end 0))) clist))
22413 ((org-in-src-block-p)
22414 (push (list :src-block
22415 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22416 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22417 (match-beginning 1))
22418 (and (search-forward "#+END_SRC" nil t)
22419 (match-beginning 0))) clist))))
22420 (goto-char p)
22422 ;; Now the small context
22423 (cond
22424 ((org-at-timestamp-p)
22425 (push (org-point-in-group p 0 :timestamp) clist))
22426 ((memq 'org-link faces)
22427 (push (list :link
22428 (previous-single-property-change p 'face)
22429 (next-single-property-change p 'face)) clist))
22430 ((memq 'org-special-keyword faces)
22431 (push (list :keyword
22432 (previous-single-property-change p 'face)
22433 (next-single-property-change p 'face)) clist))
22434 ((org-at-target-p)
22435 (push (org-point-in-group p 0 :target) clist)
22436 (goto-char (1- (match-beginning 0)))
22437 (when (looking-at org-radio-target-regexp)
22438 (push (org-point-in-group p 0 :radio-target) clist))
22439 (goto-char p))
22440 ((setq o (cl-some
22441 (lambda (o)
22442 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22444 (overlays-at (point))))
22445 (push (list :latex-fragment
22446 (overlay-start o) (overlay-end o)) clist)
22447 (push (list :latex-preview
22448 (overlay-start o) (overlay-end o)) clist))
22449 ((org-inside-LaTeX-fragment-p)
22450 ;; FIXME: positions wrong.
22451 (push (list :latex-fragment (point) (point)) clist)))
22453 (setq clist (nreverse (delq nil clist)))
22454 clist))
22456 (defun org-in-regexp (regexp &optional nlines visually)
22457 "Check if point is inside a match of REGEXP.
22459 Normally only the current line is checked, but you can include
22460 NLINES extra lines around point into the search. If VISUALLY is
22461 set, require that the cursor is not after the match but really
22462 on, so that the block visually is on the match.
22464 Return nil or a cons cell (BEG . END) where BEG and END are,
22465 respectively, the positions at the beginning and the end of the
22466 match."
22467 (catch :exit
22468 (let ((pos (point))
22469 (eol (line-end-position (if nlines (1+ nlines) 1))))
22470 (save-excursion
22471 (beginning-of-line (- 1 (or nlines 0)))
22472 (while (and (re-search-forward regexp eol t)
22473 (<= (match-beginning 0) pos))
22474 (let ((end (match-end 0)))
22475 (when (or (> end pos) (and (= end pos) (not visually)))
22476 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22478 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22479 "Non-nil when point is between matches of START-RE and END-RE.
22481 Also return a non-nil value when point is on one of the matches.
22483 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22484 buffer positions. Default values are the positions of headlines
22485 surrounding the point.
22487 The functions returns a cons cell whose car (resp. cdr) is the
22488 position before START-RE (resp. after END-RE)."
22489 (save-match-data
22490 (let ((pos (point))
22491 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22492 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22493 beg end)
22494 (save-excursion
22495 ;; Point is on a block when on START-RE or if START-RE can be
22496 ;; found before it...
22497 (and (or (org-in-regexp start-re)
22498 (re-search-backward start-re limit-up t))
22499 (setq beg (match-beginning 0))
22500 ;; ... and END-RE after it...
22501 (goto-char (match-end 0))
22502 (re-search-forward end-re limit-down t)
22503 (> (setq end (match-end 0)) pos)
22504 ;; ... without another START-RE in-between.
22505 (goto-char (match-beginning 0))
22506 (not (re-search-backward start-re (1+ beg) t))
22507 ;; Return value.
22508 (cons beg end))))))
22510 (defun org-in-block-p (names)
22511 "Non-nil when point belongs to a block whose name belongs to NAMES.
22513 NAMES is a list of strings containing names of blocks.
22515 Return first block name matched, or nil. Beware that in case of
22516 nested blocks, the returned name may not belong to the closest
22517 block from point."
22518 (save-match-data
22519 (catch 'exit
22520 (let ((case-fold-search t)
22521 (lim-up (save-excursion (outline-previous-heading)))
22522 (lim-down (save-excursion (outline-next-heading))))
22523 (dolist (name names)
22524 (let ((n (regexp-quote name)))
22525 (when (org-between-regexps-p
22526 (concat "^[ \t]*#\\+begin_" n)
22527 (concat "^[ \t]*#\\+end_" n)
22528 lim-up lim-down)
22529 (throw 'exit n)))))
22530 nil)))
22532 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22533 "Call `multi-occur' with buffers for all agenda files."
22534 (interactive "sOrg-files matching: ")
22535 (let* ((files (org-agenda-files))
22536 (tnames (mapcar #'file-truename files))
22537 (extra org-agenda-text-search-extra-files))
22538 (when (eq (car extra) 'agenda-archives)
22539 (setq extra (cdr extra))
22540 (setq files (org-add-archive-files files)))
22541 (dolist (f extra)
22542 (unless (member (file-truename f) tnames)
22543 (unless (member f files) (setq files (append files (list f))))
22544 (setq tnames (append tnames (list (file-truename f))))))
22545 (multi-occur
22546 (mapcar (lambda (x)
22547 (with-current-buffer
22548 ;; FIXME: Why not just (find-file-noselect x)?
22549 ;; Is it to avoid the "revert buffer" prompt?
22550 (or (get-file-buffer x) (find-file-noselect x))
22551 (widen)
22552 (current-buffer)))
22553 files)
22554 regexp)))
22556 (add-hook 'occur-mode-find-occurrence-hook
22557 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22559 (defun org-occur-link-in-agenda-files ()
22560 "Create a link and search for it in the agendas.
22561 The link is not stored in `org-stored-links', it is just created
22562 for the search purpose."
22563 (interactive)
22564 (let ((link (condition-case nil
22565 (org-store-link nil)
22566 (error "Unable to create a link to here"))))
22567 (org-occur-in-agenda-files (regexp-quote link))))
22569 (defun org-reverse-string (string)
22570 "Return the reverse of STRING."
22571 (apply 'string (reverse (string-to-list string))))
22573 ;; defsubst org-uniquify must be defined before first use
22575 (defun org-uniquify-alist (alist)
22576 "Merge elements of ALIST with the same key.
22578 For example, in this alist:
22580 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22581 => \\='((a 1 3) (b 2))
22583 merge (a 1) and (a 3) into (a 1 3).
22585 The function returns the new ALIST."
22586 (let (rtn)
22587 (dolist (e alist rtn)
22588 (let (n)
22589 (if (not (assoc (car e) rtn))
22590 (push e rtn)
22591 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22592 (setq rtn (assq-delete-all (car e) rtn))
22593 (push n rtn))))))
22595 (defun org-delete-all (elts list)
22596 "Remove all elements in ELTS from LIST.
22597 Comparison is done with `equal'. It is a destructive operation
22598 that may remove elements by altering the list structure."
22599 (while elts
22600 (setq list (delete (pop elts) list)))
22601 list)
22603 (defun org-back-over-empty-lines ()
22604 "Move backwards over whitespace, to the beginning of the first empty line.
22605 Returns the number of empty lines passed."
22606 (let ((pos (point)))
22607 (if (cdr (assq 'heading org-blank-before-new-entry))
22608 (skip-chars-backward " \t\n\r")
22609 (unless (eobp)
22610 (forward-line -1)))
22611 (beginning-of-line 2)
22612 (goto-char (min (point) pos))
22613 (count-lines (point) pos)))
22615 (defun org-skip-whitespace ()
22616 (skip-chars-forward " \t\n\r"))
22618 (defun org-point-in-group (point group &optional context)
22619 "Check if POINT is in match-group GROUP.
22620 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22621 match. If the match group does not exist or point is not inside it,
22622 return nil."
22623 (and (match-beginning group)
22624 (>= point (match-beginning group))
22625 (<= point (match-end group))
22626 (if context
22627 (list context (match-beginning group) (match-end group))
22628 t)))
22630 (defun org-switch-to-buffer-other-window (&rest args)
22631 "Switch to buffer in a second window on the current frame.
22632 In particular, do not allow pop-up frames.
22633 Returns the newly created buffer."
22634 (org-no-popups
22635 (apply 'switch-to-buffer-other-window args)))
22637 (defun org-combine-plists (&rest plists)
22638 "Create a single property list from all plists in PLISTS.
22639 The process starts by copying the first list, and then setting properties
22640 from the other lists. Settings in the last list are the most significant
22641 ones and overrule settings in the other lists."
22642 (let ((rtn (copy-sequence (pop plists)))
22643 p v ls)
22644 (while plists
22645 (setq ls (pop plists))
22646 (while ls
22647 (setq p (pop ls) v (pop ls))
22648 (setq rtn (plist-put rtn p v))))
22649 rtn))
22651 (defun org-replace-escapes (string table)
22652 "Replace %-escapes in STRING with values in TABLE.
22653 TABLE is an association list with keys like \"%a\" and string values.
22654 The sequences in STRING may contain normal field width and padding information,
22655 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22656 so values can contain further %-escapes if they are define later in TABLE."
22657 (let ((tbl (copy-alist table))
22658 (case-fold-search nil)
22659 (pchg 0)
22660 re rpl)
22661 (dolist (e tbl)
22662 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22663 (when (and (cdr e) (string-match re (cdr e)))
22664 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22665 (safe "SREF"))
22666 (add-text-properties 0 3 (list 'sref sref) safe)
22667 (setcdr e (replace-match safe t t (cdr e)))))
22668 (while (string-match re string)
22669 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22670 (cdr e)))
22671 (setq string (replace-match rpl t t string))))
22672 (while (setq pchg (next-property-change pchg string))
22673 (let ((sref (get-text-property pchg 'sref string)))
22674 (when (and sref (string-match "SREF" string pchg))
22675 (setq string (replace-match sref t t string)))))
22676 string))
22678 (defun org-find-base-buffer-visiting (file)
22679 "Like `find-buffer-visiting' but always return the base buffer and
22680 not an indirect buffer."
22681 (let ((buf (or (get-file-buffer file)
22682 (find-buffer-visiting file))))
22683 (if buf
22684 (or (buffer-base-buffer buf) buf)
22685 nil)))
22687 ;;; TODO: Only called once, from ox-odt which should probably use
22688 ;;; org-export-inline-image-p or something.
22689 (defun org-file-image-p (file)
22690 "Return non-nil if FILE is an image."
22691 (save-match-data
22692 (string-match (image-file-name-regexp) file)))
22694 (defun org-get-cursor-date (&optional with-time)
22695 "Return the date at cursor in as a time.
22696 This works in the calendar and in the agenda, anywhere else it just
22697 returns the current time.
22698 If WITH-TIME is non-nil, returns the time of the event at point (in
22699 the agenda) or the current time of the day."
22700 (let (date day defd tp hod mod)
22701 (when with-time
22702 (setq tp (get-text-property (point) 'time))
22703 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22704 (setq hod (string-to-number (match-string 1 tp))
22705 mod (string-to-number (match-string 2 tp))))
22706 (or tp (let ((now (decode-time)))
22707 (setq hod (nth 2 now)
22708 mod (nth 1 now)))))
22709 (cond
22710 ((eq major-mode 'calendar-mode)
22711 (setq date (calendar-cursor-to-date)
22712 defd (encode-time 0 (or mod 0) (or hod 0)
22713 (nth 1 date) (nth 0 date) (nth 2 date))))
22714 ((eq major-mode 'org-agenda-mode)
22715 (setq day (get-text-property (point) 'day))
22716 (when day
22717 (setq date (calendar-gregorian-from-absolute day)
22718 defd (encode-time 0 (or mod 0) (or hod 0)
22719 (nth 1 date) (nth 0 date) (nth 2 date))))))
22720 (or defd (current-time))))
22722 (defun org-mark-subtree (&optional up)
22723 "Mark the current subtree.
22724 This puts point at the start of the current subtree, and mark at
22725 the end. If a numeric prefix UP is given, move up into the
22726 hierarchy of headlines by UP levels before marking the subtree."
22727 (interactive "P")
22728 (org-with-limited-levels
22729 (cond ((org-at-heading-p) (beginning-of-line))
22730 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22731 (t (outline-previous-visible-heading 1))))
22732 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22733 (if (called-interactively-p 'any)
22734 (call-interactively 'org-mark-element)
22735 (org-mark-element)))
22737 (defun org-file-newer-than-p (file time)
22738 "Non-nil if FILE is newer than TIME.
22739 FILE is a filename, as a string, TIME is a list of integers, as
22740 returned by, e.g., `current-time'."
22741 (and (file-exists-p file)
22742 ;; Only compare times up to whole seconds as some file-systems
22743 ;; (e.g. HFS+) do not retain any finer granularity. As
22744 ;; a consequence, make sure we return non-nil when the two
22745 ;; times are equal.
22746 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22747 (cl-subseq time 0 2)))))
22749 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22750 "Compile a SOURCE file using PROCESS.
22752 PROCESS is either a function or a list of shell commands, as
22753 strings. EXT is a file extension, without the leading dot, as
22754 a string. It is used to check if the process actually succeeded.
22756 PROCESS must create a file with the same base name and directory
22757 as SOURCE, but ending with EXT. The function then returns its
22758 filename. Otherwise, it raises an error. The error message can
22759 then be refined by providing string ERR-MSG, which is appended to
22760 the standard message.
22762 If PROCESS is a function, it is called with a single argument:
22763 the SOURCE file.
22765 If it is a list of commands, each of them is called using
22766 `shell-command'. By default, in each command, %b, %f, %F, %o and
22767 %O are replaced with, respectively, SOURCE base name, name, full
22768 name, directory and absolute output file name. It is possible,
22769 however, to use more place-holders by specifying them in optional
22770 argument SPEC, as an alist following the pattern
22772 (CHARACTER . REPLACEMENT-STRING).
22774 When PROCESS is a list of commands, optional argument LOG-BUF can
22775 be set to a buffer or a buffer name. `shell-command' then uses
22776 it for output."
22777 (let* ((base-name (file-name-base source))
22778 (full-name (file-truename source))
22779 (out-dir (or (file-name-directory source) "./"))
22780 (output (expand-file-name (concat base-name "." ext) out-dir))
22781 (time (current-time))
22782 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22783 (save-window-excursion
22784 (pcase process
22785 ((pred functionp) (funcall process (shell-quote-argument source)))
22786 ((pred consp)
22787 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22788 (spec (append spec
22789 `((?b . ,(shell-quote-argument base-name))
22790 (?f . ,(shell-quote-argument source))
22791 (?F . ,(shell-quote-argument full-name))
22792 (?o . ,(shell-quote-argument out-dir))
22793 (?O . ,(shell-quote-argument output))))))
22794 (dolist (command process)
22795 (shell-command (format-spec command spec) log-buf))))
22796 (_ (error "No valid command to process %S%s" source err-msg))))
22797 ;; Check for process failure. Output file is expected to be
22798 ;; located in the same directory as SOURCE.
22799 (unless (org-file-newer-than-p output time)
22800 (error (format "File %S wasn't produced%s" output err-msg)))
22801 output))
22803 ;;; Indentation
22805 (defun org--get-expected-indentation (element contentsp)
22806 "Expected indentation column for current line, according to ELEMENT.
22807 ELEMENT is an element containing point. CONTENTSP is non-nil
22808 when indentation is to be computed according to contents of
22809 ELEMENT."
22810 (let ((type (org-element-type element))
22811 (start (org-element-property :begin element))
22812 (post-affiliated (org-element-property :post-affiliated element)))
22813 (org-with-wide-buffer
22814 (cond
22815 (contentsp
22816 (cl-case type
22817 ((diary-sexp footnote-definition) 0)
22818 ((headline inlinetask nil)
22819 (if (not org-adapt-indentation) 0
22820 (let ((level (org-current-level)))
22821 (if level (1+ level) 0))))
22822 ((item plain-list) (org-list-item-body-column post-affiliated))
22824 (goto-char start)
22825 (org-get-indentation))))
22826 ((memq type '(headline inlinetask nil))
22827 (if (org-match-line "[ \t]*$")
22828 (org--get-expected-indentation element t)
22830 ((memq type '(diary-sexp footnote-definition)) 0)
22831 ;; First paragraph of a footnote definition or an item.
22832 ;; Indent like parent.
22833 ((< (line-beginning-position) start)
22834 (org--get-expected-indentation
22835 (org-element-property :parent element) t))
22836 ;; At first line: indent according to previous sibling, if any,
22837 ;; ignoring footnote definitions and inline tasks, or parent's
22838 ;; contents.
22839 ((= (line-beginning-position) start)
22840 (catch 'exit
22841 (while t
22842 (if (= (point-min) start) (throw 'exit 0)
22843 (goto-char (1- start))
22844 (let* ((previous (org-element-at-point))
22845 (parent previous))
22846 (while (and parent (<= (org-element-property :end parent) start))
22847 (setq previous parent
22848 parent (org-element-property :parent parent)))
22849 (cond
22850 ((not previous) (throw 'exit 0))
22851 ((> (org-element-property :end previous) start)
22852 (throw 'exit (org--get-expected-indentation previous t)))
22853 ((memq (org-element-type previous)
22854 '(footnote-definition inlinetask))
22855 (setq start (org-element-property :begin previous)))
22856 (t (goto-char (org-element-property :begin previous))
22857 (throw 'exit
22858 (if (bolp) (org-get-indentation)
22859 ;; At first paragraph in an item or
22860 ;; a footnote definition.
22861 (org--get-expected-indentation
22862 (org-element-property :parent previous) t))))))))))
22863 ;; Otherwise, move to the first non-blank line above.
22865 (beginning-of-line)
22866 (let ((pos (point)))
22867 (skip-chars-backward " \r\t\n")
22868 (cond
22869 ;; Two blank lines end a footnote definition or a plain
22870 ;; list. When we indent an empty line after them, the
22871 ;; containing list or footnote definition is over, so it
22872 ;; qualifies as a previous sibling. Therefore, we indent
22873 ;; like its first line.
22874 ((and (memq type '(footnote-definition plain-list))
22875 (> (count-lines (point) pos) 2))
22876 (goto-char start)
22877 (org-get-indentation))
22878 ;; Line above is the first one of a paragraph at the
22879 ;; beginning of an item or a footnote definition. Indent
22880 ;; like parent.
22881 ((< (line-beginning-position) start)
22882 (org--get-expected-indentation
22883 (org-element-property :parent element) t))
22884 ;; Line above is the beginning of an element, i.e., point
22885 ;; was originally on the blank lines between element's start
22886 ;; and contents.
22887 ((= (line-beginning-position) post-affiliated)
22888 (org--get-expected-indentation element t))
22889 ;; POS is after contents in a greater element. Indent like
22890 ;; the beginning of the element.
22891 ((and (memq type org-element-greater-elements)
22892 (let ((cend (org-element-property :contents-end element)))
22893 (and cend (<= cend pos))))
22894 ;; As a special case, if point is at the end of a footnote
22895 ;; definition or an item, indent like the very last element
22896 ;; within. If that last element is an item, indent like
22897 ;; its contents.
22898 (if (memq type '(footnote-definition item plain-list))
22899 (let ((last (org-element-at-point)))
22900 (goto-char pos)
22901 (org--get-expected-indentation
22902 last (eq (org-element-type last) 'item)))
22903 (goto-char start)
22904 (org-get-indentation)))
22905 ;; In any other case, indent like the current line.
22906 (t (org-get-indentation)))))))))
22908 (defun org--align-node-property ()
22909 "Align node property at point.
22910 Alignment is done according to `org-property-format', which see."
22911 (when (save-excursion
22912 (beginning-of-line)
22913 (looking-at org-property-re))
22914 (replace-match
22915 (concat (match-string 4)
22916 (org-trim
22917 (format org-property-format (match-string 1) (match-string 3))))
22918 t t)))
22920 (defun org-indent-line ()
22921 "Indent line depending on context.
22923 Indentation is done according to the following rules:
22925 - Footnote definitions, diary sexps, headlines and inline tasks
22926 have to start at column 0.
22928 - On the very first line of an element, consider, in order, the
22929 next rules until one matches:
22931 1. If there's a sibling element before, ignoring footnote
22932 definitions and inline tasks, indent like its first line.
22934 2. If element has a parent, indent like its contents. More
22935 precisely, if parent is an item, indent after the
22936 description part, if any, or the bullet (see
22937 `org-list-description-max-indent'). Else, indent like
22938 parent's first line.
22940 3. Otherwise, indent relatively to current level, if
22941 `org-adapt-indentation' is non-nil, or to left margin.
22943 - On a blank line at the end of an element, indent according to
22944 the type of the element. More precisely
22946 1. If element is a plain list, an item, or a footnote
22947 definition, indent like the very last element within.
22949 2. If element is a paragraph, indent like its last non blank
22950 line.
22952 3. Otherwise, indent like its very first line.
22954 - In the code part of a source block, use language major mode
22955 to indent current line if `org-src-tab-acts-natively' is
22956 non-nil. If it is nil, do nothing.
22958 - Otherwise, indent like the first non-blank line above.
22960 The function doesn't indent an item as it could break the whole
22961 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22962 `\\[org-shiftmetaright]'.
22964 Also align node properties according to `org-property-format'."
22965 (interactive)
22966 (cond
22967 (orgstruct-is-++
22968 (let ((indent-line-function
22969 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22970 (indent-according-to-mode)))
22971 ((org-at-heading-p) 'noindent)
22973 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22974 (type (org-element-type element)))
22975 (cond ((and (memq type '(plain-list item))
22976 (= (line-beginning-position)
22977 (org-element-property :post-affiliated element)))
22978 'noindent)
22979 ((and (eq type 'latex-environment)
22980 (>= (point) (org-element-property :post-affiliated element))
22981 (< (point) (org-with-wide-buffer
22982 (goto-char (org-element-property :end element))
22983 (skip-chars-backward " \r\t\n")
22984 (line-beginning-position 2))))
22985 'noindent)
22986 ((and (eq type 'src-block)
22987 org-src-tab-acts-natively
22988 (> (line-beginning-position)
22989 (org-element-property :post-affiliated element))
22990 (< (line-beginning-position)
22991 (org-with-wide-buffer
22992 (goto-char (org-element-property :end element))
22993 (skip-chars-backward " \r\t\n")
22994 (line-beginning-position))))
22995 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22997 (let ((column (org--get-expected-indentation element nil)))
22998 ;; Preserve current column.
22999 (if (<= (current-column) (current-indentation))
23000 (indent-line-to column)
23001 (save-excursion (indent-line-to column))))
23002 ;; Align node property. Also preserve current column.
23003 (when (eq type 'node-property)
23004 (let ((column (current-column)))
23005 (org--align-node-property)
23006 (org-move-to-column column)))))))))
23008 (defun org-indent-region (start end)
23009 "Indent each non-blank line in the region.
23010 Called from a program, START and END specify the region to
23011 indent. The function will not indent contents of example blocks,
23012 verse blocks and export blocks as leading white spaces are
23013 assumed to be significant there."
23014 (interactive "r")
23015 (save-excursion
23016 (goto-char start)
23017 (skip-chars-forward " \r\t\n")
23018 (unless (eobp) (beginning-of-line))
23019 (let ((indent-to
23020 (lambda (ind pos)
23021 ;; Set IND as indentation for all lines between point and
23022 ;; POS. Blank lines are ignored. Leave point after POS
23023 ;; once done.
23024 (let ((limit (copy-marker pos)))
23025 (while (< (point) limit)
23026 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
23027 (forward-line))
23028 (set-marker limit nil))))
23029 (end (copy-marker end)))
23030 (while (< (point) end)
23031 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23032 (let* ((element (org-element-at-point))
23033 (type (org-element-type element))
23034 (element-end (copy-marker (org-element-property :end element)))
23035 (ind (org--get-expected-indentation element nil)))
23036 (cond
23037 ;; Element indented as a single block. Example blocks
23038 ;; preserving indentation are a special case since the
23039 ;; "contents" must not be indented whereas the block
23040 ;; boundaries can.
23041 ((or (memq type '(export-block latex-environment))
23042 (and (eq type 'example-block)
23043 (not
23044 (or org-src-preserve-indentation
23045 (org-element-property :preserve-indent element)))))
23046 (let ((offset (- ind (org-get-indentation))))
23047 (unless (zerop offset)
23048 (indent-rigidly (org-element-property :begin element)
23049 (org-element-property :end element)
23050 offset)))
23051 (goto-char element-end))
23052 ;; Elements indented line wise. Be sure to exclude
23053 ;; example blocks (preserving indentation) and source
23054 ;; blocks from this category as they are treated
23055 ;; specially later.
23056 ((or (memq type '(paragraph table table-row))
23057 (not (or (org-element-property :contents-begin element)
23058 (memq type '(example-block src-block)))))
23059 (when (eq type 'node-property)
23060 (org--align-node-property)
23061 (beginning-of-line))
23062 (funcall indent-to ind (min element-end end)))
23063 ;; Elements consisting of three parts: before the
23064 ;; contents, the contents, and after the contents. The
23065 ;; contents are treated specially, according to the
23066 ;; element type, or not indented at all. Other parts are
23067 ;; indented as a single block.
23069 (let* ((post (copy-marker
23070 (org-element-property :post-affiliated element)))
23071 (cbeg
23072 (copy-marker
23073 (cond
23074 ((not (org-element-property :contents-begin element))
23075 ;; Fake contents for source blocks.
23076 (org-with-wide-buffer
23077 (goto-char post)
23078 (line-beginning-position 2)))
23079 ((memq type '(footnote-definition item plain-list))
23080 ;; Contents in these elements could start on
23081 ;; the same line as the beginning of the
23082 ;; element. Make sure we start indenting
23083 ;; from the second line.
23084 (org-with-wide-buffer
23085 (goto-char post)
23086 (end-of-line)
23087 (skip-chars-forward " \r\t\n")
23088 (if (eobp) (point) (line-beginning-position))))
23089 (t (org-element-property :contents-begin element)))))
23090 (cend (copy-marker
23091 (or (org-element-property :contents-end element)
23092 ;; Fake contents for source blocks.
23093 (org-with-wide-buffer
23094 (goto-char element-end)
23095 (skip-chars-backward " \r\t\n")
23096 (line-beginning-position)))
23097 t)))
23098 ;; Do not change items indentation individually as it
23099 ;; might break the list as a whole. On the other
23100 ;; hand, when at a plain list, indent it as a whole.
23101 (cond ((eq type 'plain-list)
23102 (let ((offset (- ind (org-get-indentation))))
23103 (unless (zerop offset)
23104 (indent-rigidly (org-element-property :begin element)
23105 (org-element-property :end element)
23106 offset))
23107 (goto-char cbeg)))
23108 ((eq type 'item) (goto-char cbeg))
23109 (t (funcall indent-to ind (min cbeg end))))
23110 (when (< (point) end)
23111 (cl-case type
23112 ((example-block verse-block))
23113 (src-block
23114 ;; In a source block, indent source code
23115 ;; according to language major mode, but only if
23116 ;; `org-src-tab-acts-natively' is non-nil.
23117 (when (and (< (point) end) org-src-tab-acts-natively)
23118 (ignore-errors
23119 (org-babel-do-in-edit-buffer
23120 (indent-region (point-min) (point-max))))))
23121 (t (org-indent-region (point) (min cend end))))
23122 (goto-char (min cend end))
23123 (when (< (point) end)
23124 (funcall indent-to ind (min element-end end))))
23125 (set-marker post nil)
23126 (set-marker cbeg nil)
23127 (set-marker cend nil))))
23128 (set-marker element-end nil))))
23129 (set-marker end nil))))
23131 (defun org-indent-drawer ()
23132 "Indent the drawer at point."
23133 (interactive)
23134 (unless (save-excursion
23135 (beginning-of-line)
23136 (looking-at-p org-drawer-regexp))
23137 (user-error "Not at a drawer"))
23138 (let ((element (org-element-at-point)))
23139 (unless (memq (org-element-type element) '(drawer property-drawer))
23140 (user-error "Not at a drawer"))
23141 (org-with-wide-buffer
23142 (org-indent-region (org-element-property :begin element)
23143 (org-element-property :end element))))
23144 (message "Drawer at point indented"))
23146 (defun org-indent-block ()
23147 "Indent the block at point."
23148 (interactive)
23149 (unless (save-excursion
23150 (beginning-of-line)
23151 (let ((case-fold-search t))
23152 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23153 (user-error "Not at a block"))
23154 (let ((element (org-element-at-point)))
23155 (unless (memq (org-element-type element)
23156 '(comment-block center-block dynamic-block example-block
23157 export-block quote-block special-block
23158 src-block verse-block))
23159 (user-error "Not at a block"))
23160 (org-with-wide-buffer
23161 (org-indent-region (org-element-property :begin element)
23162 (org-element-property :end element))))
23163 (message "Block at point indented"))
23166 ;;; Filling
23168 ;; We use our own fill-paragraph and auto-fill functions.
23170 ;; `org-fill-paragraph' relies on adaptive filling and context
23171 ;; checking. Appropriate `fill-prefix' is computed with
23172 ;; `org-adaptive-fill-function'.
23174 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23175 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23176 ;; `org-adaptive-fill-function' value. Internally,
23177 ;; `org-comment-line-break-function' breaks the line.
23179 ;; `org-setup-filling' installs filling and auto-filling related
23180 ;; variables during `org-mode' initialization.
23182 (defvar org-element-paragraph-separate) ; org-element.el
23183 (defun org-setup-filling ()
23184 (require 'org-element)
23185 ;; Prevent auto-fill from inserting unwanted new items.
23186 (when (boundp 'fill-nobreak-predicate)
23187 (setq-local
23188 fill-nobreak-predicate
23189 (org-uniquify
23190 (append fill-nobreak-predicate
23191 '(org-fill-line-break-nobreak-p
23192 org-fill-paragraph-with-timestamp-nobreak-p)))))
23193 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23194 (setq-local paragraph-start paragraph-ending)
23195 (setq-local paragraph-separate paragraph-ending))
23196 (setq-local fill-paragraph-function 'org-fill-paragraph)
23197 (setq-local auto-fill-inhibit-regexp nil)
23198 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23199 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23200 (setq-local comment-line-break-function 'org-comment-line-break-function))
23202 (defun org-fill-line-break-nobreak-p ()
23203 "Non-nil when a new line at point would create an Org line break."
23204 (save-excursion
23205 (skip-chars-backward "[ \t]")
23206 (skip-chars-backward "\\\\")
23207 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23209 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23210 "Non-nil when a new line at point would split a timestamp."
23211 (and (org-at-timestamp-p t)
23212 (not (looking-at org-ts-regexp-both))))
23214 (declare-function message-in-body-p "message" ())
23215 (defvar orgtbl-line-start-regexp) ; From org-table.el
23216 (defun org-adaptive-fill-function ()
23217 "Compute a fill prefix for the current line.
23218 Return fill prefix, as a string, or nil if current line isn't
23219 meant to be filled. For convenience, if `adaptive-fill-regexp'
23220 matches in paragraphs or comments, use it."
23221 (catch 'exit
23222 (when (derived-mode-p 'message-mode)
23223 (save-excursion
23224 (beginning-of-line)
23225 (cond ((not (message-in-body-p)) (throw 'exit nil))
23226 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23227 ((looking-at message-cite-prefix-regexp)
23228 (throw 'exit (match-string-no-properties 0)))
23229 ((looking-at org-outline-regexp)
23230 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23231 (org-with-wide-buffer
23232 (unless (org-at-heading-p)
23233 (let* ((p (line-beginning-position))
23234 (element (save-excursion
23235 (beginning-of-line)
23236 (org-element-at-point)))
23237 (type (org-element-type element))
23238 (post-affiliated (org-element-property :post-affiliated element)))
23239 (unless (< p post-affiliated)
23240 (cl-case type
23241 (comment
23242 (save-excursion
23243 (beginning-of-line)
23244 (looking-at "[ \t]*")
23245 (concat (match-string 0) "# ")))
23246 (footnote-definition "")
23247 ((item plain-list)
23248 (make-string (org-list-item-body-column post-affiliated) ?\s))
23249 (paragraph
23250 ;; Fill prefix is usually the same as the current line,
23251 ;; unless the paragraph is at the beginning of an item.
23252 (let ((parent (org-element-property :parent element)))
23253 (save-excursion
23254 (beginning-of-line)
23255 (cond ((eq (org-element-type parent) 'item)
23256 (make-string (org-list-item-body-column
23257 (org-element-property :begin parent))
23258 ?\s))
23259 ((and adaptive-fill-regexp
23260 ;; Locally disable
23261 ;; `adaptive-fill-function' to let
23262 ;; `fill-context-prefix' handle
23263 ;; `adaptive-fill-regexp' variable.
23264 (let (adaptive-fill-function)
23265 (fill-context-prefix
23266 post-affiliated
23267 (org-element-property :end element)))))
23268 ((looking-at "[ \t]+") (match-string 0))
23269 (t "")))))
23270 (comment-block
23271 ;; Only fill contents if P is within block boundaries.
23272 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23273 (forward-line)
23274 (point)))
23275 (cend (save-excursion
23276 (goto-char (org-element-property :end element))
23277 (skip-chars-backward " \r\t\n")
23278 (line-beginning-position))))
23279 (when (and (>= p cbeg) (< p cend))
23280 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23281 (match-string 0)
23282 "")))))))))))
23284 (declare-function message-goto-body "message" ())
23285 (defvar message-cite-prefix-regexp) ; From message.el
23286 (defun org-fill-paragraph (&optional justify)
23287 "Fill element at point, when applicable.
23289 This function only applies to comment blocks, comments, example
23290 blocks and paragraphs. Also, as a special case, re-align table
23291 when point is at one.
23293 If JUSTIFY is non-nil (interactively, with prefix argument),
23294 justify as well. If `sentence-end-double-space' is non-nil, then
23295 period followed by one space does not end a sentence, so don't
23296 break a line there. The variable `fill-column' controls the
23297 width for filling.
23299 For convenience, when point is at a plain list, an item or
23300 a footnote definition, try to fill the first paragraph within."
23301 (interactive)
23302 (if (and (derived-mode-p 'message-mode)
23303 (or (not (message-in-body-p))
23304 (save-excursion (move-beginning-of-line 1)
23305 (looking-at message-cite-prefix-regexp))))
23306 ;; First ensure filling is correct in message-mode.
23307 (let ((fill-paragraph-function
23308 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23309 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23310 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23311 (paragraph-separate
23312 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23313 (fill-paragraph nil))
23314 (with-syntax-table org-mode-transpose-word-syntax-table
23315 ;; Move to end of line in order to get the first paragraph
23316 ;; within a plain list or a footnote definition.
23317 (let ((element (save-excursion
23318 (end-of-line)
23319 (or (ignore-errors (org-element-at-point))
23320 (user-error "An element cannot be parsed line %d"
23321 (line-number-at-pos (point)))))))
23322 ;; First check if point is in a blank line at the beginning of
23323 ;; the buffer. In that case, ignore filling.
23324 (cl-case (org-element-type element)
23325 ;; Use major mode filling function is src blocks.
23326 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23327 ;; Align Org tables, leave table.el tables as-is.
23328 (table-row (org-table-align) t)
23329 (table
23330 (when (eq (org-element-property :type element) 'org)
23331 (save-excursion
23332 (goto-char (org-element-property :post-affiliated element))
23333 (org-table-align)))
23335 (paragraph
23336 ;; Paragraphs may contain `line-break' type objects.
23337 (let ((beg (max (point-min)
23338 (org-element-property :contents-begin element)))
23339 (end (min (point-max)
23340 (org-element-property :contents-end element))))
23341 ;; Do nothing if point is at an affiliated keyword.
23342 (if (< (line-end-position) beg) t
23343 (when (derived-mode-p 'message-mode)
23344 ;; In `message-mode', do not fill following citation
23345 ;; in current paragraph nor text before message body.
23346 (let ((body-start (save-excursion (message-goto-body))))
23347 (when body-start (setq beg (max body-start beg))))
23348 (when (save-excursion
23349 (re-search-forward
23350 (concat "^" message-cite-prefix-regexp) end t))
23351 (setq end (match-beginning 0))))
23352 ;; Fill paragraph, taking line breaks into account.
23353 (save-excursion
23354 (goto-char beg)
23355 (let ((cuts (list beg)))
23356 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23357 (when (eq 'line-break
23358 (org-element-type
23359 (save-excursion (backward-char)
23360 (org-element-context))))
23361 (push (point) cuts)))
23362 (dolist (c (delq end cuts))
23363 (fill-region-as-paragraph c end justify)
23364 (setq end c))))
23365 t)))
23366 ;; Contents of `comment-block' type elements should be
23367 ;; filled as plain text, but only if point is within block
23368 ;; markers.
23369 (comment-block
23370 (let* ((case-fold-search t)
23371 (beg (save-excursion
23372 (goto-char (org-element-property :begin element))
23373 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23374 (forward-line)
23375 (point)))
23376 (end (save-excursion
23377 (goto-char (org-element-property :end element))
23378 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23379 (line-beginning-position))))
23380 (if (or (< (point) beg) (> (point) end)) t
23381 (fill-region-as-paragraph
23382 (save-excursion (end-of-line)
23383 (re-search-backward "^[ \t]*$" beg 'move)
23384 (line-beginning-position))
23385 (save-excursion (beginning-of-line)
23386 (re-search-forward "^[ \t]*$" end 'move)
23387 (line-beginning-position))
23388 justify))))
23389 ;; Fill comments.
23390 (comment
23391 (let ((begin (org-element-property :post-affiliated element))
23392 (end (org-element-property :end element)))
23393 (when (and (>= (point) begin) (<= (point) end))
23394 (let ((begin (save-excursion
23395 (end-of-line)
23396 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23397 (progn (forward-line) (point))
23398 begin)))
23399 (end (save-excursion
23400 (end-of-line)
23401 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23402 (1- (line-beginning-position))
23403 (skip-chars-backward " \r\t\n")
23404 (line-end-position)))))
23405 ;; Do not fill comments when at a blank line.
23406 (when (> end begin)
23407 (let ((fill-prefix
23408 (save-excursion
23409 (beginning-of-line)
23410 (looking-at "[ \t]*#")
23411 (let ((comment-prefix (match-string 0)))
23412 (goto-char (match-end 0))
23413 (if (looking-at adaptive-fill-regexp)
23414 (concat comment-prefix (match-string 0))
23415 (concat comment-prefix " "))))))
23416 (save-excursion
23417 (fill-region-as-paragraph begin end justify))))))
23419 ;; Ignore every other element.
23420 (otherwise t))))))
23422 (defun org-auto-fill-function ()
23423 "Auto-fill function."
23424 ;; Check if auto-filling is meaningful.
23425 (let ((fc (current-fill-column)))
23426 (when (and fc (> (current-column) fc))
23427 (let* ((fill-prefix (org-adaptive-fill-function))
23428 ;; Enforce empty fill prefix, if required. Otherwise, it
23429 ;; will be computed again.
23430 (adaptive-fill-mode (not (equal fill-prefix ""))))
23431 (when fill-prefix (do-auto-fill))))))
23433 (defun org-comment-line-break-function (&optional soft)
23434 "Break line at point and indent, continuing comment if within one.
23435 The inserted newline is marked hard if variable
23436 `use-hard-newlines' is true, unless optional argument SOFT is
23437 non-nil."
23438 (if soft (insert-and-inherit ?\n) (newline 1))
23439 (save-excursion (forward-char -1) (delete-horizontal-space))
23440 (delete-horizontal-space)
23441 (indent-to-left-margin)
23442 (insert-before-markers-and-inherit fill-prefix))
23445 ;;; Fixed Width Areas
23447 (defun org-toggle-fixed-width ()
23448 "Toggle fixed-width markup.
23450 Add or remove fixed-width markup on current line, whenever it
23451 makes sense. Return an error otherwise.
23453 If a region is active and if it contains only fixed-width areas
23454 or blank lines, remove all fixed-width markup in it. If the
23455 region contains anything else, convert all non-fixed-width lines
23456 to fixed-width ones.
23458 Blank lines at the end of the region are ignored unless the
23459 region only contains such lines."
23460 (interactive)
23461 (if (not (org-region-active-p))
23462 ;; No region:
23464 ;; Remove fixed width marker only in a fixed-with element.
23466 ;; Add fixed width maker in paragraphs, in blank lines after
23467 ;; elements or at the beginning of a headline or an inlinetask,
23468 ;; and before any one-line elements (e.g., a clock).
23469 (progn
23470 (beginning-of-line)
23471 (let* ((element (org-element-at-point))
23472 (type (org-element-type element)))
23473 (cond
23474 ((and (eq type 'fixed-width)
23475 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23476 (replace-match
23477 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23478 ((and (memq type '(babel-call clock comment diary-sexp headline
23479 horizontal-rule keyword paragraph
23480 planning))
23481 (<= (org-element-property :post-affiliated element) (point)))
23482 (skip-chars-forward " \t")
23483 (insert ": "))
23484 ((and (looking-at-p "[ \t]*$")
23485 (or (eq type 'inlinetask)
23486 (save-excursion
23487 (skip-chars-forward " \r\t\n")
23488 (<= (org-element-property :end element) (point)))))
23489 (delete-region (point) (line-end-position))
23490 (org-indent-line)
23491 (insert ": "))
23492 (t (user-error "Cannot insert a fixed-width line here")))))
23493 ;; Region active.
23494 (let* ((begin (save-excursion
23495 (goto-char (region-beginning))
23496 (line-beginning-position)))
23497 (end (copy-marker
23498 (save-excursion
23499 (goto-char (region-end))
23500 (unless (eolp) (beginning-of-line))
23501 (if (save-excursion (re-search-backward "\\S-" begin t))
23502 (progn (skip-chars-backward " \r\t\n") (point))
23503 (point)))))
23504 (all-fixed-width-p
23505 (catch 'not-all-p
23506 (save-excursion
23507 (goto-char begin)
23508 (skip-chars-forward " \r\t\n")
23509 (when (eobp) (throw 'not-all-p nil))
23510 (while (< (point) end)
23511 (let ((element (org-element-at-point)))
23512 (if (eq (org-element-type element) 'fixed-width)
23513 (goto-char (org-element-property :end element))
23514 (throw 'not-all-p nil))))
23515 t))))
23516 (if all-fixed-width-p
23517 (save-excursion
23518 (goto-char begin)
23519 (while (< (point) end)
23520 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23521 (replace-match
23522 "" nil nil nil
23523 (if (= (line-end-position) (match-end 0)) 0 1)))
23524 (forward-line)))
23525 (let ((min-ind (point-max)))
23526 ;; Find minimum indentation across all lines.
23527 (save-excursion
23528 (goto-char begin)
23529 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23530 (setq min-ind 0)
23531 (catch 'zerop
23532 (while (< (point) end)
23533 (unless (looking-at-p "[ \t]*$")
23534 (let ((ind (org-get-indentation)))
23535 (setq min-ind (min min-ind ind))
23536 (when (zerop ind) (throw 'zerop t))))
23537 (forward-line)))))
23538 ;; Loop over all lines and add fixed-width markup everywhere
23539 ;; but in fixed-width lines.
23540 (save-excursion
23541 (goto-char begin)
23542 (while (< (point) end)
23543 (cond
23544 ((org-at-heading-p)
23545 (insert ": ")
23546 (forward-line)
23547 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23548 (insert ":")
23549 (forward-line)))
23550 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23551 (let* ((element (org-element-at-point))
23552 (element-end (org-element-property :end element)))
23553 (if (eq (org-element-type element) 'fixed-width)
23554 (progn (goto-char element-end)
23555 (skip-chars-backward " \r\t\n")
23556 (forward-line))
23557 (let ((limit (min end element-end)))
23558 (while (< (point) limit)
23559 (org-move-to-column min-ind t)
23560 (insert ": ")
23561 (forward-line))))))
23563 (org-move-to-column min-ind t)
23564 (insert ": ")
23565 (forward-line)))))))
23566 (set-marker end nil))))
23569 ;;; Comments
23571 ;; Org comments syntax is quite complex. It requires the entire line
23572 ;; to be just a comment. Also, even with the right syntax at the
23573 ;; beginning of line, some some elements (i.e. verse-block or
23574 ;; example-block) don't accept comments. Usual Emacs comment commands
23575 ;; cannot cope with those requirements. Therefore, Org replaces them.
23577 ;; Org still relies on `comment-dwim', but cannot trust
23578 ;; `comment-only-p'. So, `comment-region-function' and
23579 ;; `uncomment-region-function' both point
23580 ;; to`org-comment-or-uncomment-region'. Eventually,
23581 ;; `org-insert-comment' takes care of insertion of comments at the
23582 ;; beginning of line.
23584 ;; `org-setup-comments-handling' install comments related variables
23585 ;; during `org-mode' initialization.
23587 (defun org-setup-comments-handling ()
23588 (interactive)
23589 (setq-local comment-use-syntax nil)
23590 (setq-local comment-start "# ")
23591 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23592 (setq-local comment-insert-comment-function 'org-insert-comment)
23593 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23594 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23596 (defun org-insert-comment ()
23597 "Insert an empty comment above current line.
23598 If the line is empty, insert comment at its beginning. When
23599 point is within a source block, comment according to the related
23600 major mode."
23601 (if (let ((element (org-element-at-point)))
23602 (and (eq (org-element-type element) 'src-block)
23603 (< (save-excursion
23604 (goto-char (org-element-property :post-affiliated element))
23605 (line-end-position))
23606 (point))
23607 (> (save-excursion
23608 (goto-char (org-element-property :end element))
23609 (skip-chars-backward " \r\t\n")
23610 (line-beginning-position))
23611 (point))))
23612 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23613 (beginning-of-line)
23614 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23615 (open-line 1))
23616 (org-indent-line)
23617 (insert "# ")))
23619 (defvar comment-empty-lines) ; From newcomment.el.
23620 (defun org-comment-or-uncomment-region (beg end &rest _)
23621 "Comment or uncomment each non-blank line in the region.
23622 Uncomment each non-blank line between BEG and END if it only
23623 contains commented lines. Otherwise, comment them. If region is
23624 strictly within a source block, use appropriate comment syntax."
23625 (if (let ((element (org-element-at-point)))
23626 (and (eq (org-element-type element) 'src-block)
23627 (< (save-excursion
23628 (goto-char (org-element-property :post-affiliated element))
23629 (line-end-position))
23630 beg)
23631 (>= (save-excursion
23632 (goto-char (org-element-property :end element))
23633 (skip-chars-backward " \r\t\n")
23634 (line-beginning-position))
23635 end)))
23636 ;; Translate region boundaries for the Org buffer to the source
23637 ;; buffer.
23638 (let ((offset (- end beg)))
23639 (save-excursion
23640 (goto-char beg)
23641 (org-babel-do-in-edit-buffer
23642 (comment-or-uncomment-region (point) (+ offset (point))))))
23643 (save-restriction
23644 ;; Restrict region
23645 (narrow-to-region (save-excursion (goto-char beg)
23646 (skip-chars-forward " \r\t\n" end)
23647 (line-beginning-position))
23648 (save-excursion (goto-char end)
23649 (skip-chars-backward " \r\t\n" beg)
23650 (line-end-position)))
23651 (let ((uncommentp
23652 ;; UNCOMMENTP is non-nil when every non blank line between
23653 ;; BEG and END is a comment.
23654 (save-excursion
23655 (goto-char (point-min))
23656 (while (and (not (eobp))
23657 (let ((element (org-element-at-point)))
23658 (and (eq (org-element-type element) 'comment)
23659 (goto-char (min (point-max)
23660 (org-element-property
23661 :end element)))))))
23662 (eobp))))
23663 (if uncommentp
23664 ;; Only blank lines and comments in region: uncomment it.
23665 (save-excursion
23666 (goto-char (point-min))
23667 (while (not (eobp))
23668 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23669 (replace-match "" nil nil nil 1))
23670 (forward-line)))
23671 ;; Comment each line in region.
23672 (let ((min-indent (point-max)))
23673 ;; First find the minimum indentation across all lines.
23674 (save-excursion
23675 (goto-char (point-min))
23676 (while (and (not (eobp)) (not (zerop min-indent)))
23677 (unless (looking-at "[ \t]*$")
23678 (setq min-indent (min min-indent (current-indentation))))
23679 (forward-line)))
23680 ;; Then loop over all lines.
23681 (save-excursion
23682 (goto-char (point-min))
23683 (while (not (eobp))
23684 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23685 ;; Don't get fooled by invisible text (e.g. link path)
23686 ;; when moving to column MIN-INDENT.
23687 (let ((buffer-invisibility-spec nil))
23688 (org-move-to-column min-indent t))
23689 (insert comment-start))
23690 (forward-line)))))))))
23692 (defun org-comment-dwim (_arg)
23693 "Call `comment-dwim' within a source edit buffer if needed."
23694 (interactive "*P")
23695 (if (org-in-src-block-p)
23696 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23697 (call-interactively 'comment-dwim)))
23700 ;;; Timestamps API
23702 ;; This section contains tools to operate on timestamp objects, as
23703 ;; returned by, e.g. `org-element-context'.
23705 (defun org-timestamp--to-internal-time (timestamp &optional end)
23706 "Encode TIMESTAMP object into Emacs internal time.
23707 Use end of date range or time range when END is non-nil."
23708 (apply #'encode-time
23709 (cons 0
23710 (mapcar
23711 (lambda (prop) (or (org-element-property prop timestamp) 0))
23712 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23713 '(:minute-start :hour-start :day-start :month-start
23714 :year-start))))))
23716 (defun org-timestamp-has-time-p (timestamp)
23717 "Non-nil when TIMESTAMP has a time specified."
23718 (org-element-property :hour-start timestamp))
23720 (defun org-timestamp-format (timestamp format &optional end utc)
23721 "Format a TIMESTAMP object into a string.
23723 FORMAT is a format specifier to be passed to
23724 `format-time-string'.
23726 When optional argument END is non-nil, use end of date-range or
23727 time-range, if possible.
23729 When optional argument UTC is non-nil, time will be expressed as
23730 Universal Time."
23731 (format-time-string
23732 format (org-timestamp--to-internal-time timestamp end)
23733 (and utc t)))
23735 (defun org-timestamp-split-range (timestamp &optional end)
23736 "Extract a TIMESTAMP object from a date or time range.
23738 END, when non-nil, means extract the end of the range.
23739 Otherwise, extract its start.
23741 Return a new timestamp object."
23742 (let ((type (org-element-property :type timestamp)))
23743 (if (memq type '(active inactive diary)) timestamp
23744 (let ((split-ts (org-element-copy timestamp)))
23745 ;; Set new type.
23746 (org-element-put-property
23747 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23748 ;; Copy start properties over end properties if END is
23749 ;; non-nil. Otherwise, copy end properties over `start' ones.
23750 (let ((p-alist '((:minute-start . :minute-end)
23751 (:hour-start . :hour-end)
23752 (:day-start . :day-end)
23753 (:month-start . :month-end)
23754 (:year-start . :year-end))))
23755 (dolist (p-cell p-alist)
23756 (org-element-put-property
23757 split-ts
23758 (funcall (if end #'car #'cdr) p-cell)
23759 (org-element-property
23760 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23761 ;; Eventually refresh `:raw-value'.
23762 (org-element-put-property split-ts :raw-value nil)
23763 (org-element-put-property
23764 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23766 (defun org-timestamp-translate (timestamp &optional boundary)
23767 "Translate TIMESTAMP object to custom format.
23769 Format string is defined in `org-time-stamp-custom-formats',
23770 which see.
23772 When optional argument BOUNDARY is non-nil, it is either the
23773 symbol `start' or `end'. In this case, only translate the
23774 starting or ending part of TIMESTAMP if it is a date or time
23775 range. Otherwise, translate both parts.
23777 Return timestamp as-is if `org-display-custom-times' is nil or if
23778 it has a `diary' type."
23779 (let ((type (org-element-property :type timestamp)))
23780 (if (or (not org-display-custom-times) (eq type 'diary))
23781 (org-element-interpret-data timestamp)
23782 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23783 org-time-stamp-custom-formats)))
23784 (if (and (not boundary) (memq type '(active-range inactive-range)))
23785 (concat (org-timestamp-format timestamp fmt)
23786 "--"
23787 (org-timestamp-format timestamp fmt t))
23788 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23792 ;;; Other stuff.
23794 (defvar reftex-docstruct-symbol)
23795 (defvar org--rds)
23797 (defun org-reftex-citation ()
23798 "Use reftex-citation to insert a citation into the buffer.
23799 This looks for a line like
23801 #+BIBLIOGRAPHY: foo plain option:-d
23803 and derives from it that foo.bib is the bibliography file relevant
23804 for this document. It then installs the necessary environment for RefTeX
23805 to work in this buffer and calls `reftex-citation' to insert a citation
23806 into the buffer.
23808 Export of such citations to both LaTeX and HTML is handled by the contributed
23809 package ox-bibtex by Taru Karttunen."
23810 (interactive)
23811 (let ((reftex-docstruct-symbol 'org--rds)
23812 org--rds bib)
23813 (org-with-wide-buffer
23814 (let ((case-fold-search t)
23815 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23816 (if (not (save-excursion
23817 (or (re-search-forward re nil t)
23818 (re-search-backward re nil t))))
23819 (user-error "No bibliography defined in file")
23820 (setq bib (concat (match-string 1) ".bib")
23821 org--rds (list (list 'bib bib))))))
23822 (call-interactively 'reftex-citation)))
23824 ;;;; Functions extending outline functionality
23826 (defun org-beginning-of-line (&optional n)
23827 "Go to the beginning of the current visible line.
23829 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23830 tags on the first attempt, and only move to after the tags when
23831 the cursor is already beyond the end of the headline.
23833 With argument N not nil or 1, move forward N - 1 lines first."
23834 (interactive "^p")
23835 (let ((origin (point))
23836 (special (pcase org-special-ctrl-a/e
23837 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23838 deactivate-mark)
23839 ;; First move to a visible line.
23840 (if (bound-and-true-p visual-line-mode)
23841 (beginning-of-visual-line n)
23842 (move-beginning-of-line n)
23843 ;; `move-beginning-of-line' may leave point after invisible
23844 ;; characters if line starts with such of these (e.g., with
23845 ;; a link at column 0). Really move to the beginning of the
23846 ;; current visible line.
23847 (beginning-of-line))
23848 (cond
23849 ;; No special behavior. Point is already at the beginning of
23850 ;; a line, logical or visual.
23851 ((not special))
23852 ;; `beginning-of-visual-line' left point before logical beginning
23853 ;; of line: point is at the beginning of a visual line. Bail
23854 ;; out.
23855 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23856 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23857 ;; At a headline, special position is before the title, but
23858 ;; after any TODO keyword or priority cookie.
23859 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23860 (line-end-position)))
23861 (bol (point)))
23862 (if (eq special 'reversed)
23863 (when (and (= origin bol) (eq last-command this-command))
23864 (goto-char refpos))
23865 (when (or (> origin refpos) (= origin bol))
23866 (goto-char refpos)))))
23867 ((and (looking-at org-list-full-item-re)
23868 (memq (org-element-type (save-match-data (org-element-at-point)))
23869 '(item plain-list)))
23870 ;; Set special position at first white space character after
23871 ;; bullet, and check-box, if any.
23872 (let ((after-bullet
23873 (let ((box (match-end 3)))
23874 (cond ((not box) (match-end 1))
23875 ((eq (char-after box) ?\s) (1+ box))
23876 (t box)))))
23877 (if (eq special 'reversed)
23878 (when (and (= (point) origin) (eq last-command this-command))
23879 (goto-char after-bullet))
23880 (when (or (> origin after-bullet) (= (point) origin))
23881 (goto-char after-bullet)))))
23882 ;; No special context. Point is already at beginning of line.
23883 (t nil))))
23885 (defun org-end-of-line (&optional n)
23886 "Go to the end of the line, but before ellipsis, if any.
23888 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23889 tags on the first attempt, and only move to after the tags when
23890 the cursor is already beyond the end of the headline.
23892 With argument N not nil or 1, move forward N - 1 lines first."
23893 (interactive "^p")
23894 (let ((origin (point))
23895 (special (pcase org-special-ctrl-a/e
23896 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23897 deactivate-mark)
23898 ;; First move to a visible line.
23899 (if (bound-and-true-p visual-line-mode)
23900 (beginning-of-visual-line n)
23901 (move-beginning-of-line n))
23902 (cond
23903 ;; At a headline, with tags.
23904 ((and special
23905 (save-excursion
23906 (beginning-of-line)
23907 (let ((case-fold-search nil))
23908 (looking-at org-complex-heading-regexp)))
23909 (match-end 5))
23910 (let ((tags (save-excursion
23911 (goto-char (match-beginning 5))
23912 (skip-chars-backward " \t")
23913 (point)))
23914 (visual-end (and (bound-and-true-p visual-line-mode)
23915 (save-excursion
23916 (end-of-visual-line)
23917 (point)))))
23918 ;; If `end-of-visual-line' brings us before end of line or
23919 ;; even tags, i.e., the headline spans over multiple visual
23920 ;; lines, move there.
23921 (cond ((and visual-end
23922 (< visual-end tags)
23923 (<= origin visual-end))
23924 (goto-char visual-end))
23925 ((eq special 'reversed)
23926 (if (and (= origin (line-end-position))
23927 (eq this-command last-command))
23928 (goto-char tags)
23929 (end-of-line)))
23931 (if (or (< origin tags) (= origin (line-end-position)))
23932 (goto-char tags)
23933 (end-of-line))))))
23934 ((bound-and-true-p visual-line-mode)
23935 (let ((bol (line-beginning-position)))
23936 (end-of-visual-line)
23937 ;; If `end-of-visual-line' gets us past the ellipsis at the
23938 ;; end of a line, backtrack and use `end-of-line' instead.
23939 (when (/= bol (line-beginning-position))
23940 (goto-char bol)
23941 (end-of-line))))
23942 (t (end-of-line)))))
23944 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23945 (define-key org-mode-map "\C-e" 'org-end-of-line)
23947 (defun org-backward-sentence (&optional _arg)
23948 "Go to beginning of sentence, or beginning of table field.
23949 This will call `backward-sentence' or `org-table-beginning-of-field',
23950 depending on context."
23951 (interactive)
23952 (let* ((element (org-element-at-point))
23953 (contents-begin (org-element-property :contents-begin element))
23954 (table (org-element-lineage element '(table) t)))
23955 (if (and table
23956 (> (point) contents-begin)
23957 (<= (point) (org-element-property :contents-end table)))
23958 (call-interactively #'org-table-beginning-of-field)
23959 (save-restriction
23960 (when (and contents-begin
23961 (< (point-min) contents-begin)
23962 (> (point) contents-begin))
23963 (narrow-to-region contents-begin
23964 (org-element-property :contents-end element)))
23965 (call-interactively #'backward-sentence)))))
23967 (defun org-forward-sentence (&optional _arg)
23968 "Go to end of sentence, or end of table field.
23969 This will call `forward-sentence' or `org-table-end-of-field',
23970 depending on context."
23971 (interactive)
23972 (let* ((element (org-element-at-point))
23973 (contents-end (org-element-property :contents-end element))
23974 (table (org-element-lineage element '(table) t)))
23975 (if (and table
23976 (>= (point) (org-element-property :contents-begin table))
23977 (< (point) contents-end))
23978 (call-interactively #'org-table-end-of-field)
23979 (save-restriction
23980 (when (and contents-end
23981 (> (point-max) contents-end)
23982 ;; Skip blank lines between elements.
23983 (< (org-element-property :end element)
23984 (save-excursion (goto-char contents-end)
23985 (skip-chars-forward " \r\t\n"))))
23986 (narrow-to-region (org-element-property :contents-begin element)
23987 contents-end))
23988 (call-interactively #'forward-sentence)))))
23990 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23991 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23993 (defun org-kill-line (&optional _arg)
23994 "Kill line, to tags or end of line."
23995 (interactive)
23996 (cond
23997 ((or (not org-special-ctrl-k)
23998 (bolp)
23999 (not (org-at-heading-p)))
24000 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
24001 org-ctrl-k-protect-subtree
24002 (or (eq org-ctrl-k-protect-subtree 'error)
24003 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
24004 (user-error "C-k aborted as it would kill a hidden subtree"))
24005 (call-interactively
24006 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
24007 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
24008 (kill-region (point) (match-beginning 1))
24009 (org-set-tags nil t))
24010 (t (kill-region (point) (point-at-eol)))))
24012 (define-key org-mode-map "\C-k" 'org-kill-line)
24014 (defun org-yank (&optional arg)
24015 "Yank. If the kill is a subtree, treat it specially.
24016 This command will look at the current kill and check if is a single
24017 subtree, or a series of subtrees[1]. If it passes the test, and if the
24018 cursor is at the beginning of a line or after the stars of a currently
24019 empty headline, then the yank is handled specially. How exactly depends
24020 on the value of the following variables.
24022 `org-yank-folded-subtrees'
24023 By default, this variable is non-nil, which results in
24024 subtree(s) being folded after insertion, except if doing so
24025 would swallow text after the yanked text.
24027 `org-yank-adjusted-subtrees'
24028 When non-nil (the default value is nil), the subtree will be
24029 promoted or demoted in order to fit into the local outline tree
24030 structure, which means that the level will be adjusted so that it
24031 becomes the smaller one of the two *visible* surrounding headings.
24033 Any prefix to this command will cause `yank' to be called directly with
24034 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
24035 will just
24036 plainly yank the text as it is.
24038 \[1] The test checks if the first non-white line is a heading
24039 and if there are no other headings with fewer stars."
24040 (interactive "P")
24041 (org-yank-generic 'yank arg))
24043 (defun org-yank-generic (command arg)
24044 "Perform some yank-like command.
24046 This function implements the behavior described in the `org-yank'
24047 documentation. However, it has been generalized to work for any
24048 interactive command with similar behavior."
24050 ;; pretend to be command COMMAND
24051 (setq this-command command)
24053 (if arg
24054 (call-interactively command)
24056 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24057 (and (org-kill-is-subtree-p)
24058 (or (bolp)
24059 (and (looking-at "[ \t]*$")
24060 (string-match
24061 "\\`\\*+\\'"
24062 (buffer-substring (point-at-bol) (point)))))))
24063 swallowp)
24064 (cond
24065 ((and subtreep org-yank-folded-subtrees)
24066 (let ((beg (point))
24067 end)
24068 (if (and subtreep org-yank-adjusted-subtrees)
24069 (org-paste-subtree nil nil 'for-yank)
24070 (call-interactively command))
24072 (setq end (point))
24073 (goto-char beg)
24074 (when (and (bolp) subtreep
24075 (not (setq swallowp
24076 (org-yank-folding-would-swallow-text beg end))))
24077 (org-with-limited-levels
24078 (or (looking-at org-outline-regexp)
24079 (re-search-forward org-outline-regexp-bol end t))
24080 (while (and (< (point) end) (looking-at org-outline-regexp))
24081 (outline-hide-subtree)
24082 (org-cycle-show-empty-lines 'folded)
24083 (condition-case nil
24084 (outline-forward-same-level 1)
24085 (error (goto-char end))))))
24086 (when swallowp
24087 (message
24088 "Inserted text not folded because that would swallow text"))
24090 (goto-char end)
24091 (skip-chars-forward " \t\n\r")
24092 (beginning-of-line 1)
24093 (push-mark beg 'nomsg)))
24094 ((and subtreep org-yank-adjusted-subtrees)
24095 (let ((beg (point-at-bol)))
24096 (org-paste-subtree nil nil 'for-yank)
24097 (push-mark beg 'nomsg)))
24099 (call-interactively command))))))
24101 (defun org-yank-folding-would-swallow-text (beg end)
24102 "Would hide-subtree at BEG swallow any text after END?"
24103 (let (level)
24104 (org-with-limited-levels
24105 (save-excursion
24106 (goto-char beg)
24107 (when (or (looking-at org-outline-regexp)
24108 (re-search-forward org-outline-regexp-bol end t))
24109 (setq level (org-outline-level)))
24110 (goto-char end)
24111 (skip-chars-forward " \t\r\n\v\f")
24112 (not (or (eobp)
24113 (and (bolp) (looking-at-p org-outline-regexp)
24114 (<= (org-outline-level) level))))))))
24116 (define-key org-mode-map "\C-y" 'org-yank)
24118 (defun org-truely-invisible-p ()
24119 "Check if point is at a character currently not visible.
24120 This version does not only check the character property, but also
24121 `visible-mode'."
24122 ;; Early versions of noutline don't have `outline-invisible-p'.
24123 (unless (bound-and-true-p visible-mode)
24124 (outline-invisible-p)))
24126 (defun org-invisible-p2 ()
24127 "Check if point is at a character currently not visible."
24128 (save-excursion
24129 (when (and (eolp) (not (bobp))) (backward-char 1))
24130 ;; Early versions of noutline don't have `outline-invisible-p'.
24131 (outline-invisible-p)))
24133 (defun org-back-to-heading (&optional invisible-ok)
24134 "Call `outline-back-to-heading', but provide a better error message."
24135 (condition-case nil
24136 (outline-back-to-heading invisible-ok)
24137 (error (error "Before first headline at position %d in buffer %s"
24138 (point) (current-buffer)))))
24140 (defun org-before-first-heading-p ()
24141 "Before first heading?"
24142 (save-excursion
24143 (end-of-line)
24144 (null (re-search-backward org-outline-regexp-bol nil t))))
24146 (defun org-at-heading-p (&optional ignored)
24147 (outline-on-heading-p t))
24149 (defun org-in-commented-heading-p (&optional no-inheritance)
24150 "Non-nil if point is under a commented heading.
24151 This function also checks ancestors of the current headline,
24152 unless optional argument NO-INHERITANCE is non-nil."
24153 (cond
24154 ((org-before-first-heading-p) nil)
24155 ((let ((headline (nth 4 (org-heading-components))))
24156 (and headline
24157 (let ((case-fold-search nil))
24158 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24159 headline)))))
24160 (no-inheritance nil)
24162 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24164 (defun org-at-comment-p nil
24165 "Is cursor in a commented line?"
24166 (save-excursion
24167 (save-match-data
24168 (beginning-of-line)
24169 (looking-at "^[ \t]*# "))))
24171 (defun org-at-drawer-p nil
24172 "Is cursor at a drawer keyword?"
24173 (save-excursion
24174 (move-beginning-of-line 1)
24175 (looking-at org-drawer-regexp)))
24177 (defun org-at-block-p nil
24178 "Is cursor at a block keyword?"
24179 (save-excursion
24180 (move-beginning-of-line 1)
24181 (looking-at org-block-regexp)))
24183 (defun org-point-at-end-of-empty-headline ()
24184 "If point is at the end of an empty headline, return t, else nil.
24185 If the heading only contains a TODO keyword, it is still still considered
24186 empty."
24187 (let ((case-fold-search nil))
24188 (and (looking-at "[ \t]*$")
24189 org-todo-line-regexp
24190 (save-excursion
24191 (beginning-of-line)
24192 (looking-at org-todo-line-regexp)
24193 (string= (match-string 3) "")))))
24195 (defun org-at-heading-or-item-p ()
24196 (or (org-at-heading-p) (org-at-item-p)))
24198 (defun org-at-target-p ()
24199 (or (org-in-regexp org-radio-target-regexp)
24200 (org-in-regexp org-target-regexp)))
24201 ;; Compatibility alias with Org versions < 7.8.03
24202 (defalias 'org-on-target-p 'org-at-target-p)
24204 (defun org-up-heading-all (arg)
24205 "Move to the heading line of which the present line is a subheading.
24206 This function considers both visible and invisible heading lines.
24207 With argument, move up ARG levels."
24208 (outline-up-heading arg t))
24210 (defun org-up-heading-safe ()
24211 "Move to the heading line of which the present line is a subheading.
24212 This version will not throw an error. It will return the level of the
24213 headline found, or nil if no higher level is found.
24215 Also, this function will be a lot faster than `outline-up-heading',
24216 because it relies on stars being the outline starters. This can really
24217 make a significant difference in outlines with very many siblings."
24218 (when (ignore-errors (org-back-to-heading t))
24219 (let ((level-up (1- (funcall outline-level))))
24220 (and (> level-up 0)
24221 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24222 (funcall outline-level)))))
24224 (defun org-first-sibling-p ()
24225 "Is this heading the first child of its parents?"
24226 (interactive)
24227 (let ((re org-outline-regexp-bol)
24228 level l)
24229 (unless (org-at-heading-p t)
24230 (user-error "Not at a heading"))
24231 (setq level (funcall outline-level))
24232 (save-excursion
24233 (if (not (re-search-backward re nil t))
24235 (setq l (funcall outline-level))
24236 (< l level)))))
24238 (defun org-goto-sibling (&optional previous)
24239 "Goto the next sibling, even if it is invisible.
24240 When PREVIOUS is set, go to the previous sibling instead. Returns t
24241 when a sibling was found. When none is found, return nil and don't
24242 move point."
24243 (let ((fun (if previous 're-search-backward 're-search-forward))
24244 (pos (point))
24245 (re org-outline-regexp-bol)
24246 level l)
24247 (when (ignore-errors (org-back-to-heading t))
24248 (setq level (funcall outline-level))
24249 (catch 'exit
24250 (or previous (forward-char 1))
24251 (while (funcall fun re nil t)
24252 (setq l (funcall outline-level))
24253 (when (< l level) (goto-char pos) (throw 'exit nil))
24254 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24255 (goto-char pos)
24256 nil))))
24258 (defun org-show-siblings ()
24259 "Show all siblings of the current headline."
24260 (save-excursion
24261 (while (org-goto-sibling) (org-flag-heading nil)))
24262 (save-excursion
24263 (while (org-goto-sibling 'previous)
24264 (org-flag-heading nil))))
24266 (defun org-goto-first-child ()
24267 "Goto the first child, even if it is invisible.
24268 Return t when a child was found. Otherwise don't move point and
24269 return nil."
24270 (let (level (pos (point)) (re org-outline-regexp-bol))
24271 (when (ignore-errors (org-back-to-heading t))
24272 (setq level (outline-level))
24273 (forward-char 1)
24274 (if (and (re-search-forward re nil t) (> (outline-level) level))
24275 (progn (goto-char (match-beginning 0)) t)
24276 (goto-char pos) nil))))
24278 (defun org-show-hidden-entry ()
24279 "Show an entry where even the heading is hidden."
24280 (save-excursion
24281 (org-show-entry)))
24283 (defun org-flag-heading (flag &optional entry)
24284 "Flag the current heading. FLAG non-nil means make invisible.
24285 When ENTRY is non-nil, show the entire entry."
24286 (save-excursion
24287 (org-back-to-heading t)
24288 ;; Check if we should show the entire entry
24289 (if entry
24290 (progn
24291 (org-show-entry)
24292 (save-excursion
24293 (and (outline-next-heading)
24294 (org-flag-heading nil))))
24295 (outline-flag-region (max (point-min) (1- (point)))
24296 (save-excursion (outline-end-of-heading) (point))
24297 flag))))
24299 (defun org-get-next-sibling ()
24300 "Move to next heading of the same level, and return point.
24301 If there is no such heading, return nil.
24302 This is like outline-next-sibling, but invisible headings are ok."
24303 (let ((level (funcall outline-level)))
24304 (outline-next-heading)
24305 (while (and (not (eobp)) (> (funcall outline-level) level))
24306 (outline-next-heading))
24307 (unless (or (eobp) (< (funcall outline-level) level))
24308 (point))))
24310 (defun org-get-last-sibling ()
24311 "Move to previous heading of the same level, and return point.
24312 If there is no such heading, return nil."
24313 (let ((opoint (point))
24314 (level (funcall outline-level)))
24315 (outline-previous-heading)
24316 (when (and (/= (point) opoint) (outline-on-heading-p t))
24317 (while (and (> (funcall outline-level) level)
24318 (not (bobp)))
24319 (outline-previous-heading))
24320 (unless (< (funcall outline-level) level)
24321 (point)))))
24323 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24324 "Goto to the end of a subtree."
24325 ;; This contains an exact copy of the original function, but it uses
24326 ;; `org-back-to-heading', to make it work also in invisible
24327 ;; trees. And is uses an invisible-ok argument.
24328 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24329 ;; Furthermore, when used inside Org, finding the end of a large subtree
24330 ;; with many children and grandchildren etc, this can be much faster
24331 ;; than the outline version.
24332 (org-back-to-heading invisible-ok)
24333 (let ((first t)
24334 (level (funcall outline-level)))
24335 (if (and (derived-mode-p 'org-mode) (< level 1000))
24336 ;; A true heading (not a plain list item), in Org
24337 ;; This means we can easily find the end by looking
24338 ;; only for the right number of stars. Using a regexp to do
24339 ;; this is so much faster than using a Lisp loop.
24340 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24341 (forward-char 1)
24342 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24343 ;; something else, do it the slow way
24344 (while (and (not (eobp))
24345 (or first (> (funcall outline-level) level)))
24346 (setq first nil)
24347 (outline-next-heading)))
24348 (unless to-heading
24349 (when (memq (preceding-char) '(?\n ?\^M))
24350 ;; Go to end of line before heading
24351 (forward-char -1)
24352 (when (memq (preceding-char) '(?\n ?\^M))
24353 ;; leave blank line before heading
24354 (forward-char -1)))))
24355 (point))
24357 (defun org-end-of-meta-data (&optional full)
24358 "Skip planning line and properties drawer in current entry.
24359 When optional argument FULL is non-nil, also skip empty lines,
24360 clocking lines and regular drawers at the beginning of the
24361 entry."
24362 (org-back-to-heading t)
24363 (forward-line)
24364 (when (looking-at-p org-planning-line-re) (forward-line))
24365 (when (looking-at org-property-drawer-re)
24366 (goto-char (match-end 0))
24367 (forward-line))
24368 (when (and full (not (org-at-heading-p)))
24369 (catch 'exit
24370 (let ((end (save-excursion (outline-next-heading) (point)))
24371 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24372 (while (not (eobp))
24373 (cond ((looking-at-p org-drawer-regexp)
24374 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24375 (forward-line)
24376 (throw 'exit t)))
24377 ((looking-at-p re) (forward-line))
24378 (t (throw 'exit t))))))))
24380 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24381 "Move forward to the ARG'th subheading at same level as this one.
24382 Stop at the first and last subheadings of a superior heading.
24383 Normally this only looks at visible headings, but when INVISIBLE-OK is
24384 non-nil it will also look at invisible ones."
24385 (interactive "p")
24386 (let ((backward? (and arg (< arg 0))))
24387 (if (org-before-first-heading-p)
24388 (if backward? (goto-char (point-min)) (outline-next-heading))
24389 (org-back-to-heading invisible-ok)
24390 (unless backward? (end-of-line)) ;do not match current headline
24391 (let ((level (- (match-end 0) (match-beginning 0) 1))
24392 (f (if backward? #'re-search-backward #'re-search-forward))
24393 (count (if arg (abs arg) 1))
24394 (result (point)))
24395 (while (and (> count 0)
24396 (funcall f org-outline-regexp-bol nil 'move))
24397 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24398 (cond ((< l level) (setq count 0))
24399 ((and (= l level)
24400 (or invisible-ok
24401 (not (outline-invisible-p
24402 (line-beginning-position)))))
24403 (cl-decf count)
24404 (when (= l level) (setq result (point)))))))
24405 (goto-char result))
24406 (beginning-of-line))))
24408 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24409 "Move backward to the ARG'th subheading at same level as this one.
24410 Stop at the first and last subheadings of a superior heading."
24411 (interactive "p")
24412 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24414 (defun org-next-visible-heading (arg)
24415 "Move to the next visible heading.
24417 This function wraps `outline-next-visible-heading' with
24418 `org-with-limited-levels' in order to skip over inline tasks and
24419 respect customization of `org-odd-levels-only'."
24420 (interactive "p")
24421 (org-with-limited-levels
24422 (outline-next-visible-heading arg)))
24424 (defun org-previous-visible-heading (arg)
24425 "Move to the previous visible heading.
24427 This function wraps `outline-previous-visible-heading' with
24428 `org-with-limited-levels' in order to skip over inline tasks and
24429 respect customization of `org-odd-levels-only'."
24430 (interactive "p")
24431 (org-with-limited-levels
24432 (outline-previous-visible-heading arg)))
24434 (defun org-next-block (arg &optional backward block-regexp)
24435 "Jump to the next block.
24437 With a prefix argument ARG, jump forward ARG many blocks.
24439 When BACKWARD is non-nil, jump to the previous block.
24441 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24442 Match data is set according to this regexp when the function
24443 returns.
24445 Return point at beginning of the opening line of found block.
24446 Throw an error if no block is found."
24447 (interactive "p")
24448 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24449 (case-fold-search t)
24450 (search-fn (if backward #'re-search-backward #'re-search-forward))
24451 (count (or arg 1))
24452 (origin (point))
24453 last-element)
24454 (if backward (beginning-of-line) (end-of-line))
24455 (while (and (> count 0) (funcall search-fn re nil t))
24456 (let ((element (save-excursion
24457 (goto-char (match-beginning 0))
24458 (save-match-data (org-element-at-point)))))
24459 (when (and (memq (org-element-type element)
24460 '(center-block comment-block dynamic-block
24461 example-block export-block quote-block
24462 special-block src-block verse-block))
24463 (<= (match-beginning 0)
24464 (org-element-property :post-affiliated element)))
24465 (setq last-element element)
24466 (cl-decf count))))
24467 (if (= count 0)
24468 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24469 (save-match-data (org-show-context)))
24470 (goto-char origin)
24471 (user-error "No %s code blocks" (if backward "previous" "further")))))
24473 (defun org-previous-block (arg &optional block-regexp)
24474 "Jump to the previous block.
24475 With a prefix argument ARG, jump backward ARG many source blocks.
24476 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24477 (interactive "p")
24478 (org-next-block arg t block-regexp))
24480 (defun org-forward-paragraph ()
24481 "Move forward to beginning of next paragraph or equivalent.
24483 The function moves point to the beginning of the next visible
24484 structural element, which can be a paragraph, a table, a list
24485 item, etc. It also provides some special moves for convenience:
24487 - On an affiliated keyword, jump to the beginning of the
24488 relative element.
24489 - On an item or a footnote definition, move to the second
24490 element inside, if any.
24491 - On a table or a property drawer, jump after it.
24492 - On a verse or source block, stop after blank lines."
24493 (interactive)
24494 (when (eobp) (user-error "Cannot move further down"))
24495 (let* ((deactivate-mark nil)
24496 (element (org-element-at-point))
24497 (type (org-element-type element))
24498 (post-affiliated (org-element-property :post-affiliated element))
24499 (contents-begin (org-element-property :contents-begin element))
24500 (contents-end (org-element-property :contents-end element))
24501 (end (let ((end (org-element-property :end element)) (parent element))
24502 (while (and (setq parent (org-element-property :parent parent))
24503 (= (org-element-property :contents-end parent) end))
24504 (setq end (org-element-property :end parent)))
24505 end)))
24506 (cond ((not element)
24507 (skip-chars-forward " \r\t\n")
24508 (or (eobp) (beginning-of-line)))
24509 ;; On affiliated keywords, move to element's beginning.
24510 ((< (point) post-affiliated)
24511 (goto-char post-affiliated))
24512 ;; At a table row, move to the end of the table. Similarly,
24513 ;; at a node property, move to the end of the property
24514 ;; drawer.
24515 ((memq type '(node-property table-row))
24516 (goto-char (org-element-property
24517 :end (org-element-property :parent element))))
24518 ((memq type '(property-drawer table)) (goto-char end))
24519 ;; Consider blank lines as separators in verse and source
24520 ;; blocks to ease editing.
24521 ((memq type '(src-block verse-block))
24522 (when (eq type 'src-block)
24523 (setq contents-end
24524 (save-excursion (goto-char end)
24525 (skip-chars-backward " \r\t\n")
24526 (line-beginning-position))))
24527 (beginning-of-line)
24528 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24529 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24530 (goto-char end)
24531 (skip-chars-forward " \r\t\n")
24532 (if (= (point) contents-end) (goto-char end)
24533 (beginning-of-line))))
24534 ;; With no contents, just skip element.
24535 ((not contents-begin) (goto-char end))
24536 ;; If contents are invisible, skip the element altogether.
24537 ((outline-invisible-p (line-end-position))
24538 (cl-case type
24539 (headline
24540 (org-with-limited-levels (outline-next-visible-heading 1)))
24541 ;; At a plain list, make sure we move to the next item
24542 ;; instead of skipping the whole list.
24543 (plain-list (forward-char)
24544 (org-forward-paragraph))
24545 (otherwise (goto-char end))))
24546 ((>= (point) contents-end) (goto-char end))
24547 ((>= (point) contents-begin)
24548 ;; This can only happen on paragraphs and plain lists.
24549 (cl-case type
24550 (paragraph (goto-char end))
24551 ;; At a plain list, try to move to second element in
24552 ;; first item, if possible.
24553 (plain-list (end-of-line)
24554 (org-forward-paragraph))))
24555 ;; When contents start on the middle of a line (e.g. in
24556 ;; items and footnote definitions), try to reach first
24557 ;; element starting after current line.
24558 ((> (line-end-position) contents-begin)
24559 (end-of-line)
24560 (org-forward-paragraph))
24561 (t (goto-char contents-begin)))))
24563 (defun org-backward-paragraph ()
24564 "Move backward to start of previous paragraph or equivalent.
24566 The function moves point to the beginning of the current
24567 structural element, which can be a paragraph, a table, a list
24568 item, etc., or to the beginning of the previous visible one if
24569 point is already there. It also provides some special moves for
24570 convenience:
24572 - On an affiliated keyword, jump to the first one.
24573 - On a table or a property drawer, move to its beginning.
24574 - On a verse or source block, stop before blank lines."
24575 (interactive)
24576 (when (bobp) (user-error "Cannot move further up"))
24577 (let* ((deactivate-mark nil)
24578 (element (org-element-at-point))
24579 (type (org-element-type element))
24580 (contents-begin (org-element-property :contents-begin element))
24581 (contents-end (org-element-property :contents-end element))
24582 (post-affiliated (org-element-property :post-affiliated element))
24583 (begin (org-element-property :begin element)))
24584 (cond
24585 ((not element) (goto-char (point-min)))
24586 ((= (point) begin)
24587 (backward-char)
24588 (org-backward-paragraph))
24589 ((<= (point) post-affiliated) (goto-char begin))
24590 ((memq type '(node-property table-row))
24591 (goto-char (org-element-property
24592 :post-affiliated (org-element-property :parent element))))
24593 ((memq type '(property-drawer table)) (goto-char begin))
24594 ((memq type '(src-block verse-block))
24595 (when (eq type 'src-block)
24596 (setq contents-begin
24597 (save-excursion (goto-char begin) (forward-line) (point))))
24598 (if (= (point) contents-begin) (goto-char post-affiliated)
24599 ;; Inside a verse block, see blank lines as paragraph
24600 ;; separators.
24601 (let ((origin (point)))
24602 (skip-chars-backward " \r\t\n" contents-begin)
24603 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24604 (skip-chars-forward " \r\t\n" origin)
24605 (if (= (point) origin) (goto-char contents-begin)
24606 (beginning-of-line))))))
24607 ((not contents-begin) (goto-char (or post-affiliated begin)))
24608 ((eq type 'paragraph)
24609 (goto-char contents-begin)
24610 ;; When at first paragraph in an item or a footnote definition,
24611 ;; move directly to beginning of line.
24612 (let ((parent-contents
24613 (org-element-property
24614 :contents-begin (org-element-property :parent element))))
24615 (when (and parent-contents (= parent-contents contents-begin))
24616 (beginning-of-line))))
24617 ;; At the end of a greater element, move to the beginning of the
24618 ;; last element within.
24619 ((>= (point) contents-end)
24620 (goto-char (1- contents-end))
24621 (org-backward-paragraph))
24622 (t (goto-char (or post-affiliated begin))))
24623 ;; Ensure we never leave point invisible.
24624 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24626 (defun org-forward-element ()
24627 "Move forward by one element.
24628 Move to the next element at the same level, when possible."
24629 (interactive)
24630 (cond ((eobp) (user-error "Cannot move further down"))
24631 ((org-with-limited-levels (org-at-heading-p))
24632 (let ((origin (point)))
24633 (goto-char (org-end-of-subtree nil t))
24634 (unless (org-with-limited-levels (org-at-heading-p))
24635 (goto-char origin)
24636 (user-error "Cannot move further down"))))
24638 (let* ((elem (org-element-at-point))
24639 (end (org-element-property :end elem))
24640 (parent (org-element-property :parent elem)))
24641 (cond ((and parent (= (org-element-property :contents-end parent) end))
24642 (goto-char (org-element-property :end parent)))
24643 ((integer-or-marker-p end) (goto-char end))
24644 (t (message "No element at point")))))))
24646 (defun org-backward-element ()
24647 "Move backward by one element.
24648 Move to the previous element at the same level, when possible."
24649 (interactive)
24650 (cond ((bobp) (user-error "Cannot move further up"))
24651 ((org-with-limited-levels (org-at-heading-p))
24652 ;; At a headline, move to the previous one, if any, or stay
24653 ;; here.
24654 (let ((origin (point)))
24655 (org-with-limited-levels (org-backward-heading-same-level 1))
24656 ;; When current headline has no sibling above, move to its
24657 ;; parent.
24658 (when (= (point) origin)
24659 (or (org-with-limited-levels (org-up-heading-safe))
24660 (progn (goto-char origin)
24661 (user-error "Cannot move further up"))))))
24663 (let* ((elem (org-element-at-point))
24664 (beg (org-element-property :begin elem)))
24665 (cond
24666 ;; Move to beginning of current element if point isn't
24667 ;; there already.
24668 ((null beg) (message "No element at point"))
24669 ((/= (point) beg) (goto-char beg))
24670 (t (goto-char beg)
24671 (skip-chars-backward " \r\t\n")
24672 (unless (bobp)
24673 (let ((prev (org-element-at-point)))
24674 (goto-char (org-element-property :begin prev))
24675 (while (and (setq prev (org-element-property :parent prev))
24676 (<= (org-element-property :end prev) beg))
24677 (goto-char (org-element-property :begin prev)))))))))))
24679 (defun org-up-element ()
24680 "Move to upper element."
24681 (interactive)
24682 (if (org-with-limited-levels (org-at-heading-p))
24683 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24684 (let* ((elem (org-element-at-point))
24685 (parent (org-element-property :parent elem)))
24686 (if parent (goto-char (org-element-property :begin parent))
24687 (if (org-with-limited-levels (org-before-first-heading-p))
24688 (user-error "No surrounding element")
24689 (org-with-limited-levels (org-back-to-heading)))))))
24691 (defvar org-element-greater-elements)
24692 (defun org-down-element ()
24693 "Move to inner element."
24694 (interactive)
24695 (let ((element (org-element-at-point)))
24696 (cond
24697 ((memq (org-element-type element) '(plain-list table))
24698 (goto-char (org-element-property :contents-begin element))
24699 (forward-char))
24700 ((memq (org-element-type element) org-element-greater-elements)
24701 ;; If contents are hidden, first disclose them.
24702 (when (outline-invisible-p (line-end-position)) (org-cycle))
24703 (goto-char (or (org-element-property :contents-begin element)
24704 (user-error "No content for this element"))))
24705 (t (user-error "No inner element")))))
24707 (defun org-drag-element-backward ()
24708 "Move backward element at point."
24709 (interactive)
24710 (let ((elem (or (org-element-at-point)
24711 (user-error "No element at point"))))
24712 (if (eq (org-element-type elem) 'headline)
24713 ;; Preserve point when moving a whole tree, even if point was
24714 ;; on blank lines below the headline.
24715 (let ((offset (skip-chars-backward " \t\n")))
24716 (unwind-protect (org-move-subtree-up)
24717 (forward-char (- offset))))
24718 (let ((prev-elem
24719 (save-excursion
24720 (goto-char (org-element-property :begin elem))
24721 (skip-chars-backward " \r\t\n")
24722 (unless (bobp)
24723 (let* ((beg (org-element-property :begin elem))
24724 (prev (org-element-at-point))
24725 (up prev))
24726 (while (and (setq up (org-element-property :parent up))
24727 (<= (org-element-property :end up) beg))
24728 (setq prev up))
24729 prev)))))
24730 ;; Error out if no previous element or previous element is
24731 ;; a parent of the current one.
24732 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24733 (user-error "Cannot drag element backward")
24734 (let ((pos (point)))
24735 (org-element-swap-A-B prev-elem elem)
24736 (goto-char (+ (org-element-property :begin prev-elem)
24737 (- pos (org-element-property :begin elem))))))))))
24739 (defun org-drag-element-forward ()
24740 "Move forward element at point."
24741 (interactive)
24742 (let* ((pos (point))
24743 (elem (or (org-element-at-point)
24744 (user-error "No element at point"))))
24745 (when (= (point-max) (org-element-property :end elem))
24746 (user-error "Cannot drag element forward"))
24747 (goto-char (org-element-property :end elem))
24748 (let ((next-elem (org-element-at-point)))
24749 (when (or (org-element-nested-p elem next-elem)
24750 (and (eq (org-element-type next-elem) 'headline)
24751 (not (eq (org-element-type elem) 'headline))))
24752 (goto-char pos)
24753 (user-error "Cannot drag element forward"))
24754 ;; Compute new position of point: it's shifted by NEXT-ELEM
24755 ;; body's length (without final blanks) and by the length of
24756 ;; blanks between ELEM and NEXT-ELEM.
24757 (let ((size-next (- (save-excursion
24758 (goto-char (org-element-property :end next-elem))
24759 (skip-chars-backward " \r\t\n")
24760 (forward-line)
24761 ;; Small correction if buffer doesn't end
24762 ;; with a newline character.
24763 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24764 (org-element-property :begin next-elem)))
24765 (size-blank (- (org-element-property :end elem)
24766 (save-excursion
24767 (goto-char (org-element-property :end elem))
24768 (skip-chars-backward " \r\t\n")
24769 (forward-line)
24770 (point)))))
24771 (org-element-swap-A-B elem next-elem)
24772 (goto-char (+ pos size-next size-blank))))))
24774 (defun org-drag-line-forward (arg)
24775 "Drag the line at point ARG lines forward."
24776 (interactive "p")
24777 (dotimes (_ (abs arg))
24778 (let ((c (current-column)))
24779 (if (< 0 arg)
24780 (progn
24781 (beginning-of-line 2)
24782 (transpose-lines 1)
24783 (beginning-of-line 0))
24784 (transpose-lines 1)
24785 (beginning-of-line -1))
24786 (org-move-to-column c))))
24788 (defun org-drag-line-backward (arg)
24789 "Drag the line at point ARG lines backward."
24790 (interactive "p")
24791 (org-drag-line-forward (- arg)))
24793 (defun org-mark-element ()
24794 "Put point at beginning of this element, mark at end.
24796 Interactively, if this command is repeated or (in Transient Mark
24797 mode) if the mark is active, it marks the next element after the
24798 ones already marked."
24799 (interactive)
24800 (let (deactivate-mark)
24801 (if (and (called-interactively-p 'any)
24802 (or (and (eq last-command this-command) (mark t))
24803 (and transient-mark-mode mark-active)))
24804 (set-mark
24805 (save-excursion
24806 (goto-char (mark))
24807 (goto-char (org-element-property :end (org-element-at-point)))))
24808 (let ((element (org-element-at-point)))
24809 (end-of-line)
24810 (push-mark (org-element-property :end element) t t)
24811 (goto-char (org-element-property :begin element))))))
24813 (defun org-narrow-to-element ()
24814 "Narrow buffer to current element."
24815 (interactive)
24816 (let ((elem (org-element-at-point)))
24817 (cond
24818 ((eq (car elem) 'headline)
24819 (narrow-to-region
24820 (org-element-property :begin elem)
24821 (org-element-property :end elem)))
24822 ((memq (car elem) org-element-greater-elements)
24823 (narrow-to-region
24824 (org-element-property :contents-begin elem)
24825 (org-element-property :contents-end elem)))
24827 (narrow-to-region
24828 (org-element-property :begin elem)
24829 (org-element-property :end elem))))))
24831 (defun org-transpose-element ()
24832 "Transpose current and previous elements, keeping blank lines between.
24833 Point is moved after both elements."
24834 (interactive)
24835 (org-skip-whitespace)
24836 (let ((end (org-element-property :end (org-element-at-point))))
24837 (org-drag-element-backward)
24838 (goto-char end)))
24840 (defun org-unindent-buffer ()
24841 "Un-indent the visible part of the buffer.
24842 Relative indentation (between items, inside blocks, etc.) isn't
24843 modified."
24844 (interactive)
24845 (unless (eq major-mode 'org-mode)
24846 (user-error "Cannot un-indent a buffer not in Org mode"))
24847 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24848 (unindent-tree
24849 (lambda (contents)
24850 (dolist (element (reverse contents))
24851 (if (memq (org-element-type element) '(headline section))
24852 (funcall unindent-tree (org-element-contents element))
24853 (save-excursion
24854 (save-restriction
24855 (narrow-to-region
24856 (org-element-property :begin element)
24857 (org-element-property :end element))
24858 (org-do-remove-indentation))))))))
24859 (funcall unindent-tree (org-element-contents parse-tree))))
24861 (defun org-show-children (&optional level)
24862 "Show all direct subheadings of this heading.
24863 Prefix arg LEVEL is how many levels below the current level
24864 should be shown. Default is enough to cause the following
24865 heading to appear."
24866 (interactive "p")
24867 ;; If `orgstruct-mode' is active, use the slower version.
24868 (if orgstruct-mode (call-interactively #'outline-show-children)
24869 (save-excursion
24870 (org-back-to-heading t)
24871 (let* ((current-level (funcall outline-level))
24872 (max-level (org-get-valid-level
24873 current-level
24874 (if level (prefix-numeric-value level) 1)))
24875 (end (save-excursion (org-end-of-subtree t t)))
24876 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24877 (past-first-child nil)
24878 ;; Make sure to skip inlinetasks.
24879 (re (format regexp-fmt
24880 current-level
24881 (cond
24882 ((not (featurep 'org-inlinetask)) "")
24883 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24885 (t (1- org-inlinetask-min-level))))))
24886 ;; Display parent heading.
24887 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24888 (forward-line)
24889 ;; Display children. First child may be deeper than expected
24890 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24891 ;; MAX-LEVEL accordingly.
24892 (while (re-search-forward re end t)
24893 (unless past-first-child
24894 (setq re (format regexp-fmt
24895 current-level
24896 (max (funcall outline-level) max-level)))
24897 (setq past-first-child t))
24898 (outline-flag-region
24899 (line-end-position 0) (line-end-position) nil))))))
24901 (defun org-show-subtree ()
24902 "Show everything after this heading at deeper levels."
24903 (interactive)
24904 (outline-flag-region
24905 (point)
24906 (save-excursion
24907 (org-end-of-subtree t t))
24908 nil))
24910 (defun org-show-entry ()
24911 "Show the body directly following this heading.
24912 Show the heading too, if it is currently invisible."
24913 (interactive)
24914 (save-excursion
24915 (ignore-errors
24916 (org-back-to-heading t)
24917 (outline-flag-region
24918 (max (point-min) (1- (point)))
24919 (save-excursion
24920 (if (re-search-forward
24921 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24922 (match-beginning 1)
24923 (point-max)))
24924 nil)
24925 (org-cycle-hide-drawers 'children))))
24927 (defun org-make-options-regexp (kwds &optional extra)
24928 "Make a regular expression for keyword lines.
24929 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24930 when non-nil, is a regexp matching keywords names."
24931 (concat "^[ \t]*#\\+\\("
24932 (regexp-opt kwds)
24933 (and extra (concat (and kwds "\\|") extra))
24934 "\\):[ \t]*\\(.*\\)"))
24936 ;;;; Integration with and fixes for other packages
24938 ;;; Imenu support
24940 (defvar-local org-imenu-markers nil
24941 "All markers currently used by Imenu.")
24943 (defun org-imenu-new-marker (&optional pos)
24944 "Return a new marker for use by Imenu, and remember the marker."
24945 (let ((m (make-marker)))
24946 (move-marker m (or pos (point)))
24947 (push m org-imenu-markers)
24950 (defun org-imenu-get-tree ()
24951 "Produce the index for Imenu."
24952 (dolist (x org-imenu-markers) (move-marker x nil))
24953 (setq org-imenu-markers nil)
24954 (let* ((case-fold-search nil)
24955 (n org-imenu-depth)
24956 (re (concat "^" (org-get-limited-outline-regexp)))
24957 (subs (make-vector (1+ n) nil))
24958 (last-level 0)
24959 m level head0 head)
24960 (org-with-wide-buffer
24961 (goto-char (point-max))
24962 (while (re-search-backward re nil t)
24963 (setq level (org-reduced-level (funcall outline-level)))
24964 (when (and (<= level n)
24965 (looking-at org-complex-heading-regexp)
24966 (setq head0 (match-string-no-properties 4)))
24967 (setq head (org-link-display-format head0)
24968 m (org-imenu-new-marker))
24969 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24970 (if (>= level last-level)
24971 (push (cons head m) (aref subs level))
24972 (push (cons head (aref subs (1+ level))) (aref subs level))
24973 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24974 (setq last-level level))))
24975 (aref subs 1)))
24977 (eval-after-load "imenu"
24978 '(progn
24979 (add-hook 'imenu-after-jump-hook
24980 (lambda ()
24981 (when (derived-mode-p 'org-mode)
24982 (org-show-context 'org-goto))))))
24984 (defun org-link-display-format (s)
24985 "Replace links in string S with their description.
24986 If there is no description, use the link target."
24987 (save-match-data
24988 (replace-regexp-in-string
24989 org-bracket-link-analytic-regexp
24990 (lambda (m)
24991 (if (match-end 5) (match-string 5 m)
24992 (concat (match-string 1 m) (match-string 3 m))))
24993 s nil t)))
24995 (defun org-toggle-link-display ()
24996 "Toggle the literal or descriptive display of links."
24997 (interactive)
24998 (if org-descriptive-links
24999 (progn (org-remove-from-invisibility-spec '(org-link))
25000 (org-restart-font-lock)
25001 (setq org-descriptive-links nil))
25002 (progn (add-to-invisibility-spec '(org-link))
25003 (org-restart-font-lock)
25004 (setq org-descriptive-links t))))
25006 ;; Speedbar support
25008 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
25009 "Overlay marking the agenda restriction line in speedbar.")
25010 (overlay-put org-speedbar-restriction-lock-overlay
25011 'face 'org-agenda-restriction-lock)
25012 (overlay-put org-speedbar-restriction-lock-overlay
25013 'help-echo "Agendas are currently limited to this item.")
25014 (delete-overlay org-speedbar-restriction-lock-overlay)
25016 (defun org-speedbar-set-agenda-restriction ()
25017 "Restrict future agenda commands to the location at point in speedbar.
25018 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
25019 (interactive)
25020 (require 'org-agenda)
25021 (let (p m tp np dir txt)
25022 (cond
25023 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25024 'org-imenu t))
25025 (setq m (get-text-property p 'org-imenu-marker))
25026 (with-current-buffer (marker-buffer m)
25027 (goto-char m)
25028 (org-agenda-set-restriction-lock 'subtree)))
25029 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25030 'speedbar-function 'speedbar-find-file))
25031 (setq tp (previous-single-property-change
25032 (1+ p) 'speedbar-function)
25033 np (next-single-property-change
25034 tp 'speedbar-function)
25035 dir (speedbar-line-directory)
25036 txt (buffer-substring-no-properties (or tp (point-min))
25037 (or np (point-max))))
25038 (with-current-buffer (find-file-noselect
25039 (let ((default-directory dir))
25040 (expand-file-name txt)))
25041 (unless (derived-mode-p 'org-mode)
25042 (user-error "Cannot restrict to non-Org mode file"))
25043 (org-agenda-set-restriction-lock 'file)))
25044 (t (user-error "Don't know how to restrict Org mode agenda")))
25045 (move-overlay org-speedbar-restriction-lock-overlay
25046 (point-at-bol) (point-at-eol))
25047 (setq current-prefix-arg nil)
25048 (org-agenda-maybe-redo)))
25050 (defvar speedbar-file-key-map)
25051 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25052 (eval-after-load "speedbar"
25053 '(progn
25054 (speedbar-add-supported-extension ".org")
25055 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25056 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25057 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25058 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25059 (add-hook 'speedbar-visiting-tag-hook
25060 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25062 ;;; Fixes and Hacks for problems with other packages
25064 (defun org--flyspell-object-check-p (element)
25065 "Non-nil when Flyspell can check object at point.
25066 ELEMENT is the element at point."
25067 (let ((object (save-excursion
25068 (when (looking-at-p "\\>") (backward-char))
25069 (org-element-context element))))
25070 (cl-case (org-element-type object)
25071 ;; Prevent checks in links due to keybinding conflict with
25072 ;; Flyspell.
25073 ((code entity export-snippet inline-babel-call
25074 inline-src-block line-break latex-fragment link macro
25075 statistics-cookie target timestamp verbatim)
25076 nil)
25077 (footnote-reference
25078 ;; Only in inline footnotes, within the definition.
25079 (and (eq (org-element-property :type object) 'inline)
25080 (< (save-excursion
25081 (goto-char (org-element-property :begin object))
25082 (search-forward ":" nil t 2))
25083 (point))))
25084 (otherwise t))))
25086 (defun org-mode-flyspell-verify ()
25087 "Function used for `flyspell-generic-check-word-predicate'."
25088 (if (org-at-heading-p)
25089 ;; At a headline or an inlinetask, check title only. This is
25090 ;; faster than relying on `org-element-at-point'.
25091 (and (save-excursion (beginning-of-line)
25092 (and (let ((case-fold-search t))
25093 (not (looking-at-p "\\*+ END[ \t]*$")))
25094 (let ((case-fold-search nil))
25095 (looking-at org-complex-heading-regexp))))
25096 (match-beginning 4)
25097 (>= (point) (match-beginning 4))
25098 (or (not (match-beginning 5))
25099 (< (point) (match-beginning 5))))
25100 (let* ((element (org-element-at-point))
25101 (post-affiliated (org-element-property :post-affiliated element)))
25102 (cond
25103 ;; Ignore checks in all affiliated keywords but captions.
25104 ((< (point) post-affiliated)
25105 (and (save-excursion
25106 (beginning-of-line)
25107 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25108 (> (point) (match-end 0))
25109 (org--flyspell-object-check-p element)))
25110 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25111 ((let ((log (org-log-into-drawer)))
25112 (and log
25113 (let ((drawer (org-element-lineage element '(drawer))))
25114 (and drawer
25115 (eq (compare-strings
25116 log nil nil
25117 (org-element-property :drawer-name drawer) nil nil t)
25118 t)))))
25119 nil)
25121 (cl-case (org-element-type element)
25122 ((comment quote-section) t)
25123 (comment-block
25124 ;; Allow checks between block markers, not on them.
25125 (and (> (line-beginning-position) post-affiliated)
25126 (save-excursion
25127 (end-of-line)
25128 (skip-chars-forward " \r\t\n")
25129 (< (point) (org-element-property :end element)))))
25130 ;; Arbitrary list of keywords where checks are meaningful.
25131 ;; Make sure point is on the value part of the element.
25132 (keyword
25133 (and (member (org-element-property :key element)
25134 '("DESCRIPTION" "TITLE"))
25135 (save-excursion
25136 (search-backward ":" (line-beginning-position) t))))
25137 ;; Check is globally allowed in paragraphs verse blocks and
25138 ;; table rows (after affiliated keywords) but some objects
25139 ;; must not be affected.
25140 ((paragraph table-row verse-block)
25141 (let ((cbeg (org-element-property :contents-begin element))
25142 (cend (org-element-property :contents-end element)))
25143 (and cbeg (>= (point) cbeg) (< (point) cend)
25144 (org--flyspell-object-check-p element))))))))))
25145 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25147 (defun org-remove-flyspell-overlays-in (beg end)
25148 "Remove flyspell overlays in region."
25149 (and (bound-and-true-p flyspell-mode)
25150 (fboundp 'flyspell-delete-region-overlays)
25151 (flyspell-delete-region-overlays beg end)))
25153 (defvar flyspell-delayed-commands)
25154 (eval-after-load "flyspell"
25155 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25157 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25158 (eval-after-load "bookmark"
25159 '(if (boundp 'bookmark-after-jump-hook)
25160 ;; We can use the hook
25161 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25162 ;; Hook not available, use advice
25163 (defadvice bookmark-jump (after org-make-visible activate)
25164 "Make the position visible."
25165 (org-bookmark-jump-unhide))))
25167 ;; Make sure saveplace shows the location if it was hidden
25168 (eval-after-load "saveplace"
25169 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25170 "Make the position visible."
25171 (org-bookmark-jump-unhide)))
25173 ;; Make sure ecb shows the location if it was hidden
25174 (eval-after-load "ecb"
25175 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25176 "Make hierarchy visible when jumping into location from ECB tree buffer."
25177 (when (derived-mode-p 'org-mode)
25178 (org-show-context))))
25180 (defun org-bookmark-jump-unhide ()
25181 "Unhide the current position, to show the bookmark location."
25182 (and (derived-mode-p 'org-mode)
25183 (or (outline-invisible-p)
25184 (save-excursion (goto-char (max (point-min) (1- (point))))
25185 (outline-invisible-p)))
25186 (org-show-context 'bookmark-jump)))
25188 (defun org-mark-jump-unhide ()
25189 "Make the point visible with `org-show-context' after jumping to the mark."
25190 (when (and (derived-mode-p 'org-mode)
25191 (outline-invisible-p))
25192 (org-show-context 'mark-goto)))
25194 (eval-after-load "simple"
25195 '(defadvice pop-to-mark-command (after org-make-visible activate)
25196 "Make the point visible with `org-show-context'."
25197 (org-mark-jump-unhide)))
25199 (eval-after-load "simple"
25200 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25201 "Make the point visible with `org-show-context'."
25202 (org-mark-jump-unhide)))
25204 (eval-after-load "simple"
25205 '(defadvice pop-global-mark (after org-make-visible activate)
25206 "Make the point visible with `org-show-context'."
25207 (org-mark-jump-unhide)))
25209 ;; Make session.el ignore our circular variable
25210 (defvar session-globals-exclude)
25211 (eval-after-load "session"
25212 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25214 ;;;; Finish up
25216 (provide 'org)
25218 (run-hooks 'org-load-hook)
25220 ;;; org.el ends here