ORG-NEWS: Backport commit 62803a2ef from Emacs
[org-mode.git] / lisp / org.el
blob1e6d0097349d6e7375fcb36b1f0d7d8f737da4c9
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2017 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org mode develops organizational tasks around NOTES files that
32 ;; contain information about projects as plain text. Org mode is
33 ;; implemented on top of outline-mode, which makes it possible to keep
34 ;; the content of large files well structured. Visibility cycling and
35 ;; structure editing help to work with the tree. Tables are easily
36 ;; created with a built-in table editor. Org mode supports ToDo
37 ;; items, deadlines, time stamps, and scheduling. It dynamically
38 ;; compiles entries into an agenda that utilizes and smoothly
39 ;; integrates much of the Emacs calendar and diary. Plain text
40 ;; URL-like links connect to websites, emails, Usenet messages, BBDB
41 ;; entries, and any files related to the projects. For printing and
42 ;; sharing of notes, an Org file can be exported as a structured ASCII
43 ;; file, as HTML, or (todo and agenda items only) as an iCalendar
44 ;; file. It can also serve as a publishing tool for a set of linked
45 ;; webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the doc/ directory.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar-local org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
70 ;;;; Require other packages
72 (require 'cl-lib)
74 (eval-when-compile (require 'gnus-sum))
76 (require 'calendar)
77 (require 'find-func)
78 (require 'format-spec)
80 (or (eq this-command 'eval-buffer)
81 (condition-case nil
82 (load (concat (file-name-directory load-file-name)
83 "org-loaddefs.el")
84 nil t t t)
85 (error
86 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
87 (sit-for 3)
88 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
89 (sit-for 3))))
91 (require 'org-macs)
92 (require 'org-compat)
94 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
95 ;; some places -- e.g. see the macro `org-with-limited-levels'.
97 ;; In Org buffers, the value of `outline-regexp' is that of
98 ;; `org-outline-regexp'. The only function still directly relying on
99 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
100 ;; job when `orgstruct-mode' is active.
101 (defvar org-outline-regexp "\\*+ "
102 "Regexp to match Org headlines.")
104 (defvar org-outline-regexp-bol "^\\*+ "
105 "Regexp to match Org headlines.
106 This is similar to `org-outline-regexp' but additionally makes
107 sure that we are at the beginning of the line.")
109 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
110 "Matches a headline, putting stars and text into groups.
111 Stars are put in group 1 and the trimmed body in group 2.")
113 (declare-function calendar-check-holidays "holidays" (date))
114 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
115 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
116 (declare-function org-add-archive-files "org-archive" (files))
117 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
118 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
119 (declare-function org-agenda-redo "org-agenda" (&optional all))
120 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
121 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
122 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
123 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
126 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
127 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
128 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
129 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
130 (declare-function org-clock-update-time-maybe "org-clock" ())
131 (declare-function org-clocktable-shift "org-clock" (dir n))
132 (declare-function org-element-at-point "org-element" ())
133 (declare-function org-element-cache-refresh "org-element" (pos))
134 (declare-function org-element-cache-reset "org-element" (&optional all))
135 (declare-function org-element-contents "org-element" (element))
136 (declare-function org-element-context "org-element" (&optional element))
137 (declare-function org-element-copy "org-element" (datum))
138 (declare-function org-element-interpret-data "org-element" (data))
139 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
140 (declare-function org-element-link-parser "org-element" ())
141 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
142 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
143 (declare-function org-element-property "org-element" (property element))
144 (declare-function org-element-put-property "org-element" (element property value))
145 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
146 (declare-function org-element-type "org-element" (element))
147 (declare-function org-element-update-syntax "org-element" ())
148 (declare-function org-id-find-id-file "org-id" (id))
149 (declare-function org-id-get-create "org-id" (&optional force))
150 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
151 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
152 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
153 (declare-function org-plot/gnuplot "org-plot" (&optional params))
154 (declare-function org-table-align "org-table" ())
155 (declare-function org-table-begin "org-table" (&optional table-type))
156 (declare-function org-table-beginning-of-field "org-table" (&optional n))
157 (declare-function org-table-blank-field "org-table" ())
158 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
159 (declare-function org-table-copy-region "org-table" (beg end &optional cut))
160 (declare-function org-table-cut-region "org-table" (beg end))
161 (declare-function org-table-edit-field "org-table" (arg))
162 (declare-function org-table-end "org-table" (&optional table-type))
163 (declare-function org-table-end-of-field "org-table" (&optional n))
164 (declare-function org-table-insert-row "org-table" (&optional arg))
165 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
166 (declare-function org-table-maybe-eval-formula "org-table" ())
167 (declare-function org-table-maybe-recalculate-line "org-table" ())
168 (declare-function org-table-next-row "org-table" ())
169 (declare-function org-table-paste-rectangle "org-table" ())
170 (declare-function org-table-recalculate "org-table" (&optional all noalign))
171 (declare-function org-table-wrap-region "org-table" (arg))
172 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
173 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
174 (declare-function orgtbl-mode "org-table" (&optional arg))
175 (declare-function org-export-get-backend "ox" (name))
176 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
177 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
179 (defsubst org-uniquify (list)
180 "Non-destructively remove duplicate elements from LIST."
181 (let ((res (copy-sequence list))) (delete-dups res)))
183 (defsubst org-get-at-bol (property)
184 "Get text property PROPERTY at the beginning of line."
185 (get-text-property (point-at-bol) property))
187 (defsubst org-trim (s &optional keep-lead)
188 "Remove whitespace at the beginning and the end of string S.
189 When optional argument KEEP-LEAD is non-nil, removing blank lines
190 at the beginning of the string does not affect leading indentation."
191 (replace-regexp-in-string
192 (if keep-lead "\\`\\([ \t]*\n\\)+" "\\`[ \t\n\r]+") ""
193 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
195 ;; load languages based on value of `org-babel-load-languages'
196 (defvar org-babel-load-languages)
198 ;;;###autoload
199 (defun org-babel-do-load-languages (sym value)
200 "Load the languages defined in `org-babel-load-languages'."
201 (set-default sym value)
202 (dolist (pair org-babel-load-languages)
203 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
204 (if active
205 (require (intern (concat "ob-" lang)))
206 (funcall 'fmakunbound
207 (intern (concat "org-babel-execute:" lang)))
208 (funcall 'fmakunbound
209 (intern (concat "org-babel-expand-body:" lang)))))))
211 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
212 ;;;###autoload
213 (defun org-babel-load-file (file &optional compile)
214 "Load Emacs Lisp source code blocks in the Org FILE.
215 This function exports the source code using `org-babel-tangle'
216 and then loads the resulting file using `load-file'. With prefix
217 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
218 file to byte-code before it is loaded."
219 (interactive "fFile to load: \nP")
220 (let* ((age (lambda (file)
221 (float-time
222 (time-subtract (current-time)
223 (nth 5 (or (file-attributes (file-truename file))
224 (file-attributes file)))))))
225 (base-name (file-name-sans-extension file))
226 (exported-file (concat base-name ".el")))
227 ;; tangle if the Org file is newer than the elisp file
228 (unless (and (file-exists-p exported-file)
229 (> (funcall age file) (funcall age exported-file)))
230 ;; Tangle-file traversal returns reversed list of tangled files
231 ;; and we want to evaluate the first target.
232 (setq exported-file
233 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
234 (message "%s %s"
235 (if compile
236 (progn (byte-compile-file exported-file 'load)
237 "Compiled and loaded")
238 (progn (load-file exported-file) "Loaded"))
239 exported-file)))
241 (defcustom org-babel-load-languages '((emacs-lisp . t))
242 "Languages which can be evaluated in Org buffers.
243 This list can be used to load support for any of the languages
244 below, note that each language will depend on a different set of
245 system executables and/or Emacs modes. When a language is
246 \"loaded\", then code blocks in that language can be evaluated
247 with `org-babel-execute-src-block' bound by default to C-c
248 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
249 be set to remove code block evaluation from the C-c C-c
250 keybinding. By default only Emacs Lisp (which has no
251 requirements) is loaded."
252 :group 'org-babel
253 :set 'org-babel-do-load-languages
254 :version "24.1"
255 :type '(alist :tag "Babel Languages"
256 :key-type
257 (choice
258 (const :tag "Awk" awk)
259 (const :tag "C" C)
260 (const :tag "R" R)
261 (const :tag "Asymptote" asymptote)
262 (const :tag "Calc" calc)
263 (const :tag "Clojure" clojure)
264 (const :tag "CSS" css)
265 (const :tag "Ditaa" ditaa)
266 (const :tag "Dot" dot)
267 (const :tag "Emacs Lisp" emacs-lisp)
268 (const :tag "Forth" forth)
269 (const :tag "Fortran" fortran)
270 (const :tag "Gnuplot" gnuplot)
271 (const :tag "Haskell" haskell)
272 (const :tag "IO" io)
273 (const :tag "J" J)
274 (const :tag "Java" java)
275 (const :tag "Javascript" js)
276 (const :tag "LaTeX" latex)
277 (const :tag "Ledger" ledger)
278 (const :tag "Lilypond" lilypond)
279 (const :tag "Lisp" lisp)
280 (const :tag "Makefile" makefile)
281 (const :tag "Maxima" maxima)
282 (const :tag "Matlab" matlab)
283 (const :tag "Mscgen" mscgen)
284 (const :tag "Ocaml" ocaml)
285 (const :tag "Octave" octave)
286 (const :tag "Org" org)
287 (const :tag "Perl" perl)
288 (const :tag "Pico Lisp" picolisp)
289 (const :tag "PlantUML" plantuml)
290 (const :tag "Python" python)
291 (const :tag "Ruby" ruby)
292 (const :tag "Sass" sass)
293 (const :tag "Scala" scala)
294 (const :tag "Scheme" scheme)
295 (const :tag "Screen" screen)
296 (const :tag "Shell Script" shell)
297 (const :tag "Shen" shen)
298 (const :tag "Sql" sql)
299 (const :tag "Sqlite" sqlite)
300 (const :tag "Stan" stan)
301 (const :tag "ebnf2ps" ebnf2ps))
302 :value-type (boolean :tag "Activate" :value t)))
304 ;;;; Customization variables
305 (defcustom org-clone-delete-id nil
306 "Remove ID property of clones of a subtree.
307 When non-nil, clones of a subtree don't inherit the ID property.
308 Otherwise they inherit the ID property with a new unique
309 identifier."
310 :type 'boolean
311 :version "24.1"
312 :group 'org-id)
314 ;;; Version
315 (org-check-version)
317 ;;;###autoload
318 (defun org-version (&optional here full message)
319 "Show the Org version.
320 Interactively, or when MESSAGE is non-nil, show it in echo area.
321 With prefix argument, or when HERE is non-nil, insert it at point.
322 In non-interactive uses, a reduced version string is output unless
323 FULL is given."
324 (interactive (list current-prefix-arg t (not current-prefix-arg)))
325 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
326 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
327 (load-suffixes (list ".el"))
328 (org-install-dir
329 (ignore-errors (org-find-library-dir "org-loaddefs"))))
330 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
331 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
332 (let* ((load-suffixes save-load-suffixes)
333 (release (org-release))
334 (git-version (org-git-version))
335 (version (format "Org mode version %s (%s @ %s)"
336 release
337 git-version
338 (if org-install-dir
339 (if (string= org-dir org-install-dir)
340 org-install-dir
341 (concat "mixed installation! "
342 org-install-dir
343 " and "
344 org-dir))
345 "org-loaddefs.el can not be found!")))
346 (version1 (if full version release)))
347 (when here (insert version1))
348 (when message (message "%s" version1))
349 version1)))
351 (defconst org-version (org-version))
354 ;;; Syntax Constants
356 ;;;; Block
358 (defconst org-block-regexp
359 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
360 "Regular expression for hiding blocks.")
362 (defconst org-dblock-start-re
363 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
364 "Matches the start line of a dynamic block, with parameters.")
366 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
367 "Matches the end of a dynamic block.")
369 ;;;; Clock and Planning
371 (defconst org-clock-string "CLOCK:"
372 "String used as prefix for timestamps clocking work hours on an item.")
374 (defvar org-closed-string "CLOSED:"
375 "String used as the prefix for timestamps logging closing a TODO entry.")
377 (defvar org-deadline-string "DEADLINE:"
378 "String to mark deadline entries.
379 \\<org-mode-map>
380 A deadline is this string, followed by a time stamp. It must be
381 a word, terminated by a colon. You can insert a schedule keyword
382 and a timestamp with `\\[org-deadline]'.")
384 (defvar org-scheduled-string "SCHEDULED:"
385 "String to mark scheduled TODO entries.
386 \\<org-mode-map>
387 A schedule is this string, followed by a time stamp. It must be
388 a word, terminated by a colon. You can insert a schedule keyword
389 and a timestamp with `\\[org-schedule]'.")
391 (defconst org-ds-keyword-length
392 (+ 2
393 (apply #'max
394 (mapcar #'length
395 (list org-deadline-string org-scheduled-string
396 org-clock-string org-closed-string))))
397 "Maximum length of the DEADLINE and SCHEDULED keywords.")
399 (defconst org-planning-line-re
400 (concat "^[ \t]*"
401 (regexp-opt
402 (list org-closed-string org-deadline-string org-scheduled-string)
404 "Matches a line with planning info.
405 Matched keyword is in group 1.")
407 (defconst org-clock-line-re
408 (concat "^[ \t]*" org-clock-string)
409 "Matches a line with clock info.")
411 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
412 "Matches the DEADLINE keyword.")
414 (defconst org-deadline-time-regexp
415 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
416 "Matches the DEADLINE keyword together with a time stamp.")
418 (defconst org-deadline-time-hour-regexp
419 (concat "\\<" org-deadline-string
420 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
421 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
423 (defconst org-deadline-line-regexp
424 (concat "\\<\\(" org-deadline-string "\\).*")
425 "Matches the DEADLINE keyword and the rest of the line.")
427 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
428 "Matches the SCHEDULED keyword.")
430 (defconst org-scheduled-time-regexp
431 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
432 "Matches the SCHEDULED keyword together with a time stamp.")
434 (defconst org-scheduled-time-hour-regexp
435 (concat "\\<" org-scheduled-string
436 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
437 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
439 (defconst org-closed-time-regexp
440 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
441 "Matches the CLOSED keyword together with a time stamp.")
443 (defconst org-keyword-time-regexp
444 (concat "\\<"
445 (regexp-opt
446 (list org-scheduled-string org-deadline-string org-closed-string
447 org-clock-string)
449 " *[[<]\\([^]>]+\\)[]>]")
450 "Matches any of the 4 keywords, together with the time stamp.")
452 (defconst org-keyword-time-not-clock-regexp
453 (concat
454 "\\<"
455 (regexp-opt
456 (list org-scheduled-string org-deadline-string org-closed-string) t)
457 " *[[<]\\([^]>]+\\)[]>]")
458 "Matches any of the 3 keywords, together with the time stamp.")
460 (defconst org-maybe-keyword-time-regexp
461 (concat "\\(\\<"
462 (regexp-opt
463 (list org-scheduled-string org-deadline-string org-closed-string
464 org-clock-string)
466 "\\)?"
467 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
468 "\\|"
469 "<%%([^\r\n>]*>\\)")
470 "Matches a timestamp, possibly preceded by a keyword.")
472 (defconst org-all-time-keywords
473 (mapcar (lambda (w) (substring w 0 -1))
474 (list org-scheduled-string org-deadline-string
475 org-clock-string org-closed-string))
476 "List of time keywords.")
478 ;;;; Drawer
480 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
481 "Matches first or last line of a hidden block.
482 Group 1 contains drawer's name or \"END\".")
484 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
485 "Regular expression matching the first line of a property drawer.")
487 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
488 "Regular expression matching the last line of a property drawer.")
490 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
491 "Regular expression matching the first line of a clock drawer.")
493 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
494 "Regular expression matching the last line of a clock drawer.")
496 (defconst org-property-drawer-re
497 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
498 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
499 "[ \t]*:END:[ \t]*$")
500 "Matches an entire property drawer.")
502 (defconst org-clock-drawer-re
503 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
504 org-clock-drawer-end-re "\\)\n?")
505 "Matches an entire clock drawer.")
507 ;;;; Headline
509 (defconst org-heading-keyword-regexp-format
510 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
511 "Printf format for a regexp matching a headline with some keyword.
512 This regexp will match the headline of any node which has the
513 exact keyword that is put into the format. The keyword isn't in
514 any group by default, but the stars and the body are.")
516 (defconst org-heading-keyword-maybe-regexp-format
517 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
518 "Printf format for a regexp matching a headline, possibly with some keyword.
519 This regexp can match any headline with the specified keyword, or
520 without a keyword. The keyword isn't in any group by default,
521 but the stars and the body are.")
523 (defconst org-archive-tag "ARCHIVE"
524 "The tag that marks a subtree as archived.
525 An archived subtree does not open during visibility cycling, and does
526 not contribute to the agenda listings.")
528 (defconst org-comment-string "COMMENT"
529 "Entries starting with this keyword will never be exported.
530 \\<org-mode-map>
531 An entry can be toggled between COMMENT and normal with
532 `\\[org-toggle-comment]'.")
535 ;;;; LaTeX Environments and Fragments
537 (defconst org-latex-regexps
538 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
539 ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
540 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
541 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
542 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
543 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
544 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
545 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
546 "Regular expressions for matching embedded LaTeX.")
548 ;;;; Node Property
550 (defconst org-effort-property "Effort"
551 "The property that is being used to keep track of effort estimates.
552 Effort estimates given in this property need to have the format H:MM.")
554 ;;;; Table
556 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
557 "Detect an org-type or table-type table.")
559 (defconst org-table-line-regexp "^[ \t]*|"
560 "Detect an org-type table line.")
562 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
563 "Detect an org-type table line.")
565 (defconst org-table-hline-regexp "^[ \t]*|-"
566 "Detect an org-type table hline.")
568 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
569 "Detect a table-type table hline.")
571 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
572 "Detect the first line outside a table when searching from within it.
573 This works for both table types.")
575 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
576 "Detect a #+TBLFM line.")
578 ;;;; Timestamp
580 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
581 "Regular expression for fast time stamp matching.")
583 (defconst org-ts-regexp-inactive
584 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
585 "Regular expression for fast inactive time stamp matching.")
587 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
588 "Regular expression for fast time stamp matching.")
590 (defconst org-ts-regexp0
591 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
592 "Regular expression matching time strings for analysis.
593 This one does not require the space after the date, so it can be used
594 on a string that terminates immediately after the date.")
596 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
597 "Regular expression matching time strings for analysis.")
599 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
600 "Regular expression matching time stamps, with groups.")
602 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
603 "Regular expression matching time stamps (also [..]), with groups.")
605 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
606 "Regular expression matching a time stamp range.")
608 (defconst org-tr-regexp-both
609 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
610 "Regular expression matching a time stamp range.")
612 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
613 org-ts-regexp "\\)?")
614 "Regular expression matching a time stamp or time stamp range.")
616 (defconst org-tsr-regexp-both
617 (concat org-ts-regexp-both "\\(--?-?"
618 org-ts-regexp-both "\\)?")
619 "Regular expression matching a time stamp or time stamp range.
620 The time stamps may be either active or inactive.")
622 (defconst org-repeat-re
623 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
624 "Regular expression for specifying repeated events.
625 After a match, group 1 contains the repeat expression.")
627 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
628 "Formats for `format-time-string' which are used for time stamps.")
631 ;;; The custom variables
633 (defgroup org nil
634 "Outline-based notes management and organizer."
635 :tag "Org"
636 :group 'outlines
637 :group 'calendar)
639 (defcustom org-mode-hook nil
640 "Mode hook for Org mode, run after the mode was turned on."
641 :group 'org
642 :type 'hook)
644 (defcustom org-load-hook nil
645 "Hook that is run after org.el has been loaded."
646 :group 'org
647 :type 'hook)
649 (defcustom org-log-buffer-setup-hook nil
650 "Hook that is run after an Org log buffer is created."
651 :group 'org
652 :version "24.1"
653 :type 'hook)
655 (defvar org-modules) ; defined below
656 (defvar org-modules-loaded nil
657 "Have the modules been loaded already?")
659 (defun org-load-modules-maybe (&optional force)
660 "Load all extensions listed in `org-modules'."
661 (when (or force (not org-modules-loaded))
662 (dolist (ext org-modules)
663 (condition-case nil (require ext)
664 (error (message "Problems while trying to load feature `%s'" ext))))
665 (setq org-modules-loaded t)))
667 (defun org-set-modules (var value)
668 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
669 (set var value)
670 (when (featurep 'org)
671 (org-load-modules-maybe 'force)
672 (org-element-cache-reset 'all)))
674 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
675 "Modules that should always be loaded together with org.el.
677 If a description starts with <C>, the file is not part of Emacs
678 and loading it will require that you have downloaded and properly
679 installed the Org mode distribution.
681 You can also use this system to load external packages (i.e. neither Org
682 core modules, nor modules from the CONTRIB directory). Just add symbols
683 to the end of the list. If the package is called org-xyz.el, then you need
684 to add the symbol `xyz', and the package must have a call to:
686 (provide \\='org-xyz)
688 For export specific modules, see also `org-export-backends'."
689 :group 'org
690 :set 'org-set-modules
691 :version "24.4"
692 :package-version '(Org . "8.0")
693 :type
694 '(set :greedy t
695 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
696 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
697 (const :tag " crypt: Encryption of subtrees" org-crypt)
698 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
699 (const :tag " docview: Links to doc-view buffers" org-docview)
700 (const :tag " eww: Store link to url of eww" org-eww)
701 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
702 (const :tag " habit: Track your consistency with habits" org-habit)
703 (const :tag " id: Global IDs for identifying entries" org-id)
704 (const :tag " info: Links to Info nodes" org-info)
705 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
706 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
707 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
708 (const :tag " mouse: Additional mouse support" org-mouse)
709 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
710 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
711 (const :tag " w3m: Special cut/paste from w3m to Org mode." org-w3m)
713 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
714 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
715 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
716 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
717 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
718 (const :tag "C collector: Collect properties into tables" org-collector)
719 (const :tag "C depend: TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
720 (const :tag "C drill: Flashcards and spaced repetition for Org mode" org-drill)
721 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
722 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
723 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
724 (const :tag "C eval: Include command output as text" org-eval)
725 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
726 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
727 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
728 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
729 (const :tag "C invoice: Help manage client invoices in Org mode" org-invoice)
730 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
731 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
732 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
733 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
734 (const :tag "C man: Support for links to manpages in Org mode" org-man)
735 (const :tag "C mew: Links to Mew folders/messages" org-mew)
736 (const :tag "C mtags: Support for muse-like tags" org-mtags)
737 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
738 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
739 (const :tag "C registry: A registry for Org links" org-registry)
740 (const :tag "C screen: Visit screen sessions through Org links" org-screen)
741 (const :tag "C secretary: Team management with org-mode" org-secretary)
742 (const :tag "C sqlinsert: Convert Org tables to SQL insertions" orgtbl-sqlinsert)
743 (const :tag "C toc: Table of contents for Org buffer" org-toc)
744 (const :tag "C track: Keep up with Org mode development" org-track)
745 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
746 (const :tag "C vm: Links to VM folders/messages" org-vm)
747 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
748 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
749 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
751 (defvar org-export-registered-backends) ; From ox.el.
752 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
753 (declare-function org-export-backend-name "ox" (backend) t)
754 (defcustom org-export-backends '(ascii html icalendar latex odt)
755 "List of export back-ends that should be always available.
757 If a description starts with <C>, the file is not part of Emacs
758 and loading it will require that you have downloaded and properly
759 installed the Org mode distribution.
761 Unlike to `org-modules', libraries in this list will not be
762 loaded along with Org, but only once the export framework is
763 needed.
765 This variable needs to be set before org.el is loaded. If you
766 need to make a change while Emacs is running, use the customize
767 interface or run the following code, where VAL stands for the new
768 value of the variable, after updating it:
770 (progn
771 (setq org-export-registered-backends
772 (cl-remove-if-not
773 (lambda (backend)
774 (let ((name (org-export-backend-name backend)))
775 (or (memq name val)
776 (catch \\='parentp
777 (dolist (b val)
778 (and (org-export-derived-backend-p b name)
779 (throw \\='parentp t)))))))
780 org-export-registered-backends))
781 (let ((new-list (mapcar #\\='org-export-backend-name
782 org-export-registered-backends)))
783 (dolist (backend val)
784 (cond
785 ((not (load (format \"ox-%s\" backend) t t))
786 (message \"Problems while trying to load export back-end \\=`%s\\='\"
787 backend))
788 ((not (memq backend new-list)) (push backend new-list))))
789 (set-default \\='org-export-backends new-list)))
791 Adding a back-end to this list will also pull the back-end it
792 depends on, if any."
793 :group 'org
794 :group 'org-export
795 :version "26.1"
796 :package-version '(Org . "9.0")
797 :initialize 'custom-initialize-set
798 :set (lambda (var val)
799 (if (not (featurep 'ox)) (set-default var val)
800 ;; Any back-end not required anymore (not present in VAL and not
801 ;; a parent of any back-end in the new value) is removed from the
802 ;; list of registered back-ends.
803 (setq org-export-registered-backends
804 (cl-remove-if-not
805 (lambda (backend)
806 (let ((name (org-export-backend-name backend)))
807 (or (memq name val)
808 (catch 'parentp
809 (dolist (b val)
810 (and (org-export-derived-backend-p b name)
811 (throw 'parentp t)))))))
812 org-export-registered-backends))
813 ;; Now build NEW-LIST of both new back-ends and required
814 ;; parents.
815 (let ((new-list (mapcar #'org-export-backend-name
816 org-export-registered-backends)))
817 (dolist (backend val)
818 (cond
819 ((not (load (format "ox-%s" backend) t t))
820 (message "Problems while trying to load export back-end `%s'"
821 backend))
822 ((not (memq backend new-list)) (push backend new-list))))
823 ;; Set VAR to that list with fixed dependencies.
824 (set-default var new-list))))
825 :type '(set :greedy t
826 (const :tag " ascii Export buffer to ASCII format" ascii)
827 (const :tag " beamer Export buffer to Beamer presentation" beamer)
828 (const :tag " html Export buffer to HTML format" html)
829 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
830 (const :tag " latex Export buffer to LaTeX format" latex)
831 (const :tag " man Export buffer to MAN format" man)
832 (const :tag " md Export buffer to Markdown format" md)
833 (const :tag " odt Export buffer to ODT format" odt)
834 (const :tag " org Export buffer to Org format" org)
835 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
836 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
837 (const :tag "C deck Export buffer to deck.js presentations" deck)
838 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
839 (const :tag "C groff Export buffer to Groff format" groff)
840 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
841 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
842 (const :tag "C s5 Export buffer to s5 presentations" s5)
843 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
845 (eval-after-load 'ox
846 '(dolist (backend org-export-backends)
847 (condition-case nil (require (intern (format "ox-%s" backend)))
848 (error (message "Problems while trying to load export back-end `%s'"
849 backend)))))
851 (defcustom org-support-shift-select nil
852 "Non-nil means make shift-cursor commands select text when possible.
853 \\<org-mode-map>\
855 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
856 start selecting a region, or enlarge regions started in this way.
857 In Org mode, in special contexts, these same keys are used for
858 other purposes, important enough to compete with shift selection.
859 Org tries to balance these needs by supporting `shift-select-mode'
860 outside these special contexts, under control of this variable.
862 The default of this variable is nil, to avoid confusing behavior. Shifted
863 cursor keys will then execute Org commands in the following contexts:
864 - on a headline, changing TODO state (left/right) and priority (up/down)
865 - on a time stamp, changing the time
866 - in a plain list item, changing the bullet type
867 - in a property definition line, switching between allowed values
868 - in the BEGIN line of a clock table (changing the time block).
869 Outside these contexts, the commands will throw an error.
871 When this variable is t and the cursor is not in a special
872 context, Org mode will support shift-selection for making and
873 enlarging regions. To make this more effective, the bullet
874 cycling will no longer happen anywhere in an item line, but only
875 if the cursor is exactly on the bullet.
877 If you set this variable to the symbol `always', then the keys
878 will not be special in headlines, property lines, and item lines,
879 to make shift selection work there as well. If this is what you
880 want, you can use the following alternative commands:
881 `\\[org-todo]' and `\\[org-priority]' \
882 to change TODO state and priority,
883 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
884 can be used to switch TODO sets,
885 `\\[org-ctrl-c-minus]' to cycle item bullet types,
886 and properties can be edited by hand or in column view.
888 However, when the cursor is on a timestamp, shift-cursor commands
889 will still edit the time stamp - this is just too good to give up."
890 :group 'org
891 :type '(choice
892 (const :tag "Never" nil)
893 (const :tag "When outside special context" t)
894 (const :tag "Everywhere except timestamps" always)))
896 (defcustom org-loop-over-headlines-in-active-region nil
897 "Shall some commands act upon headlines in the active region?
899 When set to t, some commands will be performed in all headlines
900 within the active region.
902 When set to `start-level', some commands will be performed in all
903 headlines within the active region, provided that these headlines
904 are of the same level than the first one.
906 When set to a string, those commands will be performed on the
907 matching headlines within the active region. Such string must be
908 a tags/property/todo match as it is used in the agenda tags view.
910 The list of commands is: `org-schedule', `org-deadline',
911 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
912 `org-archive-to-archive-sibling'. The archiving commands skip
913 already archived entries."
914 :type '(choice (const :tag "Don't loop" nil)
915 (const :tag "All headlines in active region" t)
916 (const :tag "In active region, headlines at the same level than the first one" start-level)
917 (string :tag "Tags/Property/Todo matcher"))
918 :version "24.1"
919 :group 'org-todo
920 :group 'org-archive)
922 (defgroup org-startup nil
923 "Options concerning startup of Org mode."
924 :tag "Org Startup"
925 :group 'org)
927 (defcustom org-startup-folded t
928 "Non-nil means entering Org mode will switch to OVERVIEW.
930 This can also be configured on a per-file basis by adding one of
931 the following lines anywhere in the buffer:
933 #+STARTUP: fold (or `overview', this is equivalent)
934 #+STARTUP: nofold (or `showall', this is equivalent)
935 #+STARTUP: content
936 #+STARTUP: showeverything
938 Set `org-agenda-inhibit-startup' to a non-nil value if you want
939 to ignore this option when Org opens agenda files for the first
940 time."
941 :group 'org-startup
942 :type '(choice
943 (const :tag "nofold: show all" nil)
944 (const :tag "fold: overview" t)
945 (const :tag "content: all headlines" content)
946 (const :tag "show everything, even drawers" showeverything)))
948 (defcustom org-startup-truncated t
949 "Non-nil means entering Org mode will set `truncate-lines'.
950 This is useful since some lines containing links can be very long and
951 uninteresting. Also tables look terrible when wrapped.
953 The variable `org-startup-truncated' allows to configure
954 truncation for Org mode different to the other modes that use the
955 variable `truncate-lines' and as a shortcut instead of putting
956 the variable `truncate-lines' into the `org-mode-hook'. If one
957 wants to configure truncation for Org mode not statically but
958 dynamically e. g. in a hook like `ediff-prepare-buffer-hook' then
959 the variable `truncate-lines' has to be used because in such a
960 case it is too late to set the variable `org-startup-truncated'."
961 :group 'org-startup
962 :type 'boolean)
964 (defcustom org-startup-indented nil
965 "Non-nil means turn on `org-indent-mode' on startup.
966 This can also be configured on a per-file basis by adding one of
967 the following lines anywhere in the buffer:
969 #+STARTUP: indent
970 #+STARTUP: noindent"
971 :group 'org-structure
972 :type '(choice
973 (const :tag "Not" nil)
974 (const :tag "Globally (slow on startup in large files)" t)))
976 (defcustom org-use-sub-superscripts t
977 "Non-nil means interpret \"_\" and \"^\" for display.
979 If you want to control how Org exports those characters, see
980 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
981 used to be an alias for `org-export-with-sub-superscripts' in
982 Org <8.0, it is not anymore.
984 When this option is turned on, you can use TeX-like syntax for
985 sub- and superscripts within the buffer. Several characters after
986 \"_\" or \"^\" will be considered as a single item - so grouping
987 with {} is normally not needed. For example, the following things
988 will be parsed as single sub- or superscripts:
990 10^24 or 10^tau several digits will be considered 1 item.
991 10^-12 or 10^-tau a leading sign with digits or a word
992 x^2-y^3 will be read as x^2 - y^3, because items are
993 terminated by almost any nonword/nondigit char.
994 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
996 Still, ambiguity is possible. So when in doubt, use {} to enclose
997 the sub/superscript. If you set this variable to the symbol `{}',
998 the braces are *required* in order to trigger interpretations as
999 sub/superscript. This can be helpful in documents that need \"_\"
1000 frequently in plain text."
1001 :group 'org-startup
1002 :version "24.4"
1003 :package-version '(Org . "8.0")
1004 :type '(choice
1005 (const :tag "Always interpret" t)
1006 (const :tag "Only with braces" {})
1007 (const :tag "Never interpret" nil)))
1009 (defcustom org-startup-with-beamer-mode nil
1010 "Non-nil means turn on `org-beamer-mode' on startup.
1011 This can also be configured on a per-file basis by adding one of
1012 the following lines anywhere in the buffer:
1014 #+STARTUP: beamer"
1015 :group 'org-startup
1016 :version "24.1"
1017 :type 'boolean)
1019 (defcustom org-startup-align-all-tables nil
1020 "Non-nil means align all tables when visiting a file.
1021 This is useful when the column width in tables is forced with <N> cookies
1022 in table fields. Such tables will look correct only after the first re-align.
1023 This can also be configured on a per-file basis by adding one of
1024 the following lines anywhere in the buffer:
1025 #+STARTUP: align
1026 #+STARTUP: noalign"
1027 :group 'org-startup
1028 :type 'boolean)
1030 (defcustom org-startup-with-inline-images nil
1031 "Non-nil means show inline images when loading a new Org file.
1032 This can also be configured on a per-file basis by adding one of
1033 the following lines anywhere in the buffer:
1034 #+STARTUP: inlineimages
1035 #+STARTUP: noinlineimages"
1036 :group 'org-startup
1037 :version "24.1"
1038 :type 'boolean)
1040 (defcustom org-startup-with-latex-preview nil
1041 "Non-nil means preview LaTeX fragments when loading a new Org file.
1043 This can also be configured on a per-file basis by adding one of
1044 the following lines anywhere in the buffer:
1045 #+STARTUP: latexpreview
1046 #+STARTUP: nolatexpreview"
1047 :group 'org-startup
1048 :version "24.4"
1049 :package-version '(Org . "8.0")
1050 :type 'boolean)
1052 (defcustom org-insert-mode-line-in-empty-file nil
1053 "Non-nil means insert the first line setting Org mode in empty files.
1054 When the function `org-mode' is called interactively in an empty file, this
1055 normally means that the file name does not automatically trigger Org mode.
1056 To ensure that the file will always be in Org mode in the future, a
1057 line enforcing Org mode will be inserted into the buffer, if this option
1058 has been set."
1059 :group 'org-startup
1060 :type 'boolean)
1062 (defcustom org-replace-disputed-keys nil
1063 "Non-nil means use alternative key bindings for some keys.
1064 Org mode uses S-<cursor> keys for changing timestamps and priorities.
1065 These keys are also used by other packages like shift-selection-mode'
1066 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1067 If you want to use Org mode together with one of these other modes,
1068 or more generally if you would like to move some Org mode commands to
1069 other keys, set this variable and configure the keys with the variable
1070 `org-disputed-keys'.
1072 This option is only relevant at load-time of Org mode, and must be set
1073 *before* org.el is loaded. Changing it requires a restart of Emacs to
1074 become effective."
1075 :group 'org-startup
1076 :type 'boolean)
1078 (defcustom org-use-extra-keys nil
1079 "Non-nil means use extra key sequence definitions for certain commands.
1080 This happens automatically if `window-system' is nil. This
1081 variable lets you do the same manually. You must set it before
1082 loading Org."
1083 :group 'org-startup
1084 :type 'boolean)
1086 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1088 (defcustom org-disputed-keys
1089 '(([(shift up)] . [(meta p)])
1090 ([(shift down)] . [(meta n)])
1091 ([(shift left)] . [(meta -)])
1092 ([(shift right)] . [(meta +)])
1093 ([(control shift right)] . [(meta shift +)])
1094 ([(control shift left)] . [(meta shift -)]))
1095 "Keys for which Org mode and other modes compete.
1096 This is an alist, cars are the default keys, second element specifies
1097 the alternative to use when `org-replace-disputed-keys' is t.
1099 Keys can be specified in any syntax supported by `define-key'.
1100 The value of this option takes effect only at Org mode startup,
1101 therefore you'll have to restart Emacs to apply it after changing."
1102 :group 'org-startup
1103 :type 'alist)
1105 (defun org-key (key)
1106 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1107 Or return the original if not disputed."
1108 (when org-replace-disputed-keys
1109 (let* ((nkey (key-description key))
1110 (x (cl-find-if (lambda (x) (equal (key-description (car x)) nkey))
1111 org-disputed-keys)))
1112 (setq key (if x (cdr x) key))))
1113 key)
1115 (defun org-defkey (keymap key def)
1116 "Define a key, possibly translated, as returned by `org-key'."
1117 (define-key keymap (org-key key) def))
1119 (defcustom org-ellipsis nil
1120 "The ellipsis to use in the Org mode outline.
1122 When nil, just use the standard three dots.
1123 When a string, use that string instead.
1125 The change affects only Org mode (which will then use its own display table).
1126 Changing this requires executing `\\[org-mode]' in a buffer to become
1127 effective."
1128 :group 'org-startup
1129 :type '(choice (const :tag "Default" nil)
1130 (string :tag "String" :value "...#"))
1131 :safe #'string-or-null-p)
1133 (defvar org-display-table nil
1134 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1136 (defgroup org-keywords nil
1137 "Keywords in Org mode."
1138 :tag "Org Keywords"
1139 :group 'org)
1141 (defcustom org-closed-keep-when-no-todo nil
1142 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1143 :group 'org-todo
1144 :group 'org-keywords
1145 :version "24.4"
1146 :package-version '(Org . "8.0")
1147 :type 'boolean)
1149 (defgroup org-structure nil
1150 "Options concerning the general structure of Org files."
1151 :tag "Org Structure"
1152 :group 'org)
1154 (defgroup org-reveal-location nil
1155 "Options about how to make context of a location visible."
1156 :tag "Org Reveal Location"
1157 :group 'org-structure)
1159 (defcustom org-show-context-detail '((agenda . local)
1160 (bookmark-jump . lineage)
1161 (isearch . lineage)
1162 (default . ancestors))
1163 "Alist between context and visibility span when revealing a location.
1165 \\<org-mode-map>Some actions may move point into invisible
1166 locations. As a consequence, Org always expose a neighborhood
1167 around point. How much is shown depends on the initial action,
1168 or context. Valid contexts are
1170 agenda when exposing an entry from the agenda
1171 org-goto when using the command `org-goto' (`\\[org-goto]')
1172 occur-tree when using the command `org-occur' (`\\[org-sparse-tree] /')
1173 tags-tree when constructing a sparse tree based on tags matches
1174 link-search when exposing search matches associated with a link
1175 mark-goto when exposing the jump goal of a mark
1176 bookmark-jump when exposing a bookmark location
1177 isearch when exiting from an incremental search
1178 default default for all contexts not set explicitly
1180 Allowed visibility spans are
1182 minimal show current headline; if point is not on headline,
1183 also show entry
1185 local show current headline, entry and next headline
1187 ancestors show current headline and its direct ancestors; if
1188 point is not on headline, also show entry
1190 lineage show current headline, its direct ancestors and all
1191 their children; if point is not on headline, also show
1192 entry and first child
1194 tree show current headline, its direct ancestors and all
1195 their children; if point is not on headline, also show
1196 entry and all children
1198 canonical show current headline, its direct ancestors along with
1199 their entries and children; if point is not located on
1200 the headline, also show current entry and all children
1202 As special cases, a nil or t value means show all contexts in
1203 `minimal' or `canonical' view, respectively.
1205 Some views can make displayed information very compact, but also
1206 make it harder to edit the location of the match. In such
1207 a case, use the command `org-reveal' (`\\[org-reveal]') to show
1208 more context."
1209 :group 'org-reveal-location
1210 :version "26.1"
1211 :package-version '(Org . "9.0")
1212 :type '(choice
1213 (const :tag "Canonical" t)
1214 (const :tag "Minimal" nil)
1215 (repeat :greedy t :tag "Individual contexts"
1216 (cons
1217 (choice :tag "Context"
1218 (const agenda)
1219 (const org-goto)
1220 (const occur-tree)
1221 (const tags-tree)
1222 (const link-search)
1223 (const mark-goto)
1224 (const bookmark-jump)
1225 (const isearch)
1226 (const default))
1227 (choice :tag "Detail level"
1228 (const minimal)
1229 (const local)
1230 (const ancestors)
1231 (const lineage)
1232 (const tree)
1233 (const canonical))))))
1235 (defcustom org-indirect-buffer-display 'other-window
1236 "How should indirect tree buffers be displayed?
1238 This applies to indirect buffers created with the commands
1239 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
1241 Valid values are:
1242 current-window Display in the current window
1243 other-window Just display in another window.
1244 dedicated-frame Create one new frame, and re-use it each time.
1245 new-frame Make a new frame each time. Note that in this case
1246 previously-made indirect buffers are kept, and you need to
1247 kill these buffers yourself."
1248 :group 'org-structure
1249 :group 'org-agenda-windows
1250 :type '(choice
1251 (const :tag "In current window" current-window)
1252 (const :tag "In current frame, other window" other-window)
1253 (const :tag "Each time a new frame" new-frame)
1254 (const :tag "One dedicated frame" dedicated-frame)))
1256 (defcustom org-use-speed-commands nil
1257 "Non-nil means activate single letter commands at beginning of a headline.
1258 This may also be a function to test for appropriate locations where speed
1259 commands should be active.
1261 For example, to activate speed commands when the point is on any
1262 star at the beginning of the headline, you can do this:
1264 (setq org-use-speed-commands
1265 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1266 :group 'org-structure
1267 :type '(choice
1268 (const :tag "Never" nil)
1269 (const :tag "At beginning of headline stars" t)
1270 (function)))
1272 (defcustom org-speed-commands-user nil
1273 "Alist of additional speed commands.
1274 This list will be checked before `org-speed-commands-default'
1275 when the variable `org-use-speed-commands' is non-nil
1276 and when the cursor is at the beginning of a headline.
1277 The car if each entry is a string with a single letter, which must
1278 be assigned to `self-insert-command' in the global map.
1279 The cdr is either a command to be called interactively, a function
1280 to be called, or a form to be evaluated.
1281 An entry that is just a list with a single string will be interpreted
1282 as a descriptive headline that will be added when listing the speed
1283 commands in the Help buffer using the `?' speed command."
1284 :group 'org-structure
1285 :type '(repeat :value ("k" . ignore)
1286 (choice :value ("k" . ignore)
1287 (list :tag "Descriptive Headline" (string :tag "Headline"))
1288 (cons :tag "Letter and Command"
1289 (string :tag "Command letter")
1290 (choice
1291 (function)
1292 (sexp))))))
1294 (defcustom org-bookmark-names-plist
1295 '(:last-capture "org-capture-last-stored"
1296 :last-refile "org-refile-last-stored"
1297 :last-capture-marker "org-capture-last-stored-marker")
1298 "Names for bookmarks automatically set by some Org commands.
1299 This can provide strings as names for a number of bookmarks Org sets
1300 automatically. The following keys are currently implemented:
1301 :last-capture
1302 :last-capture-marker
1303 :last-refile
1304 When a key does not show up in the property list, the corresponding bookmark
1305 is not set."
1306 :group 'org-structure
1307 :type 'plist)
1309 (defgroup org-cycle nil
1310 "Options concerning visibility cycling in Org mode."
1311 :tag "Org Cycle"
1312 :group 'org-structure)
1314 (defcustom org-cycle-skip-children-state-if-no-children t
1315 "Non-nil means skip CHILDREN state in entries that don't have any."
1316 :group 'org-cycle
1317 :type 'boolean)
1319 (defcustom org-cycle-max-level nil
1320 "Maximum level which should still be subject to visibility cycling.
1321 Levels higher than this will, for cycling, be treated as text, not a headline.
1322 When `org-odd-levels-only' is set, a value of N in this variable actually
1323 means 2N-1 stars as the limiting headline.
1324 When nil, cycle all levels.
1325 Note that the limiting level of cycling is also influenced by
1326 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1327 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1328 than its value."
1329 :group 'org-cycle
1330 :type '(choice
1331 (const :tag "No limit" nil)
1332 (integer :tag "Maximum level")))
1334 (defcustom org-hide-block-startup nil
1335 "Non-nil means entering Org mode will fold all blocks.
1336 This can also be set in on a per-file basis with
1338 #+STARTUP: hideblocks
1339 #+STARTUP: showblocks"
1340 :group 'org-startup
1341 :group 'org-cycle
1342 :type 'boolean)
1344 (defcustom org-cycle-global-at-bob nil
1345 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1347 This makes it possible to do global cycling without having to use `S-TAB'
1348 or `\\[universal-argument] TAB'. For this special case to work, the first \
1349 line of the buffer
1350 must not be a headline -- it may be empty or some other text.
1352 When used in this way, `org-cycle-hook' is disabled temporarily to make
1353 sure the cursor stays at the beginning of the buffer.
1355 When this option is nil, don't do anything special at the beginning of
1356 the buffer."
1357 :group 'org-cycle
1358 :type 'boolean)
1360 (defcustom org-cycle-level-after-item/entry-creation t
1361 "Non-nil means cycle entry level or item indentation in new empty entries.
1363 When the cursor is at the end of an empty headline, i.e., with only stars
1364 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1365 and then all possible ancestor states, before returning to the original state.
1366 This makes data entry extremely fast: M-RET to create a new headline,
1367 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1369 When the cursor is at the end of an empty plain list item, one TAB will
1370 make it a subitem, two or more tabs will back up to make this an item
1371 higher up in the item hierarchy."
1372 :group 'org-cycle
1373 :type 'boolean)
1375 (defcustom org-cycle-emulate-tab t
1376 "Where should `org-cycle' emulate TAB.
1377 nil Never
1378 white Only in completely white lines
1379 whitestart Only at the beginning of lines, before the first non-white char
1380 t Everywhere except in headlines
1381 exc-hl-bol Everywhere except at the start of a headline
1382 If TAB is used in a place where it does not emulate TAB, the current subtree
1383 visibility is cycled."
1384 :group 'org-cycle
1385 :type '(choice (const :tag "Never" nil)
1386 (const :tag "Only in completely white lines" white)
1387 (const :tag "Before first char in a line" whitestart)
1388 (const :tag "Everywhere except in headlines" t)
1389 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1391 (defcustom org-cycle-separator-lines 2
1392 "Number of empty lines needed to keep an empty line between collapsed trees.
1393 If you leave an empty line between the end of a subtree and the following
1394 headline, this empty line is hidden when the subtree is folded.
1395 Org mode will leave (exactly) one empty line visible if the number of
1396 empty lines is equal or larger to the number given in this variable.
1397 So the default 2 means at least 2 empty lines after the end of a subtree
1398 are needed to produce free space between a collapsed subtree and the
1399 following headline.
1401 If the number is negative, and the number of empty lines is at least -N,
1402 all empty lines are shown.
1404 Special case: when 0, never leave empty lines in collapsed view."
1405 :group 'org-cycle
1406 :type 'integer)
1407 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1409 (defcustom org-pre-cycle-hook nil
1410 "Hook that is run before visibility cycling is happening.
1411 The function(s) in this hook must accept a single argument which indicates
1412 the new state that will be set right after running this hook. The
1413 argument is a symbol. Before a global state change, it can have the values
1414 `overview', `content', or `all'. Before a local state change, it can have
1415 the values `folded', `children', or `subtree'."
1416 :group 'org-cycle
1417 :type 'hook)
1419 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1420 org-cycle-hide-drawers
1421 org-cycle-show-empty-lines
1422 org-optimize-window-after-visibility-change)
1423 "Hook that is run after `org-cycle' has changed the buffer visibility.
1424 The function(s) in this hook must accept a single argument which indicates
1425 the new state that was set by the most recent `org-cycle' command. The
1426 argument is a symbol. After a global state change, it can have the values
1427 `overview', `contents', or `all'. After a local state change, it can have
1428 the values `folded', `children', or `subtree'."
1429 :group 'org-cycle
1430 :type 'hook
1431 :version "26.1"
1432 :package-version '(Org . "8.3"))
1434 (defgroup org-edit-structure nil
1435 "Options concerning structure editing in Org mode."
1436 :tag "Org Edit Structure"
1437 :group 'org-structure)
1439 (defcustom org-odd-levels-only nil
1440 "Non-nil means skip even levels and only use odd levels for the outline.
1441 This has the effect that two stars are being added/taken away in
1442 promotion/demotion commands. It also influences how levels are
1443 handled by the exporters.
1444 Changing it requires restart of `font-lock-mode' to become effective
1445 for fontification also in regions already fontified.
1446 You may also set this on a per-file basis by adding one of the following
1447 lines to the buffer:
1449 #+STARTUP: odd
1450 #+STARTUP: oddeven"
1451 :group 'org-edit-structure
1452 :group 'org-appearance
1453 :type 'boolean)
1455 (defcustom org-adapt-indentation t
1456 "Non-nil means adapt indentation to outline node level.
1458 When this variable is set, Org assumes that you write outlines by
1459 indenting text in each node to align with the headline (after the
1460 stars). The following issues are influenced by this variable:
1462 - The indentation is increased by one space in a demotion
1463 command, and decreased by one in a promotion command. However,
1464 in the latter case, if shifting some line in the entry body
1465 would alter document structure (e.g., insert a new headline),
1466 indentation is not changed at all.
1468 - Property drawers and planning information is inserted indented
1469 when this variable is set. When nil, they will not be indented.
1471 - TAB indents a line relative to current level. The lines below
1472 a headline will be indented when this variable is set.
1474 Note that this is all about true indentation, by adding and
1475 removing space characters. See also `org-indent.el' which does
1476 level-dependent indentation in a virtual way, i.e. at display
1477 time in Emacs."
1478 :group 'org-edit-structure
1479 :type 'boolean)
1481 (defcustom org-special-ctrl-a/e nil
1482 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1484 When t, `C-a' will bring back the cursor to the beginning of the
1485 headline text, i.e. after the stars and after a possible TODO
1486 keyword. In an item, this will be the position after bullet and
1487 check-box, if any. When the cursor is already at that position,
1488 another `C-a' will bring it to the beginning of the line.
1490 `C-e' will jump to the end of the headline, ignoring the presence
1491 of tags in the headline. A second `C-e' will then jump to the
1492 true end of the line, after any tags. This also means that, when
1493 this variable is non-nil, `C-e' also will never jump beyond the
1494 end of the heading of a folded section, i.e. not after the
1495 ellipses.
1497 When set to the symbol `reversed', the first `C-a' or `C-e' works
1498 normally, going to the true line boundary first. Only a directly
1499 following, identical keypress will bring the cursor to the
1500 special positions.
1502 This may also be a cons cell where the behavior for `C-a' and
1503 `C-e' is set separately."
1504 :group 'org-edit-structure
1505 :type '(choice
1506 (const :tag "off" nil)
1507 (const :tag "on: after stars/bullet and before tags first" t)
1508 (const :tag "reversed: true line boundary first" reversed)
1509 (cons :tag "Set C-a and C-e separately"
1510 (choice :tag "Special C-a"
1511 (const :tag "off" nil)
1512 (const :tag "on: after stars/bullet first" t)
1513 (const :tag "reversed: before stars/bullet first" reversed))
1514 (choice :tag "Special C-e"
1515 (const :tag "off" nil)
1516 (const :tag "on: before tags first" t)
1517 (const :tag "reversed: after tags first" reversed)))))
1518 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1520 (defcustom org-special-ctrl-k nil
1521 "Non-nil means `C-k' will behave specially in headlines.
1522 When nil, `C-k' will call the default `kill-line' command.
1523 When t, the following will happen while the cursor is in the headline:
1525 - When the cursor is at the beginning of a headline, kill the entire
1526 line and possible the folded subtree below the line.
1527 - When in the middle of the headline text, kill the headline up to the tags.
1528 - When after the headline text, kill the tags."
1529 :group 'org-edit-structure
1530 :type 'boolean)
1532 (defcustom org-ctrl-k-protect-subtree nil
1533 "Non-nil means, do not delete a hidden subtree with C-k.
1534 When set to the symbol `error', simply throw an error when C-k is
1535 used to kill (part-of) a headline that has hidden text behind it.
1536 Any other non-nil value will result in a query to the user, if it is
1537 OK to kill that hidden subtree. When nil, kill without remorse."
1538 :group 'org-edit-structure
1539 :version "24.1"
1540 :type '(choice
1541 (const :tag "Do not protect hidden subtrees" nil)
1542 (const :tag "Protect hidden subtrees with a security query" t)
1543 (const :tag "Never kill a hidden subtree with C-k" error)))
1545 (defcustom org-special-ctrl-o t
1546 "Non-nil means, make `C-o' insert a row in tables."
1547 :group 'org-edit-structure
1548 :type 'boolean)
1550 (defcustom org-catch-invisible-edits nil
1551 "Check if in invisible region before inserting or deleting a character.
1552 Valid values are:
1554 nil Do not check, so just do invisible edits.
1555 error Throw an error and do nothing.
1556 show Make point visible, and do the requested edit.
1557 show-and-error Make point visible, then throw an error and abort the edit.
1558 smart Make point visible, and do insertion/deletion if it is
1559 adjacent to visible text and the change feels predictable.
1560 Never delete a previously invisible character or add in the
1561 middle or right after an invisible region. Basically, this
1562 allows insertion and backward-delete right before ellipses.
1563 FIXME: maybe in this case we should not even show?"
1564 :group 'org-edit-structure
1565 :version "24.1"
1566 :type '(choice
1567 (const :tag "Do not check" nil)
1568 (const :tag "Throw error when trying to edit" error)
1569 (const :tag "Unhide, but do not do the edit" show-and-error)
1570 (const :tag "Show invisible part and do the edit" show)
1571 (const :tag "Be smart and do the right thing" smart)))
1573 (defcustom org-yank-folded-subtrees t
1574 "Non-nil means when yanking subtrees, fold them.
1575 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1576 it starts with a heading and all other headings in it are either children
1577 or siblings, then fold all the subtrees. However, do this only if no
1578 text after the yank would be swallowed into a folded tree by this action."
1579 :group 'org-edit-structure
1580 :type 'boolean)
1582 (defcustom org-yank-adjusted-subtrees nil
1583 "Non-nil means when yanking subtrees, adjust the level.
1584 With this setting, `org-paste-subtree' is used to insert the subtree, see
1585 this function for details."
1586 :group 'org-edit-structure
1587 :type 'boolean)
1589 (defcustom org-M-RET-may-split-line '((default . t))
1590 "Non-nil means M-RET will split the line at the cursor position.
1591 When nil, it will go to the end of the line before making a
1592 new line.
1593 You may also set this option in a different way for different
1594 contexts. Valid contexts are:
1596 headline when creating a new headline
1597 item when creating a new item
1598 table in a table field
1599 default the value to be used for all contexts not explicitly
1600 customized"
1601 :group 'org-structure
1602 :group 'org-table
1603 :type '(choice
1604 (const :tag "Always" t)
1605 (const :tag "Never" nil)
1606 (repeat :greedy t :tag "Individual contexts"
1607 (cons
1608 (choice :tag "Context"
1609 (const headline)
1610 (const item)
1611 (const table)
1612 (const default))
1613 (boolean)))))
1616 (defcustom org-insert-heading-respect-content nil
1617 "Non-nil means insert new headings after the current subtree.
1618 \\<org-mode-map>
1619 When nil, the new heading is created directly after the current line.
1620 The commands `\\[org-insert-heading-respect-content]' and \
1621 `\\[org-insert-todo-heading-respect-content]' turn this variable on
1622 for the duration of the command."
1623 :group 'org-structure
1624 :type 'boolean)
1626 (defcustom org-blank-before-new-entry '((heading . auto)
1627 (plain-list-item . auto))
1628 "Should `org-insert-heading' leave a blank line before new heading/item?
1629 The value is an alist, with `heading' and `plain-list-item' as CAR,
1630 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1631 which case Org will look at the surrounding headings/items and try to
1632 make an intelligent decision whether to insert a blank line or not."
1633 :group 'org-edit-structure
1634 :type '(list
1635 (cons (const heading)
1636 (choice (const :tag "Never" nil)
1637 (const :tag "Always" t)
1638 (const :tag "Auto" auto)))
1639 (cons (const plain-list-item)
1640 (choice (const :tag "Never" nil)
1641 (const :tag "Always" t)
1642 (const :tag "Auto" auto)))))
1644 (defcustom org-insert-heading-hook nil
1645 "Hook being run after inserting a new heading."
1646 :group 'org-edit-structure
1647 :type 'hook)
1649 (defcustom org-enable-fixed-width-editor t
1650 "Non-nil means lines starting with \":\" are treated as fixed-width.
1651 This currently only means they are never auto-wrapped.
1652 When nil, such lines will be treated like ordinary lines."
1653 :group 'org-edit-structure
1654 :type 'boolean)
1656 (defcustom org-goto-auto-isearch t
1657 "Non-nil means typing characters in `org-goto' starts incremental search.
1658 When nil, you can use these keybindings to navigate the buffer:
1660 q Quit the org-goto interface
1661 n Go to the next visible heading
1662 p Go to the previous visible heading
1663 f Go one heading forward on same level
1664 b Go one heading backward on same level
1665 u Go one heading up"
1666 :group 'org-edit-structure
1667 :type 'boolean)
1669 (defgroup org-sparse-trees nil
1670 "Options concerning sparse trees in Org mode."
1671 :tag "Org Sparse Trees"
1672 :group 'org-structure)
1674 (defcustom org-highlight-sparse-tree-matches t
1675 "Non-nil means highlight all matches that define a sparse tree.
1676 The highlights will automatically disappear the next time the buffer is
1677 changed by an edit command."
1678 :group 'org-sparse-trees
1679 :type 'boolean)
1681 (defcustom org-remove-highlights-with-change t
1682 "Non-nil means any change to the buffer will remove temporary highlights.
1683 \\<org-mode-map>\
1684 Such highlights are created by `org-occur' and `org-clock-display'.
1685 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1686 to get rid of the highlights.
1687 The highlights created by `org-toggle-latex-fragment' always need
1688 `\\[org-toggle-latex-fragment]' to be removed."
1689 :group 'org-sparse-trees
1690 :group 'org-time
1691 :type 'boolean)
1693 (defcustom org-occur-case-fold-search t
1694 "Non-nil means `org-occur' should be case-insensitive.
1695 If set to `smart' the search will be case-insensitive only if it
1696 doesn't specify any upper case character."
1697 :group 'org-sparse-trees
1698 :version "26.1"
1699 :type '(choice
1700 (const :tag "Case-sensitive" nil)
1701 (const :tag "Case-insensitive" t)
1702 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1704 (defcustom org-occur-hook '(org-first-headline-recenter)
1705 "Hook that is run after `org-occur' has constructed a sparse tree.
1706 This can be used to recenter the window to show as much of the structure
1707 as possible."
1708 :group 'org-sparse-trees
1709 :type 'hook)
1711 (defgroup org-imenu-and-speedbar nil
1712 "Options concerning imenu and speedbar in Org mode."
1713 :tag "Org Imenu and Speedbar"
1714 :group 'org-structure)
1716 (defcustom org-imenu-depth 2
1717 "The maximum level for Imenu access to Org headlines.
1718 This also applied for speedbar access."
1719 :group 'org-imenu-and-speedbar
1720 :type 'integer)
1722 (defgroup org-table nil
1723 "Options concerning tables in Org mode."
1724 :tag "Org Table"
1725 :group 'org)
1727 (defcustom org-enable-table-editor 'optimized
1728 "Non-nil means lines starting with \"|\" are handled by the table editor.
1729 When nil, such lines will be treated like ordinary lines.
1731 When equal to the symbol `optimized', the table editor will be optimized to
1732 do the following:
1733 - Automatic overwrite mode in front of whitespace in table fields.
1734 This makes the structure of the table stay in tact as long as the edited
1735 field does not exceed the column width.
1736 - Minimize the number of realigns. Normally, the table is aligned each time
1737 TAB or RET are pressed to move to another field. With optimization this
1738 happens only if changes to a field might have changed the column width.
1739 Optimization requires replacing the functions `self-insert-command',
1740 `delete-char', and `backward-delete-char' in Org buffers, with a
1741 slight (in fact: unnoticeable) speed impact for normal typing. Org is very
1742 good at guessing when a re-align will be necessary, but you can always
1743 force one with `\\[org-ctrl-c-ctrl-c]'.
1745 If you would like to use the optimized version in Org mode, but the
1746 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1748 This variable can be used to turn on and off the table editor during a session,
1749 but in order to toggle optimization, a restart is required.
1751 See also the variable `org-table-auto-blank-field'."
1752 :group 'org-table
1753 :type '(choice
1754 (const :tag "off" nil)
1755 (const :tag "on" t)
1756 (const :tag "on, optimized" optimized)))
1758 (defcustom org-self-insert-cluster-for-undo nil
1759 "Non-nil means cluster self-insert commands for undo when possible.
1760 If this is set, then, like in the Emacs command loop, 20 consecutive
1761 characters will be undone together.
1762 This is configurable, because there is some impact on typing performance."
1763 :group 'org-table
1764 :type 'boolean)
1766 (defcustom org-table-tab-recognizes-table.el t
1767 "Non-nil means TAB will automatically notice a table.el table.
1768 When it sees such a table, it moves point into it and - if necessary -
1769 calls `table-recognize-table'."
1770 :group 'org-table-editing
1771 :type 'boolean)
1773 (defgroup org-link nil
1774 "Options concerning links in Org mode."
1775 :tag "Org Link"
1776 :group 'org)
1778 (defvar-local org-link-abbrev-alist-local nil
1779 "Buffer-local version of `org-link-abbrev-alist', which see.
1780 The value of this is taken from the #+LINK lines.")
1782 (defcustom org-link-parameters
1783 '(("doi" :follow org--open-doi-link)
1784 ("elisp" :follow org--open-elisp-link)
1785 ("file" :complete org-file-complete-link)
1786 ("ftp" :follow (lambda (path) (browse-url (concat "ftp:" path))))
1787 ("help" :follow org--open-help-link)
1788 ("http" :follow (lambda (path) (browse-url (concat "http:" path))))
1789 ("https" :follow (lambda (path) (browse-url (concat "https:" path))))
1790 ("mailto" :follow (lambda (path) (browse-url (concat "mailto:" path))))
1791 ("message" :follow (lambda (path) (browse-url (concat "message:" path))))
1792 ("news" :follow (lambda (path) (browse-url (concat "news:" path))))
1793 ("shell" :follow org--open-shell-link))
1794 "An alist of properties that defines all the links in Org mode.
1795 The key in each association is a string of the link type.
1796 Subsequent optional elements make up a p-list of link properties.
1798 :follow - A function that takes the link path as an argument.
1800 :export - A function that takes the link path, description and
1801 export-backend as arguments.
1803 :store - A function responsible for storing the link. See the
1804 function `org-store-link-functions'.
1806 :complete - A function that inserts a link with completion. The
1807 function takes one optional prefix arg.
1809 :face - A face for the link, or a function that returns a face.
1810 The function takes one argument which is the link path. The
1811 default face is `org-link'.
1813 :mouse-face - The mouse-face. The default is `highlight'.
1815 :display - `full' will not fold the link in descriptive
1816 display. Default is `org-link'.
1818 :help-echo - A string or function that takes (window object position)
1819 as arguments and returns a string.
1821 :keymap - A keymap that is active on the link. The default is
1822 `org-mouse-map'.
1824 :htmlize-link - A function for the htmlize-link. Defaults
1825 to (list :uri \"type:path\")
1827 :activate-func - A function to run at the end of font-lock
1828 activation. The function must accept (link-start link-end path bracketp)
1829 as arguments."
1830 :group 'org-link
1831 :type '(alist :tag "Link display parameters"
1832 :value-type plist))
1834 (defun org-link-get-parameter (type key)
1835 "Get TYPE link property for KEY.
1836 TYPE is a string and KEY is a plist keyword."
1837 (plist-get
1838 (cdr (assoc type org-link-parameters))
1839 key))
1841 (defun org-link-set-parameters (type &rest parameters)
1842 "Set link TYPE properties to PARAMETERS.
1843 PARAMETERS should be :key val pairs."
1844 (let ((data (assoc type org-link-parameters)))
1845 (if data (setcdr data (org-combine-plists (cdr data) parameters))
1846 (push (cons type parameters) org-link-parameters)
1847 (org-make-link-regexps)
1848 (org-element-update-syntax))))
1850 (defun org-link-types ()
1851 "Return a list of known link types."
1852 (mapcar #'car org-link-parameters))
1854 (defcustom org-link-abbrev-alist nil
1855 "Alist of link abbreviations.
1856 The car of each element is a string, to be replaced at the start of a link.
1857 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1858 links in Org buffers can have an optional tag after a double colon, e.g.,
1860 [[linkkey:tag][description]]
1862 The `linkkey' must be a single word, starting with a letter, followed
1863 by letters, numbers, `-' or `_'.
1865 If REPLACE is a string, the tag will simply be appended to create the link.
1866 If the string contains \"%s\", the tag will be inserted there. If the string
1867 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1868 at that point (see the function `url-hexify-string'). If the string contains
1869 the specifier \"%(my-function)\", then the custom function `my-function' will
1870 be invoked: this function takes the tag as its only argument and must return
1871 a string.
1873 REPLACE may also be a function that will be called with the tag as the
1874 only argument to create the link, which should be returned as a string.
1876 See the manual for examples."
1877 :group 'org-link
1878 :type '(repeat
1879 (cons
1880 (string :tag "Protocol")
1881 (choice
1882 (string :tag "Format")
1883 (function)))))
1885 (defcustom org-descriptive-links t
1886 "Non-nil means Org will display descriptive links.
1887 E.g. [[http://orgmode.org][Org website]] will be displayed as
1888 \"Org Website\", hiding the link itself and just displaying its
1889 description. When set to nil, Org will display the full links
1890 literally.
1892 You can interactively set the value of this variable by calling
1893 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1894 :group 'org-link
1895 :type 'boolean)
1897 (defcustom org-link-file-path-type 'adaptive
1898 "How the path name in file links should be stored.
1899 Valid values are:
1901 relative Relative to the current directory, i.e. the directory of the file
1902 into which the link is being inserted.
1903 absolute Absolute path, if possible with ~ for home directory.
1904 noabbrev Absolute path, no abbreviation of home directory.
1905 adaptive Use relative path for files in the current directory and sub-
1906 directories of it. For other files, use an absolute path."
1907 :group 'org-link
1908 :type '(choice
1909 (const relative)
1910 (const absolute)
1911 (const noabbrev)
1912 (const adaptive)))
1914 (defvaralias 'org-activate-links 'org-highlight-links)
1915 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1916 "Types of links that should be highlighted in Org files.
1918 This is a list of symbols, each one of them leading to the
1919 highlighting of a certain link type.
1921 You can still open links that are not highlighted.
1923 In principle, it does not hurt to turn on highlighting for all
1924 link types. There may be a small gain when turning off unused
1925 link types. The types are:
1927 bracket The recommended [[link][description]] or [[link]] links with hiding.
1928 angle Links in angular brackets that may contain whitespace like
1929 <bbdb:Carsten Dominik>.
1930 plain Plain links in normal text, no whitespace, like http://google.com.
1931 radio Text that is matched by a radio target, see manual for details.
1932 tag Tag settings in a headline (link to tag search).
1933 date Time stamps (link to calendar).
1934 footnote Footnote labels.
1936 If you set this variable during an Emacs session, use `org-mode-restart'
1937 in the Org buffer so that the change takes effect."
1938 :group 'org-link
1939 :group 'org-appearance
1940 :type '(set :greedy t
1941 (const :tag "Double bracket links" bracket)
1942 (const :tag "Angular bracket links" angle)
1943 (const :tag "Plain text links" plain)
1944 (const :tag "Radio target matches" radio)
1945 (const :tag "Tags" tag)
1946 (const :tag "Timestamps" date)
1947 (const :tag "Footnotes" footnote)))
1949 (defcustom org-make-link-description-function nil
1950 "Function to use for generating link descriptions from links.
1951 When nil, the link location will be used. This function must take
1952 two parameters: the first one is the link, the second one is the
1953 description generated by `org-insert-link'. The function should
1954 return the description to use."
1955 :group 'org-link
1956 :type '(choice (const nil) (function)))
1958 (defgroup org-link-store nil
1959 "Options concerning storing links in Org mode."
1960 :tag "Org Store Link"
1961 :group 'org-link)
1963 (defcustom org-url-hexify-p t
1964 "When non-nil, hexify URL when creating a link."
1965 :type 'boolean
1966 :version "24.3"
1967 :group 'org-link-store)
1969 (defcustom org-email-link-description-format "Email %c: %.30s"
1970 "Format of the description part of a link to an email or usenet message.
1971 The following %-escapes will be replaced by corresponding information:
1973 %F full \"From\" field
1974 %f name, taken from \"From\" field, address if no name
1975 %T full \"To\" field
1976 %t first name in \"To\" field, address if no name
1977 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1978 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1979 %s subject
1980 %d date
1981 %m message-id.
1983 You may use normal field width specification between the % and the letter.
1984 This is for example useful to limit the length of the subject.
1986 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1987 :group 'org-link-store
1988 :type 'string)
1990 (defcustom org-from-is-user-regexp
1991 (let (r1 r2)
1992 (when (and user-mail-address (not (string= user-mail-address "")))
1993 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1994 (when (and user-full-name (not (string= user-full-name "")))
1995 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1996 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1997 "Regexp matched against the \"From:\" header of an email or usenet message.
1998 It should match if the message is from the user him/herself."
1999 :group 'org-link-store
2000 :type 'regexp)
2002 (defcustom org-context-in-file-links t
2003 "Non-nil means file links from `org-store-link' contain context.
2004 \\<org-mode-map>
2005 A search string will be added to the file name with :: as separator
2006 and used to find the context when the link is activated by the command
2007 `org-open-at-point'. When this option is t, the entire active region
2008 will be placed in the search string of the file link. If set to a
2009 positive integer, only the first n lines of context will be stored.
2011 Using a prefix arg to the command `org-store-link' (`\\[universal-argument] \
2012 \\[org-store-link]')
2013 negates this setting for the duration of the command."
2014 :group 'org-link-store
2015 :type '(choice boolean integer))
2017 (defcustom org-keep-stored-link-after-insertion nil
2018 "Non-nil means keep link in list for entire session.
2019 \\<org-mode-map>
2020 The command `org-store-link' adds a link pointing to the current
2021 location to an internal list. These links accumulate during a session.
2022 The command `org-insert-link' can be used to insert links into any
2023 Org file (offering completion for all stored links).
2025 When this option is nil, every link which has been inserted once using
2026 `\\[org-insert-link]' will be removed from the list, to make completing the \
2027 unused
2028 links more efficient."
2029 :group 'org-link-store
2030 :type 'boolean)
2032 (defgroup org-link-follow nil
2033 "Options concerning following links in Org mode."
2034 :tag "Org Follow Link"
2035 :group 'org-link)
2037 (defcustom org-link-translation-function nil
2038 "Function to translate links with different syntax to Org syntax.
2039 This can be used to translate links created for example by the Planner
2040 or emacs-wiki packages to Org syntax.
2041 The function must accept two parameters, a TYPE containing the link
2042 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
2043 which is everything after the link protocol. It should return a cons
2044 with possibly modified values of type and path.
2045 Org contains a function for this, so if you set this variable to
2046 `org-translate-link-from-planner', you should be able follow many
2047 links created by planner."
2048 :group 'org-link-follow
2049 :type '(choice (const nil) (function)))
2051 (defcustom org-follow-link-hook nil
2052 "Hook that is run after a link has been followed."
2053 :group 'org-link-follow
2054 :type 'hook)
2056 (defcustom org-tab-follows-link nil
2057 "Non-nil means on links TAB will follow the link.
2058 Needs to be set before org.el is loaded.
2059 This really should not be used, it does not make sense, and the
2060 implementation is bad."
2061 :group 'org-link-follow
2062 :type 'boolean)
2064 (defcustom org-return-follows-link nil
2065 "Non-nil means on links RET will follow the link.
2066 In tables, the special behavior of RET has precedence."
2067 :group 'org-link-follow
2068 :type 'boolean)
2070 (defcustom org-mouse-1-follows-link
2071 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
2072 "Non-nil means mouse-1 on a link will follow the link.
2073 A longer mouse click will still set point. Needs to be set
2074 before org.el is loaded."
2075 :group 'org-link-follow
2076 :version "24.4"
2077 :package-version '(Org . "8.3")
2078 :type '(choice
2079 (const :tag "A double click follows the link" double)
2080 (const :tag "Unconditionally follow the link with mouse-1" t)
2081 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
2083 (defcustom org-mark-ring-length 4
2084 "Number of different positions to be recorded in the ring.
2085 Changing this requires a restart of Emacs to work correctly."
2086 :group 'org-link-follow
2087 :type 'integer)
2089 (defcustom org-link-search-must-match-exact-headline 'query-to-create
2090 "Non-nil means internal fuzzy links can only match headlines.
2092 When nil, the a fuzzy link may point to a target or a named
2093 construct in the document. When set to the special value
2094 `query-to-create', offer to create a new headline when none
2095 matched.
2097 Spaces and statistics cookies are ignored during heading searches."
2098 :group 'org-link-follow
2099 :version "24.1"
2100 :type '(choice
2101 (const :tag "Use fuzzy text search" nil)
2102 (const :tag "Match only exact headline" t)
2103 (const :tag "Match exact headline or query to create it"
2104 query-to-create))
2105 :safe #'symbolp)
2107 (defcustom org-link-frame-setup
2108 '((vm . vm-visit-folder-other-frame)
2109 (vm-imap . vm-visit-imap-folder-other-frame)
2110 (gnus . org-gnus-no-new-news)
2111 (file . find-file-other-window)
2112 (wl . wl-other-frame))
2113 "Setup the frame configuration for following links.
2114 When following a link with Emacs, it may often be useful to display
2115 this link in another window or frame. This variable can be used to
2116 set this up for the different types of links.
2117 For VM, use any of
2118 `vm-visit-folder'
2119 `vm-visit-folder-other-window'
2120 `vm-visit-folder-other-frame'
2121 For Gnus, use any of
2122 `gnus'
2123 `gnus-other-frame'
2124 `org-gnus-no-new-news'
2125 For FILE, use any of
2126 `find-file'
2127 `find-file-other-window'
2128 `find-file-other-frame'
2129 For Wanderlust use any of
2130 `wl'
2131 `wl-other-frame'
2132 For the calendar, use the variable `calendar-setup'.
2133 For BBDB, it is currently only possible to display the matches in
2134 another window."
2135 :group 'org-link-follow
2136 :type '(list
2137 (cons (const vm)
2138 (choice
2139 (const vm-visit-folder)
2140 (const vm-visit-folder-other-window)
2141 (const vm-visit-folder-other-frame)))
2142 (cons (const vm-imap)
2143 (choice
2144 (const vm-visit-imap-folder)
2145 (const vm-visit-imap-folder-other-window)
2146 (const vm-visit-imap-folder-other-frame)))
2147 (cons (const gnus)
2148 (choice
2149 (const gnus)
2150 (const gnus-other-frame)
2151 (const org-gnus-no-new-news)))
2152 (cons (const file)
2153 (choice
2154 (const find-file)
2155 (const find-file-other-window)
2156 (const find-file-other-frame)))
2157 (cons (const wl)
2158 (choice
2159 (const wl)
2160 (const wl-other-frame)))))
2162 (defcustom org-display-internal-link-with-indirect-buffer nil
2163 "Non-nil means use indirect buffer to display infile links.
2164 Activating internal links (from one location in a file to another location
2165 in the same file) normally just jumps to the location. When the link is
2166 activated with a `\\[universal-argument]' prefix (or with mouse-3), the link \
2167 is displayed in
2168 another window. When this option is set, the other window actually displays
2169 an indirect buffer clone of the current buffer, to avoid any visibility
2170 changes to the current buffer."
2171 :group 'org-link-follow
2172 :type 'boolean)
2174 (defcustom org-open-non-existing-files nil
2175 "Non-nil means `org-open-file' will open non-existing files.
2176 When nil, an error will be generated.
2177 This variable applies only to external applications because they
2178 might choke on non-existing files. If the link is to a file that
2179 will be opened in Emacs, the variable is ignored."
2180 :group 'org-link-follow
2181 :type 'boolean)
2183 (defcustom org-open-directory-means-index-dot-org nil
2184 "Non-nil means a link to a directory really means to index.org.
2185 When nil, following a directory link will run dired or open a finder/explorer
2186 window on that directory."
2187 :group 'org-link-follow
2188 :type 'boolean)
2190 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2191 "Non-nil means ask for confirmation before executing shell links.
2192 Shell links can be dangerous: just think about a link
2194 [[shell:rm -rf ~/*][Google Search]]
2196 This link would show up in your Org document as \"Google Search\",
2197 but really it would remove your entire home directory.
2198 Therefore we advise against setting this variable to nil.
2199 Just change it to `y-or-n-p' if you want to confirm with a
2200 single keystroke rather than having to type \"yes\"."
2201 :group 'org-link-follow
2202 :type '(choice
2203 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2204 (const :tag "with y-or-n (faster)" y-or-n-p)
2205 (const :tag "no confirmation (dangerous)" nil)))
2206 (put 'org-confirm-shell-link-function
2207 'safe-local-variable
2208 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2210 (defcustom org-confirm-shell-link-not-regexp ""
2211 "A regexp to skip confirmation for shell links."
2212 :group 'org-link-follow
2213 :version "24.1"
2214 :type 'regexp)
2216 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2217 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2218 Elisp links can be dangerous: just think about a link
2220 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2222 This link would show up in your Org document as \"Google Search\",
2223 but really it would remove your entire home directory.
2224 Therefore we advise against setting this variable to nil.
2225 Just change it to `y-or-n-p' if you want to confirm with a
2226 single keystroke rather than having to type \"yes\"."
2227 :group 'org-link-follow
2228 :type '(choice
2229 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2230 (const :tag "with y-or-n (faster)" y-or-n-p)
2231 (const :tag "no confirmation (dangerous)" nil)))
2232 (put 'org-confirm-shell-link-function
2233 'safe-local-variable
2234 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2236 (defcustom org-confirm-elisp-link-not-regexp ""
2237 "A regexp to skip confirmation for Elisp links."
2238 :group 'org-link-follow
2239 :version "24.1"
2240 :type 'regexp)
2242 (defconst org-file-apps-defaults-gnu
2243 '((remote . emacs)
2244 (system . mailcap)
2245 (t . mailcap))
2246 "Default file applications on a UNIX or GNU/Linux system.
2247 See `org-file-apps'.")
2249 (defconst org-file-apps-defaults-macosx
2250 '((remote . emacs)
2251 (system . "open %s")
2252 ("ps.gz" . "gv %s")
2253 ("eps.gz" . "gv %s")
2254 ("dvi" . "xdvi %s")
2255 ("fig" . "xfig %s")
2256 (t . "open %s"))
2257 "Default file applications on a macOS system.
2258 The system \"open\" is known as a default, but we use X11 applications
2259 for some files for which the OS does not have a good default.
2260 See `org-file-apps'.")
2262 (defconst org-file-apps-defaults-windowsnt
2263 (list '(remote . emacs)
2264 (cons 'system (lambda (file _path)
2265 (with-no-warnings (w32-shell-execute "open" file))))
2266 (cons t (lambda (file _path)
2267 (with-no-warnings (w32-shell-execute "open" file)))))
2268 "Default file applications on a Windows NT system.
2269 The system \"open\" is used for most files.
2270 See `org-file-apps'.")
2272 (defcustom org-file-apps
2273 '((auto-mode . emacs)
2274 ("\\.mm\\'" . default)
2275 ("\\.x?html?\\'" . default)
2276 ("\\.pdf\\'" . default))
2277 "External applications for opening `file:path' items in a document.
2278 \\<org-mode-map>\
2280 Org mode uses system defaults for different file types, but
2281 you can use this variable to set the application for a given file
2282 extension. The entries in this list are cons cells where the car identifies
2283 files and the cdr the corresponding command.
2285 Possible values for the file identifier are:
2287 \"string\" A string as a file identifier can be interpreted in different
2288 ways, depending on its contents:
2290 - Alphanumeric characters only:
2291 Match links with this file extension.
2292 Example: (\"pdf\" . \"evince %s\")
2293 to open PDFs with evince.
2295 - Regular expression: Match links where the
2296 filename matches the regexp. If you want to
2297 use groups here, use shy groups.
2299 Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
2300 (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
2301 to open *.html and *.xhtml with firefox.
2303 - Regular expression which contains (non-shy) groups:
2304 Match links where the whole link, including \"::\", and
2305 anything after that, matches the regexp.
2306 In a custom command string, %1, %2, etc. are replaced with
2307 the parts of the link that were matched by the groups.
2308 For backwards compatibility, if a command string is given
2309 that does not use any of the group matches, this case is
2310 handled identically to the second one (i.e. match against
2311 file name only).
2312 In a custom function, you can access the group matches with
2313 (match-string n link).
2315 Example: (\"\\\\.pdf::\\\\(\\\\d+\\\\)\\\\\\='\" . \
2316 \"evince -p %1 %s\")
2317 to open [[file:document.pdf::5]] with evince at page 5.
2319 `directory' Matches a directory
2320 `remote' Matches a remote file, accessible through tramp or efs.
2321 Remote files most likely should be visited through Emacs
2322 because external applications cannot handle such paths.
2323 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2324 so all files Emacs knows how to handle. Using this with
2325 command `emacs' will open most files in Emacs. Beware that this
2326 will also open html files inside Emacs, unless you add
2327 (\"html\" . default) to the list as well.
2328 `system' The system command to open files, like `open' on Windows
2329 and macOS, and mailcap under GNU/Linux. This is the command
2330 that will be selected if you call `org-open-at-point' with a
2331 double prefix argument (`\\[universal-argument] \
2332 \\[universal-argument] \\[org-open-at-point]').
2333 t Default for files not matched by any of the other options.
2335 Possible values for the command are:
2337 `emacs' The file will be visited by the current Emacs process.
2338 `default' Use the default application for this file type, which is the
2339 association for t in the list, most likely in the system-specific
2340 part. This can be used to overrule an unwanted setting in the
2341 system-specific variable.
2342 `system' Use the system command for opening files, like \"open\".
2343 This command is specified by the entry whose car is `system'.
2344 Most likely, the system-specific version of this variable
2345 does define this command, but you can overrule/replace it
2346 here.
2347 `mailcap' Use command specified in the mailcaps.
2348 string A command to be executed by a shell; %s will be replaced
2349 by the path to the file.
2350 function A Lisp function, which will be called with two arguments:
2351 the file path and the original link string, without the
2352 \"file:\" prefix.
2354 For more examples, see the system specific constants
2355 `org-file-apps-defaults-macosx'
2356 `org-file-apps-defaults-windowsnt'
2357 `org-file-apps-defaults-gnu'."
2358 :group 'org-link-follow
2359 :type '(repeat
2360 (cons (choice :value ""
2361 (string :tag "Extension")
2362 (const :tag "System command to open files" system)
2363 (const :tag "Default for unrecognized files" t)
2364 (const :tag "Remote file" remote)
2365 (const :tag "Links to a directory" directory)
2366 (const :tag "Any files that have Emacs modes"
2367 auto-mode))
2368 (choice :value ""
2369 (const :tag "Visit with Emacs" emacs)
2370 (const :tag "Use default" default)
2371 (const :tag "Use the system command" system)
2372 (string :tag "Command")
2373 (function :tag "Function")))))
2375 (defcustom org-doi-server-url "http://dx.doi.org/"
2376 "The URL of the DOI server."
2377 :type 'string
2378 :version "24.3"
2379 :group 'org-link-follow)
2381 (defgroup org-refile nil
2382 "Options concerning refiling entries in Org mode."
2383 :tag "Org Refile"
2384 :group 'org)
2386 (defcustom org-directory "~/org"
2387 "Directory with Org files.
2388 This is just a default location to look for Org files. There is no need
2389 at all to put your files into this directory. It is used in the
2390 following situations:
2392 1. When a capture template specifies a target file that is not an
2393 absolute path. The path will then be interpreted relative to
2394 `org-directory'
2395 2. When the value of variable `org-agenda-files' is a single file, any
2396 relative paths in this file will be taken as relative to
2397 `org-directory'."
2398 :group 'org-refile
2399 :group 'org-capture
2400 :type 'directory)
2402 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2403 "Default target for storing notes.
2404 Used as a fall back file for org-capture.el, for templates that
2405 do not specify a target file."
2406 :group 'org-refile
2407 :group 'org-capture
2408 :type 'file)
2410 (defcustom org-goto-interface 'outline
2411 "The default interface to be used for `org-goto'.
2412 Allowed values are:
2413 outline The interface shows an outline of the relevant file
2414 and the correct heading is found by moving through
2415 the outline or by searching with incremental search.
2416 outline-path-completion Headlines in the current buffer are offered via
2417 completion. This is the interface also used by
2418 the refile command."
2419 :group 'org-refile
2420 :type '(choice
2421 (const :tag "Outline" outline)
2422 (const :tag "Outline-path-completion" outline-path-completion)))
2424 (defcustom org-goto-max-level 5
2425 "Maximum target level when running `org-goto' with refile interface."
2426 :group 'org-refile
2427 :type 'integer)
2429 (defcustom org-reverse-note-order nil
2430 "Non-nil means store new notes at the beginning of a file or entry.
2431 When nil, new notes will be filed to the end of a file or entry.
2432 This can also be a list with cons cells of regular expressions that
2433 are matched against file names, and values."
2434 :group 'org-capture
2435 :group 'org-refile
2436 :type '(choice
2437 (const :tag "Reverse always" t)
2438 (const :tag "Reverse never" nil)
2439 (repeat :tag "By file name regexp"
2440 (cons regexp boolean))))
2442 (defcustom org-log-refile nil
2443 "Information to record when a task is refiled.
2445 Possible values are:
2447 nil Don't add anything
2448 time Add a time stamp to the task
2449 note Prompt for a note and add it with template `org-log-note-headings'
2451 This option can also be set with on a per-file-basis with
2453 #+STARTUP: nologrefile
2454 #+STARTUP: logrefile
2455 #+STARTUP: lognoterefile
2457 You can have local logging settings for a subtree by setting the LOGGING
2458 property to one or more of these keywords.
2460 When bulk-refiling from the agenda, the value `note' is forbidden and
2461 will temporarily be changed to `time'."
2462 :group 'org-refile
2463 :group 'org-progress
2464 :version "24.1"
2465 :type '(choice
2466 (const :tag "No logging" nil)
2467 (const :tag "Record timestamp" time)
2468 (const :tag "Record timestamp with note." note)))
2470 (defcustom org-refile-targets nil
2471 "Targets for refiling entries with `\\[org-refile]'.
2472 This is a list of cons cells. Each cell contains:
2473 - a specification of the files to be considered, either a list of files,
2474 or a symbol whose function or variable value will be used to retrieve
2475 a file name or a list of file names. If you use `org-agenda-files' for
2476 that, all agenda files will be scanned for targets. Nil means consider
2477 headings in the current buffer.
2478 - A specification of how to find candidate refile targets. This may be
2479 any of:
2480 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2481 This tag has to be present in all target headlines, inheritance will
2482 not be considered.
2483 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2484 todo keyword.
2485 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2486 headlines that are refiling targets.
2487 - a cons cell (:level . N). Any headline of level N is considered a target.
2488 Note that, when `org-odd-levels-only' is set, level corresponds to
2489 order in hierarchy, not to the number of stars.
2490 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2491 Note that, when `org-odd-levels-only' is set, level corresponds to
2492 order in hierarchy, not to the number of stars.
2494 Each element of this list generates a set of possible targets.
2495 The union of these sets is presented (with completion) to
2496 the user by `org-refile'.
2498 You can set the variable `org-refile-target-verify-function' to a function
2499 to verify each headline found by the simple criteria above.
2501 When this variable is nil, all top-level headlines in the current buffer
2502 are used, equivalent to the value `((nil . (:level . 1))'."
2503 :group 'org-refile
2504 :type '(repeat
2505 (cons
2506 (choice :value org-agenda-files
2507 (const :tag "All agenda files" org-agenda-files)
2508 (const :tag "Current buffer" nil)
2509 (function) (variable) (file))
2510 (choice :tag "Identify target headline by"
2511 (cons :tag "Specific tag" (const :value :tag) (string))
2512 (cons :tag "TODO keyword" (const :value :todo) (string))
2513 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2514 (cons :tag "Level number" (const :value :level) (integer))
2515 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2517 (defcustom org-refile-target-verify-function nil
2518 "Function to verify if the headline at point should be a refile target.
2519 The function will be called without arguments, with point at the
2520 beginning of the headline. It should return t and leave point
2521 where it is if the headline is a valid target for refiling.
2523 If the target should not be selected, the function must return nil.
2524 In addition to this, it may move point to a place from where the search
2525 should be continued. For example, the function may decide that the entire
2526 subtree of the current entry should be excluded and move point to the end
2527 of the subtree."
2528 :group 'org-refile
2529 :type '(choice
2530 (const nil)
2531 (function)))
2533 (defcustom org-refile-use-cache nil
2534 "Non-nil means cache refile targets to speed up the process.
2535 \\<org-mode-map>\
2536 The cache for a particular file will be updated automatically when
2537 the buffer has been killed, or when any of the marker used for flagging
2538 refile targets no longer points at a live buffer.
2539 If you have added new entries to a buffer that might themselves be targets,
2540 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2541 if you find that easier, \
2542 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2543 \\[org-refile]'."
2544 :group 'org-refile
2545 :version "24.1"
2546 :type 'boolean)
2548 (defcustom org-refile-use-outline-path nil
2549 "Non-nil means provide refile targets as paths.
2550 So a level 3 headline will be available as level1/level2/level3.
2552 When the value is `file', also include the file name (without directory)
2553 into the path. In this case, you can also stop the completion after
2554 the file name, to get entries inserted as top level in the file.
2556 When `full-file-path', include the full file path."
2557 :group 'org-refile
2558 :type '(choice
2559 (const :tag "Not" nil)
2560 (const :tag "Yes" t)
2561 (const :tag "Start with file name" file)
2562 (const :tag "Start with full file path" full-file-path)))
2564 (defcustom org-outline-path-complete-in-steps t
2565 "Non-nil means complete the outline path in hierarchical steps.
2566 When Org uses the refile interface to select an outline path (see
2567 `org-refile-use-outline-path'), the completion of the path can be
2568 done in a single go, or it can be done in steps down the headline
2569 hierarchy. Going in steps is probably the best if you do not use
2570 a special completion package like `ido' or `icicles'. However,
2571 when using these packages, going in one step can be very fast,
2572 while still showing the whole path to the entry."
2573 :group 'org-refile
2574 :type 'boolean)
2576 (defcustom org-refile-allow-creating-parent-nodes nil
2577 "Non-nil means allow the creation of new nodes as refile targets.
2578 New nodes are then created by adding \"/new node name\" to the completion
2579 of an existing node. When the value of this variable is `confirm',
2580 new node creation must be confirmed by the user (recommended).
2581 When nil, the completion must match an existing entry.
2583 Note that, if the new heading is not seen by the criteria
2584 listed in `org-refile-targets', multiple instances of the same
2585 heading would be created by trying again to file under the new
2586 heading."
2587 :group 'org-refile
2588 :type '(choice
2589 (const :tag "Never" nil)
2590 (const :tag "Always" t)
2591 (const :tag "Prompt for confirmation" confirm)))
2593 (defcustom org-refile-active-region-within-subtree nil
2594 "Non-nil means also refile active region within a subtree.
2596 By default `org-refile' doesn't allow refiling regions if they
2597 don't contain a set of subtrees, but it might be convenient to
2598 do so sometimes: in that case, the first line of the region is
2599 converted to a headline before refiling."
2600 :group 'org-refile
2601 :version "24.1"
2602 :type 'boolean)
2604 (defgroup org-todo nil
2605 "Options concerning TODO items in Org mode."
2606 :tag "Org TODO"
2607 :group 'org)
2609 (defgroup org-progress nil
2610 "Options concerning Progress logging in Org mode."
2611 :tag "Org Progress"
2612 :group 'org-time)
2614 (defvar org-todo-interpretation-widgets
2615 '((:tag "Sequence (cycling hits every state)" sequence)
2616 (:tag "Type (cycling directly to DONE)" type))
2617 "The available interpretation symbols for customizing `org-todo-keywords'.
2618 Interested libraries should add to this list.")
2620 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2621 "List of TODO entry keyword sequences and their interpretation.
2622 \\<org-mode-map>This is a list of sequences.
2624 Each sequence starts with a symbol, either `sequence' or `type',
2625 indicating if the keywords should be interpreted as a sequence of
2626 action steps, or as different types of TODO items. The first
2627 keywords are states requiring action - these states will select a headline
2628 for inclusion into the global TODO list Org produces. If one of the
2629 \"keywords\" is the vertical bar, \"|\", the remaining keywords
2630 signify that no further action is necessary. If \"|\" is not found,
2631 the last keyword is treated as the only DONE state of the sequence.
2633 The command `\\[org-todo]' cycles an entry through these states, and one
2634 additional state where no keyword is present. For details about this
2635 cycling, see the manual.
2637 TODO keywords and interpretation can also be set on a per-file basis with
2638 the special #+SEQ_TODO and #+TYP_TODO lines.
2640 Each keyword can optionally specify a character for fast state selection
2641 \(in combination with the variable `org-use-fast-todo-selection')
2642 and specifiers for state change logging, using the same syntax that
2643 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2644 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2645 indicates to record a time stamp each time this state is selected.
2647 Each keyword may also specify if a timestamp or a note should be
2648 recorded when entering or leaving the state, by adding additional
2649 characters in the parenthesis after the keyword. This looks like this:
2650 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2651 record only the time of the state change. With X and Y being either
2652 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2653 Y when leaving the state if and only if the *target* state does not
2654 define X. You may omit any of the fast-selection key or X or /Y,
2655 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2657 For backward compatibility, this variable may also be just a list
2658 of keywords. In this case the interpretation (sequence or type) will be
2659 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2660 :group 'org-todo
2661 :group 'org-keywords
2662 :type '(choice
2663 (repeat :tag "Old syntax, just keywords"
2664 (string :tag "Keyword"))
2665 (repeat :tag "New syntax"
2666 (cons
2667 (choice
2668 :tag "Interpretation"
2669 ;;Quick and dirty way to see
2670 ;;`org-todo-interpretations'. This takes the
2671 ;;place of item arguments
2672 :convert-widget
2673 (lambda (widget)
2674 (widget-put widget
2675 :args (mapcar
2676 (lambda (x)
2677 (widget-convert
2678 (cons 'const x)))
2679 org-todo-interpretation-widgets))
2680 widget))
2681 (repeat
2682 (string :tag "Keyword"))))))
2684 (defvar-local org-todo-keywords-1 nil
2685 "All TODO and DONE keywords active in a buffer.")
2686 (defvar org-todo-keywords-for-agenda nil)
2687 (defvar org-done-keywords-for-agenda nil)
2688 (defvar org-todo-keyword-alist-for-agenda nil)
2689 (defvar org-tag-alist-for-agenda nil
2690 "Alist of all tags from all agenda files.")
2691 (defvar org-tag-groups-alist-for-agenda nil
2692 "Alist of all groups tags from all current agenda files.")
2693 (defvar-local org-tag-groups-alist nil)
2694 (defvar org-agenda-contributing-files nil)
2695 (defvar-local org-current-tag-alist nil
2696 "Alist of all tag groups in current buffer.
2697 This variable takes into consideration `org-tag-alist',
2698 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2699 (defvar-local org-not-done-keywords nil)
2700 (defvar-local org-done-keywords nil)
2701 (defvar-local org-todo-heads nil)
2702 (defvar-local org-todo-sets nil)
2703 (defvar-local org-todo-log-states nil)
2704 (defvar-local org-todo-kwd-alist nil)
2705 (defvar-local org-todo-key-alist nil)
2706 (defvar-local org-todo-key-trigger nil)
2708 (defcustom org-todo-interpretation 'sequence
2709 "Controls how TODO keywords are interpreted.
2710 This variable is in principle obsolete and is only used for
2711 backward compatibility, if the interpretation of todo keywords is
2712 not given already in `org-todo-keywords'. See that variable for
2713 more information."
2714 :group 'org-todo
2715 :group 'org-keywords
2716 :type '(choice (const sequence)
2717 (const type)))
2719 (defcustom org-use-fast-todo-selection t
2720 "\\<org-mode-map>\
2721 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
2722 This variable describes if and under what circumstances the cycling
2723 mechanism for TODO keywords will be replaced by a single-key, direct
2724 selection scheme.
2726 When nil, fast selection is never used.
2728 When the symbol `prefix', it will be used when `org-todo' is called
2729 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2730 in an Org buffer, and
2731 `\\[universal-argument] t' in an agenda buffer.
2733 When t, fast selection is used by default. In this case, the prefix
2734 argument forces cycling instead.
2736 In all cases, the special interface is only used if access keys have
2737 actually been assigned by the user, i.e. if keywords in the configuration
2738 are followed by a letter in parenthesis, like TODO(t)."
2739 :group 'org-todo
2740 :type '(choice
2741 (const :tag "Never" nil)
2742 (const :tag "By default" t)
2743 (const :tag "Only with C-u C-c C-t" prefix)))
2745 (defcustom org-provide-todo-statistics t
2746 "Non-nil means update todo statistics after insert and toggle.
2747 ALL-HEADLINES means update todo statistics by including headlines
2748 with no TODO keyword as well, counting them as not done.
2749 A list of TODO keywords means the same, but skip keywords that are
2750 not in this list.
2751 When set to a list of two lists, the first list contains keywords
2752 to consider as TODO keywords, the second list contains keywords
2753 to consider as DONE keywords.
2755 When this is set, todo statistics is updated in the parent of the
2756 current entry each time a todo state is changed."
2757 :group 'org-todo
2758 :type '(choice
2759 (const :tag "Yes, only for TODO entries" t)
2760 (const :tag "Yes, including all entries" all-headlines)
2761 (repeat :tag "Yes, for TODOs in this list"
2762 (string :tag "TODO keyword"))
2763 (list :tag "Yes, for TODOs and DONEs in these lists"
2764 (repeat (string :tag "TODO keyword"))
2765 (repeat (string :tag "DONE keyword")))
2766 (other :tag "No TODO statistics" nil)))
2768 (defcustom org-hierarchical-todo-statistics t
2769 "Non-nil means TODO statistics covers just direct children.
2770 When nil, all entries in the subtree are considered.
2771 This has only an effect if `org-provide-todo-statistics' is set.
2772 To set this to nil for only a single subtree, use a COOKIE_DATA
2773 property and include the word \"recursive\" into the value."
2774 :group 'org-todo
2775 :type 'boolean)
2777 (defcustom org-after-todo-state-change-hook nil
2778 "Hook which is run after the state of a TODO item was changed.
2779 The new state (a string with a TODO keyword, or nil) is available in the
2780 Lisp variable `org-state'."
2781 :group 'org-todo
2782 :type 'hook)
2784 (defvar org-blocker-hook nil
2785 "Hook for functions that are allowed to block a state change.
2787 Functions in this hook should not modify the buffer.
2788 Each function gets as its single argument a property list,
2789 see `org-trigger-hook' for more information about this list.
2791 If any of the functions in this hook returns nil, the state change
2792 is blocked.")
2794 (defvar org-trigger-hook nil
2795 "Hook for functions that are triggered by a state change.
2797 Each function gets as its single argument a property list with at
2798 least the following elements:
2800 (:type type-of-change :position pos-at-entry-start
2801 :from old-state :to new-state)
2803 Depending on the type, more properties may be present.
2805 This mechanism is currently implemented for:
2807 TODO state changes
2808 ------------------
2809 :type todo-state-change
2810 :from previous state (keyword as a string), or nil, or a symbol
2811 `todo' or `done', to indicate the general type of state.
2812 :to new state, like in :from")
2814 (defcustom org-enforce-todo-dependencies nil
2815 "Non-nil means undone TODO entries will block switching the parent to DONE.
2816 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2817 be blocked if any prior sibling is not yet done.
2818 Finally, if the parent is blocked because of ordered siblings of its own,
2819 the child will also be blocked."
2820 :set (lambda (var val)
2821 (set var val)
2822 (if val
2823 (add-hook 'org-blocker-hook
2824 'org-block-todo-from-children-or-siblings-or-parent)
2825 (remove-hook 'org-blocker-hook
2826 'org-block-todo-from-children-or-siblings-or-parent)))
2827 :group 'org-todo
2828 :type 'boolean)
2830 (defcustom org-enforce-todo-checkbox-dependencies nil
2831 "Non-nil means unchecked boxes will block switching the parent to DONE.
2832 When this is nil, checkboxes have no influence on switching TODO states.
2833 When non-nil, you first need to check off all check boxes before the TODO
2834 entry can be switched to DONE.
2835 This variable needs to be set before org.el is loaded, and you need to
2836 restart Emacs after a change to make the change effective. The only way
2837 to change is while Emacs is running is through the customize interface."
2838 :set (lambda (var val)
2839 (set var val)
2840 (if val
2841 (add-hook 'org-blocker-hook
2842 'org-block-todo-from-checkboxes)
2843 (remove-hook 'org-blocker-hook
2844 'org-block-todo-from-checkboxes)))
2845 :group 'org-todo
2846 :type 'boolean)
2848 (defcustom org-treat-insert-todo-heading-as-state-change nil
2849 "Non-nil means inserting a TODO heading is treated as state change.
2850 So when the command `\\[org-insert-todo-heading]' is used, state change
2851 logging will apply if appropriate. When nil, the new TODO item will
2852 be inserted directly, and no logging will take place."
2853 :group 'org-todo
2854 :type 'boolean)
2856 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2857 "Non-nil means switching TODO states with S-cursor counts as state change.
2858 This is the default behavior. However, setting this to nil allows a
2859 convenient way to select a TODO state and bypass any logging associated
2860 with that."
2861 :group 'org-todo
2862 :type 'boolean)
2864 (defcustom org-todo-state-tags-triggers nil
2865 "Tag changes that should be triggered by TODO state changes.
2866 This is a list. Each entry is
2868 (state-change (tag . flag) .......)
2870 State-change can be a string with a state, and empty string to indicate the
2871 state that has no TODO keyword, or it can be one of the symbols `todo'
2872 or `done', meaning any not-done or done state, respectively."
2873 :group 'org-todo
2874 :group 'org-tags
2875 :type '(repeat
2876 (cons (choice :tag "When changing to"
2877 (const :tag "Not-done state" todo)
2878 (const :tag "Done state" done)
2879 (string :tag "State"))
2880 (repeat
2881 (cons :tag "Tag action"
2882 (string :tag "Tag")
2883 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2885 (defcustom org-log-done nil
2886 "Information to record when a task moves to the DONE state.
2888 Possible values are:
2890 nil Don't add anything, just change the keyword
2891 time Add a time stamp to the task
2892 note Prompt for a note and add it with template `org-log-note-headings'
2894 This option can also be set with on a per-file-basis with
2896 #+STARTUP: nologdone
2897 #+STARTUP: logdone
2898 #+STARTUP: lognotedone
2900 You can have local logging settings for a subtree by setting the LOGGING
2901 property to one or more of these keywords."
2902 :group 'org-todo
2903 :group 'org-progress
2904 :type '(choice
2905 (const :tag "No logging" nil)
2906 (const :tag "Record CLOSED timestamp" time)
2907 (const :tag "Record CLOSED timestamp with note." note)))
2909 ;; Normalize old uses of org-log-done.
2910 (cond
2911 ((eq org-log-done t) (setq org-log-done 'time))
2912 ((and (listp org-log-done) (memq 'done org-log-done))
2913 (setq org-log-done 'note)))
2915 (defcustom org-log-reschedule nil
2916 "Information to record when the scheduling date of a tasks is modified.
2918 Possible values are:
2920 nil Don't add anything, just change the date
2921 time Add a time stamp to the task
2922 note Prompt for a note and add it with template `org-log-note-headings'
2924 This option can also be set with on a per-file-basis with
2926 #+STARTUP: nologreschedule
2927 #+STARTUP: logreschedule
2928 #+STARTUP: lognotereschedule"
2929 :group 'org-todo
2930 :group 'org-progress
2931 :type '(choice
2932 (const :tag "No logging" nil)
2933 (const :tag "Record timestamp" time)
2934 (const :tag "Record timestamp with note." note)))
2936 (defcustom org-log-redeadline nil
2937 "Information to record when the deadline date of a tasks is modified.
2939 Possible values are:
2941 nil Don't add anything, just change the date
2942 time Add a time stamp to the task
2943 note Prompt for a note and add it with template `org-log-note-headings'
2945 This option can also be set with on a per-file-basis with
2947 #+STARTUP: nologredeadline
2948 #+STARTUP: logredeadline
2949 #+STARTUP: lognoteredeadline
2951 You can have local logging settings for a subtree by setting the LOGGING
2952 property to one or more of these keywords."
2953 :group 'org-todo
2954 :group 'org-progress
2955 :type '(choice
2956 (const :tag "No logging" nil)
2957 (const :tag "Record timestamp" time)
2958 (const :tag "Record timestamp with note." note)))
2960 (defcustom org-log-note-clock-out nil
2961 "Non-nil means record a note when clocking out of an item.
2962 This can also be configured on a per-file basis by adding one of
2963 the following lines anywhere in the buffer:
2965 #+STARTUP: lognoteclock-out
2966 #+STARTUP: nolognoteclock-out"
2967 :group 'org-todo
2968 :group 'org-progress
2969 :type 'boolean)
2971 (defcustom org-log-done-with-time t
2972 "Non-nil means the CLOSED time stamp will contain date and time.
2973 When nil, only the date will be recorded."
2974 :group 'org-progress
2975 :type 'boolean)
2977 (defcustom org-log-note-headings
2978 '((done . "CLOSING NOTE %t")
2979 (state . "State %-12s from %-12S %t")
2980 (note . "Note taken on %t")
2981 (reschedule . "Rescheduled from %S on %t")
2982 (delschedule . "Not scheduled, was %S on %t")
2983 (redeadline . "New deadline from %S on %t")
2984 (deldeadline . "Removed deadline, was %S on %t")
2985 (refile . "Refiled on %t")
2986 (clock-out . ""))
2987 "Headings for notes added to entries.
2989 The value is an alist, with the car being a symbol indicating the
2990 note context, and the cdr is the heading to be used. The heading
2991 may also be the empty string. The following placeholders can be
2992 used:
2994 %t a time stamp.
2995 %T an active time stamp instead the default inactive one
2996 %d a short-format time stamp.
2997 %D an active short-format time stamp.
2998 %s the new TODO state or time stamp (inactive), in double quotes.
2999 %S the old TODO state or time stamp (inactive), in double quotes.
3000 %u the user name.
3001 %U full user name.
3003 In fact, it is not a good idea to change the `state' entry,
3004 because Agenda Log mode depends on the format of these entries."
3005 :group 'org-todo
3006 :group 'org-progress
3007 :type '(list :greedy t
3008 (cons (const :tag "Heading when closing an item" done) string)
3009 (cons (const :tag
3010 "Heading when changing todo state (todo sequence only)"
3011 state) string)
3012 (cons (const :tag "Heading when just taking a note" note) string)
3013 (cons (const :tag "Heading when rescheduling" reschedule) string)
3014 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
3015 (cons (const :tag "Heading when changing deadline" redeadline) string)
3016 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
3017 (cons (const :tag "Heading when refiling" refile) string)
3018 (cons (const :tag "Heading when clocking out" clock-out) string)))
3020 (unless (assq 'note org-log-note-headings)
3021 (push '(note . "%t") org-log-note-headings))
3023 (defcustom org-log-into-drawer nil
3024 "Non-nil means insert state change notes and time stamps into a drawer.
3025 When nil, state changes notes will be inserted after the headline and
3026 any scheduling and clock lines, but not inside a drawer.
3028 The value of this variable should be the name of the drawer to use.
3029 LOGBOOK is proposed as the default drawer for this purpose, you can
3030 also set this to a string to define the drawer of your choice.
3032 A value of t is also allowed, representing \"LOGBOOK\".
3034 A value of t or nil can also be set with on a per-file-basis with
3036 #+STARTUP: logdrawer
3037 #+STARTUP: nologdrawer
3039 If this variable is set, `org-log-state-notes-insert-after-drawers'
3040 will be ignored.
3042 You can set the property LOG_INTO_DRAWER to overrule this setting for
3043 a subtree.
3045 Do not check directly this variable in a Lisp program. Call
3046 function `org-log-into-drawer' instead."
3047 :group 'org-todo
3048 :group 'org-progress
3049 :type '(choice
3050 (const :tag "Not into a drawer" nil)
3051 (const :tag "LOGBOOK" t)
3052 (string :tag "Other")))
3054 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
3056 (defun org-log-into-drawer ()
3057 "Name of the log drawer, as a string, or nil.
3058 This is the value of `org-log-into-drawer'. However, if the
3059 current entry has or inherits a LOG_INTO_DRAWER property, it will
3060 be used instead of the default value."
3061 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
3062 (cond ((equal p "nil") nil)
3063 ((equal p "t") "LOGBOOK")
3064 ((stringp p) p)
3065 (p "LOGBOOK")
3066 ((stringp org-log-into-drawer) org-log-into-drawer)
3067 (org-log-into-drawer "LOGBOOK"))))
3069 (defcustom org-log-state-notes-insert-after-drawers nil
3070 "Non-nil means insert state change notes after any drawers in entry.
3071 Only the drawers that *immediately* follow the headline and the
3072 deadline/scheduled line are skipped.
3073 When nil, insert notes right after the heading and perhaps the line
3074 with deadline/scheduling if present.
3076 This variable will have no effect if `org-log-into-drawer' is
3077 set."
3078 :group 'org-todo
3079 :group 'org-progress
3080 :type 'boolean)
3082 (defcustom org-log-states-order-reversed t
3083 "Non-nil means the latest state note will be directly after heading.
3084 When nil, the state change notes will be ordered according to time.
3086 This option can also be set with on a per-file-basis with
3088 #+STARTUP: logstatesreversed
3089 #+STARTUP: nologstatesreversed"
3090 :group 'org-todo
3091 :group 'org-progress
3092 :type 'boolean)
3094 (defcustom org-todo-repeat-to-state nil
3095 "The TODO state to which a repeater should return the repeating task.
3096 By default this is the first task in a TODO sequence, or the previous state
3097 in a TODO_TYP set. But you can specify another task here.
3098 alternatively, set the :REPEAT_TO_STATE: property of the entry."
3099 :group 'org-todo
3100 :version "24.1"
3101 :type '(choice (const :tag "Head of sequence" nil)
3102 (string :tag "Specific state")))
3104 (defcustom org-log-repeat 'time
3105 "Non-nil means record moving through the DONE state when triggering repeat.
3106 An auto-repeating task is immediately switched back to TODO when
3107 marked DONE. If you are not logging state changes (by adding \"@\"
3108 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3109 record a closing note, there will be no record of the task moving
3110 through DONE. This variable forces taking a note anyway.
3112 nil Don't force a record
3113 time Record a time stamp
3114 note Prompt for a note and add it with template `org-log-note-headings'
3116 This option can also be set with on a per-file-basis with
3118 #+STARTUP: nologrepeat
3119 #+STARTUP: logrepeat
3120 #+STARTUP: lognoterepeat
3122 You can have local logging settings for a subtree by setting the LOGGING
3123 property to one or more of these keywords."
3124 :group 'org-todo
3125 :group 'org-progress
3126 :type '(choice
3127 (const :tag "Don't force a record" nil)
3128 (const :tag "Force recording the DONE state" time)
3129 (const :tag "Force recording a note with the DONE state" note)))
3132 (defgroup org-priorities nil
3133 "Priorities in Org mode."
3134 :tag "Org Priorities"
3135 :group 'org-todo)
3137 (defcustom org-enable-priority-commands t
3138 "Non-nil means priority commands are active.
3139 When nil, these commands will be disabled, so that you never accidentally
3140 set a priority."
3141 :group 'org-priorities
3142 :type 'boolean)
3144 (defcustom org-highest-priority ?A
3145 "The highest priority of TODO items. A character like ?A, ?B etc.
3146 Must have a smaller ASCII number than `org-lowest-priority'."
3147 :group 'org-priorities
3148 :type 'character)
3150 (defcustom org-lowest-priority ?C
3151 "The lowest priority of TODO items. A character like ?A, ?B etc.
3152 Must have a larger ASCII number than `org-highest-priority'."
3153 :group 'org-priorities
3154 :type 'character)
3156 (defcustom org-default-priority ?B
3157 "The default priority of TODO items.
3158 This is the priority an item gets if no explicit priority is given.
3159 When starting to cycle on an empty priority the first step in the cycle
3160 depends on `org-priority-start-cycle-with-default'. The resulting first
3161 step priority must not exceed the range from `org-highest-priority' to
3162 `org-lowest-priority' which means that `org-default-priority' has to be
3163 in this range exclusive or inclusive the range boundaries. Else the
3164 first step refuses to set the default and the second will fall back
3165 to (depending on the command used) the highest or lowest priority."
3166 :group 'org-priorities
3167 :type 'character)
3169 (defcustom org-priority-start-cycle-with-default t
3170 "Non-nil means start with default priority when starting to cycle.
3171 When this is nil, the first step in the cycle will be (depending on the
3172 command used) one higher or lower than the default priority.
3173 See also `org-default-priority'."
3174 :group 'org-priorities
3175 :type 'boolean)
3177 (defcustom org-get-priority-function nil
3178 "Function to extract the priority from a string.
3179 The string is normally the headline. If this is nil Org computes the
3180 priority from the priority cookie like [#A] in the headline. It returns
3181 an integer, increasing by 1000 for each priority level.
3182 The user can set a different function here, which should take a string
3183 as an argument and return the numeric priority."
3184 :group 'org-priorities
3185 :version "24.1"
3186 :type '(choice
3187 (const nil)
3188 (function)))
3190 (defgroup org-time nil
3191 "Options concerning time stamps and deadlines in Org mode."
3192 :tag "Org Time"
3193 :group 'org)
3195 (defcustom org-time-stamp-rounding-minutes '(0 5)
3196 "Number of minutes to round time stamps to.
3197 \\<org-mode-map>\
3198 These are two values, the first applies when first creating a time stamp.
3199 The second applies when changing it with the commands `S-up' and `S-down'.
3200 When changing the time stamp, this means that it will change in steps
3201 of N minutes, as given by the second value.
3203 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3204 numbers should be factors of 60, so for example 5, 10, 15.
3206 When this is larger than 1, you can still force an exact time stamp by using
3207 a double prefix argument to a time stamp command like \
3208 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3209 and by using a prefix arg to `S-up/down' to specify the exact number
3210 of minutes to shift."
3211 :group 'org-time
3212 :get (lambda (var) ; Make sure both elements are there
3213 (if (integerp (default-value var))
3214 (list (default-value var) 5)
3215 (default-value var)))
3216 :type '(list
3217 (integer :tag "when inserting times")
3218 (integer :tag "when modifying times")))
3220 ;; Normalize old customizations of this variable.
3221 (when (integerp org-time-stamp-rounding-minutes)
3222 (setq org-time-stamp-rounding-minutes
3223 (list org-time-stamp-rounding-minutes
3224 org-time-stamp-rounding-minutes)))
3226 (defcustom org-display-custom-times nil
3227 "Non-nil means overlay custom formats over all time stamps.
3228 The formats are defined through the variable `org-time-stamp-custom-formats'.
3229 To turn this on on a per-file basis, insert anywhere in the file:
3230 #+STARTUP: customtime"
3231 :group 'org-time
3232 :set 'set-default
3233 :type 'sexp)
3234 (make-variable-buffer-local 'org-display-custom-times)
3236 (defcustom org-time-stamp-custom-formats
3237 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3238 "Custom formats for time stamps. See `format-time-string' for the syntax.
3239 These are overlaid over the default ISO format if the variable
3240 `org-display-custom-times' is set. Time like %H:%M should be at the
3241 end of the second format. The custom formats are also honored by export
3242 commands, if custom time display is turned on at the time of export."
3243 :group 'org-time
3244 :type 'sexp)
3246 (defun org-time-stamp-format (&optional long inactive)
3247 "Get the right format for a time string."
3248 (let ((f (if long (cdr org-time-stamp-formats)
3249 (car org-time-stamp-formats))))
3250 (if inactive
3251 (concat "[" (substring f 1 -1) "]")
3252 f)))
3254 (defcustom org-time-clocksum-format
3255 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3256 "The format string used when creating CLOCKSUM lines.
3257 This is also used when Org mode generates a time duration.
3259 The value can be a single format string containing two
3260 %-sequences, which will be filled with the number of hours and
3261 minutes in that order.
3263 Alternatively, the value can be a plist associating any of the
3264 keys :years, :months, :weeks, :days, :hours or :minutes with
3265 format strings. The time duration is formatted using only the
3266 time components that are needed and concatenating the results.
3267 If a time unit in absent, it falls back to the next smallest
3268 unit.
3270 The keys :require-years, :require-months, :require-days,
3271 :require-weeks, :require-hours, :require-minutes are also
3272 meaningful. A non-nil value for these keys indicates that the
3273 corresponding time component should always be included, even if
3274 its value is 0.
3277 For example,
3279 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3280 :require-minutes t)
3282 means durations longer than a day will be expressed in days,
3283 hours and minutes, and durations less than a day will always be
3284 expressed in hours and minutes (even for durations less than an
3285 hour).
3287 The value
3289 (:days \"%dd\" :minutes \"%dm\")
3291 means durations longer than a day will be expressed in days and
3292 minutes, and durations less than a day will be expressed entirely
3293 in minutes (even for durations longer than an hour)."
3294 :group 'org-time
3295 :group 'org-clock
3296 :version "24.4"
3297 :package-version '(Org . "8.0")
3298 :type '(choice (string :tag "Format string")
3299 (set :tag "Plist"
3300 (group :inline t (const :tag "Years" :years)
3301 (string :tag "Format string"))
3302 (group :inline t
3303 (const :tag "Always show years" :require-years)
3304 (const t))
3305 (group :inline t (const :tag "Months" :months)
3306 (string :tag "Format string"))
3307 (group :inline t
3308 (const :tag "Always show months" :require-months)
3309 (const t))
3310 (group :inline t (const :tag "Weeks" :weeks)
3311 (string :tag "Format string"))
3312 (group :inline t
3313 (const :tag "Always show weeks" :require-weeks)
3314 (const t))
3315 (group :inline t (const :tag "Days" :days)
3316 (string :tag "Format string"))
3317 (group :inline t
3318 (const :tag "Always show days" :require-days)
3319 (const t))
3320 (group :inline t (const :tag "Hours" :hours)
3321 (string :tag "Format string"))
3322 (group :inline t
3323 (const :tag "Always show hours" :require-hours)
3324 (const t))
3325 (group :inline t (const :tag "Minutes" :minutes)
3326 (string :tag "Format string"))
3327 (group :inline t
3328 (const :tag "Always show minutes" :require-minutes)
3329 (const t)))))
3331 (defcustom org-time-clocksum-use-fractional nil
3332 "When non-nil, `\\[org-clock-display]' uses fractional times.
3333 See `org-time-clocksum-format' for more on time clock formats."
3334 :group 'org-time
3335 :group 'org-clock
3336 :version "24.3"
3337 :type 'boolean)
3339 (defcustom org-time-clocksum-use-effort-durations nil
3340 "When non-nil, `\\[org-clock-display]' uses effort durations.
3341 E.g. by default, one day is considered to be a 8 hours effort,
3342 so a task that has been clocked for 16 hours will be displayed
3343 as during 2 days in the clock display or in the clocktable.
3345 See `org-effort-durations' on how to set effort durations
3346 and `org-time-clocksum-format' for more on time clock formats."
3347 :group 'org-time
3348 :group 'org-clock
3349 :version "24.4"
3350 :package-version '(Org . "8.0")
3351 :type 'boolean)
3353 (defcustom org-time-clocksum-fractional-format "%.2f"
3354 "The format string used when creating CLOCKSUM lines,
3355 or when Org mode generates a time duration, if
3356 `org-time-clocksum-use-fractional' is enabled.
3358 The value can be a single format string containing one
3359 %-sequence, which will be filled with the number of hours as
3360 a float.
3362 Alternatively, the value can be a plist associating any of the
3363 keys :years, :months, :weeks, :days, :hours or :minutes with
3364 a format string. The time duration is formatted using the
3365 largest time unit which gives a non-zero integer part. If all
3366 specified formats have zero integer part, the smallest time unit
3367 is used."
3368 :group 'org-time
3369 :type '(choice (string :tag "Format string")
3370 (set (group :inline t (const :tag "Years" :years)
3371 (string :tag "Format string"))
3372 (group :inline t (const :tag "Months" :months)
3373 (string :tag "Format string"))
3374 (group :inline t (const :tag "Weeks" :weeks)
3375 (string :tag "Format string"))
3376 (group :inline t (const :tag "Days" :days)
3377 (string :tag "Format string"))
3378 (group :inline t (const :tag "Hours" :hours)
3379 (string :tag "Format string"))
3380 (group :inline t (const :tag "Minutes" :minutes)
3381 (string :tag "Format string")))))
3383 (defcustom org-deadline-warning-days 14
3384 "Number of days before expiration during which a deadline becomes active.
3385 This variable governs the display in sparse trees and in the agenda.
3386 When 0 or negative, it means use this number (the absolute value of it)
3387 even if a deadline has a different individual lead time specified.
3389 Custom commands can set this variable in the options section."
3390 :group 'org-time
3391 :group 'org-agenda-daily/weekly
3392 :type 'integer)
3394 (defcustom org-scheduled-delay-days 0
3395 "Number of days before a scheduled item becomes active.
3396 This variable governs the display in sparse trees and in the agenda.
3397 The default value (i.e. 0) means: don't delay scheduled item.
3398 When negative, it means use this number (the absolute value of it)
3399 even if a scheduled item has a different individual delay time
3400 specified.
3402 Custom commands can set this variable in the options section."
3403 :group 'org-time
3404 :group 'org-agenda-daily/weekly
3405 :version "24.4"
3406 :package-version '(Org . "8.0")
3407 :type 'integer)
3409 (defcustom org-read-date-prefer-future t
3410 "Non-nil means assume future for incomplete date input from user.
3411 This affects the following situations:
3412 1. The user gives a month but not a year.
3413 For example, if it is April and you enter \"feb 2\", this will be read
3414 as Feb 2, *next* year. \"May 5\", however, will be this year.
3415 2. The user gives a day, but no month.
3416 For example, if today is the 15th, and you enter \"3\", Org will read
3417 this as the third of *next* month. However, if you enter \"17\",
3418 it will be considered as *this* month.
3420 If you set this variable to the symbol `time', then also the following
3421 will work:
3423 3. If the user gives a time.
3424 If the time is before now, it will be interpreted as tomorrow.
3426 Currently none of this works for ISO week specifications.
3428 When this option is nil, the current day, month and year will always be
3429 used as defaults.
3431 See also `org-agenda-jump-prefer-future'."
3432 :group 'org-time
3433 :type '(choice
3434 (const :tag "Never" nil)
3435 (const :tag "Check month and day" t)
3436 (const :tag "Check month, day, and time" time)))
3438 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3439 "Should the agenda jump command prefer the future for incomplete dates?
3440 The default is to do the same as configured in `org-read-date-prefer-future'.
3441 But you can also set a deviating value here.
3442 This may t or nil, or the symbol `org-read-date-prefer-future'."
3443 :group 'org-agenda
3444 :group 'org-time
3445 :version "24.1"
3446 :type '(choice
3447 (const :tag "Use org-read-date-prefer-future"
3448 org-read-date-prefer-future)
3449 (const :tag "Never" nil)
3450 (const :tag "Always" t)))
3452 (defcustom org-read-date-force-compatible-dates t
3453 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3455 Depending on the system Emacs is running on, certain dates cannot
3456 be represented with the type used internally to represent time.
3457 Dates between 1970-1-1 and 2038-1-1 can always be represented
3458 correctly. Some systems allow for earlier dates, some for later,
3459 some for both. One way to find out it to insert any date into an
3460 Org buffer, putting the cursor on the year and hitting S-up and
3461 S-down to test the range.
3463 When this variable is set to t, the date/time prompt will not let
3464 you specify dates outside the 1970-2037 range, so it is certain that
3465 these dates will work in whatever version of Emacs you are
3466 running, and also that you can move a file from one Emacs implementation
3467 to another. WHenever Org is forcing the year for you, it will display
3468 a message and beep.
3470 When this variable is nil, Org will check if the date is
3471 representable in the specific Emacs implementation you are using.
3472 If not, it will force a year, usually the current year, and beep
3473 to remind you. Currently this setting is not recommended because
3474 the likelihood that you will open your Org files in an Emacs that
3475 has limited date range is not negligible.
3477 A workaround for this problem is to use diary sexp dates for time
3478 stamps outside of this range."
3479 :group 'org-time
3480 :version "24.1"
3481 :type 'boolean)
3483 (defcustom org-read-date-display-live t
3484 "Non-nil means display current interpretation of date prompt live.
3485 This display will be in an overlay, in the minibuffer."
3486 :group 'org-time
3487 :type 'boolean)
3489 (defcustom org-read-date-popup-calendar t
3490 "Non-nil means pop up a calendar when prompting for a date.
3491 In the calendar, the date can be selected with mouse-1. However, the
3492 minibuffer will also be active, and you can simply enter the date as well.
3493 When nil, only the minibuffer will be available."
3494 :group 'org-time
3495 :type 'boolean)
3496 (defvaralias 'org-popup-calendar-for-date-prompt
3497 'org-read-date-popup-calendar)
3499 (defcustom org-extend-today-until 0
3500 "The hour when your day really ends. Must be an integer.
3501 This has influence for the following applications:
3502 - When switching the agenda to \"today\". It it is still earlier than
3503 the time given here, the day recognized as TODAY is actually yesterday.
3504 - When a date is read from the user and it is still before the time given
3505 here, the current date and time will be assumed to be yesterday, 23:59.
3506 Also, timestamps inserted in capture templates follow this rule.
3508 IMPORTANT: This is a feature whose implementation is and likely will
3509 remain incomplete. Really, it is only here because past midnight seems to
3510 be the favorite working time of John Wiegley :-)"
3511 :group 'org-time
3512 :type 'integer)
3514 (defcustom org-use-effective-time nil
3515 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3516 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3517 \"effective time\" of any timestamps between midnight and 8am will be
3518 23:59 of the previous day."
3519 :group 'org-time
3520 :version "24.1"
3521 :type 'boolean)
3523 (defcustom org-use-last-clock-out-time-as-effective-time nil
3524 "When non-nil, use the last clock out time for `org-todo'.
3525 Note that this option has precedence over the combined use of
3526 `org-use-effective-time' and `org-extend-today-until'."
3527 :group 'org-time
3528 :version "24.4"
3529 :package-version '(Org . "8.0")
3530 :type 'boolean)
3532 (defcustom org-edit-timestamp-down-means-later nil
3533 "Non-nil means S-down will increase the time in a time stamp.
3534 When nil, S-up will increase."
3535 :group 'org-time
3536 :type 'boolean)
3538 (defcustom org-calendar-follow-timestamp-change t
3539 "Non-nil means make the calendar window follow timestamp changes.
3540 When a timestamp is modified and the calendar window is visible, it will be
3541 moved to the new date."
3542 :group 'org-time
3543 :type 'boolean)
3545 (defgroup org-tags nil
3546 "Options concerning tags in Org mode."
3547 :tag "Org Tags"
3548 :group 'org)
3550 (defcustom org-tag-alist nil
3551 "Default tags available in Org files.
3553 The value of this variable is an alist. Associations either:
3555 (TAG)
3556 (TAG . SELECT)
3557 (SPECIAL)
3559 where TAG is a tag as a string, SELECT is character, used to
3560 select that tag through the fast tag selection interface, and
3561 SPECIAL is one of the following keywords: `:startgroup',
3562 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3563 `:newline'. These keywords are used to define a hierarchy of
3564 tags. See manual for details.
3566 When this variable is nil, Org mode bases tag input on what is
3567 already in the buffer. The value can be overridden locally by
3568 using a TAGS keyword, e.g.,
3570 #+TAGS: tag1 tag2
3572 See also `org-tag-persistent-alist' to sidestep this behavior."
3573 :group 'org-tags
3574 :type '(repeat
3575 (choice
3576 (cons (string :tag "Tag name")
3577 (character :tag "Access char"))
3578 (const :tag "Start radio group" (:startgroup))
3579 (const :tag "Start tag group, non distinct" (:startgrouptag))
3580 (const :tag "Group tags delimiter" (:grouptags))
3581 (const :tag "End radio group" (:endgroup))
3582 (const :tag "End tag group, non distinct" (:endgrouptag))
3583 (const :tag "New line" (:newline)))))
3585 (defcustom org-tag-persistent-alist nil
3586 "Tags always available in Org files.
3588 The value of this variable is an alist. Associations either:
3590 (TAG)
3591 (TAG . SELECT)
3592 (SPECIAL)
3594 where TAG is a tag as a string, SELECT is a character, used to
3595 select that tag through the fast tag selection interface, and
3596 SPECIAL is one of the following keywords: `:startgroup',
3597 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3598 `:newline'. These keywords are used to define a hierarchy of
3599 tags. See manual for details.
3601 Unlike to `org-tag-alist', tags defined in this variable do not
3602 depend on a local TAGS keyword. Instead, to disable these tags
3603 on a per-file basis, insert anywhere in the file:
3605 #+STARTUP: noptag"
3606 :group 'org-tags
3607 :type '(repeat
3608 (choice
3609 (cons (string :tag "Tag name")
3610 (character :tag "Access char"))
3611 (const :tag "Start radio group" (:startgroup))
3612 (const :tag "Start tag group, non distinct" (:startgrouptag))
3613 (const :tag "Group tags delimiter" (:grouptags))
3614 (const :tag "End radio group" (:endgroup))
3615 (const :tag "End tag group, non distinct" (:endgrouptag))
3616 (const :tag "New line" (:newline)))))
3618 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3619 "If non-nil, always offer completion for all tags of all agenda files.
3620 Instead of customizing this variable directly, you might want to
3621 set it locally for capture buffers, because there no list of
3622 tags in that file can be created dynamically (there are none).
3624 (add-hook \\='org-capture-mode-hook
3625 (lambda ()
3626 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3627 :group 'org-tags
3628 :version "24.1"
3629 :type 'boolean)
3631 (defvar org-file-tags nil
3632 "List of tags that can be inherited by all entries in the file.
3633 The tags will be inherited if the variable `org-use-tag-inheritance'
3634 says they should be.
3635 This variable is populated from #+FILETAGS lines.")
3637 (defcustom org-use-fast-tag-selection 'auto
3638 "Non-nil means use fast tag selection scheme.
3639 This is a special interface to select and deselect tags with single keys.
3640 When nil, fast selection is never used.
3641 When the symbol `auto', fast selection is used if and only if selection
3642 characters for tags have been configured, either through the variable
3643 `org-tag-alist' or through a #+TAGS line in the buffer.
3644 When t, fast selection is always used and selection keys are assigned
3645 automatically if necessary."
3646 :group 'org-tags
3647 :type '(choice
3648 (const :tag "Always" t)
3649 (const :tag "Never" nil)
3650 (const :tag "When selection characters are configured" auto)))
3652 (defcustom org-fast-tag-selection-single-key nil
3653 "Non-nil means fast tag selection exits after first change.
3654 When nil, you have to press RET to exit it.
3655 During fast tag selection, you can toggle this flag with `C-c'.
3656 This variable can also have the value `expert'. In this case, the window
3657 displaying the tags menu is not even shown, until you press C-c again."
3658 :group 'org-tags
3659 :type '(choice
3660 (const :tag "No" nil)
3661 (const :tag "Yes" t)
3662 (const :tag "Expert" expert)))
3664 (defvar org-fast-tag-selection-include-todo nil
3665 "Non-nil means fast tags selection interface will also offer TODO states.
3666 This is an undocumented feature, you should not rely on it.")
3668 (defcustom org-tags-column -77
3669 "The column to which tags should be indented in a headline.
3670 If this number is positive, it specifies the column. If it is negative,
3671 it means that the tags should be flushright to that column. For example,
3672 -80 works well for a normal 80 character screen.
3673 When 0, place tags directly after headline text, with only one space in
3674 between."
3675 :group 'org-tags
3676 :type 'integer)
3678 (defcustom org-auto-align-tags t
3679 "Non-nil keeps tags aligned when modifying headlines.
3680 Some operations (i.e. demoting) change the length of a headline and
3681 therefore shift the tags around. With this option turned on, after
3682 each such operation the tags are again aligned to `org-tags-column'."
3683 :group 'org-tags
3684 :type 'boolean)
3686 (defcustom org-use-tag-inheritance t
3687 "Non-nil means tags in levels apply also for sublevels.
3688 When nil, only the tags directly given in a specific line apply there.
3689 This may also be a list of tags that should be inherited, or a regexp that
3690 matches tags that should be inherited. Additional control is possible
3691 with the variable `org-tags-exclude-from-inheritance' which gives an
3692 explicit list of tags to be excluded from inheritance, even if the value of
3693 `org-use-tag-inheritance' would select it for inheritance.
3695 If this option is t, a match early-on in a tree can lead to a large
3696 number of matches in the subtree when constructing the agenda or creating
3697 a sparse tree. If you only want to see the first match in a tree during
3698 a search, check out the variable `org-tags-match-list-sublevels'."
3699 :group 'org-tags
3700 :type '(choice
3701 (const :tag "Not" nil)
3702 (const :tag "Always" t)
3703 (repeat :tag "Specific tags" (string :tag "Tag"))
3704 (regexp :tag "Tags matched by regexp")))
3706 (defcustom org-tags-exclude-from-inheritance nil
3707 "List of tags that should never be inherited.
3708 This is a way to exclude a few tags from inheritance. For way to do
3709 the opposite, to actively allow inheritance for selected tags,
3710 see the variable `org-use-tag-inheritance'."
3711 :group 'org-tags
3712 :type '(repeat (string :tag "Tag")))
3714 (defun org-tag-inherit-p (tag)
3715 "Check if TAG is one that should be inherited."
3716 (cond
3717 ((member tag org-tags-exclude-from-inheritance) nil)
3718 ((eq org-use-tag-inheritance t) t)
3719 ((not org-use-tag-inheritance) nil)
3720 ((stringp org-use-tag-inheritance)
3721 (string-match org-use-tag-inheritance tag))
3722 ((listp org-use-tag-inheritance)
3723 (member tag org-use-tag-inheritance))
3724 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3726 (defcustom org-tags-match-list-sublevels t
3727 "Non-nil means list also sublevels of headlines matching a search.
3728 This variable applies to tags/property searches, and also to stuck
3729 projects because this search is based on a tags match as well.
3731 When set to the symbol `indented', sublevels are indented with
3732 leading dots.
3734 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3735 the sublevels of a headline matching a tag search often also match
3736 the same search. Listing all of them can create very long lists.
3737 Setting this variable to nil causes subtrees of a match to be skipped.
3739 This variable is semi-obsolete and probably should always be true. It
3740 is better to limit inheritance to certain tags using the variables
3741 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3742 :group 'org-tags
3743 :type '(choice
3744 (const :tag "No, don't list them" nil)
3745 (const :tag "Yes, do list them" t)
3746 (const :tag "List them, indented with leading dots" indented)))
3748 (defcustom org-tags-sort-function nil
3749 "When set, tags are sorted using this function as a comparator."
3750 :group 'org-tags
3751 :type '(choice
3752 (const :tag "No sorting" nil)
3753 (const :tag "Alphabetical" string<)
3754 (const :tag "Reverse alphabetical" string>)
3755 (function :tag "Custom function" nil)))
3757 (defvar org-tags-history nil
3758 "History of minibuffer reads for tags.")
3759 (defvar org-last-tags-completion-table nil
3760 "The last used completion table for tags.")
3761 (defvar org-after-tags-change-hook nil
3762 "Hook that is run after the tags in a line have changed.")
3764 (defgroup org-properties nil
3765 "Options concerning properties in Org mode."
3766 :tag "Org Properties"
3767 :group 'org)
3769 (defcustom org-property-format "%-10s %s"
3770 "How property key/value pairs should be formatted by `indent-line'.
3771 When `indent-line' hits a property definition, it will format the line
3772 according to this format, mainly to make sure that the values are
3773 lined-up with respect to each other."
3774 :group 'org-properties
3775 :type 'string)
3777 (defcustom org-properties-postprocess-alist nil
3778 "Alist of properties and functions to adjust inserted values.
3779 Elements of this alist must be of the form
3781 ([string] [function])
3783 where [string] must be a property name and [function] must be a
3784 lambda expression: this lambda expression must take one argument,
3785 the value to adjust, and return the new value as a string.
3787 For example, this element will allow the property \"Remaining\"
3788 to be updated wrt the relation between the \"Effort\" property
3789 and the clock summary:
3791 ((\"Remaining\" (lambda(value)
3792 (let ((clocksum (org-clock-sum-current-item))
3793 (effort (org-duration-string-to-minutes
3794 (org-entry-get (point) \"Effort\"))))
3795 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3796 :group 'org-properties
3797 :version "24.1"
3798 :type '(alist :key-type (string :tag "Property")
3799 :value-type (function :tag "Function")))
3801 (defcustom org-use-property-inheritance nil
3802 "Non-nil means properties apply also for sublevels.
3804 This setting is chiefly used during property searches. Turning it on can
3805 cause significant overhead when doing a search, which is why it is not
3806 on by default.
3808 When nil, only the properties directly given in the current entry count.
3809 When t, every property is inherited. The value may also be a list of
3810 properties that should have inheritance, or a regular expression matching
3811 properties that should be inherited.
3813 However, note that some special properties use inheritance under special
3814 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3815 and the properties ending in \"_ALL\" when they are used as descriptor
3816 for valid values of a property.
3818 Note for programmers:
3819 When querying an entry with `org-entry-get', you can control if inheritance
3820 should be used. By default, `org-entry-get' looks only at the local
3821 properties. You can request inheritance by setting the inherit argument
3822 to t (to force inheritance) or to `selective' (to respect the setting
3823 in this variable)."
3824 :group 'org-properties
3825 :type '(choice
3826 (const :tag "Not" nil)
3827 (const :tag "Always" t)
3828 (repeat :tag "Specific properties" (string :tag "Property"))
3829 (regexp :tag "Properties matched by regexp")))
3831 (defun org-property-inherit-p (property)
3832 "Return a non-nil value if PROPERTY should be inherited."
3833 (cond
3834 ((eq org-use-property-inheritance t) t)
3835 ((not org-use-property-inheritance) nil)
3836 ((stringp org-use-property-inheritance)
3837 (string-match org-use-property-inheritance property))
3838 ((listp org-use-property-inheritance)
3839 (member-ignore-case property org-use-property-inheritance))
3840 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3842 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3843 "The default column format, if no other format has been defined.
3844 This variable can be set on the per-file basis by inserting a line
3846 #+COLUMNS: %25ITEM ....."
3847 :group 'org-properties
3848 :type 'string)
3850 (defcustom org-columns-ellipses ".."
3851 "The ellipses to be used when a field in column view is truncated.
3852 When this is the empty string, as many characters as possible are shown,
3853 but then there will be no visual indication that the field has been truncated.
3854 When this is a string of length N, the last N characters of a truncated
3855 field are replaced by this string. If the column is narrower than the
3856 ellipses string, only part of the ellipses string will be shown."
3857 :group 'org-properties
3858 :type 'string)
3860 (defconst org-global-properties-fixed
3861 '(("VISIBILITY_ALL" . "folded children content all")
3862 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3863 "List of property/value pairs that can be inherited by any entry.
3865 These are fixed values, for the preset properties. The user variable
3866 that can be used to add to this list is `org-global-properties'.
3868 The entries in this list are cons cells where the car is a property
3869 name and cdr is a string with the value. If the value represents
3870 multiple items like an \"_ALL\" property, separate the items by
3871 spaces.")
3873 (defcustom org-global-properties nil
3874 "List of property/value pairs that can be inherited by any entry.
3876 This list will be combined with the constant `org-global-properties-fixed'.
3878 The entries in this list are cons cells where the car is a property
3879 name and cdr is a string with the value.
3881 You can set buffer-local values for the same purpose in the variable
3882 `org-file-properties' this by adding lines like
3884 #+PROPERTY: NAME VALUE"
3885 :group 'org-properties
3886 :type '(repeat
3887 (cons (string :tag "Property")
3888 (string :tag "Value"))))
3890 (defvar-local org-file-properties nil
3891 "List of property/value pairs that can be inherited by any entry.
3892 Valid for the current buffer.
3893 This variable is populated from #+PROPERTY lines.")
3895 (defgroup org-agenda nil
3896 "Options concerning agenda views in Org mode."
3897 :tag "Org Agenda"
3898 :group 'org)
3900 (defvar-local org-category nil
3901 "Variable used by org files to set a category for agenda display.
3902 Such files should use a file variable to set it, for example
3904 # -*- mode: org; org-category: \"ELisp\"
3906 or contain a special line
3908 #+CATEGORY: ELisp
3910 If the file does not specify a category, then file's base name
3911 is used instead.")
3912 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3914 (defcustom org-agenda-files nil
3915 "The files to be used for agenda display.
3917 If an entry is a directory, all files in that directory that are matched
3918 by `org-agenda-file-regexp' will be part of the file list.
3920 If the value of the variable is not a list but a single file name, then
3921 the list of agenda files is actually stored and maintained in that file,
3922 one agenda file per line. In this file paths can be given relative to
3923 `org-directory'. Tilde expansion and environment variable substitution
3924 are also made.
3926 Entries may be added to this list with `\\[org-agenda-file-to-front]'
3927 and removed with `\\[org-remove-file]'."
3928 :group 'org-agenda
3929 :type '(choice
3930 (repeat :tag "List of files and directories" file)
3931 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3933 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3934 "Regular expression to match files for `org-agenda-files'.
3935 If any element in the list in that variable contains a directory instead
3936 of a normal file, all files in that directory that are matched by this
3937 regular expression will be included."
3938 :group 'org-agenda
3939 :type 'regexp)
3941 (defcustom org-agenda-text-search-extra-files nil
3942 "List of extra files to be searched by text search commands.
3943 These files will be searched in addition to the agenda files by the
3944 commands `org-search-view' (`\\[org-agenda] s') \
3945 and `org-occur-in-agenda-files'.
3946 Note that these files will only be searched for text search commands,
3947 not for the other agenda views like todo lists, tag searches or the weekly
3948 agenda. This variable is intended to list notes and possibly archive files
3949 that should also be searched by these two commands.
3950 In fact, if the first element in the list is the symbol `agenda-archives',
3951 then all archive files of all agenda files will be added to the search
3952 scope."
3953 :group 'org-agenda
3954 :type '(set :greedy t
3955 (const :tag "Agenda Archives" agenda-archives)
3956 (repeat :inline t (file))))
3958 (defvaralias 'org-agenda-multi-occur-extra-files
3959 'org-agenda-text-search-extra-files)
3961 (defcustom org-agenda-skip-unavailable-files nil
3962 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3963 A nil value means to remove them, after a query, from the list."
3964 :group 'org-agenda
3965 :type 'boolean)
3967 (defcustom org-calendar-to-agenda-key [?c]
3968 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3969 The command `org-calendar-goto-agenda' will be bound to this key. The
3970 default is the character `c' because then `c' can be used to switch back and
3971 forth between agenda and calendar."
3972 :group 'org-agenda
3973 :type 'sexp)
3975 (defcustom org-calendar-insert-diary-entry-key [?i]
3976 "The key to be installed in `calendar-mode-map' for adding diary entries.
3977 This option is irrelevant until `org-agenda-diary-file' has been configured
3978 to point to an Org file. When that is the case, the command
3979 `org-agenda-diary-entry' will be bound to the key given here, by default
3980 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3981 if you want to continue doing this, you need to change this to a different
3982 key."
3983 :group 'org-agenda
3984 :type 'sexp)
3986 (defcustom org-agenda-diary-file 'diary-file
3987 "File to which to add new entries with the `i' key in agenda and calendar.
3988 When this is the symbol `diary-file', the functionality in the Emacs
3989 calendar will be used to add entries to the `diary-file'. But when this
3990 points to a file, `org-agenda-diary-entry' will be used instead."
3991 :group 'org-agenda
3992 :type '(choice
3993 (const :tag "The standard Emacs diary file" diary-file)
3994 (file :tag "Special Org file diary entries")))
3996 (eval-after-load "calendar"
3997 '(progn
3998 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3999 'org-calendar-goto-agenda)
4000 (add-hook 'calendar-mode-hook
4001 (lambda ()
4002 (unless (eq org-agenda-diary-file 'diary-file)
4003 (define-key calendar-mode-map
4004 org-calendar-insert-diary-entry-key
4005 'org-agenda-diary-entry))))))
4007 (defgroup org-latex nil
4008 "Options for embedding LaTeX code into Org mode."
4009 :tag "Org LaTeX"
4010 :group 'org)
4012 (defcustom org-format-latex-options
4013 '(:foreground default :background default :scale 1.0
4014 :html-foreground "Black" :html-background "Transparent"
4015 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
4016 "Options for creating images from LaTeX fragments.
4017 This is a property list with the following properties:
4018 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
4019 `default' means use the foreground of the default face.
4020 `auto' means use the foreground from the text face.
4021 :background the background color, or \"Transparent\".
4022 `default' means use the background of the default face.
4023 `auto' means use the background from the text face.
4024 :scale a scaling factor for the size of the images, to get more pixels
4025 :html-foreground, :html-background, :html-scale
4026 the same numbers for HTML export.
4027 :matchers a list indicating which matchers should be used to
4028 find LaTeX fragments. Valid members of this list are:
4029 \"begin\" find environments
4030 \"$1\" find single characters surrounded by $.$
4031 \"$\" find math expressions surrounded by $...$
4032 \"$$\" find math expressions surrounded by $$....$$
4033 \"\\(\" find math expressions surrounded by \\(...\\)
4034 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
4035 :group 'org-latex
4036 :type 'plist)
4038 (defcustom org-format-latex-signal-error t
4039 "Non-nil means signal an error when image creation of LaTeX snippets fails.
4040 When nil, just push out a message."
4041 :group 'org-latex
4042 :version "24.1"
4043 :type 'boolean)
4045 (defcustom org-latex-to-mathml-jar-file nil
4046 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
4047 Use this to specify additional executable file say a jar file.
4049 When using MathToWeb as the converter, specify the full-path to
4050 your mathtoweb.jar file."
4051 :group 'org-latex
4052 :version "24.1"
4053 :type '(choice
4054 (const :tag "None" nil)
4055 (file :tag "JAR file" :must-match t)))
4057 (defcustom org-latex-to-mathml-convert-command nil
4058 "Command to convert LaTeX fragments to MathML.
4059 Replace format-specifiers in the command as noted below and use
4060 `shell-command' to convert LaTeX to MathML.
4061 %j: Executable file in fully expanded form as specified by
4062 `org-latex-to-mathml-jar-file'.
4063 %I: Input LaTeX file in fully expanded form.
4064 %i: The latex fragment to be converted.
4065 %o: Output MathML file.
4067 This command is used by `org-create-math-formula'.
4069 When using MathToWeb as the converter, set this option to
4070 \"java -jar %j -unicode -force -df %o %I\".
4072 When using LaTeXML set this option to
4073 \"latexmlmath \"%i\" --presentationmathml=%o\"."
4074 :group 'org-latex
4075 :version "24.1"
4076 :type '(choice
4077 (const :tag "None" nil)
4078 (string :tag "\nShell command")))
4080 (defcustom org-preview-latex-default-process 'dvipng
4081 "The default process to convert LaTeX fragments to image files.
4082 All available processes and theirs documents can be found in
4083 `org-preview-latex-process-alist', which see."
4084 :group 'org-latex
4085 :version "26.1"
4086 :package-version '(Org . "9.0")
4087 :type 'symbol)
4089 (defcustom org-preview-latex-process-alist
4090 '((dvipng
4091 :programs ("latex" "dvipng")
4092 :description "dvi > png"
4093 :message "you need to install the programs: latex and dvipng."
4094 :image-input-type "dvi"
4095 :image-output-type "png"
4096 :image-size-adjust (1.0 . 1.0)
4097 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4098 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %O %f"))
4099 (dvisvgm
4100 :programs ("latex" "dvisvgm")
4101 :description "dvi > svg"
4102 :message "you need to install the programs: latex and dvisvgm."
4103 :use-xcolor t
4104 :image-input-type "dvi"
4105 :image-output-type "svg"
4106 :image-size-adjust (1.7 . 1.5)
4107 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4108 :image-converter ("dvisvgm %f -n -b min -c %S -o %O"))
4109 (imagemagick
4110 :programs ("latex" "convert")
4111 :description "pdf > png"
4112 :message "you need to install the programs: latex and imagemagick."
4113 :use-xcolor t
4114 :image-input-type "pdf"
4115 :image-output-type "png"
4116 :image-size-adjust (1.0 . 1.0)
4117 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4118 :image-converter
4119 ("convert -density %D -trim -antialias %f -quality 100 %O")))
4120 "Definitions of external processes for LaTeX previewing.
4121 Org mode can use some external commands to generate TeX snippet's images for
4122 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4123 `org-create-formula-image' how to call them.
4125 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4126 PROPERTIES accepts the following attributes:
4128 :programs list of strings, required programs.
4129 :description string, describe the process.
4130 :message string, message it when required programs cannot be found.
4131 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4132 :image-output-type string, output file type of image converter (e.g., \"png\").
4133 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4134 deal with background and foreground color of image.
4135 Otherwise, dvipng style background and foregroud color
4136 format are generated. You may then refer to them in
4137 command options with \"%F\" and \"%B\".
4138 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4139 image size showed in buffer and the cdr element is for
4140 HTML file. This option is only useful for process
4141 developers, users should use variable
4142 `org-format-latex-options' instead.
4143 :post-clean list of strings, files matched are to be cleaned up once
4144 the image is generated. When nil, the files with \".dvi\",
4145 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4146 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4147 be cleaned up.
4148 :latex-header list of strings, the LaTeX header of the snippet file.
4149 When nil, the fallback value is used instead, which is
4150 controlled by `org-format-latex-header',
4151 `org-latex-default-packages-alist' and
4152 `org-latex-packages-alist', which see.
4153 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4154 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4155 replaced with values defined below.
4156 :image-converter list of image converter commands strings. Each of them is
4157 given to the shell and supports any of the following
4158 place-holders defined below.
4160 Place-holders used by `:image-converter' and `:latex-compiler':
4162 %f input file name
4163 %b base name of input file
4164 %o base directory of input file
4165 %O absolute output file name
4167 Place-holders only used by `:image-converter':
4169 %F foreground of image
4170 %B background of image
4171 %D dpi, which is used to adjust image size by some processing commands.
4172 %S the image size scale ratio, which is used to adjust image size by some
4173 processing commands."
4174 :group 'org-latex
4175 :version "26.1"
4176 :package-version '(Org . "9.0")
4177 :type '(alist :tag "LaTeX to image backends"
4178 :value-type (plist)))
4180 (defcustom org-preview-latex-image-directory "ltximg/"
4181 "Path to store latex preview images.
4182 A relative path here creates many directories relative to the
4183 processed org files paths. An absolute path puts all preview
4184 images at the same place."
4185 :group 'org-latex
4186 :version "26.1"
4187 :package-version '(Org . "9.0")
4188 :type 'string)
4190 (defun org-format-latex-mathml-available-p ()
4191 "Return t if `org-latex-to-mathml-convert-command' is usable."
4192 (save-match-data
4193 (when (and (boundp 'org-latex-to-mathml-convert-command)
4194 org-latex-to-mathml-convert-command)
4195 (let ((executable (car (split-string
4196 org-latex-to-mathml-convert-command))))
4197 (when (executable-find executable)
4198 (if (string-match
4199 "%j" org-latex-to-mathml-convert-command)
4200 (file-readable-p org-latex-to-mathml-jar-file)
4201 t))))))
4203 (defcustom org-format-latex-header "\\documentclass{article}
4204 \\usepackage[usenames]{color}
4205 \[PACKAGES]
4206 \[DEFAULT-PACKAGES]
4207 \\pagestyle{empty} % do not remove
4208 % The settings below are copied from fullpage.sty
4209 \\setlength{\\textwidth}{\\paperwidth}
4210 \\addtolength{\\textwidth}{-3cm}
4211 \\setlength{\\oddsidemargin}{1.5cm}
4212 \\addtolength{\\oddsidemargin}{-2.54cm}
4213 \\setlength{\\evensidemargin}{\\oddsidemargin}
4214 \\setlength{\\textheight}{\\paperheight}
4215 \\addtolength{\\textheight}{-\\headheight}
4216 \\addtolength{\\textheight}{-\\headsep}
4217 \\addtolength{\\textheight}{-\\footskip}
4218 \\addtolength{\\textheight}{-3cm}
4219 \\setlength{\\topmargin}{1.5cm}
4220 \\addtolength{\\topmargin}{-2.54cm}"
4221 "The document header used for processing LaTeX fragments.
4222 It is imperative that this header make sure that no page number
4223 appears on the page. The package defined in the variables
4224 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4225 will either replace the placeholder \"[PACKAGES]\" in this
4226 header, or they will be appended."
4227 :group 'org-latex
4228 :type 'string)
4230 (defun org-set-packages-alist (var val)
4231 "Set the packages alist and make sure it has 3 elements per entry."
4232 (set var (mapcar (lambda (x)
4233 (if (and (consp x) (= (length x) 2))
4234 (list (car x) (nth 1 x) t)
4236 val)))
4238 (defun org-get-packages-alist (var)
4239 "Get the packages alist and make sure it has 3 elements per entry."
4240 (mapcar (lambda (x)
4241 (if (and (consp x) (= (length x) 2))
4242 (list (car x) (nth 1 x) t)
4244 (default-value var)))
4246 (defcustom org-latex-default-packages-alist
4247 '(("AUTO" "inputenc" t ("pdflatex"))
4248 ("T1" "fontenc" t ("pdflatex"))
4249 ("" "graphicx" t)
4250 ("" "grffile" t)
4251 ("" "longtable" nil)
4252 ("" "wrapfig" nil)
4253 ("" "rotating" nil)
4254 ("normalem" "ulem" t)
4255 ("" "amsmath" t)
4256 ("" "textcomp" t)
4257 ("" "amssymb" t)
4258 ("" "capt-of" nil)
4259 ("" "hyperref" nil))
4260 "Alist of default packages to be inserted in the header.
4262 Change this only if one of the packages here causes an
4263 incompatibility with another package you are using.
4265 The packages in this list are needed by one part or another of
4266 Org mode to function properly:
4268 - inputenc, fontenc: for basic font and character selection
4269 - graphicx: for including images
4270 - grffile: allow periods and spaces in graphics file names
4271 - longtable: For multipage tables
4272 - wrapfig: for figure placement
4273 - rotating: for sideways figures and tables
4274 - ulem: for underline and strike-through
4275 - amsmath: for subscript and superscript and math environments
4276 - textcomp, amssymb: for various symbols used
4277 for interpreting the entities in `org-entities'. You can skip
4278 some of these packages if you don't use any of their symbols.
4279 - capt-of: for captions outside of floats
4280 - hyperref: for cross references
4282 Therefore you should not modify this variable unless you know
4283 what you are doing. The one reason to change it anyway is that
4284 you might be loading some other package that conflicts with one
4285 of the default packages. Each element is either a cell or
4286 a string.
4288 A cell is of the format
4290 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4292 If SNIPPET-FLAG is non-nil, the package also needs to be included
4293 when compiling LaTeX snippets into images for inclusion into
4294 non-LaTeX output. COMPILERS is a list of compilers that should
4295 include the package, see `org-latex-compiler'. If the document
4296 compiler is not in the list, and the list is non-nil, the package
4297 will not be inserted in the final document.
4299 A string will be inserted as-is in the header of the document."
4300 :group 'org-latex
4301 :group 'org-export-latex
4302 :set 'org-set-packages-alist
4303 :get 'org-get-packages-alist
4304 :version "26.1"
4305 :package-version '(Org . "8.3")
4306 :type '(repeat
4307 (choice
4308 (list :tag "options/package pair"
4309 (string :tag "options")
4310 (string :tag "package")
4311 (boolean :tag "Snippet"))
4312 (string :tag "A line of LaTeX"))))
4314 (defcustom org-latex-packages-alist nil
4315 "Alist of packages to be inserted in every LaTeX header.
4317 These will be inserted after `org-latex-default-packages-alist'.
4318 Each element is either a cell or a string.
4320 A cell is of the format:
4322 (\"options\" \"package\" SNIPPET-FLAG)
4324 SNIPPET-FLAG, when non-nil, indicates that this package is also
4325 needed when turning LaTeX snippets into images for inclusion into
4326 non-LaTeX output.
4328 A string will be inserted as-is in the header of the document.
4330 Make sure that you only list packages here which:
4332 - you want in every file;
4333 - do not conflict with the setup in `org-format-latex-header';
4334 - do not conflict with the default packages in
4335 `org-latex-default-packages-alist'."
4336 :group 'org-latex
4337 :group 'org-export-latex
4338 :set 'org-set-packages-alist
4339 :get 'org-get-packages-alist
4340 :type '(repeat
4341 (choice
4342 (list :tag "options/package pair"
4343 (string :tag "options")
4344 (string :tag "package")
4345 (boolean :tag "Snippet"))
4346 (string :tag "A line of LaTeX"))))
4348 (defgroup org-appearance nil
4349 "Settings for Org mode appearance."
4350 :tag "Org Appearance"
4351 :group 'org)
4353 (defcustom org-level-color-stars-only nil
4354 "Non-nil means fontify only the stars in each headline.
4355 When nil, the entire headline is fontified.
4356 Changing it requires restart of `font-lock-mode' to become effective
4357 also in regions already fontified."
4358 :group 'org-appearance
4359 :type 'boolean)
4361 (defcustom org-hide-leading-stars nil
4362 "Non-nil means hide the first N-1 stars in a headline.
4363 This works by using the face `org-hide' for these stars. This
4364 face is white for a light background, and black for a dark
4365 background. You may have to customize the face `org-hide' to
4366 make this work.
4367 Changing it requires restart of `font-lock-mode' to become effective
4368 also in regions already fontified.
4369 You may also set this on a per-file basis by adding one of the following
4370 lines to the buffer:
4372 #+STARTUP: hidestars
4373 #+STARTUP: showstars"
4374 :group 'org-appearance
4375 :type 'boolean)
4377 (defcustom org-hidden-keywords nil
4378 "List of symbols corresponding to keywords to be hidden the org buffer.
4379 For example, a value \\='(title) for this list will make the document's title
4380 appear in the buffer without the initial #+TITLE: keyword."
4381 :group 'org-appearance
4382 :version "24.1"
4383 :type '(set (const :tag "#+AUTHOR" author)
4384 (const :tag "#+DATE" date)
4385 (const :tag "#+EMAIL" email)
4386 (const :tag "#+TITLE" title)))
4388 (defcustom org-custom-properties nil
4389 "List of properties (as strings) with a special meaning.
4390 The default use of these custom properties is to let the user
4391 hide them with `org-toggle-custom-properties-visibility'."
4392 :group 'org-properties
4393 :group 'org-appearance
4394 :version "24.3"
4395 :type '(repeat (string :tag "Property Name")))
4397 (defcustom org-fontify-done-headline nil
4398 "Non-nil means change the face of a headline if it is marked DONE.
4399 Normally, only the TODO/DONE keyword indicates the state of a headline.
4400 When this is non-nil, the headline after the keyword is set to the
4401 `org-headline-done' as an additional indication."
4402 :group 'org-appearance
4403 :type 'boolean)
4405 (defcustom org-fontify-emphasized-text t
4406 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4407 Changing this variable requires a restart of Emacs to take effect."
4408 :group 'org-appearance
4409 :type 'boolean)
4411 (defcustom org-fontify-whole-heading-line nil
4412 "Non-nil means fontify the whole line for headings.
4413 This is useful when setting a background color for the
4414 org-level-* faces."
4415 :group 'org-appearance
4416 :type 'boolean)
4418 (defcustom org-highlight-latex-and-related nil
4419 "Non-nil means highlight LaTeX related syntax in the buffer.
4420 When non nil, the value should be a list containing any of the
4421 following symbols:
4422 `latex' Highlight LaTeX snippets and environments.
4423 `script' Highlight subscript and superscript.
4424 `entities' Highlight entities."
4425 :group 'org-appearance
4426 :version "24.4"
4427 :package-version '(Org . "8.0")
4428 :type '(choice
4429 (const :tag "No highlighting" nil)
4430 (set :greedy t :tag "Highlight"
4431 (const :tag "LaTeX snippets and environments" latex)
4432 (const :tag "Subscript and superscript" script)
4433 (const :tag "Entities" entities))))
4435 (defcustom org-hide-emphasis-markers nil
4436 "Non-nil mean font-lock should hide the emphasis marker characters."
4437 :group 'org-appearance
4438 :type 'boolean)
4440 (defcustom org-hide-macro-markers nil
4441 "Non-nil mean font-lock should hide the brackets marking macro calls."
4442 :group 'org-appearance
4443 :type 'boolean)
4445 (defcustom org-pretty-entities nil
4446 "Non-nil means show entities as UTF8 characters.
4447 When nil, the \\name form remains in the buffer."
4448 :group 'org-appearance
4449 :version "24.1"
4450 :type 'boolean)
4452 (defcustom org-pretty-entities-include-sub-superscripts t
4453 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4454 :group 'org-appearance
4455 :version "24.1"
4456 :type 'boolean)
4458 (defvar org-emph-re nil
4459 "Regular expression for matching emphasis.
4460 After a match, the match groups contain these elements:
4461 0 The match of the full regular expression, including the characters
4462 before and after the proper match
4463 1 The character before the proper match, or empty at beginning of line
4464 2 The proper match, including the leading and trailing markers
4465 3 The leading marker like * or /, indicating the type of highlighting
4466 4 The text between the emphasis markers, not including the markers
4467 5 The character after the match, empty at the end of a line")
4468 (defvar org-verbatim-re nil
4469 "Regular expression for matching verbatim text.")
4470 (defvar org-emphasis-regexp-components) ; defined just below
4471 (defvar org-emphasis-alist) ; defined just below
4472 (defun org-set-emph-re (var val)
4473 "Set variable and compute the emphasis regular expression."
4474 (set var val)
4475 (when (and (boundp 'org-emphasis-alist)
4476 (boundp 'org-emphasis-regexp-components)
4477 org-emphasis-alist org-emphasis-regexp-components)
4478 (let* ((e org-emphasis-regexp-components)
4479 (pre (car e))
4480 (post (nth 1 e))
4481 (border (nth 2 e))
4482 (body (nth 3 e))
4483 (nl (nth 4 e))
4484 (body1 (concat body "*?"))
4485 (markers (mapconcat 'car org-emphasis-alist ""))
4486 (vmarkers (mapconcat
4487 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4488 org-emphasis-alist "")))
4489 ;; make sure special characters appear at the right position in the class
4490 (if (string-match "\\^" markers)
4491 (setq markers (concat (replace-match "" t t markers) "^")))
4492 (if (string-match "-" markers)
4493 (setq markers (concat (replace-match "" t t markers) "-")))
4494 (if (string-match "\\^" vmarkers)
4495 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4496 (if (string-match "-" vmarkers)
4497 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4498 (if (> nl 0)
4499 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4500 (int-to-string nl) "\\}")))
4501 ;; Make the regexp
4502 (setq org-emph-re
4503 (concat "\\([" pre "]\\|^\\)"
4504 "\\("
4505 "\\([" markers "]\\)"
4506 "\\("
4507 "[^" border "]\\|"
4508 "[^" border "]"
4509 body1
4510 "[^" border "]"
4511 "\\)"
4512 "\\3\\)"
4513 "\\([" post "]\\|$\\)"))
4514 (setq org-verbatim-re
4515 (concat "\\([" pre "]\\|^\\)"
4516 "\\("
4517 "\\([" vmarkers "]\\)"
4518 "\\("
4519 "[^" border "]\\|"
4520 "[^" border "]"
4521 body1
4522 "[^" border "]"
4523 "\\)"
4524 "\\3\\)"
4525 "\\([" post "]\\|$\\)")))))
4527 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4528 ;; set this option proved cumbersome. See this message/thread:
4529 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4530 (defvar org-emphasis-regexp-components
4531 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4532 "Components used to build the regular expression for emphasis.
4533 This is a list with five entries. Terminology: In an emphasis string
4534 like \" *strong word* \", we call the initial space PREMATCH, the final
4535 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4536 and \"trong wor\" is the body. The different components in this variable
4537 specify what is allowed/forbidden in each part:
4539 pre Chars allowed as prematch. Beginning of line will be allowed too.
4540 post Chars allowed as postmatch. End of line will be allowed too.
4541 border The chars *forbidden* as border characters.
4542 body-regexp A regexp like \".\" to match a body character. Don't use
4543 non-shy groups here, and don't allow newline here.
4544 newline The maximum number of newlines allowed in an emphasis exp.
4546 You need to reload Org or to restart Emacs after customizing this.")
4548 (defcustom org-emphasis-alist
4549 '(("*" bold)
4550 ("/" italic)
4551 ("_" underline)
4552 ("=" org-verbatim verbatim)
4553 ("~" org-code verbatim)
4554 ("+" (:strike-through t)))
4555 "Alist of characters and faces to emphasize text.
4556 Text starting and ending with a special character will be emphasized,
4557 for example *bold*, _underlined_ and /italic/. This variable sets the
4558 marker characters and the face to be used by font-lock for highlighting
4559 in Org buffers.
4561 You need to reload Org or to restart Emacs after customizing this."
4562 :group 'org-appearance
4563 :set 'org-set-emph-re
4564 :version "24.4"
4565 :package-version '(Org . "8.0")
4566 :type '(repeat
4567 (list
4568 (string :tag "Marker character")
4569 (choice
4570 (face :tag "Font-lock-face")
4571 (plist :tag "Face property list"))
4572 (option (const verbatim)))))
4574 (defvar org-protecting-blocks '("src" "example" "export")
4575 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4576 This is needed for font-lock setup.")
4578 ;;; Functions and variables from their packages
4579 ;; Declared here to avoid compiler warnings
4580 (defvar mark-active)
4582 ;; Various packages
4583 (declare-function calc-eval "calc" (str &optional separator &rest args))
4584 (declare-function calendar-forward-day "cal-move" (arg))
4585 (declare-function calendar-goto-date "cal-move" (date))
4586 (declare-function calendar-goto-today "cal-move" ())
4587 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4588 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4589 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4590 (declare-function cdlatex-tab "ext:cdlatex" ())
4591 (declare-function dired-get-filename
4592 "dired"
4593 (&optional localp no-error-if-not-filep))
4594 (declare-function iswitchb-read-buffer
4595 "iswitchb"
4596 (prompt &optional
4597 default require-match _predicate start matches-set))
4598 (declare-function org-agenda-change-all-lines
4599 "org-agenda"
4600 (newhead hdmarker &optional fixface just-this))
4601 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4602 "org-agenda"
4603 (&optional end))
4604 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4605 (declare-function org-agenda-format-item
4606 "org-agenda"
4607 (extra txt &optional level category tags dotime
4608 remove-re habitp))
4609 (declare-function org-agenda-maybe-redo "org-agenda" ())
4610 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4611 (declare-function org-agenda-save-markers-for-cut-and-paste
4612 "org-agenda"
4613 (beg end))
4614 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4615 (declare-function org-agenda-skip "org-agenda" ())
4616 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4617 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4618 (declare-function org-indent-mode "org-indent" (&optional arg))
4619 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4620 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4621 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4622 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4623 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4624 (declare-function parse-time-string "parse-time" (string))
4625 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4627 (defvar align-mode-rules-list)
4628 (defvar calc-embedded-close-formula)
4629 (defvar calc-embedded-open-formula)
4630 (defvar calc-embedded-open-mode)
4631 (defvar font-lock-unfontify-region-function)
4632 (defvar iswitchb-temp-buflist)
4633 (defvar org-agenda-tags-todo-honor-ignore-options)
4634 (defvar remember-data-file)
4635 (defvar texmathp-why)
4637 ;;;###autoload
4638 (defun turn-on-orgtbl ()
4639 "Unconditionally turn on `orgtbl-mode'."
4640 (require 'org-table)
4641 (orgtbl-mode 1))
4643 (defun org-at-table-p (&optional table-type)
4644 "Non-nil if the cursor is inside an Org table.
4645 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4646 If `org-enable-table-editor' is nil, return nil unconditionally."
4647 (and
4648 org-enable-table-editor
4649 (save-excursion
4650 (beginning-of-line)
4651 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4652 (or (not (derived-mode-p 'org-mode))
4653 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4654 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4656 (defun org-at-table.el-p ()
4657 "Non-nil when point is at a table.el table."
4658 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4659 (let ((element (org-element-at-point)))
4660 (and (eq (org-element-type element) 'table)
4661 (eq (org-element-property :type element) 'table.el)))))
4663 (defun org-at-table-hline-p ()
4664 "Non-nil when point is inside a hline in a table.
4665 Assume point is already in a table. If `org-enable-table-editor'
4666 is nil, return nil unconditionally."
4667 (and org-enable-table-editor
4668 (save-excursion
4669 (beginning-of-line)
4670 (looking-at org-table-hline-regexp))))
4672 (defun org-table-map-tables (function &optional quietly)
4673 "Apply FUNCTION to the start of all tables in the buffer."
4674 (org-with-wide-buffer
4675 (goto-char (point-min))
4676 (while (re-search-forward org-table-any-line-regexp nil t)
4677 (unless quietly
4678 (message "Mapping tables: %d%%"
4679 (floor (* 100.0 (point)) (buffer-size))))
4680 (beginning-of-line 1)
4681 (when (and (looking-at org-table-line-regexp)
4682 ;; Exclude tables in src/example/verbatim/clocktable blocks
4683 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4684 (save-excursion (funcall function))
4685 (or (looking-at org-table-line-regexp)
4686 (forward-char 1)))
4687 (re-search-forward org-table-any-border-regexp nil 1)))
4688 (unless quietly (message "Mapping tables: done")))
4690 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4691 (declare-function org-clock-update-mode-line "org-clock" ())
4692 (declare-function org-resolve-clocks "org-clock"
4693 (&optional also-non-dangling-p prompt last-valid))
4695 (defun org-at-TBLFM-p (&optional pos)
4696 "Non-nil when point (or POS) is in #+TBLFM line."
4697 (save-excursion
4698 (goto-char (or pos (point)))
4699 (beginning-of-line)
4700 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4701 (eq (org-element-type (org-element-at-point)) 'table))))
4703 (defvar org-clock-start-time)
4704 (defvar org-clock-marker (make-marker)
4705 "Marker recording the last clock-in.")
4706 (defvar org-clock-hd-marker (make-marker)
4707 "Marker recording the last clock-in, but the headline position.")
4708 (defvar org-clock-heading ""
4709 "The heading of the current clock entry.")
4710 (defun org-clock-is-active ()
4711 "Return the buffer where the clock is currently running.
4712 Return nil if no clock is running."
4713 (marker-buffer org-clock-marker))
4715 (defun org-check-running-clock ()
4716 "Check if the current buffer contains the running clock.
4717 If yes, offer to stop it and to save the buffer with the changes."
4718 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4719 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4720 (buffer-name))))
4721 (org-clock-out)
4722 (when (y-or-n-p "Save changed buffer?")
4723 (save-buffer))))
4725 (defun org-clocktable-try-shift (dir n)
4726 "Check if this line starts a clock table, if yes, shift the time block."
4727 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4728 (org-clocktable-shift dir n)))
4730 ;;;###autoload
4731 (defun org-clock-persistence-insinuate ()
4732 "Set up hooks for clock persistence."
4733 (require 'org-clock)
4734 (add-hook 'org-mode-hook 'org-clock-load)
4735 (add-hook 'kill-emacs-hook 'org-clock-save))
4737 (defgroup org-archive nil
4738 "Options concerning archiving in Org mode."
4739 :tag "Org Archive"
4740 :group 'org-structure)
4742 (defcustom org-archive-location "%s_archive::"
4743 "The location where subtrees should be archived.
4745 The value of this variable is a string, consisting of two parts,
4746 separated by a double-colon. The first part is a filename and
4747 the second part is a headline.
4749 When the filename is omitted, archiving happens in the same file.
4750 %s in the filename will be replaced by the current file
4751 name (without the directory part). Archiving to a different file
4752 is useful to keep archived entries from contributing to the
4753 Org Agenda.
4755 The archived entries will be filed as subtrees of the specified
4756 headline. When the headline is omitted, the subtrees are simply
4757 filed away at the end of the file, as top-level entries. Also in
4758 the heading you can use %s to represent the file name, this can be
4759 useful when using the same archive for a number of different files.
4761 Here are a few examples:
4762 \"%s_archive::\"
4763 If the current file is Projects.org, archive in file
4764 Projects.org_archive, as top-level trees. This is the default.
4766 \"::* Archived Tasks\"
4767 Archive in the current file, under the top-level headline
4768 \"* Archived Tasks\".
4770 \"~/org/archive.org::\"
4771 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4773 \"~/org/archive.org::* From %s\"
4774 Archive in file ~/org/archive.org (absolute path), under headlines
4775 \"From FILENAME\" where file name is the current file name.
4777 \"~/org/datetree.org::datetree/* Finished Tasks\"
4778 The \"datetree/\" string is special, signifying to archive
4779 items to the datetree. Items are placed in either the CLOSED
4780 date of the item, or the current date if there is no CLOSED date.
4781 The heading will be a subentry to the current date. There doesn't
4782 need to be a heading, but there always needs to be a slash after
4783 datetree. For example, to store archived items directly in the
4784 datetree, use \"~/org/datetree.org::datetree/\".
4786 \"basement::** Finished Tasks\"
4787 Archive in file ./basement (relative path), as level 3 trees
4788 below the level 2 heading \"** Finished Tasks\".
4790 You may set this option on a per-file basis by adding to the buffer a
4791 line like
4793 #+ARCHIVE: basement::** Finished Tasks
4795 You may also define it locally for a subtree by setting an ARCHIVE property
4796 in the entry. If such a property is found in an entry, or anywhere up
4797 the hierarchy, it will be used."
4798 :group 'org-archive
4799 :type 'string)
4801 (defcustom org-agenda-skip-archived-trees t
4802 "Non-nil means the agenda will skip any items located in archived trees.
4803 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4804 variable is no longer recommended, you should leave it at the value t.
4805 Instead, use the key `v' to cycle the archives-mode in the agenda."
4806 :group 'org-archive
4807 :group 'org-agenda-skip
4808 :type 'boolean)
4810 (defcustom org-columns-skip-archived-trees t
4811 "Non-nil means ignore archived trees when creating column view."
4812 :group 'org-archive
4813 :group 'org-properties
4814 :type 'boolean)
4816 (defcustom org-cycle-open-archived-trees nil
4817 "Non-nil means `org-cycle' will open archived trees.
4818 An archived tree is a tree marked with the tag ARCHIVE.
4819 When nil, archived trees will stay folded. You can still open them with
4820 normal outline commands like `show-all', but not with the cycling commands."
4821 :group 'org-archive
4822 :group 'org-cycle
4823 :type 'boolean)
4825 (defcustom org-sparse-tree-open-archived-trees nil
4826 "Non-nil means sparse tree construction shows matches in archived trees.
4827 When nil, matches in these trees are highlighted, but the trees are kept in
4828 collapsed state."
4829 :group 'org-archive
4830 :group 'org-sparse-trees
4831 :type 'boolean)
4833 (defcustom org-sparse-tree-default-date-type nil
4834 "The default date type when building a sparse tree.
4835 When this is nil, a date is a scheduled or a deadline timestamp.
4836 Otherwise, these types are allowed:
4838 all: all timestamps
4839 active: only active timestamps (<...>)
4840 inactive: only inactive timestamps ([...])
4841 scheduled: only scheduled timestamps
4842 deadline: only deadline timestamps"
4843 :type '(choice (const :tag "Scheduled or deadline" nil)
4844 (const :tag "All timestamps" all)
4845 (const :tag "Only active timestamps" active)
4846 (const :tag "Only inactive timestamps" inactive)
4847 (const :tag "Only scheduled timestamps" scheduled)
4848 (const :tag "Only deadline timestamps" deadline)
4849 (const :tag "Only closed timestamps" closed))
4850 :version "26.1"
4851 :package-version '(Org . "8.3")
4852 :group 'org-sparse-trees)
4854 (defun org-cycle-hide-archived-subtrees (state)
4855 "Re-hide all archived subtrees after a visibility state change."
4856 (when (and (not org-cycle-open-archived-trees)
4857 (not (memq state '(overview folded))))
4858 (save-excursion
4859 (let* ((globalp (memq state '(contents all)))
4860 (beg (if globalp (point-min) (point)))
4861 (end (if globalp (point-max) (org-end-of-subtree t))))
4862 (org-hide-archived-subtrees beg end)
4863 (goto-char beg)
4864 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4865 (message "%s" (substitute-command-keys
4866 "Subtree is archived and stays closed. Use \
4867 `\\[org-force-cycle-archived]' to cycle it anyway.")))))))
4869 (defun org-force-cycle-archived ()
4870 "Cycle subtree even if it is archived."
4871 (interactive)
4872 (setq this-command 'org-cycle)
4873 (let ((org-cycle-open-archived-trees t))
4874 (call-interactively 'org-cycle)))
4876 (defun org-hide-archived-subtrees (beg end)
4877 "Re-hide all archived subtrees after a visibility state change."
4878 (org-with-wide-buffer
4879 (let ((case-fold-search nil)
4880 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4881 (goto-char beg)
4882 ;; Include headline point is currently on.
4883 (beginning-of-line)
4884 (while (and (< (point) end) (re-search-forward re end t))
4885 (when (member org-archive-tag (org-get-tags))
4886 (org-flag-subtree t)
4887 (org-end-of-subtree t))))))
4889 (declare-function outline-end-of-heading "outline" ())
4890 (declare-function outline-flag-region "outline" (from to flag))
4891 (defun org-flag-subtree (flag)
4892 (save-excursion
4893 (org-back-to-heading t)
4894 (outline-end-of-heading)
4895 (outline-flag-region (point)
4896 (progn (org-end-of-subtree t) (point))
4897 flag)))
4899 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4901 ;; Declare Column View Code
4903 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4904 (declare-function org-columns-compute "org-colview" (property))
4906 ;; Declare ID code
4908 (declare-function org-id-store-link "org-id")
4909 (declare-function org-id-locations-load "org-id")
4910 (declare-function org-id-locations-save "org-id")
4911 (defvar org-id-track-globally)
4913 ;;; Variables for pre-computed regular expressions, all buffer local
4915 (defvar-local org-todo-regexp nil
4916 "Matches any of the TODO state keywords.
4917 Since TODO keywords are case-sensitive, `case-fold-search' is
4918 expected to be bound to nil when matching against this regexp.")
4920 (defvar-local org-not-done-regexp nil
4921 "Matches any of the TODO state keywords except the last one.
4922 Since TODO keywords are case-sensitive, `case-fold-search' is
4923 expected to be bound to nil when matching against this regexp.")
4925 (defvar-local org-not-done-heading-regexp nil
4926 "Matches a TODO headline that is not done.
4927 Since TODO keywords are case-sensitive, `case-fold-search' is
4928 expected to be bound to nil when matching against this regexp.")
4930 (defvar-local org-todo-line-regexp nil
4931 "Matches a headline and puts TODO state into group 2 if present.
4932 Since TODO keywords are case-sensitive, `case-fold-search' is
4933 expected to be bound to nil when matching against this regexp.")
4935 (defvar-local org-complex-heading-regexp nil
4936 "Matches a headline and puts everything into groups:
4938 group 1: Stars
4939 group 2: The TODO keyword, maybe
4940 group 3: Priority cookie
4941 group 4: True headline
4942 group 5: Tags
4944 Since TODO keywords are case-sensitive, `case-fold-search' is
4945 expected to be bound to nil when matching against this regexp.")
4947 (defvar-local org-complex-heading-regexp-format nil
4948 "Printf format to make regexp to match an exact headline.
4949 This regexp will match the headline of any node which has the
4950 exact headline text that is put into the format, but may have any
4951 TODO state, priority and tags.")
4953 (defvar-local org-todo-line-tags-regexp nil
4954 "Matches a headline and puts TODO state into group 2 if present.
4955 Also put tags into group 4 if tags are present.")
4957 (defconst org-plain-time-of-day-regexp
4958 (concat
4959 "\\(\\<[012]?[0-9]"
4960 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4961 "\\(--?"
4962 "\\(\\<[012]?[0-9]"
4963 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4964 "\\)?")
4965 "Regular expression to match a plain time or time range.
4966 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4967 groups carry important information:
4968 0 the full match
4969 1 the first time, range or not
4970 8 the second time, if it is a range.")
4972 (defconst org-plain-time-extension-regexp
4973 (concat
4974 "\\(\\<[012]?[0-9]"
4975 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4976 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4977 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4978 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4979 groups carry important information:
4980 0 the full match
4981 7 hours of duration
4982 9 minutes of duration")
4984 (defconst org-stamp-time-of-day-regexp
4985 (concat
4986 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4987 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4988 "\\(--?"
4989 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4990 "Regular expression to match a timestamp time or time range.
4991 After a match, the following groups carry important information:
4992 0 the full match
4993 1 date plus weekday, for back referencing to make sure both times are on the same day
4994 2 the first time, range or not
4995 4 the second time, if it is a range.")
4997 (defconst org-startup-options
4998 '(("fold" org-startup-folded t)
4999 ("overview" org-startup-folded t)
5000 ("nofold" org-startup-folded nil)
5001 ("showall" org-startup-folded nil)
5002 ("showeverything" org-startup-folded showeverything)
5003 ("content" org-startup-folded content)
5004 ("indent" org-startup-indented t)
5005 ("noindent" org-startup-indented nil)
5006 ("hidestars" org-hide-leading-stars t)
5007 ("showstars" org-hide-leading-stars nil)
5008 ("odd" org-odd-levels-only t)
5009 ("oddeven" org-odd-levels-only nil)
5010 ("align" org-startup-align-all-tables t)
5011 ("noalign" org-startup-align-all-tables nil)
5012 ("inlineimages" org-startup-with-inline-images t)
5013 ("noinlineimages" org-startup-with-inline-images nil)
5014 ("latexpreview" org-startup-with-latex-preview t)
5015 ("nolatexpreview" org-startup-with-latex-preview nil)
5016 ("customtime" org-display-custom-times t)
5017 ("logdone" org-log-done time)
5018 ("lognotedone" org-log-done note)
5019 ("nologdone" org-log-done nil)
5020 ("lognoteclock-out" org-log-note-clock-out t)
5021 ("nolognoteclock-out" org-log-note-clock-out nil)
5022 ("logrepeat" org-log-repeat state)
5023 ("lognoterepeat" org-log-repeat note)
5024 ("logdrawer" org-log-into-drawer t)
5025 ("nologdrawer" org-log-into-drawer nil)
5026 ("logstatesreversed" org-log-states-order-reversed t)
5027 ("nologstatesreversed" org-log-states-order-reversed nil)
5028 ("nologrepeat" org-log-repeat nil)
5029 ("logreschedule" org-log-reschedule time)
5030 ("lognotereschedule" org-log-reschedule note)
5031 ("nologreschedule" org-log-reschedule nil)
5032 ("logredeadline" org-log-redeadline time)
5033 ("lognoteredeadline" org-log-redeadline note)
5034 ("nologredeadline" org-log-redeadline nil)
5035 ("logrefile" org-log-refile time)
5036 ("lognoterefile" org-log-refile note)
5037 ("nologrefile" org-log-refile nil)
5038 ("fninline" org-footnote-define-inline t)
5039 ("nofninline" org-footnote-define-inline nil)
5040 ("fnlocal" org-footnote-section nil)
5041 ("fnauto" org-footnote-auto-label t)
5042 ("fnprompt" org-footnote-auto-label nil)
5043 ("fnconfirm" org-footnote-auto-label confirm)
5044 ("fnplain" org-footnote-auto-label plain)
5045 ("fnadjust" org-footnote-auto-adjust t)
5046 ("nofnadjust" org-footnote-auto-adjust nil)
5047 ("constcgs" constants-unit-system cgs)
5048 ("constSI" constants-unit-system SI)
5049 ("noptag" org-tag-persistent-alist nil)
5050 ("hideblocks" org-hide-block-startup t)
5051 ("nohideblocks" org-hide-block-startup nil)
5052 ("beamer" org-startup-with-beamer-mode t)
5053 ("entitiespretty" org-pretty-entities t)
5054 ("entitiesplain" org-pretty-entities nil))
5055 "Variable associated with STARTUP options for org-mode.
5056 Each element is a list of three items: the startup options (as written
5057 in the #+STARTUP line), the corresponding variable, and the value to set
5058 this variable to if the option is found. An optional forth element PUSH
5059 means to push this value onto the list in the variable.")
5061 (defcustom org-group-tags t
5062 "When non-nil (the default), use group tags.
5063 This can be turned on/off through `org-toggle-tags-groups'."
5064 :group 'org-tags
5065 :group 'org-startup
5066 :type 'boolean)
5068 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5070 (defun org-toggle-tags-groups ()
5071 "Toggle support for group tags.
5072 Support for group tags is controlled by the option
5073 `org-group-tags', which is non-nil by default."
5074 (interactive)
5075 (setq org-group-tags (not org-group-tags))
5076 (cond ((and (derived-mode-p 'org-agenda-mode)
5077 org-group-tags)
5078 (org-agenda-redo))
5079 ((derived-mode-p 'org-mode)
5080 (let ((org-inhibit-startup t)) (org-mode))))
5081 (message "Groups tags support has been turned %s"
5082 (if org-group-tags "on" "off")))
5084 (defun org-set-regexps-and-options (&optional tags-only)
5085 "Precompute regular expressions used in the current buffer.
5086 When optional argument TAGS-ONLY is non-nil, only compute tags
5087 related expressions."
5088 (when (derived-mode-p 'org-mode)
5089 (let ((alist (org--setup-collect-keywords
5090 (org-make-options-regexp
5091 (append '("FILETAGS" "TAGS" "SETUPFILE")
5092 (and (not tags-only)
5093 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
5094 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
5095 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
5096 ;; Startup options. Get this early since it does change
5097 ;; behavior for other options (e.g., tags).
5098 (let ((startup (cdr (assq 'startup alist))))
5099 (dolist (option startup)
5100 (let ((entry (assoc-string option org-startup-options t)))
5101 (when entry
5102 (let ((var (nth 1 entry))
5103 (val (nth 2 entry)))
5104 (if (not (nth 3 entry)) (set (make-local-variable var) val)
5105 (unless (listp (symbol-value var))
5106 (set (make-local-variable var) nil))
5107 (add-to-list var val)))))))
5108 (setq-local org-file-tags
5109 (mapcar #'org-add-prop-inherited
5110 (cdr (assq 'filetags alist))))
5111 (setq org-current-tag-alist
5112 (append org-tag-persistent-alist
5113 (let ((tags (cdr (assq 'tags alist))))
5114 (if tags (org-tag-string-to-alist tags)
5115 org-tag-alist))))
5116 (setq org-tag-groups-alist
5117 (org-tag-alist-to-groups org-current-tag-alist))
5118 (unless tags-only
5119 ;; File properties.
5120 (setq-local org-file-properties (cdr (assq 'property alist)))
5121 ;; Archive location.
5122 (let ((archive (cdr (assq 'archive alist))))
5123 (when archive (setq-local org-archive-location archive)))
5124 ;; Category.
5125 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
5126 (when cat
5127 (setq-local org-category (intern cat))
5128 (setq-local org-file-properties
5129 (org--update-property-plist
5130 "CATEGORY" cat org-file-properties))))
5131 ;; Columns.
5132 (let ((column (cdr (assq 'columns alist))))
5133 (when column (setq-local org-columns-default-format column)))
5134 ;; Constants.
5135 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
5136 ;; Link abbreviations.
5137 (let ((links (cdr (assq 'link alist))))
5138 (when links (setq org-link-abbrev-alist-local (nreverse links))))
5139 ;; Priorities.
5140 (let ((priorities (cdr (assq 'priorities alist))))
5141 (when priorities
5142 (setq-local org-highest-priority (nth 0 priorities))
5143 (setq-local org-lowest-priority (nth 1 priorities))
5144 (setq-local org-default-priority (nth 2 priorities))))
5145 ;; Scripts.
5146 (let ((scripts (assq 'scripts alist)))
5147 (when scripts
5148 (setq-local org-use-sub-superscripts (cdr scripts))))
5149 ;; TODO keywords.
5150 (setq-local org-todo-kwd-alist nil)
5151 (setq-local org-todo-key-alist nil)
5152 (setq-local org-todo-key-trigger nil)
5153 (setq-local org-todo-keywords-1 nil)
5154 (setq-local org-done-keywords nil)
5155 (setq-local org-todo-heads nil)
5156 (setq-local org-todo-sets nil)
5157 (setq-local org-todo-log-states nil)
5158 (let ((todo-sequences
5159 (or (nreverse (cdr (assq 'todo alist)))
5160 (let ((d (default-value 'org-todo-keywords)))
5161 (if (not (stringp (car d))) d
5162 ;; XXX: Backward compatibility code.
5163 (list (cons org-todo-interpretation d)))))))
5164 (dolist (sequence todo-sequences)
5165 (let* ((sequence (or (run-hook-with-args-until-success
5166 'org-todo-setup-filter-hook sequence)
5167 sequence))
5168 (sequence-type (car sequence))
5169 (keywords (cdr sequence))
5170 (sep (member "|" keywords))
5171 names alist)
5172 (dolist (k (remove "|" keywords))
5173 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5175 (error "Invalid TODO keyword %s" k))
5176 (let ((name (match-string 1 k))
5177 (key (match-string 2 k))
5178 (log (org-extract-log-state-settings k)))
5179 (push name names)
5180 (push (cons name (and key (string-to-char key))) alist)
5181 (when log (push log org-todo-log-states))))
5182 (let* ((names (nreverse names))
5183 (done (if sep (org-remove-keyword-keys (cdr sep))
5184 (last names)))
5185 (head (car names))
5186 (tail (list sequence-type head (car done) (org-last done))))
5187 (add-to-list 'org-todo-heads head 'append)
5188 (push names org-todo-sets)
5189 (setq org-done-keywords (append org-done-keywords done nil))
5190 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5191 (setq org-todo-key-alist
5192 (append org-todo-key-alist
5193 (and alist
5194 (append '((:startgroup))
5195 (nreverse alist)
5196 '((:endgroup))))))
5197 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5198 (setq org-todo-sets (nreverse org-todo-sets)
5199 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5200 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5201 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5202 ;; Compute the regular expressions and other local variables.
5203 ;; Using `org-outline-regexp-bol' would complicate them much,
5204 ;; because of the fixed white space at the end of that string.
5205 (unless org-done-keywords
5206 (setq org-done-keywords
5207 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5208 (setq org-not-done-keywords
5209 (org-delete-all org-done-keywords
5210 (copy-sequence org-todo-keywords-1))
5211 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5212 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5213 org-not-done-heading-regexp
5214 (format org-heading-keyword-regexp-format org-not-done-regexp)
5215 org-todo-line-regexp
5216 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5217 org-complex-heading-regexp
5218 (concat "^\\(\\*+\\)"
5219 "\\(?: +" org-todo-regexp "\\)?"
5220 "\\(?: +\\(\\[#.\\]\\)\\)?"
5221 "\\(?: +\\(.*?\\)\\)??"
5222 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5223 "[ \t]*$")
5224 org-complex-heading-regexp-format
5225 (concat "^\\(\\*+\\)"
5226 "\\(?: +" org-todo-regexp "\\)?"
5227 "\\(?: +\\(\\[#.\\]\\)\\)?"
5228 "\\(?: +"
5229 ;; Stats cookies can be stuck to body.
5230 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5231 "\\(%s\\)"
5232 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5233 "\\)"
5234 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5235 "[ \t]*$")
5236 org-todo-line-tags-regexp
5237 (concat "^\\(\\*+\\)"
5238 "\\(?: +" org-todo-regexp "\\)?"
5239 "\\(?: +\\(.*?\\)\\)??"
5240 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5241 "[ \t]*$"))
5242 (org-compute-latex-and-related-regexp)))))
5244 (defun org--setup-collect-keywords (regexp &optional files alist)
5245 "Return setup keywords values as an alist.
5247 REGEXP matches a subset of setup keywords. FILES is a list of
5248 file names already visited. It is used to avoid circular setup
5249 files. ALIST, when non-nil, is the alist computed so far.
5251 Return value contains the following keys: `archive', `category',
5252 `columns', `constants', `filetags', `link', `priorities',
5253 `property', `scripts', `startup', `tags' and `todo'."
5254 (org-with-wide-buffer
5255 (goto-char (point-min))
5256 (let ((case-fold-search t))
5257 (while (re-search-forward regexp nil t)
5258 (let ((element (org-element-at-point)))
5259 (when (eq (org-element-type element) 'keyword)
5260 (let ((key (org-element-property :key element))
5261 (value (org-element-property :value element)))
5262 (cond
5263 ((equal key "ARCHIVE")
5264 (when (org-string-nw-p value)
5265 (push (cons 'archive value) alist)))
5266 ((equal key "CATEGORY") (push (cons 'category value) alist))
5267 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5268 ((equal key "CONSTANTS")
5269 (let* ((constants (assq 'constants alist))
5270 (store (cdr constants)))
5271 (dolist (pair (org-split-string value))
5272 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5273 pair)
5274 (let* ((name (match-string 1 pair))
5275 (value (match-string 2 pair))
5276 (old (assoc name store)))
5277 (if old (setcdr old value)
5278 (push (cons name value) store)))))
5279 (if constants (setcdr constants store)
5280 (push (cons 'constants store) alist))))
5281 ((equal key "FILETAGS")
5282 (when (org-string-nw-p value)
5283 (let ((old (assq 'filetags alist))
5284 (new (apply #'nconc
5285 (mapcar (lambda (x) (org-split-string x ":"))
5286 (org-split-string value)))))
5287 (if old (setcdr old (append new (cdr old)))
5288 (push (cons 'filetags new) alist)))))
5289 ((equal key "LINK")
5290 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5291 (let ((links (assq 'link alist))
5292 (pair (cons (match-string-no-properties 1 value)
5293 (match-string-no-properties 2 value))))
5294 (if links (push pair (cdr links))
5295 (push (list 'link pair) alist)))))
5296 ((equal key "OPTIONS")
5297 (when (and (org-string-nw-p value)
5298 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5299 (push (cons 'scripts (read (match-string 1 value))) alist)))
5300 ((equal key "PRIORITIES")
5301 (push (cons 'priorities
5302 (let ((prio (org-split-string value)))
5303 (if (< (length prio) 3) '(?A ?C ?B)
5304 (mapcar #'string-to-char prio))))
5305 alist))
5306 ((equal key "PROPERTY")
5307 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5308 (let* ((property (assq 'property alist))
5309 (value (org--update-property-plist
5310 (match-string-no-properties 1 value)
5311 (match-string-no-properties 2 value)
5312 (cdr property))))
5313 (if property (setcdr property value)
5314 (push (cons 'property value) alist)))))
5315 ((equal key "STARTUP")
5316 (let ((startup (assq 'startup alist)))
5317 (if startup
5318 (setcdr startup
5319 (append (cdr startup) (org-split-string value)))
5320 (push (cons 'startup (org-split-string value)) alist))))
5321 ((equal key "TAGS")
5322 (let ((tag-cell (assq 'tags alist)))
5323 (if tag-cell
5324 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5325 (push (cons 'tags value) alist))))
5326 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5327 (let ((todo (assq 'todo alist))
5328 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5329 (org-split-string value))))
5330 (if todo (push value (cdr todo))
5331 (push (list 'todo value) alist))))
5332 ((equal key "SETUPFILE")
5333 (unless buffer-read-only ; Do not check in Gnus messages.
5334 (let ((f (and (org-string-nw-p value)
5335 (expand-file-name
5336 (org-unbracket-string "\"" "\"" value)))))
5337 (when (and f (file-readable-p f) (not (member f files)))
5338 (with-temp-buffer
5339 (setq default-directory (file-name-directory f))
5340 (insert-file-contents f)
5341 (setq alist
5342 ;; Fake Org mode to benefit from cache
5343 ;; without recurring needlessly.
5344 (let ((major-mode 'org-mode))
5345 (org--setup-collect-keywords
5346 regexp (cons f files) alist)))))))))))))))
5347 alist)
5349 (defun org-tag-string-to-alist (s)
5350 "Return tag alist associated to string S.
5351 S is a value for TAGS keyword or produced with
5352 `org-tag-alist-to-string'. Return value is an alist suitable for
5353 `org-tag-alist' or `org-tag-persistent-alist'."
5354 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5355 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5356 "\\|{.+?}\\)" ; regular expression
5357 "\\(?:(\\(.\\))\\)?\\'"))
5358 alist group-flag)
5359 (dolist (tokens lines (cdr (nreverse alist)))
5360 (push '(:newline) alist)
5361 (while tokens
5362 (let ((token (pop tokens)))
5363 (pcase token
5364 ("{"
5365 (push '(:startgroup) alist)
5366 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5367 ("}"
5368 (push '(:endgroup) alist)
5369 (setq group-flag nil))
5370 ("["
5371 (push '(:startgrouptag) alist)
5372 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5373 ("]"
5374 (push '(:endgrouptag) alist)
5375 (setq group-flag nil))
5376 (":"
5377 (push '(:grouptags) alist))
5378 ((guard (string-match tag-re token))
5379 (let ((tag (match-string 1 token))
5380 (key (and (match-beginning 2)
5381 (string-to-char (match-string 2 token)))))
5382 ;; Push all tags in groups, no matter if they already
5383 ;; appear somewhere else in the list.
5384 (when (or group-flag (not (assoc tag alist)))
5385 (push (cons tag key) alist))))))))))
5387 (defun org-tag-alist-to-string (alist &optional skip-key)
5388 "Return tag string associated to ALIST.
5390 ALIST is an alist, as defined in `org-tag-alist' or
5391 `org-tag-persistent-alist', or produced with
5392 `org-tag-string-to-alist'.
5394 Return value is a string suitable as a value for \"TAGS\"
5395 keyword.
5397 When optional argument SKIP-KEY is non-nil, skip selection keys
5398 next to tags."
5399 (mapconcat (lambda (token)
5400 (pcase token
5401 (`(:startgroup) "{")
5402 (`(:endgroup) "}")
5403 (`(:startgrouptag) "[")
5404 (`(:endgrouptag) "]")
5405 (`(:grouptags) ":")
5406 (`(:newline) "\\n")
5407 ((and
5408 (guard (not skip-key))
5409 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5410 (format "%s(%c)" tag key))
5411 (`(,(and tag (pred stringp)) . ,_) tag)
5412 (_ (user-error "Invalid tag token: %S" token))))
5413 alist
5414 " "))
5416 (defun org-tag-alist-to-groups (alist)
5417 "Return group alist from tag ALIST.
5418 ALIST is an alist, as defined in `org-tag-alist' or
5419 `org-tag-persistent-alist', or produced with
5420 `org-tag-string-to-alist'. Return value is an alist following
5421 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5422 a string, summarizing TAGS, as a list of strings."
5423 (let (groups group-status current-group)
5424 (dolist (token alist (nreverse groups))
5425 (pcase token
5426 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5427 (`(,(or :endgroup :endgrouptag))
5428 (when (eq group-status 'append)
5429 (push (nreverse current-group) groups))
5430 (setq group-status nil))
5431 (`(:grouptags) (setq group-status 'append))
5432 ((and `(,tag . ,_) (guard group-status))
5433 (if (eq group-status 'append) (push tag current-group)
5434 (setq current-group (list tag))))
5435 (_ nil)))))
5437 (defun org-file-contents (file &optional noerror)
5438 "Return the contents of FILE, as a string."
5439 (if (and file (file-readable-p file))
5440 (with-temp-buffer
5441 (insert-file-contents file)
5442 (buffer-string))
5443 (funcall (if noerror 'message 'error)
5444 "Cannot read file \"%s\"%s"
5445 file
5446 (let ((from (buffer-file-name (buffer-base-buffer))))
5447 (if from (concat " (referenced in file \"" from "\")") "")))))
5449 (defun org-extract-log-state-settings (x)
5450 "Extract the log state setting from a TODO keyword string.
5451 This will extract info from a string like \"WAIT(w@/!)\"."
5452 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5453 (let ((kw (match-string 1 x))
5454 (log1 (and (match-end 3) (match-string 3 x)))
5455 (log2 (and (match-end 4) (match-string 4 x))))
5456 (and (or log1 log2)
5457 (list kw
5458 (and log1 (if (equal log1 "!") 'time 'note))
5459 (and log2 (if (equal log2 "!") 'time 'note)))))))
5461 (defun org-remove-keyword-keys (list)
5462 "Remove a pair of parenthesis at the end of each string in LIST."
5463 (mapcar (lambda (x)
5464 (if (string-match "(.*)$" x)
5465 (substring x 0 (match-beginning 0))
5467 list))
5469 (defun org-assign-fast-keys (alist)
5470 "Assign fast keys to a keyword-key alist.
5471 Respect keys that are already there."
5472 (let (new e (alt ?0))
5473 (while (setq e (pop alist))
5474 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5475 (cdr e)) ;; Key already assigned.
5476 (push e new)
5477 (let ((clist (string-to-list (downcase (car e))))
5478 (used (append new alist)))
5479 (when (= (car clist) ?@)
5480 (pop clist))
5481 (while (and clist (rassoc (car clist) used))
5482 (pop clist))
5483 (unless clist
5484 (while (rassoc alt used)
5485 (cl-incf alt)))
5486 (push (cons (car e) (or (car clist) alt)) new))))
5487 (nreverse new)))
5489 ;;; Some variables used in various places
5491 (defvar org-window-configuration nil
5492 "Used in various places to store a window configuration.")
5493 (defvar org-selected-window nil
5494 "Used in various places to store a window configuration.")
5495 (defvar org-finish-function nil
5496 "Function to be called when `C-c C-c' is used.
5497 This is for getting out of special buffers like capture.")
5498 (defvar org-last-state)
5500 ;; Defined somewhere in this file, but used before definition.
5501 (defvar org-entities) ;; defined in org-entities.el
5502 (defvar org-struct-menu)
5503 (defvar org-org-menu)
5504 (defvar org-tbl-menu)
5506 ;;;; Define the Org mode
5508 ;; We use a before-change function to check if a table might need
5509 ;; an update.
5510 (defvar org-table-may-need-update t
5511 "Indicates that a table might need an update.
5512 This variable is set by `org-before-change-function'.
5513 `org-table-align' sets it back to nil.")
5514 (defun org-before-change-function (_beg _end)
5515 "Every change indicates that a table might need an update."
5516 (setq org-table-may-need-update t))
5517 (defvar org-mode-map)
5518 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5519 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5520 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5521 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5522 (defvar org-table-buffer-is-an nil)
5524 (defvar bidi-paragraph-direction)
5525 (defvar buffer-face-mode-face)
5527 (require 'outline)
5529 ;; Other stuff we need.
5530 (require 'time-date)
5531 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5532 (require 'easymenu)
5533 (autoload 'easy-menu-add "easymenu")
5534 (require 'overlay)
5536 ;; (require 'org-macs) moved higher up in the file before it is first used
5537 (require 'org-entities)
5538 ;; (require 'org-compat) moved higher up in the file before it is first used
5539 (require 'org-faces)
5540 (require 'org-list)
5541 (require 'org-pcomplete)
5542 (require 'org-src)
5543 (require 'org-footnote)
5544 (require 'org-macro)
5546 ;; babel
5547 (require 'ob)
5549 ;;;###autoload
5550 (define-derived-mode org-mode outline-mode "Org"
5551 "Outline-based notes management and organizer, alias
5552 \"Carsten's outline-mode for keeping track of everything.\"
5554 Org mode develops organizational tasks around a NOTES file which
5555 contains information about projects as plain text. Org mode is
5556 implemented on top of Outline mode, which is ideal to keep the content
5557 of large files well structured. It supports ToDo items, deadlines and
5558 time stamps, which magically appear in the diary listing of the Emacs
5559 calendar. Tables are easily created with a built-in table editor.
5560 Plain text URL-like links connect to websites, emails (VM), Usenet
5561 messages (Gnus), BBDB entries, and any files related to the project.
5562 For printing and sharing of notes, an Org file (or a part of it)
5563 can be exported as a structured ASCII or HTML file.
5565 The following commands are available:
5567 \\{org-mode-map}"
5569 ;; Get rid of Outline menus, they are not needed
5570 ;; Need to do this here because define-derived-mode sets up
5571 ;; the keymap so late. Still, it is a waste to call this each time
5572 ;; we switch another buffer into Org mode.
5573 (define-key org-mode-map [menu-bar headings] 'undefined)
5574 (define-key org-mode-map [menu-bar hide] 'undefined)
5575 (define-key org-mode-map [menu-bar show] 'undefined)
5577 (org-load-modules-maybe)
5578 (org-install-agenda-files-menu)
5579 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5580 (add-to-invisibility-spec '(org-cwidth))
5581 (add-to-invisibility-spec '(org-hide-block . t))
5582 (setq-local outline-regexp org-outline-regexp)
5583 (setq-local outline-level 'org-outline-level)
5584 (setq bidi-paragraph-direction 'left-to-right)
5585 (when (and org-ellipsis
5586 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5587 (fboundp 'make-glyph-code))
5588 (unless org-display-table
5589 (setq org-display-table (make-display-table)))
5590 (set-display-table-slot
5591 org-display-table 4
5592 (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
5593 (if (stringp org-ellipsis) org-ellipsis "..."))))
5594 (setq buffer-display-table org-display-table))
5595 (org-set-regexps-and-options)
5596 (org-set-font-lock-defaults)
5597 (when (and org-tag-faces (not org-tags-special-faces-re))
5598 ;; tag faces set outside customize.... force initialization.
5599 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5600 ;; Calc embedded
5601 (setq-local calc-embedded-open-mode "# ")
5602 ;; Modify a few syntax entries
5603 (modify-syntax-entry ?@ "w")
5604 (modify-syntax-entry ?\" "\"")
5605 (modify-syntax-entry ?\\ "_")
5606 (modify-syntax-entry ?~ "_")
5607 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5608 ;; Activate before-change-function
5609 (setq-local org-table-may-need-update t)
5610 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5611 ;; Check for running clock before killing a buffer
5612 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5613 ;; Initialize macros templates.
5614 (org-macro-initialize-templates)
5615 ;; Initialize radio targets.
5616 (org-update-radio-target-regexp)
5617 ;; Indentation.
5618 (setq-local indent-line-function 'org-indent-line)
5619 (setq-local indent-region-function 'org-indent-region)
5620 ;; Filling and auto-filling.
5621 (org-setup-filling)
5622 ;; Comments.
5623 (org-setup-comments-handling)
5624 ;; Initialize cache.
5625 (org-element-cache-reset)
5626 ;; Beginning/end of defun
5627 (setq-local beginning-of-defun-function 'org-backward-element)
5628 (setq-local end-of-defun-function
5629 (lambda ()
5630 (if (not (org-at-heading-p))
5631 (org-forward-element)
5632 (org-forward-element)
5633 (forward-char -1))))
5634 ;; Next error for sparse trees
5635 (setq-local next-error-function 'org-occur-next-match)
5636 ;; Make sure dependence stuff works reliably, even for users who set it
5637 ;; too late :-(
5638 (if org-enforce-todo-dependencies
5639 (add-hook 'org-blocker-hook
5640 'org-block-todo-from-children-or-siblings-or-parent)
5641 (remove-hook 'org-blocker-hook
5642 'org-block-todo-from-children-or-siblings-or-parent))
5643 (if org-enforce-todo-checkbox-dependencies
5644 (add-hook 'org-blocker-hook
5645 'org-block-todo-from-checkboxes)
5646 (remove-hook 'org-blocker-hook
5647 'org-block-todo-from-checkboxes))
5649 ;; Align options lines
5650 (setq-local
5651 align-mode-rules-list
5652 '((org-in-buffer-settings
5653 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5654 (modes . '(org-mode)))))
5656 ;; Imenu
5657 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5659 ;; Make isearch reveal context
5660 (setq-local outline-isearch-open-invisible-function
5661 (lambda (&rest _) (org-show-context 'isearch)))
5663 ;; Setup the pcomplete hooks
5664 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5665 (setq-local pcomplete-command-name-function 'org-command-at-point)
5666 (setq-local pcomplete-default-completion-function 'ignore)
5667 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5668 (setq-local pcomplete-termination-string "")
5669 (setq-local buffer-face-mode-face 'org-default)
5671 ;; If empty file that did not turn on Org mode automatically, make
5672 ;; it to.
5673 (when (and org-insert-mode-line-in-empty-file
5674 (called-interactively-p 'any)
5675 (= (point-min) (point-max)))
5676 (insert "# -*- mode: org -*-\n\n"))
5677 (unless org-inhibit-startup
5678 (org-unmodified
5679 (when org-startup-with-beamer-mode (org-beamer-mode))
5680 (when org-startup-align-all-tables
5681 (org-table-map-tables #'org-table-align t))
5682 (when org-startup-with-inline-images (org-display-inline-images))
5683 (when org-startup-with-latex-preview (org-toggle-latex-fragment '(16)))
5684 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5685 (when org-startup-truncated (setq truncate-lines t))
5686 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5687 (org-refresh-effort-properties)))
5688 ;; Try to set `org-hide' face correctly.
5689 (let ((foreground (org-find-invisible-foreground)))
5690 (when foreground
5691 (set-face-foreground 'org-hide foreground))))
5693 ;; Update `customize-package-emacs-version-alist'
5694 (add-to-list 'customize-package-emacs-version-alist
5695 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5696 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5697 ("8.2.6" . "24.4") ("8.2.10" . "24.5")
5698 ("9.0" . "26.1")))
5700 (defvar org-mode-transpose-word-syntax-table
5701 (let ((st (make-syntax-table text-mode-syntax-table)))
5702 (dolist (c org-emphasis-alist st)
5703 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5705 (when (fboundp 'abbrev-table-put)
5706 (abbrev-table-put org-mode-abbrev-table
5707 :parents (list text-mode-abbrev-table)))
5709 (defun org-find-invisible-foreground ()
5710 (let ((candidates (remove
5711 "unspecified-bg"
5712 (nconc
5713 (list (face-background 'default)
5714 (face-background 'org-default))
5715 (mapcar
5716 (lambda (alist)
5717 (when (boundp alist)
5718 (cdr (assq 'background-color (symbol-value alist)))))
5719 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5720 (list (face-foreground 'org-hide))))))
5721 (car (remove nil candidates))))
5723 (defun org-current-time (&optional rounding-minutes past)
5724 "Current time, possibly rounded to ROUNDING-MINUTES.
5725 When ROUNDING-MINUTES is not an integer, fall back on the car of
5726 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5727 the rounding returns a past time."
5728 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5729 (car org-time-stamp-rounding-minutes)))
5730 (time (decode-time)) res)
5731 (if (< r 1)
5732 (current-time)
5733 (setq res
5734 (apply 'encode-time
5735 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5736 (nthcdr 2 time))))
5737 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5738 (seconds-to-time (- (float-time res) (* r 60)))
5739 res))))
5741 (defun org-today ()
5742 "Return today date, considering `org-extend-today-until'."
5743 (time-to-days
5744 (time-subtract (current-time)
5745 (list 0 (* 3600 org-extend-today-until) 0))))
5747 ;;;; Font-Lock stuff, including the activators
5749 (defvar org-mouse-map (make-sparse-keymap))
5750 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5751 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5752 (when org-mouse-1-follows-link
5753 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5754 (when org-tab-follows-link
5755 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5756 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5758 (require 'font-lock)
5760 (defconst org-non-link-chars "]\t\n\r<>")
5761 (defvar org-link-types-re nil
5762 "Matches a link that has a url-like prefix like \"http:\"")
5763 (defvar org-link-re-with-space nil
5764 "Matches a link with spaces, optional angular brackets around it.")
5765 (defvar org-link-re-with-space2 nil
5766 "Matches a link with spaces, optional angular brackets around it.")
5767 (defvar org-link-re-with-space3 nil
5768 "Matches a link with spaces, only for internal part in bracket links.")
5769 (defvar org-angle-link-re nil
5770 "Matches link with angular brackets, spaces are allowed.")
5771 (defvar org-plain-link-re nil
5772 "Matches plain link, without spaces.")
5773 (defvar org-bracket-link-regexp nil
5774 "Matches a link in double brackets.")
5775 (defvar org-bracket-link-analytic-regexp nil
5776 "Regular expression used to analyze links.
5777 Here is what the match groups contain after a match:
5778 1: http:
5779 2: http
5780 3: path
5781 4: [desc]
5782 5: desc")
5783 (defvar org-bracket-link-analytic-regexp++ nil
5784 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5785 (defvar org-any-link-re nil
5786 "Regular expression matching any link.")
5788 (defconst org-match-sexp-depth 3
5789 "Number of stacked braces for sub/superscript matching.")
5791 (defun org-create-multibrace-regexp (left right n)
5792 "Create a regular expression which will match a balanced sexp.
5793 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5794 as single character strings.
5795 The regexp returned will match the entire expression including the
5796 delimiters. It will also define a single group which contains the
5797 match except for the outermost delimiters. The maximum depth of
5798 stacked delimiters is N. Escaping delimiters is not possible."
5799 (let* ((nothing (concat "[^" left right "]*?"))
5800 (or "\\|")
5801 (re nothing)
5802 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5803 (while (> n 1)
5804 (setq n (1- n)
5805 re (concat re or next)
5806 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5807 (concat left "\\(" re "\\)" right)))
5809 (defconst org-match-substring-regexp
5810 (concat
5811 "\\(\\S-\\)\\([_^]\\)\\("
5812 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5813 "\\|"
5814 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5815 "\\|"
5816 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5817 "The regular expression matching a sub- or superscript.")
5819 (defconst org-match-substring-with-braces-regexp
5820 (concat
5821 "\\(\\S-\\)\\([_^]\\)"
5822 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5823 "The regular expression matching a sub- or superscript, forcing braces.")
5825 (defun org-make-link-regexps ()
5826 "Update the link regular expressions.
5827 This should be called after the variable `org-link-parameters' has changed."
5828 (let ((types-re (regexp-opt (org-link-types) t)))
5829 (setq org-link-types-re
5830 (concat "\\`" types-re ":")
5831 org-link-re-with-space
5832 (concat "<?" types-re ":"
5833 "\\([^" org-non-link-chars " ]"
5834 "[^" org-non-link-chars "]*"
5835 "[^" org-non-link-chars " ]\\)>?")
5836 org-link-re-with-space2
5837 (concat "<?" types-re ":"
5838 "\\([^" org-non-link-chars " ]"
5839 "[^\t\n\r]*"
5840 "[^" org-non-link-chars " ]\\)>?")
5841 org-link-re-with-space3
5842 (concat "<?" types-re ":"
5843 "\\([^" org-non-link-chars " ]"
5844 "[^\t\n\r]*\\)")
5845 org-angle-link-re
5846 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5847 types-re)
5848 org-plain-link-re
5849 (concat
5850 "\\<" types-re ":"
5851 "\\([^][ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5852 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5853 org-bracket-link-regexp
5854 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5855 org-bracket-link-analytic-regexp
5856 (concat
5857 "\\[\\["
5858 "\\(" types-re ":\\)?"
5859 "\\([^]]+\\)"
5860 "\\]"
5861 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5862 "\\]")
5863 org-bracket-link-analytic-regexp++
5864 (concat
5865 "\\[\\["
5866 "\\(" (regexp-opt (cons "coderef" (org-link-types)) t) ":\\)?"
5867 "\\([^]]+\\)"
5868 "\\]"
5869 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5870 "\\]")
5871 org-any-link-re
5872 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5873 org-angle-link-re "\\)\\|\\("
5874 org-plain-link-re "\\)"))))
5876 (org-make-link-regexps)
5878 (defvar org-emph-face nil)
5880 (defun org-do-emphasis-faces (limit)
5881 "Run through the buffer and emphasize strings."
5882 (let (rtn a)
5883 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5884 (let* ((border (char-after (match-beginning 3)))
5885 (bre (regexp-quote (char-to-string border))))
5886 (when (and (not (= border (char-after (match-beginning 4))))
5887 (not (string-match-p (concat bre ".*" bre)
5888 (replace-regexp-in-string
5889 "\n" " "
5890 (substring (match-string 2) 1 -1)))))
5891 (setq rtn t)
5892 (setq a (assoc (match-string 3) org-emphasis-alist))
5893 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5894 'face
5895 (nth 1 a))
5896 (and (nth 2 a)
5897 (org-remove-flyspell-overlays-in
5898 (match-beginning 0) (match-end 0)))
5899 (add-text-properties (match-beginning 2) (match-end 2)
5900 '(font-lock-multiline t org-emphasis t))
5901 (when org-hide-emphasis-markers
5902 (add-text-properties (match-end 4) (match-beginning 5)
5903 '(invisible org-link))
5904 (add-text-properties (match-beginning 3) (match-end 3)
5905 '(invisible org-link)))))
5906 (goto-char (1+ (match-beginning 0))))
5907 rtn))
5909 (defun org-emphasize (&optional char)
5910 "Insert or change an emphasis, i.e. a font like bold or italic.
5911 If there is an active region, change that region to a new emphasis.
5912 If there is no region, just insert the marker characters and position
5913 the cursor between them.
5914 CHAR should be the marker character. If it is a space, it means to
5915 remove the emphasis of the selected region.
5916 If CHAR is not given (for example in an interactive call) it will be
5917 prompted for."
5918 (interactive)
5919 (let ((erc org-emphasis-regexp-components)
5920 (string "") beg end move s)
5921 (if (org-region-active-p)
5922 (setq beg (region-beginning)
5923 end (region-end)
5924 string (buffer-substring beg end))
5925 (setq move t))
5927 (unless char
5928 (message "Emphasis marker or tag: [%s]"
5929 (mapconcat #'car org-emphasis-alist ""))
5930 (setq char (read-char-exclusive)))
5931 (if (equal char ?\s)
5932 (setq s ""
5933 move nil)
5934 (unless (assoc (char-to-string char) org-emphasis-alist)
5935 (user-error "No such emphasis marker: \"%c\"" char))
5936 (setq s (char-to-string char)))
5937 (while (and (> (length string) 1)
5938 (equal (substring string 0 1) (substring string -1))
5939 (assoc (substring string 0 1) org-emphasis-alist))
5940 (setq string (substring string 1 -1)))
5941 (setq string (concat s string s))
5942 (when beg (delete-region beg end))
5943 (unless (or (bolp)
5944 (string-match (concat "[" (nth 0 erc) "\n]")
5945 (char-to-string (char-before (point)))))
5946 (insert " "))
5947 (unless (or (eobp)
5948 (string-match (concat "[" (nth 1 erc) "\n]")
5949 (char-to-string (char-after (point)))))
5950 (insert " ") (backward-char 1))
5951 (insert string)
5952 (and move (backward-char 1))))
5954 (defconst org-nonsticky-props
5955 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5957 (defsubst org-rear-nonsticky-at (pos)
5958 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5960 (defun org-activate-links (limit)
5961 "Add link properties to links.
5962 This includes angle, plain, and bracket links."
5963 (catch :exit
5964 (while (re-search-forward org-any-link-re limit t)
5965 (let* ((start (match-beginning 0))
5966 (end (match-end 0))
5967 (style (cond ((eq ?< (char-after start)) 'angle)
5968 ((eq ?\[ (char-after (1+ start))) 'bracket)
5969 (t 'plain))))
5970 (when (and (memq style org-highlight-links)
5971 ;; Do not confuse plain links with tags.
5972 (not (and (eq style 'plain)
5973 (let ((face (get-text-property
5974 (max (1- start) (point-min)) 'face)))
5975 (if (consp face) (memq 'org-tag face)
5976 (eq 'org-tag face))))))
5977 (let* ((link-object (save-excursion
5978 (goto-char start)
5979 (save-match-data (org-element-link-parser))))
5980 (link (org-element-property :raw-link link-object))
5981 (type (org-element-property :type link-object))
5982 (path (org-element-property :path link-object))
5983 (properties ;for link's visible part
5984 (list
5985 'face (pcase (org-link-get-parameter type :face)
5986 ((and (pred functionp) face) (funcall face path))
5987 ((and (pred facep) face) face)
5988 ((and (pred consp) face) face) ;anonymous
5989 (_ 'org-link))
5990 'mouse-face (or (org-link-get-parameter type :mouse-face)
5991 'highlight)
5992 'keymap (or (org-link-get-parameter type :keymap)
5993 org-mouse-map)
5994 'help-echo (pcase (org-link-get-parameter type :help-echo)
5995 ((and (pred stringp) echo) echo)
5996 ((and (pred functionp) echo) echo)
5997 (_ (concat "LINK: " link)))
5998 'htmlize-link (pcase (org-link-get-parameter type
5999 :htmlize-link)
6000 ((and (pred functionp) f) (funcall f))
6001 (_ `(:uri ,link)))
6002 'font-lock-multiline t)))
6003 (org-remove-flyspell-overlays-in start end)
6004 (org-rear-nonsticky-at end)
6005 (if (not (eq 'bracket style))
6006 (add-text-properties start end properties)
6007 ;; Handle invisible parts in bracket links.
6008 (remove-text-properties start end '(invisible nil))
6009 (let ((hidden
6010 (append `(invisible
6011 ,(or (org-link-get-parameter type :display)
6012 'org-link))
6013 properties))
6014 (visible-start (or (match-beginning 4) (match-beginning 2)))
6015 (visible-end (or (match-end 4) (match-end 2))))
6016 (add-text-properties start visible-start hidden)
6017 (add-text-properties visible-start visible-end properties)
6018 (add-text-properties visible-end end hidden)
6019 (org-rear-nonsticky-at visible-start)
6020 (org-rear-nonsticky-at visible-end)))
6021 (let ((f (org-link-get-parameter type :activate-func)))
6022 (when (functionp f)
6023 (funcall f start end path (eq style 'bracket))))
6024 (throw :exit t))))) ;signal success
6025 nil))
6027 (defun org-activate-code (limit)
6028 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
6029 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6030 (remove-text-properties (match-beginning 0) (match-end 0)
6031 '(display t invisible t intangible t))
6034 (defcustom org-src-fontify-natively t
6035 "When non-nil, fontify code in code blocks.
6036 See also the `org-block' face."
6037 :type 'boolean
6038 :version "24.4"
6039 :package-version '(Org . "8.3")
6040 :group 'org-appearance
6041 :group 'org-babel)
6043 (defcustom org-allow-promoting-top-level-subtree nil
6044 "When non-nil, allow promoting a top level subtree.
6045 The leading star of the top level headline will be replaced
6046 by a #."
6047 :type 'boolean
6048 :version "24.1"
6049 :group 'org-appearance)
6051 (defun org-fontify-meta-lines-and-blocks (limit)
6052 (condition-case nil
6053 (org-fontify-meta-lines-and-blocks-1 limit)
6054 (error (message "org-mode fontification error in %S at %d"
6055 (current-buffer)
6056 (line-number-at-pos)))))
6058 (defun org-fontify-meta-lines-and-blocks-1 (limit)
6059 "Fontify #+ lines and blocks."
6060 (let ((case-fold-search t))
6061 (when (re-search-forward
6062 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
6063 limit t)
6064 (let ((beg (match-beginning 0))
6065 (block-start (match-end 0))
6066 (block-end nil)
6067 (lang (match-string 7))
6068 (beg1 (line-beginning-position 2))
6069 (dc1 (downcase (match-string 2)))
6070 (dc3 (downcase (match-string 3)))
6071 end end1 quoting block-type)
6072 (cond
6073 ((and (match-end 4) (equal dc3 "+begin"))
6074 ;; Truly a block
6075 (setq block-type (downcase (match-string 5))
6076 quoting (member block-type org-protecting-blocks))
6077 (when (re-search-forward
6078 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
6079 nil t) ;; on purpose, we look further than LIMIT
6080 (setq end (min (point-max) (match-end 0))
6081 end1 (min (point-max) (1- (match-beginning 0))))
6082 (setq block-end (match-beginning 0))
6083 (when quoting
6084 (org-remove-flyspell-overlays-in beg1 end1)
6085 (remove-text-properties beg end
6086 '(display t invisible t intangible t)))
6087 (add-text-properties
6088 beg end '(font-lock-fontified t font-lock-multiline t))
6089 (add-text-properties beg beg1 '(face org-meta-line))
6090 (org-remove-flyspell-overlays-in beg beg1)
6091 (add-text-properties ; For end_src
6092 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6093 (org-remove-flyspell-overlays-in end1 end)
6094 (cond
6095 ((and lang (not (string= lang "")) org-src-fontify-natively)
6096 (org-src-font-lock-fontify-block lang block-start block-end)
6097 (add-text-properties beg1 block-end '(src-block t)))
6098 (quoting
6099 (add-text-properties beg1 (min (point-max) (1+ end1))
6100 (list 'face
6101 (list :inherit
6102 (let ((face-name
6103 (intern (format "org-block-%s" lang))))
6104 (append (and (facep face-name) (list face-name))
6105 '(org-block))))))) ; end of source block
6106 ((not org-fontify-quote-and-verse-blocks))
6107 ((string= block-type "quote")
6108 (add-face-text-property
6109 beg1 (min (point-max) (1+ end1)) 'org-quote t))
6110 ((string= block-type "verse")
6111 (add-face-text-property
6112 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
6113 (add-text-properties beg beg1 '(face org-block-begin-line))
6114 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6115 '(face org-block-end-line))
6117 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6118 (org-remove-flyspell-overlays-in
6119 (match-beginning 0)
6120 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6121 (add-text-properties
6122 beg (match-end 3)
6123 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6124 '(font-lock-fontified t invisible t)
6125 '(font-lock-fontified t face org-document-info-keyword)))
6126 (add-text-properties
6127 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6128 (if (string-equal dc1 "+title:")
6129 '(font-lock-fontified t face org-document-title)
6130 '(font-lock-fontified t face org-document-info))))
6131 ((string-prefix-p "+caption" dc1)
6132 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6133 (remove-text-properties (match-beginning 0) (match-end 0)
6134 '(display t invisible t intangible t))
6135 ;; Handle short captions.
6136 (save-excursion
6137 (beginning-of-line)
6138 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6139 (add-text-properties (line-beginning-position) (match-end 1)
6140 '(font-lock-fontified t face org-meta-line))
6141 (add-text-properties (match-end 0) (line-end-position)
6142 '(font-lock-fontified t face org-block))
6144 ((member dc3 '(" " ""))
6145 (org-remove-flyspell-overlays-in beg (match-end 0))
6146 (add-text-properties
6147 beg (match-end 0)
6148 '(font-lock-fontified t face font-lock-comment-face)))
6149 (t ;; just any other in-buffer setting, but not indented
6150 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6151 (remove-text-properties (match-beginning 0) (match-end 0)
6152 '(display t invisible t intangible t))
6153 (add-text-properties beg (match-end 0)
6154 '(font-lock-fontified t face org-meta-line))
6155 t))))))
6157 (defun org-fontify-drawers (limit)
6158 "Fontify drawers."
6159 (when (re-search-forward org-drawer-regexp limit t)
6160 (add-text-properties
6161 (match-beginning 0) (match-end 0)
6162 '(font-lock-fontified t face org-special-keyword))
6163 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6166 (defun org-fontify-macros (limit)
6167 "Fontify macros."
6168 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6169 (add-text-properties
6170 (match-beginning 0) (match-end 0)
6171 '(font-lock-fontified t face org-macro))
6172 (when org-hide-macro-markers
6173 (add-text-properties (match-end 2) (match-beginning 2)
6174 '(invisible t))
6175 (add-text-properties (match-beginning 1) (match-end 1)
6176 '(invisible t)))
6177 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6180 (defun org-activate-footnote-links (limit)
6181 "Add text properties for footnotes."
6182 (let ((fn (org-footnote-next-reference-or-definition limit)))
6183 (when fn
6184 (let* ((beg (nth 1 fn))
6185 (end (nth 2 fn))
6186 (label (car fn))
6187 (referencep (/= (line-beginning-position) beg)))
6188 (when (and referencep (nth 3 fn))
6189 (save-excursion
6190 (goto-char beg)
6191 (search-forward (or label "fn:"))
6192 (org-remove-flyspell-overlays-in beg (match-end 0))))
6193 (add-text-properties beg end
6194 (list 'mouse-face 'highlight
6195 'keymap org-mouse-map
6196 'help-echo
6197 (if referencep "Footnote reference"
6198 "Footnote definition")
6199 'font-lock-fontified t
6200 'font-lock-multiline t
6201 'face 'org-footnote))))))
6203 (defun org-activate-dates (limit)
6204 "Add text properties for dates."
6205 (when (and (re-search-forward org-tsr-regexp-both limit t)
6206 (not (equal (char-before (match-beginning 0)) 91)))
6207 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6208 (add-text-properties (match-beginning 0) (match-end 0)
6209 (list 'mouse-face 'highlight
6210 'keymap org-mouse-map))
6211 (org-rear-nonsticky-at (match-end 0))
6212 (when org-display-custom-times
6213 (if (match-end 3)
6214 (org-display-custom-time (match-beginning 3) (match-end 3))
6215 (org-display-custom-time (match-beginning 1) (match-end 1))))
6218 (defvar-local org-target-link-regexp nil
6219 "Regular expression matching radio targets in plain text.")
6221 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6222 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6223 border border border))
6224 "Regular expression matching a link target.")
6226 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6227 "Regular expression matching a radio target.")
6229 (defconst org-any-target-regexp
6230 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6231 "Regular expression matching any target.")
6233 (defun org-activate-target-links (limit)
6234 "Add text properties for target matches."
6235 (when org-target-link-regexp
6236 (let ((case-fold-search t))
6237 (when (re-search-forward org-target-link-regexp limit t)
6238 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6239 (add-text-properties (match-beginning 1) (match-end 1)
6240 (list 'mouse-face 'highlight
6241 'keymap org-mouse-map
6242 'help-echo "Radio target link"
6243 'org-linked-text t))
6244 (org-rear-nonsticky-at (match-end 1))
6245 t))))
6247 (defun org-update-radio-target-regexp ()
6248 "Find all radio targets in this file and update the regular expression.
6249 Also refresh fontification if needed."
6250 (interactive)
6251 (let ((old-regexp org-target-link-regexp)
6252 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6253 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6254 (targets
6255 (org-with-wide-buffer
6256 (goto-char (point-min))
6257 (let (rtn)
6258 (while (re-search-forward org-radio-target-regexp nil t)
6259 ;; Make sure point is really within the object.
6260 (backward-char)
6261 (let ((obj (org-element-context)))
6262 (when (eq (org-element-type obj) 'radio-target)
6263 (cl-pushnew (org-element-property :value obj) rtn
6264 :test #'equal))))
6265 rtn))))
6266 (setq org-target-link-regexp
6267 (and targets
6268 (concat before-re
6269 (mapconcat
6270 (lambda (x)
6271 (replace-regexp-in-string
6272 " +" "\\s-+" (regexp-quote x) t t))
6273 targets
6274 "\\|")
6275 after-re)))
6276 (unless (equal old-regexp org-target-link-regexp)
6277 ;; Clean-up cache.
6278 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6279 ((not org-target-link-regexp) old-regexp)
6281 (concat before-re
6282 (mapconcat
6283 (lambda (re)
6284 (substring re (length before-re)
6285 (- (length after-re))))
6286 (list old-regexp org-target-link-regexp)
6287 "\\|")
6288 after-re)))))
6289 (org-with-wide-buffer
6290 (goto-char (point-min))
6291 (while (re-search-forward regexp nil t)
6292 (org-element-cache-refresh (match-beginning 1)))))
6293 ;; Re fontify buffer.
6294 (when (memq 'radio org-highlight-links)
6295 (org-restart-font-lock)))))
6297 (defun org-hide-wide-columns (limit)
6298 (let (s e)
6299 (setq s (text-property-any (point) (or limit (point-max))
6300 'org-cwidth t))
6301 (when s
6302 (setq e (next-single-property-change s 'org-cwidth))
6303 (add-text-properties s e '(invisible org-cwidth))
6304 (goto-char e)
6305 t)))
6307 (defvar org-latex-and-related-regexp nil
6308 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6310 (defun org-compute-latex-and-related-regexp ()
6311 "Compute regular expression for LaTeX, entities and sub/superscript.
6312 Result depends on variable `org-highlight-latex-and-related'."
6313 (setq-local
6314 org-latex-and-related-regexp
6315 (let* ((re-sub
6316 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6317 ((eq org-use-sub-superscripts '{})
6318 (list org-match-substring-with-braces-regexp))
6319 (org-use-sub-superscripts (list org-match-substring-regexp))))
6320 (re-latex
6321 (when (memq 'latex org-highlight-latex-and-related)
6322 (let ((matchers (plist-get org-format-latex-options :matchers)))
6323 (delq nil
6324 (mapcar (lambda (x)
6325 (and (member (car x) matchers) (nth 1 x)))
6326 org-latex-regexps)))))
6327 (re-entities
6328 (when (memq 'entities org-highlight-latex-and-related)
6329 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6330 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6332 (defun org-do-latex-and-related (limit)
6333 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6334 LIMIT bounds the search for syntax to highlight. Stop at first
6335 highlighted object, if any. Return t if some highlighting was
6336 done, nil otherwise."
6337 (when (org-string-nw-p org-latex-and-related-regexp)
6338 (catch 'found
6339 (while (re-search-forward org-latex-and-related-regexp limit t)
6340 (unless
6341 (cl-some
6342 (lambda (f)
6343 (memq f '(org-code org-verbatim underline org-special-keyword)))
6344 (save-excursion
6345 (goto-char (1+ (match-beginning 0)))
6346 (face-at-point nil t)))
6347 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6348 '(?_ ?^))
6350 0)))
6351 (font-lock-prepend-text-property
6352 (+ offset (match-beginning 0)) (match-end 0)
6353 'face 'org-latex-and-related)
6354 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6355 '(font-lock-multiline t)))
6356 (throw 'found t)))
6357 nil)))
6359 (defun org-restart-font-lock ()
6360 "Restart `font-lock-mode', to force refontification."
6361 (when (and (boundp 'font-lock-mode) font-lock-mode)
6362 (font-lock-mode -1)
6363 (font-lock-mode 1)))
6365 (defun org-activate-tags (limit)
6366 (when (re-search-forward
6367 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6368 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6369 (add-text-properties (match-beginning 1) (match-end 1)
6370 (list 'mouse-face 'highlight
6371 'keymap org-mouse-map))
6372 (org-rear-nonsticky-at (match-end 1))
6375 (defun org-outline-level ()
6376 "Compute the outline level of the heading at point.
6378 If this is called at a normal headline, the level is the number
6379 of stars. Use `org-reduced-level' to remove the effect of
6380 `org-odd-levels'. Unlike to `org-current-level', this function
6381 takes into consideration inlinetasks."
6382 (org-with-wide-buffer
6383 (end-of-line)
6384 (if (re-search-backward org-outline-regexp-bol nil t)
6385 (1- (- (match-end 0) (match-beginning 0)))
6386 0)))
6388 (defvar org-font-lock-keywords nil)
6390 (defsubst org-re-property (property &optional literal allow-null value)
6391 "Return a regexp matching a PROPERTY line.
6393 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6394 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6395 non-nil, match properties even without a value.
6397 Match group 3 is set to the value when it exists. If there is no
6398 value and ALLOW-NULL is non-nil, it is set to the empty string.
6400 With optional argument VALUE, match only property lines with
6401 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6402 unless LITERAL is non-nil."
6403 (concat
6404 "^\\(?4:[ \t]*\\)"
6405 (format "\\(?1::\\(?2:%s\\):\\)"
6406 (if literal property (regexp-quote property)))
6407 (cond (value
6408 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6409 (if literal value (regexp-quote value))))
6410 (allow-null
6411 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6413 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6415 (defconst org-property-re
6416 (org-re-property "\\S-+" 'literal t)
6417 "Regular expression matching a property line.
6418 There are four matching groups:
6419 1: :PROPKEY: including the leading and trailing colon,
6420 2: PROPKEY without the leading and trailing colon,
6421 3: PROPVAL without leading or trailing spaces,
6422 4: the indentation of the current line,
6423 5: trailing whitespace.")
6425 (defvar org-font-lock-hook nil
6426 "Functions to be called for special font lock stuff.")
6428 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6430 (defvar org-font-lock-set-keywords-hook nil
6431 "Functions that can manipulate `org-font-lock-extra-keywords'.
6432 This is called after `org-font-lock-extra-keywords' is defined, but before
6433 it is installed to be used by font lock. This can be useful if something
6434 needs to be inserted at a specific position in the font-lock sequence.")
6436 (defun org-font-lock-hook (limit)
6437 "Run `org-font-lock-hook' within LIMIT."
6438 (run-hook-with-args 'org-font-lock-hook limit))
6440 (defun org-set-font-lock-defaults ()
6441 "Set font lock defaults for the current buffer."
6442 (let* ((em org-fontify-emphasized-text)
6443 (lk org-highlight-links)
6444 (org-font-lock-extra-keywords
6445 (list
6446 ;; Call the hook
6447 '(org-font-lock-hook)
6448 ;; Headlines
6449 `(,(if org-fontify-whole-heading-line
6450 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6451 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6452 (1 (org-get-level-face 1))
6453 (2 (org-get-level-face 2))
6454 (3 (org-get-level-face 3)))
6455 ;; Table lines
6456 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6457 (1 'org-table t))
6458 ;; Table internals
6459 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6460 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6461 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6462 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6463 ;; Drawers
6464 '(org-fontify-drawers)
6465 ;; Properties
6466 (list org-property-re
6467 '(1 'org-special-keyword t)
6468 '(3 'org-property-value t))
6469 ;; Link related fontification.
6470 '(org-activate-links)
6471 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6472 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6473 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6474 (when (memq 'footnote lk) '(org-activate-footnote-links))
6475 ;; Targets.
6476 (list org-any-target-regexp '(0 'org-target t))
6477 ;; Diary sexps.
6478 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6479 ;; Macro
6480 '(org-fontify-macros)
6481 '(org-hide-wide-columns (0 nil append))
6482 ;; TODO keyword
6483 (list (format org-heading-keyword-regexp-format
6484 org-todo-regexp)
6485 '(2 (org-get-todo-face 2) t))
6486 ;; DONE
6487 (if org-fontify-done-headline
6488 (list (format org-heading-keyword-regexp-format
6489 (concat
6490 "\\(?:"
6491 (mapconcat 'regexp-quote org-done-keywords "\\|")
6492 "\\)"))
6493 '(2 'org-headline-done t))
6494 nil)
6495 ;; Priorities
6496 '(org-font-lock-add-priority-faces)
6497 ;; Tags
6498 '(org-font-lock-add-tag-faces)
6499 ;; Tags groups
6500 (when (and org-group-tags org-tag-groups-alist)
6501 (list (concat org-outline-regexp-bol ".+\\(:"
6502 (regexp-opt (mapcar 'car org-tag-groups-alist))
6503 ":\\).*$")
6504 '(1 'org-tag-group prepend)))
6505 ;; Special keywords
6506 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6507 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6508 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6509 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6510 ;; Emphasis
6511 (when em '(org-do-emphasis-faces))
6512 ;; Checkboxes
6513 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6514 1 'org-checkbox prepend)
6515 (when (cdr (assq 'checkbox org-list-automatic-rules))
6516 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6517 (0 (org-get-checkbox-statistics-face) t)))
6518 ;; Description list items
6519 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6520 1 'org-list-dt prepend)
6521 ;; ARCHIVEd headings
6522 (list (concat
6523 org-outline-regexp-bol
6524 "\\(.*:" org-archive-tag ":.*\\)")
6525 '(1 'org-archived prepend))
6526 ;; Specials
6527 '(org-do-latex-and-related)
6528 '(org-fontify-entities)
6529 '(org-raise-scripts)
6530 ;; Code
6531 '(org-activate-code (1 'org-code t))
6532 ;; COMMENT
6533 (list (format
6534 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6535 org-todo-regexp
6536 org-comment-string)
6537 '(9 'org-special-keyword t))
6538 ;; Blocks and meta lines
6539 '(org-fontify-meta-lines-and-blocks))))
6540 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6541 (run-hooks 'org-font-lock-set-keywords-hook)
6542 ;; Now set the full font-lock-keywords
6543 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6544 (setq-local font-lock-defaults
6545 '(org-font-lock-keywords t nil nil backward-paragraph))
6546 (kill-local-variable 'font-lock-keywords)
6547 nil))
6549 (defun org-toggle-pretty-entities ()
6550 "Toggle the composition display of entities as UTF8 characters."
6551 (interactive)
6552 (setq-local org-pretty-entities (not org-pretty-entities))
6553 (org-restart-font-lock)
6554 (if org-pretty-entities
6555 (message "Entities are now displayed as UTF8 characters")
6556 (save-restriction
6557 (widen)
6558 (decompose-region (point-min) (point-max))
6559 (message "Entities are now displayed as plain text"))))
6561 (defvar-local org-custom-properties-overlays nil
6562 "List of overlays used for custom properties.")
6564 (defun org-toggle-custom-properties-visibility ()
6565 "Display or hide properties in `org-custom-properties'."
6566 (interactive)
6567 (if org-custom-properties-overlays
6568 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6569 (setq org-custom-properties-overlays nil))
6570 (when org-custom-properties
6571 (org-with-wide-buffer
6572 (goto-char (point-min))
6573 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6574 (while (re-search-forward regexp nil t)
6575 (let ((end (cdr (save-match-data (org-get-property-block)))))
6576 (when (and end (< (point) end))
6577 ;; Hide first custom property in current drawer.
6578 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6579 (overlay-put o 'invisible t)
6580 (overlay-put o 'org-custom-property t)
6581 (push o org-custom-properties-overlays))
6582 ;; Hide additional custom properties in the same drawer.
6583 (while (re-search-forward regexp end t)
6584 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6585 (overlay-put o 'invisible t)
6586 (overlay-put o 'org-custom-property t)
6587 (push o org-custom-properties-overlays)))))
6588 ;; Each entry is limited to a single property drawer.
6589 (outline-next-heading)))))))
6591 (defun org-fontify-entities (limit)
6592 "Find an entity to fontify."
6593 (let (ee)
6594 (when org-pretty-entities
6595 (catch 'match
6596 ;; "\_ "-family is left out on purpose. Only the first one,
6597 ;; i.e., "\_ ", could be fontified anyway, and it would be
6598 ;; confusing when adding a second white space character.
6599 (while (re-search-forward
6600 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6601 limit t)
6602 (when (and (not (org-at-comment-p))
6603 (setq ee (org-entity-get (match-string 1)))
6604 (= (length (nth 6 ee)) 1))
6605 (let* ((end (if (equal (match-string 2) "{}")
6606 (match-end 2)
6607 (match-end 1))))
6608 (add-text-properties
6609 (match-beginning 0) end
6610 (list 'font-lock-fontified t))
6611 (compose-region (match-beginning 0) end
6612 (nth 6 ee) nil)
6613 (backward-char 1)
6614 (throw 'match t))))
6615 nil))))
6617 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6618 "Fontify string S like in Org mode."
6619 (with-temp-buffer
6620 (insert s)
6621 (let ((org-odd-levels-only odd-levels))
6622 (org-mode)
6623 (org-font-lock-ensure)
6624 (buffer-string))))
6626 (defvar org-m nil)
6627 (defvar org-l nil)
6628 (defvar org-f nil)
6629 (defun org-get-level-face (n)
6630 "Get the right face for match N in font-lock matching of headlines."
6631 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6632 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6633 (if org-cycle-level-faces
6634 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6635 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6636 (cond
6637 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6638 ((eq n 2) org-f)
6639 (t (unless org-level-color-stars-only org-f))))
6641 (defun org-face-from-face-or-color (context inherit face-or-color)
6642 "Create a face list that inherits INHERIT, but sets the foreground color.
6643 When FACE-OR-COLOR is not a string, just return it."
6644 (if (stringp face-or-color)
6645 (list :inherit inherit
6646 (cdr (assoc context org-faces-easy-properties))
6647 face-or-color)
6648 face-or-color))
6650 (defun org-get-todo-face (kwd)
6651 "Get the right face for a TODO keyword KWD.
6652 If KWD is a number, get the corresponding match group."
6653 (when (numberp kwd) (setq kwd (match-string kwd)))
6654 (or (org-face-from-face-or-color
6655 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6656 (and (member kwd org-done-keywords) 'org-done)
6657 'org-todo))
6659 (defun org-get-priority-face (priority)
6660 "Get the right face for PRIORITY.
6661 PRIORITY is a character."
6662 (or (org-face-from-face-or-color
6663 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6664 'org-priority))
6666 (defun org-get-tag-face (tag)
6667 "Get the right face for TAG.
6668 If TAG is a number, get the corresponding match group."
6669 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6670 (or (org-face-from-face-or-color
6671 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6672 'org-tag)))
6674 (defun org-font-lock-add-priority-faces (limit)
6675 "Add the special priority faces."
6676 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6677 (add-text-properties
6678 (match-beginning 1) (match-end 1)
6679 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6680 'font-lock-fontified t))))
6682 (defun org-font-lock-add-tag-faces (limit)
6683 "Add the special tag faces."
6684 (when (and org-tag-faces org-tags-special-faces-re)
6685 (while (re-search-forward org-tags-special-faces-re limit t)
6686 (add-text-properties (match-beginning 1) (match-end 1)
6687 (list 'face (org-get-tag-face 1)
6688 'font-lock-fontified t))
6689 (backward-char 1))))
6691 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6692 "Remove fontification and activation overlays from links."
6693 (font-lock-default-unfontify-region beg end)
6694 (let* ((buffer-undo-list t)
6695 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6696 (inhibit-modification-hooks t)
6697 deactivate-mark buffer-file-name buffer-file-truename)
6698 (decompose-region beg end)
6699 (remove-text-properties beg end
6700 '(mouse-face t keymap t org-linked-text t
6701 invisible t intangible t
6702 org-emphasis t))
6703 (org-remove-font-lock-display-properties beg end)))
6705 (defconst org-script-display '(((raise -0.3) (height 0.7))
6706 ((raise 0.3) (height 0.7))
6707 ((raise -0.5))
6708 ((raise 0.5)))
6709 "Display properties for showing superscripts and subscripts.")
6711 (defun org-remove-font-lock-display-properties (beg end)
6712 "Remove specific display properties that have been added by font lock.
6713 The will remove the raise properties that are used to show superscripts
6714 and subscripts."
6715 (let (next prop)
6716 (while (< beg end)
6717 (setq next (next-single-property-change beg 'display nil end)
6718 prop (get-text-property beg 'display))
6719 (when (member prop org-script-display)
6720 (put-text-property beg next 'display nil))
6721 (setq beg next))))
6723 (defun org-raise-scripts (limit)
6724 "Add raise properties to sub/superscripts."
6725 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6726 (re-search-forward
6727 (if (eq org-use-sub-superscripts t)
6728 org-match-substring-regexp
6729 org-match-substring-with-braces-regexp)
6730 limit t))
6731 (let* ((pos (point)) table-p comment-p
6732 (mpos (match-beginning 3))
6733 (emph-p (get-text-property mpos 'org-emphasis))
6734 (link-p (get-text-property mpos 'mouse-face))
6735 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6736 (goto-char (point-at-bol))
6737 (setq table-p (looking-at-p org-table-dataline-regexp)
6738 comment-p (looking-at-p "^[ \t]*#[ +]"))
6739 (goto-char pos)
6740 ;; Handle a_b^c
6741 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6742 (unless (or comment-p emph-p link-p keyw-p)
6743 (put-text-property (match-beginning 3) (match-end 0)
6744 'display
6745 (if (equal (char-after (match-beginning 2)) ?^)
6746 (nth (if table-p 3 1) org-script-display)
6747 (nth (if table-p 2 0) org-script-display)))
6748 (add-text-properties (match-beginning 2) (match-end 2)
6749 (list 'invisible t
6750 'org-dwidth t 'org-dwidth-n 1))
6751 (if (and (eq (char-after (match-beginning 3)) ?{)
6752 (eq (char-before (match-end 3)) ?}))
6753 (progn
6754 (add-text-properties
6755 (match-beginning 3) (1+ (match-beginning 3))
6756 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6757 (add-text-properties
6758 (1- (match-end 3)) (match-end 3)
6759 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6760 t)))
6762 ;;;; Visibility cycling, including org-goto and indirect buffer
6764 ;;; Cycling
6766 (defvar-local org-cycle-global-status nil)
6767 (put 'org-cycle-global-status 'org-state t)
6768 (defvar-local org-cycle-subtree-status nil)
6769 (put 'org-cycle-subtree-status 'org-state t)
6771 (defvar org-inlinetask-min-level)
6773 (defun org-unlogged-message (&rest args)
6774 "Display a message, but avoid logging it in the *Messages* buffer."
6775 (let ((message-log-max nil))
6776 (apply 'message args)))
6778 ;;;###autoload
6779 (defun org-cycle (&optional arg)
6780 "TAB-action and visibility cycling for Org mode.
6782 This is the command invoked in Org mode by the `TAB' key. Its main
6783 purpose is outline visibility cycling, but it also invokes other actions
6784 in special contexts.
6786 When this function is called with a `\\[universal-argument]' prefix, rotate \
6787 the entire
6788 buffer through 3 states (global cycling)
6789 1. OVERVIEW: Show only top-level headlines.
6790 2. CONTENTS: Show all headlines of all levels, but no body text.
6791 3. SHOW ALL: Show everything.
6793 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6794 switch to the startup visibility,
6795 determined by the variable `org-startup-folded', and by any VISIBILITY
6796 properties in the buffer.
6798 With a `\\[universal-argument] \\[universal-argument] \
6799 \\[universal-argument]' prefix argument, show the entire buffer, including
6800 any drawers.
6802 When inside a table, re-align the table and move to the next field.
6804 When point is at the beginning of a headline, rotate the subtree started
6805 by this line through 3 different states (local cycling)
6806 1. FOLDED: Only the main headline is shown.
6807 2. CHILDREN: The main headline and the direct children are shown.
6808 From this state, you can move to one of the children
6809 and zoom in further.
6810 3. SUBTREE: Show the entire subtree, including body text.
6811 If there is no subtree, switch directly from CHILDREN to FOLDED.
6813 When point is at the beginning of an empty headline and the variable
6814 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6815 of the headline by demoting and promoting it to likely levels. This
6816 speeds up creation document structure by pressing `TAB' once or several
6817 times right after creating a new headline.
6819 When there is a numeric prefix, go up to a heading with level ARG, do
6820 a `show-subtree' and return to the previous cursor position. If ARG
6821 is negative, go up that many levels.
6823 When point is not at the beginning of a headline, execute the global
6824 binding for `TAB', which is re-indenting the line. See the option
6825 `org-cycle-emulate-tab' for details.
6827 As a special case, if point is at the beginning of the buffer and there is
6828 no headline in line 1, this function will act as if called with prefix arg
6829 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6830 prefix arg, but only
6831 if the variable `org-cycle-global-at-bob' is t."
6832 (interactive "P")
6833 (org-load-modules-maybe)
6834 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6835 (and org-cycle-level-after-item/entry-creation
6836 (or (org-cycle-level)
6837 (org-cycle-item-indentation))))
6838 (let* ((limit-level
6839 (or org-cycle-max-level
6840 (and (boundp 'org-inlinetask-min-level)
6841 org-inlinetask-min-level
6842 (1- org-inlinetask-min-level))))
6843 (nstars (and limit-level
6844 (if org-odd-levels-only
6845 (and limit-level (1- (* limit-level 2)))
6846 limit-level)))
6847 (org-outline-regexp
6848 (if (not (derived-mode-p 'org-mode))
6849 outline-regexp
6850 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6851 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6852 (not (looking-at org-outline-regexp))))
6853 (org-cycle-hook
6854 (if bob-special
6855 (delq 'org-optimize-window-after-visibility-change
6856 (copy-sequence org-cycle-hook))
6857 org-cycle-hook))
6858 (pos (point)))
6860 (cond
6862 ((equal arg '(16))
6863 (setq last-command 'dummy)
6864 (org-set-startup-visibility)
6865 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6867 ((equal arg '(64))
6868 (outline-show-all)
6869 (org-unlogged-message "Entire buffer visible, including drawers"))
6871 ((equal arg '(4)) (org-cycle-internal-global))
6873 ;; Try hiding block at point.
6874 ((org-hide-block-toggle-maybe))
6876 ;; Try cdlatex TAB completion
6877 ((org-try-cdlatex-tab))
6879 ;; Table: enter it or move to the next field.
6880 ((org-at-table-p 'any)
6881 (if (org-at-table.el-p)
6882 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6883 Use `\\[org-edit-special]' to edit table.el tables"))
6884 (if arg (org-table-edit-field t)
6885 (org-table-justify-field-maybe)
6886 (call-interactively 'org-table-next-field))))
6888 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6890 ;; Global cycling: delegate to `org-cycle-internal-global'.
6891 (bob-special (org-cycle-internal-global))
6893 ;; Drawers: delegate to `org-flag-drawer'.
6894 ((save-excursion
6895 (beginning-of-line 1)
6896 (looking-at org-drawer-regexp))
6897 (org-flag-drawer ; toggle block visibility
6898 (not (get-char-property (match-end 0) 'invisible))))
6900 ;; Show-subtree, ARG levels up from here.
6901 ((integerp arg)
6902 (save-excursion
6903 (org-back-to-heading)
6904 (outline-up-heading (if (< arg 0) (- arg)
6905 (- (funcall outline-level) arg)))
6906 (org-show-subtree)))
6908 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6909 ((and (featurep 'org-inlinetask)
6910 (org-inlinetask-at-task-p)
6911 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6912 (org-inlinetask-toggle-visibility))
6914 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6915 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6916 (save-excursion (move-beginning-of-line 1)
6917 (looking-at org-outline-regexp)))
6918 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6919 (org-cycle-internal-local))
6921 ;; From there: TAB emulation and template completion.
6922 (buffer-read-only (org-back-to-heading))
6924 ((run-hook-with-args-until-success
6925 'org-tab-after-check-for-cycling-hook))
6927 ((org-try-structure-completion))
6929 ((run-hook-with-args-until-success
6930 'org-tab-before-tab-emulation-hook))
6932 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6933 (or (not (bolp))
6934 (not (looking-at org-outline-regexp))))
6935 (call-interactively (global-key-binding "\t")))
6937 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6938 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6939 (or (and (eq org-cycle-emulate-tab 'white)
6940 (= (match-end 0) (point-at-eol)))
6941 (and (eq org-cycle-emulate-tab 'whitestart)
6942 (>= (match-end 0) pos))))
6944 (eq org-cycle-emulate-tab t))
6945 (call-interactively (global-key-binding "\t")))
6947 (t (save-excursion
6948 (org-back-to-heading)
6949 (org-cycle)))))))
6951 (defun org-cycle-internal-global ()
6952 "Do the global cycling action."
6953 ;; Hack to avoid display of messages for .org attachments in Gnus
6954 (let ((ga (string-match "\\*fontification" (buffer-name))))
6955 (cond
6956 ((and (eq last-command this-command)
6957 (eq org-cycle-global-status 'overview))
6958 ;; We just created the overview - now do table of contents
6959 ;; This can be slow in very large buffers, so indicate action
6960 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6961 (unless ga (org-unlogged-message "CONTENTS..."))
6962 (org-content)
6963 (unless ga (org-unlogged-message "CONTENTS...done"))
6964 (setq org-cycle-global-status 'contents)
6965 (run-hook-with-args 'org-cycle-hook 'contents))
6967 ((and (eq last-command this-command)
6968 (eq org-cycle-global-status 'contents))
6969 ;; We just showed the table of contents - now show everything
6970 (run-hook-with-args 'org-pre-cycle-hook 'all)
6971 (outline-show-all)
6972 (unless ga (org-unlogged-message "SHOW ALL"))
6973 (setq org-cycle-global-status 'all)
6974 (run-hook-with-args 'org-cycle-hook 'all))
6977 ;; Default action: go to overview
6978 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6979 (org-overview)
6980 (unless ga (org-unlogged-message "OVERVIEW"))
6981 (setq org-cycle-global-status 'overview)
6982 (run-hook-with-args 'org-cycle-hook 'overview)))))
6984 (defvar org-called-with-limited-levels nil
6985 "Non-nil when `org-with-limited-levels' is currently active.")
6987 (defun org-invisible-p (&optional pos)
6988 "Non-nil if the character after POS is invisible.
6989 If POS is nil, use `point' instead."
6990 (get-char-property (or pos (point)) 'invisible))
6992 (defun org-cycle-internal-local ()
6993 "Do the local cycling action."
6994 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6995 ;; First, determine end of headline (EOH), end of subtree or item
6996 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6997 (save-excursion
6998 (if (org-at-item-p)
6999 (progn
7000 (beginning-of-line)
7001 (setq struct (org-list-struct))
7002 (setq eoh (point-at-eol))
7003 (setq eos (org-list-get-item-end-before-blank (point) struct))
7004 (setq has-children (org-list-has-child-p (point) struct)))
7005 (org-back-to-heading)
7006 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7007 (setq eos (save-excursion (org-end-of-subtree t t)
7008 (when (bolp) (backward-char)) (point)))
7009 (setq has-children
7010 (or (save-excursion
7011 (let ((level (funcall outline-level)))
7012 (outline-next-heading)
7013 (and (org-at-heading-p t)
7014 (> (funcall outline-level) level))))
7015 (save-excursion
7016 (org-list-search-forward (org-item-beginning-re) eos t)))))
7017 ;; Determine end invisible part of buffer (EOL)
7018 (beginning-of-line 2)
7019 (while (and (not (eobp)) ;This is like `next-line'.
7020 (get-char-property (1- (point)) 'invisible))
7021 (goto-char (next-single-char-property-change (point) 'invisible))
7022 (and (eolp) (beginning-of-line 2)))
7023 (setq eol (point)))
7024 ;; Find out what to do next and set `this-command'
7025 (cond
7026 ((= eos eoh)
7027 ;; Nothing is hidden behind this heading
7028 (unless (org-before-first-heading-p)
7029 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7030 (org-unlogged-message "EMPTY ENTRY")
7031 (setq org-cycle-subtree-status nil)
7032 (save-excursion
7033 (goto-char eos)
7034 (outline-next-heading)
7035 (when (org-invisible-p) (org-flag-heading nil))))
7036 ((and (or (>= eol eos)
7037 (not (string-match "\\S-" (buffer-substring eol eos))))
7038 (or has-children
7039 (not (setq children-skipped
7040 org-cycle-skip-children-state-if-no-children))))
7041 ;; Entire subtree is hidden in one line: children view
7042 (unless (org-before-first-heading-p)
7043 (run-hook-with-args 'org-pre-cycle-hook 'children))
7044 (if (org-at-item-p)
7045 (org-list-set-item-visibility (point-at-bol) struct 'children)
7046 (org-show-entry)
7047 (org-with-limited-levels (org-show-children))
7048 ;; FIXME: This slows down the func way too much.
7049 ;; How keep drawers hidden in subtree anyway?
7050 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
7051 ;; (org-cycle-hide-drawers 'subtree))
7053 ;; Fold every list in subtree to top-level items.
7054 (when (eq org-cycle-include-plain-lists 'integrate)
7055 (save-excursion
7056 (org-back-to-heading)
7057 (while (org-list-search-forward (org-item-beginning-re) eos t)
7058 (beginning-of-line 1)
7059 (let* ((struct (org-list-struct))
7060 (prevs (org-list-prevs-alist struct))
7061 (end (org-list-get-bottom-point struct)))
7062 (dolist (e (org-list-get-all-items (point) struct prevs))
7063 (org-list-set-item-visibility e struct 'folded))
7064 (goto-char (if (< end eos) end eos)))))))
7065 (org-unlogged-message "CHILDREN")
7066 (save-excursion
7067 (goto-char eos)
7068 (outline-next-heading)
7069 (when (org-invisible-p) (org-flag-heading nil)))
7070 (setq org-cycle-subtree-status 'children)
7071 (unless (org-before-first-heading-p)
7072 (run-hook-with-args 'org-cycle-hook 'children)))
7073 ((or children-skipped
7074 (and (eq last-command this-command)
7075 (eq org-cycle-subtree-status 'children)))
7076 ;; We just showed the children, or no children are there,
7077 ;; now show everything.
7078 (unless (org-before-first-heading-p)
7079 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7080 (outline-flag-region eoh eos nil)
7081 (org-unlogged-message
7082 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7083 (setq org-cycle-subtree-status 'subtree)
7084 (unless (org-before-first-heading-p)
7085 (run-hook-with-args 'org-cycle-hook 'subtree)))
7087 ;; Default action: hide the subtree.
7088 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7089 (outline-flag-region eoh eos t)
7090 (org-unlogged-message "FOLDED")
7091 (setq org-cycle-subtree-status 'folded)
7092 (unless (org-before-first-heading-p)
7093 (run-hook-with-args 'org-cycle-hook 'folded))))))
7095 ;;;###autoload
7096 (defun org-global-cycle (&optional arg)
7097 "Cycle the global visibility. For details see `org-cycle'.
7098 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7099 With a numeric prefix, show all headlines up to that level."
7100 (interactive "P")
7101 (let ((org-cycle-include-plain-lists
7102 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7103 (cond
7104 ((integerp arg)
7105 (outline-show-all)
7106 (outline-hide-sublevels arg)
7107 (setq org-cycle-global-status 'contents))
7108 ((equal arg '(4))
7109 (org-set-startup-visibility)
7110 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7112 (org-cycle '(4))))))
7114 (defun org-set-startup-visibility ()
7115 "Set the visibility required by startup options and properties."
7116 (cond
7117 ((eq org-startup-folded t)
7118 (org-overview))
7119 ((eq org-startup-folded 'content)
7120 (org-content))
7121 ((or (eq org-startup-folded 'showeverything)
7122 (eq org-startup-folded nil))
7123 (outline-show-all)))
7124 (unless (eq org-startup-folded 'showeverything)
7125 (when org-hide-block-startup (org-hide-block-all))
7126 (org-set-visibility-according-to-property 'no-cleanup)
7127 (org-cycle-hide-archived-subtrees 'all)
7128 (org-cycle-hide-drawers 'all)
7129 (org-cycle-show-empty-lines t)))
7131 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7132 "Switch subtree visibilities according to :VISIBILITY: property."
7133 (interactive)
7134 (org-with-wide-buffer
7135 (goto-char (point-min))
7136 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7137 (if (not (org-at-property-p)) (outline-next-heading)
7138 (let ((state (match-string 3)))
7139 (save-excursion
7140 (org-back-to-heading t)
7141 (outline-hide-subtree)
7142 (org-reveal)
7143 (cond
7144 ((equal state "folded")
7145 (outline-hide-subtree))
7146 ((equal state "children")
7147 (org-show-hidden-entry)
7148 (org-show-children))
7149 ((equal state "content")
7150 (save-excursion
7151 (save-restriction
7152 (org-narrow-to-subtree)
7153 (org-content))))
7154 ((member state '("all" "showall"))
7155 (outline-show-subtree)))))))
7156 (unless no-cleanup
7157 (org-cycle-hide-archived-subtrees 'all)
7158 (org-cycle-hide-drawers 'all)
7159 (org-cycle-show-empty-lines 'all))))
7161 ;; This function uses outline-regexp instead of the more fundamental
7162 ;; org-outline-regexp so that org-cycle-global works outside of Org
7163 ;; buffers, where outline-regexp is needed.
7164 (defun org-overview ()
7165 "Switch to overview mode, showing only top-level headlines.
7166 This shows all headlines with a level equal or greater than the level
7167 of the first headline in the buffer. This is important, because if the
7168 first headline is not level one, then (hide-sublevels 1) gives confusing
7169 results."
7170 (interactive)
7171 (save-excursion
7172 (let ((level
7173 (save-excursion
7174 (goto-char (point-min))
7175 (when (re-search-forward (concat "^" outline-regexp) nil t)
7176 (goto-char (match-beginning 0))
7177 (funcall outline-level)))))
7178 (and level (outline-hide-sublevels level)))))
7180 (defun org-content (&optional arg)
7181 "Show all headlines in the buffer, like a table of contents.
7182 With numerical argument N, show content up to level N."
7183 (interactive "P")
7184 (org-overview)
7185 (save-excursion
7186 ;; Visit all headings and show their offspring
7187 (and (integerp arg) (org-overview))
7188 (goto-char (point-max))
7189 (catch 'exit
7190 (while (and (progn (condition-case nil
7191 (outline-previous-visible-heading 1)
7192 (error (goto-char (point-min))))
7194 (looking-at org-outline-regexp))
7195 (if (integerp arg)
7196 (org-show-children (1- arg))
7197 (outline-show-branches))
7198 (when (bobp) (throw 'exit nil))))))
7200 (defun org-optimize-window-after-visibility-change (state)
7201 "Adjust the window after a change in outline visibility.
7202 This function is the default value of the hook `org-cycle-hook'."
7203 (when (get-buffer-window (current-buffer))
7204 (cond
7205 ((eq state 'content) nil)
7206 ((eq state 'all) nil)
7207 ((eq state 'folded) nil)
7208 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7209 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7211 (defun org-remove-empty-overlays-at (pos)
7212 "Remove outline overlays that do not contain non-white stuff."
7213 (dolist (o (overlays-at pos))
7214 (and (eq 'outline (overlay-get o 'invisible))
7215 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7216 (overlay-end o))))
7217 (delete-overlay o))))
7219 (defun org-clean-visibility-after-subtree-move ()
7220 "Fix visibility issues after moving a subtree."
7221 ;; First, find a reasonable region to look at:
7222 ;; Start two siblings above, end three below
7223 (let* ((beg (save-excursion
7224 (and (org-get-last-sibling)
7225 (org-get-last-sibling))
7226 (point)))
7227 (end (save-excursion
7228 (and (org-get-next-sibling)
7229 (org-get-next-sibling)
7230 (org-get-next-sibling))
7231 (if (org-at-heading-p)
7232 (point-at-eol)
7233 (point))))
7234 (level (looking-at "\\*+"))
7235 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7236 (save-excursion
7237 (save-restriction
7238 (narrow-to-region beg end)
7239 (when re
7240 ;; Properly fold already folded siblings
7241 (goto-char (point-min))
7242 (while (re-search-forward re nil t)
7243 (when (and (not (org-invisible-p))
7244 (save-excursion
7245 (goto-char (point-at-eol)) (org-invisible-p)))
7246 (outline-hide-entry))))
7247 (org-cycle-show-empty-lines 'overview)
7248 (org-cycle-hide-drawers 'overview)))))
7250 (defun org-cycle-show-empty-lines (state)
7251 "Show empty lines above all visible headlines.
7252 The region to be covered depends on STATE when called through
7253 `org-cycle-hook'. Lisp program can use t for STATE to get the
7254 entire buffer covered. Note that an empty line is only shown if there
7255 are at least `org-cycle-separator-lines' empty lines before the headline."
7256 (when (/= org-cycle-separator-lines 0)
7257 (save-excursion
7258 (let* ((n (abs org-cycle-separator-lines))
7259 (re (cond
7260 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7261 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7262 (t (let ((ns (number-to-string (- n 2))))
7263 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7264 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7265 beg end)
7266 (cond
7267 ((memq state '(overview contents t))
7268 (setq beg (point-min) end (point-max)))
7269 ((memq state '(children folded))
7270 (setq beg (point)
7271 end (progn (org-end-of-subtree t t)
7272 (line-beginning-position 2)))))
7273 (when beg
7274 (goto-char beg)
7275 (while (re-search-forward re end t)
7276 (unless (get-char-property (match-end 1) 'invisible)
7277 (let ((e (match-end 1))
7278 (b (if (>= org-cycle-separator-lines 0)
7279 (match-beginning 1)
7280 (save-excursion
7281 (goto-char (match-beginning 0))
7282 (skip-chars-backward " \t\n")
7283 (line-end-position)))))
7284 (outline-flag-region b e nil))))))))
7285 ;; Never hide empty lines at the end of the file.
7286 (save-excursion
7287 (goto-char (point-max))
7288 (outline-previous-heading)
7289 (outline-end-of-heading)
7290 (when (and (looking-at "[ \t\n]+")
7291 (= (match-end 0) (point-max)))
7292 (outline-flag-region (point) (match-end 0) nil))))
7294 (defun org-show-empty-lines-in-parent ()
7295 "Move to the parent and re-show empty lines before visible headlines."
7296 (save-excursion
7297 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7298 (org-cycle-show-empty-lines context))))
7300 (defun org-files-list ()
7301 "Return `org-agenda-files' list, plus all open Org files.
7302 This is useful for operations that need to scan all of a user's
7303 open and agenda-wise Org files."
7304 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7305 (dolist (buf (buffer-list))
7306 (with-current-buffer buf
7307 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7308 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7309 files))
7311 (defsubst org-entry-beginning-position ()
7312 "Return the beginning position of the current entry."
7313 (save-excursion (org-back-to-heading t) (point)))
7315 (defsubst org-entry-end-position ()
7316 "Return the end position of the current entry."
7317 (save-excursion (outline-next-heading) (point)))
7319 (defun org-cycle-hide-drawers (state &optional exceptions)
7320 "Re-hide all drawers after a visibility state change.
7321 When non-nil, optional argument EXCEPTIONS is a list of strings
7322 specifying which drawers should not be hidden."
7323 (when (and (derived-mode-p 'org-mode)
7324 (not (memq state '(overview folded contents))))
7325 (save-excursion
7326 (let* ((globalp (memq state '(contents all)))
7327 (beg (if globalp (point-min) (point)))
7328 (end (if globalp (point-max)
7329 (if (eq state 'children)
7330 (save-excursion (outline-next-heading) (point))
7331 (org-end-of-subtree t)))))
7332 (goto-char beg)
7333 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7334 (unless (member-ignore-case (match-string 1) exceptions)
7335 (let ((drawer (org-element-at-point)))
7336 (when (memq (org-element-type drawer) '(drawer property-drawer))
7337 (org-flag-drawer t drawer)
7338 ;; Make sure to skip drawer entirely or we might flag
7339 ;; it another time when matching its ending line with
7340 ;; `org-drawer-regexp'.
7341 (goto-char (org-element-property :end drawer))))))))))
7343 (defun org-flag-drawer (flag &optional element)
7344 "When FLAG is non-nil, hide the drawer we are at.
7345 Otherwise make it visible. When optional argument ELEMENT is
7346 a parsed drawer, as returned by `org-element-at-point', hide or
7347 show that drawer instead."
7348 (let ((drawer (or element
7349 (and (save-excursion
7350 (beginning-of-line)
7351 (looking-at-p org-drawer-regexp))
7352 (org-element-at-point)))))
7353 (when (memq (org-element-type drawer) '(drawer property-drawer))
7354 (let ((post (org-element-property :post-affiliated drawer)))
7355 (save-excursion
7356 (outline-flag-region
7357 (progn (goto-char post) (line-end-position))
7358 (progn (goto-char (org-element-property :end drawer))
7359 (skip-chars-backward " \r\t\n")
7360 (line-end-position))
7361 flag))
7362 ;; When the drawer is hidden away, make sure point lies in
7363 ;; a visible part of the buffer.
7364 (when (and flag (> (line-beginning-position) post))
7365 (goto-char post))))))
7367 (defun org-subtree-end-visible-p ()
7368 "Is the end of the current subtree visible?"
7369 (pos-visible-in-window-p
7370 (save-excursion (org-end-of-subtree t) (point))))
7372 (defun org-first-headline-recenter ()
7373 "Move cursor to the first headline and recenter the headline."
7374 (let ((window (get-buffer-window)))
7375 (when window
7376 (goto-char (point-min))
7377 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7378 (set-window-start window (line-beginning-position))))))
7380 ;;; Saving and restoring visibility
7382 (defun org-outline-overlay-data (&optional use-markers)
7383 "Return a list of the locations of all outline overlays.
7384 These are overlays with the `invisible' property value `outline'.
7385 The return value is a list of cons cells, with start and stop
7386 positions for each overlay.
7387 If USE-MARKERS is set, return the positions as markers."
7388 (let (beg end)
7389 (org-with-wide-buffer
7390 (delq nil
7391 (mapcar (lambda (o)
7392 (when (eq (overlay-get o 'invisible) 'outline)
7393 (setq beg (overlay-start o)
7394 end (overlay-end o))
7395 (and beg end (> end beg)
7396 (if use-markers
7397 (cons (copy-marker beg)
7398 (copy-marker end t))
7399 (cons beg end)))))
7400 (overlays-in (point-min) (point-max)))))))
7402 (defun org-set-outline-overlay-data (data)
7403 "Create visibility overlays for all positions in DATA.
7404 DATA should have been made by `org-outline-overlay-data'."
7405 (org-with-wide-buffer
7406 (outline-show-all)
7407 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7409 ;;; Folding of blocks
7411 (defvar-local org-hide-block-overlays nil
7412 "Overlays hiding blocks.")
7414 (defun org-block-map (function &optional start end)
7415 "Call FUNCTION at the head of all source blocks in the current buffer.
7416 Optional arguments START and END can be used to limit the range."
7417 (let ((start (or start (point-min)))
7418 (end (or end (point-max))))
7419 (save-excursion
7420 (goto-char start)
7421 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7422 (save-excursion
7423 (save-match-data
7424 (goto-char (match-beginning 0))
7425 (funcall function)))))))
7427 (defun org-hide-block-toggle-all ()
7428 "Toggle the visibility of all blocks in the current buffer."
7429 (org-block-map 'org-hide-block-toggle))
7431 (defun org-hide-block-all ()
7432 "Fold all blocks in the current buffer."
7433 (interactive)
7434 (org-show-block-all)
7435 (org-block-map 'org-hide-block-toggle-maybe))
7437 (defun org-show-block-all ()
7438 "Unfold all blocks in the current buffer."
7439 (interactive)
7440 (mapc #'delete-overlay org-hide-block-overlays)
7441 (setq org-hide-block-overlays nil))
7443 (defun org-hide-block-toggle-maybe ()
7444 "Toggle visibility of block at point.
7445 Unlike to `org-hide-block-toggle', this function does not throw
7446 an error. Return a non-nil value when toggling is successful."
7447 (interactive)
7448 (ignore-errors (org-hide-block-toggle)))
7450 (defun org-hide-block-toggle (&optional force)
7451 "Toggle the visibility of the current block.
7452 When optional argument FORCE is `off', make block visible. If it
7453 is non-nil, hide it unconditionally. Throw an error when not at
7454 a block. Return a non-nil value when toggling is successful."
7455 (interactive)
7456 (let ((element (org-element-at-point)))
7457 (unless (memq (org-element-type element)
7458 '(center-block comment-block dynamic-block example-block
7459 export-block quote-block special-block
7460 src-block verse-block))
7461 (user-error "Not at a block"))
7462 (let* ((start (save-excursion
7463 (goto-char (org-element-property :post-affiliated element))
7464 (line-end-position)))
7465 (end (save-excursion
7466 (goto-char (org-element-property :end element))
7467 (skip-chars-backward " \r\t\n")
7468 (line-end-position)))
7469 (overlays (overlays-at start)))
7470 (cond
7471 ;; Do nothing when not before or at the block opening line or
7472 ;; at the block closing line.
7473 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7474 ((and (not (eq force 'off))
7475 (not (memq t (mapcar
7476 (lambda (o)
7477 (eq (overlay-get o 'invisible) 'org-hide-block))
7478 overlays))))
7479 (let ((ov (make-overlay start end)))
7480 (overlay-put ov 'invisible 'org-hide-block)
7481 ;; Make the block accessible to `isearch'.
7482 (overlay-put
7483 ov 'isearch-open-invisible
7484 (lambda (ov)
7485 (when (memq ov org-hide-block-overlays)
7486 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7487 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7488 (delete-overlay ov))))
7489 (push ov org-hide-block-overlays)
7490 ;; When the block is hidden away, make sure point is left in
7491 ;; a visible part of the buffer.
7492 (when (> (line-beginning-position) start)
7493 (goto-char start)
7494 (beginning-of-line))
7495 ;; Signal successful toggling.
7497 ((or (not force) (eq force 'off))
7498 (dolist (ov overlays t)
7499 (when (memq ov org-hide-block-overlays)
7500 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7501 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7502 (delete-overlay ov))))))))
7504 ;; Remove overlays when changing major mode
7505 (add-hook 'org-mode-hook
7506 (lambda () (add-hook 'change-major-mode-hook
7507 'org-show-block-all 'append 'local)))
7509 ;;; Org-goto
7511 (defvar org-goto-window-configuration nil)
7512 (defvar org-goto-marker nil)
7513 (defvar org-goto-map)
7514 (defun org-goto-map ()
7515 "Set the keymap `org-goto'."
7516 (setq org-goto-map
7517 (let ((map (make-sparse-keymap)))
7518 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7519 mouse-drag-region universal-argument org-occur)))
7520 (dolist (cmd cmds)
7521 (substitute-key-definition cmd cmd map global-map)))
7522 (suppress-keymap map)
7523 (org-defkey map "\C-m" 'org-goto-ret)
7524 (org-defkey map [(return)] 'org-goto-ret)
7525 (org-defkey map [(left)] 'org-goto-left)
7526 (org-defkey map [(right)] 'org-goto-right)
7527 (org-defkey map [(control ?g)] 'org-goto-quit)
7528 (org-defkey map "\C-i" 'org-cycle)
7529 (org-defkey map [(tab)] 'org-cycle)
7530 (org-defkey map [(down)] 'outline-next-visible-heading)
7531 (org-defkey map [(up)] 'outline-previous-visible-heading)
7532 (if org-goto-auto-isearch
7533 (if (fboundp 'define-key-after)
7534 (define-key-after map [t] 'org-goto-local-auto-isearch)
7535 nil)
7536 (org-defkey map "q" 'org-goto-quit)
7537 (org-defkey map "n" 'outline-next-visible-heading)
7538 (org-defkey map "p" 'outline-previous-visible-heading)
7539 (org-defkey map "f" 'outline-forward-same-level)
7540 (org-defkey map "b" 'outline-backward-same-level)
7541 (org-defkey map "u" 'outline-up-heading))
7542 (org-defkey map "/" 'org-occur)
7543 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7544 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7545 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7546 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7547 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7548 map)))
7550 (defconst org-goto-help
7551 "Browse buffer copy, to find location or copy text.%s
7552 RET=jump to location C-g=quit and return to previous location
7553 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7555 (defvar org-goto-start-pos) ; dynamically scoped parameter
7557 (defun org-goto (&optional alternative-interface)
7558 "Look up a different location in the current file, keeping current visibility.
7560 When you want look-up or go to a different location in a
7561 document, the fastest way is often to fold the entire buffer and
7562 then dive into the tree. This method has the disadvantage, that
7563 the previous location will be folded, which may not be what you
7564 want.
7566 This command works around this by showing a copy of the current
7567 buffer in an indirect buffer, in overview mode. You can dive
7568 into the tree in that copy, use org-occur and incremental search
7569 to find a location. When pressing RET or `Q', the command
7570 returns to the original buffer in which the visibility is still
7571 unchanged. After RET it will also jump to the location selected
7572 in the indirect buffer and expose the headline hierarchy above.
7574 With a prefix argument, use the alternative interface: e.g., if
7575 `org-goto-interface' is `outline' use `outline-path-completion'."
7576 (interactive "P")
7577 (org-goto-map)
7578 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7579 (org-refile-use-outline-path t)
7580 (org-refile-target-verify-function nil)
7581 (interface
7582 (if (not alternative-interface)
7583 org-goto-interface
7584 (if (eq org-goto-interface 'outline)
7585 'outline-path-completion
7586 'outline)))
7587 (org-goto-start-pos (point))
7588 (selected-point
7589 (if (eq interface 'outline)
7590 (car (org-get-location (current-buffer) org-goto-help))
7591 (let ((pa (org-refile-get-location "Goto")))
7592 (org-refile-check-position pa)
7593 (nth 3 pa)))))
7594 (if selected-point
7595 (progn
7596 (org-mark-ring-push org-goto-start-pos)
7597 (goto-char selected-point)
7598 (when (or (org-invisible-p) (org-invisible-p2))
7599 (org-show-context 'org-goto)))
7600 (message "Quit"))))
7602 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7603 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7604 (defvar org-goto-local-auto-isearch-map) ; defined below
7606 (defun org-get-location (_buf help)
7607 "Let the user select a location in current buffer.
7608 This function uses a recursive edit. It returns the selected position
7609 or nil."
7610 (org-no-popups
7611 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7612 (isearch-hide-immediately nil)
7613 (isearch-search-fun-function
7614 (lambda () 'org-goto-local-search-headings))
7615 (org-goto-selected-point org-goto-exit-command))
7616 (save-excursion
7617 (save-window-excursion
7618 (delete-other-windows)
7619 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7620 (pop-to-buffer-same-window
7621 (condition-case nil
7622 (make-indirect-buffer (current-buffer) "*org-goto*")
7623 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7624 (with-output-to-temp-buffer "*Org Help*"
7625 (princ (format help (if org-goto-auto-isearch
7626 " Just type for auto-isearch."
7627 " n/p/f/b/u to navigate, q to quit."))))
7628 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7629 (setq buffer-read-only nil)
7630 (let ((org-startup-truncated t)
7631 (org-startup-folded nil)
7632 (org-startup-align-all-tables nil))
7633 (org-mode)
7634 (org-overview))
7635 (setq buffer-read-only t)
7636 (if (and (boundp 'org-goto-start-pos)
7637 (integer-or-marker-p org-goto-start-pos))
7638 (progn (goto-char org-goto-start-pos)
7639 (when (org-invisible-p)
7640 (org-show-set-visibility 'lineage)))
7641 (goto-char (point-min)))
7642 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7643 (message "Select location and press RET")
7644 (use-local-map org-goto-map)
7645 (recursive-edit)))
7646 (kill-buffer "*org-goto*")
7647 (cons org-goto-selected-point org-goto-exit-command))))
7649 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7650 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7651 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7652 (if (fboundp 'isearch-other-control-char)
7653 (progn
7654 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7655 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7656 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7657 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7658 (define-key org-goto-local-auto-isearch-map [return] nil))
7660 (defun org-goto-local-search-headings (string bound noerror)
7661 "Search and make sure that any matches are in headlines."
7662 (catch 'return
7663 (while (if isearch-forward
7664 (search-forward string bound noerror)
7665 (search-backward string bound noerror))
7666 (when (save-match-data
7667 (and (save-excursion
7668 (beginning-of-line)
7669 (looking-at org-complex-heading-regexp))
7670 (or (not (match-beginning 5))
7671 (< (point) (match-beginning 5)))))
7672 (throw 'return (point))))))
7674 (defun org-goto-local-auto-isearch ()
7675 "Start isearch."
7676 (interactive)
7677 (goto-char (point-min))
7678 (let ((keys (this-command-keys)))
7679 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7680 (isearch-mode t)
7681 (isearch-process-search-char (string-to-char keys)))))
7683 (defun org-goto-ret (&optional _arg)
7684 "Finish `org-goto' by going to the new location."
7685 (interactive "P")
7686 (setq org-goto-selected-point (point))
7687 (setq org-goto-exit-command 'return)
7688 (throw 'exit nil))
7690 (defun org-goto-left ()
7691 "Finish `org-goto' by going to the new location."
7692 (interactive)
7693 (if (org-at-heading-p)
7694 (progn
7695 (beginning-of-line 1)
7696 (setq org-goto-selected-point (point)
7697 org-goto-exit-command 'left)
7698 (throw 'exit nil))
7699 (user-error "Not on a heading")))
7701 (defun org-goto-right ()
7702 "Finish `org-goto' by going to the new location."
7703 (interactive)
7704 (if (org-at-heading-p)
7705 (progn
7706 (setq org-goto-selected-point (point)
7707 org-goto-exit-command 'right)
7708 (throw 'exit nil))
7709 (user-error "Not on a heading")))
7711 (defun org-goto-quit ()
7712 "Finish `org-goto' without cursor motion."
7713 (interactive)
7714 (setq org-goto-selected-point nil)
7715 (setq org-goto-exit-command 'quit)
7716 (throw 'exit nil))
7718 ;;; Indirect buffer display of subtrees
7720 (defvar org-indirect-dedicated-frame nil
7721 "This is the frame being used for indirect tree display.")
7722 (defvar org-last-indirect-buffer nil)
7724 (defun org-tree-to-indirect-buffer (&optional arg)
7725 "Create indirect buffer and narrow it to current subtree.
7727 With a numerical prefix ARG, go up to this level and then take that tree.
7728 If ARG is negative, go up that many levels.
7730 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7731 indirect buffer previously made with this command, to avoid proliferation of
7732 indirect buffers. However, when you call the command with a \
7733 `\\[universal-argument]' prefix, or
7734 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7735 so that you can work with several indirect buffers at the same time. If
7736 `org-indirect-buffer-display' is `dedicated-frame', the \
7737 `\\[universal-argument]' prefix also
7738 requests that a new frame be made for the new buffer, so that the dedicated
7739 frame is not changed."
7740 (interactive "P")
7741 (let ((cbuf (current-buffer))
7742 (cwin (selected-window))
7743 (pos (point))
7744 beg end level heading ibuf)
7745 (save-excursion
7746 (org-back-to-heading t)
7747 (when (numberp arg)
7748 (setq level (org-outline-level))
7749 (when (< arg 0) (setq arg (+ level arg)))
7750 (while (> (setq level (org-outline-level)) arg)
7751 (org-up-heading-safe)))
7752 (setq beg (point)
7753 heading (org-get-heading 'no-tags))
7754 (org-end-of-subtree t t)
7755 (when (org-at-heading-p) (backward-char 1))
7756 (setq end (point)))
7757 (when (and (buffer-live-p org-last-indirect-buffer)
7758 (not (eq org-indirect-buffer-display 'new-frame))
7759 (not arg))
7760 (kill-buffer org-last-indirect-buffer))
7761 (setq ibuf (org-get-indirect-buffer cbuf heading)
7762 org-last-indirect-buffer ibuf)
7763 (cond
7764 ((or (eq org-indirect-buffer-display 'new-frame)
7765 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7766 (select-frame (make-frame))
7767 (delete-other-windows)
7768 (pop-to-buffer-same-window ibuf)
7769 (org-set-frame-title heading))
7770 ((eq org-indirect-buffer-display 'dedicated-frame)
7771 (raise-frame
7772 (select-frame (or (and org-indirect-dedicated-frame
7773 (frame-live-p org-indirect-dedicated-frame)
7774 org-indirect-dedicated-frame)
7775 (setq org-indirect-dedicated-frame (make-frame)))))
7776 (delete-other-windows)
7777 (pop-to-buffer-same-window ibuf)
7778 (org-set-frame-title (concat "Indirect: " heading)))
7779 ((eq org-indirect-buffer-display 'current-window)
7780 (pop-to-buffer-same-window ibuf))
7781 ((eq org-indirect-buffer-display 'other-window)
7782 (pop-to-buffer ibuf))
7783 (t (error "Invalid value")))
7784 (narrow-to-region beg end)
7785 (outline-show-all)
7786 (goto-char pos)
7787 (run-hook-with-args 'org-cycle-hook 'all)
7788 (and (window-live-p cwin) (select-window cwin))))
7790 (defun org-get-indirect-buffer (&optional buffer heading)
7791 (setq buffer (or buffer (current-buffer)))
7792 (let ((n 1) (base (buffer-name buffer)) bname)
7793 (while (buffer-live-p
7794 (get-buffer
7795 (setq bname
7796 (concat base "-"
7797 (if heading (concat heading "-" (number-to-string n))
7798 (number-to-string n))))))
7799 (setq n (1+ n)))
7800 (condition-case nil
7801 (make-indirect-buffer buffer bname 'clone)
7802 (error (make-indirect-buffer buffer bname)))))
7804 (defun org-set-frame-title (title)
7805 "Set the title of the current frame to the string TITLE."
7806 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7808 ;;;; Structure editing
7810 ;;; Inserting headlines
7812 (defun org--line-empty-p (n)
7813 "Is the Nth next line empty?
7815 Counts the current line as N = 1 and the previous line as N = 0;
7816 see `beginning-of-line'."
7817 (save-excursion
7818 (and (not (bobp))
7819 (or (beginning-of-line n) t)
7820 (save-match-data
7821 (looking-at "[ \t]*$")))))
7823 (defun org-previous-line-empty-p ()
7824 "Is the previous line a blank line?
7825 When NEXT is non-nil, check the next line instead."
7826 (org--line-empty-p 0))
7828 (defun org-next-line-empty-p ()
7829 "Is the previous line a blank line?
7830 When NEXT is non-nil, check the next line instead."
7831 (org--line-empty-p 2))
7833 (defun org-insert-heading (&optional arg invisible-ok top)
7834 "Insert a new heading or an item with the same depth at point.
7836 If point is at the beginning of a heading or a list item, insert
7837 a new heading or a new item above the current one. When at the
7838 beginning of a regular line of text, turn it into a heading.
7840 If point is in the middle of a line, split it and create a new
7841 headline/item with the text in the current line after point (see
7842 `org-M-RET-may-split-line' on how to modify this behavior). As
7843 a special case, on a headline, splitting can only happen on the
7844 title itself. E.g., this excludes breaking stars or tags.
7846 With a `\\[universal-argument]' prefix, set \
7847 `org-insert-heading-respect-content' to
7848 a non-nil value for the duration of the command. This forces the
7849 insertion of a heading after the current subtree, independently
7850 on the location of point.
7852 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7853 insert the heading at the end of the tree
7854 above the current heading. For example, if point is within a
7855 2nd-level heading, then it will insert a 2nd-level heading at
7856 the end of the 1st-level parent subtree.
7858 When INVISIBLE-OK is set, stop at invisible headlines when going
7859 back. This is important for non-interactive uses of the
7860 command.
7862 When optional argument TOP is non-nil, insert a level 1 heading,
7863 unconditionally."
7864 (interactive "P")
7865 (let ((itemp (and (not top) (org-in-item-p)))
7866 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7867 (respect-content (or org-insert-heading-respect-content
7868 (equal arg '(4))))
7869 (initial-content ""))
7871 (cond
7873 ((or (= (buffer-size) 0)
7874 (and (not (save-excursion
7875 (and (ignore-errors (org-back-to-heading invisible-ok))
7876 (org-at-heading-p))))
7877 (or arg (not itemp))))
7878 ;; At beginning of buffer or so high up that only a heading
7879 ;; makes sense.
7880 (cond ((and (bolp) (not respect-content)) (insert "* "))
7881 ((not respect-content)
7882 (unless may-split (end-of-line))
7883 (insert "\n* "))
7884 ((re-search-forward org-outline-regexp-bol nil t)
7885 (beginning-of-line)
7886 (insert "* \n")
7887 (backward-char))
7888 (t (goto-char (point-max))
7889 (insert "\n* ")))
7890 (run-hooks 'org-insert-heading-hook))
7892 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7895 ;; Maybe move at the end of the subtree
7896 (when (equal arg '(16))
7897 (org-up-heading-safe)
7898 (org-end-of-subtree t))
7899 ;; Insert a heading
7900 (save-restriction
7901 (widen)
7902 (let* ((level nil)
7903 (on-heading (org-at-heading-p))
7904 (empty-line-p (if on-heading
7905 (org-previous-line-empty-p)
7906 ;; We will decide later
7907 nil))
7908 ;; Get a level string to fall back on.
7909 (fix-level
7910 (if (org-before-first-heading-p) "*"
7911 (save-excursion
7912 (org-back-to-heading t)
7913 (when (org-previous-line-empty-p) (setq empty-line-p t))
7914 (looking-at org-outline-regexp)
7915 (make-string (1- (length (match-string 0))) ?*))))
7916 (stars
7917 (save-excursion
7918 (condition-case nil
7919 (if top "* "
7920 (org-back-to-heading invisible-ok)
7921 (when (and (not on-heading)
7922 (featurep 'org-inlinetask)
7923 (integerp org-inlinetask-min-level)
7924 (>= (length (match-string 0))
7925 org-inlinetask-min-level))
7926 ;; Find a heading level before the inline
7927 ;; task.
7928 (while (and (setq level (org-up-heading-safe))
7929 (>= level org-inlinetask-min-level)))
7930 (if (org-at-heading-p)
7931 (org-back-to-heading invisible-ok)
7932 (error "This should not happen")))
7933 (unless (and (save-excursion
7934 (save-match-data
7935 (org-backward-heading-same-level
7936 1 invisible-ok))
7937 (= (point) (match-beginning 0)))
7938 (not (org-next-line-empty-p)))
7939 (setq empty-line-p (or empty-line-p
7940 (org-previous-line-empty-p))))
7941 (match-string 0))
7942 (error (or fix-level "* ")))))
7943 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7944 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7946 ;; If we insert after content, move there and clean up
7947 ;; whitespace.
7948 (when respect-content
7949 (if (not (org-before-first-heading-p))
7950 (org-end-of-subtree nil t)
7951 (re-search-forward org-outline-regexp-bol)
7952 (beginning-of-line 0))
7953 (skip-chars-backward " \r\t\n")
7954 (and (not (looking-back "^\\*+" (line-beginning-position)))
7955 (looking-at "[ \t]+") (replace-match ""))
7956 (unless (eobp) (forward-char 1))
7957 (when (looking-at "^\\*")
7958 (unless (bobp) (backward-char 1))
7959 (insert "\n")))
7961 ;; If we are splitting, grab the text that should be moved
7962 ;; to the new headline.
7963 (when may-split
7964 (if (org-at-heading-p)
7965 ;; This is a heading: split intelligently (keeping
7966 ;; tags).
7967 (let ((pos (point)))
7968 (beginning-of-line)
7969 (let ((case-fold-search nil))
7970 (unless (looking-at org-complex-heading-regexp)
7971 (error "This should not happen")))
7972 (when (and (match-beginning 4)
7973 (> pos (match-beginning 4))
7974 (< pos (match-end 4)))
7975 (setq initial-content (buffer-substring pos (match-end 4)))
7976 (goto-char pos)
7977 (delete-region (point) (match-end 4))
7978 (if (looking-at "[ \t]*$")
7979 (replace-match "")
7980 (insert (make-string (length initial-content) ?\s)))
7981 (setq initial-content (org-trim initial-content)))
7982 (goto-char pos))
7983 ;; A normal line.
7984 (setq initial-content
7985 (org-trim
7986 (delete-and-extract-region (point) (line-end-position))))))
7988 ;; If we are at the beginning of the line, insert before it.
7989 ;; Otherwise, after it.
7990 (cond
7991 ((and (bolp) (looking-at "[ \t]*$")))
7992 ((bolp) (save-excursion (insert "\n")))
7993 (t (end-of-line)
7994 (insert "\n")))
7996 ;; Insert the new heading
7997 (insert stars)
7998 (just-one-space)
7999 (insert initial-content)
8000 (unless (and blank (org-previous-line-empty-p))
8001 (org-N-empty-lines-before-current (if blank 1 0)))
8002 ;; Adjust visibility, which may be messed up if we removed
8003 ;; blank lines while previous entry was hidden.
8004 (let ((bol (line-beginning-position)))
8005 (dolist (o (overlays-at (1- bol)))
8006 (when (and (eq (overlay-get o 'invisible) 'outline)
8007 (eq (overlay-end o) bol))
8008 (move-overlay o (overlay-start o) (1- bol)))))
8009 (run-hooks 'org-insert-heading-hook)))))))
8011 (defun org-N-empty-lines-before-current (N)
8012 "Make the number of empty lines before current exactly N.
8013 So this will delete or add empty lines."
8014 (save-excursion
8015 (beginning-of-line)
8016 (let ((p (point)))
8017 (skip-chars-backward " \r\t\n")
8018 (unless (bolp) (forward-line))
8019 (delete-region (point) p))
8020 (when (> N 0) (insert (make-string N ?\n)))))
8022 (defun org-get-heading (&optional no-tags no-todo)
8023 "Return the heading of the current entry, without the stars.
8024 When NO-TAGS is non-nil, don't include tags.
8025 When NO-TODO is non-nil, don't include TODO keywords."
8026 (save-excursion
8027 (org-back-to-heading t)
8028 (let ((case-fold-search nil))
8029 (cond
8030 ((and no-tags no-todo)
8031 (looking-at org-complex-heading-regexp)
8032 ;; Return value has to be a string, but match group 4 is
8033 ;; optional.
8034 (or (match-string 4) ""))
8035 (no-tags
8036 (looking-at (concat org-outline-regexp
8037 "\\(.*?\\)"
8038 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8039 (match-string 1))
8040 (no-todo
8041 (looking-at org-todo-line-regexp)
8042 (match-string 3))
8043 (t (looking-at org-heading-regexp)
8044 (match-string 2))))))
8046 (defvar orgstruct-mode) ; defined below
8048 (defun org-heading-components ()
8049 "Return the components of the current heading.
8050 This is a list with the following elements:
8051 - the level as an integer
8052 - the reduced level, different if `org-odd-levels-only' is set.
8053 - the TODO keyword, or nil
8054 - the priority character, like ?A, or nil if no priority is given
8055 - the headline text itself, or the tags string if no headline text
8056 - the tags string, or nil."
8057 (save-excursion
8058 (org-back-to-heading t)
8059 (when (let (case-fold-search)
8060 (looking-at
8061 (if orgstruct-mode
8062 org-heading-regexp
8063 org-complex-heading-regexp)))
8064 (if orgstruct-mode
8065 (list (length (match-string 1))
8066 (org-reduced-level (length (match-string 1)))
8069 (match-string 2)
8070 nil)
8071 (list (length (match-string 1))
8072 (org-reduced-level (length (match-string 1)))
8073 (match-string-no-properties 2)
8074 (and (match-end 3) (aref (match-string 3) 2))
8075 (match-string-no-properties 4)
8076 (match-string-no-properties 5))))))
8078 (defun org-get-entry ()
8079 "Get the entry text, after heading, entire subtree."
8080 (save-excursion
8081 (org-back-to-heading t)
8082 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8084 (defun org-edit-headline (&optional heading)
8085 "Edit the current headline.
8086 Set it to HEADING when provided."
8087 (interactive)
8088 (org-with-wide-buffer
8089 (org-back-to-heading t)
8090 (let ((case-fold-search nil))
8091 (when (looking-at org-complex-heading-regexp)
8092 (let* ((old (match-string-no-properties 4))
8093 (new (save-match-data
8094 (org-trim (or heading (read-string "Edit: " old))))))
8095 (unless (equal old new)
8096 (if old (replace-match new t t nil 4)
8097 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8098 (insert " " new))
8099 (org-set-tags nil t)
8100 (when (looking-at "[ \t]*$") (replace-match ""))))))))
8102 (defun org-insert-heading-after-current ()
8103 "Insert a new heading with same level as current, after current subtree."
8104 (interactive)
8105 (org-back-to-heading)
8106 (org-insert-heading)
8107 (org-move-subtree-down)
8108 (end-of-line 1))
8110 (defun org-insert-heading-respect-content (&optional invisible-ok)
8111 "Insert heading with `org-insert-heading-respect-content' set to t."
8112 (interactive)
8113 (org-insert-heading '(4) invisible-ok))
8115 (defun org-insert-todo-heading-respect-content (&optional force-state)
8116 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8117 (interactive)
8118 (org-insert-todo-heading force-state '(4)))
8120 (defun org-insert-todo-heading (arg &optional force-heading)
8121 "Insert a new heading with the same level and TODO state as current heading.
8123 If the heading has no TODO state, or if the state is DONE, use
8124 the first state (TODO by default). Also with one prefix arg,
8125 force first state. With two prefix args, force inserting at the
8126 end of the parent subtree.
8128 When called at a plain list item, insert a new item with an
8129 unchecked check box."
8130 (interactive "P")
8131 (when (or force-heading (not (org-insert-item 'checkbox)))
8132 (org-insert-heading (or (and (equal arg '(16)) '(16))
8133 force-heading))
8134 (save-excursion
8135 (org-back-to-heading)
8136 (outline-previous-heading)
8137 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
8138 (let* ((new-mark-x
8139 (if (or (equal arg '(4))
8140 (not (match-beginning 2))
8141 (member (match-string 2) org-done-keywords))
8142 (car org-todo-keywords-1)
8143 (match-string 2)))
8144 (new-mark
8146 (run-hook-with-args-until-success
8147 'org-todo-get-default-hook new-mark-x nil)
8148 new-mark-x)))
8149 (beginning-of-line 1)
8150 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8151 (if org-treat-insert-todo-heading-as-state-change
8152 (org-todo new-mark)
8153 (insert new-mark " "))))
8154 (when org-provide-todo-statistics
8155 (org-update-parent-todo-statistics))))
8157 (defun org-insert-subheading (arg)
8158 "Insert a new subheading and demote it.
8159 Works for outline headings and for plain lists alike."
8160 (interactive "P")
8161 (org-insert-heading arg)
8162 (cond
8163 ((org-at-heading-p) (org-do-demote))
8164 ((org-at-item-p) (org-indent-item))))
8166 (defun org-insert-todo-subheading (arg)
8167 "Insert a new subheading with TODO keyword or checkbox and demote it.
8168 Works for outline headings and for plain lists alike."
8169 (interactive "P")
8170 (org-insert-todo-heading arg)
8171 (cond
8172 ((org-at-heading-p) (org-do-demote))
8173 ((org-at-item-p) (org-indent-item))))
8175 ;;; Promotion and Demotion
8177 (defvar org-after-demote-entry-hook nil
8178 "Hook run after an entry has been demoted.
8179 The cursor will be at the beginning of the entry.
8180 When a subtree is being demoted, the hook will be called for each node.")
8182 (defvar org-after-promote-entry-hook nil
8183 "Hook run after an entry has been promoted.
8184 The cursor will be at the beginning of the entry.
8185 When a subtree is being promoted, the hook will be called for each node.")
8187 (defun org-promote-subtree ()
8188 "Promote the entire subtree.
8189 See also `org-promote'."
8190 (interactive)
8191 (save-excursion
8192 (org-with-limited-levels (org-map-tree 'org-promote)))
8193 (org-fix-position-after-promote))
8195 (defun org-demote-subtree ()
8196 "Demote the entire subtree.
8197 See `org-demote' and `org-promote'."
8198 (interactive)
8199 (save-excursion
8200 (org-with-limited-levels (org-map-tree 'org-demote)))
8201 (org-fix-position-after-promote))
8203 (defun org-do-promote ()
8204 "Promote the current heading higher up the tree.
8205 If the region is active in `transient-mark-mode', promote all
8206 headings in the region."
8207 (interactive)
8208 (save-excursion
8209 (if (org-region-active-p)
8210 (org-map-region 'org-promote (region-beginning) (region-end))
8211 (org-promote)))
8212 (org-fix-position-after-promote))
8214 (defun org-do-demote ()
8215 "Demote the current heading lower down the tree.
8216 If the region is active in `transient-mark-mode', demote all
8217 headings in the region."
8218 (interactive)
8219 (save-excursion
8220 (if (org-region-active-p)
8221 (org-map-region 'org-demote (region-beginning) (region-end))
8222 (org-demote)))
8223 (org-fix-position-after-promote))
8225 (defun org-fix-position-after-promote ()
8226 "Fix cursor position and indentation after demoting/promoting."
8227 (let ((pos (point)))
8228 (when (save-excursion
8229 (beginning-of-line)
8230 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8231 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8232 (cond ((eobp) (insert " "))
8233 ((eolp) (insert " "))
8234 ((equal (char-after) ?\s) (forward-char 1))))))
8236 (defun org-current-level ()
8237 "Return the level of the current entry, or nil if before the first headline.
8238 The level is the number of stars at the beginning of the
8239 headline. Use `org-reduced-level' to remove the effect of
8240 `org-odd-levels'. Unlike to `org-outline-level', this function
8241 ignores inlinetasks."
8242 (let ((level (org-with-limited-levels (org-outline-level))))
8243 (and (> level 0) level)))
8245 (defun org-get-previous-line-level ()
8246 "Return the outline depth of the last headline before the current line.
8247 Returns 0 for the first headline in the buffer, and nil if before the
8248 first headline."
8249 (and (org-current-level)
8250 (or (and (/= (line-beginning-position) (point-min))
8251 (save-excursion (beginning-of-line 0) (org-current-level)))
8252 0)))
8254 (defun org-reduced-level (l)
8255 "Compute the effective level of a heading.
8256 This takes into account the setting of `org-odd-levels-only'."
8257 (cond
8258 ((zerop l) 0)
8259 (org-odd-levels-only (1+ (floor (/ l 2))))
8260 (t l)))
8262 (defun org-level-increment ()
8263 "Return the number of stars that will be added or removed at a
8264 time to headlines when structure editing, based on the value of
8265 `org-odd-levels-only'."
8266 (if org-odd-levels-only 2 1))
8268 (defun org-get-valid-level (level &optional change)
8269 "Rectify a level change under the influence of `org-odd-levels-only'
8270 LEVEL is a current level, CHANGE is by how much the level should be
8271 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8272 even level numbers will become the next higher odd number."
8273 (if org-odd-levels-only
8274 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8275 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8276 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8277 (max 1 (+ level (or change 0)))))
8279 (defun org-promote ()
8280 "Promote the current heading higher up the tree."
8281 (org-with-wide-buffer
8282 (org-back-to-heading t)
8283 (let* ((after-change-functions (remq 'flyspell-after-change-function
8284 after-change-functions))
8285 (level (save-match-data (funcall outline-level)))
8286 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8287 (diff (abs (- level (length up-head) -1))))
8288 (cond
8289 ((and (= level 1) org-allow-promoting-top-level-subtree)
8290 (replace-match "# " nil t))
8291 ((= level 1)
8292 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8293 (t (replace-match up-head nil t)))
8294 (unless (= level 1)
8295 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8296 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8297 (run-hooks 'org-after-promote-entry-hook))))
8299 (defun org-demote ()
8300 "Demote the current heading lower down the tree."
8301 (org-with-wide-buffer
8302 (org-back-to-heading t)
8303 (let* ((after-change-functions (remq 'flyspell-after-change-function
8304 after-change-functions))
8305 (level (save-match-data (funcall outline-level)))
8306 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8307 (diff (abs (- level (length down-head) -1))))
8308 (replace-match down-head nil t)
8309 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8310 (when org-adapt-indentation (org-fixup-indentation diff))
8311 (run-hooks 'org-after-demote-entry-hook))))
8313 (defun org-cycle-level ()
8314 "Cycle the level of an empty headline through possible states.
8315 This goes first to child, then to parent, level, then up the hierarchy.
8316 After top level, it switches back to sibling level."
8317 (interactive)
8318 (let ((org-adapt-indentation nil))
8319 (when (org-point-at-end-of-empty-headline)
8320 (setq this-command 'org-cycle-level) ; Only needed for caching
8321 (let ((cur-level (org-current-level))
8322 (prev-level (org-get-previous-line-level)))
8323 (cond
8324 ;; If first headline in file, promote to top-level.
8325 ((= prev-level 0)
8326 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8327 do (org-do-promote)))
8328 ;; If same level as prev, demote one.
8329 ((= prev-level cur-level)
8330 (org-do-demote))
8331 ;; If parent is top-level, promote to top level if not already.
8332 ((= prev-level 1)
8333 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8334 do (org-do-promote)))
8335 ;; If top-level, return to prev-level.
8336 ((= cur-level 1)
8337 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8338 do (org-do-demote)))
8339 ;; If less than prev-level, promote one.
8340 ((< cur-level prev-level)
8341 (org-do-promote))
8342 ;; If deeper than prev-level, promote until higher than
8343 ;; prev-level.
8344 ((> cur-level prev-level)
8345 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8346 do (org-do-promote))))
8347 t))))
8349 (defun org-map-tree (fun)
8350 "Call FUN for every heading underneath the current one."
8351 (org-back-to-heading t)
8352 (let ((level (funcall outline-level)))
8353 (save-excursion
8354 (funcall fun)
8355 (while (and (progn
8356 (outline-next-heading)
8357 (> (funcall outline-level) level))
8358 (not (eobp)))
8359 (funcall fun)))))
8361 (defun org-map-region (fun beg end)
8362 "Call FUN for every heading between BEG and END."
8363 (let ((org-ignore-region t))
8364 (save-excursion
8365 (setq end (copy-marker end))
8366 (goto-char beg)
8367 (when (and (re-search-forward org-outline-regexp-bol nil t)
8368 (< (point) end))
8369 (funcall fun))
8370 (while (and (progn
8371 (outline-next-heading)
8372 (< (point) end))
8373 (not (eobp)))
8374 (funcall fun)))))
8376 (defun org-fixup-indentation (diff)
8377 "Change the indentation in the current entry by DIFF.
8379 DIFF is an integer. Indentation is done according to the
8380 following rules:
8382 - Planning information and property drawers are always indented
8383 according to the new level of the headline;
8385 - Footnote definitions and their contents are ignored;
8387 - Inlinetasks' boundaries are not shifted;
8389 - Empty lines are ignored;
8391 - Other lines' indentation are shifted by DIFF columns, unless
8392 it would introduce a structural change in the document, in
8393 which case no shifting is done at all.
8395 Assume point is at a heading or an inlinetask beginning."
8396 (org-with-wide-buffer
8397 (narrow-to-region (line-beginning-position)
8398 (save-excursion
8399 (if (org-with-limited-levels (org-at-heading-p))
8400 (org-with-limited-levels (outline-next-heading))
8401 (org-inlinetask-goto-end))
8402 (point)))
8403 (forward-line)
8404 ;; Indent properly planning info and property drawer.
8405 (when (looking-at-p org-planning-line-re)
8406 (org-indent-line)
8407 (forward-line))
8408 (when (looking-at org-property-drawer-re)
8409 (goto-char (match-end 0))
8410 (forward-line)
8411 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8412 (catch 'no-shift
8413 (when (zerop diff) (throw 'no-shift nil))
8414 ;; If DIFF is negative, first check if a shift is possible at all
8415 ;; (e.g., it doesn't break structure). This can only happen if
8416 ;; some contents are not properly indented.
8417 (let ((case-fold-search t))
8418 (when (< diff 0)
8419 (let ((diff (- diff))
8420 (forbidden-re (concat org-outline-regexp
8421 "\\|"
8422 (substring org-footnote-definition-re 1))))
8423 (save-excursion
8424 (while (not (eobp))
8425 (cond
8426 ((looking-at-p "[ \t]*$") (forward-line))
8427 ((and (looking-at-p org-footnote-definition-re)
8428 (let ((e (org-element-at-point)))
8429 (and (eq (org-element-type e) 'footnote-definition)
8430 (goto-char (org-element-property :end e))))))
8431 ((looking-at-p org-outline-regexp) (forward-line))
8432 ;; Give up if shifting would move before column 0 or
8433 ;; if it would introduce a headline or a footnote
8434 ;; definition.
8436 (skip-chars-forward " \t")
8437 (let ((ind (current-column)))
8438 (when (or (< ind diff)
8439 (and (= ind diff) (looking-at-p forbidden-re)))
8440 (throw 'no-shift nil)))
8441 ;; Ignore contents of example blocks and source
8442 ;; blocks if their indentation is meant to be
8443 ;; preserved. Jump to block's closing line.
8444 (beginning-of-line)
8445 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8446 (let ((e (org-element-at-point)))
8447 (and (memq (org-element-type e)
8448 '(example-block src-block))
8449 (or org-src-preserve-indentation
8450 (org-element-property :preserve-indent e))
8451 (goto-char (org-element-property :end e))
8452 (progn (skip-chars-backward " \r\t\n")
8453 (beginning-of-line)
8454 t))))
8455 (forward-line))))))))
8456 ;; Shift lines but footnote definitions, inlinetasks boundaries
8457 ;; by DIFF. Also skip contents of source or example blocks
8458 ;; when indentation is meant to be preserved.
8459 (while (not (eobp))
8460 (cond
8461 ((and (looking-at-p org-footnote-definition-re)
8462 (let ((e (org-element-at-point)))
8463 (and (eq (org-element-type e) 'footnote-definition)
8464 (goto-char (org-element-property :end e))))))
8465 ((looking-at-p org-outline-regexp) (forward-line))
8466 ((looking-at-p "[ \t]*$") (forward-line))
8468 (indent-line-to (+ (org-get-indentation) diff))
8469 (beginning-of-line)
8470 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8471 (let ((e (org-element-at-point)))
8472 (and (memq (org-element-type e)
8473 '(example-block src-block))
8474 (or org-src-preserve-indentation
8475 (org-element-property :preserve-indent e))
8476 (goto-char (org-element-property :end e))
8477 (progn (skip-chars-backward " \r\t\n")
8478 (beginning-of-line)
8479 t))))
8480 (forward-line)))))))))
8482 (defun org-convert-to-odd-levels ()
8483 "Convert an Org file with all levels allowed to one with odd levels.
8484 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8485 level 5 etc."
8486 (interactive)
8487 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8488 (let ((outline-level 'org-outline-level)
8489 (org-odd-levels-only nil) n)
8490 (save-excursion
8491 (goto-char (point-min))
8492 (while (re-search-forward "^\\*\\*+ " nil t)
8493 (setq n (- (length (match-string 0)) 2))
8494 (while (>= (setq n (1- n)) 0)
8495 (org-demote))
8496 (end-of-line 1))))))
8498 (defun org-convert-to-oddeven-levels ()
8499 "Convert an Org file with only odd levels to one with odd/even levels.
8500 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8501 file contains a section with an even level, conversion would
8502 destroy the structure of the file. An error is signaled in this
8503 case."
8504 (interactive)
8505 (goto-char (point-min))
8506 ;; First check if there are no even levels
8507 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8508 (org-show-set-visibility 'canonical)
8509 (error "Not all levels are odd in this file. Conversion not possible"))
8510 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8511 (let ((outline-regexp org-outline-regexp)
8512 (outline-level 'org-outline-level)
8513 (org-odd-levels-only nil) n)
8514 (save-excursion
8515 (goto-char (point-min))
8516 (while (re-search-forward "^\\*\\*+ " nil t)
8517 (setq n (/ (1- (length (match-string 0))) 2))
8518 (while (>= (setq n (1- n)) 0)
8519 (org-promote))
8520 (end-of-line 1))))))
8522 (defun org-tr-level (n)
8523 "Make N odd if required."
8524 (if org-odd-levels-only (1+ (/ n 2)) n))
8526 ;;; Vertical tree motion, cutting and pasting of subtrees
8528 (defun org-move-subtree-up (&optional arg)
8529 "Move the current subtree up past ARG headlines of the same level."
8530 (interactive "p")
8531 (org-move-subtree-down (- (prefix-numeric-value arg))))
8533 (defun org-move-subtree-down (&optional arg)
8534 "Move the current subtree down past ARG headlines of the same level."
8535 (interactive "p")
8536 (setq arg (prefix-numeric-value arg))
8537 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8538 'org-get-last-sibling))
8539 (ins-point (make-marker))
8540 (cnt (abs arg))
8541 (col (current-column))
8542 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8543 ;; Select the tree
8544 (org-back-to-heading)
8545 (setq beg0 (point))
8546 (save-excursion
8547 (setq ne-beg (org-back-over-empty-lines))
8548 (setq beg (point)))
8549 (save-match-data
8550 (save-excursion (outline-end-of-heading)
8551 (setq folded (org-invisible-p)))
8552 (progn (org-end-of-subtree nil t)
8553 (unless (eobp) (backward-char))))
8554 (outline-next-heading)
8555 (setq ne-end (org-back-over-empty-lines))
8556 (setq end (point))
8557 (goto-char beg0)
8558 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8559 ;; include less whitespace
8560 (save-excursion
8561 (goto-char beg)
8562 (forward-line (- ne-beg ne-end))
8563 (setq beg (point))))
8564 ;; Find insertion point, with error handling
8565 (while (> cnt 0)
8566 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8567 (progn (goto-char beg0)
8568 (user-error "Cannot move past superior level or buffer limit")))
8569 (setq cnt (1- cnt)))
8570 (when (> arg 0)
8571 ;; Moving forward - still need to move over subtree
8572 (org-end-of-subtree t t)
8573 (save-excursion
8574 (org-back-over-empty-lines)
8575 (or (bolp) (newline))))
8576 (setq ne-ins (org-back-over-empty-lines))
8577 (move-marker ins-point (point))
8578 (setq txt (buffer-substring beg end))
8579 (org-save-markers-in-region beg end)
8580 (delete-region beg end)
8581 (org-remove-empty-overlays-at beg)
8582 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8583 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8584 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8585 (let ((bbb (point)))
8586 (insert-before-markers txt)
8587 (org-reinstall-markers-in-region bbb)
8588 (move-marker ins-point bbb))
8589 (or (bolp) (insert "\n"))
8590 (setq ins-end (point))
8591 (goto-char ins-point)
8592 (org-skip-whitespace)
8593 (when (and (< arg 0)
8594 (org-first-sibling-p)
8595 (> ne-ins ne-beg))
8596 ;; Move whitespace back to beginning
8597 (save-excursion
8598 (goto-char ins-end)
8599 (let ((kill-whole-line t))
8600 (kill-line (- ne-ins ne-beg)) (point)))
8601 (insert (make-string (- ne-ins ne-beg) ?\n)))
8602 (move-marker ins-point nil)
8603 (if folded
8604 (outline-hide-subtree)
8605 (org-show-entry)
8606 (org-show-children)
8607 (org-cycle-hide-drawers 'children))
8608 (org-clean-visibility-after-subtree-move)
8609 ;; move back to the initial column we were at
8610 (move-to-column col)))
8612 (defvar org-subtree-clip ""
8613 "Clipboard for cut and paste of subtrees.
8614 This is actually only a copy of the kill, because we use the normal kill
8615 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8617 (defvar org-subtree-clip-folded nil
8618 "Was the last copied subtree folded?
8619 This is used to fold the tree back after pasting.")
8621 (defun org-cut-subtree (&optional n)
8622 "Cut the current subtree into the clipboard.
8623 With prefix arg N, cut this many sequential subtrees.
8624 This is a short-hand for marking the subtree and then cutting it."
8625 (interactive "p")
8626 (org-copy-subtree n 'cut))
8628 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8629 "Copy the current subtree it in the clipboard.
8630 With prefix arg N, copy this many sequential subtrees.
8631 This is a short-hand for marking the subtree and then copying it.
8632 If CUT is non-nil, actually cut the subtree.
8633 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8634 of some markers in the region, even if CUT is non-nil. This is
8635 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8636 (interactive "p")
8637 (let (beg end folded (beg0 (point)))
8638 (if (called-interactively-p 'any)
8639 (org-back-to-heading nil) ; take what looks like a subtree
8640 (org-back-to-heading t)) ; take what is really there
8641 (setq beg (point))
8642 (skip-chars-forward " \t\r\n")
8643 (save-match-data
8644 (if nosubtrees
8645 (outline-next-heading)
8646 (save-excursion (outline-end-of-heading)
8647 (setq folded (org-invisible-p)))
8648 (ignore-errors (org-forward-heading-same-level (1- n) t))
8649 (org-end-of-subtree t t)))
8650 ;; Include the end of an inlinetask
8651 (when (and (featurep 'org-inlinetask)
8652 (looking-at-p (concat (org-inlinetask-outline-regexp)
8653 "END[ \t]*$")))
8654 (end-of-line))
8655 (setq end (point))
8656 (goto-char beg0)
8657 (when (> end beg)
8658 (setq org-subtree-clip-folded folded)
8659 (when (or cut force-store-markers)
8660 (org-save-markers-in-region beg end))
8661 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8662 (setq org-subtree-clip (current-kill 0))
8663 (message "%s: Subtree(s) with %d characters"
8664 (if cut "Cut" "Copied")
8665 (length org-subtree-clip)))))
8667 (defun org-paste-subtree (&optional level tree for-yank remove)
8668 "Paste the clipboard as a subtree, with modification of headline level.
8669 The entire subtree is promoted or demoted in order to match a new headline
8670 level.
8672 If the cursor is at the beginning of a headline, the same level as
8673 that headline is used to paste the tree.
8675 If not, the new level is derived from the *visible* headings
8676 before and after the insertion point, and taken to be the inferior headline
8677 level of the two. So if the previous visible heading is level 3 and the
8678 next is level 4 (or vice versa), level 4 will be used for insertion.
8679 This makes sure that the subtree remains an independent subtree and does
8680 not swallow low level entries.
8682 You can also force a different level, either by using a numeric prefix
8683 argument, or by inserting the heading marker by hand. For example, if the
8684 cursor is after \"*****\", then the tree will be shifted to level 5.
8686 If optional TREE is given, use this text instead of the kill ring.
8688 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8689 move back over whitespace before inserting, and move point to the end of
8690 the inserted text when done.
8692 When REMOVE is non-nil, remove the subtree from the clipboard."
8693 (interactive "P")
8694 (setq tree (or tree (and kill-ring (current-kill 0))))
8695 (unless (org-kill-is-subtree-p tree)
8696 (user-error "%s"
8697 (substitute-command-keys
8698 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8699 (org-with-limited-levels
8700 (let* ((visp (not (org-invisible-p)))
8701 (txt tree)
8702 (^re_ "\\(\\*+\\)[ \t]*")
8703 (old-level (if (string-match org-outline-regexp-bol txt)
8704 (- (match-end 0) (match-beginning 0) 1)
8705 -1))
8706 (force-level (cond (level (prefix-numeric-value level))
8707 ((and (looking-at "[ \t]*$")
8708 (string-match
8709 "^\\*+$" (buffer-substring
8710 (point-at-bol) (point))))
8711 (- (match-end 0) (match-beginning 0)))
8712 ((and (bolp)
8713 (looking-at org-outline-regexp))
8714 (- (match-end 0) (point) 1))))
8715 (previous-level (save-excursion
8716 (condition-case nil
8717 (progn
8718 (outline-previous-visible-heading 1)
8719 (if (looking-at ^re_)
8720 (- (match-end 0) (match-beginning 0) 1)
8722 (error 1))))
8723 (next-level (save-excursion
8724 (condition-case nil
8725 (progn
8726 (or (looking-at org-outline-regexp)
8727 (outline-next-visible-heading 1))
8728 (if (looking-at ^re_)
8729 (- (match-end 0) (match-beginning 0) 1)
8731 (error 1))))
8732 (new-level (or force-level (max previous-level next-level)))
8733 (shift (if (or (= old-level -1)
8734 (= new-level -1)
8735 (= old-level new-level))
8737 (- new-level old-level)))
8738 (delta (if (> shift 0) -1 1))
8739 (func (if (> shift 0) 'org-demote 'org-promote))
8740 (org-odd-levels-only nil)
8741 beg end newend)
8742 ;; Remove the forced level indicator
8743 (when force-level
8744 (delete-region (point-at-bol) (point)))
8745 ;; Paste
8746 (beginning-of-line (if (bolp) 1 2))
8747 (setq beg (point))
8748 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8749 (insert-before-markers txt)
8750 (unless (string-suffix-p "\n" txt) (insert "\n"))
8751 (setq newend (point))
8752 (org-reinstall-markers-in-region beg)
8753 (setq end (point))
8754 (goto-char beg)
8755 (skip-chars-forward " \t\n\r")
8756 (setq beg (point))
8757 (when (and (org-invisible-p) visp)
8758 (save-excursion (outline-show-heading)))
8759 ;; Shift if necessary
8760 (unless (= shift 0)
8761 (save-restriction
8762 (narrow-to-region beg end)
8763 (while (not (= shift 0))
8764 (org-map-region func (point-min) (point-max))
8765 (setq shift (+ delta shift)))
8766 (goto-char (point-min))
8767 (setq newend (point-max))))
8768 (when (or (called-interactively-p 'interactive) for-yank)
8769 (message "Clipboard pasted as level %d subtree" new-level))
8770 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8771 kill-ring
8772 (eq org-subtree-clip (current-kill 0))
8773 org-subtree-clip-folded)
8774 ;; The tree was folded before it was killed/copied
8775 (outline-hide-subtree))
8776 (and for-yank (goto-char newend))
8777 (and remove (setq kill-ring (cdr kill-ring))))))
8779 (defun org-kill-is-subtree-p (&optional txt)
8780 "Check if the current kill is an outline subtree, or a set of trees.
8781 Returns nil if kill does not start with a headline, or if the first
8782 headline level is not the largest headline level in the tree.
8783 So this will actually accept several entries of equal levels as well,
8784 which is OK for `org-paste-subtree'.
8785 If optional TXT is given, check this string instead of the current kill."
8786 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8787 (re (org-get-limited-outline-regexp))
8788 (^re (concat "^" re))
8789 (start-level (and kill
8790 (string-match
8791 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8792 kill)
8793 (- (match-end 2) (match-beginning 2) 1)))
8794 (start (1+ (or (match-beginning 2) -1))))
8795 (if (not start-level)
8796 (progn
8797 nil) ;; does not even start with a heading
8798 (catch 'exit
8799 (while (setq start (string-match ^re kill (1+ start)))
8800 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8801 (throw 'exit nil)))
8802 t))))
8804 (defvar org-markers-to-move nil
8805 "Markers that should be moved with a cut-and-paste operation.
8806 Those markers are stored together with their positions relative to
8807 the start of the region.")
8809 (defun org-save-markers-in-region (beg end)
8810 "Check markers in region.
8811 If these markers are between BEG and END, record their position relative
8812 to BEG, so that after moving the block of text, we can put the markers back
8813 into place.
8814 This function gets called just before an entry or tree gets cut from the
8815 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8816 called immediately, to move the markers with the entries."
8817 (setq org-markers-to-move nil)
8818 (when (featurep 'org-clock)
8819 (org-clock-save-markers-for-cut-and-paste beg end))
8820 (when (featurep 'org-agenda)
8821 (org-agenda-save-markers-for-cut-and-paste beg end)))
8823 (defun org-check-and-save-marker (marker beg end)
8824 "Check if MARKER is between BEG and END.
8825 If yes, remember the marker and the distance to BEG."
8826 (when (and (marker-buffer marker)
8827 (equal (marker-buffer marker) (current-buffer))
8828 (>= marker beg) (< marker end))
8829 (push (cons marker (- marker beg)) org-markers-to-move)))
8831 (defun org-reinstall-markers-in-region (beg)
8832 "Move all remembered markers to their position relative to BEG."
8833 (dolist (x org-markers-to-move)
8834 (move-marker (car x) (+ beg (cdr x))))
8835 (setq org-markers-to-move nil))
8837 (defun org-narrow-to-subtree ()
8838 "Narrow buffer to the current subtree."
8839 (interactive)
8840 (save-excursion
8841 (save-match-data
8842 (org-with-limited-levels
8843 (narrow-to-region
8844 (progn (org-back-to-heading t) (point))
8845 (progn (org-end-of-subtree t t)
8846 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8847 (point)))))))
8849 (defun org-narrow-to-block ()
8850 "Narrow buffer to the current block."
8851 (interactive)
8852 (let* ((case-fold-search t)
8853 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8854 "^[ \t]*#\\+end_.*")))
8855 (if blockp
8856 (narrow-to-region (car blockp) (cdr blockp))
8857 (user-error "Not in a block"))))
8859 (defun org-clone-subtree-with-time-shift (n &optional shift)
8860 "Clone the task (subtree) at point N times.
8861 The clones will be inserted as siblings.
8863 In interactive use, the user will be prompted for the number of
8864 clones to be produced. If the entry has a timestamp, the user
8865 will also be prompted for a time shift, which may be a repeater
8866 as used in time stamps, for example `+3d'. To disable this,
8867 you can call the function with a universal prefix argument.
8869 When a valid repeater is given and the entry contains any time
8870 stamps, the clones will become a sequence in time, with time
8871 stamps in the subtree shifted for each clone produced. If SHIFT
8872 is nil or the empty string, time stamps will be left alone. The
8873 ID property of the original subtree is removed.
8875 In each clone, all the CLOCK entries will be removed. This
8876 prevents Org from considering that the clocked times overlap.
8878 If the original subtree did contain time stamps with a repeater,
8879 the following will happen:
8880 - the repeater will be removed in each clone
8881 - an additional clone will be produced, with the current, unshifted
8882 date(s) in the entry.
8883 - the original entry will be placed *after* all the clones, with
8884 repeater intact.
8885 - the start days in the repeater in the original entry will be shifted
8886 to past the last clone.
8887 In this way you can spell out a number of instances of a repeating task,
8888 and still retain the repeater to cover future instances of the task.
8890 As described above, N+1 clones are produced when the original
8891 subtree has a repeater. Setting N to 0, then, can be used to
8892 remove the repeater from a subtree and create a shifted clone
8893 with the original repeater."
8894 (interactive "nNumber of clones to produce: ")
8895 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8896 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8897 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8898 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8899 (shift
8900 (or shift
8901 (if (and (not (equal current-prefix-arg '(4)))
8902 (save-excursion
8903 (goto-char beg)
8904 (re-search-forward org-ts-regexp-both end-of-tree t)))
8905 (read-from-minibuffer
8906 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8907 ""))) ;No time shift
8908 (doshift
8909 (and (org-string-nw-p shift)
8910 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8911 shift)
8912 (user-error "Invalid shift specification %s" shift)))))
8913 (goto-char end-of-tree)
8914 (unless (bolp) (insert "\n"))
8915 (let* ((end (point))
8916 (template (buffer-substring beg end))
8917 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8918 (shift-what (pcase (and doshift (match-string 2 shift))
8919 (`nil nil)
8920 ("d" 'day)
8921 ("w" (setq shift-n (* 7 shift-n)) 'day)
8922 ("m" 'month)
8923 ("y" 'year)
8924 (_ (error "Unsupported time unit"))))
8925 (nmin 1)
8926 (nmax n)
8927 (n-no-remove -1)
8928 (idprop (org-entry-get nil "ID")))
8929 (when (and doshift
8930 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8931 template))
8932 (delete-region beg end)
8933 (setq end beg)
8934 (setq nmin 0)
8935 (setq nmax (1+ nmax))
8936 (setq n-no-remove nmax))
8937 (goto-char end)
8938 (cl-loop for n from nmin to nmax do
8939 (insert
8940 ;; Prepare clone.
8941 (with-temp-buffer
8942 (insert template)
8943 (org-mode)
8944 (goto-char (point-min))
8945 (org-show-subtree)
8946 (and idprop (if org-clone-delete-id
8947 (org-entry-delete nil "ID")
8948 (org-id-get-create t)))
8949 (unless (= n 0)
8950 (while (re-search-forward org-clock-line-re nil t)
8951 (delete-region (line-beginning-position)
8952 (line-beginning-position 2)))
8953 (goto-char (point-min))
8954 (while (re-search-forward org-drawer-regexp nil t)
8955 (org-remove-empty-drawer-at (point))))
8956 (goto-char (point-min))
8957 (when doshift
8958 (while (re-search-forward org-ts-regexp-both nil t)
8959 (org-timestamp-change (* n shift-n) shift-what))
8960 (unless (= n n-no-remove)
8961 (goto-char (point-min))
8962 (while (re-search-forward org-ts-regexp nil t)
8963 (save-excursion
8964 (goto-char (match-beginning 0))
8965 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8966 (delete-region (match-beginning 1) (match-end 1)))))))
8967 (buffer-string)))))
8968 (goto-char beg)))
8970 ;;; Outline Sorting
8972 (defun org-sort (with-case)
8973 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8974 Optional argument WITH-CASE means sort case-sensitively."
8975 (interactive "P")
8976 (cond
8977 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8978 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8980 (org-call-with-arg 'org-sort-entries with-case))))
8982 (defun org-sort-remove-invisible (s)
8983 "Remove invisible links from string S."
8984 (remove-text-properties 0 (length s) org-rm-props s)
8985 (while (string-match org-bracket-link-regexp s)
8986 (setq s (replace-match (if (match-end 2)
8987 (match-string 3 s)
8988 (match-string 1 s))
8989 t t s)))
8990 (let ((st (format " %s " s)))
8991 (while (string-match org-emph-re st)
8992 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8993 (setq s (substring st 1 -1)))
8996 (defvar org-priority-regexp) ; defined later in the file
8998 (defvar org-after-sorting-entries-or-items-hook nil
8999 "Hook that is run after a bunch of entries or items have been sorted.
9000 When children are sorted, the cursor is in the parent line when this
9001 hook gets called. When a region or a plain list is sorted, the cursor
9002 will be in the first entry of the sorted region/list.")
9004 (defun org-sort-entries
9005 (&optional with-case sorting-type getkey-func compare-func property
9006 interactive?)
9007 "Sort entries on a certain level of an outline tree.
9008 If there is an active region, the entries in the region are sorted.
9009 Else, if the cursor is before the first entry, sort the top-level items.
9010 Else, the children of the entry at point are sorted.
9012 Sorting can be alphabetically, numerically, by date/time as given by
9013 a time stamp, by a property, by priority order, or by a custom function.
9015 The command prompts for the sorting type unless it has been given to the
9016 function through the SORTING-TYPE argument, which needs to be a character,
9017 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9018 the precise meaning of each character:
9020 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9021 c By creation time, which is assumed to be the first inactive time stamp
9022 at the beginning of a line.
9023 d By deadline date/time.
9024 k By clocking time.
9025 n Numerically, by converting the beginning of the entry/item to a number.
9026 o By order of TODO keywords.
9027 p By priority according to the cookie.
9028 r By the value of a property.
9029 s By scheduled date/time.
9030 t By date/time, either the first active time stamp in the entry, or, if
9031 none exist, by the first inactive one.
9033 Capital letters will reverse the sort order.
9035 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9036 called with point at the beginning of the record. It must return a
9037 value that is compatible with COMPARE-FUNC, the function used to
9038 compare entries.
9040 Comparing entries ignores case by default. However, with an optional argument
9041 WITH-CASE, the sorting considers case as well.
9043 Sorting is done against the visible part of the headlines, it ignores hidden
9044 links.
9046 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
9048 A non-nil value for INTERACTIVE? is used to signal that this
9049 function is being called interactively."
9050 (interactive (list current-prefix-arg nil nil nil nil t))
9051 (let ((case-func (if with-case 'identity 'downcase))
9052 (cmstr
9053 ;; The clock marker is lost when using `sort-subr', let's
9054 ;; store the clocking string.
9055 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9056 (save-excursion
9057 (goto-char org-clock-marker)
9058 (buffer-substring-no-properties (line-beginning-position)
9059 (point)))))
9060 start beg end stars re re2
9061 txt what tmp)
9062 ;; Find beginning and end of region to sort
9063 (cond
9064 ((org-region-active-p)
9065 ;; we will sort the region
9066 (setq end (region-end)
9067 what "region")
9068 (goto-char (region-beginning))
9069 (unless (org-at-heading-p) (outline-next-heading))
9070 (setq start (point)))
9071 ((or (org-at-heading-p)
9072 (ignore-errors (progn (org-back-to-heading) t)))
9073 ;; we will sort the children of the current headline
9074 (org-back-to-heading)
9075 (setq start (point)
9076 end (progn (org-end-of-subtree t t)
9077 (or (bolp) (insert "\n"))
9078 (when (>= (org-back-over-empty-lines) 1)
9079 (forward-line 1))
9080 (point))
9081 what "children")
9082 (goto-char start)
9083 (outline-show-subtree)
9084 (outline-next-heading))
9086 ;; we will sort the top-level entries in this file
9087 (goto-char (point-min))
9088 (or (org-at-heading-p) (outline-next-heading))
9089 (setq start (point))
9090 (goto-char (point-max))
9091 (beginning-of-line 1)
9092 (when (looking-at ".*?\\S-")
9093 ;; File ends in a non-white line
9094 (end-of-line 1)
9095 (insert "\n"))
9096 (setq end (point-max))
9097 (setq what "top-level")
9098 (goto-char start)
9099 (outline-show-all)))
9101 (setq beg (point))
9102 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9104 (looking-at "\\(\\*+\\)")
9105 (setq stars (match-string 1)
9106 re (concat "^" (regexp-quote stars) " +")
9107 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9108 txt (buffer-substring beg end))
9109 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9110 (when (and (not (equal stars "*")) (string-match re2 txt))
9111 (user-error "Region to sort contains a level above the first entry"))
9113 (unless sorting-type
9114 (message
9115 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9116 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9117 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9118 what)
9119 (setq sorting-type (read-char-exclusive)))
9121 (unless getkey-func
9122 (and (= (downcase sorting-type) ?f)
9123 (setq getkey-func
9124 (or (and interactive?
9125 (org-read-function
9126 "Function for extracting keys: "))
9127 (error "Missing key extractor")))))
9129 (and (= (downcase sorting-type) ?r)
9130 (not property)
9131 (setq property
9132 (completing-read "Property: "
9133 (mapcar #'list (org-buffer-property-keys t))
9134 nil t)))
9136 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9137 (message "Sorting entries...")
9139 (save-restriction
9140 (narrow-to-region start end)
9141 (let ((dcst (downcase sorting-type))
9142 (case-fold-search nil)
9143 (now (current-time)))
9144 (sort-subr
9145 (/= dcst sorting-type)
9146 ;; This function moves to the beginning character of the "record" to
9147 ;; be sorted.
9148 (lambda nil
9149 (if (re-search-forward re nil t)
9150 (goto-char (match-beginning 0))
9151 (goto-char (point-max))))
9152 ;; This function moves to the last character of the "record" being
9153 ;; sorted.
9154 (lambda nil
9155 (save-match-data
9156 (condition-case nil
9157 (outline-forward-same-level 1)
9158 (error
9159 (goto-char (point-max))))))
9160 ;; This function returns the value that gets sorted against.
9161 (lambda nil
9162 (cond
9163 ((= dcst ?n)
9164 (if (looking-at org-complex-heading-regexp)
9165 (string-to-number (org-sort-remove-invisible (match-string 4)))
9166 nil))
9167 ((= dcst ?a)
9168 (if (looking-at org-complex-heading-regexp)
9169 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9170 nil))
9171 ((= dcst ?k)
9172 (or (get-text-property (point) :org-clock-minutes) 0))
9173 ((= dcst ?t)
9174 (let ((end (save-excursion (outline-next-heading) (point))))
9175 (if (or (re-search-forward org-ts-regexp end t)
9176 (re-search-forward org-ts-regexp-both end t))
9177 (org-time-string-to-seconds (match-string 0))
9178 (float-time now))))
9179 ((= dcst ?c)
9180 (let ((end (save-excursion (outline-next-heading) (point))))
9181 (if (re-search-forward
9182 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9183 end t)
9184 (org-time-string-to-seconds (match-string 0))
9185 (float-time now))))
9186 ((= dcst ?s)
9187 (let ((end (save-excursion (outline-next-heading) (point))))
9188 (if (re-search-forward org-scheduled-time-regexp end t)
9189 (org-time-string-to-seconds (match-string 1))
9190 (float-time now))))
9191 ((= dcst ?d)
9192 (let ((end (save-excursion (outline-next-heading) (point))))
9193 (if (re-search-forward org-deadline-time-regexp end t)
9194 (org-time-string-to-seconds (match-string 1))
9195 (float-time now))))
9196 ((= dcst ?p)
9197 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9198 (string-to-char (match-string 2))
9199 org-default-priority))
9200 ((= dcst ?r)
9201 (or (org-entry-get nil property) ""))
9202 ((= dcst ?o)
9203 (when (looking-at org-complex-heading-regexp)
9204 (let* ((m (match-string 2))
9205 (s (if (member m org-done-keywords) '- '+)))
9206 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9207 ((= dcst ?f)
9208 (if getkey-func
9209 (progn
9210 (setq tmp (funcall getkey-func))
9211 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9212 tmp)
9213 (error "Invalid key function `%s'" getkey-func)))
9214 (t (error "Invalid sorting type `%c'" sorting-type))))
9216 (cond
9217 ((= dcst ?a) 'string<)
9218 ((= dcst ?f)
9219 (or compare-func
9220 (and interactive?
9221 (org-read-function
9222 (concat "Function for comparing keys "
9223 "(empty for default `sort-subr' predicate): ")
9224 'allow-empty))))
9225 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9226 (run-hooks 'org-after-sorting-entries-or-items-hook)
9227 ;; Reset the clock marker if needed
9228 (when cmstr
9229 (save-excursion
9230 (goto-char start)
9231 (search-forward cmstr nil t)
9232 (move-marker org-clock-marker (point))))
9233 (message "Sorting entries...done")))
9235 ;;; The orgstruct minor mode
9237 ;; Define a minor mode which can be used in other modes in order to
9238 ;; integrate the Org mode structure editing commands.
9240 ;; This is really a hack, because the Org mode structure commands use
9241 ;; keys which normally belong to the major mode. Here is how it
9242 ;; works: The minor mode defines all the keys necessary to operate the
9243 ;; structure commands, but wraps the commands into a function which
9244 ;; tests if the cursor is currently at a headline or a plain list
9245 ;; item. If that is the case, the structure command is used,
9246 ;; temporarily setting many Org mode variables like regular
9247 ;; expressions for filling etc. However, when any of those keys is
9248 ;; used at a different location, function uses `key-binding' to look
9249 ;; up if the key has an associated command in another currently active
9250 ;; keymap (minor modes, major mode, global), and executes that
9251 ;; command. There might be problems if any of the keys is otherwise
9252 ;; used as a prefix key.
9254 (defcustom orgstruct-heading-prefix-regexp ""
9255 "Regexp that matches the custom prefix of Org headlines in
9256 orgstruct(++)-mode."
9257 :group 'org
9258 :version "24.4"
9259 :package-version '(Org . "8.3")
9260 :type 'regexp)
9261 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9263 (defcustom orgstruct-setup-hook nil
9264 "Hook run after orgstruct-mode-map is filled."
9265 :group 'org
9266 :version "24.4"
9267 :package-version '(Org . "8.0")
9268 :type 'hook)
9270 (defvar orgstruct-initialized nil)
9272 (defvar org-local-vars nil
9273 "List of local variables, for use by `orgstruct-mode'.")
9275 ;;;###autoload
9276 (define-minor-mode orgstruct-mode
9277 "Toggle the minor mode `orgstruct-mode'.
9278 This mode is for using Org mode structure commands in other
9279 modes. The following keys behave as if Org mode were active, if
9280 the cursor is on a headline, or on a plain list item (both as
9281 defined by Org mode)."
9282 nil " OrgStruct" (make-sparse-keymap)
9283 (funcall (if orgstruct-mode
9284 'add-to-invisibility-spec
9285 'remove-from-invisibility-spec)
9286 '(outline . t))
9287 (when orgstruct-mode
9288 (org-load-modules-maybe)
9289 (unless orgstruct-initialized
9290 (orgstruct-setup)
9291 (setq orgstruct-initialized t))))
9293 ;;;###autoload
9294 (defun turn-on-orgstruct ()
9295 "Unconditionally turn on `orgstruct-mode'."
9296 (orgstruct-mode 1))
9298 (defvar-local orgstruct-is-++ nil
9299 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9300 (defvar-local org-fb-vars nil)
9301 (defun orgstruct++-mode (&optional arg)
9302 "Toggle `orgstruct-mode', the enhanced version of it.
9303 In addition to setting orgstruct-mode, this also exports all
9304 indentation and autofilling variables from Org mode into the
9305 buffer. It will also recognize item context in multiline items."
9306 (interactive "P")
9307 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9308 (if (< arg 1)
9309 (progn (orgstruct-mode -1)
9310 (dolist (v org-fb-vars)
9311 (set (make-local-variable (car v))
9312 (if (eq (car-safe (cadr v)) 'quote)
9313 (cl-cadadr v)
9314 (nth 1 v)))))
9315 (orgstruct-mode 1)
9316 (setq org-fb-vars nil)
9317 (unless org-local-vars
9318 (setq org-local-vars (org-get-local-variables)))
9319 (let (var val)
9320 (dolist (x org-local-vars)
9321 (when (string-match
9322 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9323 \\|fill-prefix\\|indent-\\)"
9324 (symbol-name (car x)))
9325 (setq var (car x) val (nth 1 x))
9326 (push (list var `(quote ,(eval var))) org-fb-vars)
9327 (set (make-local-variable var)
9328 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9329 (setq-local orgstruct-is-++ t))))
9331 ;;;###autoload
9332 (defun turn-on-orgstruct++ ()
9333 "Unconditionally turn on `orgstruct++-mode'."
9334 (orgstruct++-mode 1))
9336 (defun orgstruct-error ()
9337 "Error when there is no default binding for a structure key."
9338 (interactive)
9339 (funcall (if (fboundp 'user-error)
9340 'user-error
9341 'error)
9342 "This key has no function outside structure elements"))
9344 (defun orgstruct-setup ()
9345 "Setup orgstruct keymap."
9346 (dolist (cell '((org-demote . t)
9347 (org-metaleft . t)
9348 (org-metaright . t)
9349 (org-promote . t)
9350 (org-shiftmetaleft . t)
9351 (org-shiftmetaright . t)
9352 org-backward-element
9353 org-backward-heading-same-level
9354 org-ctrl-c-ret
9355 org-ctrl-c-minus
9356 org-ctrl-c-star
9357 org-cycle
9358 org-force-cycle-archived
9359 org-forward-heading-same-level
9360 org-insert-heading
9361 org-insert-heading-respect-content
9362 org-kill-note-or-show-branches
9363 org-mark-subtree
9364 org-meta-return
9365 org-metadown
9366 org-metaup
9367 org-narrow-to-subtree
9368 org-promote-subtree
9369 org-reveal
9370 org-shiftdown
9371 org-shiftleft
9372 org-shiftmetadown
9373 org-shiftmetaup
9374 org-shiftright
9375 org-shifttab
9376 org-shifttab
9377 org-shiftup
9378 org-show-children
9379 org-show-subtree
9380 org-sort
9381 org-up-element
9382 outline-demote
9383 outline-next-visible-heading
9384 outline-previous-visible-heading
9385 outline-promote
9386 outline-up-heading))
9387 (let ((f (or (car-safe cell) cell))
9388 (disable-when-heading-prefix (cdr-safe cell)))
9389 (when (fboundp f)
9390 (let ((new-bindings))
9391 (dolist (binding (nconc (where-is-internal f org-mode-map)
9392 (where-is-internal f outline-mode-map)))
9393 (push binding new-bindings)
9394 ;; TODO use local-function-key-map
9395 (dolist (rep '(("<tab>" . "TAB")
9396 ("<return>" . "RET")
9397 ("<escape>" . "ESC")
9398 ("<delete>" . "DEL")))
9399 (setq binding (read-kbd-macro
9400 (let ((case-fold-search))
9401 (replace-regexp-in-string
9402 (regexp-quote (cdr rep))
9403 (car rep)
9404 (key-description binding)))))
9405 (cl-pushnew binding new-bindings :test 'equal)))
9406 (dolist (binding new-bindings)
9407 (let ((key (lookup-key orgstruct-mode-map binding)))
9408 (when (or (not key) (numberp key))
9409 (ignore-errors
9410 (org-defkey orgstruct-mode-map
9411 binding
9412 (orgstruct-make-binding
9413 f binding disable-when-heading-prefix))))))))))
9414 (run-hooks 'orgstruct-setup-hook))
9416 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9417 "Create a function for binding in the structure minor mode.
9418 FUN is the command to call inside a table. KEY is the key that
9419 should be checked in for a command to execute outside of tables.
9420 Non-nil `disable-when-heading-prefix' means to disable the command
9421 if `orgstruct-heading-prefix-regexp' is not empty."
9422 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9423 (let ((nname name)
9424 (i 0))
9425 (while (fboundp (intern nname))
9426 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9427 (setq name (intern nname)))
9428 (eval
9429 (let ((bindings '((org-heading-regexp
9430 (concat "^"
9431 orgstruct-heading-prefix-regexp
9432 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9433 (org-outline-regexp
9434 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9435 (org-outline-regexp-bol
9436 (concat "^" org-outline-regexp))
9437 (outline-regexp org-outline-regexp)
9438 (outline-heading-end-regexp "\n")
9439 (outline-level 'org-outline-level)
9440 (outline-heading-alist))))
9441 `(defun ,name (arg)
9442 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9443 "Outside of structure, run the binding of `"
9444 (key-description key) "'."
9445 (when disable-when-heading-prefix
9446 (concat
9447 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9448 "back to the default binding due to limitations of Org's implementation of\n"
9449 "`" (symbol-name fun) "'.")))
9450 (interactive "p")
9451 (let* ((disable
9452 ,(and disable-when-heading-prefix
9453 '(not (string= orgstruct-heading-prefix-regexp ""))))
9454 (fallback
9455 (or disable
9456 (not
9457 (let* ,bindings
9458 (org-context-p 'headline 'item
9459 ,(when (memq fun
9460 '(org-insert-heading
9461 org-insert-heading-respect-content
9462 org-meta-return))
9463 '(when orgstruct-is-++
9464 'item-body))))))))
9465 (if fallback
9466 (let* ((orgstruct-mode)
9467 (binding
9468 (let ((key ,key))
9469 (catch 'exit
9470 (dolist
9471 (rep
9472 '(nil
9473 ("<\\([^>]*\\)tab>" . "\\1TAB")
9474 ("<\\([^>]*\\)return>" . "\\1RET")
9475 ("<\\([^>]*\\)escape>" . "\\1ESC")
9476 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9477 nil)
9478 (when rep
9479 (setq key (read-kbd-macro
9480 (let ((case-fold-search))
9481 (replace-regexp-in-string
9482 (car rep)
9483 (cdr rep)
9484 (key-description key))))))
9485 (when (key-binding key)
9486 (throw 'exit (key-binding key))))))))
9487 (if (keymapp binding)
9488 (org-set-transient-map binding)
9489 (let ((func (or binding
9490 (unless disable
9491 'orgstruct-error))))
9492 (when func
9493 (call-interactively func)))))
9494 (org-run-like-in-org-mode
9495 (lambda ()
9496 (interactive)
9497 (let* ,bindings
9498 (call-interactively ',fun)))))))))
9499 name))
9501 (defun org-contextualize-keys (alist contexts)
9502 "Return valid elements in ALIST depending on CONTEXTS.
9504 `org-agenda-custom-commands' or `org-capture-templates' are the
9505 values used for ALIST, and `org-agenda-custom-commands-contexts'
9506 or `org-capture-templates-contexts' are the associated contexts
9507 definitions."
9508 (let ((contexts
9509 ;; normalize contexts
9510 (mapcar
9511 (lambda(c) (cond ((listp (cadr c))
9512 (list (car c) (car c) (nth 1 c)))
9513 ((string= "" (cadr c))
9514 (list (car c) (car c) (nth 2 c)))
9515 (t c)))
9516 contexts))
9517 (a alist) r s)
9518 ;; loop over all commands or templates
9519 (dolist (c a)
9520 (let (vrules repl)
9521 (cond
9522 ((not (assoc (car c) contexts))
9523 (push c r))
9524 ((and (assoc (car c) contexts)
9525 (setq vrules (org-contextualize-validate-key
9526 (car c) contexts)))
9527 (mapc (lambda (vr)
9528 (unless (equal (car vr) (cadr vr))
9529 (setq repl vr)))
9530 vrules)
9531 (if (not repl) (push c r)
9532 (push (cadr repl) s)
9533 (push
9534 (cons (car c)
9535 (cdr (or (assoc (cadr repl) alist)
9536 (error "Undefined key `%s' as contextual replacement for `%s'"
9537 (cadr repl) (car c)))))
9538 r))))))
9539 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9540 (delq
9542 (delete-dups
9543 (mapcar (lambda (x)
9544 (let ((tpl (car x)))
9545 (unless (delq
9547 (mapcar (lambda (y)
9548 (equal y tpl))
9550 x)))
9551 (reverse r))))))
9553 (defun org-contextualize-validate-key (key contexts)
9554 "Check CONTEXTS for agenda or capture KEY."
9555 (let (res)
9556 (dolist (r contexts)
9557 (dolist (rr (car (last r)))
9558 (when
9559 (and (equal key (car r))
9560 (if (functionp rr) (funcall rr)
9561 (or (and (eq (car rr) 'in-file)
9562 (buffer-file-name)
9563 (string-match (cdr rr) (buffer-file-name)))
9564 (and (eq (car rr) 'in-mode)
9565 (string-match (cdr rr) (symbol-name major-mode)))
9566 (and (eq (car rr) 'in-buffer)
9567 (string-match (cdr rr) (buffer-name)))
9568 (when (and (eq (car rr) 'not-in-file)
9569 (buffer-file-name))
9570 (not (string-match (cdr rr) (buffer-file-name))))
9571 (when (eq (car rr) 'not-in-mode)
9572 (not (string-match (cdr rr) (symbol-name major-mode))))
9573 (when (eq (car rr) 'not-in-buffer)
9574 (not (string-match (cdr rr) (buffer-name)))))))
9575 (push r res))))
9576 (delete-dups (delq nil res))))
9578 (defun org-context-p (&rest contexts)
9579 "Check if local context is any of CONTEXTS.
9580 Possible values in the list of contexts are `table', `headline', and `item'."
9581 (let ((pos (point)))
9582 (goto-char (point-at-bol))
9583 (prog1 (or (and (memq 'table contexts)
9584 (looking-at "[ \t]*|"))
9585 (and (memq 'headline contexts)
9586 (looking-at org-outline-regexp))
9587 (and (memq 'item contexts)
9588 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9589 (and (memq 'item-body contexts)
9590 (org-in-item-p)))
9591 (goto-char pos))))
9593 (defconst org-unique-local-variables
9594 '(org-element--cache
9595 org-element--cache-objects
9596 org-element--cache-sync-keys
9597 org-element--cache-sync-requests
9598 org-element--cache-sync-timer)
9599 "List of local variables that cannot be transferred to another buffer.")
9601 (defun org-get-local-variables ()
9602 "Return a list of all local variables in an Org mode buffer."
9603 (delq nil
9604 (mapcar
9605 (lambda (x)
9606 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9607 (name (car binding)))
9608 (and (not (get name 'org-state))
9609 (not (memq name org-unique-local-variables))
9610 (string-match-p
9611 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9612 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9613 (symbol-name name))
9614 binding)))
9615 (with-temp-buffer
9616 (org-mode)
9617 (buffer-local-variables)))))
9619 (defun org-clone-local-variables (from-buffer &optional regexp)
9620 "Clone local variables from FROM-BUFFER.
9621 Optional argument REGEXP selects variables to clone."
9622 (dolist (pair (buffer-local-variables from-buffer))
9623 (pcase pair
9624 (`(,name . ,value) ;ignore unbound variables
9625 (when (and (not (memq name org-unique-local-variables))
9626 (or (null regexp) (string-match-p regexp (symbol-name name))))
9627 (set (make-local-variable name) value))))))
9629 ;;;###autoload
9630 (defun org-run-like-in-org-mode (cmd)
9631 "Run a command, pretending that the current buffer is in Org mode.
9632 This will temporarily bind local variables that are typically bound in
9633 Org mode to the values they have in Org mode, and then interactively
9634 call CMD."
9635 (org-load-modules-maybe)
9636 (unless org-local-vars
9637 (setq org-local-vars (org-get-local-variables)))
9638 (let (binds)
9639 (dolist (var org-local-vars)
9640 (when (or (not (boundp (car var)))
9641 (eq (symbol-value (car var))
9642 (default-value (car var))))
9643 (push (list (car var) `(quote ,(cadr var))) binds)))
9644 (eval `(let ,binds
9645 (call-interactively (quote ,cmd))))))
9647 (defun org-get-category (&optional pos force-refresh)
9648 "Get the category applying to position POS."
9649 (save-match-data
9650 (when force-refresh (org-refresh-category-properties))
9651 (let ((pos (or pos (point))))
9652 (or (get-text-property pos 'org-category)
9653 (progn (org-refresh-category-properties)
9654 (get-text-property pos 'org-category))))))
9656 ;;; Refresh properties
9658 (defun org-refresh-properties (dprop tprop)
9659 "Refresh buffer text properties.
9660 DPROP is the drawer property and TPROP is either the
9661 corresponding text property to set, or an alist with each element
9662 being a text property (as a symbol) and a function to apply to
9663 the value of the drawer property."
9664 (let* ((case-fold-search t)
9665 (inhibit-read-only t)
9666 (inherit? (org-property-inherit-p dprop))
9667 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9668 (global (and inherit? (org--property-global-value dprop nil))))
9669 (org-with-silent-modifications
9670 (org-with-point-at 1
9671 ;; Set global values (e.g., values defined through
9672 ;; "#+PROPERTY:" keywords) to the whole buffer.
9673 (when global (put-text-property (point-min) (point-max) tprop global))
9674 ;; Set local values.
9675 (while (re-search-forward property-re nil t)
9676 (when (org-at-property-p)
9677 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9678 (outline-next-heading))))))
9680 (defun org-refresh-property (tprop p &optional inherit)
9681 "Refresh the buffer text property TPROP from the drawer property P.
9682 The refresh happens only for the current headline, or the whole
9683 sub-tree if optional argument INHERIT is non-nil."
9684 (unless (org-before-first-heading-p)
9685 (save-excursion
9686 (org-back-to-heading t)
9687 (let ((start (point))
9688 (end (save-excursion
9689 (if inherit (org-end-of-subtree t t)
9690 (or (outline-next-heading) (point-max))))))
9691 (if (symbolp tprop)
9692 ;; TPROP is a text property symbol.
9693 (put-text-property start end tprop p)
9694 ;; TPROP is an alist with (property . function) elements.
9695 (pcase-dolist (`(,prop . ,f) tprop)
9696 (put-text-property start end prop (funcall f p))))))))
9698 (defun org-refresh-category-properties ()
9699 "Refresh category text properties in the buffer."
9700 (let ((case-fold-search t)
9701 (inhibit-read-only t)
9702 (default-category
9703 (cond ((null org-category)
9704 (if buffer-file-name
9705 (file-name-sans-extension
9706 (file-name-nondirectory buffer-file-name))
9707 "???"))
9708 ((symbolp org-category) (symbol-name org-category))
9709 (t org-category))))
9710 (org-with-silent-modifications
9711 (org-with-wide-buffer
9712 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9713 ;; This is the default category for the buffer. If none is
9714 ;; found, fall-back to `org-category' or buffer file name.
9715 (put-text-property
9716 (point-min) (point-max)
9717 'org-category
9718 (catch 'buffer-category
9719 (goto-char (point-max))
9720 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9721 (let ((element (org-element-at-point)))
9722 (when (eq (org-element-type element) 'keyword)
9723 (throw 'buffer-category
9724 (org-element-property :value element)))))
9725 default-category))
9726 ;; Set sub-tree specific categories.
9727 (goto-char (point-min))
9728 (let ((regexp (org-re-property "CATEGORY")))
9729 (while (re-search-forward regexp nil t)
9730 (let ((value (match-string-no-properties 3)))
9731 (when (org-at-property-p)
9732 (put-text-property
9733 (save-excursion (org-back-to-heading t) (point))
9734 (save-excursion (org-end-of-subtree t t) (point))
9735 'org-category
9736 value)))))))))
9738 (defun org-refresh-stats-properties ()
9739 "Refresh stats text properties in the buffer."
9740 (org-with-silent-modifications
9741 (org-with-point-at 1
9742 (let ((regexp (concat org-outline-regexp-bol
9743 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9744 (while (re-search-forward regexp nil t)
9745 (let* ((numerator (string-to-number (match-string 1)))
9746 (denominator (and (match-end 2)
9747 (string-to-number (match-string 2))))
9748 (stats (cond ((not denominator) numerator) ;percent
9749 ((= denominator 0) 0)
9750 (t (/ (* numerator 100) denominator)))))
9751 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9752 'org-stats stats)))))))
9754 (defun org-refresh-effort-properties ()
9755 "Refresh effort properties"
9756 (org-refresh-properties
9757 org-effort-property
9758 '((effort . identity)
9759 (effort-minutes . org-duration-string-to-minutes))))
9761 ;;;; Link Stuff
9763 ;;; Link abbreviations
9765 (defun org-link-expand-abbrev (link)
9766 "Apply replacements as defined in `org-link-abbrev-alist'."
9767 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9768 (let* ((key (match-string 1 link))
9769 (as (or (assoc key org-link-abbrev-alist-local)
9770 (assoc key org-link-abbrev-alist)))
9771 (tag (and (match-end 2) (match-string 3 link)))
9772 rpl)
9773 (if (not as)
9774 link
9775 (setq rpl (cdr as))
9776 (cond
9777 ((symbolp rpl) (funcall rpl tag))
9778 ((string-match "%(\\([^)]+\\))" rpl)
9779 (replace-match
9780 (save-match-data
9781 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9782 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9783 ((string-match "%h" rpl)
9784 (replace-match (url-hexify-string (or tag "")) t t rpl))
9785 (t (concat rpl tag)))))
9786 link))
9788 ;;; Storing and inserting links
9790 (defvar org-insert-link-history nil
9791 "Minibuffer history for links inserted with `org-insert-link'.")
9793 (defvar org-stored-links nil
9794 "Contains the links stored with `org-store-link'.")
9796 (defvar org-store-link-plist nil
9797 "Plist with info about the most recently link created with `org-store-link'.")
9799 (defun org-store-link-functions ()
9800 "Return a list of functions that are called to create and store a link.
9801 The functions defined in the :store property of
9802 `org-link-parameters'.
9804 Each function will be called in turn until one returns a non-nil
9805 value. Each function should check if it is responsible for
9806 creating this link (for example by looking at the major mode).
9807 If not, it must exit and return nil. If yes, it should return
9808 a non-nil value after calling `org-store-link-props' with a list
9809 of properties and values. Special properties are:
9811 :type The link prefix, like \"http\". This must be given.
9812 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9813 This is obligatory as well.
9814 :description Optional default description for the second pair
9815 of brackets in an Org mode link. The user can still change
9816 this when inserting this link into an Org mode buffer.
9818 In addition to these, any additional properties can be specified
9819 and then used in capture templates."
9820 (cl-loop for link in org-link-parameters
9821 with store-func
9822 do (setq store-func (org-link-get-parameter (car link) :store))
9823 if store-func
9824 collect store-func))
9826 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9827 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9829 ;;;###autoload
9830 (defun org-store-link (arg)
9831 "Store an org-link to the current location.
9832 \\<org-mode-map>
9833 This link is added to `org-stored-links' and can later be inserted
9834 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9836 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9837 A single
9838 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9839 `org-gnus-prefer-web-links' for links to Usenet articles.
9841 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9842 skipping storing functions that are not
9843 part of Org core.
9845 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9846 prefix ARG forces storing a link for each line in the
9847 active region."
9848 (interactive "P")
9849 (org-load-modules-maybe)
9850 (if (and (equal arg '(64)) (org-region-active-p))
9851 (save-excursion
9852 (let ((end (region-end)))
9853 (goto-char (region-beginning))
9854 (set-mark (point))
9855 (while (< (point-at-eol) end)
9856 (move-end-of-line 1) (activate-mark)
9857 (let (current-prefix-arg)
9858 (call-interactively 'org-store-link))
9859 (move-beginning-of-line 2)
9860 (set-mark (point)))))
9861 (setq org-store-link-plist nil)
9862 (let (link cpltxt desc description search
9863 txt custom-id agenda-link sfuns sfunsn)
9864 (cond
9866 ;; Store a link using an external link type
9867 ((and (not (equal arg '(16)))
9868 (setq sfuns
9869 (delq
9870 nil (mapcar (lambda (f)
9871 (let (fs) (if (funcall f) (push f fs))))
9872 (org-store-link-functions)))
9873 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9874 (or (and (cdr sfuns)
9875 (funcall (intern
9876 (completing-read
9877 "Which function for creating the link? "
9878 sfunsn nil t (car sfunsn)))))
9879 (funcall (caar sfuns)))
9880 (setq link (plist-get org-store-link-plist :link)
9881 desc (or (plist-get org-store-link-plist
9882 :description)
9883 link))))
9885 ;; Store a link from a source code buffer.
9886 ((org-src-edit-buffer-p)
9887 (let ((coderef-format (org-src-coderef-format)))
9888 (cond ((save-excursion
9889 (beginning-of-line)
9890 (looking-at (org-src-coderef-regexp coderef-format)))
9891 (setq link (format "(%s)" (match-string-no-properties 3))))
9892 ((called-interactively-p 'any)
9893 (let ((label (read-string "Code line label: ")))
9894 (end-of-line)
9895 (setq link (format coderef-format label))
9896 (let ((gc (- 79 (length link))))
9897 (if (< (current-column) gc)
9898 (org-move-to-column gc t)
9899 (insert " ")))
9900 (insert link)
9901 (setq link (concat "(" label ")"))
9902 (setq desc nil)))
9903 (t (setq link nil)))))
9905 ;; We are in the agenda, link to referenced location
9906 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9907 (let ((m (or (get-text-property (point) 'org-hd-marker)
9908 (get-text-property (point) 'org-marker))))
9909 (when m
9910 (org-with-point-at m
9911 (setq agenda-link
9912 (if (called-interactively-p 'any)
9913 (call-interactively 'org-store-link)
9914 (org-store-link nil)))))))
9916 ((eq major-mode 'calendar-mode)
9917 (let ((cd (calendar-cursor-to-date)))
9918 (setq link
9919 (format-time-string
9920 (car org-time-stamp-formats)
9921 (apply 'encode-time
9922 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9923 nil nil nil))))
9924 (org-store-link-props :type "calendar" :date cd)))
9926 ((eq major-mode 'help-mode)
9927 (setq link (concat "help:" (save-excursion
9928 (goto-char (point-min))
9929 (looking-at "^[^ ]+")
9930 (match-string 0))))
9931 (org-store-link-props :type "help"))
9933 ((eq major-mode 'w3-mode)
9934 (setq cpltxt (if (and (buffer-name)
9935 (not (string-match "Untitled" (buffer-name))))
9936 (buffer-name)
9937 (url-view-url t))
9938 link (url-view-url t))
9939 (org-store-link-props :type "w3" :url (url-view-url t)))
9941 ((eq major-mode 'image-mode)
9942 (setq cpltxt (concat "file:"
9943 (abbreviate-file-name buffer-file-name))
9944 link cpltxt)
9945 (org-store-link-props :type "image" :file buffer-file-name))
9947 ;; In dired, store a link to the file of the current line
9948 ((derived-mode-p 'dired-mode)
9949 (let ((file (dired-get-filename nil t)))
9950 (setq file (if file
9951 (abbreviate-file-name
9952 (expand-file-name (dired-get-filename nil t)))
9953 ;; otherwise, no file so use current directory.
9954 default-directory))
9955 (setq cpltxt (concat "file:" file)
9956 link cpltxt)))
9958 ((setq search (run-hook-with-args-until-success
9959 'org-create-file-search-functions))
9960 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9961 "::" search))
9962 (setq cpltxt (or description link)))
9964 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9965 (org-with-limited-levels
9966 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9967 (cond
9968 ;; Store a link using the target at point
9969 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9970 (setq cpltxt
9971 (concat "file:"
9972 (abbreviate-file-name
9973 (buffer-file-name (buffer-base-buffer)))
9974 "::" (match-string 1))
9975 link cpltxt))
9976 ((and (featurep 'org-id)
9977 (or (eq org-id-link-to-org-use-id t)
9978 (and (called-interactively-p 'any)
9979 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9980 (and (eq org-id-link-to-org-use-id
9981 'create-if-interactive-and-no-custom-id)
9982 (not custom-id))))
9983 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9984 ;; Store a link using the ID at point
9985 (setq link (condition-case nil
9986 (prog1 (org-id-store-link)
9987 (setq desc (or (plist-get org-store-link-plist
9988 :description)
9989 "")))
9990 (error
9991 ;; Probably before first headline, link only to file
9992 (concat "file:"
9993 (abbreviate-file-name
9994 (buffer-file-name (buffer-base-buffer))))))))
9996 ;; Just link to current headline
9997 (setq cpltxt (concat "file:"
9998 (abbreviate-file-name
9999 (buffer-file-name (buffer-base-buffer)))))
10000 ;; Add a context search string
10001 (when (org-xor org-context-in-file-links
10002 (equal arg '(4)))
10003 (let* ((element (org-element-at-point))
10004 (name (org-element-property :name element)))
10005 (setq txt (cond
10006 ((org-at-heading-p) nil)
10007 (name)
10008 ((org-region-active-p)
10009 (buffer-substring (region-beginning) (region-end)))))
10010 (when (or (null txt) (string-match "\\S-" txt))
10011 (setq cpltxt
10012 (concat cpltxt "::"
10013 (condition-case nil
10014 (org-make-org-heading-search-string txt)
10015 (error "")))
10016 desc (or name
10017 (nth 4 (ignore-errors (org-heading-components)))
10018 "NONE")))))
10019 (when (string-match "::\\'" cpltxt)
10020 (setq cpltxt (substring cpltxt 0 -2)))
10021 (setq link cpltxt)))))
10023 ((buffer-file-name (buffer-base-buffer))
10024 ;; Just link to this file here.
10025 (setq cpltxt (concat "file:"
10026 (abbreviate-file-name
10027 (buffer-file-name (buffer-base-buffer)))))
10028 ;; Add a context string.
10029 (when (org-xor org-context-in-file-links
10030 (equal arg '(4)))
10031 (setq txt (if (org-region-active-p)
10032 (buffer-substring (region-beginning) (region-end))
10033 (buffer-substring (point-at-bol) (point-at-eol))))
10034 ;; Only use search option if there is some text.
10035 (when (string-match "\\S-" txt)
10036 (setq cpltxt
10037 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10038 desc "NONE")))
10039 (setq link cpltxt))
10041 ((called-interactively-p 'interactive)
10042 (user-error "No method for storing a link from this buffer"))
10044 (t (setq link nil)))
10046 ;; We're done setting link and desc, clean up
10047 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10048 (setq link (or link cpltxt)
10049 desc (or desc cpltxt))
10050 (cond ((not desc))
10051 ((equal desc "NONE") (setq desc nil))
10052 (t (setq desc
10053 (replace-regexp-in-string
10054 org-bracket-link-analytic-regexp
10055 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10056 desc))))
10057 ;; Return the link
10058 (if (not (and (or (called-interactively-p 'any)
10059 executing-kbd-macro)
10060 link))
10061 (or agenda-link (and link (org-make-link-string link desc)))
10062 (push (list link desc) org-stored-links)
10063 (message "Stored: %s" (or desc link))
10064 (when custom-id
10065 (setq link (concat "file:" (abbreviate-file-name
10066 (buffer-file-name)) "::#" custom-id))
10067 (push (list link desc) org-stored-links))
10068 (car org-stored-links)))))
10070 (defun org-store-link-props (&rest plist)
10071 "Store link properties, extract names, addresses and dates."
10072 (let ((x (plist-get plist :from)))
10073 (when x
10074 (let ((adr (mail-extract-address-components x)))
10075 (setq plist (plist-put plist :fromname (car adr)))
10076 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10077 (let ((x (plist-get plist :to)))
10078 (when x
10079 (let ((adr (mail-extract-address-components x)))
10080 (setq plist (plist-put plist :toname (car adr)))
10081 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10082 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10083 (when x
10084 (setq plist (plist-put plist :date-timestamp
10085 (format-time-string
10086 (org-time-stamp-format t) x)))
10087 (setq plist (plist-put plist :date-timestamp-inactive
10088 (format-time-string
10089 (org-time-stamp-format t t) x)))))
10090 (let ((from (plist-get plist :from))
10091 (to (plist-get plist :to)))
10092 (when (and from to org-from-is-user-regexp)
10093 (setq plist
10094 (plist-put plist :fromto
10095 (if (string-match org-from-is-user-regexp from)
10096 (concat "to %t")
10097 (concat "from %f"))))))
10098 (setq org-store-link-plist plist))
10100 (defun org-add-link-props (&rest plist)
10101 "Add these properties to the link property list."
10102 (let (key value)
10103 (while plist
10104 (setq key (pop plist) value (pop plist))
10105 (setq org-store-link-plist
10106 (plist-put org-store-link-plist key value)))))
10108 (defun org-email-link-description (&optional fmt)
10109 "Return the description part of an email link.
10110 This takes information from `org-store-link-plist' and formats it
10111 according to FMT (default from `org-email-link-description-format')."
10112 (setq fmt (or fmt org-email-link-description-format))
10113 (let* ((p org-store-link-plist)
10114 (to (plist-get p :toaddress))
10115 (from (plist-get p :fromaddress))
10116 (table
10117 (list
10118 (cons "%c" (plist-get p :fromto))
10119 (cons "%F" (plist-get p :from))
10120 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10121 (cons "%T" (plist-get p :to))
10122 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10123 (cons "%s" (plist-get p :subject))
10124 (cons "%d" (plist-get p :date))
10125 (cons "%m" (plist-get p :message-id)))))
10126 (when (string-match "%c" fmt)
10127 ;; Check if the user wrote this message
10128 (if (and org-from-is-user-regexp from to
10129 (save-match-data (string-match org-from-is-user-regexp from)))
10130 (setq fmt (replace-match "to %t" t t fmt))
10131 (setq fmt (replace-match "from %f" t t fmt))))
10132 (org-replace-escapes fmt table)))
10134 (defun org-make-org-heading-search-string (&optional string)
10135 "Make search string for the current headline or STRING."
10136 (let ((s (or string
10137 (and (derived-mode-p 'org-mode)
10138 (save-excursion
10139 (org-back-to-heading t)
10140 (org-element-property :raw-value (org-element-at-point))))))
10141 (lines org-context-in-file-links))
10142 (or string (setq s (concat "*" s))) ; Add * for headlines
10143 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10144 (when (and string (integerp lines) (> lines 0))
10145 (let ((slines (org-split-string s "\n")))
10146 (when (< lines (length slines))
10147 (setq s (mapconcat
10148 'identity
10149 (reverse (nthcdr (- (length slines) lines)
10150 (reverse slines))) "\n")))))
10151 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10153 (defun org-make-link-string (link &optional description)
10154 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10155 (unless (org-string-nw-p link) (error "Empty link"))
10156 (let ((uri (cond ((string-match org-link-types-re link)
10157 (concat (match-string 1 link)
10158 (org-link-escape (substring link (match-end 1)))))
10159 ;; For readability, url-encode internal links only
10160 ;; when absolutely needed (i.e, when they contain
10161 ;; square brackets). File links however, are
10162 ;; encoded since, e.g., spaces are significant.
10163 ((or (file-name-absolute-p link)
10164 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10165 (org-link-escape link))
10166 (t link)))
10167 (description
10168 (and (org-string-nw-p description)
10169 ;; Remove brackets from description, as they are fatal.
10170 (replace-regexp-in-string
10171 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10172 (org-trim description)))))
10173 (format "[[%s]%s]"
10175 (if description (format "[%s]" description) ""))))
10177 (defconst org-link-escape-chars
10178 ;;%20 %5B %5D %25
10179 '(?\s ?\[ ?\] ?%)
10180 "List of characters that should be escaped in a link when stored to Org.
10181 This is the list that is used for internal purposes.")
10183 (defun org-link-escape (text &optional table merge)
10184 "Return percent escaped representation of TEXT.
10185 TEXT is a string with the text to escape.
10186 Optional argument TABLE is a list with characters that should be
10187 escaped. When nil, `org-link-escape-chars' is used.
10188 If optional argument MERGE is set, merge TABLE into
10189 `org-link-escape-chars'."
10190 (let ((characters-to-encode
10191 (cond ((null table) org-link-escape-chars)
10192 (merge (append org-link-escape-chars table))
10193 (t table))))
10194 (mapconcat
10195 (lambda (c)
10196 (if (or (memq c characters-to-encode)
10197 (and org-url-hexify-p (or (< c 32) (> c 126))))
10198 (mapconcat (lambda (e) (format "%%%.2X" e))
10199 (or (encode-coding-char c 'utf-8)
10200 (error "Unable to percent escape character: %c" c))
10202 (char-to-string c)))
10203 text "")))
10205 (defun org-link-unescape (str)
10206 "Unhex hexified Unicode parts in string STR.
10207 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10208 reciprocal of `org-link-escape', which see."
10209 (if (org-string-nw-p str)
10210 (replace-regexp-in-string
10211 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10212 str))
10214 (defun org-link-unescape-compound (hex)
10215 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10216 Note: this function also decodes single byte encodings like
10217 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10218 (save-match-data
10219 (let* ((bytes (cdr (split-string hex "%")))
10220 (ret "")
10221 (eat 0)
10222 (sum 0))
10223 (while bytes
10224 (let* ((val (string-to-number (pop bytes) 16))
10225 (shift-xor
10226 (if (= 0 eat)
10227 (cond
10228 ((>= val 252) (cons 6 252))
10229 ((>= val 248) (cons 5 248))
10230 ((>= val 240) (cons 4 240))
10231 ((>= val 224) (cons 3 224))
10232 ((>= val 192) (cons 2 192))
10233 (t (cons 0 0)))
10234 (cons 6 128))))
10235 (when (>= val 192) (setq eat (car shift-xor)))
10236 (setq val (logxor val (cdr shift-xor)))
10237 (setq sum (+ (lsh sum (car shift-xor)) val))
10238 (when (> eat 0) (setq eat (- eat 1)))
10239 (cond
10240 ((= 0 eat) ;multi byte
10241 (setq ret (concat ret (char-to-string sum)))
10242 (setq sum 0))
10243 ((not bytes) ; single byte(s)
10244 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10245 ret)))
10247 (defun org-link-unescape-single-byte-sequence (hex)
10248 "Unhexify hex-encoded single byte character sequences."
10249 (mapconcat (lambda (byte)
10250 (char-to-string (string-to-number byte 16)))
10251 (cdr (split-string hex "%")) ""))
10253 (defun org-xor (a b)
10254 "Exclusive or."
10255 (if a (not b) b))
10257 (defun org-fixup-message-id-for-http (s)
10258 "Replace special characters in a message id, so it can be used in an http query."
10259 (when (string-match "%" s)
10260 (setq s (mapconcat (lambda (c)
10261 (if (eq c ?%)
10262 "%25"
10263 (char-to-string c)))
10264 s "")))
10265 (while (string-match "<" s)
10266 (setq s (replace-match "%3C" t t s)))
10267 (while (string-match ">" s)
10268 (setq s (replace-match "%3E" t t s)))
10269 (while (string-match "@" s)
10270 (setq s (replace-match "%40" t t s)))
10273 (defun org-link-prettify (link)
10274 "Return a human-readable representation of LINK.
10275 The car of LINK must be a raw link.
10276 The cdr of LINK must be either a link description or nil."
10277 (let ((desc (or (cadr link) "<no description>")))
10278 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10279 "<" (car link) ">")))
10281 ;;;###autoload
10282 (defun org-insert-link-global ()
10283 "Insert a link like Org mode does.
10284 This command can be called in any mode to insert a link in Org syntax."
10285 (interactive)
10286 (org-load-modules-maybe)
10287 (org-run-like-in-org-mode 'org-insert-link))
10289 (defun org-insert-all-links (arg &optional pre post)
10290 "Insert all links in `org-stored-links'.
10291 When a universal prefix, do not delete the links from `org-stored-links'.
10292 When `ARG' is a number, insert the last N link(s).
10293 `PRE' and `POST' are optional arguments to define a string to
10294 prepend or to append."
10295 (interactive "P")
10296 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10297 (links (copy-sequence org-stored-links))
10298 (pr (or pre "- "))
10299 (po (or post "\n"))
10300 (cnt 1) l)
10301 (if (null org-stored-links)
10302 (message "No link to insert")
10303 (while (and (or (listp arg) (>= arg cnt))
10304 (setq l (if (listp arg)
10305 (pop links)
10306 (pop org-stored-links))))
10307 (setq cnt (1+ cnt))
10308 (insert pr)
10309 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10310 (insert po)))))
10312 (defun org-insert-last-stored-link (arg)
10313 "Insert the last link stored in `org-stored-links'."
10314 (interactive "p")
10315 (org-insert-all-links arg "" "\n"))
10317 (defun org-link-fontify-links-to-this-file ()
10318 "Fontify links to the current file in `org-stored-links'."
10319 (let ((f (buffer-file-name)) a b)
10320 (setq a (mapcar (lambda(l)
10321 (let ((ll (car l)))
10322 (when (and (string-match "^file:\\(.+\\)::" ll)
10323 (equal f (expand-file-name (match-string 1 ll))))
10324 ll)))
10325 org-stored-links))
10326 (when (featurep 'org-id)
10327 (setq b (mapcar (lambda(l)
10328 (let ((ll (car l)))
10329 (when (and (string-match "^id:\\(.+\\)$" ll)
10330 (equal f (expand-file-name
10331 (or (org-id-find-id-file
10332 (match-string 1 ll)) ""))))
10333 ll)))
10334 org-stored-links)))
10335 (mapcar (lambda(l)
10336 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10337 (delq nil (append a b)))))
10339 (defvar org--links-history nil)
10340 (defun org-insert-link (&optional complete-file link-location default-description)
10341 "Insert a link. At the prompt, enter the link.
10343 Completion can be used to insert any of the link protocol prefixes in use.
10345 The history can be used to select a link previously stored with
10346 `org-store-link'. When the empty string is entered (i.e. if you just
10347 press `RET' at the prompt), the link defaults to the most recently
10348 stored link. As `SPC' triggers completion in the minibuffer, you need to
10349 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10351 You will also be prompted for a description, and if one is given, it will
10352 be displayed in the buffer instead of the link.
10354 If there is already a link at point, this command will allow you to edit
10355 link and description parts.
10357 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10358 file name can be
10359 selected using completion. The path to the file will be relative to the
10360 current directory if the file is in the current directory or a subdirectory.
10361 Otherwise, the link will be the absolute path as completed in the minibuffer
10362 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10363 option `org-link-file-path-type'.
10365 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10366 absolute path even if the file is in
10367 the current directory or below.
10369 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10370 prefix negates `org-keep-stored-link-after-insertion'.
10372 If `org-make-link-description-function' is non-nil, this function will be
10373 called with the link target, and the result will be the default
10374 link description.
10376 If the LINK-LOCATION parameter is non-nil, this value will be used as
10377 the link location instead of reading one interactively.
10379 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10380 as the default description."
10381 (interactive "P")
10382 (let* ((wcf (current-window-configuration))
10383 (origbuf (current-buffer))
10384 (region (when (org-region-active-p)
10385 (buffer-substring (region-beginning) (region-end))))
10386 (remove (and region (list (region-beginning) (region-end))))
10387 (desc region)
10388 (link link-location)
10389 (abbrevs org-link-abbrev-alist-local)
10390 entry all-prefixes auto-desc)
10391 (cond
10392 (link-location) ; specified by arg, just use it.
10393 ((org-in-regexp org-bracket-link-regexp 1)
10394 ;; We do have a link at point, and we are going to edit it.
10395 (setq remove (list (match-beginning 0) (match-end 0)))
10396 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10397 (setq link (read-string "Link: "
10398 (org-link-unescape
10399 (match-string-no-properties 1)))))
10400 ((or (org-in-regexp org-angle-link-re)
10401 (org-in-regexp org-plain-link-re))
10402 ;; Convert to bracket link
10403 (setq remove (list (match-beginning 0) (match-end 0))
10404 link (read-string "Link: "
10405 (org-unbracket-string "<" ">" (match-string 0)))))
10406 ((member complete-file '((4) (16)))
10407 ;; Completing read for file names.
10408 (setq link (org-file-complete-link complete-file)))
10410 ;; Read link, with completion for stored links.
10411 (org-link-fontify-links-to-this-file)
10412 (org-switch-to-buffer-other-window "*Org Links*")
10413 (with-current-buffer "*Org Links*"
10414 (erase-buffer)
10415 (insert "Insert a link.
10416 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10417 (when org-stored-links
10418 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10419 (insert (mapconcat 'org-link-prettify
10420 (reverse org-stored-links) "\n")))
10421 (goto-char (point-min)))
10422 (let ((cw (selected-window)))
10423 (select-window (get-buffer-window "*Org Links*" 'visible))
10424 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10425 (unless (pos-visible-in-window-p (point-max))
10426 (org-fit-window-to-buffer))
10427 (and (window-live-p cw) (select-window cw)))
10428 (setq all-prefixes (append (mapcar 'car abbrevs)
10429 (mapcar 'car org-link-abbrev-alist)
10430 (org-link-types)))
10431 (unwind-protect
10432 ;; Fake a link history, containing the stored links.
10433 (let ((org--links-history
10434 (append (mapcar #'car org-stored-links)
10435 org-insert-link-history)))
10436 (setq link
10437 (org-completing-read
10438 "Link: "
10439 (append
10440 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10441 (mapcar #'car org-stored-links))
10442 nil nil nil
10443 'org--links-history
10444 (caar org-stored-links)))
10445 (unless (org-string-nw-p link) (user-error "No link selected"))
10446 (dolist (l org-stored-links)
10447 (when (equal link (cadr l))
10448 (setq link (car l))
10449 (setq auto-desc t)))
10450 (when (or (member link all-prefixes)
10451 (and (equal ":" (substring link -1))
10452 (member (substring link 0 -1) all-prefixes)
10453 (setq link (substring link 0 -1))))
10454 (setq link (with-current-buffer origbuf
10455 (org-link-try-special-completion link)))))
10456 (set-window-configuration wcf)
10457 (kill-buffer "*Org Links*"))
10458 (setq entry (assoc link org-stored-links))
10459 (or entry (push link org-insert-link-history))
10460 (setq desc (or desc (nth 1 entry)))))
10462 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10463 (not org-keep-stored-link-after-insertion))
10464 (setq org-stored-links (delq (assoc link org-stored-links)
10465 org-stored-links)))
10467 (when (and (string-match org-plain-link-re link)
10468 (not (string-match org-ts-regexp link)))
10469 ;; URL-like link, normalize the use of angular brackets.
10470 (setq link (org-unbracket-string "<" ">" link)))
10472 ;; Check if we are linking to the current file with a search
10473 ;; option If yes, simplify the link by using only the search
10474 ;; option.
10475 (when (and buffer-file-name
10476 (let ((case-fold-search nil))
10477 (string-match "\\`file:\\(.+?\\)::" link)))
10478 (let ((path (match-string-no-properties 1 link))
10479 (search (substring-no-properties link (match-end 0))))
10480 (save-match-data
10481 (when (equal (file-truename buffer-file-name) (file-truename path))
10482 ;; We are linking to this same file, with a search option
10483 (setq link search)))))
10485 ;; Check if we can/should use a relative path. If yes, simplify the link
10486 (let ((case-fold-search nil))
10487 (when (string-match "\\`\\(file\\|docview\\):" link)
10488 (let* ((type (match-string-no-properties 0 link))
10489 (path (substring-no-properties link (match-end 0)))
10490 (origpath path))
10491 (cond
10492 ((or (eq org-link-file-path-type 'absolute)
10493 (equal complete-file '(16)))
10494 (setq path (abbreviate-file-name (expand-file-name path))))
10495 ((eq org-link-file-path-type 'noabbrev)
10496 (setq path (expand-file-name path)))
10497 ((eq org-link-file-path-type 'relative)
10498 (setq path (file-relative-name path)))
10500 (save-match-data
10501 (if (string-match (concat "^" (regexp-quote
10502 (expand-file-name
10503 (file-name-as-directory
10504 default-directory))))
10505 (expand-file-name path))
10506 ;; We are linking a file with relative path name.
10507 (setq path (substring (expand-file-name path)
10508 (match-end 0)))
10509 (setq path (abbreviate-file-name (expand-file-name path)))))))
10510 (setq link (concat type path))
10511 (when (equal desc origpath)
10512 (setq desc path)))))
10514 (if org-make-link-description-function
10515 (setq desc
10516 (or (condition-case nil
10517 (funcall org-make-link-description-function link desc)
10518 (error (progn (message "Can't get link description from `%s'"
10519 (symbol-name org-make-link-description-function))
10520 (sit-for 2) nil)))
10521 (read-string "Description: " default-description)))
10522 (if default-description (setq desc default-description)
10523 (setq desc (or (and auto-desc desc)
10524 (read-string "Description: " desc)))))
10526 (unless (string-match "\\S-" desc) (setq desc nil))
10527 (when remove (apply 'delete-region remove))
10528 (insert (org-make-link-string link desc))
10529 ;; Redisplay so as the new link has proper invisible characters.
10530 (sit-for 0)))
10532 (defun org-link-try-special-completion (type)
10533 "If there is completion support for link type TYPE, offer it."
10534 (let ((fun (org-link-get-parameter type :complete)))
10535 (if (functionp fun)
10536 (funcall fun)
10537 (read-string "Link (no completion support): " (concat type ":")))))
10539 (defun org-file-complete-link (&optional arg)
10540 "Create a file link using completion."
10541 (let ((file (read-file-name "File: "))
10542 (pwd (file-name-as-directory (expand-file-name ".")))
10543 (pwd1 (file-name-as-directory (abbreviate-file-name
10544 (expand-file-name ".")))))
10545 (cond ((equal arg '(16))
10546 (concat "file:"
10547 (abbreviate-file-name (expand-file-name file))))
10548 ((string-match
10549 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10550 (concat "file:" (match-string 1 file)))
10551 ((string-match
10552 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10553 (expand-file-name file))
10554 (concat "file:"
10555 (match-string 1 (expand-file-name file))))
10556 (t (concat "file:" file)))))
10558 (defun org-completing-read (&rest args)
10559 "Completing-read with SPACE being a normal character."
10560 (let ((enable-recursive-minibuffers t)
10561 (minibuffer-local-completion-map
10562 (copy-keymap minibuffer-local-completion-map)))
10563 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10564 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10565 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10566 'org-time-stamp-inactive)
10567 (apply #'completing-read args)))
10569 ;;; Opening/following a link
10571 (defvar org-link-search-failed nil)
10573 (defvar org-open-link-functions nil
10574 "Hook for functions finding a plain text link.
10575 These functions must take a single argument, the link content.
10576 They will be called for links that look like [[link text][description]]
10577 when LINK TEXT does not have a protocol like \"http:\" and does not look
10578 like a filename (e.g. \"./blue.png\").
10580 These functions will be called *before* Org attempts to resolve the
10581 link by doing text searches in the current buffer - so if you want a
10582 link \"[[target]]\" to still find \"<<target>>\", your function should
10583 handle this as a special case.
10585 When the function does handle the link, it must return a non-nil value.
10586 If it decides that it is not responsible for this link, it must return
10587 nil to indicate that that Org can continue with other options like
10588 exact and fuzzy text search.")
10590 (defun org-next-link (&optional search-backward)
10591 "Move forward to the next link.
10592 If the link is in hidden text, expose it."
10593 (interactive "P")
10594 (when (and org-link-search-failed (eq this-command last-command))
10595 (goto-char (point-min))
10596 (message "Link search wrapped back to beginning of buffer"))
10597 (setq org-link-search-failed nil)
10598 (let* ((pos (point))
10599 (ct (org-context))
10600 (a (assq :link ct))
10601 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10602 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10603 ((looking-at org-any-link-re)
10604 ;; Don't stay stuck at link without an org-link face
10605 (forward-char (if search-backward -1 1))))
10606 (if (funcall srch-fun org-any-link-re nil t)
10607 (progn
10608 (goto-char (match-beginning 0))
10609 (when (org-invisible-p) (org-show-context)))
10610 (goto-char pos)
10611 (setq org-link-search-failed t)
10612 (message "No further link found"))))
10614 (defun org-previous-link ()
10615 "Move backward to the previous link.
10616 If the link is in hidden text, expose it."
10617 (interactive)
10618 (funcall 'org-next-link t))
10620 (defun org-translate-link (s)
10621 "Translate a link string if a translation function has been defined."
10622 (with-temp-buffer
10623 (insert (org-trim s))
10624 (org-trim (org-element-interpret-data (org-element-context)))))
10626 (defun org-translate-link-from-planner (type path)
10627 "Translate a link from Emacs Planner syntax so that Org can follow it.
10628 This is still an experimental function, your mileage may vary."
10629 (cond
10630 ((member type '("http" "https" "news" "ftp"))
10631 ;; standard Internet links are the same.
10632 nil)
10633 ((and (equal type "irc") (string-match "^//" path))
10634 ;; Planner has two / at the beginning of an irc link, we have 1.
10635 ;; We should have zero, actually....
10636 (setq path (substring path 1)))
10637 ((and (equal type "lisp") (string-match "^/" path))
10638 ;; Planner has a slash, we do not.
10639 (setq type "elisp" path (substring path 1)))
10640 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10641 ;; A typical message link. Planner has the id after the final slash,
10642 ;; we separate it with a hash mark
10643 (setq path (concat (match-string 1 path) "#"
10644 (org-unbracket-string "<" ">" (match-string 2 path))))))
10645 (cons type path))
10647 (defun org-find-file-at-mouse (ev)
10648 "Open file link or URL at mouse."
10649 (interactive "e")
10650 (mouse-set-point ev)
10651 (org-open-at-point 'in-emacs))
10653 (defun org-open-at-mouse (ev)
10654 "Open file link or URL at mouse.
10655 See the docstring of `org-open-file' for details."
10656 (interactive "e")
10657 (mouse-set-point ev)
10658 (when (eq major-mode 'org-agenda-mode)
10659 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10660 (org-open-at-point))
10662 (defvar org-window-config-before-follow-link nil
10663 "The window configuration before following a link.
10664 This is saved in case the need arises to restore it.")
10666 ;;;###autoload
10667 (defun org-open-at-point-global ()
10668 "Follow a link or time-stamp like Org mode does.
10669 This command can be called in any mode to follow an external link
10670 or a time-stamp that has Org mode syntax. Its behavior is
10671 undefined when called on internal links (e.g., fuzzy links).
10672 Raise an error when there is nothing to follow. "
10673 (interactive)
10674 (cond ((org-in-regexp org-any-link-re)
10675 (org-open-link-from-string (match-string-no-properties 0)))
10676 ((or (org-in-regexp org-ts-regexp-both nil t)
10677 (org-in-regexp org-tsr-regexp-both nil t))
10678 (org-follow-timestamp-link))
10679 (t (user-error "No link found"))))
10681 ;;;###autoload
10682 (defun org-open-link-from-string (s &optional arg reference-buffer)
10683 "Open a link in the string S, as if it was in Org mode."
10684 (interactive "sLink: \nP")
10685 (let ((reference-buffer (or reference-buffer (current-buffer))))
10686 (with-temp-buffer
10687 (let ((org-inhibit-startup (not reference-buffer)))
10688 (org-mode)
10689 (insert s)
10690 (goto-char (point-min))
10691 (when reference-buffer
10692 (setq org-link-abbrev-alist-local
10693 (with-current-buffer reference-buffer
10694 org-link-abbrev-alist-local)))
10695 (org-open-at-point arg reference-buffer)))))
10697 (defvar org-open-at-point-functions nil
10698 "Hook that is run when following a link at point.
10700 Functions in this hook must return t if they identify and follow
10701 a link at point. If they don't find anything interesting at point,
10702 they must return nil.")
10704 (defvar org-link-search-inhibit-query nil)
10705 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10706 (defun org--open-doi-link (path)
10707 "Open a \"doi\" type link.
10708 PATH is a the path to search for, as a string."
10709 (browse-url (url-encode-url (concat org-doi-server-url path))))
10711 (defun org--open-elisp-link (path)
10712 "Open a \"elisp\" type link.
10713 PATH is the sexp to evaluate, as a string."
10714 (let ((cmd path))
10715 (if (or (and (org-string-nw-p
10716 org-confirm-elisp-link-not-regexp)
10717 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10718 (not org-confirm-elisp-link-function)
10719 (funcall org-confirm-elisp-link-function
10720 (format "Execute \"%s\" as elisp? "
10721 (org-add-props cmd nil 'face 'org-warning))))
10722 (message "%s => %s" cmd
10723 (if (eq (string-to-char cmd) ?\()
10724 (eval (read cmd))
10725 (call-interactively (read cmd))))
10726 (user-error "Abort"))))
10728 (defun org--open-help-link (path)
10729 "Open a \"help\" type link.
10730 PATH is a symbol name, as a string."
10731 (pcase (intern path)
10732 ((and (pred fboundp) variable) (describe-function variable))
10733 ((and (pred boundp) function) (describe-variable function))
10734 (name (user-error "Unknown function or variable: %s" name))))
10736 (defun org--open-shell-link (path)
10737 "Open a \"shell\" type link.
10738 PATH is the command to execute, as a string."
10739 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10740 (cmd path))
10741 (if (or (and (org-string-nw-p
10742 org-confirm-shell-link-not-regexp)
10743 (string-match
10744 org-confirm-shell-link-not-regexp cmd))
10745 (not org-confirm-shell-link-function)
10746 (funcall org-confirm-shell-link-function
10747 (format "Execute \"%s\" in shell? "
10748 (org-add-props cmd nil
10749 'face 'org-warning))))
10750 (progn
10751 (message "Executing %s" cmd)
10752 (shell-command cmd buf)
10753 (when (featurep 'midnight)
10754 (setq clean-buffer-list-kill-buffer-names
10755 (cons (buffer-name buf)
10756 clean-buffer-list-kill-buffer-names))))
10757 (user-error "Abort"))))
10759 (defun org-open-at-point (&optional arg reference-buffer)
10760 "Open link, timestamp, footnote or tags at point.
10762 When point is on a link, follow it. Normally, files will be
10763 opened by an appropriate application. If the optional prefix
10764 argument ARG is non-nil, Emacs will visit the file. With
10765 a double prefix argument, try to open outside of Emacs, in the
10766 application the system uses for this file type.
10768 When point is on a timestamp, open the agenda at the day
10769 specified.
10771 When point is a footnote definition, move to the first reference
10772 found. If it is on a reference, move to the associated
10773 definition.
10775 When point is on a headline, display a list of every link in the
10776 entry, so it is possible to pick one, or all, of them. If point
10777 is on a tag, call `org-tags-view' instead.
10779 When optional argument REFERENCE-BUFFER is non-nil, it should
10780 specify a buffer from where the link search should happen. This
10781 is used internally by `org-open-link-from-string'.
10783 On top of syntactically correct links, this function will also
10784 try to open links and time-stamps in comments, example
10785 blocks... i.e., whenever point is on something looking like
10786 a timestamp or a link."
10787 (interactive "P")
10788 ;; On a code block, open block's results.
10789 (unless (call-interactively 'org-babel-open-src-block-result)
10790 (org-load-modules-maybe)
10791 (setq org-window-config-before-follow-link (current-window-configuration))
10792 (org-remove-occur-highlights nil nil t)
10793 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10794 (let* ((context
10795 ;; Only consider supported types, even if they are not
10796 ;; the closest one.
10797 (org-element-lineage
10798 (org-element-context)
10799 '(clock footnote-definition footnote-reference headline
10800 inlinetask link timestamp)
10802 (type (org-element-type context))
10803 (value (org-element-property :value context)))
10804 (cond
10805 ;; On a headline or an inlinetask, but not on a timestamp,
10806 ;; a link, a footnote reference or on tags.
10807 ((and (memq type '(headline inlinetask))
10808 ;; Not on tags.
10809 (let ((case-fold-search nil))
10810 (and (org-match-line org-complex-heading-regexp)
10811 (or (not (match-beginning 5))
10812 (< (point) (match-beginning 5))))))
10813 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10814 (links (car data))
10815 (links-end (cdr data)))
10816 (if links
10817 (dolist (link (if (stringp links) (list links) links))
10818 (search-forward link nil links-end)
10819 (goto-char (match-beginning 0))
10820 (org-open-at-point))
10821 (require 'org-attach)
10822 (org-attach-reveal 'if-exists))))
10823 ;; On a footnote reference or at definition's label.
10824 ((or (eq type 'footnote-reference)
10825 (and (eq type 'footnote-definition)
10826 (save-excursion
10827 ;; Do not validate action when point is on the
10828 ;; spaces right after the footnote label, in
10829 ;; order to be on par with behaviour on links.
10830 (skip-chars-forward " \t")
10831 (let ((begin
10832 (org-element-property :contents-begin context)))
10833 (if begin (< (point) begin)
10834 (= (org-element-property :post-affiliated context)
10835 (line-beginning-position)))))))
10836 (org-footnote-action))
10837 ;; No valid context. Ignore catch-all types like `headline'.
10838 ;; If point is on something looking like a link or
10839 ;; a time-stamp, try opening it. It may be useful in
10840 ;; comments, example blocks...
10841 ((memq type '(footnote-definition headline inlinetask nil))
10842 (call-interactively #'org-open-at-point-global))
10843 ;; On a clock line, make sure point is on the timestamp
10844 ;; before opening it.
10845 ((and (eq type 'clock)
10846 value
10847 (>= (point) (org-element-property :begin value))
10848 (<= (point) (org-element-property :end value)))
10849 (org-follow-timestamp-link))
10850 ;; Do nothing on white spaces after an object.
10851 ((>= (point)
10852 (save-excursion
10853 (goto-char (org-element-property :end context))
10854 (skip-chars-backward " \t")
10855 (point)))
10856 (user-error "No link found"))
10857 ((eq type 'timestamp) (org-follow-timestamp-link))
10858 ;; On tags within a headline or an inlinetask.
10859 ((and (memq type '(headline inlinetask))
10860 (let ((case-fold-search nil))
10861 (save-excursion (beginning-of-line)
10862 (looking-at org-complex-heading-regexp))
10863 (and (match-beginning 5)
10864 (>= (point) (match-beginning 5)))))
10865 (org-tags-view arg (substring (match-string 5) 0 -1)))
10866 ((eq type 'link)
10867 ;; When link is located within the description of another
10868 ;; link (e.g., an inline image), always open the parent
10869 ;; link.
10870 (let* ((link (let ((up (org-element-property :parent context)))
10871 (if (eq (org-element-type up) 'link) up context)))
10872 (type (org-element-property :type link))
10873 (path (org-link-unescape (org-element-property :path link))))
10874 ;; Switch back to REFERENCE-BUFFER needed when called in
10875 ;; a temporary buffer through `org-open-link-from-string'.
10876 (with-current-buffer (or reference-buffer (current-buffer))
10877 (cond
10878 ((equal type "file")
10879 (if (string-match "[*?{]" (file-name-nondirectory path))
10880 (dired path)
10881 ;; Look into `org-link-parameters' in order to find
10882 ;; a DEDICATED-FUNCTION to open file. The function
10883 ;; will be applied on raw link instead of parsed
10884 ;; link due to the limitation in `org-add-link-type'
10885 ;; ("open" function called with a single argument).
10886 ;; If no such function is found, fallback to
10887 ;; `org-open-file'.
10888 (let* ((option (org-element-property :search-option link))
10889 (app (org-element-property :application link))
10890 (dedicated-function
10891 (org-link-get-parameter
10892 (if app (concat type "+" app) type)
10893 :follow)))
10894 (if dedicated-function
10895 (funcall dedicated-function
10896 (concat path
10897 (and option (concat "::" option))))
10898 (apply #'org-open-file
10899 path
10900 (cond (arg)
10901 ((equal app "emacs") 'emacs)
10902 ((equal app "sys") 'system))
10903 (cond ((not option) nil)
10904 ((string-match-p "\\`[0-9]+\\'" option)
10905 (list (string-to-number option)))
10906 (t (list nil
10907 (org-link-unescape option)))))))))
10908 ((functionp (org-link-get-parameter type :follow))
10909 (funcall (org-link-get-parameter type :follow) path))
10910 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10911 (unless (run-hook-with-args-until-success
10912 'org-open-link-functions path)
10913 (if (not arg) (org-mark-ring-push)
10914 (switch-to-buffer-other-window
10915 (org-get-buffer-for-internal-link (current-buffer))))
10916 (let ((destination
10917 (org-with-wide-buffer
10918 (if (equal type "radio")
10919 (org-search-radio-target
10920 (org-element-property :path link))
10921 (org-link-search
10922 (if (member type '("custom-id" "coderef"))
10923 (org-element-property :raw-link link)
10924 path)
10925 ;; Prevent fuzzy links from matching
10926 ;; themselves.
10927 (and (equal type "fuzzy")
10928 (+ 2 (org-element-property :begin link)))))
10929 (point))))
10930 (unless (and (<= (point-min) destination)
10931 (>= (point-max) destination))
10932 (widen))
10933 (goto-char destination))))
10934 (t (browse-url-at-point))))))
10935 (t (user-error "No link found")))))
10936 (run-hook-with-args 'org-follow-link-hook)))
10938 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10939 "Offer links in the current entry and return the selected link.
10940 If there is only one link, return it.
10941 If NTH is an integer, return the NTH link found.
10942 If ZERO is a string, check also this string for a link, and if
10943 there is one, return it."
10944 (with-current-buffer buffer
10945 (org-with-wide-buffer
10946 (goto-char marker)
10947 (let ((cnt ?0)
10948 have-zero end links link c)
10949 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10950 (push (match-string 0 zero) links)
10951 (setq cnt (1- cnt) have-zero t))
10952 (save-excursion
10953 (org-back-to-heading t)
10954 (setq end (save-excursion (outline-next-heading) (point)))
10955 (while (re-search-forward org-any-link-re end t)
10956 (push (match-string 0) links))
10957 (setq links (org-uniquify (reverse links))))
10958 (cond
10959 ((null links)
10960 (message "No links"))
10961 ((equal (length links) 1)
10962 (setq link (car links)))
10963 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10964 (setq link (nth (if have-zero nth (1- nth)) links)))
10965 (t ; we have to select a link
10966 (save-excursion
10967 (save-window-excursion
10968 (delete-other-windows)
10969 (with-output-to-temp-buffer "*Select Link*"
10970 (dolist (l links)
10971 (cond
10972 ((not (string-match org-bracket-link-regexp l))
10973 (princ (format "[%c] %s\n" (cl-incf cnt)
10974 (org-unbracket-string "<" ">" l))))
10975 ((match-end 3)
10976 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10977 (match-string 3 l) (match-string 1 l))))
10978 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10979 (match-string 1 l)))))))
10980 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10981 (message "Select link to open, RET to open all:")
10982 (setq c (read-char-exclusive))
10983 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10984 (when (equal c ?q) (user-error "Abort"))
10985 (if (equal c ?\C-m)
10986 (setq link links)
10987 (setq nth (- c ?0))
10988 (when have-zero (setq nth (1+ nth)))
10989 (unless (and (integerp nth) (>= (length links) nth))
10990 (user-error "Invalid link selection"))
10991 (setq link (nth (1- nth) links)))))
10992 (cons link end)))))
10994 ;; TODO: These functions are deprecated since `org-open-at-point'
10995 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10996 (defun org-open-file-with-system (path)
10997 "Open file at PATH using the system way of opening it."
10998 (org-open-file path 'system))
10999 (defun org-open-file-with-emacs (path)
11000 "Open file at PATH in Emacs."
11001 (org-open-file path 'emacs))
11004 ;;; File search
11006 (defvar org-create-file-search-functions nil
11007 "List of functions to construct the right search string for a file link.
11008 These functions are called in turn with point at the location to
11009 which the link should point.
11011 A function in the hook should first test if it would like to
11012 handle this file type, for example by checking the `major-mode'
11013 or the file extension. If it decides not to handle this file, it
11014 should just return nil to give other functions a chance. If it
11015 does handle the file, it must return the search string to be used
11016 when following the link. The search string will be part of the
11017 file link, given after a double colon, and `org-open-at-point'
11018 will automatically search for it. If special measures must be
11019 taken to make the search successful, another function should be
11020 added to the companion hook `org-execute-file-search-functions',
11021 which see.
11023 A function in this hook may also use `setq' to set the variable
11024 `description' to provide a suggestion for the descriptive text to
11025 be used for this link when it gets inserted into an Org buffer
11026 with \\[org-insert-link].")
11028 (defvar org-execute-file-search-functions nil
11029 "List of functions to execute a file search triggered by a link.
11031 Functions added to this hook must accept a single argument, the
11032 search string that was part of the file link, the part after the
11033 double colon. The function must first check if it would like to
11034 handle this search, for example by checking the `major-mode' or
11035 the file extension. If it decides not to handle this search, it
11036 should just return nil to give other functions a chance. If it
11037 does handle the search, it must return a non-nil value to keep
11038 other functions from trying.
11040 Each function can access the current prefix argument through the
11041 variable `current-prefix-arg'. Note that a single prefix is used
11042 to force opening a link in Emacs, so it may be good to only use a
11043 numeric or double prefix to guide the search function.
11045 In case this is needed, a function in this hook can also restore
11046 the window configuration before `org-open-at-point' was called using:
11048 (set-window-configuration org-window-config-before-follow-link)")
11050 (defun org-search-radio-target (target)
11051 "Search a radio target matching TARGET in current buffer.
11052 White spaces are not significant."
11053 (let ((re (format "<<<%s>>>"
11054 (mapconcat #'regexp-quote
11055 (org-split-string target "[ \t\n]+")
11056 "[ \t]+\\(?:\n[ \t]*\\)?")))
11057 (origin (point)))
11058 (goto-char (point-min))
11059 (catch :radio-match
11060 (while (re-search-forward re nil t)
11061 (backward-char)
11062 (let ((object (org-element-context)))
11063 (when (eq (org-element-type object) 'radio-target)
11064 (goto-char (org-element-property :begin object))
11065 (org-show-context 'link-search)
11066 (throw :radio-match nil))))
11067 (goto-char origin)
11068 (user-error "No match for radio target: %s" target))))
11070 (defun org-link-search (s &optional avoid-pos stealth)
11071 "Search for a search string S.
11073 If S starts with \"#\", it triggers a custom ID search.
11075 If S is enclosed within parenthesis, it initiates a coderef
11076 search.
11078 If S is surrounded by forward slashes, it is interpreted as
11079 a regular expression. In Org mode files, this will create an
11080 `org-occur' sparse tree. In ordinary files, `occur' will be used
11081 to list matches. If the current buffer is in `dired-mode', grep
11082 will be used to search in all files.
11084 When AVOID-POS is given, ignore matches near that position.
11086 When optional argument STEALTH is non-nil, do not modify
11087 visibility around point, thus ignoring `org-show-context-detail'
11088 variable.
11090 Search is case-insensitive and ignores white spaces. Return type
11091 of matched result, which is either `dedicated' or `fuzzy'."
11092 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11093 (let* ((case-fold-search t)
11094 (origin (point))
11095 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11096 (starred (eq (string-to-char normalized) ?*))
11097 (words (split-string (if starred (substring s 1) s)))
11098 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
11099 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11100 type)
11101 (cond
11102 ;; Check if there are any special search functions.
11103 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11104 ((eq (string-to-char s) ?#)
11105 ;; Look for a custom ID S if S starts with "#".
11106 (let* ((id (substring normalized 1))
11107 (match (org-find-property "CUSTOM_ID" id)))
11108 (if match (progn (goto-char match) (setf type 'dedicated))
11109 (error "No match for custom ID: %s" id))))
11110 ((string-match "\\`(\\(.*\\))\\'" normalized)
11111 ;; Look for coderef targets if S is enclosed within parenthesis.
11112 (let ((coderef (match-string-no-properties 1 normalized))
11113 (re (substring s-single-re 1 -1)))
11114 (goto-char (point-min))
11115 (catch :coderef-match
11116 (while (re-search-forward re nil t)
11117 (let ((element (org-element-at-point)))
11118 (when (and (memq (org-element-type element)
11119 '(example-block src-block))
11120 ;; Build proper regexp according to current
11121 ;; block's label format.
11122 (let ((label-fmt
11123 (regexp-quote
11124 (or (org-element-property :label-fmt element)
11125 org-coderef-label-format))))
11126 (save-excursion
11127 (beginning-of-line)
11128 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11129 (format label-fmt coderef))))))
11130 (setq type 'dedicated)
11131 (goto-char (match-beginning 1))
11132 (throw :coderef-match nil))))
11133 (goto-char origin)
11134 (error "No match for coderef: %s" coderef))))
11135 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11136 ;; Look for a regular expression.
11137 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11138 (match-string 1 s)))
11139 ;; From here, we handle fuzzy links.
11141 ;; Look for targets, only if not in a headline search.
11142 ((and (not starred)
11143 (let ((target (format "<<%s>>" s-multi-re)))
11144 (catch :target-match
11145 (goto-char (point-min))
11146 (while (re-search-forward target nil t)
11147 (backward-char)
11148 (let ((context (org-element-context)))
11149 (when (eq (org-element-type context) 'target)
11150 (setq type 'dedicated)
11151 (goto-char (org-element-property :begin context))
11152 (throw :target-match t))))
11153 nil))))
11154 ;; Look for elements named after S, only if not in a headline
11155 ;; search.
11156 ((and (not starred)
11157 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11158 (catch :name-match
11159 (goto-char (point-min))
11160 (while (re-search-forward name nil t)
11161 (let ((element (org-element-at-point)))
11162 (when (equal words
11163 (split-string
11164 (org-element-property :name element)))
11165 (setq type 'dedicated)
11166 (beginning-of-line)
11167 (throw :name-match t))))
11168 nil))))
11169 ;; Regular text search. Prefer headlines in Org mode buffers.
11170 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
11171 ;; statistics cookies and tags.
11172 ((and (derived-mode-p 'org-mode)
11173 (let ((title-re
11174 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
11175 org-outline-regexp-bol
11176 org-comment-string
11177 (mapconcat #'regexp-quote words ".+")))
11178 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
11179 (comment-re (format "\\`%s[ \t]+" org-comment-string)))
11180 (goto-char (point-min))
11181 (catch :found
11182 (while (re-search-forward title-re nil t)
11183 (when (equal words
11184 (split-string
11185 (replace-regexp-in-string
11186 cookie-re ""
11187 (replace-regexp-in-string
11188 comment-re "" (org-get-heading t t)))))
11189 (throw :found t)))
11190 nil)))
11191 (beginning-of-line)
11192 (setq type 'dedicated))
11193 ;; Offer to create non-existent headline depending on
11194 ;; `org-link-search-must-match-exact-headline'.
11195 ((and (derived-mode-p 'org-mode)
11196 (not org-link-search-inhibit-query)
11197 (eq org-link-search-must-match-exact-headline 'query-to-create)
11198 (yes-or-no-p "No match - create this as a new heading? "))
11199 (goto-char (point-max))
11200 (unless (bolp) (newline))
11201 (org-insert-heading nil t t)
11202 (insert s "\n")
11203 (beginning-of-line 0))
11204 ;; Only headlines are looked after. No need to process
11205 ;; further: throw an error.
11206 ((and (derived-mode-p 'org-mode)
11207 (or starred org-link-search-must-match-exact-headline))
11208 (goto-char origin)
11209 (error "No match for fuzzy expression: %s" normalized))
11210 ;; Regular text search.
11211 ((catch :fuzzy-match
11212 (goto-char (point-min))
11213 (while (re-search-forward s-multi-re nil t)
11214 ;; Skip match if it contains AVOID-POS or it is included in
11215 ;; a link with a description but outside the description.
11216 (unless (or (and avoid-pos
11217 (<= (match-beginning 0) avoid-pos)
11218 (> (match-end 0) avoid-pos))
11219 (and (save-match-data
11220 (org-in-regexp org-bracket-link-regexp))
11221 (match-beginning 3)
11222 (or (> (match-beginning 3) (point))
11223 (<= (match-end 3) (point)))
11224 (org-element-lineage
11225 (save-match-data (org-element-context))
11226 '(link) t)))
11227 (goto-char (match-beginning 0))
11228 (setq type 'fuzzy)
11229 (throw :fuzzy-match t)))
11230 nil))
11231 ;; All failed. Throw an error.
11232 (t (goto-char origin)
11233 (error "No match for fuzzy expression: %s" normalized)))
11234 ;; Disclose surroundings of match, if appropriate.
11235 (when (and (derived-mode-p 'org-mode) (not stealth))
11236 (org-show-context 'link-search))
11237 type))
11239 (defun org-get-buffer-for-internal-link (buffer)
11240 "Return a buffer to be used for displaying the link target of internal links."
11241 (cond
11242 ((not org-display-internal-link-with-indirect-buffer)
11243 buffer)
11244 ((string-suffix-p "(Clone)" (buffer-name buffer))
11245 (message "Buffer is already a clone, not making another one")
11246 ;; we also do not modify visibility in this case
11247 buffer)
11248 (t ; make a new indirect buffer for displaying the link
11249 (let* ((bn (buffer-name buffer))
11250 (ibn (concat bn "(Clone)"))
11251 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11252 (with-current-buffer ib (org-overview))
11253 ib))))
11255 (defun org-do-occur (regexp &optional cleanup)
11256 "Call the Emacs command `occur'.
11257 If CLEANUP is non-nil, remove the printout of the regular expression
11258 in the *Occur* buffer. This is useful if the regex is long and not useful
11259 to read."
11260 (occur regexp)
11261 (when cleanup
11262 (let ((cwin (selected-window)) win beg end)
11263 (when (setq win (get-buffer-window "*Occur*"))
11264 (select-window win))
11265 (goto-char (point-min))
11266 (when (re-search-forward "match[a-z]+" nil t)
11267 (setq beg (match-end 0))
11268 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11269 (setq end (1- (match-beginning 0)))))
11270 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11271 (goto-char (point-min))
11272 (select-window cwin))))
11274 ;;; The mark ring for links jumps
11276 (defvar org-mark-ring nil
11277 "Mark ring for positions before jumps in Org mode.")
11278 (defvar org-mark-ring-last-goto nil
11279 "Last position in the mark ring used to go back.")
11280 ;; Fill and close the ring
11281 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11282 (dotimes (_ org-mark-ring-length)
11283 (push (make-marker) org-mark-ring))
11284 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11285 org-mark-ring)
11287 (defun org-mark-ring-push (&optional pos buffer)
11288 "Put the current position or POS into the mark ring and rotate it."
11289 (interactive)
11290 (setq pos (or pos (point)))
11291 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11292 (move-marker (car org-mark-ring)
11293 (or pos (point))
11294 (or buffer (current-buffer)))
11295 (message "%s"
11296 (substitute-command-keys
11297 "Position saved to mark ring, go back with \
11298 `\\[org-mark-ring-goto]'.")))
11300 (defun org-mark-ring-goto (&optional n)
11301 "Jump to the previous position in the mark ring.
11302 With prefix arg N, jump back that many stored positions. When
11303 called several times in succession, walk through the entire ring.
11304 Org mode commands jumping to a different position in the current file,
11305 or to another Org file, automatically push the old position onto the ring."
11306 (interactive "p")
11307 (let (p m)
11308 (if (eq last-command this-command)
11309 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11310 (setq p org-mark-ring))
11311 (setq org-mark-ring-last-goto p)
11312 (setq m (car p))
11313 (pop-to-buffer-same-window (marker-buffer m))
11314 (goto-char m)
11315 (when (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11317 (defun org-add-angle-brackets (s)
11318 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11319 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11322 ;;; Following specific links
11324 (defvar org-agenda-buffer-tmp-name)
11325 (defvar org-agenda-start-on-weekday)
11326 (defun org-follow-timestamp-link ()
11327 "Open an agenda view for the time-stamp date/range at point."
11328 (cond
11329 ((org-at-date-range-p t)
11330 (let ((org-agenda-start-on-weekday)
11331 (t1 (match-string 1))
11332 (t2 (match-string 2)) tt1 tt2)
11333 (setq tt1 (time-to-days (org-time-string-to-time t1))
11334 tt2 (time-to-days (org-time-string-to-time t2)))
11335 (let ((org-agenda-buffer-tmp-name
11336 (format "*Org Agenda(a:%s)"
11337 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11338 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11339 ((org-at-timestamp-p t)
11340 (let ((org-agenda-buffer-tmp-name
11341 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11342 (org-agenda-list nil (time-to-days (org-time-string-to-time
11343 (substring (match-string 1) 0 10)))
11344 1)))
11345 (t (error "This should not happen"))))
11348 ;;; Following file links
11349 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11350 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11351 (declare-function mailcap-mime-info
11352 "mailcap" (string &optional request no-decode))
11353 (defvar org-wait nil)
11354 (defun org-open-file (path &optional in-emacs line search)
11355 "Open the file at PATH.
11356 First, this expands any special file name abbreviations. Then the
11357 configuration variable `org-file-apps' is checked if it contains an
11358 entry for this file type, and if yes, the corresponding command is launched.
11360 If no application is found, Emacs simply visits the file.
11362 With optional prefix argument IN-EMACS, Emacs will visit the file.
11363 With a double \\[universal-argument] \\[universal-argument] \
11364 prefix arg, Org tries to avoid opening in Emacs
11365 and to use an external application to visit the file.
11367 Optional LINE specifies a line to go to, optional SEARCH a string
11368 to search for. If LINE or SEARCH is given, the file will be
11369 opened in Emacs, unless an entry from org-file-apps that makes
11370 use of groups in a regexp matches.
11372 If you want to change the way frames are used when following a
11373 link, please customize `org-link-frame-setup'.
11375 If the file does not exist, an error is thrown."
11376 (let* ((file (if (equal path "")
11377 buffer-file-name
11378 (substitute-in-file-name (expand-file-name path))))
11379 (file-apps (append org-file-apps (org-default-apps)))
11380 (apps (cl-remove-if
11381 'org-file-apps-entry-match-against-dlink-p file-apps))
11382 (apps-dlink (cl-remove-if-not
11383 'org-file-apps-entry-match-against-dlink-p file-apps))
11384 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11385 (dirp (unless remp (file-directory-p file)))
11386 (file (if (and dirp org-open-directory-means-index-dot-org)
11387 (concat (file-name-as-directory file) "index.org")
11388 file))
11389 (a-m-a-p (assq 'auto-mode apps))
11390 (dfile (downcase file))
11391 ;; Reconstruct the original link from the PATH, LINE and
11392 ;; SEARCH args.
11393 (link (cond (line (concat file "::" (number-to-string line)))
11394 (search (concat file "::" search))
11395 (t file)))
11396 (dlink (downcase link))
11397 (old-buffer (current-buffer))
11398 (old-pos (point))
11399 (old-mode major-mode)
11400 (ext
11401 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11402 (match-string 1 dfile)))
11403 cmd link-match-data)
11404 (cond
11405 ((member in-emacs '((16) system))
11406 (setq cmd (cdr (assq 'system apps))))
11407 (in-emacs (setq cmd 'emacs))
11409 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11410 (and dirp (cdr (assq 'directory apps)))
11411 ;; First, try matching against apps-dlink if we
11412 ;; get a match here, store the match data for
11413 ;; later.
11414 (let ((match (assoc-default dlink apps-dlink
11415 'string-match)))
11416 (if match
11417 (progn (setq link-match-data (match-data))
11418 match)
11419 (progn (setq in-emacs (or in-emacs line search))
11420 nil))) ; if we have no match in apps-dlink,
11421 ; always open the file in emacs if line or search
11422 ; is given (for backwards compatibility)
11423 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11424 'string-match)
11425 (cdr (assoc ext apps))
11426 (cdr (assq t apps))))))
11427 (when (eq cmd 'system)
11428 (setq cmd (cdr (assq 'system apps))))
11429 (when (eq cmd 'default)
11430 (setq cmd (cdr (assoc t apps))))
11431 (when (eq cmd 'mailcap)
11432 (require 'mailcap)
11433 (mailcap-parse-mailcaps)
11434 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11435 (command (mailcap-mime-info mime-type)))
11436 (if (stringp command)
11437 (setq cmd command)
11438 (setq cmd 'emacs))))
11439 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11440 (not (file-exists-p file))
11441 (not org-open-non-existing-files))
11442 (user-error "No such file: %s" file))
11443 (cond
11444 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11445 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11446 (while (string-match "['\"]%s['\"]" cmd)
11447 (setq cmd (replace-match "%s" t t cmd)))
11448 (setq cmd (replace-regexp-in-string
11449 "%s"
11450 (shell-quote-argument (convert-standard-filename file))
11452 nil t))
11454 ;; Replace "%1", "%2" etc. in command with group matches from regex
11455 (save-match-data
11456 (let ((match-index 1)
11457 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11458 (set-match-data link-match-data)
11459 (while (<= match-index number-of-groups)
11460 (let ((regex (concat "%" (number-to-string match-index)))
11461 (replace-with (match-string match-index dlink)))
11462 (while (string-match regex cmd)
11463 (setq cmd (replace-match replace-with t t cmd))))
11464 (setq match-index (+ match-index 1)))))
11466 (save-window-excursion
11467 (message "Running %s...done" cmd)
11468 (start-process-shell-command cmd nil cmd)
11469 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11470 ((or (stringp cmd)
11471 (eq cmd 'emacs))
11472 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11473 (widen)
11474 (cond (line (org-goto-line line)
11475 (when (derived-mode-p 'org-mode) (org-reveal)))
11476 (search (org-link-search search))))
11477 ((functionp cmd)
11478 (save-match-data
11479 (set-match-data link-match-data)
11480 (condition-case nil
11481 (funcall cmd file link)
11482 ;; FIXME: Remove this check when most default installations
11483 ;; of Emacs have at least Org 9.0.
11484 ((debug wrong-number-of-arguments wrong-type-argument
11485 invalid-function)
11486 (user-error "Please see Org News for version 9.0 about \
11487 `org-file-apps'--Lisp error: %S" cmd)))))
11488 ((consp cmd)
11489 ;; FIXME: Remove this check when most default installations of
11490 ;; Emacs have at least Org 9.0.
11491 ;; Heads-up instead of silently fall back to
11492 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11493 ;; with sexp instead of a function for `cmd'.
11494 (user-error "Please see Org News for version 9.0 about \
11495 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11496 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11497 (and (derived-mode-p 'org-mode)
11498 (eq old-mode 'org-mode)
11499 (or (not (eq old-buffer (current-buffer)))
11500 (not (eq old-pos (point))))
11501 (org-mark-ring-push old-pos old-buffer))))
11503 (defun org-file-apps-entry-match-against-dlink-p (entry)
11504 "This function returns non-nil if `entry' uses a regular
11505 expression which should be matched against the whole link by
11506 org-open-file.
11508 It assumes that is the case when the entry uses a regular
11509 expression which has at least one grouping construct and the
11510 action is either a lisp form or a command string containing
11511 `%1', i.e. using at least one subexpression match as a
11512 parameter."
11513 (let ((selector (car entry))
11514 (action (cdr entry)))
11515 (if (stringp selector)
11516 (and (> (regexp-opt-depth selector) 0)
11517 (or (and (stringp action)
11518 (string-match "%[0-9]" action))
11519 (consp action)))
11520 nil)))
11522 (defun org-default-apps ()
11523 "Return the default applications for this operating system."
11524 (cond
11525 ((eq system-type 'darwin)
11526 org-file-apps-defaults-macosx)
11527 ((eq system-type 'windows-nt)
11528 org-file-apps-defaults-windowsnt)
11529 (t org-file-apps-defaults-gnu)))
11531 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11532 "Convert extensions to regular expressions in the cars of LIST.
11533 Also, weed out any non-string entries, because the return value is used
11534 only for regexp matching.
11535 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11536 point to the symbol `emacs', indicating that the file should
11537 be opened in Emacs."
11538 (append
11539 (delq nil
11540 (mapcar (lambda (x)
11541 (unless (not (stringp (car x)))
11542 (if (string-match "\\W" (car x))
11544 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11545 list))
11546 (when add-auto-mode
11547 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11549 (defvar ange-ftp-name-format)
11550 (defun org-file-remote-p (file)
11551 "Test whether FILE specifies a location on a remote system.
11552 Return non-nil if the location is indeed remote.
11554 For example, the filename \"/user@host:/foo\" specifies a location
11555 on the system \"/user@host:\"."
11556 (cond ((fboundp 'file-remote-p)
11557 (file-remote-p file))
11558 ((fboundp 'tramp-handle-file-remote-p)
11559 (tramp-handle-file-remote-p file))
11560 ((and (boundp 'ange-ftp-name-format)
11561 (string-match (car ange-ftp-name-format) file))
11562 t)))
11565 ;;;; Refiling
11567 (defun org-get-org-file ()
11568 "Read a filename, with default directory `org-directory'."
11569 (let ((default (or org-default-notes-file remember-data-file)))
11570 (read-file-name (format "File name [%s]: " default)
11571 (file-name-as-directory org-directory)
11572 default)))
11574 (defun org-notes-order-reversed-p ()
11575 "Check if the current file should receive notes in reversed order."
11576 (cond
11577 ((not org-reverse-note-order) nil)
11578 ((eq t org-reverse-note-order) t)
11579 ((not (listp org-reverse-note-order)) nil)
11580 (t (catch 'exit
11581 (dolist (entry org-reverse-note-order)
11582 (when (string-match (car entry) buffer-file-name)
11583 (throw 'exit (cdr entry))))))))
11585 (defvar org-refile-target-table nil
11586 "The list of refile targets, created by `org-refile'.")
11588 (defvar org-agenda-new-buffers nil
11589 "Buffers created to visit agenda files.")
11591 (defvar org-refile-cache nil
11592 "Cache for refile targets.")
11594 (defvar org-refile-markers nil
11595 "All the markers used for caching refile locations.")
11597 (defun org-refile-marker (pos)
11598 "Get a new refile marker, but only if caching is in use."
11599 (if (not org-refile-use-cache)
11601 (let ((m (make-marker)))
11602 (move-marker m pos)
11603 (push m org-refile-markers)
11604 m)))
11606 (defun org-refile-cache-clear ()
11607 "Clear the refile cache and disable all the markers."
11608 (dolist (m org-refile-markers) (move-marker m nil))
11609 (setq org-refile-markers nil)
11610 (setq org-refile-cache nil)
11611 (message "Refile cache has been cleared"))
11613 (defun org-refile-cache-check-set (set)
11614 "Check if all the markers in the cache still have live buffers."
11615 (let (marker)
11616 (catch 'exit
11617 (while (and set (setq marker (nth 3 (pop set))))
11618 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11619 (when (and marker (null (marker-buffer marker)))
11620 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11621 (sit-for 3)
11622 (throw 'exit nil)))
11623 t)))
11625 (defun org-refile-cache-put (set &rest identifiers)
11626 "Push the refile targets SET into the cache, under IDENTIFIERS."
11627 (let* ((key (sha1 (prin1-to-string identifiers)))
11628 (entry (assoc key org-refile-cache)))
11629 (if entry
11630 (setcdr entry set)
11631 (push (cons key set) org-refile-cache))))
11633 (defun org-refile-cache-get (&rest identifiers)
11634 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11635 (cond
11636 ((not org-refile-cache) nil)
11637 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11639 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11640 org-refile-cache))))
11641 (and set (org-refile-cache-check-set set) set)))))
11643 (defvar org-outline-path-cache nil
11644 "Alist between buffer positions and outline paths.
11645 It value is an alist (POSITION . PATH) where POSITION is the
11646 buffer position at the beginning of an entry and PATH is a list
11647 of strings describing the outline path for that entry, in reverse
11648 order.")
11650 (defun org-refile-get-targets (&optional default-buffer)
11651 "Produce a table with refile targets."
11652 (let ((case-fold-search nil)
11653 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11654 (entries (or org-refile-targets '((nil . (:level . 1)))))
11655 targets tgs files desc descre)
11656 (message "Getting targets...")
11657 (with-current-buffer (or default-buffer (current-buffer))
11658 (dolist (entry entries)
11659 (setq files (car entry) desc (cdr entry))
11660 (cond
11661 ((null files) (setq files (list (current-buffer))))
11662 ((eq files 'org-agenda-files)
11663 (setq files (org-agenda-files 'unrestricted)))
11664 ((and (symbolp files) (fboundp files))
11665 (setq files (funcall files)))
11666 ((and (symbolp files) (boundp files))
11667 (setq files (symbol-value files))))
11668 (when (stringp files) (setq files (list files)))
11669 (cond
11670 ((eq (car desc) :tag)
11671 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11672 ((eq (car desc) :todo)
11673 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11674 ((eq (car desc) :regexp)
11675 (setq descre (cdr desc)))
11676 ((eq (car desc) :level)
11677 (setq descre (concat "^\\*\\{" (number-to-string
11678 (if org-odd-levels-only
11679 (1- (* 2 (cdr desc)))
11680 (cdr desc)))
11681 "\\}[ \t]")))
11682 ((eq (car desc) :maxlevel)
11683 (setq descre (concat "^\\*\\{1," (number-to-string
11684 (if org-odd-levels-only
11685 (1- (* 2 (cdr desc)))
11686 (cdr desc)))
11687 "\\}[ \t]")))
11688 (t (error "Bad refiling target description %s" desc)))
11689 (dolist (f files)
11690 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11692 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11693 (progn
11694 (when (bufferp f)
11695 (setq f (buffer-file-name (buffer-base-buffer f))))
11696 (setq f (and f (expand-file-name f)))
11697 (when (eq org-refile-use-outline-path 'file)
11698 (push (list (file-name-nondirectory f) f nil nil) tgs))
11699 (org-with-wide-buffer
11700 (goto-char (point-min))
11701 (setq org-outline-path-cache nil)
11702 (while (re-search-forward descre nil t)
11703 (beginning-of-line)
11704 (let ((case-fold-search nil))
11705 (looking-at org-complex-heading-regexp))
11706 (let ((begin (point))
11707 (heading (match-string-no-properties 4)))
11708 (unless (or (and
11709 org-refile-target-verify-function
11710 (not
11711 (funcall org-refile-target-verify-function)))
11712 (not heading))
11713 (let ((re (format org-complex-heading-regexp-format
11714 (regexp-quote heading)))
11715 (target
11716 (if (not org-refile-use-outline-path) heading
11717 (mapconcat
11718 #'org-protect-slash
11719 (append
11720 (pcase org-refile-use-outline-path
11721 (`file (list (file-name-nondirectory
11722 (buffer-file-name
11723 (buffer-base-buffer)))))
11724 (`full-file-path
11725 (list (buffer-file-name
11726 (buffer-base-buffer))))
11727 (_ nil))
11728 (org-get-outline-path t t))
11729 "/"))))
11730 (push (list target f re (org-refile-marker (point)))
11731 tgs)))
11732 (when (= (point) begin)
11733 ;; Verification function has not moved point.
11734 (end-of-line)))))))
11735 (when org-refile-use-cache
11736 (org-refile-cache-put tgs (buffer-file-name) descre))
11737 (setq targets (append tgs targets))))))
11738 (message "Getting targets...done")
11739 (delete-dups (nreverse targets))))
11741 (defun org-protect-slash (s)
11742 (replace-regexp-in-string "/" "\\/" s nil t))
11744 (defun org--get-outline-path-1 (&optional use-cache)
11745 "Return outline path to current headline.
11747 Outline path is a list of strings, in reverse order. When
11748 optional argument USE-CACHE is non-nil, make use of a cache. See
11749 `org-get-outline-path' for details.
11751 Assume buffer is widened and point is on a headline."
11752 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11753 (let ((p (point))
11754 (heading (let ((case-fold-search nil))
11755 (looking-at org-complex-heading-regexp)
11756 (if (not (match-end 4)) ""
11757 ;; Remove statistics cookies.
11758 (org-trim
11759 (org-link-display-format
11760 (replace-regexp-in-string
11761 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11762 (match-string-no-properties 4))))))))
11763 (if (org-up-heading-safe)
11764 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11765 (when use-cache
11766 (push (cons p path) org-outline-path-cache))
11767 path)
11768 ;; This is a new root node. Since we assume we are moving
11769 ;; forward, we can drop previous cache so as to limit number
11770 ;; of associations there.
11771 (let ((path (list heading)))
11772 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11773 path)))))
11775 (defun org-get-outline-path (&optional with-self use-cache)
11776 "Return the outline path to the current entry.
11778 An outline path is a list of ancestors for current headline, as
11779 a list of strings. Statistics cookies are removed and links are
11780 replaced with their description, if any, or their path otherwise.
11782 When optional argument WITH-SELF is non-nil, the path also
11783 includes the current headline.
11785 When optional argument USE-CACHE is non-nil, cache outline paths
11786 between calls to this function so as to avoid backtracking. This
11787 argument is useful when planning to find more than one outline
11788 path in the same document. In that case, there are two
11789 conditions to satisfy:
11790 - `org-outline-path-cache' is set to nil before starting the
11791 process;
11792 - outline paths are computed by increasing buffer positions."
11793 (org-with-wide-buffer
11794 (and (or (and with-self (org-back-to-heading t))
11795 (org-up-heading-safe))
11796 (reverse (org--get-outline-path-1 use-cache)))))
11798 (defun org-format-outline-path (path &optional width prefix separator)
11799 "Format the outline path PATH for display.
11800 WIDTH is the maximum number of characters that is available.
11801 PREFIX is a prefix to be included in the returned string,
11802 such as the file name.
11803 SEPARATOR is inserted between the different parts of the path,
11804 the default is \"/\"."
11805 (setq width (or width 79))
11806 (setq path (delq nil path))
11807 (unless (> width 0)
11808 (user-error "Argument `width' must be positive"))
11809 (setq separator (or separator "/"))
11810 (let* ((org-odd-levels-only nil)
11811 (fpath (concat
11812 prefix (and prefix path separator)
11813 (mapconcat
11814 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11815 (cl-loop for head in path
11816 for n from 0
11817 collect (org-add-props
11818 head nil 'face
11819 (nth (% n org-n-level-faces) org-level-faces)))
11820 separator))))
11821 (when (> (length fpath) width)
11822 (if (< width 7)
11823 ;; It's unlikely that `width' will be this small, but don't
11824 ;; waste characters by adding ".." if it is.
11825 (setq fpath (substring fpath 0 width))
11826 (setf (substring fpath (- width 2)) "..")))
11827 fpath))
11829 (defun org-display-outline-path (&optional file current separator just-return-string)
11830 "Display the current outline path in the echo area.
11832 If FILE is non-nil, prepend the output with the file name.
11833 If CURRENT is non-nil, append the current heading to the output.
11834 SEPARATOR is passed through to `org-format-outline-path'. It separates
11835 the different parts of the path and defaults to \"/\".
11836 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11837 (interactive "P")
11838 (let* (case-fold-search
11839 (bfn (buffer-file-name (buffer-base-buffer)))
11840 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11841 res)
11842 (when current (setq path (append path
11843 (save-excursion
11844 (org-back-to-heading t)
11845 (when (looking-at org-complex-heading-regexp)
11846 (list (match-string 4)))))))
11847 (setq res
11848 (org-format-outline-path
11849 path
11850 (1- (frame-width))
11851 (and file bfn (concat (file-name-nondirectory bfn) separator))
11852 separator))
11853 (if just-return-string
11854 (org-no-properties res)
11855 (org-unlogged-message "%s" res))))
11857 (defvar org-refile-history nil
11858 "History for refiling operations.")
11860 (defvar org-after-refile-insert-hook nil
11861 "Hook run after `org-refile' has inserted its stuff at the new location.
11862 Note that this is still *before* the stuff will be removed from
11863 the *old* location.")
11865 (defvar org-capture-last-stored-marker)
11866 (defvar org-refile-keep nil
11867 "Non-nil means `org-refile' will copy instead of refile.")
11869 (defun org-copy ()
11870 "Like `org-refile', but copy."
11871 (interactive)
11872 (let ((org-refile-keep t))
11873 (funcall 'org-refile nil nil nil "Copy")))
11875 (defun org-refile (&optional arg default-buffer rfloc msg)
11876 "Move the entry or entries at point to another heading.
11878 The list of target headings is compiled using the information in
11879 `org-refile-targets', which see.
11881 At the target location, the entry is filed as a subitem of the
11882 target heading. Depending on `org-reverse-note-order', the new
11883 subitem will either be the first or the last subitem.
11885 If there is an active region, all entries in that region will be
11886 refiled. However, the region must fulfill the requirement that
11887 the first heading sets the top-level of the moved text.
11889 With a `\\[universal-argument]' ARG, the command will only visit the target \
11890 location
11891 and not actually move anything.
11893 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11894 location where the last
11895 refiling operation has put the subtree.
11897 With a numeric prefix argument of `2', refile to the running clock.
11899 With a numeric prefix argument of `3', emulate `org-refile-keep'
11900 being set to t and copy to the target location, don't move it.
11901 Beware that keeping refiled entries may result in duplicated ID
11902 properties.
11904 RFLOC can be a refile location obtained in a different way.
11906 MSG is a string to replace \"Refile\" in the default prompt with
11907 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11909 See also `org-refile-use-outline-path'.
11911 If you are using target caching (see `org-refile-use-cache'), you
11912 have to clear the target cache in order to find new targets.
11913 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11914 prefix argument (`C-u C-u C-u C-c C-w')."
11915 (interactive "P")
11916 (if (member arg '(0 (64)))
11917 (org-refile-cache-clear)
11918 (let* ((actionmsg (cond (msg msg)
11919 ((equal arg 3) "Refile (and keep)")
11920 (t "Refile")))
11921 (regionp (org-region-active-p))
11922 (region-start (and regionp (region-beginning)))
11923 (region-end (and regionp (region-end)))
11924 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11925 pos it nbuf file level reversed)
11926 (setq last-command nil)
11927 (when regionp
11928 (goto-char region-start)
11929 (or (bolp) (goto-char (point-at-bol)))
11930 (setq region-start (point))
11931 (unless (or (org-kill-is-subtree-p
11932 (buffer-substring region-start region-end))
11933 (prog1 org-refile-active-region-within-subtree
11934 (let ((s (point-at-eol)))
11935 (org-toggle-heading)
11936 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11937 (user-error "The region is not a (sequence of) subtree(s)")))
11938 (if (equal arg '(16))
11939 (org-refile-goto-last-stored)
11940 (when (or
11941 (and (equal arg 2)
11942 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11943 (prog1
11944 (setq it (list (or org-clock-heading "running clock")
11945 (buffer-file-name
11946 (marker-buffer org-clock-hd-marker))
11948 (marker-position org-clock-hd-marker)))
11949 (setq arg nil)))
11950 (setq it
11951 (or rfloc
11952 (let (heading-text)
11953 (save-excursion
11954 (unless (and arg (listp arg))
11955 (org-back-to-heading t)
11956 (setq heading-text
11957 (replace-regexp-in-string
11958 org-bracket-link-regexp
11959 "\\3"
11960 (or (nth 4 (org-heading-components))
11961 ""))))
11962 (org-refile-get-location
11963 (cond ((and arg (listp arg)) "Goto")
11964 (regionp (concat actionmsg " region to"))
11965 (t (concat actionmsg " subtree \""
11966 heading-text "\" to")))
11967 default-buffer
11968 (and (not (equal '(4) arg))
11969 org-refile-allow-creating-parent-nodes)))))))
11970 (setq file (nth 1 it)
11971 pos (nth 3 it))
11972 (when (and (not arg)
11974 (equal (buffer-file-name) file)
11975 (if regionp
11976 (and (>= pos region-start)
11977 (<= pos region-end))
11978 (and (>= pos (point))
11979 (< pos (save-excursion
11980 (org-end-of-subtree t t))))))
11981 (error "Cannot refile to position inside the tree or region"))
11982 (setq nbuf (or (find-buffer-visiting file)
11983 (find-file-noselect file)))
11984 (if (and arg (not (equal arg 3)))
11985 (progn
11986 (pop-to-buffer-same-window nbuf)
11987 (goto-char pos)
11988 (org-show-context 'org-goto))
11989 (if regionp
11990 (progn
11991 (org-kill-new (buffer-substring region-start region-end))
11992 (org-save-markers-in-region region-start region-end))
11993 (org-copy-subtree 1 nil t))
11994 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11995 (find-file-noselect file)))
11996 (setq reversed (org-notes-order-reversed-p))
11997 (org-with-wide-buffer
11998 (if pos
11999 (progn
12000 (goto-char pos)
12001 (looking-at org-outline-regexp)
12002 (setq level (org-get-valid-level (funcall outline-level) 1))
12003 (goto-char
12004 (if reversed
12005 (or (outline-next-heading) (point-max))
12006 (or (save-excursion (org-get-next-sibling))
12007 (org-end-of-subtree t t)
12008 (point-max)))))
12009 (setq level 1)
12010 (if (not reversed)
12011 (goto-char (point-max))
12012 (goto-char (point-min))
12013 (or (outline-next-heading) (goto-char (point-max)))))
12014 (unless (bolp) (newline))
12015 (org-paste-subtree level nil nil t)
12016 (when org-log-refile
12017 (org-add-log-setup 'refile nil nil org-log-refile)
12018 (unless (eq org-log-refile 'note)
12019 (save-excursion (org-add-log-note))))
12020 (and org-auto-align-tags
12021 (let ((org-loop-over-headlines-in-active-region nil))
12022 (org-set-tags nil t)))
12023 (let ((bookmark-name (plist-get org-bookmark-names-plist
12024 :last-refile)))
12025 (when bookmark-name
12026 (with-demoted-errors
12027 (bookmark-set bookmark-name))))
12028 ;; If we are refiling for capture, make sure that the
12029 ;; last-capture pointers point here
12030 (when (bound-and-true-p org-capture-is-refiling)
12031 (let ((bookmark-name (plist-get org-bookmark-names-plist
12032 :last-capture-marker)))
12033 (when bookmark-name
12034 (with-demoted-errors
12035 (bookmark-set bookmark-name))))
12036 (move-marker org-capture-last-stored-marker (point)))
12037 (when (fboundp 'deactivate-mark) (deactivate-mark))
12038 (run-hooks 'org-after-refile-insert-hook)))
12039 (unless org-refile-keep
12040 (if regionp
12041 (delete-region (point) (+ (point) (- region-end region-start)))
12042 (delete-region
12043 (and (org-back-to-heading t) (point))
12044 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12045 (when (featurep 'org-inlinetask)
12046 (org-inlinetask-remove-END-maybe))
12047 (setq org-markers-to-move nil)
12048 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12050 (defun org-refile-goto-last-stored ()
12051 "Go to the location where the last refile was stored."
12052 (interactive)
12053 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12054 (message "This is the location of the last refile"))
12056 (defun org-refile--get-location (refloc tbl)
12057 "When user refile to REFLOC, find the associated target in TBL.
12058 Also check `org-refile-target-table'."
12059 (car (delq
12061 (mapcar
12062 (lambda (r) (or (assoc r tbl)
12063 (assoc r org-refile-target-table)))
12064 (list (replace-regexp-in-string "/$" "" refloc)
12065 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12067 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12068 "Prompt the user for a refile location, using PROMPT.
12069 PROMPT should not be suffixed with a colon and a space, because
12070 this function appends the default value from
12071 `org-refile-history' automatically, if that is not empty."
12072 (let ((org-refile-targets org-refile-targets)
12073 (org-refile-use-outline-path org-refile-use-outline-path))
12074 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12075 (unless org-refile-target-table
12076 (user-error "No refile targets"))
12077 (let* ((cbuf (current-buffer))
12078 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12079 (cfunc (if (and org-refile-use-outline-path
12080 org-outline-path-complete-in-steps)
12081 #'org-olpath-completing-read
12082 #'completing-read))
12083 (extra (if org-refile-use-outline-path "/" ""))
12084 (cbnex (concat (buffer-name) extra))
12085 (filename (and cfn (expand-file-name cfn)))
12086 (tbl (mapcar
12087 (lambda (x)
12088 (if (and (not (member org-refile-use-outline-path
12089 '(file full-file-path)))
12090 (not (equal filename (nth 1 x))))
12091 (cons (concat (car x) extra " ("
12092 (file-name-nondirectory (nth 1 x)) ")")
12093 (cdr x))
12094 (cons (concat (car x) extra) (cdr x))))
12095 org-refile-target-table))
12096 (completion-ignore-case t)
12097 cdef
12098 (prompt (concat prompt
12099 (or (and (car org-refile-history)
12100 (concat " (default " (car org-refile-history) ")"))
12101 (and (assoc cbnex tbl) (setq cdef cbnex)
12102 (concat " (default " cbnex ")"))) ": "))
12103 pa answ parent-target child parent old-hist)
12104 (setq old-hist org-refile-history)
12105 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12106 nil 'org-refile-history (or cdef (car org-refile-history))))
12107 (if (setq pa (org-refile--get-location answ tbl))
12108 (progn
12109 (org-refile-check-position pa)
12110 (when (or (not org-refile-history)
12111 (not (eq old-hist org-refile-history))
12112 (not (equal (car pa) (car org-refile-history))))
12113 (setq org-refile-history
12114 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12115 org-refile-history
12116 (cdr org-refile-history))))
12117 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12118 (pop org-refile-history)))
12120 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12121 (progn
12122 (setq parent (match-string 1 answ)
12123 child (match-string 2 answ))
12124 (setq parent-target (org-refile--get-location parent tbl))
12125 (when (and parent-target
12126 (or (eq new-nodes t)
12127 (and (eq new-nodes 'confirm)
12128 (y-or-n-p (format "Create new node \"%s\"? "
12129 child)))))
12130 (org-refile-new-child parent-target child)))
12131 (user-error "Invalid target location")))))
12133 (declare-function org-string-nw-p "org-macs" (s))
12134 (defun org-refile-check-position (refile-pointer)
12135 "Check if the refile pointer matches the headline to which it points."
12136 (let* ((file (nth 1 refile-pointer))
12137 (re (nth 2 refile-pointer))
12138 (pos (nth 3 refile-pointer))
12139 buffer)
12140 (if (and (not (markerp pos)) (not file))
12141 (user-error "Please indicate a target file in the refile path")
12142 (when (org-string-nw-p re)
12143 (setq buffer (if (markerp pos)
12144 (marker-buffer pos)
12145 (or (find-buffer-visiting file)
12146 (find-file-noselect file))))
12147 (with-current-buffer buffer
12148 (org-with-wide-buffer
12149 (goto-char pos)
12150 (beginning-of-line 1)
12151 (unless (looking-at-p re)
12152 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12154 (defun org-refile-new-child (parent-target child)
12155 "Use refile target PARENT-TARGET to add new CHILD below it."
12156 (unless parent-target
12157 (error "Cannot find parent for new node"))
12158 (let ((file (nth 1 parent-target))
12159 (pos (nth 3 parent-target))
12160 level)
12161 (with-current-buffer (or (find-buffer-visiting file)
12162 (find-file-noselect file))
12163 (org-with-wide-buffer
12164 (if pos
12165 (goto-char pos)
12166 (goto-char (point-max))
12167 (unless (bolp) (newline)))
12168 (when (looking-at org-outline-regexp)
12169 (setq level (funcall outline-level))
12170 (org-end-of-subtree t t))
12171 (org-back-over-empty-lines)
12172 (insert "\n" (make-string
12173 (if pos (org-get-valid-level level 1) 1) ?*)
12174 " " child "\n")
12175 (beginning-of-line 0)
12176 (list (concat (car parent-target) "/" child) file "" (point))))))
12178 (defun org-olpath-completing-read (prompt collection &rest args)
12179 "Read an outline path like a file name."
12180 (let ((thetable collection))
12181 (apply #'completing-read
12182 prompt
12183 (lambda (string predicate &optional flag)
12184 (cond
12185 ((eq flag nil) (try-completion string thetable))
12186 ((eq flag t)
12187 (let ((l (length string)))
12188 (mapcar (lambda (x)
12189 (let ((r (substring x l))
12190 (f (if (string-match " ([^)]*)$" x)
12191 (match-string 0 x)
12192 "")))
12193 (if (string-match "/" r)
12194 (concat string (substring r 0 (match-end 0)) f)
12195 x)))
12196 (all-completions string thetable predicate))))
12197 ;; Exact match?
12198 ((eq flag 'lambda) (assoc string thetable))))
12199 args)))
12201 ;;;; Dynamic blocks
12203 (defun org-find-dblock (name)
12204 "Find the first dynamic block with name NAME in the buffer.
12205 If not found, stay at current position and return nil."
12206 (let ((case-fold-search t) pos)
12207 (save-excursion
12208 (goto-char (point-min))
12209 (setq pos (and (re-search-forward
12210 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12211 (match-beginning 0))))
12212 (when pos (goto-char pos))
12213 pos))
12215 (defun org-create-dblock (plist)
12216 "Create a dynamic block section, with parameters taken from PLIST.
12217 PLIST must contain a :name entry which is used as the name of the block."
12218 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12219 (end-of-line 1)
12220 (newline))
12221 (let ((col (current-column))
12222 (name (plist-get plist :name)))
12223 (insert "#+BEGIN: " name)
12224 (while plist
12225 (if (eq (car plist) :name)
12226 (setq plist (cddr plist))
12227 (insert " " (prin1-to-string (pop plist)))))
12228 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12229 (beginning-of-line -2)))
12231 (defun org-prepare-dblock ()
12232 "Prepare dynamic block for refresh.
12233 This empties the block, puts the cursor at the insert position and returns
12234 the property list including an extra property :name with the block name."
12235 (unless (looking-at org-dblock-start-re)
12236 (user-error "Not at a dynamic block"))
12237 (let* ((begdel (1+ (match-end 0)))
12238 (name (org-no-properties (match-string 1)))
12239 (params (append (list :name name)
12240 (read (concat "(" (match-string 3) ")")))))
12241 (save-excursion
12242 (beginning-of-line 1)
12243 (skip-chars-forward " \t")
12244 (setq params (plist-put params :indentation-column (current-column))))
12245 (unless (re-search-forward org-dblock-end-re nil t)
12246 (error "Dynamic block not terminated"))
12247 (setq params
12248 (append params
12249 (list :content (buffer-substring
12250 begdel (match-beginning 0)))))
12251 (delete-region begdel (match-beginning 0))
12252 (goto-char begdel)
12253 (open-line 1)
12254 params))
12256 (defun org-map-dblocks (&optional command)
12257 "Apply COMMAND to all dynamic blocks in the current buffer.
12258 If COMMAND is not given, use `org-update-dblock'."
12259 (let ((cmd (or command 'org-update-dblock)))
12260 (save-excursion
12261 (goto-char (point-min))
12262 (while (re-search-forward org-dblock-start-re nil t)
12263 (goto-char (match-beginning 0))
12264 (save-excursion
12265 (condition-case nil
12266 (funcall cmd)
12267 (error (message "Error during update of dynamic block"))))
12268 (unless (re-search-forward org-dblock-end-re nil t)
12269 (error "Dynamic block not terminated"))))))
12271 (defun org-dblock-update (&optional arg)
12272 "User command for updating dynamic blocks.
12273 Update the dynamic block at point. With prefix ARG, update all dynamic
12274 blocks in the buffer."
12275 (interactive "P")
12276 (if arg
12277 (org-update-all-dblocks)
12278 (or (looking-at org-dblock-start-re)
12279 (org-beginning-of-dblock))
12280 (org-update-dblock)))
12282 (defun org-update-dblock ()
12283 "Update the dynamic block at point.
12284 This means to empty the block, parse for parameters and then call
12285 the correct writing function."
12286 (interactive)
12287 (save-excursion
12288 (let* ((win (selected-window))
12289 (pos (point))
12290 (line (org-current-line))
12291 (params (org-prepare-dblock))
12292 (name (plist-get params :name))
12293 (indent (plist-get params :indentation-column))
12294 (cmd (intern (concat "org-dblock-write:" name))))
12295 (message "Updating dynamic block `%s' at line %d..." name line)
12296 (funcall cmd params)
12297 (message "Updating dynamic block `%s' at line %d...done" name line)
12298 (goto-char pos)
12299 (when (and indent (> indent 0))
12300 (setq indent (make-string indent ?\ ))
12301 (save-excursion
12302 (select-window win)
12303 (org-beginning-of-dblock)
12304 (forward-line 1)
12305 (while (not (looking-at org-dblock-end-re))
12306 (insert indent)
12307 (beginning-of-line 2))
12308 (when (looking-at org-dblock-end-re)
12309 (and (looking-at "[ \t]+")
12310 (replace-match ""))
12311 (insert indent)))))))
12313 (defun org-beginning-of-dblock ()
12314 "Find the beginning of the dynamic block at point.
12315 Error if there is no such block at point."
12316 (let ((pos (point))
12317 beg)
12318 (end-of-line 1)
12319 (if (and (re-search-backward org-dblock-start-re nil t)
12320 (setq beg (match-beginning 0))
12321 (re-search-forward org-dblock-end-re nil t)
12322 (> (match-end 0) pos))
12323 (goto-char beg)
12324 (goto-char pos)
12325 (error "Not in a dynamic block"))))
12327 (defun org-update-all-dblocks ()
12328 "Update all dynamic blocks in the buffer.
12329 This function can be used in a hook."
12330 (interactive)
12331 (when (derived-mode-p 'org-mode)
12332 (org-map-dblocks 'org-update-dblock)))
12335 ;;;; Completion
12337 (declare-function org-export-backend-options "ox" (cl-x) t)
12338 (defun org-get-export-keywords ()
12339 "Return a list of all currently understood export keywords.
12340 Export keywords include options, block names, attributes and
12341 keywords relative to each registered export back-end."
12342 (let (keywords)
12343 (dolist (backend
12344 (bound-and-true-p org-export-registered-backends)
12345 (delq nil keywords))
12346 ;; Back-end name (for keywords, like #+LATEX:)
12347 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12348 (dolist (option-entry (org-export-backend-options backend))
12349 ;; Back-end options.
12350 (push (nth 1 option-entry) keywords)))))
12352 (defconst org-options-keywords
12353 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12354 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12355 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12356 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12357 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12359 (defcustom org-structure-template-alist
12360 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12361 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12362 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12363 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12364 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12365 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12366 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12367 ("L" "#+LaTeX: ")
12368 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12369 ("H" "#+HTML: ")
12370 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12371 ("A" "#+ASCII: ")
12372 ("i" "#+INDEX: ?")
12373 ("I" "#+INCLUDE: %file ?"))
12374 "Structure completion elements.
12375 This is a list of abbreviation keys and values. The value gets inserted
12376 if you type `<' followed by the key and then press the completion key,
12377 usually `TAB'. %file will be replaced by a file name after prompting
12378 for the file using completion. The cursor will be placed at the position
12379 of the `?' in the template.
12380 There are two templates for each key, the first uses the original Org syntax,
12381 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12382 the default when the /org-mtags.el/ module has been loaded. See also the
12383 variable `org-mtags-prefer-muse-templates'."
12384 :group 'org-completion
12385 :type '(repeat
12386 (list
12387 (string :tag "Key")
12388 (string :tag "Template")))
12389 :version "26.1"
12390 :package-version '(Org . "8.3"))
12392 (defun org-try-structure-completion ()
12393 "Try to complete a structure template before point.
12394 This looks for strings like \"<e\" on an otherwise empty line and
12395 expands them."
12396 (let ((l (buffer-substring (point-at-bol) (point)))
12398 (when (and (looking-at "[ \t]*$")
12399 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12400 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12401 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12402 (match-beginning 1)) a)
12403 t)))
12405 (defun org-complete-expand-structure-template (start cell)
12406 "Expand a structure template."
12407 (let ((rpl (nth 1 cell))
12408 (ind ""))
12409 (delete-region start (point))
12410 (when (string-match "\\`[ \t]*#\\+" rpl)
12411 (cond
12412 ((bolp))
12413 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12414 (setq ind (buffer-substring (point-at-bol) (point))))
12415 (t (newline))))
12416 (setq start (point))
12417 (when (string-match "%file" rpl)
12418 (setq rpl (replace-match
12419 (concat
12420 "\""
12421 (save-match-data
12422 (abbreviate-file-name (read-file-name "Include file: ")))
12423 "\"")
12424 t t rpl)))
12425 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12426 (concat "\n" ind)))
12427 (insert rpl)
12428 (when (re-search-backward "\\?" start t) (delete-char 1))))
12430 ;;;; TODO, DEADLINE, Comments
12432 (defun org-toggle-comment ()
12433 "Change the COMMENT state of an entry."
12434 (interactive)
12435 (save-excursion
12436 (org-back-to-heading)
12437 (let ((case-fold-search nil))
12438 (looking-at org-complex-heading-regexp))
12439 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12440 (skip-chars-forward " \t")
12441 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12442 (if (org-in-commented-heading-p t)
12443 (delete-region (point)
12444 (progn (search-forward " " (line-end-position) 'move)
12445 (skip-chars-forward " \t")
12446 (point)))
12447 (insert org-comment-string)
12448 (unless (eolp) (insert " ")))))
12450 (defvar org-last-todo-state-is-todo nil
12451 "This is non-nil when the last TODO state change led to a TODO state.
12452 If the last change removed the TODO tag or switched to DONE, then
12453 this is nil.")
12455 (defvar org-setting-tags nil) ; dynamically skipped
12457 (defvar org-todo-setup-filter-hook nil
12458 "Hook for functions that pre-filter todo specs.
12459 Each function takes a todo spec and returns either nil or the spec
12460 transformed into canonical form." )
12462 (defvar org-todo-get-default-hook nil
12463 "Hook for functions that get a default item for todo.
12464 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12465 nil or a string to be used for the todo mark." )
12467 (defvar org-agenda-headline-snapshot-before-repeat)
12469 (defun org-current-effective-time ()
12470 "Return current time adjusted for `org-extend-today-until' variable."
12471 (let* ((ct (org-current-time))
12472 (dct (decode-time ct))
12473 (ct1
12474 (cond
12475 (org-use-last-clock-out-time-as-effective-time
12476 (or (org-clock-get-last-clock-out-time) ct))
12477 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12478 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12479 (t ct))))
12480 ct1))
12482 (defun org-todo-yesterday (&optional arg)
12483 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12484 (interactive "P")
12485 (if (eq major-mode 'org-agenda-mode)
12486 (apply 'org-agenda-todo-yesterday arg)
12487 (let* ((org-use-effective-time t)
12488 (hour (nth 2 (decode-time (org-current-time))))
12489 (org-extend-today-until (1+ hour)))
12490 (org-todo arg))))
12492 (defvar org-block-entry-blocking ""
12493 "First entry preventing the TODO state change.")
12495 (defun org-cancel-repeater ()
12496 "Cancel a repeater by setting its numeric value to zero."
12497 (interactive)
12498 (save-excursion
12499 (org-back-to-heading t)
12500 (let ((bound1 (point))
12501 (bound0 (save-excursion (outline-next-heading) (point))))
12502 (when (and (re-search-forward
12503 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12504 org-deadline-time-regexp "\\)\\|\\("
12505 org-ts-regexp "\\)")
12506 bound0 t)
12507 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12508 bound1 t))
12509 (replace-match "0" t nil nil 1)))))
12511 (defvar org-state)
12512 (defvar org-blocked-by-checkboxes)
12513 (defun org-todo (&optional arg)
12514 "Change the TODO state of an item.
12516 The state of an item is given by a keyword at the start of the heading,
12517 like
12518 *** TODO Write paper
12519 *** DONE Call mom
12521 The different keywords are specified in the variable `org-todo-keywords'.
12522 By default the available states are \"TODO\" and \"DONE\". So, for this
12523 example: when the item starts with TODO, it is changed to DONE.
12524 When it starts with DONE, the DONE is removed. And when neither TODO nor
12525 DONE are present, add TODO at the beginning of the heading.
12527 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12528 state.
12529 With numeric prefix ARG, switch to that state.
12530 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12531 next set of TODO \
12532 keywords (nextset).
12533 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12534 prefix, circumvent any state blocking.
12535 With a numeric prefix arg of 0, inhibit note taking for the change.
12536 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12538 When called through ELisp, arg is also interpreted in the following way:
12539 `none' -> empty state
12540 \"\" -> switch to empty state
12541 `done' -> switch to DONE
12542 `nextset' -> switch to the next set of keywords
12543 `previousset' -> switch to the previous set of keywords
12544 \"WAITING\" -> switch to the specified keyword, but only if it
12545 really is a member of `org-todo-keywords'."
12546 (interactive "P")
12547 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12548 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12549 'region-start-level 'region))
12550 org-loop-over-headlines-in-active-region)
12551 (org-map-entries
12552 `(org-todo ,arg)
12553 org-loop-over-headlines-in-active-region
12554 cl (when (org-invisible-p) (org-end-of-subtree nil t))))
12555 (when (equal arg '(16)) (setq arg 'nextset))
12556 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12557 (let ((org-blocker-hook org-blocker-hook)
12558 commentp
12559 case-fold-search)
12560 (when (equal arg '(64))
12561 (setq arg nil org-blocker-hook nil))
12562 (when (and org-blocker-hook
12563 (or org-inhibit-blocking
12564 (org-entry-get nil "NOBLOCKING")))
12565 (setq org-blocker-hook nil))
12566 (save-excursion
12567 (catch 'exit
12568 (org-back-to-heading t)
12569 (when (org-in-commented-heading-p t)
12570 (org-toggle-comment)
12571 (setq commentp t))
12572 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12573 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12574 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12575 (let* ((match-data (match-data))
12576 (startpos (point-at-bol))
12577 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12578 (org-log-done org-log-done)
12579 (org-log-repeat org-log-repeat)
12580 (org-todo-log-states org-todo-log-states)
12581 (org-inhibit-logging
12582 (if (equal arg 0)
12583 (progn (setq arg nil) 'note) org-inhibit-logging))
12584 (this (match-string 1))
12585 (hl-pos (match-beginning 0))
12586 (head (org-get-todo-sequence-head this))
12587 (ass (assoc head org-todo-kwd-alist))
12588 (interpret (nth 1 ass))
12589 (done-word (nth 3 ass))
12590 (final-done-word (nth 4 ass))
12591 (org-last-state (or this ""))
12592 (completion-ignore-case t)
12593 (member (member this org-todo-keywords-1))
12594 (tail (cdr member))
12595 (org-state (cond
12596 ((and org-todo-key-trigger
12597 (or (and (equal arg '(4))
12598 (eq org-use-fast-todo-selection 'prefix))
12599 (and (not arg) org-use-fast-todo-selection
12600 (not (eq org-use-fast-todo-selection
12601 'prefix)))))
12602 ;; Use fast selection.
12603 (org-fast-todo-selection))
12604 ((and (equal arg '(4))
12605 (or (not org-use-fast-todo-selection)
12606 (not org-todo-key-trigger)))
12607 ;; Read a state with completion.
12608 (completing-read
12609 "State: " (mapcar #'list org-todo-keywords-1)
12610 nil t))
12611 ((eq arg 'right)
12612 (if this
12613 (if tail (car tail) nil)
12614 (car org-todo-keywords-1)))
12615 ((eq arg 'left)
12616 (unless (equal member org-todo-keywords-1)
12617 (if this
12618 (nth (- (length org-todo-keywords-1)
12619 (length tail) 2)
12620 org-todo-keywords-1)
12621 (org-last org-todo-keywords-1))))
12622 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12623 (setq arg nil))) ;hack to fall back to cycling
12624 (arg
12625 ;; User or caller requests a specific state.
12626 (cond
12627 ((equal arg "") nil)
12628 ((eq arg 'none) nil)
12629 ((eq arg 'done) (or done-word (car org-done-keywords)))
12630 ((eq arg 'nextset)
12631 (or (car (cdr (member head org-todo-heads)))
12632 (car org-todo-heads)))
12633 ((eq arg 'previousset)
12634 (let ((org-todo-heads (reverse org-todo-heads)))
12635 (or (car (cdr (member head org-todo-heads)))
12636 (car org-todo-heads))))
12637 ((car (member arg org-todo-keywords-1)))
12638 ((stringp arg)
12639 (user-error "State `%s' not valid in this file" arg))
12640 ((nth (1- (prefix-numeric-value arg))
12641 org-todo-keywords-1))))
12642 ((null member) (or head (car org-todo-keywords-1)))
12643 ((equal this final-done-word) nil) ;-> make empty
12644 ((null tail) nil) ;-> first entry
12645 ((memq interpret '(type priority))
12646 (if (eq this-command last-command)
12647 (car tail)
12648 (if (> (length tail) 0)
12649 (or done-word (car org-done-keywords))
12650 nil)))
12652 (car tail))))
12653 (org-state (or
12654 (run-hook-with-args-until-success
12655 'org-todo-get-default-hook org-state org-last-state)
12656 org-state))
12657 (next (if org-state (concat " " org-state " ") " "))
12658 (change-plist (list :type 'todo-state-change :from this :to org-state
12659 :position startpos))
12660 dolog now-done-p)
12661 (when org-blocker-hook
12662 (let (org-blocked-by-checkboxes block-reason)
12663 (setq org-last-todo-state-is-todo
12664 (not (member this org-done-keywords)))
12665 (unless (save-excursion
12666 (save-match-data
12667 (org-with-wide-buffer
12668 (run-hook-with-args-until-failure
12669 'org-blocker-hook change-plist))))
12670 (setq block-reason (if org-blocked-by-checkboxes
12671 "contained checkboxes"
12672 (format "\"%s\"" org-block-entry-blocking)))
12673 (if (called-interactively-p 'interactive)
12674 (user-error "TODO state change from %s to %s blocked (by %s)"
12675 this org-state block-reason)
12676 ;; Fail silently.
12677 (message "TODO state change from %s to %s blocked (by %s)"
12678 this org-state block-reason)
12679 (throw 'exit nil)))))
12680 (store-match-data match-data)
12681 (replace-match next t t)
12682 (cond ((equal this org-state)
12683 (message "TODO state was already %s" (org-trim next)))
12684 ((pos-visible-in-window-p hl-pos)
12685 (message "TODO state changed to %s" (org-trim next))))
12686 (unless head
12687 (setq head (org-get-todo-sequence-head org-state)
12688 ass (assoc head org-todo-kwd-alist)
12689 interpret (nth 1 ass)
12690 done-word (nth 3 ass)
12691 final-done-word (nth 4 ass)))
12692 (when (memq arg '(nextset previousset))
12693 (message "Keyword-Set %d/%d: %s"
12694 (- (length org-todo-sets) -1
12695 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12696 (length org-todo-sets)
12697 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12698 (setq org-last-todo-state-is-todo
12699 (not (member org-state org-done-keywords)))
12700 (setq now-done-p (and (member org-state org-done-keywords)
12701 (not (member this org-done-keywords))))
12702 (and logging (org-local-logging logging))
12703 (when (and (or org-todo-log-states org-log-done)
12704 (not (eq org-inhibit-logging t))
12705 (not (memq arg '(nextset previousset))))
12706 ;; We need to look at recording a time and note.
12707 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12708 (nth 2 (assoc this org-todo-log-states))))
12709 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12710 (setq dolog 'time))
12711 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12712 (and org-state
12713 (member org-state org-not-done-keywords)
12714 (not (member this org-not-done-keywords))))
12715 ;; This is now a todo state and was not one before
12716 ;; If there was a CLOSED time stamp, get rid of it.
12717 (org-add-planning-info nil nil 'closed))
12718 (when (and now-done-p org-log-done)
12719 ;; It is now done, and it was not done before.
12720 (org-add-planning-info 'closed (org-current-effective-time))
12721 (when (and (not dolog) (eq 'note org-log-done))
12722 (org-add-log-setup 'done org-state this 'note)))
12723 (when (and org-state dolog)
12724 ;; This is a non-nil state, and we need to log it.
12725 (org-add-log-setup 'state org-state this dolog)))
12726 ;; Fixup tag positioning.
12727 (org-todo-trigger-tag-changes org-state)
12728 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12729 (when org-provide-todo-statistics
12730 (org-update-parent-todo-statistics))
12731 (run-hooks 'org-after-todo-state-change-hook)
12732 (when (and arg (not (member org-state org-done-keywords)))
12733 (setq head (org-get-todo-sequence-head org-state)))
12734 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12735 ;; Do we need to trigger a repeat?
12736 (when now-done-p
12737 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12738 ;; This is for the agenda, take a snapshot of the headline.
12739 (save-match-data
12740 (setq org-agenda-headline-snapshot-before-repeat
12741 (org-get-heading))))
12742 (org-auto-repeat-maybe org-state))
12743 ;; Fixup cursor location if close to the keyword.
12744 (when (and (outline-on-heading-p)
12745 (not (bolp))
12746 (save-excursion (beginning-of-line 1)
12747 (looking-at org-todo-line-regexp))
12748 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12749 (goto-char (or (match-end 2) (match-end 1)))
12750 (and (looking-at " ") (just-one-space)))
12751 (when org-trigger-hook
12752 (save-excursion
12753 (run-hook-with-args 'org-trigger-hook change-plist)))
12754 (when commentp (org-toggle-comment))))))))
12756 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12757 "Block turning an entry into a TODO, using the hierarchy.
12758 This checks whether the current task should be blocked from state
12759 changes. Such blocking occurs when:
12761 1. The task has children which are not all in a completed state.
12763 2. A task has a parent with the property :ORDERED:, and there
12764 are siblings prior to the current task with incomplete
12765 status.
12767 3. The parent of the task is blocked because it has siblings that should
12768 be done first, or is child of a block grandparent TODO entry."
12770 (if (not org-enforce-todo-dependencies)
12771 t ; if locally turned off don't block
12772 (catch 'dont-block
12773 ;; If this is not a todo state change, or if this entry is already DONE,
12774 ;; do not block
12775 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12776 (member (plist-get change-plist :from)
12777 (cons 'done org-done-keywords))
12778 (member (plist-get change-plist :to)
12779 (cons 'todo org-not-done-keywords))
12780 (not (plist-get change-plist :to)))
12781 (throw 'dont-block t))
12782 ;; If this task has children, and any are undone, it's blocked
12783 (save-excursion
12784 (org-back-to-heading t)
12785 (let ((this-level (funcall outline-level)))
12786 (outline-next-heading)
12787 (let ((child-level (funcall outline-level)))
12788 (while (and (not (eobp))
12789 (> child-level this-level))
12790 ;; this todo has children, check whether they are all
12791 ;; completed
12792 (when (and (not (org-entry-is-done-p))
12793 (org-entry-is-todo-p))
12794 (setq org-block-entry-blocking (org-get-heading))
12795 (throw 'dont-block nil))
12796 (outline-next-heading)
12797 (setq child-level (funcall outline-level))))))
12798 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12799 ;; any previous siblings are undone, it's blocked
12800 (save-excursion
12801 (org-back-to-heading t)
12802 (let* ((pos (point))
12803 (parent-pos (and (org-up-heading-safe) (point)))
12804 (case-fold-search nil))
12805 (unless parent-pos (throw 'dont-block t)) ; no parent
12806 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12807 (forward-line 1)
12808 (re-search-forward org-not-done-heading-regexp pos t))
12809 (setq org-block-entry-blocking (match-string 0))
12810 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12811 ;; Search further up the hierarchy, to see if an ancestor is blocked
12812 (while t
12813 (goto-char parent-pos)
12814 (unless (looking-at org-not-done-heading-regexp)
12815 (throw 'dont-block t)) ; do not block, parent is not a TODO
12816 (setq pos (point))
12817 (setq parent-pos (and (org-up-heading-safe) (point)))
12818 (unless parent-pos (throw 'dont-block t)) ; no parent
12819 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12820 (forward-line 1)
12821 (re-search-forward org-not-done-heading-regexp pos t)
12822 (setq org-block-entry-blocking (org-get-heading)))
12823 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12825 (defcustom org-track-ordered-property-with-tag nil
12826 "Should the ORDERED property also be shown as a tag?
12827 The ORDERED property decides if an entry should require subtasks to be
12828 completed in sequence. Since a property is not very visible, setting
12829 this option means that toggling the ORDERED property with the command
12830 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12831 not relevant for the behavior, but it makes things more visible.
12833 Note that toggling the tag with tags commands will not change the property
12834 and therefore not influence behavior!
12836 This can be t, meaning the tag ORDERED should be used, It can also be a
12837 string to select a different tag for this task."
12838 :group 'org-todo
12839 :type '(choice
12840 (const :tag "No tracking" nil)
12841 (const :tag "Track with ORDERED tag" t)
12842 (string :tag "Use other tag")))
12844 (defun org-toggle-ordered-property ()
12845 "Toggle the ORDERED property of the current entry.
12846 For better visibility, you can track the value of this property with a tag.
12847 See variable `org-track-ordered-property-with-tag'."
12848 (interactive)
12849 (let* ((t1 org-track-ordered-property-with-tag)
12850 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12851 (save-excursion
12852 (org-back-to-heading)
12853 (if (org-entry-get nil "ORDERED")
12854 (progn
12855 (org-delete-property "ORDERED")
12856 (and tag (org-toggle-tag tag 'off))
12857 (message "Subtasks can be completed in arbitrary order"))
12858 (org-entry-put nil "ORDERED" "t")
12859 (and tag (org-toggle-tag tag 'on))
12860 (message "Subtasks must be completed in sequence")))))
12862 (defun org-block-todo-from-checkboxes (change-plist)
12863 "Block turning an entry into a TODO, using checkboxes.
12864 This checks whether the current task should be blocked from state
12865 changes because there are unchecked boxes in this entry."
12866 (if (not org-enforce-todo-checkbox-dependencies)
12867 t ; if locally turned off don't block
12868 (catch 'dont-block
12869 ;; If this is not a todo state change, or if this entry is already DONE,
12870 ;; do not block
12871 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12872 (member (plist-get change-plist :from)
12873 (cons 'done org-done-keywords))
12874 (member (plist-get change-plist :to)
12875 (cons 'todo org-not-done-keywords))
12876 (not (plist-get change-plist :to)))
12877 (throw 'dont-block t))
12878 ;; If this task has checkboxes that are not checked, it's blocked
12879 (save-excursion
12880 (org-back-to-heading t)
12881 (let ((beg (point)) end)
12882 (outline-next-heading)
12883 (setq end (point))
12884 (goto-char beg)
12885 (when (org-list-search-forward
12886 (concat (org-item-beginning-re)
12887 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12888 "\\[[- ]\\]")
12889 end t)
12890 (when (boundp 'org-blocked-by-checkboxes)
12891 (setq org-blocked-by-checkboxes t))
12892 (throw 'dont-block nil))))
12893 t))) ; do not block
12895 (defun org-entry-blocked-p ()
12896 "Non-nil if entry at point is blocked."
12897 (and (not (org-entry-get nil "NOBLOCKING"))
12898 (member (org-entry-get nil "TODO") org-not-done-keywords)
12899 (not (run-hook-with-args-until-failure
12900 'org-blocker-hook
12901 (list :type 'todo-state-change
12902 :position (point)
12903 :from 'todo
12904 :to 'done)))))
12906 (defun org-update-statistics-cookies (all)
12907 "Update the statistics cookie, either from TODO or from checkboxes.
12908 This should be called with the cursor in a line with a statistics
12909 cookie. When called with a \\[universal-argument] prefix, update
12910 all statistics cookies in the buffer."
12911 (interactive "P")
12912 (if all
12913 (progn
12914 (org-update-checkbox-count 'all)
12915 (org-map-entries 'org-update-parent-todo-statistics))
12916 (if (not (org-at-heading-p))
12917 (org-update-checkbox-count)
12918 (let ((pos (point-marker))
12919 end l1 l2)
12920 (ignore-errors (org-back-to-heading t))
12921 (if (not (org-at-heading-p))
12922 (org-update-checkbox-count)
12923 (setq l1 (org-outline-level))
12924 (setq end (save-excursion
12925 (outline-next-heading)
12926 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12927 (point)))
12928 (if (and (save-excursion
12929 (re-search-forward
12930 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12931 (not (save-excursion (re-search-forward
12932 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12933 (org-update-checkbox-count)
12934 (if (and l2 (> l2 l1))
12935 (progn
12936 (goto-char end)
12937 (org-update-parent-todo-statistics))
12938 (goto-char pos)
12939 (beginning-of-line 1)
12940 (while (re-search-forward
12941 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12942 (point-at-eol) t)
12943 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12944 (goto-char pos)
12945 (move-marker pos nil)))))
12947 (defvar org-entry-property-inherited-from) ;; defined below
12948 (defun org-update-parent-todo-statistics ()
12949 "Update any statistics cookie in the parent of the current headline.
12950 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12951 the entire subtree and this will travel up the hierarchy and update
12952 statistics everywhere."
12953 (let* ((prop (save-excursion (org-up-heading-safe)
12954 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12955 (recursive (or (not org-hierarchical-todo-statistics)
12956 (and prop (string-match "\\<recursive\\>" prop))))
12957 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12959 (first t)
12960 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12961 level ltoggle l1 new ndel
12962 (cnt-all 0) (cnt-done 0) is-percent kwd
12963 checkbox-beg cookie-present)
12964 (catch 'exit
12965 (save-excursion
12966 (beginning-of-line 1)
12967 (setq ltoggle (funcall outline-level))
12968 ;; Three situations are to consider:
12970 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12971 ;; to the top-level ancestor on the headline;
12973 ;; 2. If parent has "recursive" property, repeat up to the
12974 ;; headline setting that property, taking inheritance into
12975 ;; account;
12977 ;; 3. Else, move up to direct parent and proceed only once.
12978 (while (and (setq level (org-up-heading-safe))
12979 (or recursive first)
12980 (>= (point) lim))
12981 (setq first nil cookie-present nil)
12982 (unless (and level
12983 (not (string-match
12984 "\\<checkbox\\>"
12985 (downcase (or (org-entry-get nil "COOKIE_DATA")
12986 "")))))
12987 (throw 'exit nil))
12988 (while (re-search-forward box-re (point-at-eol) t)
12989 (setq cnt-all 0 cnt-done 0 cookie-present t)
12990 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12991 (save-match-data
12992 (unless (outline-next-heading) (throw 'exit nil))
12993 (while (and (looking-at org-complex-heading-regexp)
12994 (> (setq l1 (length (match-string 1))) level))
12995 (setq kwd (and (or recursive (= l1 ltoggle))
12996 (match-string 2)))
12997 (if (or (eq org-provide-todo-statistics 'all-headlines)
12998 (and (eq org-provide-todo-statistics t)
12999 (or (member kwd org-done-keywords)))
13000 (and (listp org-provide-todo-statistics)
13001 (stringp (car org-provide-todo-statistics))
13002 (or (member kwd org-provide-todo-statistics)
13003 (member kwd org-done-keywords)))
13004 (and (listp org-provide-todo-statistics)
13005 (listp (car org-provide-todo-statistics))
13006 (or (member kwd (car org-provide-todo-statistics))
13007 (and (member kwd org-done-keywords)
13008 (member kwd (cadr org-provide-todo-statistics))))))
13009 (setq cnt-all (1+ cnt-all))
13010 (and (eq org-provide-todo-statistics t)
13012 (setq cnt-all (1+ cnt-all))))
13013 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
13014 (member kwd org-done-keywords))
13015 (and (listp org-provide-todo-statistics)
13016 (listp (car org-provide-todo-statistics))
13017 (member kwd org-done-keywords)
13018 (member kwd (cadr org-provide-todo-statistics)))
13019 (and (listp org-provide-todo-statistics)
13020 (stringp (car org-provide-todo-statistics))
13021 (member kwd org-done-keywords)))
13022 (setq cnt-done (1+ cnt-done)))
13023 (outline-next-heading)))
13024 (setq new
13025 (if is-percent
13026 (format "[%d%%]" (floor (* 100.0 cnt-done)
13027 (max 1 cnt-all)))
13028 (format "[%d/%d]" cnt-done cnt-all))
13029 ndel (- (match-end 0) checkbox-beg))
13030 (goto-char checkbox-beg)
13031 (insert new)
13032 (delete-region (point) (+ (point) ndel))
13033 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
13034 (when cookie-present
13035 (run-hook-with-args 'org-after-todo-statistics-hook
13036 cnt-done (- cnt-all cnt-done))))))
13037 (run-hooks 'org-todo-statistics-hook)))
13039 (defvar org-after-todo-statistics-hook nil
13040 "Hook that is called after a TODO statistics cookie has been updated.
13041 Each function is called with two arguments: the number of not-done entries
13042 and the number of done entries.
13044 For example, the following function, when added to this hook, will switch
13045 an entry to DONE when all children are done, and back to TODO when new
13046 entries are set to a TODO status. Note that this hook is only called
13047 when there is a statistics cookie in the headline!
13049 (defun org-summary-todo (n-done n-not-done)
13050 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13051 (let (org-log-done org-log-states) ; turn off logging
13052 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13055 (defvar org-todo-statistics-hook nil
13056 "Hook that is run whenever Org thinks TODO statistics should be updated.
13057 This hook runs even if there is no statistics cookie present, in which case
13058 `org-after-todo-statistics-hook' would not run.")
13060 (defun org-todo-trigger-tag-changes (state)
13061 "Apply the changes defined in `org-todo-state-tags-triggers'."
13062 (let ((l org-todo-state-tags-triggers)
13063 changes)
13064 (when (or (not state) (equal state ""))
13065 (setq changes (append changes (cdr (assoc "" l)))))
13066 (when (and (stringp state) (> (length state) 0))
13067 (setq changes (append changes (cdr (assoc state l)))))
13068 (when (member state org-not-done-keywords)
13069 (setq changes (append changes (cdr (assq 'todo l)))))
13070 (when (member state org-done-keywords)
13071 (setq changes (append changes (cdr (assq 'done l)))))
13072 (dolist (c changes)
13073 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13075 (defun org-local-logging (value)
13076 "Get logging settings from a property VALUE."
13077 ;; Directly set the variables, they are already local.
13078 (setq org-log-done nil
13079 org-log-repeat nil
13080 org-todo-log-states nil)
13081 (dolist (w (org-split-string value))
13082 (let (a)
13083 (cond
13084 ((setq a (assoc w org-startup-options))
13085 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13086 (set (nth 1 a) (nth 2 a))))
13087 ((setq a (org-extract-log-state-settings w))
13088 (and (member (car a) org-todo-keywords-1)
13089 (push a org-todo-log-states)))))))
13091 (defun org-get-todo-sequence-head (kwd)
13092 "Return the head of the TODO sequence to which KWD belongs.
13093 If KWD is not set, check if there is a text property remembering the
13094 right sequence."
13095 (let (p)
13096 (cond
13097 ((not kwd)
13098 (or (get-text-property (point-at-bol) 'org-todo-head)
13099 (progn
13100 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13101 nil (point-at-eol)))
13102 (get-text-property p 'org-todo-head))))
13103 ((not (member kwd org-todo-keywords-1))
13104 (car org-todo-keywords-1))
13105 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13107 (defun org-fast-todo-selection ()
13108 "Fast TODO keyword selection with single keys.
13109 Returns the new TODO keyword, or nil if no state change should occur."
13110 (let* ((fulltable org-todo-key-alist)
13111 (done-keywords org-done-keywords) ;; needed for the faces.
13112 (maxlen (apply 'max (mapcar
13113 (lambda (x)
13114 (if (stringp (car x)) (string-width (car x)) 0))
13115 fulltable)))
13116 (expert nil)
13117 (fwidth (+ maxlen 3 1 3))
13118 (ncol (/ (- (window-width) 4) fwidth))
13119 tg cnt e c tbl
13120 groups ingroup)
13121 (save-excursion
13122 (save-window-excursion
13123 (if expert
13124 (set-buffer (get-buffer-create " *Org todo*"))
13125 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13126 (erase-buffer)
13127 (setq-local org-done-keywords done-keywords)
13128 (setq tbl fulltable cnt 0)
13129 (while (setq e (pop tbl))
13130 (cond
13131 ((equal e '(:startgroup))
13132 (push '() groups) (setq ingroup t)
13133 (unless (= cnt 0)
13134 (setq cnt 0)
13135 (insert "\n"))
13136 (insert "{ "))
13137 ((equal e '(:endgroup))
13138 (setq ingroup nil cnt 0)
13139 (insert "}\n"))
13140 ((equal e '(:newline))
13141 (unless (= cnt 0)
13142 (setq cnt 0)
13143 (insert "\n")
13144 (setq e (car tbl))
13145 (while (equal (car tbl) '(:newline))
13146 (insert "\n")
13147 (setq tbl (cdr tbl)))))
13149 (setq tg (car e) c (cdr e))
13150 (when ingroup (push tg (car groups)))
13151 (setq tg (org-add-props tg nil 'face
13152 (org-get-todo-face tg)))
13153 (when (and (= cnt 0) (not ingroup)) (insert " "))
13154 (insert "[" c "] " tg (make-string
13155 (- fwidth 4 (length tg)) ?\ ))
13156 (when (= (setq cnt (1+ cnt)) ncol)
13157 (insert "\n")
13158 (when ingroup (insert " "))
13159 (setq cnt 0)))))
13160 (insert "\n")
13161 (goto-char (point-min))
13162 (unless expert (org-fit-window-to-buffer))
13163 (message "[a-z..]:Set [SPC]:clear")
13164 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13165 (cond
13166 ((or (= c ?\C-g)
13167 (and (= c ?q) (not (rassoc c fulltable))))
13168 (setq quit-flag t))
13169 ((= c ?\ ) nil)
13170 ((setq e (rassoc c fulltable) tg (car e))
13172 (t (setq quit-flag t)))))))
13174 (defun org-entry-is-todo-p ()
13175 (member (org-get-todo-state) org-not-done-keywords))
13177 (defun org-entry-is-done-p ()
13178 (member (org-get-todo-state) org-done-keywords))
13180 (defun org-get-todo-state ()
13181 "Return the TODO keyword of the current subtree."
13182 (save-excursion
13183 (org-back-to-heading t)
13184 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13185 (match-end 2)
13186 (match-string 2))))
13188 (defun org-at-date-range-p (&optional inactive-ok)
13189 "Non-nil if point is inside a date range.
13191 When optional argument INACTIVE-OK is non-nil, also consider
13192 inactive time ranges.
13194 When this function returns a non-nil value, match data is set
13195 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13196 on INACTIVE-OK."
13197 (interactive)
13198 (save-excursion
13199 (catch 'exit
13200 (let ((pos (point)))
13201 (skip-chars-backward "^[<\r\n")
13202 (skip-chars-backward "<[")
13203 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13204 (>= (match-end 0) pos)
13205 (throw 'exit t))
13206 (skip-chars-backward "^<[\r\n")
13207 (skip-chars-backward "<[")
13208 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13209 (>= (match-end 0) pos)
13210 (throw 'exit t)))
13211 nil)))
13213 (defun org-get-repeat (&optional tagline)
13214 "Check if there is a deadline/schedule with repeater in this entry."
13215 (save-match-data
13216 (save-excursion
13217 (org-back-to-heading t)
13218 (and (re-search-forward (if tagline
13219 (concat tagline "\\s-*" org-repeat-re)
13220 org-repeat-re)
13221 (org-entry-end-position) t)
13222 (match-string-no-properties 1)))))
13224 (defvar org-last-changed-timestamp)
13225 (defvar org-last-inserted-timestamp)
13226 (defvar org-log-post-message)
13227 (defvar org-log-note-purpose)
13228 (defvar org-log-note-how nil)
13229 (defvar org-log-note-extra)
13230 (defun org-auto-repeat-maybe (done-word)
13231 "Check if the current headline contains a repeated time-stamp.
13233 If yes, set TODO state back to what it was and change the base date
13234 of repeating deadline/scheduled time stamps to new date.
13236 This function is run automatically after each state change to a DONE state."
13237 (let* ((repeat (org-get-repeat))
13238 (aa (assoc org-last-state org-todo-kwd-alist))
13239 (interpret (nth 1 aa))
13240 (head (nth 2 aa))
13241 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13242 (msg "Entry repeats: ")
13243 (org-log-done nil)
13244 (org-todo-log-states nil))
13245 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13246 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13247 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13248 org-todo-repeat-to-state)))
13249 (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
13250 to-state)
13251 ((eq interpret 'type) org-last-state)
13252 (head)
13253 (t 'none))))
13254 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13255 (org-entry-put nil "LAST_REPEAT" (format-time-string
13256 (org-time-stamp-format t t))))
13257 (when org-log-repeat
13258 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13259 (memq 'org-add-log-note post-command-hook))
13260 ;; We are already setup for some record.
13261 (when (eq org-log-repeat 'note)
13262 ;; Make sure we take a note, not only a time stamp.
13263 (setq org-log-note-how 'note))
13264 ;; Set up for taking a record.
13265 (org-add-log-setup 'state
13266 (or done-word (car org-done-keywords))
13267 org-last-state
13268 org-log-repeat)))
13269 (org-back-to-heading t)
13270 (org-add-planning-info nil nil 'closed)
13271 (let ((end (save-excursion (outline-next-heading) (point)))
13272 (planning-re (regexp-opt
13273 (list org-scheduled-string org-deadline-string))))
13274 (while (re-search-forward org-ts-regexp end t)
13275 (let* ((ts (match-string 0))
13276 (planning? (org-at-planning-p))
13277 (type (if (not planning?) "Plain:"
13278 (save-excursion
13279 (re-search-backward
13280 planning-re (line-beginning-position) t)
13281 (match-string 0)))))
13282 (cond
13283 ;; Ignore fake time-stamps (e.g., within comments).
13284 ((and (not planning?)
13285 (not (org-at-property-p))
13286 (not (eq 'timestamp
13287 (org-element-type (save-excursion
13288 (backward-char)
13289 (org-element-context)))))))
13290 ;; Time-stamps without a repeater are usually skipped.
13291 ;; However, a SCHEDULED time-stamp without one is
13292 ;; removed, as it is considered as no longer relevant.
13293 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13294 (when (equal type org-scheduled-string)
13295 (org-remove-timestamp-with-keyword type)))
13297 (let ((n (string-to-number (match-string 2 ts)))
13298 (what (match-string 3 ts)))
13299 (when (equal what "w") (setq n (* n 7) what "d"))
13300 (when (and (equal what "h")
13301 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13302 ts)))
13303 (user-error
13304 "Cannot repeat in Repeat in %d hour(s) because no hour \
13305 has been set"
13307 ;; Preparation, see if we need to modify the start
13308 ;; date for the change.
13309 (when (match-end 1)
13310 (let ((time (save-match-data (org-time-string-to-time ts))))
13311 (cond
13312 ((equal (match-string 1 ts) ".")
13313 ;; Shift starting date to today
13314 (org-timestamp-change
13315 (- (org-today) (time-to-days time))
13316 'day))
13317 ((equal (match-string 1 ts) "+")
13318 (let ((nshiftmax 10)
13319 (nshift 0))
13320 (while (or (= nshift 0)
13321 (not (time-less-p (current-time) time)))
13322 (when (= (cl-incf nshift) nshiftmax)
13323 (or (y-or-n-p
13324 (format "%d repeater intervals were not \
13325 enough to shift date past today. Continue? "
13326 nshift))
13327 (user-error "Abort")))
13328 (org-timestamp-change n (cdr (assoc what whata)))
13329 (org-at-timestamp-p t)
13330 (setq ts (match-string 1))
13331 (setq time
13332 (save-match-data
13333 (org-time-string-to-time ts)))))
13334 (org-timestamp-change (- n) (cdr (assoc what whata)))
13335 ;; Rematch, so that we have everything in place
13336 ;; for the real shift.
13337 (org-at-timestamp-p t)
13338 (setq ts (match-string 1))
13339 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13340 ts)))))
13341 (save-excursion
13342 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13343 (setq msg
13344 (concat
13345 msg type " " org-last-changed-timestamp " "))))))))
13346 (setq org-log-post-message msg)
13347 (message "%s" msg))))
13349 (defun org-show-todo-tree (arg)
13350 "Make a compact tree which shows all headlines marked with TODO.
13351 The tree will show the lines where the regexp matches, and all higher
13352 headlines above the match.
13353 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13354 With a numeric prefix N, construct a sparse tree for the Nth element
13355 of `org-todo-keywords-1'."
13356 (interactive "P")
13357 (let ((case-fold-search nil)
13358 (kwd-re
13359 (cond ((null arg) org-not-done-regexp)
13360 ((equal arg '(4))
13361 (let ((kwd
13362 (completing-read "Keyword (or KWD1|KWD2|...): "
13363 (mapcar #'list org-todo-keywords-1))))
13364 (concat "\\("
13365 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13366 "\\)\\>")))
13367 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13368 (regexp-quote (nth (1- (prefix-numeric-value arg))
13369 org-todo-keywords-1)))
13370 (t (user-error "Invalid prefix argument: %s" arg)))))
13371 (message "%d TODO entries found"
13372 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13374 (defun org--deadline-or-schedule (arg type time)
13375 "Insert DEADLINE or SCHEDULE information in current entry.
13376 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13377 `org-schedule' for information about ARG and TIME arguments."
13378 (let* ((deadline? (eq type 'deadline))
13379 (keyword (if deadline? org-deadline-string org-scheduled-string))
13380 (log (if deadline? org-log-redeadline org-log-reschedule))
13381 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13382 (old-date-time (and old-date (org-time-string-to-time old-date)))
13383 ;; Save repeater cookie from either TIME or current scheduled
13384 ;; time stamp. We are going to insert it back at the end of
13385 ;; the process.
13386 (repeater (or (and (org-string-nw-p time)
13387 ;; We use `org-repeat-re' because we need
13388 ;; to tell the difference between a real
13389 ;; repeater and a time delta, e.g. "+2d".
13390 (string-match org-repeat-re time)
13391 (match-string 1 time))
13392 (and (org-string-nw-p old-date)
13393 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13394 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13395 old-date)
13396 (match-string 1 old-date)))))
13397 (pcase arg
13398 (`(4)
13399 (when (and old-date log)
13400 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13401 nil old-date log))
13402 (org-remove-timestamp-with-keyword keyword)
13403 (message (if deadline? "Item no longer has a deadline."
13404 "Item is no longer scheduled.")))
13405 (`(16)
13406 (save-excursion
13407 (org-back-to-heading t)
13408 (let ((regexp (if deadline? org-deadline-time-regexp
13409 org-scheduled-time-regexp)))
13410 (if (not (re-search-forward regexp (line-end-position 2) t))
13411 (user-error (if deadline? "No deadline information to update"
13412 "No scheduled information to update"))
13413 (let* ((rpl0 (match-string 1))
13414 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13415 (msg (if deadline? "Warn starting from" "Delay until")))
13416 (replace-match
13417 (concat keyword
13418 " <" rpl
13419 (format " -%dd"
13420 (abs (- (time-to-days
13421 (save-match-data
13422 (org-read-date
13423 nil t nil msg old-date-time)))
13424 (time-to-days old-date-time))))
13425 ">") t t))))))
13427 (org-add-planning-info type time 'closed)
13428 (when (and old-date
13430 (not (equal old-date org-last-inserted-timestamp)))
13431 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13432 org-last-inserted-timestamp
13433 old-date
13434 log))
13435 (when repeater
13436 (save-excursion
13437 (org-back-to-heading t)
13438 (when (re-search-forward
13439 (concat keyword " " org-last-inserted-timestamp)
13440 (line-end-position 2)
13442 (goto-char (1- (match-end 0)))
13443 (insert " " repeater)
13444 (setq org-last-inserted-timestamp
13445 (concat (substring org-last-inserted-timestamp 0 -1)
13446 " " repeater
13447 (substring org-last-inserted-timestamp -1))))))
13448 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13449 org-last-inserted-timestamp)))))
13451 (defun org-deadline (arg &optional time)
13452 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13453 With one universal prefix argument, remove any deadline from the item.
13454 With two universal prefix arguments, prompt for a warning delay.
13455 With argument TIME, set the deadline at the corresponding date. TIME
13456 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13457 (interactive "P")
13458 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13459 (org-map-entries
13460 (lambda () (org--deadline-or-schedule arg 'deadline time))
13462 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13463 'region-start-level
13464 'region)
13465 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13466 (org--deadline-or-schedule arg 'deadline time)))
13468 (defun org-schedule (arg &optional time)
13469 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13470 With one universal prefix argument, remove any scheduling date from the item.
13471 With two universal prefix arguments, prompt for a delay cookie.
13472 With argument TIME, scheduled at the corresponding date. TIME can
13473 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13474 (interactive "P")
13475 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13476 (org-map-entries
13477 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13479 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13480 'region-start-level
13481 'region)
13482 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
13483 (org--deadline-or-schedule arg 'scheduled time)))
13485 (defun org-get-scheduled-time (pom &optional inherit)
13486 "Get the scheduled time as a time tuple, of a format suitable
13487 for calling org-schedule with, or if there is no scheduling,
13488 returns nil."
13489 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13490 (when time
13491 (apply 'encode-time (org-parse-time-string time)))))
13493 (defun org-get-deadline-time (pom &optional inherit)
13494 "Get the deadline as a time tuple, of a format suitable for
13495 calling org-deadline with, or if there is no scheduling, returns
13496 nil."
13497 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13498 (when time
13499 (apply 'encode-time (org-parse-time-string time)))))
13501 (defun org-remove-timestamp-with-keyword (keyword)
13502 "Remove all time stamps with KEYWORD in the current entry."
13503 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13504 beg)
13505 (save-excursion
13506 (org-back-to-heading t)
13507 (setq beg (point))
13508 (outline-next-heading)
13509 (while (re-search-backward re beg t)
13510 (replace-match "")
13511 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13512 (equal (char-before) ?\ ))
13513 (backward-delete-char 1)
13514 (when (string-match "^[ \t]*$" (buffer-substring
13515 (point-at-bol) (point-at-eol)))
13516 (delete-region (point-at-bol)
13517 (min (point-max) (1+ (point-at-eol))))))))))
13519 (defvar org-time-was-given) ; dynamically scoped parameter
13520 (defvar org-end-time-was-given) ; dynamically scoped parameter
13522 (defun org-at-planning-p ()
13523 "Non-nil when point is on a planning info line."
13524 ;; This is as accurate and faster than `org-element-at-point' since
13525 ;; planning info location is fixed in the section.
13526 (org-with-wide-buffer
13527 (beginning-of-line)
13528 (and (looking-at-p org-planning-line-re)
13529 (eq (point)
13530 (ignore-errors
13531 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13532 (org-back-to-heading t)
13533 (org-with-limited-levels (org-back-to-heading t)))
13534 (line-beginning-position 2))))))
13536 (defun org-add-planning-info (what &optional time &rest remove)
13537 "Insert new timestamp with keyword in the planning line.
13538 WHAT indicates what kind of time stamp to add. It is a symbol
13539 among `closed', `deadline', `scheduled' and nil. TIME indicates
13540 the time to use. If none is given, the user is prompted for
13541 a date. REMOVE indicates what kind of entries to remove. An old
13542 WHAT entry will also be removed."
13543 (let (org-time-was-given org-end-time-was-given default-time default-input)
13544 (catch 'exit
13545 (when (and (memq what '(scheduled deadline))
13546 (or (not time)
13547 (and (stringp time)
13548 (string-match "^[-+]+[0-9]" time))))
13549 ;; Try to get a default date/time from existing timestamp
13550 (save-excursion
13551 (org-back-to-heading t)
13552 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13553 (when (re-search-forward (if (eq what 'scheduled)
13554 org-scheduled-time-regexp
13555 org-deadline-time-regexp)
13556 end t)
13557 (setq ts (match-string 1)
13558 default-time (apply 'encode-time (org-parse-time-string ts))
13559 default-input (and ts (org-get-compact-tod ts)))))))
13560 (when what
13561 (setq time
13562 (if (stringp time)
13563 ;; This is a string (relative or absolute), set
13564 ;; proper date.
13565 (apply #'encode-time
13566 (org-read-date-analyze
13567 time default-time (decode-time default-time)))
13568 ;; If necessary, get the time from the user
13569 (or time (org-read-date nil 'to-time nil nil
13570 default-time default-input)))))
13572 (org-with-wide-buffer
13573 (org-back-to-heading t)
13574 (forward-line)
13575 (unless (bolp) (insert "\n"))
13576 (cond ((looking-at-p org-planning-line-re)
13577 ;; Move to current indentation.
13578 (skip-chars-forward " \t")
13579 ;; Check if we have to remove something.
13580 (dolist (type (if what (cons what remove) remove))
13581 (save-excursion
13582 (when (re-search-forward
13583 (cl-case type
13584 (closed org-closed-time-regexp)
13585 (deadline org-deadline-time-regexp)
13586 (scheduled org-scheduled-time-regexp)
13587 (otherwise
13588 (error "Invalid planning type: %s" type)))
13589 (line-end-position) t)
13590 ;; Delete until next keyword or end of line.
13591 (delete-region
13592 (match-beginning 0)
13593 (if (re-search-forward org-keyword-time-not-clock-regexp
13594 (line-end-position)
13596 (match-beginning 0)
13597 (line-end-position))))))
13598 ;; If there is nothing more to add and no more keyword
13599 ;; is left, remove the line completely.
13600 (if (and (looking-at-p "[ \t]*$") (not what))
13601 (delete-region (line-beginning-position)
13602 (line-beginning-position 2))
13603 ;; If we removed last keyword, do not leave trailing
13604 ;; white space at the end of line.
13605 (let ((p (point)))
13606 (save-excursion
13607 (end-of-line)
13608 (unless (= (skip-chars-backward " \t" p) 0)
13609 (delete-region (point) (line-end-position)))))))
13610 ((not what) (throw 'exit nil)) ; Nothing to do.
13611 (t (insert-before-markers "\n")
13612 (backward-char 1)
13613 (when org-adapt-indentation
13614 (indent-to-column (1+ (org-outline-level))))))
13615 (when what
13616 ;; Insert planning keyword.
13617 (insert (cl-case what
13618 (closed org-closed-string)
13619 (deadline org-deadline-string)
13620 (scheduled org-scheduled-string)
13621 (otherwise (error "Invalid planning type: %s" what)))
13622 " ")
13623 ;; Insert associated timestamp.
13624 (let ((ts (org-insert-time-stamp
13625 time
13626 (or org-time-was-given
13627 (and (eq what 'closed) org-log-done-with-time))
13628 (eq what 'closed)
13629 nil nil (list org-end-time-was-given))))
13630 (unless (eolp) (insert " "))
13631 ts))))))
13633 (defvar org-log-note-marker (make-marker)
13634 "Marker pointing at the entry where the note is to be inserted.")
13635 (defvar org-log-note-purpose nil)
13636 (defvar org-log-note-state nil)
13637 (defvar org-log-note-previous-state nil)
13638 (defvar org-log-note-extra nil)
13639 (defvar org-log-note-window-configuration nil)
13640 (defvar org-log-note-return-to (make-marker))
13641 (defvar org-log-note-effective-time nil
13642 "Remembered current time so that dynamically scoped
13643 `org-extend-today-until' affects timestamps in state change log")
13645 (defvar org-log-post-message nil
13646 "Message to be displayed after a log note has been stored.
13647 The auto-repeater uses this.")
13649 (defun org-add-note ()
13650 "Add a note to the current entry.
13651 This is done in the same way as adding a state change note."
13652 (interactive)
13653 (org-add-log-setup 'note))
13655 (defun org-log-beginning (&optional create)
13656 "Return expected start of log notes in current entry.
13657 When optional argument CREATE is non-nil, the function creates
13658 a drawer to store notes, if necessary. Returned position ignores
13659 narrowing."
13660 (org-with-wide-buffer
13661 (let ((drawer (org-log-into-drawer)))
13662 (cond
13663 (drawer
13664 (org-end-of-meta-data)
13665 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13666 (end (if (org-at-heading-p) (point)
13667 (save-excursion (outline-next-heading) (point))))
13668 (case-fold-search t))
13669 (catch 'exit
13670 ;; Try to find existing drawer.
13671 (while (re-search-forward regexp end t)
13672 (let ((element (org-element-at-point)))
13673 (when (eq (org-element-type element) 'drawer)
13674 (let ((cend (org-element-property :contents-end element)))
13675 (when (and (not org-log-states-order-reversed) cend)
13676 (goto-char cend)))
13677 (throw 'exit nil))))
13678 ;; No drawer found. Create one, if permitted.
13679 (when create
13680 (unless (bolp) (insert "\n"))
13681 (let ((beg (point)))
13682 (insert ":" drawer ":\n:END:\n")
13683 (org-indent-region beg (point)))
13684 (end-of-line -1)))))
13686 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13687 (skip-chars-forward " \t\n")
13688 (beginning-of-line)
13689 (unless org-log-states-order-reversed
13690 (org-skip-over-state-notes)
13691 (skip-chars-backward " \t\n")
13692 (forward-line)))))
13693 (if (bolp) (point) (line-beginning-position 2))))
13695 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13696 "Set up the post command hook to take a note.
13697 If this is about to TODO state change, the new state is expected in STATE.
13698 HOW is an indicator what kind of note should be created.
13699 EXTRA is additional text that will be inserted into the notes buffer."
13700 (move-marker org-log-note-marker (point))
13701 (setq org-log-note-purpose purpose
13702 org-log-note-state state
13703 org-log-note-previous-state prev-state
13704 org-log-note-how how
13705 org-log-note-extra extra
13706 org-log-note-effective-time (org-current-effective-time))
13707 (add-hook 'post-command-hook 'org-add-log-note 'append))
13709 (defun org-skip-over-state-notes ()
13710 "Skip past the list of State notes in an entry."
13711 (when (ignore-errors (goto-char (org-in-item-p)))
13712 (let* ((struct (org-list-struct))
13713 (prevs (org-list-prevs-alist struct))
13714 (regexp
13715 (concat "[ \t]*- +"
13716 (replace-regexp-in-string
13717 " +" " +"
13718 (org-replace-escapes
13719 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13720 `(("%d" . ,org-ts-regexp-inactive)
13721 ("%D" . ,org-ts-regexp)
13722 ("%s" . "\"\\S-+\"")
13723 ("%S" . "\"\\S-+\"")
13724 ("%t" . ,org-ts-regexp-inactive)
13725 ("%T" . ,org-ts-regexp)
13726 ("%u" . ".*?")
13727 ("%U" . ".*?")))))))
13728 (while (looking-at-p regexp)
13729 (goto-char (or (org-list-get-next-item (point) struct prevs)
13730 (org-list-get-item-end (point) struct)))))))
13732 (defun org-add-log-note (&optional _purpose)
13733 "Pop up a window for taking a note, and add this note later."
13734 (remove-hook 'post-command-hook 'org-add-log-note)
13735 (setq org-log-note-window-configuration (current-window-configuration))
13736 (delete-other-windows)
13737 (move-marker org-log-note-return-to (point))
13738 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13739 (goto-char org-log-note-marker)
13740 (org-switch-to-buffer-other-window "*Org Note*")
13741 (erase-buffer)
13742 (if (memq org-log-note-how '(time state))
13743 (let (current-prefix-arg) (org-store-log-note))
13744 (let ((org-inhibit-startup t)) (org-mode))
13745 (insert (format "# Insert note for %s.
13746 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13747 (cond
13748 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13749 ((eq org-log-note-purpose 'done) "closed todo item")
13750 ((eq org-log-note-purpose 'state)
13751 (format "state change from \"%s\" to \"%s\""
13752 (or org-log-note-previous-state "")
13753 (or org-log-note-state "")))
13754 ((eq org-log-note-purpose 'reschedule)
13755 "rescheduling")
13756 ((eq org-log-note-purpose 'delschedule)
13757 "no longer scheduled")
13758 ((eq org-log-note-purpose 'redeadline)
13759 "changing deadline")
13760 ((eq org-log-note-purpose 'deldeadline)
13761 "removing deadline")
13762 ((eq org-log-note-purpose 'refile)
13763 "refiling")
13764 ((eq org-log-note-purpose 'note)
13765 "this entry")
13766 (t (error "This should not happen")))))
13767 (when org-log-note-extra (insert org-log-note-extra))
13768 (setq-local org-finish-function 'org-store-log-note)
13769 (run-hooks 'org-log-buffer-setup-hook)))
13771 (defvar org-note-abort nil) ; dynamically scoped
13772 (defun org-store-log-note ()
13773 "Finish taking a log note, and insert it to where it belongs."
13774 (let ((txt (prog1 (buffer-string)
13775 (kill-buffer)))
13776 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13777 lines)
13778 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13779 (setq txt (replace-match "" t t txt)))
13780 (when (string-match "\\s-+\\'" txt)
13781 (setq txt (replace-match "" t t txt)))
13782 (setq lines (org-split-string txt "\n"))
13783 (when (org-string-nw-p note)
13784 (setq note
13785 (org-replace-escapes
13786 note
13787 (list (cons "%u" (user-login-name))
13788 (cons "%U" user-full-name)
13789 (cons "%t" (format-time-string
13790 (org-time-stamp-format 'long 'inactive)
13791 org-log-note-effective-time))
13792 (cons "%T" (format-time-string
13793 (org-time-stamp-format 'long nil)
13794 org-log-note-effective-time))
13795 (cons "%d" (format-time-string
13796 (org-time-stamp-format nil 'inactive)
13797 org-log-note-effective-time))
13798 (cons "%D" (format-time-string
13799 (org-time-stamp-format nil nil)
13800 org-log-note-effective-time))
13801 (cons "%s" (cond
13802 ((not org-log-note-state) "")
13803 ((string-match-p org-ts-regexp
13804 org-log-note-state)
13805 (format "\"[%s]\""
13806 (substring org-log-note-state 1 -1)))
13807 (t (format "\"%s\"" org-log-note-state))))
13808 (cons "%S"
13809 (cond
13810 ((not org-log-note-previous-state) "")
13811 ((string-match-p org-ts-regexp
13812 org-log-note-previous-state)
13813 (format "\"[%s]\""
13814 (substring
13815 org-log-note-previous-state 1 -1)))
13816 (t (format "\"%s\""
13817 org-log-note-previous-state)))))))
13818 (when lines (setq note (concat note " \\\\")))
13819 (push note lines))
13820 (when (and lines (not (or current-prefix-arg org-note-abort)))
13821 (with-current-buffer (marker-buffer org-log-note-marker)
13822 (org-with-wide-buffer
13823 ;; Find location for the new note.
13824 (goto-char org-log-note-marker)
13825 (set-marker org-log-note-marker nil)
13826 ;; Note associated to a clock is to be located right after
13827 ;; the clock. Do not move point.
13828 (unless (eq org-log-note-purpose 'clock-out)
13829 (goto-char (org-log-beginning t)))
13830 ;; Make sure point is at the beginning of an empty line.
13831 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13832 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13833 ;; In an existing list, add a new item at the top level.
13834 ;; Otherwise, indent line like a regular one.
13835 (let ((itemp (org-in-item-p)))
13836 (if itemp
13837 (indent-line-to
13838 (let ((struct (save-excursion
13839 (goto-char itemp) (org-list-struct))))
13840 (org-list-get-ind (org-list-get-top-point struct) struct)))
13841 (org-indent-line)))
13842 (insert (org-list-bullet-string "-") (pop lines))
13843 (let ((ind (org-list-item-body-column (line-beginning-position))))
13844 (dolist (line lines)
13845 (insert "\n")
13846 (indent-line-to ind)
13847 (insert line)))
13848 (message "Note stored")
13849 (org-back-to-heading t)
13850 (org-cycle-hide-drawers 'children))
13851 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13852 ;; from within `org-add-log-note' because `buffer-undo-list'
13853 ;; is then modified outside of `org-with-remote-undo'.
13854 (when (eq this-command 'org-agenda-todo)
13855 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13856 ;; Don't add undo information when called from `org-agenda-todo'.
13857 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13858 (set-window-configuration org-log-note-window-configuration)
13859 (with-current-buffer (marker-buffer org-log-note-return-to)
13860 (goto-char org-log-note-return-to))
13861 (move-marker org-log-note-return-to nil)
13862 (when org-log-post-message (message "%s" org-log-post-message))))
13864 (defun org-remove-empty-drawer-at (pos)
13865 "Remove an empty drawer at position POS.
13866 POS may also be a marker."
13867 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13868 (org-with-wide-buffer
13869 (goto-char pos)
13870 (let ((drawer (org-element-at-point)))
13871 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13872 (not (org-element-property :contents-begin drawer)))
13873 (delete-region (org-element-property :begin drawer)
13874 (progn (goto-char (org-element-property :end drawer))
13875 (skip-chars-backward " \r\t\n")
13876 (forward-line)
13877 (point))))))))
13879 (defvar org-ts-type nil)
13880 (defun org-sparse-tree (&optional arg type)
13881 "Create a sparse tree, prompt for the details.
13882 This command can create sparse trees. You first need to select the type
13883 of match used to create the tree:
13885 t Show all TODO entries.
13886 T Show entries with a specific TODO keyword.
13887 m Show entries selected by a tags/property match.
13888 p Enter a property name and its value (both with completion on existing
13889 names/values) and show entries with that property.
13890 r Show entries matching a regular expression (`/' can be used as well).
13891 b Show deadlines and scheduled items before a date.
13892 a Show deadlines and scheduled items after a date.
13893 d Show deadlines due within `org-deadline-warning-days'.
13894 D Show deadlines and scheduled items between a date range."
13895 (interactive "P")
13896 (setq type (or type org-sparse-tree-default-date-type))
13897 (setq org-ts-type type)
13898 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13899 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13900 \[c]ycle through date types: %s"
13901 (cl-case type
13902 (all "all timestamps")
13903 (scheduled "only scheduled")
13904 (deadline "only deadline")
13905 (active "only active timestamps")
13906 (inactive "only inactive timestamps")
13907 (closed "with a closed time-stamp")
13908 (otherwise "scheduled/deadline")))
13909 (let ((answer (read-char-exclusive)))
13910 (cl-case answer
13912 (org-sparse-tree
13914 (cadr
13915 (memq type '(nil all scheduled deadline active inactive closed)))))
13916 (?d (call-interactively 'org-check-deadlines))
13917 (?b (call-interactively 'org-check-before-date))
13918 (?a (call-interactively 'org-check-after-date))
13919 (?D (call-interactively 'org-check-dates-range))
13920 (?t (call-interactively 'org-show-todo-tree))
13921 (?T (org-show-todo-tree '(4)))
13922 (?m (call-interactively 'org-match-sparse-tree))
13923 ((?p ?P)
13924 (let* ((kwd (completing-read
13925 "Property: " (mapcar #'list (org-buffer-property-keys))))
13926 (value (completing-read
13927 "Value: " (mapcar #'list (org-property-values kwd)))))
13928 (unless (string-match "\\`{.*}\\'" value)
13929 (setq value (concat "\"" value "\"")))
13930 (org-match-sparse-tree arg (concat kwd "=" value))))
13931 ((?r ?R ?/) (call-interactively 'org-occur))
13932 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13934 (defvar-local org-occur-highlights nil
13935 "List of overlays used for occur matches.")
13936 (defvar-local org-occur-parameters nil
13937 "Parameters of the active org-occur calls.
13938 This is a list, each call to org-occur pushes as cons cell,
13939 containing the regular expression and the callback, onto the list.
13940 The list can contain several entries if `org-occur' has been called
13941 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13942 will only contain one set of parameters. When the highlights are
13943 removed (for example with `C-c C-c', or with the next edit (depending
13944 on `org-remove-highlights-with-change'), this variable is emptied
13945 as well.")
13947 (defun org-occur (regexp &optional keep-previous callback)
13948 "Make a compact tree which shows all matches of REGEXP.
13950 The tree will show the lines where the regexp matches, and any other context
13951 defined in `org-show-context-detail', which see.
13953 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13954 done by a previous call to `org-occur' will be kept, to allow stacking of
13955 calls to this command.
13957 Optional argument CALLBACK can be a function of no argument. In this case,
13958 it is called with point at the end of the match, match data being set
13959 accordingly. Current match is shown only if the return value is non-nil.
13960 The function must neither move point nor alter narrowing."
13961 (interactive "sRegexp: \nP")
13962 (when (equal regexp "")
13963 (user-error "Regexp cannot be empty"))
13964 (unless keep-previous
13965 (org-remove-occur-highlights nil nil t))
13966 (push (cons regexp callback) org-occur-parameters)
13967 (let ((cnt 0))
13968 (save-excursion
13969 (goto-char (point-min))
13970 (when (or (not keep-previous) ; do not want to keep
13971 (not org-occur-highlights)) ; no previous matches
13972 ;; hide everything
13973 (org-overview))
13974 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13975 (isearch-no-upper-case-p regexp t)
13976 org-occur-case-fold-search)))
13977 (while (re-search-forward regexp nil t)
13978 (when (or (not callback)
13979 (save-match-data (funcall callback)))
13980 (setq cnt (1+ cnt))
13981 (when org-highlight-sparse-tree-matches
13982 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13983 (org-show-context 'occur-tree)))))
13984 (when org-remove-highlights-with-change
13985 (add-hook 'before-change-functions 'org-remove-occur-highlights
13986 nil 'local))
13987 (unless org-sparse-tree-open-archived-trees
13988 (org-hide-archived-subtrees (point-min) (point-max)))
13989 (run-hooks 'org-occur-hook)
13990 (when (called-interactively-p 'interactive)
13991 (message "%d match(es) for regexp %s" cnt regexp))
13992 cnt))
13994 (defun org-occur-next-match (&optional n _reset)
13995 "Function for `next-error-function' to find sparse tree matches.
13996 N is the number of matches to move, when negative move backwards.
13997 This function always goes back to the starting point when no
13998 match is found."
13999 (let* ((limit (if (< n 0) (point-min) (point-max)))
14000 (search-func (if (< n 0)
14001 'previous-single-char-property-change
14002 'next-single-char-property-change))
14003 (n (abs n))
14004 (pos (point))
14006 (catch 'exit
14007 (while (setq p1 (funcall search-func (point) 'org-type))
14008 (when (equal p1 limit)
14009 (goto-char pos)
14010 (user-error "No more matches"))
14011 (when (equal (get-char-property p1 'org-type) 'org-occur)
14012 (setq n (1- n))
14013 (when (= n 0)
14014 (goto-char p1)
14015 (throw 'exit (point))))
14016 (goto-char p1))
14017 (goto-char p1)
14018 (user-error "No more matches"))))
14020 (defun org-show-context (&optional key)
14021 "Make sure point and context are visible.
14022 Optional argument KEY, when non-nil, is a symbol. See
14023 `org-show-context-detail' for allowed values and how much is to
14024 be shown."
14025 (org-show-set-visibility
14026 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14027 ((cdr (assq key org-show-context-detail)))
14028 (t (cdr (assq 'default org-show-context-detail))))))
14030 (defun org-show-set-visibility (detail)
14031 "Set visibility around point according to DETAIL.
14032 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14033 `tree', `canonical' or t. See `org-show-context-detail' for more
14034 information."
14035 ;; Show current heading and possibly its entry, following headline
14036 ;; or all children.
14037 (if (and (org-at-heading-p) (not (eq detail 'local)))
14038 (org-flag-heading nil)
14039 (org-show-entry)
14040 ;; If point is hidden within a drawer or a block, make sure to
14041 ;; expose it.
14042 (dolist (o (overlays-at (point)))
14043 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14044 (delete-overlay o)))
14045 (unless (org-before-first-heading-p)
14046 (org-with-limited-levels
14047 (cl-case detail
14048 ((tree canonical t) (org-show-children))
14049 ((nil minimal ancestors))
14050 (t (save-excursion
14051 (outline-next-heading)
14052 (org-flag-heading nil)))))))
14053 ;; Show all siblings.
14054 (when (eq detail 'lineage) (org-show-siblings))
14055 ;; Show ancestors, possibly with their children.
14056 (when (memq detail '(ancestors lineage tree canonical t))
14057 (save-excursion
14058 (while (org-up-heading-safe)
14059 (org-flag-heading nil)
14060 (when (memq detail '(canonical t)) (org-show-entry))
14061 (when (memq detail '(tree canonical t)) (org-show-children))))))
14063 (defvar org-reveal-start-hook nil
14064 "Hook run before revealing a location.")
14066 (defun org-reveal (&optional siblings)
14067 "Show current entry, hierarchy above it, and the following headline.
14069 This can be used to show a consistent set of context around
14070 locations exposed with `org-show-context'.
14072 With optional argument SIBLINGS, on each level of the hierarchy all
14073 siblings are shown. This repairs the tree structure to what it would
14074 look like when opened with hierarchical calls to `org-cycle'.
14076 With a \\[universal-argument] \\[universal-argument] prefix, \
14077 go to the parent and show the entire tree."
14078 (interactive "P")
14079 (run-hooks 'org-reveal-start-hook)
14080 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14081 ((equal siblings '(16))
14082 (save-excursion
14083 (when (org-up-heading-safe)
14084 (org-show-subtree)
14085 (run-hook-with-args 'org-cycle-hook 'subtree))))
14086 (t (org-show-set-visibility 'lineage))))
14088 (defun org-highlight-new-match (beg end)
14089 "Highlight from BEG to END and mark the highlight is an occur headline."
14090 (let ((ov (make-overlay beg end)))
14091 (overlay-put ov 'face 'secondary-selection)
14092 (overlay-put ov 'org-type 'org-occur)
14093 (push ov org-occur-highlights)))
14095 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14096 "Remove the occur highlights from the buffer.
14097 BEG and END are ignored. If NOREMOVE is nil, remove this function
14098 from the `before-change-functions' in the current buffer."
14099 (interactive)
14100 (unless org-inhibit-highlight-removal
14101 (mapc #'delete-overlay org-occur-highlights)
14102 (setq org-occur-highlights nil)
14103 (setq org-occur-parameters nil)
14104 (unless noremove
14105 (remove-hook 'before-change-functions
14106 'org-remove-occur-highlights 'local))))
14108 ;;;; Priorities
14110 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14111 "Regular expression matching the priority indicator.")
14113 (defvar org-remove-priority-next-time nil)
14115 (defun org-priority-up ()
14116 "Increase the priority of the current item."
14117 (interactive)
14118 (org-priority 'up))
14120 (defun org-priority-down ()
14121 "Decrease the priority of the current item."
14122 (interactive)
14123 (org-priority 'down))
14125 (defun org-priority (&optional action _show)
14126 "Change the priority of an item.
14127 ACTION can be `set', `up', `down', or a character."
14128 (interactive "P")
14129 (if (equal action '(4))
14130 (org-show-priority)
14131 (unless org-enable-priority-commands
14132 (user-error "Priority commands are disabled"))
14133 (setq action (or action 'set))
14134 (let (current new news have remove)
14135 (save-excursion
14136 (org-back-to-heading t)
14137 (when (looking-at org-priority-regexp)
14138 (setq current (string-to-char (match-string 2))
14139 have t))
14140 (cond
14141 ((eq action 'remove)
14142 (setq remove t new ?\ ))
14143 ((or (eq action 'set)
14144 (integerp action))
14145 (if (not (eq action 'set))
14146 (setq new action)
14147 (message "Priority %c-%c, SPC to remove: "
14148 org-highest-priority org-lowest-priority)
14149 (save-match-data
14150 (setq new (read-char-exclusive))))
14151 (when (and (= (upcase org-highest-priority) org-highest-priority)
14152 (= (upcase org-lowest-priority) org-lowest-priority))
14153 (setq new (upcase new)))
14154 (cond ((equal new ?\ ) (setq remove t))
14155 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14156 (user-error "Priority must be between `%c' and `%c'"
14157 org-highest-priority org-lowest-priority))))
14158 ((eq action 'up)
14159 (setq new (if have
14160 (1- current) ; normal cycling
14161 ;; last priority was empty
14162 (if (eq last-command this-command)
14163 org-lowest-priority ; wrap around empty to lowest
14164 ;; default
14165 (if org-priority-start-cycle-with-default
14166 org-default-priority
14167 (1- org-default-priority))))))
14168 ((eq action 'down)
14169 (setq new (if have
14170 (1+ current) ; normal cycling
14171 ;; last priority was empty
14172 (if (eq last-command this-command)
14173 org-highest-priority ; wrap around empty to highest
14174 ;; default
14175 (if org-priority-start-cycle-with-default
14176 org-default-priority
14177 (1+ org-default-priority))))))
14178 (t (user-error "Invalid action")))
14179 (when (or (< (upcase new) org-highest-priority)
14180 (> (upcase new) org-lowest-priority))
14181 (if (and (memq action '(up down))
14182 (not have) (not (eq last-command this-command)))
14183 ;; `new' is from default priority
14184 (error
14185 "The default can not be set, see `org-default-priority' why")
14186 ;; normal cycling: `new' is beyond highest/lowest priority
14187 ;; and is wrapped around to the empty priority
14188 (setq remove t)))
14189 (setq news (format "%c" new))
14190 (if have
14191 (if remove
14192 (replace-match "" t t nil 1)
14193 (replace-match news t t nil 2))
14194 (if remove
14195 (user-error "No priority cookie found in line")
14196 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14197 (if (match-end 2)
14198 (progn
14199 (goto-char (match-end 2))
14200 (insert " [#" news "]"))
14201 (goto-char (match-beginning 3))
14202 (insert "[#" news "] "))))
14203 (org-set-tags nil 'align))
14204 (if remove
14205 (message "Priority removed")
14206 (message "Priority of current item set to %s" news)))))
14208 (defun org-show-priority ()
14209 "Show the priority of the current item.
14210 This priority is composed of the main priority given with the [#A] cookies,
14211 and by additional input from the age of a schedules or deadline entry."
14212 (interactive)
14213 (let ((pri (if (eq major-mode 'org-agenda-mode)
14214 (org-get-at-bol 'priority)
14215 (save-excursion
14216 (save-match-data
14217 (beginning-of-line)
14218 (and (looking-at org-heading-regexp)
14219 (org-get-priority (match-string 0))))))))
14220 (message "Priority is %d" (if pri pri -1000))))
14222 (defun org-get-priority (s)
14223 "Find priority cookie and return priority."
14224 (save-match-data
14225 (if (functionp org-get-priority-function)
14226 (funcall org-get-priority-function)
14227 (if (not (string-match org-priority-regexp s))
14228 (* 1000 (- org-lowest-priority org-default-priority))
14229 (* 1000 (- org-lowest-priority
14230 (string-to-char (match-string 2 s))))))))
14232 ;;;; Tags
14234 (defvar org-agenda-archives-mode)
14235 (defvar org-map-continue-from nil
14236 "Position from where mapping should continue.
14237 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14239 (defvar org-scanner-tags nil
14240 "The current tag list while the tags scanner is running.")
14242 (defvar org-trust-scanner-tags nil
14243 "Should `org-get-tags-at' use the tags for the scanner.
14244 This is for internal dynamical scoping only.
14245 When this is non-nil, the function `org-get-tags-at' will return the value
14246 of `org-scanner-tags' instead of building the list by itself. This
14247 can lead to large speed-ups when the tags scanner is used in a file with
14248 many entries, and when the list of tags is retrieved, for example to
14249 obtain a list of properties. Building the tags list for each entry in such
14250 a file becomes an N^2 operation - but with this variable set, it scales
14251 as N.")
14253 (defvar org--matcher-tags-todo-only nil)
14255 (defun org-scan-tags (action matcher todo-only &optional start-level)
14256 "Scan headline tags with inheritance and produce output ACTION.
14258 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14259 or `agenda' to produce an entry list for an agenda view. It can also be
14260 a Lisp form or a function that should be called at each matched headline, in
14261 this case the return value is a list of all return values from these calls.
14263 MATCHER is a function accepting three arguments, returning
14264 a non-nil value whenever a given set of tags qualifies a headline
14265 for inclusion. See `org-make-tags-matcher' for more information.
14266 As a special case, it can also be set to t (respectively nil) in
14267 order to match all (respectively none) headline.
14269 When TODO-ONLY is non-nil, only lines with a not-done TODO
14270 keyword are included in the output.
14272 START-LEVEL can be a string with asterisks, reducing the scope to
14273 headlines matching this string."
14274 (require 'org-agenda)
14275 (let* ((re (concat "^"
14276 (if start-level
14277 ;; Get the correct level to match
14278 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14279 org-outline-regexp)
14280 " *\\(\\<\\("
14281 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14282 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14283 (props (list 'face 'default
14284 'done-face 'org-agenda-done
14285 'undone-face 'default
14286 'mouse-face 'highlight
14287 'org-not-done-regexp org-not-done-regexp
14288 'org-todo-regexp org-todo-regexp
14289 'org-complex-heading-regexp org-complex-heading-regexp
14290 'help-echo
14291 (format "mouse-2 or RET jump to org file %s"
14292 (abbreviate-file-name
14293 (or (buffer-file-name (buffer-base-buffer))
14294 (buffer-name (buffer-base-buffer)))))))
14295 (org-map-continue-from nil)
14296 lspos tags tags-list
14297 (tags-alist (list (cons 0 org-file-tags)))
14298 (llast 0) rtn rtn1 level category i txt
14299 todo marker entry priority
14300 ts-date ts-date-type ts-date-pair)
14301 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14302 (setq action (list 'lambda nil action)))
14303 (save-excursion
14304 (goto-char (point-min))
14305 (when (eq action 'sparse-tree)
14306 (org-overview)
14307 (org-remove-occur-highlights))
14308 (while (let (case-fold-search)
14309 (re-search-forward re nil t))
14310 (setq org-map-continue-from nil)
14311 (catch :skip
14312 (setq todo
14313 ;; TODO: is the 1-2 difference a bug?
14314 (when (match-end 1) (match-string-no-properties 2))
14315 tags (when (match-end 4) (match-string-no-properties 4)))
14316 (goto-char (setq lspos (match-beginning 0)))
14317 (setq level (org-reduced-level (org-outline-level))
14318 category (org-get-category))
14319 (when (eq action 'agenda)
14320 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14321 ts-date (car ts-date-pair)
14322 ts-date-type (cdr ts-date-pair)))
14323 (setq i llast llast level)
14324 ;; remove tag lists from same and sublevels
14325 (while (>= i level)
14326 (when (setq entry (assoc i tags-alist))
14327 (setq tags-alist (delete entry tags-alist)))
14328 (setq i (1- i)))
14329 ;; add the next tags
14330 (when tags
14331 (setq tags (org-split-string tags ":")
14332 tags-alist
14333 (cons (cons level tags) tags-alist)))
14334 ;; compile tags for current headline
14335 (setq tags-list
14336 (if org-use-tag-inheritance
14337 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14338 tags)
14339 org-scanner-tags tags-list)
14340 (when org-use-tag-inheritance
14341 (setcdr (car tags-alist)
14342 (mapcar (lambda (x)
14343 (setq x (copy-sequence x))
14344 (org-add-prop-inherited x))
14345 (cdar tags-alist))))
14346 (when (and tags org-use-tag-inheritance
14347 (or (not (eq t org-use-tag-inheritance))
14348 org-tags-exclude-from-inheritance))
14349 ;; Selective inheritance, remove uninherited ones.
14350 (setcdr (car tags-alist)
14351 (org-remove-uninherited-tags (cdar tags-alist))))
14352 (when (and
14354 ;; eval matcher only when the todo condition is OK
14355 (and (or (not todo-only) (member todo org-not-done-keywords))
14356 (if (functionp matcher)
14357 (let ((case-fold-search t) (org-trust-scanner-tags t))
14358 (funcall matcher todo tags-list level))
14359 matcher))
14361 ;; Call the skipper, but return t if it does not
14362 ;; skip, so that the `and' form continues evaluating.
14363 (progn
14364 (unless (eq action 'sparse-tree) (org-agenda-skip))
14367 ;; Check if timestamps are deselecting this entry
14368 (or (not todo-only)
14369 (and (member todo org-not-done-keywords)
14370 (or (not org-agenda-tags-todo-honor-ignore-options)
14371 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14373 ;; select this headline
14374 (cond
14375 ((eq action 'sparse-tree)
14376 (and org-highlight-sparse-tree-matches
14377 (org-get-heading) (match-end 0)
14378 (org-highlight-new-match
14379 (match-beginning 1) (match-end 1)))
14380 (org-show-context 'tags-tree))
14381 ((eq action 'agenda)
14382 (setq txt (org-agenda-format-item
14384 (concat
14385 (if (eq org-tags-match-list-sublevels 'indented)
14386 (make-string (1- level) ?.) "")
14387 (org-get-heading))
14388 (make-string level ?\s)
14389 category
14390 tags-list)
14391 priority (org-get-priority txt))
14392 (goto-char lspos)
14393 (setq marker (org-agenda-new-marker))
14394 (org-add-props txt props
14395 'org-marker marker 'org-hd-marker marker 'org-category category
14396 'todo-state todo
14397 'ts-date ts-date
14398 'priority priority
14399 'type (concat "tagsmatch" ts-date-type))
14400 (push txt rtn))
14401 ((functionp action)
14402 (setq org-map-continue-from nil)
14403 (save-excursion
14404 (setq rtn1 (funcall action))
14405 (push rtn1 rtn)))
14406 (t (user-error "Invalid action")))
14408 ;; if we are to skip sublevels, jump to end of subtree
14409 (unless org-tags-match-list-sublevels
14410 (org-end-of-subtree t)
14411 (backward-char 1))))
14412 ;; Get the correct position from where to continue
14413 (if org-map-continue-from
14414 (goto-char org-map-continue-from)
14415 (and (= (point) lspos) (end-of-line 1)))))
14416 (when (and (eq action 'sparse-tree)
14417 (not org-sparse-tree-open-archived-trees))
14418 (org-hide-archived-subtrees (point-min) (point-max)))
14419 (nreverse rtn)))
14421 (defun org-remove-uninherited-tags (tags)
14422 "Remove all tags that are not inherited from the list TAGS."
14423 (cond
14424 ((eq org-use-tag-inheritance t)
14425 (if org-tags-exclude-from-inheritance
14426 (org-delete-all org-tags-exclude-from-inheritance tags)
14427 tags))
14428 ((not org-use-tag-inheritance) nil)
14429 ((stringp org-use-tag-inheritance)
14430 (delq nil (mapcar
14431 (lambda (x)
14432 (if (and (string-match org-use-tag-inheritance x)
14433 (not (member x org-tags-exclude-from-inheritance)))
14434 x nil))
14435 tags)))
14436 ((listp org-use-tag-inheritance)
14437 (delq nil (mapcar
14438 (lambda (x)
14439 (if (member x org-use-tag-inheritance) x nil))
14440 tags)))))
14442 (defun org-match-sparse-tree (&optional todo-only match)
14443 "Create a sparse tree according to tags string MATCH.
14445 MATCH is a string with match syntax. It can contain a selection
14446 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14447 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14448 those. See the manual for details.
14450 If optional argument TODO-ONLY is non-nil, only select lines that
14451 are also TODO tasks."
14452 (interactive "P")
14453 (org-agenda-prepare-buffers (list (current-buffer)))
14454 (let ((org--matcher-tags-todo-only todo-only))
14455 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14456 org--matcher-tags-todo-only)))
14458 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14460 (defvar org-cached-props nil)
14461 (defun org-cached-entry-get (pom property)
14462 (if (or (eq t org-use-property-inheritance)
14463 (and (stringp org-use-property-inheritance)
14464 (let ((case-fold-search t))
14465 (string-match-p org-use-property-inheritance property)))
14466 (and (listp org-use-property-inheritance)
14467 (member-ignore-case property org-use-property-inheritance)))
14468 ;; Caching is not possible, check it directly.
14469 (org-entry-get pom property 'inherit)
14470 ;; Get all properties, so we can do complicated checks easily.
14471 (cdr (assoc-string property
14472 (or org-cached-props
14473 (setq org-cached-props (org-entry-properties pom)))
14474 t))))
14476 (defun org-global-tags-completion-table (&optional files)
14477 "Return the list of all tags in all agenda buffer/files.
14478 Optional FILES argument is a list of files which can be used
14479 instead of the agenda files."
14480 (save-excursion
14481 (org-uniquify
14482 (delq nil
14483 (apply #'append
14484 (mapcar
14485 (lambda (file)
14486 (set-buffer (find-file-noselect file))
14487 (mapcar (lambda (x)
14488 (and (stringp (car-safe x))
14489 (list (car-safe x))))
14490 (or org-current-tag-alist (org-get-buffer-tags))))
14491 (if (car-safe files) files
14492 (org-agenda-files))))))))
14494 (defun org-make-tags-matcher (match)
14495 "Create the TAGS/TODO matcher form for the selection string MATCH.
14497 Returns a cons of the selection string MATCH and a function
14498 implementing the matcher.
14500 The matcher is to be called at an Org entry, with point on the
14501 headline, and returns non-nil if the entry matches the selection
14502 string MATCH. It must be called with three arguments: the TODO
14503 keyword at the entry (or nil if none), the list of all tags at
14504 the entry including inherited ones and the reduced level of the
14505 headline. Additionally, the category of the entry, if any, must
14506 be specified as the text property `org-category' on the headline.
14508 This function sets the variable `org--matcher-tags-todo-only' to
14509 a non-nil value if the matcher restricts matching to TODO
14510 entries, otherwise it is not touched.
14512 See also `org-scan-tags'."
14513 (unless match
14514 ;; Get a new match request, with completion against the global
14515 ;; tags table and the local tags in current buffer.
14516 (let ((org-last-tags-completion-table
14517 (org-uniquify
14518 (delq nil (append (org-get-buffer-tags)
14519 (org-global-tags-completion-table))))))
14520 (setq match
14521 (completing-read
14522 "Match: "
14523 'org-tags-completion-function nil nil nil 'org-tags-history))))
14525 (let ((match0 match)
14526 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14527 (start 0)
14528 tagsmatch todomatch tagsmatcher todomatcher)
14530 ;; Expand group tags.
14531 (setq match (org-tags-expand match))
14533 ;; Check if there is a TODO part of this match, which would be the
14534 ;; part after a "/". To make sure that this slash is not part of
14535 ;; a property value to be matched against, we also check that
14536 ;; there is no / after that slash. First, find the last slash.
14537 (let ((s 0))
14538 (while (string-match "/+" match s)
14539 (setq start (match-beginning 0))
14540 (setq s (match-end 0))))
14541 (if (and (string-match "/+" match start)
14542 (not (string-match-p "\"" match start)))
14543 ;; Match contains also a TODO-matching request.
14544 (progn
14545 (setq tagsmatch (substring match 0 (match-beginning 0)))
14546 (setq todomatch (substring match (match-end 0)))
14547 (when (string-prefix-p "!" todomatch)
14548 (setq org--matcher-tags-todo-only t)
14549 (setq todomatch (substring todomatch 1)))
14550 (when (string-match "\\`\\s-*\\'" todomatch)
14551 (setq todomatch nil)))
14552 ;; Only matching tags.
14553 (setq tagsmatch match)
14554 (setq todomatch nil))
14556 ;; Make the tags matcher.
14557 (when (org-string-nw-p tagsmatch)
14558 (let ((orlist nil)
14559 (orterms (org-split-string tagsmatch "|"))
14560 term)
14561 (while (setq term (pop orterms))
14562 (while (and (equal (substring term -1) "\\") orterms)
14563 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14564 (while (string-match re term)
14565 (let* ((rest (substring term (match-end 0)))
14566 (minus (and (match-end 1)
14567 (equal (match-string 1 term) "-")))
14568 (tag (save-match-data
14569 (replace-regexp-in-string
14570 "\\\\-" "-" (match-string 2 term))))
14571 (regexp (eq (string-to-char tag) ?{))
14572 (levelp (match-end 4))
14573 (propp (match-end 5))
14575 (cond
14576 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14577 (levelp
14578 `(,(org-op-to-function (match-string 3 term))
14579 level
14580 ,(string-to-number (match-string 4 term))))
14581 (propp
14582 (let* ((gv (pcase (upcase (match-string 5 term))
14583 ("CATEGORY"
14584 '(get-text-property (point) 'org-category))
14585 ("TODO" 'todo)
14586 (p `(org-cached-entry-get nil ,p))))
14587 (pv (match-string 7 term))
14588 (regexp (eq (string-to-char pv) ?{))
14589 (strp (eq (string-to-char pv) ?\"))
14590 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14591 (po (org-op-to-function (match-string 6 term)
14592 (if timep 'time strp))))
14593 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14594 (when timep (setq pv (org-matcher-time pv)))
14595 (cond ((and regexp (eq po 'org<>))
14596 `(not (string-match ,pv (or ,gv ""))))
14597 (regexp `(string-match ,pv (or ,gv "")))
14598 (strp `(,po (or ,gv "") ,pv))
14600 `(,po
14601 (string-to-number (or ,gv ""))
14602 ,(string-to-number pv))))))
14603 (t `(member ,tag tags-list)))))
14604 (push (if minus `(not ,mm) mm) tagsmatcher)
14605 (setq term rest)))
14606 (push `(and ,@tagsmatcher) orlist)
14607 (setq tagsmatcher nil))
14608 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14610 ;; Make the TODO matcher.
14611 (when (org-string-nw-p todomatch)
14612 (let ((orlist nil))
14613 (dolist (term (org-split-string todomatch "|"))
14614 (while (string-match re term)
14615 (let* ((minus (and (match-end 1)
14616 (equal (match-string 1 term) "-")))
14617 (kwd (match-string 2 term))
14618 (regexp (eq (string-to-char kwd) ?{))
14619 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14620 `(equal todo ,kwd))))
14621 (push (if minus `(not ,mm) mm) todomatcher))
14622 (setq term (substring term (match-end 0))))
14623 (push (if (> (length todomatcher) 1)
14624 (cons 'and todomatcher)
14625 (car todomatcher))
14626 orlist)
14627 (setq todomatcher nil))
14628 (setq todomatcher (cons 'or orlist))))
14630 ;; Return the string and function of the matcher. If no
14631 ;; tags-specific or todo-specific matcher exists, match
14632 ;; everything.
14633 (let ((matcher (if (and tagsmatcher todomatcher)
14634 `(and ,tagsmatcher ,todomatcher)
14635 (or tagsmatcher todomatcher t))))
14636 (when org--matcher-tags-todo-only
14637 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14638 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14640 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14641 "Expand group tags in MATCH.
14643 This replaces every group tag in MATCH with a regexp tag search.
14644 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14645 will be replaced like this:
14647 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14648 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14649 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14651 Replacing by a regexp preserves the structure of the match.
14652 E.g., this expansion
14654 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14656 will match anything tagged with \"Lab\" and \"Home\", or tagged
14657 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14659 A group tag in MATCH can contain regular expressions of its own.
14660 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14661 will be replaced like this:
14663 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14665 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14666 assumed to be a single group tag, and the function will return
14667 the list of tags in this group.
14669 When DOWNCASE is non-nil, expand downcased TAGS."
14670 (if org-group-tags
14671 (let* ((case-fold-search t)
14672 (stable org-mode-syntax-table)
14673 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14674 (taggroups (if downcased
14675 (mapcar (lambda (tg) (mapcar #'downcase tg))
14676 taggroups)
14677 taggroups))
14678 (taggroups-keys (mapcar #'car taggroups))
14679 (return-match (if downcased (downcase match) match))
14680 (count 0)
14681 (work-already-expanded tags-already-expanded)
14682 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14683 ;; @ and _ are allowed as word-components in tags.
14684 (modify-syntax-entry ?@ "w" stable)
14685 (modify-syntax-entry ?_ "w" stable)
14686 ;; Temporarily replace regexp-expressions in the match-expression.
14687 (while (string-match "{.+?}" return-match)
14688 (cl-incf count)
14689 (push (match-string 0 return-match) regexps-in-match)
14690 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14691 (while (and taggroups-keys
14692 (with-syntax-table stable
14693 (string-match
14694 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14695 (regexp-opt taggroups-keys) "\\>\\)")
14696 return-match)))
14697 (let* ((dir (match-string 1 return-match))
14698 (tag (match-string 2 return-match))
14699 (tag (if downcased (downcase tag) tag)))
14700 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14701 (member tag work-already-expanded))
14702 (setq tags-in-group (assoc tag taggroups))
14703 (push tag work-already-expanded)
14704 ;; Recursively expand each tag in the group, if the tag hasn't
14705 ;; already been expanded. Restore the match-data after all recursive calls.
14706 (save-match-data
14707 (let (tags-expanded)
14708 (dolist (x (cdr tags-in-group))
14709 (if (and (member x taggroups-keys)
14710 (not (member x work-already-expanded)))
14711 (setq tags-expanded
14712 (delete-dups
14713 (append
14714 (org-tags-expand x t downcased
14715 work-already-expanded)
14716 tags-expanded)))
14717 (setq tags-expanded
14718 (append (list x) tags-expanded)))
14719 (setq work-already-expanded
14720 (delete-dups
14721 (append tags-expanded
14722 work-already-expanded))))
14723 (setq tags-in-group
14724 (delete-dups (cons (car tags-in-group)
14725 tags-expanded)))))
14726 ;; Filter tag-regexps from tags.
14727 (setq regexp-in-group-escaped
14728 (delq nil (mapcar (lambda (x)
14729 (if (stringp x)
14730 (and (equal "{" (substring x 0 1))
14731 (equal "}" (substring x -1))
14734 tags-in-group))
14735 regexp-in-group
14736 (mapcar (lambda (x)
14737 (substring x 1 -1))
14738 regexp-in-group-escaped)
14739 tags-in-group
14740 (delq nil (mapcar (lambda (x)
14741 (if (stringp x)
14742 (and (not (equal "{" (substring x 0 1)))
14743 (not (equal "}" (substring x -1)))
14746 tags-in-group)))
14747 ;; If single-as-list, do no more in the while-loop.
14748 (if (not single-as-list)
14749 (progn
14750 (when regexp-in-group
14751 (setq regexp-in-group
14752 (concat "\\|"
14753 (mapconcat 'identity regexp-in-group
14754 "\\|"))))
14755 (setq tags-in-group
14756 (concat dir
14757 "{\\<"
14758 (regexp-opt tags-in-group)
14759 "\\>"
14760 regexp-in-group
14761 "}"))
14762 (when (stringp tags-in-group)
14763 (org-add-props tags-in-group '(grouptag t)))
14764 (setq return-match
14765 (replace-match tags-in-group t t return-match)))
14766 (setq tags-in-group
14767 (append regexp-in-group-escaped tags-in-group))))
14768 (setq taggroups-keys (delete tag taggroups-keys))))
14769 ;; Add the regular expressions back into the match-expression again.
14770 (while regexps-in-match
14771 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14772 (pop regexps-in-match)
14773 return-match t t))
14774 (cl-decf count))
14775 (if single-as-list
14776 (if tags-in-group tags-in-group (list return-match))
14777 return-match))
14778 (if single-as-list
14779 (list (if downcased (downcase match) match))
14780 match)))
14782 (defun org-op-to-function (op &optional stringp)
14783 "Turn an operator into the appropriate function."
14784 (setq op
14785 (cond
14786 ((equal op "<" ) '(< string< org-time<))
14787 ((equal op ">" ) '(> org-string> org-time>))
14788 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14789 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14790 ((member op '("=" "==")) '(= string= org-time=))
14791 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14792 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14794 (defun org<> (a b) (not (= a b)))
14795 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14796 (defun org-string>= (a b) (not (string< a b)))
14797 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14798 (defun org-string<> (a b) (not (string= a b)))
14799 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14800 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14801 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14802 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14803 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14804 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14805 (defun org-2ft (s)
14806 "Convert S to a floating point time.
14807 If S is already a number, just return it. If it is a string, parse
14808 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14809 (cond
14810 ((numberp s) s)
14811 ((stringp s)
14812 (condition-case nil
14813 (float-time (apply 'encode-time (org-parse-time-string s)))
14814 (error 0.)))
14815 (t 0.)))
14817 (defun org-time-today ()
14818 "Time in seconds today at 0:00.
14819 Returns the float number of seconds since the beginning of the
14820 epoch to the beginning of today (00:00)."
14821 (float-time (apply 'encode-time
14822 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14824 (defun org-matcher-time (s)
14825 "Interpret a time comparison value."
14826 (save-match-data
14827 (cond
14828 ((string= s "<now>") (float-time))
14829 ((string= s "<today>") (org-time-today))
14830 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14831 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14832 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14833 (+ (org-time-today)
14834 (* (string-to-number (match-string 1 s))
14835 (cdr (assoc (match-string 2 s)
14836 '(("d" . 86400.0) ("w" . 604800.0)
14837 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14838 (t (org-2ft s)))))
14840 (defun org-match-any-p (re list)
14841 "Does re match any element of list?"
14842 (setq list (mapcar (lambda (x) (string-match re x)) list))
14843 (delq nil list))
14845 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14846 (defvar org-tags-overlay (make-overlay 1 1))
14847 (delete-overlay org-tags-overlay)
14849 (defun org-get-local-tags-at (&optional pos)
14850 "Get a list of tags defined in the current headline."
14851 (org-get-tags-at pos 'local))
14853 (defun org-get-local-tags ()
14854 "Get a list of tags defined in the current headline."
14855 (org-get-tags-at nil 'local))
14857 (defun org-get-tags-at (&optional pos local)
14858 "Get a list of all headline tags applicable at POS.
14859 POS defaults to point. If tags are inherited, the list contains
14860 the targets in the same sequence as the headlines appear, i.e.
14861 the tags of the current headline come last.
14862 When LOCAL is non-nil, only return tags from the current headline,
14863 ignore inherited ones."
14864 (interactive)
14865 (if (and org-trust-scanner-tags
14866 (or (not pos) (equal pos (point)))
14867 (not local))
14868 org-scanner-tags
14869 (let (tags ltags lastpos parent)
14870 (save-excursion
14871 (save-restriction
14872 (widen)
14873 (goto-char (or pos (point)))
14874 (save-match-data
14875 (catch 'done
14876 (condition-case nil
14877 (progn
14878 (org-back-to-heading t)
14879 (while (not (equal lastpos (point)))
14880 (setq lastpos (point))
14881 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14882 (setq ltags (org-split-string
14883 (match-string-no-properties 1) ":"))
14884 (when parent
14885 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14886 (setq tags (append
14887 (if parent
14888 (org-remove-uninherited-tags ltags)
14889 ltags)
14890 tags)))
14891 (or org-use-tag-inheritance (throw 'done t))
14892 (when local (throw 'done t))
14893 (or (org-up-heading-safe) (error nil))
14894 (setq parent t)))
14895 (error nil)))))
14896 (if local
14897 tags
14898 (reverse (delete-dups
14899 (reverse (append
14900 (org-remove-uninherited-tags
14901 org-file-tags)
14902 tags)))))))))
14904 (defun org-add-prop-inherited (s)
14905 (add-text-properties 0 (length s) '(inherited t) s)
14908 (defun org-toggle-tag (tag &optional onoff)
14909 "Toggle the tag TAG for the current line.
14910 If ONOFF is `on' or `off', don't toggle but set to this state."
14911 (let (res current)
14912 (save-excursion
14913 (org-back-to-heading t)
14914 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14915 (point-at-eol) t)
14916 (progn
14917 (setq current (match-string 1))
14918 (replace-match ""))
14919 (setq current ""))
14920 (setq current (nreverse (org-split-string current ":")))
14921 (cond
14922 ((eq onoff 'on)
14923 (setq res t)
14924 (or (member tag current) (push tag current)))
14925 ((eq onoff 'off)
14926 (or (not (member tag current)) (setq current (delete tag current))))
14927 (t (if (member tag current)
14928 (setq current (delete tag current))
14929 (setq res t)
14930 (push tag current))))
14931 (end-of-line 1)
14932 (if current
14933 (progn
14934 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14935 (org-set-tags nil t))
14936 (delete-horizontal-space))
14937 (run-hooks 'org-after-tags-change-hook))
14938 res))
14940 (defun org--align-tags-here (to-col)
14941 "Align tags on the current headline to TO-COL.
14942 Assume point is on a headline."
14943 (let ((pos (point)))
14944 (beginning-of-line)
14945 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14946 (>= pos (match-beginning 2)))
14947 ;; No tags or point within tags: do not align.
14948 (goto-char pos)
14949 (goto-char (match-beginning 1))
14950 (let ((shift (max (- (if (>= to-col 0) to-col
14951 (- (abs to-col) (string-width (match-string 2))))
14952 (current-column))
14953 1)))
14954 (replace-match (make-string shift ?\s) nil nil nil 1)
14955 ;; Preserve initial position, if possible. In any case, stop
14956 ;; before tags.
14957 (when (< pos (point)) (goto-char pos))))))
14959 (defun org-set-tags-command (&optional arg just-align)
14960 "Call the set-tags command for the current entry."
14961 (interactive "P")
14962 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14963 (org-set-tags arg just-align)
14964 (save-excursion
14965 (unless (and (org-region-active-p)
14966 org-loop-over-headlines-in-active-region)
14967 (org-back-to-heading t))
14968 (org-set-tags arg just-align))))
14970 (defun org-set-tags-to (data)
14971 "Set the tags of the current entry to DATA, replacing the current tags.
14972 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14973 If DATA is nil or the empty string, any tags will be removed."
14974 (interactive "sTags: ")
14975 (setq data
14976 (cond
14977 ((eq data nil) "")
14978 ((equal data "") "")
14979 ((stringp data)
14980 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14981 ":"))
14982 ((listp data)
14983 (concat ":" (mapconcat 'identity data ":") ":"))))
14984 (when data
14985 (save-excursion
14986 (org-back-to-heading t)
14987 (when (let ((case-fold-search nil))
14988 (looking-at org-complex-heading-regexp))
14989 (if (match-end 5)
14990 (progn
14991 (goto-char (match-beginning 5))
14992 (insert data)
14993 (delete-region (point) (point-at-eol))
14994 (org-set-tags nil 'align))
14995 (goto-char (point-at-eol))
14996 (insert " " data)
14997 (org-set-tags nil 'align)))
14998 (beginning-of-line 1)
14999 (when (looking-at ".*?\\([ \t]+\\)$")
15000 (delete-region (match-beginning 1) (match-end 1))))))
15002 (defun org-align-all-tags ()
15003 "Align the tags in all headings."
15004 (interactive)
15005 (save-excursion
15006 (or (ignore-errors (org-back-to-heading t))
15007 (outline-next-heading))
15008 (if (org-at-heading-p)
15009 (org-set-tags t)
15010 (message "No headings"))))
15012 (defvar org-indent-indentation-per-level)
15013 (defun org-set-tags (&optional arg just-align)
15014 "Set the tags for the current headline.
15015 With prefix ARG, realign all tags in headings in the current buffer.
15016 When JUST-ALIGN is non-nil, only align tags."
15017 (interactive "P")
15018 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15019 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15020 'region-start-level
15021 'region))
15022 org-loop-over-headlines-in-active-region)
15023 (org-map-entries
15024 ;; We don't use ARG and JUST-ALIGN here because these args
15025 ;; are not useful when looping over headlines.
15026 #'org-set-tags
15027 org-loop-over-headlines-in-active-region
15029 '(when (org-invisible-p) (org-end-of-subtree nil t))))
15030 (let ((org-setting-tags t))
15031 (if arg
15032 (save-excursion
15033 (goto-char (point-min))
15034 (while (re-search-forward org-outline-regexp-bol nil t)
15035 (org-set-tags nil t)
15036 (end-of-line))
15037 (message "All tags realigned to column %d" org-tags-column))
15038 (let* ((current (org-get-tags-string))
15039 (tags
15040 (if just-align current
15041 ;; Get a new set of tags from the user.
15042 (save-excursion
15043 (let* ((seen)
15044 (table
15045 (setq
15046 org-last-tags-completion-table
15047 ;; Uniquify tags in alists, yet preserve
15048 ;; structure (i.e., keywords).
15049 (delq nil
15050 (mapcar
15051 (lambda (pair)
15052 (let ((head (car pair)))
15053 (cond ((symbolp head) pair)
15054 ((member head seen) nil)
15055 (t (push head seen)
15056 pair))))
15057 (append
15058 (or org-current-tag-alist
15059 (org-get-buffer-tags))
15060 (and
15061 org-complete-tags-always-offer-all-agenda-tags
15062 (org-global-tags-completion-table
15063 (org-agenda-files))))))))
15064 (current-tags (org-split-string current ":"))
15065 (inherited-tags
15066 (nreverse (nthcdr (length current-tags)
15067 (nreverse (org-get-tags-at))))))
15068 (replace-regexp-in-string
15069 "\\([-+&]+\\|,\\)"
15071 (if (or (eq t org-use-fast-tag-selection)
15072 (and org-use-fast-tag-selection
15073 (delq nil (mapcar #'cdr table))))
15074 (org-fast-tag-selection
15075 current-tags inherited-tags table
15076 (and org-fast-tag-selection-include-todo
15077 org-todo-key-alist))
15078 (let ((org-add-colon-after-tag-completion
15079 (< 1 (length table))))
15080 (org-trim
15081 (completing-read
15082 "Tags: "
15083 #'org-tags-completion-function
15084 nil nil current 'org-tags-history))))))))))
15086 (when org-tags-sort-function
15087 (setq tags
15088 (mapconcat
15089 #'identity
15090 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15091 org-tags-sort-function)
15092 ":")))
15094 (if (or (string= ":" tags)
15095 (string= "::" tags))
15096 (setq tags ""))
15097 (if (not (org-string-nw-p tags)) (setq tags "")
15098 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
15099 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
15101 ;; Insert new tags at the correct column.
15102 (unless (equal current tags)
15103 (save-excursion
15104 (beginning-of-line)
15105 (let ((case-fold-search nil))
15106 (looking-at org-complex-heading-regexp))
15107 ;; Remove current tags, if any.
15108 (when (match-end 5) (replace-match "" nil nil nil 5))
15109 ;; Insert new tags, if any. Otherwise, remove trailing
15110 ;; white spaces.
15111 (end-of-line)
15112 (if (not (equal tags ""))
15113 ;; When text is being inserted on an invisible
15114 ;; region boundary, it can be inadvertently sucked
15115 ;; into invisibility.
15116 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
15117 (skip-chars-backward " \t")
15118 (delete-region (point) (line-end-position)))))
15119 ;; Align tags, if any. Fix tags column if `org-indent-mode'
15120 ;; is on.
15121 (unless (equal tags "")
15122 (let* ((level (save-excursion
15123 (beginning-of-line)
15124 (skip-chars-forward "\\*")))
15125 (offset (if (bound-and-true-p org-indent-mode)
15126 (* (1- org-indent-indentation-per-level)
15127 (1- level))
15129 (tags-column
15130 (+ org-tags-column
15131 (if (> org-tags-column 0) (- offset) offset))))
15132 (org--align-tags-here tags-column))))
15133 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15135 (defun org-change-tag-in-region (beg end tag off)
15136 "Add or remove TAG for each entry in the region.
15137 This works in the agenda, and also in an Org buffer."
15138 (interactive
15139 (list (region-beginning) (region-end)
15140 (let ((org-last-tags-completion-table
15141 (if (derived-mode-p 'org-mode)
15142 (org-uniquify
15143 (delq nil (append (org-get-buffer-tags)
15144 (org-global-tags-completion-table))))
15145 (org-global-tags-completion-table))))
15146 (completing-read
15147 "Tag: " 'org-tags-completion-function nil nil nil
15148 'org-tags-history))
15149 (progn
15150 (message "[s]et or [r]emove? ")
15151 (equal (read-char-exclusive) ?r))))
15152 (when (fboundp 'deactivate-mark) (deactivate-mark))
15153 (let ((agendap (equal major-mode 'org-agenda-mode))
15154 l1 l2 m buf pos newhead (cnt 0))
15155 (goto-char end)
15156 (setq l2 (1- (org-current-line)))
15157 (goto-char beg)
15158 (setq l1 (org-current-line))
15159 (cl-loop for l from l1 to l2 do
15160 (org-goto-line l)
15161 (setq m (get-text-property (point) 'org-hd-marker))
15162 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15163 (and agendap m))
15164 (setq buf (if agendap (marker-buffer m) (current-buffer))
15165 pos (if agendap m (point)))
15166 (with-current-buffer buf
15167 (save-excursion
15168 (save-restriction
15169 (goto-char pos)
15170 (setq cnt (1+ cnt))
15171 (org-toggle-tag tag (if off 'off 'on))
15172 (setq newhead (org-get-heading)))))
15173 (and agendap (org-agenda-change-all-lines newhead m))))
15174 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15176 (defun org-tags-completion-function (string _predicate &optional flag)
15177 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15178 (confirm (lambda (x) (stringp (car x)))))
15179 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15180 (setq s1 (match-string 1 string)
15181 s2 (match-string 2 string))
15182 (setq s1 "" s2 string))
15183 (cond
15184 ((eq flag nil)
15185 ;; try completion
15186 (setq rtn (try-completion s2 ctable confirm))
15187 (when (stringp rtn)
15188 (setq rtn
15189 (concat s1 s2 (substring rtn (length s2))
15190 (if (and org-add-colon-after-tag-completion
15191 (assoc rtn ctable))
15192 ":" ""))))
15193 rtn)
15194 ((eq flag t)
15195 ;; all-completions
15196 (all-completions s2 ctable confirm))
15197 ((eq flag 'lambda)
15198 ;; exact match?
15199 (assoc s2 ctable)))))
15201 (defun org-fast-tag-insert (kwd tags face &optional end)
15202 "Insert KDW, and the TAGS, the latter with face FACE.
15203 Also insert END."
15204 (insert (format "%-12s" (concat kwd ":"))
15205 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15206 (or end "")))
15208 (defun org-fast-tag-show-exit (flag)
15209 (save-excursion
15210 (org-goto-line 3)
15211 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15212 (replace-match ""))
15213 (when flag
15214 (end-of-line 1)
15215 (org-move-to-column (- (window-width) 19) t)
15216 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15218 (defun org-set-current-tags-overlay (current prefix)
15219 "Add an overlay to CURRENT tag with PREFIX."
15220 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15221 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15222 (org-overlay-display org-tags-overlay (concat prefix s))))
15224 (defvar org-last-tag-selection-key nil)
15225 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15226 "Fast tag selection with single keys.
15227 CURRENT is the current list of tags in the headline, INHERITED is the
15228 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15229 possibly with grouping information. TODO-TABLE is a similar table with
15230 TODO keywords, should these have keys assigned to them.
15231 If the keys are nil, a-z are automatically assigned.
15232 Returns the new tags string, or nil to not change the current settings."
15233 (let* ((fulltable (append table todo-table))
15234 (maxlen (apply 'max (mapcar
15235 (lambda (x)
15236 (if (stringp (car x)) (string-width (car x)) 0))
15237 fulltable)))
15238 (buf (current-buffer))
15239 (expert (eq org-fast-tag-selection-single-key 'expert))
15240 (buffer-tags nil)
15241 (fwidth (+ maxlen 3 1 3))
15242 (ncol (/ (- (window-width) 4) fwidth))
15243 (i-face 'org-done)
15244 (c-face 'org-todo)
15245 tg cnt e c char c1 c2 ntable tbl rtn
15246 ov-start ov-end ov-prefix
15247 (exit-after-next org-fast-tag-selection-single-key)
15248 (done-keywords org-done-keywords)
15249 groups ingroup intaggroup)
15250 (save-excursion
15251 (beginning-of-line 1)
15252 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15253 (setq ov-start (match-beginning 1)
15254 ov-end (match-end 1)
15255 ov-prefix "")
15256 (setq ov-start (1- (point-at-eol))
15257 ov-end (1+ ov-start))
15258 (skip-chars-forward "^\n\r")
15259 (setq ov-prefix
15260 (concat
15261 (buffer-substring (1- (point)) (point))
15262 (if (> (current-column) org-tags-column)
15264 (make-string (- org-tags-column (current-column)) ?\ ))))))
15265 (move-overlay org-tags-overlay ov-start ov-end)
15266 (save-window-excursion
15267 (if expert
15268 (set-buffer (get-buffer-create " *Org tags*"))
15269 (delete-other-windows)
15270 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15271 (org-switch-to-buffer-other-window " *Org tags*"))
15272 (erase-buffer)
15273 (setq-local org-done-keywords done-keywords)
15274 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15275 (org-fast-tag-insert "Current" current c-face "\n\n")
15276 (org-fast-tag-show-exit exit-after-next)
15277 (org-set-current-tags-overlay current ov-prefix)
15278 (setq tbl fulltable char ?a cnt 0)
15279 (while (setq e (pop tbl))
15280 (cond
15281 ((eq (car e) :startgroup)
15282 (push '() groups) (setq ingroup t)
15283 (unless (zerop cnt)
15284 (setq cnt 0)
15285 (insert "\n"))
15286 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15287 ((eq (car e) :endgroup)
15288 (setq ingroup nil cnt 0)
15289 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15290 ((eq (car e) :startgrouptag)
15291 (setq intaggroup t)
15292 (unless (zerop cnt)
15293 (setq cnt 0)
15294 (insert "\n"))
15295 (insert "[ "))
15296 ((eq (car e) :endgrouptag)
15297 (setq intaggroup nil cnt 0)
15298 (insert "]\n"))
15299 ((equal e '(:newline))
15300 (unless (zerop cnt)
15301 (setq cnt 0)
15302 (insert "\n")
15303 (setq e (car tbl))
15304 (while (equal (car tbl) '(:newline))
15305 (insert "\n")
15306 (setq tbl (cdr tbl)))))
15307 ((equal e '(:grouptags)) (insert " : "))
15309 (setq tg (copy-sequence (car e)) c2 nil)
15310 (if (cdr e)
15311 (setq c (cdr e))
15312 ;; automatically assign a character.
15313 (setq c1 (string-to-char
15314 (downcase (substring
15315 tg (if (= (string-to-char tg) ?@) 1 0)))))
15316 (if (or (rassoc c1 ntable) (rassoc c1 table))
15317 (while (or (rassoc char ntable) (rassoc char table))
15318 (setq char (1+ char)))
15319 (setq c2 c1))
15320 (setq c (or c2 char)))
15321 (when ingroup (push tg (car groups)))
15322 (setq tg (org-add-props tg nil 'face
15323 (cond
15324 ((not (assoc tg table))
15325 (org-get-todo-face tg))
15326 ((member tg current) c-face)
15327 ((member tg inherited) i-face))))
15328 (when (equal (caar tbl) :grouptags)
15329 (org-add-props tg nil 'face 'org-tag-group))
15330 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15331 (insert "[" c "] " tg (make-string
15332 (- fwidth 4 (length tg)) ?\ ))
15333 (push (cons tg c) ntable)
15334 (when (= (cl-incf cnt) ncol)
15335 (insert "\n")
15336 (when (or ingroup intaggroup) (insert " "))
15337 (setq cnt 0)))))
15338 (setq ntable (nreverse ntable))
15339 (insert "\n")
15340 (goto-char (point-min))
15341 (unless expert (org-fit-window-to-buffer))
15342 (setq rtn
15343 (catch 'exit
15344 (while t
15345 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15346 (if (not groups) "no " "")
15347 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15348 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15349 (setq org-last-tag-selection-key c)
15350 (cond
15351 ((= c ?\r) (throw 'exit t))
15352 ((= c ?!)
15353 (setq groups (not groups))
15354 (goto-char (point-min))
15355 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15356 ((= c ?\C-c)
15357 (if (not expert)
15358 (org-fast-tag-show-exit
15359 (setq exit-after-next (not exit-after-next)))
15360 (setq expert nil)
15361 (delete-other-windows)
15362 (set-window-buffer (split-window-vertically) " *Org tags*")
15363 (org-switch-to-buffer-other-window " *Org tags*")
15364 (org-fit-window-to-buffer)))
15365 ((or (= c ?\C-g)
15366 (and (= c ?q) (not (rassoc c ntable))))
15367 (delete-overlay org-tags-overlay)
15368 (setq quit-flag t))
15369 ((= c ?\ )
15370 (setq current nil)
15371 (when exit-after-next (setq exit-after-next 'now)))
15372 ((= c ?\t)
15373 (condition-case nil
15374 (setq tg (completing-read
15375 "Tag: "
15376 (or buffer-tags
15377 (with-current-buffer buf
15378 (setq buffer-tags
15379 (org-get-buffer-tags))))))
15380 (quit (setq tg "")))
15381 (when (string-match "\\S-" tg)
15382 (cl-pushnew (list tg) buffer-tags :test #'equal)
15383 (if (member tg current)
15384 (setq current (delete tg current))
15385 (push tg current)))
15386 (when exit-after-next (setq exit-after-next 'now)))
15387 ((setq e (rassoc c todo-table) tg (car e))
15388 (with-current-buffer buf
15389 (save-excursion (org-todo tg)))
15390 (when exit-after-next (setq exit-after-next 'now)))
15391 ((setq e (rassoc c ntable) tg (car e))
15392 (if (member tg current)
15393 (setq current (delete tg current))
15394 (cl-loop for g in groups do
15395 (when (member tg g)
15396 (dolist (x g) (setq current (delete x current)))))
15397 (push tg current))
15398 (when exit-after-next (setq exit-after-next 'now))))
15400 ;; Create a sorted list
15401 (setq current
15402 (sort current
15403 (lambda (a b)
15404 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15405 (when (eq exit-after-next 'now) (throw 'exit t))
15406 (goto-char (point-min))
15407 (beginning-of-line 2)
15408 (delete-region (point) (point-at-eol))
15409 (org-fast-tag-insert "Current" current c-face)
15410 (org-set-current-tags-overlay current ov-prefix)
15411 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15412 (setq tg (match-string 1))
15413 (add-text-properties
15414 (match-beginning 1) (match-end 1)
15415 (list 'face
15416 (cond
15417 ((member tg current) c-face)
15418 ((member tg inherited) i-face)
15419 (t (get-text-property (match-beginning 1) 'face))))))
15420 (goto-char (point-min)))))
15421 (delete-overlay org-tags-overlay)
15422 (if rtn
15423 (mapconcat 'identity current ":")
15424 nil))))
15426 (defun org-get-tags-string ()
15427 "Get the TAGS string in the current headline."
15428 (unless (org-at-heading-p t)
15429 (user-error "Not on a heading"))
15430 (save-excursion
15431 (beginning-of-line 1)
15432 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15433 (match-string-no-properties 1)
15434 "")))
15436 (defun org-get-tags ()
15437 "Get the list of tags specified in the current headline."
15438 (org-split-string (org-get-tags-string) ":"))
15440 (defun org-get-buffer-tags ()
15441 "Get a table of all tags used in the buffer, for completion."
15442 (org-with-wide-buffer
15443 (goto-char (point-min))
15444 (let ((tag-re (concat org-outline-regexp-bol
15445 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15446 tags)
15447 (while (re-search-forward tag-re nil t)
15448 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15449 (push tag tags)))
15450 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15452 ;;;; The mapping API
15454 (defvar org-agenda-skip-comment-trees)
15455 (defvar org-agenda-skip-function)
15456 (defun org-map-entries (func &optional match scope &rest skip)
15457 "Call FUNC at each headline selected by MATCH in SCOPE.
15459 FUNC is a function or a lisp form. The function will be called without
15460 arguments, with the cursor positioned at the beginning of the headline.
15461 The return values of all calls to the function will be collected and
15462 returned as a list.
15464 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15465 does not need to preserve point. After evaluation, the cursor will be
15466 moved to the end of the line (presumably of the headline of the
15467 processed entry) and search continues from there. Under some
15468 circumstances, this may not produce the wanted results. For example,
15469 if you have removed (e.g. archived) the current (sub)tree it could
15470 mean that the next entry will be skipped entirely. In such cases, you
15471 can specify the position from where search should continue by making
15472 FUNC set the variable `org-map-continue-from' to the desired buffer
15473 position.
15475 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15476 Only headlines that are matched by this query will be considered during
15477 the iteration. When MATCH is nil or t, all headlines will be
15478 visited by the iteration.
15480 SCOPE determines the scope of this command. It can be any of:
15482 nil The current buffer, respecting the restriction if any
15483 tree The subtree started with the entry at point
15484 region The entries within the active region, if any
15485 region-start-level
15486 The entries within the active region, but only those at
15487 the same level than the first one.
15488 file The current buffer, without restriction
15489 file-with-archives
15490 The current buffer, and any archives associated with it
15491 agenda All agenda files
15492 agenda-with-archives
15493 All agenda files with any archive files associated with them
15494 \(file1 file2 ...)
15495 If this is a list, all files in the list will be scanned
15497 The remaining args are treated as settings for the skipping facilities of
15498 the scanner. The following items can be given here:
15500 archive skip trees with the archive tag
15501 comment skip trees with the COMMENT keyword
15502 function or Emacs Lisp form:
15503 will be used as value for `org-agenda-skip-function', so
15504 whenever the function returns a position, FUNC will not be
15505 called for that entry and search will continue from the
15506 position returned
15508 If your function needs to retrieve the tags including inherited tags
15509 at the *current* entry, you can use the value of the variable
15510 `org-scanner-tags' which will be much faster than getting the value
15511 with `org-get-tags-at'. If your function gets properties with
15512 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15513 to t around the call to `org-entry-properties' to get the same speedup.
15514 Note that if your function moves around to retrieve tags and properties at
15515 a *different* entry, you cannot use these techniques."
15516 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15517 (not (org-region-active-p)))
15518 (let* ((org-agenda-archives-mode nil) ; just to make sure
15519 (org-agenda-skip-archived-trees (memq 'archive skip))
15520 (org-agenda-skip-comment-trees (memq 'comment skip))
15521 (org-agenda-skip-function
15522 (car (org-delete-all '(comment archive) skip)))
15523 (org-tags-match-list-sublevels t)
15524 (start-level (eq scope 'region-start-level))
15525 matcher res
15526 org-todo-keywords-for-agenda
15527 org-done-keywords-for-agenda
15528 org-todo-keyword-alist-for-agenda
15529 org-tag-alist-for-agenda
15530 org--matcher-tags-todo-only)
15532 (cond
15533 ((eq match t) (setq matcher t))
15534 ((eq match nil) (setq matcher t))
15535 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15537 (save-excursion
15538 (save-restriction
15539 (cond ((eq scope 'tree)
15540 (org-back-to-heading t)
15541 (org-narrow-to-subtree)
15542 (setq scope nil))
15543 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15544 (org-region-active-p))
15545 ;; If needed, set start-level to a string like "2"
15546 (when start-level
15547 (save-excursion
15548 (goto-char (region-beginning))
15549 (unless (org-at-heading-p) (outline-next-heading))
15550 (setq start-level (org-current-level))))
15551 (narrow-to-region (region-beginning)
15552 (save-excursion
15553 (goto-char (region-end))
15554 (unless (and (bolp) (org-at-heading-p))
15555 (outline-next-heading))
15556 (point)))
15557 (setq scope nil)))
15559 (if (not scope)
15560 (progn
15561 (org-agenda-prepare-buffers
15562 (and buffer-file-name (list buffer-file-name)))
15563 (setq res
15564 (org-scan-tags
15565 func matcher org--matcher-tags-todo-only start-level)))
15566 ;; Get the right scope
15567 (cond
15568 ((and scope (listp scope) (symbolp (car scope)))
15569 (setq scope (eval scope)))
15570 ((eq scope 'agenda)
15571 (setq scope (org-agenda-files t)))
15572 ((eq scope 'agenda-with-archives)
15573 (setq scope (org-agenda-files t))
15574 (setq scope (org-add-archive-files scope)))
15575 ((eq scope 'file)
15576 (setq scope (and buffer-file-name (list buffer-file-name))))
15577 ((eq scope 'file-with-archives)
15578 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15579 (org-agenda-prepare-buffers scope)
15580 (dolist (file scope)
15581 (with-current-buffer (org-find-base-buffer-visiting file)
15582 (org-with-wide-buffer
15583 (goto-char (point-min))
15584 (setq res
15585 (append
15587 (org-scan-tags
15588 func matcher org--matcher-tags-todo-only)))))))))
15589 res)))
15591 ;;; Properties API
15593 (defconst org-special-properties
15594 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15595 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15596 "The special properties valid in Org mode.
15597 These are properties that are not defined in the property drawer,
15598 but in some other way.")
15600 (defconst org-default-properties
15601 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15602 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15603 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15604 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15605 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15606 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15607 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15608 "Some properties that are used by Org mode for various purposes.
15609 Being in this list makes sure that they are offered for completion.")
15611 (defun org--valid-property-p (property)
15612 "Non nil when string PROPERTY is a valid property name."
15613 (not
15614 (or (equal property "")
15615 (string-match-p "\\s-" property))))
15617 (defun org--update-property-plist (key val props)
15618 "Associate KEY to VAL in alist PROPS.
15619 Modifications are made by side-effect. Return new alist."
15620 (let* ((appending (string= (substring key -1) "+"))
15621 (key (if appending (substring key 0 -1) key))
15622 (old (assoc-string key props t)))
15623 (if (not old) (cons (cons key val) props)
15624 (setcdr old (if appending (concat (cdr old) " " val) val))
15625 props)))
15627 (defun org-get-property-block (&optional beg force)
15628 "Return the (beg . end) range of the body of the property drawer.
15629 BEG is the beginning of the current subtree, or of the part
15630 before the first headline. If it is not given, it will be found.
15631 If the drawer does not exist, create it if FORCE is non-nil, or
15632 return nil."
15633 (org-with-wide-buffer
15634 (when beg (goto-char beg))
15635 (unless (org-before-first-heading-p)
15636 (let ((beg (cond (beg)
15637 ((or (not (featurep 'org-inlinetask))
15638 (org-inlinetask-in-task-p))
15639 (org-back-to-heading t))
15640 (t (org-with-limited-levels (org-back-to-heading t))))))
15641 (forward-line)
15642 (when (looking-at-p org-planning-line-re) (forward-line))
15643 (cond ((looking-at org-property-drawer-re)
15644 (forward-line)
15645 (cons (point) (progn (goto-char (match-end 0))
15646 (line-beginning-position))))
15647 (force
15648 (goto-char beg)
15649 (org-insert-property-drawer)
15650 (let ((pos (save-excursion (search-forward ":END:")
15651 (line-beginning-position))))
15652 (cons pos pos))))))))
15654 (defun org-at-property-p ()
15655 "Non-nil when point is inside a property drawer.
15656 See `org-property-re' for match data, if applicable."
15657 (save-excursion
15658 (beginning-of-line)
15659 (and (looking-at org-property-re)
15660 (let ((property-drawer (save-match-data (org-get-property-block))))
15661 (and property-drawer
15662 (>= (point) (car property-drawer))
15663 (< (point) (cdr property-drawer)))))))
15665 (defun org-property-action ()
15666 "Do an action on properties."
15667 (interactive)
15668 (unless (org-at-property-p) (user-error "Not at a property"))
15669 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15670 (let ((c (read-char-exclusive)))
15671 (cl-case c
15672 (?s (call-interactively #'org-set-property))
15673 (?d (call-interactively #'org-delete-property))
15674 (?D (call-interactively #'org-delete-property-globally))
15675 (?c (call-interactively #'org-compute-property-at-point))
15676 (otherwise (user-error "No such property action %c" c)))))
15678 (defun org-inc-effort ()
15679 "Increment the value of the effort property in the current entry."
15680 (interactive)
15681 (org-set-effort nil t))
15683 (defvar org-clock-effort) ; Defined in org-clock.el.
15684 (defvar org-clock-current-task) ; Defined in org-clock.el.
15685 (defun org-set-effort (&optional value increment)
15686 "Set the effort property of the current entry.
15687 With numerical prefix arg, use the nth allowed value, 0 stands for the
15688 10th allowed value.
15690 When INCREMENT is non-nil, set the property to the next allowed value."
15691 (interactive "P")
15692 (when (equal value 0) (setq value 10))
15693 (let* ((completion-ignore-case t)
15694 (prop org-effort-property)
15695 (cur (org-entry-get nil prop))
15696 (allowed (org-property-get-allowed-values nil prop 'table))
15697 (existing (mapcar 'list (org-property-values prop)))
15698 (heading (nth 4 (org-heading-components)))
15700 (val (cond
15701 ((stringp value) value)
15702 ((and allowed (integerp value))
15703 (or (car (nth (1- value) allowed))
15704 (car (org-last allowed))))
15705 ((and allowed increment)
15706 (or (cl-caadr (member (list cur) allowed))
15707 (user-error "Allowed effort values are not set")))
15708 (allowed
15709 (message "Select 1-9,0, [RET%s]: %s"
15710 (if cur (concat "=" cur) "")
15711 (mapconcat 'car allowed " "))
15712 (setq rpl (read-char-exclusive))
15713 (if (equal rpl ?\r)
15715 (setq rpl (- rpl ?0))
15716 (when (equal rpl 0) (setq rpl 10))
15717 (if (and (> rpl 0) (<= rpl (length allowed)))
15718 (car (nth (1- rpl) allowed))
15719 (org-completing-read "Effort: " allowed nil))))
15721 (org-completing-read
15722 (concat "Effort" (and cur (string-match "\\S-" cur)
15723 (concat " [" cur "]"))
15724 ": ")
15725 existing nil nil "" nil cur)))))
15726 (unless (equal (org-entry-get nil prop) val)
15727 (org-entry-put nil prop val))
15728 (org-refresh-property
15729 '((effort . identity)
15730 (effort-minutes . org-duration-string-to-minutes))
15731 val)
15732 (when (equal heading (bound-and-true-p org-clock-current-task))
15733 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15734 (org-clock-update-mode-line))
15735 (message "%s is now %s" prop val)))
15737 (defun org-entry-properties (&optional pom which)
15738 "Get all properties of the current entry.
15740 When POM is a buffer position, get all properties from the entry
15741 there instead.
15743 This includes the TODO keyword, the tags, time strings for
15744 deadline, scheduled, and clocking, and any additional properties
15745 defined in the entry.
15747 If WHICH is nil or `all', get all properties. If WHICH is
15748 `special' or `standard', only get that subclass. If WHICH is
15749 a string, only get that property.
15751 Return value is an alist. Keys are properties, as upcased
15752 strings."
15753 (org-with-point-at pom
15754 (when (and (derived-mode-p 'org-mode)
15755 (ignore-errors (org-back-to-heading t)))
15756 (catch 'exit
15757 (let* ((beg (point))
15758 (specific (and (stringp which) (upcase which)))
15759 (which (cond ((not specific) which)
15760 ((member specific org-special-properties) 'special)
15761 (t 'standard)))
15762 props)
15763 ;; Get the special properties, like TODO and TAGS.
15764 (when (memq which '(nil all special))
15765 (when (or (not specific) (string= specific "CLOCKSUM"))
15766 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15767 (when clocksum
15768 (push (cons "CLOCKSUM"
15769 (org-minutes-to-clocksum-string clocksum))
15770 props)))
15771 (when specific (throw 'exit props)))
15772 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15773 (let ((clocksumt (get-text-property (point)
15774 :org-clock-minutes-today)))
15775 (when clocksumt
15776 (push (cons "CLOCKSUM_T"
15777 (org-minutes-to-clocksum-string clocksumt))
15778 props)))
15779 (when specific (throw 'exit props)))
15780 (when (or (not specific) (string= specific "ITEM"))
15781 (let ((case-fold-search nil))
15782 (when (looking-at org-complex-heading-regexp)
15783 (push (cons "ITEM"
15784 (let ((title (match-string-no-properties 4)))
15785 (if (org-string-nw-p title)
15786 (org-remove-tabs title)
15787 "")))
15788 props)))
15789 (when specific (throw 'exit props)))
15790 (when (or (not specific) (string= specific "TODO"))
15791 (let ((case-fold-search nil))
15792 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15793 (push (cons "TODO" (match-string-no-properties 2)) props)))
15794 (when specific (throw 'exit props)))
15795 (when (or (not specific) (string= specific "PRIORITY"))
15796 (push (cons "PRIORITY"
15797 (if (looking-at org-priority-regexp)
15798 (match-string-no-properties 2)
15799 (char-to-string org-default-priority)))
15800 props)
15801 (when specific (throw 'exit props)))
15802 (when (or (not specific) (string= specific "FILE"))
15803 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15804 props)
15805 (when specific (throw 'exit props)))
15806 (when (or (not specific) (string= specific "TAGS"))
15807 (let ((value (org-string-nw-p (org-get-tags-string))))
15808 (when value (push (cons "TAGS" value) props)))
15809 (when specific (throw 'exit props)))
15810 (when (or (not specific) (string= specific "ALLTAGS"))
15811 (let ((value (org-get-tags-at)))
15812 (when value
15813 (push (cons "ALLTAGS"
15814 (format ":%s:" (mapconcat #'identity value ":")))
15815 props)))
15816 (when specific (throw 'exit props)))
15817 (when (or (not specific) (string= specific "BLOCKED"))
15818 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15819 (when specific (throw 'exit props)))
15820 (when (or (not specific)
15821 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15822 (forward-line)
15823 (when (looking-at-p org-planning-line-re)
15824 (end-of-line)
15825 (let ((bol (line-beginning-position))
15826 ;; Backward compatibility: time keywords used to
15827 ;; be configurable (before 8.3). Make sure we
15828 ;; get the correct keyword.
15829 (key-assoc `(("CLOSED" . ,org-closed-string)
15830 ("DEADLINE" . ,org-deadline-string)
15831 ("SCHEDULED" . ,org-scheduled-string))))
15832 (dolist (pair (if specific (list (assoc specific key-assoc))
15833 key-assoc))
15834 (save-excursion
15835 (when (search-backward (cdr pair) bol t)
15836 (goto-char (match-end 0))
15837 (skip-chars-forward " \t")
15838 (and (looking-at org-ts-regexp-both)
15839 (push (cons (car pair)
15840 (match-string-no-properties 0))
15841 props)))))))
15842 (when specific (throw 'exit props)))
15843 (when (or (not specific)
15844 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15845 (let ((find-ts
15846 (lambda (end ts)
15847 ;; Fix next time-stamp before END. TS is the
15848 ;; list of time-stamps found so far.
15849 (let ((ts ts)
15850 (regexp (cond
15851 ((string= specific "TIMESTAMP")
15852 org-ts-regexp)
15853 ((string= specific "TIMESTAMP_IA")
15854 org-ts-regexp-inactive)
15855 ((assoc "TIMESTAMP_IA" ts)
15856 org-ts-regexp)
15857 ((assoc "TIMESTAMP" ts)
15858 org-ts-regexp-inactive)
15859 (t org-ts-regexp-both))))
15860 (catch 'next
15861 (while (re-search-forward regexp end t)
15862 (backward-char)
15863 (let ((object (org-element-context)))
15864 ;; Accept to match timestamps in node
15865 ;; properties, too.
15866 (when (memq (org-element-type object)
15867 '(node-property timestamp))
15868 (let ((type
15869 (org-element-property :type object)))
15870 (cond
15871 ((and (memq type '(active active-range))
15872 (not (equal specific "TIMESTAMP_IA")))
15873 (unless (assoc "TIMESTAMP" ts)
15874 (push (cons "TIMESTAMP"
15875 (org-element-property
15876 :raw-value object))
15878 (when specific (throw 'exit ts))))
15879 ((and (memq type '(inactive inactive-range))
15880 (not (string= specific "TIMESTAMP")))
15881 (unless (assoc "TIMESTAMP_IA" ts)
15882 (push (cons "TIMESTAMP_IA"
15883 (org-element-property
15884 :raw-value object))
15886 (when specific (throw 'exit ts))))))
15887 ;; Both timestamp types are found,
15888 ;; move to next part.
15889 (when (= (length ts) 2) (throw 'next ts)))))
15890 ts)))))
15891 (goto-char beg)
15892 ;; First look for timestamps within headline.
15893 (let ((ts (funcall find-ts (line-end-position) nil)))
15894 (if (= (length ts) 2) (setq props (nconc ts props))
15895 ;; Then find timestamps in the section, skipping
15896 ;; planning line.
15897 (let ((end (save-excursion (outline-next-heading))))
15898 (forward-line)
15899 (when (looking-at-p org-planning-line-re) (forward-line))
15900 (setq props (nconc (funcall find-ts end ts) props))))))))
15901 ;; Get the standard properties, like :PROP:.
15902 (when (memq which '(nil all standard))
15903 ;; If we are looking after a specific property, delegate
15904 ;; to `org-entry-get', which is faster. However, make an
15905 ;; exception for "CATEGORY", since it can be also set
15906 ;; through keywords (i.e. #+CATEGORY).
15907 (if (and specific (not (equal specific "CATEGORY")))
15908 (let ((value (org-entry-get beg specific nil t)))
15909 (throw 'exit (and value (list (cons specific value)))))
15910 (let ((range (org-get-property-block beg)))
15911 (when range
15912 (let ((end (cdr range)) seen-base)
15913 (goto-char (car range))
15914 ;; Unlike to `org--update-property-plist', we
15915 ;; handle the case where base values is found
15916 ;; after its extension. We also forbid standard
15917 ;; properties to be named as special properties.
15918 (while (re-search-forward org-property-re end t)
15919 (let* ((key (upcase (match-string-no-properties 2)))
15920 (extendp (string-match-p "\\+\\'" key))
15921 (key-base (if extendp (substring key 0 -1) key))
15922 (value (match-string-no-properties 3)))
15923 (cond
15924 ((member-ignore-case key-base org-special-properties))
15925 (extendp
15926 (setq props
15927 (org--update-property-plist key value props)))
15928 ((member key seen-base))
15929 (t (push key seen-base)
15930 (let ((p (assoc-string key props t)))
15931 (if p (setcdr p (concat value " " (cdr p)))
15932 (push (cons key value) props))))))))))))
15933 (unless (assoc "CATEGORY" props)
15934 (push (cons "CATEGORY" (org-get-category beg)) props)
15935 (when (string= specific "CATEGORY") (throw 'exit props)))
15936 ;; Return value.
15937 props)))))
15939 (defun org--property-local-values (property literal-nil)
15940 "Return value for PROPERTY in current entry.
15941 Value is a list whose car is the base value for PROPERTY and cdr
15942 a list of accumulated values. Return nil if neither is found in
15943 the entry. Also return nil when PROPERTY is set to \"nil\",
15944 unless LITERAL-NIL is non-nil."
15945 (let ((range (org-get-property-block)))
15946 (when range
15947 (goto-char (car range))
15948 (let* ((case-fold-search t)
15949 (end (cdr range))
15950 (value
15951 ;; Base value.
15952 (save-excursion
15953 (let ((v (and (re-search-forward
15954 (org-re-property property nil t) end t)
15955 (match-string-no-properties 3))))
15956 (list (if literal-nil v (org-not-nil v)))))))
15957 ;; Find additional values.
15958 (let* ((property+ (org-re-property (concat property "+") nil t)))
15959 (while (re-search-forward property+ end t)
15960 (push (match-string-no-properties 3) value)))
15961 ;; Return final values.
15962 (and (not (equal value '(nil))) (nreverse value))))))
15964 (defun org--property-global-value (property literal-nil)
15965 "Return value for PROPERTY in current buffer.
15966 Return value is a string. Return nil if property is not set
15967 globally. Also return nil when PROPERTY is set to \"nil\",
15968 unless LITERAL-NIL is non-nil."
15969 (let ((global
15970 (cdr (or (assoc-string property org-file-properties t)
15971 (assoc-string property org-global-properties t)
15972 (assoc-string property org-global-properties-fixed t)))))
15973 (if literal-nil global (org-not-nil global))))
15975 (defun org-entry-get (pom property &optional inherit literal-nil)
15976 "Get value of PROPERTY for entry or content at point-or-marker POM.
15978 If INHERIT is non-nil and the entry does not have the property,
15979 then also check higher levels of the hierarchy. If INHERIT is
15980 the symbol `selective', use inheritance only if the setting in
15981 `org-use-property-inheritance' selects PROPERTY for inheritance.
15983 If the property is present but empty, the return value is the
15984 empty string. If the property is not present at all, nil is
15985 returned. In any other case, return the value as a string.
15986 Search is case-insensitive.
15988 If LITERAL-NIL is set, return the string value \"nil\" as
15989 a string, do not interpret it as the list atom nil. This is used
15990 for inheritance when a \"nil\" value can supersede a non-nil
15991 value higher up the hierarchy."
15992 (org-with-point-at pom
15993 (cond
15994 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15995 ;; We need a special property. Use `org-entry-properties' to
15996 ;; retrieve it, but specify the wanted property.
15997 (cdr (assoc-string property (org-entry-properties nil property))))
15998 ((and inherit
15999 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
16000 (org-entry-get-with-inheritance property literal-nil))
16002 (let* ((local (org--property-local-values property literal-nil))
16003 (value (and local (mapconcat #'identity (delq nil local) " "))))
16004 (if literal-nil value (org-not-nil value)))))))
16006 (defun org-property-or-variable-value (var &optional inherit)
16007 "Check if there is a property fixing the value of VAR.
16008 If yes, return this value. If not, return the current value of the variable."
16009 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
16010 (if (and prop (stringp prop) (string-match "\\S-" prop))
16011 (read prop)
16012 (symbol-value var))))
16014 (defun org-entry-delete (pom property)
16015 "Delete PROPERTY from entry at point-or-marker POM.
16016 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16017 non-nil when a property was removed."
16018 (org-with-point-at pom
16019 (pcase (org-get-property-block)
16020 (`(,begin . ,origin)
16021 (let* ((end (copy-marker origin))
16022 (re (org-re-property
16023 (concat (regexp-quote property) "\\+?") t t)))
16024 (goto-char begin)
16025 (while (re-search-forward re end t)
16026 (delete-region (match-beginning 0) (line-beginning-position 2)))
16027 ;; If drawer is empty, remove it altogether.
16028 (when (= begin end)
16029 (delete-region (line-beginning-position 0)
16030 (line-beginning-position 2)))
16031 ;; Return non-nil if some property was removed.
16032 (prog1 (/= end origin) (set-marker end nil))))
16033 (_ nil))))
16035 ;; Multi-values properties are properties that contain multiple values
16036 ;; These values are assumed to be single words, separated by whitespace.
16037 (defun org-entry-add-to-multivalued-property (pom property value)
16038 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16039 (let* ((old (org-entry-get pom property))
16040 (values (and old (org-split-string old "[ \t]"))))
16041 (setq value (org-entry-protect-space value))
16042 (unless (member value values)
16043 (setq values (append values (list value)))
16044 (org-entry-put pom property
16045 (mapconcat 'identity values " ")))))
16047 (defun org-entry-remove-from-multivalued-property (pom property value)
16048 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16049 (let* ((old (org-entry-get pom property))
16050 (values (and old (org-split-string old "[ \t]"))))
16051 (setq value (org-entry-protect-space value))
16052 (when (member value values)
16053 (setq values (delete value values))
16054 (org-entry-put pom property
16055 (mapconcat 'identity values " ")))))
16057 (defun org-entry-member-in-multivalued-property (pom property value)
16058 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16059 (let* ((old (org-entry-get pom property))
16060 (values (and old (org-split-string old "[ \t]"))))
16061 (setq value (org-entry-protect-space value))
16062 (member value values)))
16064 (defun org-entry-get-multivalued-property (pom property)
16065 "Return a list of values in a multivalued property."
16066 (let* ((value (org-entry-get pom property))
16067 (values (and value (org-split-string value "[ \t]"))))
16068 (mapcar 'org-entry-restore-space values)))
16070 (defun org-entry-put-multivalued-property (pom property &rest values)
16071 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16072 VALUES should be a list of strings. Spaces will be protected."
16073 (org-entry-put pom property
16074 (mapconcat 'org-entry-protect-space values " "))
16075 (let* ((value (org-entry-get pom property))
16076 (values (and value (org-split-string value "[ \t]"))))
16077 (mapcar 'org-entry-restore-space values)))
16079 (defun org-entry-protect-space (s)
16080 "Protect spaces and newline in string S."
16081 (while (string-match " " s)
16082 (setq s (replace-match "%20" t t s)))
16083 (while (string-match "\n" s)
16084 (setq s (replace-match "%0A" t t s)))
16087 (defun org-entry-restore-space (s)
16088 "Restore spaces and newline in string S."
16089 (while (string-match "%20" s)
16090 (setq s (replace-match " " t t s)))
16091 (while (string-match "%0A" s)
16092 (setq s (replace-match "\n" t t s)))
16095 (defvar org-entry-property-inherited-from (make-marker)
16096 "Marker pointing to the entry from where a property was inherited.
16097 Each call to `org-entry-get-with-inheritance' will set this marker to the
16098 location of the entry where the inheritance search matched. If there was
16099 no match, the marker will point nowhere.
16100 Note that also `org-entry-get' calls this function, if the INHERIT flag
16101 is set.")
16103 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16104 "Get PROPERTY of entry or content at point, search higher levels if needed.
16105 The search will stop at the first ancestor which has the property defined.
16106 If the value found is \"nil\", return nil to show that the property
16107 should be considered as undefined (this is the meaning of nil here).
16108 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16109 (move-marker org-entry-property-inherited-from nil)
16110 (org-with-wide-buffer
16111 (let (value)
16112 (catch 'exit
16113 (while t
16114 (let ((v (org--property-local-values property literal-nil)))
16115 (when v
16116 (setq value
16117 (concat (mapconcat #'identity (delq nil v) " ")
16118 (and value " ")
16119 value)))
16120 (cond
16121 ((car v)
16122 (org-back-to-heading t)
16123 (move-marker org-entry-property-inherited-from (point))
16124 (throw 'exit nil))
16125 ((org-up-heading-safe))
16127 (let ((global (org--property-global-value property literal-nil)))
16128 (cond ((not global))
16129 (value (setq value (concat global " " value)))
16130 (t (setq value global))))
16131 (throw 'exit nil))))))
16132 (if literal-nil value (org-not-nil value)))))
16134 (defvar org-property-changed-functions nil
16135 "Hook called when the value of a property has changed.
16136 Each hook function should accept two arguments, the name of the property
16137 and the new value.")
16139 (defun org-entry-put (pom property value)
16140 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16142 If the value is nil, it is converted to the empty string. If it
16143 is not a string, an error is raised. Also raise an error on
16144 invalid property names.
16146 PROPERTY can be any regular property (see
16147 `org-special-properties'). It can also be \"TODO\",
16148 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16150 For the last two properties, VALUE may have any of the special
16151 values \"earlier\" and \"later\". The function then increases or
16152 decreases scheduled or deadline date by one day."
16153 (cond ((null value) (setq value ""))
16154 ((not (stringp value)) (error "Properties values should be strings"))
16155 ((not (org--valid-property-p property))
16156 (user-error "Invalid property name: \"%s\"" property)))
16157 (org-with-point-at pom
16158 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16159 (org-back-to-heading t)
16160 (org-with-limited-levels (org-back-to-heading t)))
16161 (let ((beg (point)))
16162 (cond
16163 ((equal property "TODO")
16164 (cond ((not (org-string-nw-p value)) (setq value 'none))
16165 ((not (member value org-todo-keywords-1))
16166 (user-error "\"%s\" is not a valid TODO state" value)))
16167 (org-todo value)
16168 (org-set-tags nil 'align))
16169 ((equal property "PRIORITY")
16170 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16171 (org-set-tags nil 'align))
16172 ((equal property "SCHEDULED")
16173 (forward-line)
16174 (if (and (looking-at-p org-planning-line-re)
16175 (re-search-forward
16176 org-scheduled-time-regexp (line-end-position) t))
16177 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16178 ((string= value "later") (org-timestamp-change 1 'day))
16179 ((string= value "") (org-schedule '(4)))
16180 (t (org-schedule nil value)))
16181 (if (member value '("earlier" "later" ""))
16182 (call-interactively #'org-schedule)
16183 (org-schedule nil value))))
16184 ((equal property "DEADLINE")
16185 (forward-line)
16186 (if (and (looking-at-p org-planning-line-re)
16187 (re-search-forward
16188 org-deadline-time-regexp (line-end-position) t))
16189 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16190 ((string= value "later") (org-timestamp-change 1 'day))
16191 ((string= value "") (org-deadline '(4)))
16192 (t (org-deadline nil value)))
16193 (if (member value '("earlier" "later" ""))
16194 (call-interactively #'org-deadline)
16195 (org-deadline nil value))))
16196 ((member property org-special-properties)
16197 (error "The %s property cannot be set with `org-entry-put'" property))
16199 (let* ((range (org-get-property-block beg 'force))
16200 (end (cdr range))
16201 (case-fold-search t))
16202 (goto-char (car range))
16203 (if (re-search-forward (org-re-property property nil t) end t)
16204 (progn (delete-region (match-beginning 0) (match-end 0))
16205 (goto-char (match-beginning 0)))
16206 (goto-char end)
16207 (insert "\n")
16208 (backward-char))
16209 (insert ":" property ":")
16210 (when value (insert " " value))
16211 (org-indent-line)))))
16212 (run-hook-with-args 'org-property-changed-functions property value)))
16214 (defun org-buffer-property-keys
16215 (&optional specials defaults columns ignore-malformed)
16216 "Get all property keys in the current buffer.
16218 When SPECIALS is non-nil, also list the special properties that
16219 reflect things like tags and TODO state.
16221 When DEFAULTS is non-nil, also include properties that has
16222 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16223 DESCRIPTION, LOCATION, and LOGGING and others.
16225 When COLUMNS in non-nil, also include property names given in
16226 COLUMN formats in the current buffer.
16228 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16229 automatically performed, such drawers will be silently ignored."
16230 (let ((case-fold-search t)
16231 (props (append
16232 (and specials org-special-properties)
16233 (and defaults (cons org-effort-property org-default-properties))
16234 nil)))
16235 (org-with-wide-buffer
16236 (goto-char (point-min))
16237 (while (re-search-forward org-property-start-re nil t)
16238 (let ((range (org-get-property-block)))
16239 (catch 'skip
16240 (unless range
16241 (when (and (not ignore-malformed)
16242 (not (org-before-first-heading-p))
16243 (y-or-n-p (format "Malformed drawer at %d, repair?"
16244 (line-beginning-position))))
16245 (org-get-property-block nil t))
16246 (throw 'skip nil))
16247 (goto-char (car range))
16248 (let ((begin (car range))
16249 (end (cdr range)))
16250 ;; Make sure that found property block is not located
16251 ;; before current point, as it would generate an infloop.
16252 ;; It can happen, for example, in the following
16253 ;; situation:
16255 ;; * Headline
16256 ;; :PROPERTIES:
16257 ;; ...
16258 ;; :END:
16259 ;; *************** Inlinetask
16260 ;; #+BEGIN_EXAMPLE
16261 ;; :PROPERTIES:
16262 ;; #+END_EXAMPLE
16264 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16265 (while (< (point) end)
16266 (let ((p (progn (looking-at org-property-re)
16267 (match-string-no-properties 2))))
16268 ;; Only add true property name, not extension symbol.
16269 (push (if (not (string-match-p "\\+\\'" p)) p
16270 (substring p 0 -1))
16271 props))
16272 (forward-line))))
16273 (outline-next-heading)))
16274 (when columns
16275 (goto-char (point-min))
16276 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16277 (let ((element (org-element-at-point)))
16278 (when (memq (org-element-type element) '(keyword node-property))
16279 (let ((value (org-element-property :value element))
16280 (start 0))
16281 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16282 (setq start (match-end 0))
16283 (let ((p (match-string-no-properties 1 value)))
16284 (unless (member-ignore-case p org-special-properties)
16285 (push p props))))))))))
16286 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16288 (defun org-property-values (key)
16289 "List all non-nil values of property KEY in current buffer."
16290 (org-with-wide-buffer
16291 (goto-char (point-min))
16292 (let ((case-fold-search t)
16293 (re (org-re-property key))
16294 values)
16295 (while (re-search-forward re nil t)
16296 (push (org-entry-get (point) key) values))
16297 (delete-dups values))))
16299 (defun org-insert-property-drawer ()
16300 "Insert a property drawer into the current entry."
16301 (org-with-wide-buffer
16302 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16303 (org-back-to-heading t)
16304 (org-with-limited-levels (org-back-to-heading t)))
16305 (forward-line)
16306 (when (looking-at-p org-planning-line-re) (forward-line))
16307 (unless (looking-at-p org-property-drawer-re)
16308 ;; Make sure we start editing a line from current entry, not from
16309 ;; next one. It prevents extending text properties or overlays
16310 ;; belonging to the latter.
16311 (when (bolp) (backward-char))
16312 (let ((begin (1+ (point)))
16313 (inhibit-read-only t))
16314 (insert "\n:PROPERTIES:\n:END:")
16315 (when (eobp) (insert "\n"))
16316 (org-indent-region begin (point))))))
16318 (defun org-insert-drawer (&optional arg drawer)
16319 "Insert a drawer at point.
16321 When optional argument ARG is non-nil, insert a property drawer.
16323 Optional argument DRAWER, when non-nil, is a string representing
16324 drawer's name. Otherwise, the user is prompted for a name.
16326 If a region is active, insert the drawer around that region
16327 instead.
16329 Point is left between drawer's boundaries."
16330 (interactive "P")
16331 (let* ((drawer (if arg "PROPERTIES"
16332 (or drawer (read-from-minibuffer "Drawer: ")))))
16333 (cond
16334 ;; With C-u, fall back on `org-insert-property-drawer'
16335 (arg (org-insert-property-drawer))
16336 ;; Check validity of suggested drawer's name.
16337 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16338 (user-error "Invalid drawer name"))
16339 ;; With an active region, insert a drawer at point.
16340 ((not (org-region-active-p))
16341 (progn
16342 (unless (bolp) (insert "\n"))
16343 (insert (format ":%s:\n\n:END:\n" drawer))
16344 (forward-line -2)))
16345 ;; Otherwise, insert the drawer at point
16347 (let ((rbeg (region-beginning))
16348 (rend (copy-marker (region-end))))
16349 (unwind-protect
16350 (progn
16351 (goto-char rbeg)
16352 (beginning-of-line)
16353 (when (save-excursion
16354 (re-search-forward org-outline-regexp-bol rend t))
16355 (user-error "Drawers cannot contain headlines"))
16356 ;; Position point at the beginning of the first
16357 ;; non-blank line in region. Insert drawer's opening
16358 ;; there, then indent it.
16359 (org-skip-whitespace)
16360 (beginning-of-line)
16361 (insert ":" drawer ":\n")
16362 (forward-line -1)
16363 (indent-for-tab-command)
16364 ;; Move point to the beginning of the first blank line
16365 ;; after the last non-blank line in region. Insert
16366 ;; drawer's closing, then indent it.
16367 (goto-char rend)
16368 (skip-chars-backward " \r\t\n")
16369 (insert "\n:END:")
16370 (deactivate-mark t)
16371 (indent-for-tab-command)
16372 (unless (eolp) (insert "\n")))
16373 ;; Clear marker, whatever the outcome of insertion is.
16374 (set-marker rend nil)))))))
16376 (defvar org-property-set-functions-alist nil
16377 "Property set function alist.
16378 Each entry should have the following format:
16380 (PROPERTY . READ-FUNCTION)
16382 The read function will be called with the same argument as
16383 `org-completing-read'.")
16385 (defun org-set-property-function (property)
16386 "Get the function that should be used to set PROPERTY.
16387 This is computed according to `org-property-set-functions-alist'."
16388 (or (cdr (assoc property org-property-set-functions-alist))
16389 'org-completing-read))
16391 (defun org-read-property-value (property)
16392 "Read PROPERTY value from user."
16393 (let* ((completion-ignore-case t)
16394 (allowed (org-property-get-allowed-values nil property 'table))
16395 (cur (org-entry-get nil property))
16396 (prompt (concat property " value"
16397 (if (and cur (string-match "\\S-" cur))
16398 (concat " [" cur "]") "") ": "))
16399 (set-function (org-set-property-function property))
16400 (val (if allowed
16401 (funcall set-function prompt allowed nil
16402 (not (get-text-property 0 'org-unrestricted
16403 (caar allowed))))
16404 (funcall set-function prompt
16405 (mapcar 'list (org-property-values property))
16406 nil nil "" nil cur))))
16407 (org-trim val)))
16409 (defvar org-last-set-property nil)
16410 (defvar org-last-set-property-value nil)
16411 (defun org-read-property-name ()
16412 "Read a property name."
16413 (let ((completion-ignore-case t)
16414 (default-prop (or (and (org-at-property-p)
16415 (match-string-no-properties 2))
16416 org-last-set-property)))
16417 (org-completing-read
16418 (concat "Property"
16419 (if default-prop (concat " [" default-prop "]") "")
16420 ": ")
16421 (mapcar #'list (org-buffer-property-keys nil t t))
16422 nil nil nil nil default-prop)))
16424 (defun org-set-property-and-value (use-last)
16425 "Allow to set [PROPERTY]: [value] direction from prompt.
16426 When use-default, don't even ask, just use the last
16427 \"[PROPERTY]: [value]\" string from the history."
16428 (interactive "P")
16429 (let* ((completion-ignore-case t)
16430 (pv (or (and use-last org-last-set-property-value)
16431 (org-completing-read
16432 "Enter a \"[Property]: [value]\" pair: "
16433 nil nil nil nil nil
16434 org-last-set-property-value)))
16435 prop val)
16436 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16437 (setq prop (match-string 1 pv)
16438 val (match-string 2 pv))
16439 (org-set-property prop val))))
16441 (defun org-set-property (property value)
16442 "In the current entry, set PROPERTY to VALUE.
16444 When called interactively, this will prompt for a property name, offering
16445 completion on existing and default properties. And then it will prompt
16446 for a value, offering completion either on allowed values (via an inherited
16447 xxx_ALL property) or on existing values in other instances of this property
16448 in the current file.
16450 Throw an error when trying to set a property with an invalid name."
16451 (interactive (list nil nil))
16452 (let ((property (or property (org-read-property-name))))
16453 ;; `org-entry-put' also makes the following check, but this one
16454 ;; avoids polluting `org-last-set-property' and
16455 ;; `org-last-set-property-value' needlessly.
16456 (unless (org--valid-property-p property)
16457 (user-error "Invalid property name: \"%s\"" property))
16458 (let ((value (or value (org-read-property-value property)))
16459 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16460 (setq org-last-set-property property)
16461 (setq org-last-set-property-value (concat property ": " value))
16462 ;; Possibly postprocess the inserted value:
16463 (when fn (setq value (funcall fn value)))
16464 (unless (equal (org-entry-get nil property) value)
16465 (org-entry-put nil property value)))))
16467 (defun org-find-property (property &optional value)
16468 "Find first entry in buffer that sets PROPERTY.
16470 When optional argument VALUE is non-nil, only consider an entry
16471 if it contains PROPERTY set to this value. If PROPERTY should be
16472 explicitly set to nil, use string \"nil\" for VALUE.
16474 Return position where the entry begins, or nil if there is no
16475 such entry. If narrowing is in effect, only search the visible
16476 part of the buffer."
16477 (save-excursion
16478 (goto-char (point-min))
16479 (let ((case-fold-search t)
16480 (re (org-re-property property nil (not value) value)))
16481 (catch 'exit
16482 (while (re-search-forward re nil t)
16483 (when (if value (org-at-property-p)
16484 (org-entry-get (point) property nil t))
16485 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16487 (defun org-delete-property (property)
16488 "In the current entry, delete PROPERTY."
16489 (interactive
16490 (let* ((completion-ignore-case t)
16491 (cat (org-entry-get (point) "CATEGORY"))
16492 (props0 (org-entry-properties nil 'standard))
16493 (props (if cat props0
16494 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16495 (prop (if (< 1 (length props))
16496 (completing-read "Property: " props nil t)
16497 (caar props))))
16498 (list prop)))
16499 (if (not property)
16500 (message "No property to delete in this entry")
16501 (org-entry-delete nil property)
16502 (message "Property \"%s\" deleted" property)))
16504 (defun org-delete-property-globally (property)
16505 "Remove PROPERTY globally, from all entries.
16506 This function ignores narrowing, if any."
16507 (interactive
16508 (let* ((completion-ignore-case t)
16509 (prop (completing-read
16510 "Globally remove property: "
16511 (mapcar #'list (org-buffer-property-keys)))))
16512 (list prop)))
16513 (org-with-wide-buffer
16514 (goto-char (point-min))
16515 (let ((count 0)
16516 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16517 (while (re-search-forward re nil t)
16518 (when (org-entry-delete (point) property) (cl-incf count)))
16519 (message "Property \"%s\" removed from %d entries" property count))))
16521 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16523 (defun org-compute-property-at-point ()
16524 "Compute the property at point.
16525 This looks for an enclosing column format, extracts the operator and
16526 then applies it to the property in the column format's scope."
16527 (interactive)
16528 (unless (org-at-property-p)
16529 (user-error "Not at a property"))
16530 (let ((prop (match-string-no-properties 2)))
16531 (org-columns-get-format-and-top-level)
16532 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16533 (user-error "No operator defined for property %s" prop))
16534 (org-columns-compute prop)))
16536 (defvar org-property-allowed-value-functions nil
16537 "Hook for functions supplying allowed values for a specific property.
16538 The functions must take a single argument, the name of the property, and
16539 return a flat list of allowed values. If \":ETC\" is one of
16540 the values, this means that these values are intended as defaults for
16541 completion, but that other values should be allowed too.
16542 The functions must return nil if they are not responsible for this
16543 property.")
16545 (defun org-property-get-allowed-values (pom property &optional table)
16546 "Get allowed values for the property PROPERTY.
16547 When TABLE is non-nil, return an alist that can directly be used for
16548 completion."
16549 (let (vals)
16550 (cond
16551 ((equal property "TODO")
16552 (setq vals (org-with-point-at pom
16553 (append org-todo-keywords-1 '("")))))
16554 ((equal property "PRIORITY")
16555 (let ((n org-lowest-priority))
16556 (while (>= n org-highest-priority)
16557 (push (char-to-string n) vals)
16558 (setq n (1- n)))))
16559 ((equal property "CATEGORY"))
16560 ((member property org-special-properties))
16561 ((setq vals (run-hook-with-args-until-success
16562 'org-property-allowed-value-functions property)))
16564 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16565 (when (and vals (string-match "\\S-" vals))
16566 (setq vals (car (read-from-string (concat "(" vals ")"))))
16567 (setq vals (mapcar (lambda (x)
16568 (cond ((stringp x) x)
16569 ((numberp x) (number-to-string x))
16570 ((symbolp x) (symbol-name x))
16571 (t "???")))
16572 vals)))))
16573 (when (member ":ETC" vals)
16574 (setq vals (remove ":ETC" vals))
16575 (org-add-props (car vals) '(org-unrestricted t)))
16576 (if table (mapcar 'list vals) vals)))
16578 (defun org-property-previous-allowed-value (&optional _previous)
16579 "Switch to the next allowed value for this property."
16580 (interactive)
16581 (org-property-next-allowed-value t))
16583 (defun org-property-next-allowed-value (&optional previous)
16584 "Switch to the next allowed value for this property."
16585 (interactive)
16586 (unless (org-at-property-p)
16587 (user-error "Not at a property"))
16588 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16589 (key (match-string 2))
16590 (value (match-string 3))
16591 (allowed (or (org-property-get-allowed-values (point) key)
16592 (and (member value '("[ ]" "[-]" "[X]"))
16593 '("[ ]" "[X]"))))
16594 (heading (save-match-data (nth 4 (org-heading-components))))
16595 nval)
16596 (unless allowed
16597 (user-error "Allowed values for this property have not been defined"))
16598 (when previous (setq allowed (reverse allowed)))
16599 (when (member value allowed)
16600 (setq nval (car (cdr (member value allowed)))))
16601 (setq nval (or nval (car allowed)))
16602 (when (equal nval value)
16603 (user-error "Only one allowed value for this property"))
16604 (org-at-property-p)
16605 (replace-match (concat " :" key ": " nval) t t)
16606 (org-indent-line)
16607 (beginning-of-line 1)
16608 (skip-chars-forward " \t")
16609 (when (equal prop org-effort-property)
16610 (org-refresh-property
16611 '((effort . identity)
16612 (effort-minutes . org-duration-string-to-minutes))
16613 nval)
16614 (when (string= org-clock-current-task heading)
16615 (setq org-clock-effort nval)
16616 (org-clock-update-mode-line)))
16617 (run-hook-with-args 'org-property-changed-functions key nval)))
16619 (defun org-find-olp (path &optional this-buffer)
16620 "Return a marker pointing to the entry at outline path OLP.
16621 If anything goes wrong, throw an error.
16622 You can wrap this call to catch the error like this:
16624 (condition-case msg
16625 (org-mobile-locate-entry (match-string 4))
16626 (error (nth 1 msg)))
16628 The return value will then be either a string with the error message,
16629 or a marker if everything is OK.
16631 If THIS-BUFFER is set, the outline path does not contain a file,
16632 only headings."
16633 (let* ((file (if this-buffer buffer-file-name (pop path)))
16634 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16635 (level 1)
16636 (lmin 1)
16637 (lmax 1)
16638 end found flevel)
16639 (unless buffer (error "File not found :%s" file))
16640 (with-current-buffer buffer
16641 (org-with-wide-buffer
16642 (goto-char (point-min))
16643 (dolist (heading path)
16644 (let ((re (format org-complex-heading-regexp-format
16645 (regexp-quote heading)))
16646 (cnt 0))
16647 (while (re-search-forward re end t)
16648 (setq level (- (match-end 1) (match-beginning 1)))
16649 (when (and (>= level lmin) (<= level lmax))
16650 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16651 (when (= cnt 0)
16652 (error "Heading not found on level %d: %s" lmax heading))
16653 (when (> cnt 1)
16654 (error "Heading not unique on level %d: %s" lmax heading))
16655 (goto-char found)
16656 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16657 (setq end (save-excursion (org-end-of-subtree t t)))))
16658 (when (org-at-heading-p)
16659 (point-marker))))))
16661 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16662 "Find node HEADING in BUFFER.
16663 Return a marker to the heading if it was found, or nil if not.
16664 If POS-ONLY is set, return just the position instead of a marker.
16666 The heading text must match exact, but it may have a TODO keyword,
16667 a priority cookie and tags in the standard locations."
16668 (with-current-buffer (or buffer (current-buffer))
16669 (org-with-wide-buffer
16670 (goto-char (point-min))
16671 (let (case-fold-search)
16672 (when (re-search-forward
16673 (format org-complex-heading-regexp-format
16674 (regexp-quote heading)) nil t)
16675 (if pos-only
16676 (match-beginning 0)
16677 (move-marker (make-marker) (match-beginning 0))))))))
16679 (defun org-find-exact-heading-in-directory (heading &optional dir)
16680 "Find Org node headline HEADING in all .org files in directory DIR.
16681 When the target headline is found, return a marker to this location."
16682 (let ((files (directory-files (or dir default-directory)
16683 t "\\`[^.#].*\\.org\\'"))
16684 visiting m buffer)
16685 (catch 'found
16686 (dolist (file files)
16687 (message "trying %s" file)
16688 (setq visiting (org-find-base-buffer-visiting file))
16689 (setq buffer (or visiting (find-file-noselect file)))
16690 (setq m (org-find-exact-headline-in-buffer
16691 heading buffer))
16692 (when (and (not m) (not visiting)) (kill-buffer buffer))
16693 (and m (throw 'found m))))))
16695 (defun org-find-entry-with-id (ident)
16696 "Locate the entry that contains the ID property with exact value IDENT.
16697 IDENT can be a string, a symbol or a number, this function will search for
16698 the string representation of it.
16699 Return the position where this entry starts, or nil if there is no such entry."
16700 (interactive "sID: ")
16701 (let ((id (cond
16702 ((stringp ident) ident)
16703 ((symbolp ident) (symbol-name ident))
16704 ((numberp ident) (number-to-string ident))
16705 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16706 (org-with-wide-buffer (org-find-property "ID" id))))
16708 ;;;; Timestamps
16710 (defvar org-last-changed-timestamp nil)
16711 (defvar org-last-inserted-timestamp nil
16712 "The last time stamp inserted with `org-insert-time-stamp'.")
16713 (defvar org-ts-what) ; dynamically scoped parameter
16715 (defun org-time-stamp (arg &optional inactive)
16716 "Prompt for a date/time and insert a time stamp.
16718 If the user specifies a time like HH:MM or if this command is
16719 called with at least one prefix argument, the time stamp contains
16720 the date and the time. Otherwise, only the date is included.
16722 All parts of a date not specified by the user are filled in from
16723 the timestamp at point, if any, or the current date/time
16724 otherwise.
16726 If there is already a timestamp at the cursor, it is replaced.
16728 With two universal prefix arguments, insert an active timestamp
16729 with the current time without prompting the user.
16731 When called from lisp, the timestamp is inactive if INACTIVE is
16732 non-nil."
16733 (interactive "P")
16734 (let* ((ts (cond
16735 ((org-at-date-range-p t)
16736 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16737 ((org-at-timestamp-p t) (match-string 0))))
16738 ;; Default time is either the timestamp at point or today.
16739 ;; When entering a range, only the range start is considered.
16740 (default-time (if (not ts) (current-time)
16741 (apply #'encode-time (org-parse-time-string ts))))
16742 (default-input (and ts (org-get-compact-tod ts)))
16743 (repeater (and ts
16744 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16745 (match-string 0 ts)))
16746 org-time-was-given
16747 org-end-time-was-given
16748 (time
16749 (and (if (equal arg '(16)) (current-time)
16750 ;; Preserve `this-command' and `last-command'.
16751 (let ((this-command this-command)
16752 (last-command last-command))
16753 (org-read-date
16754 arg 'totime nil nil default-time default-input
16755 inactive))))))
16756 (cond
16757 ((and ts
16758 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16759 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16760 (insert "--")
16761 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16763 ;; Make sure we're on a timestamp. When in the middle of a date
16764 ;; range, move arbitrarily to range end.
16765 (unless (org-at-timestamp-p t)
16766 (skip-chars-forward "-")
16767 (org-at-timestamp-p t))
16768 (replace-match "")
16769 (setq org-last-changed-timestamp
16770 (org-insert-time-stamp
16771 time (or org-time-was-given arg)
16772 inactive nil nil (list org-end-time-was-given)))
16773 (when repeater
16774 (backward-char)
16775 (insert " " repeater)
16776 (setq org-last-changed-timestamp
16777 (concat (substring org-last-inserted-timestamp 0 -1)
16778 " " repeater ">")))
16779 (message "Timestamp updated"))
16780 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16781 (t (org-insert-time-stamp
16782 time (or org-time-was-given arg) inactive nil nil
16783 (list org-end-time-was-given))))))
16785 ;; FIXME: can we use this for something else, like computing time differences?
16786 (defun org-get-compact-tod (s)
16787 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16788 (let* ((t1 (match-string 1 s))
16789 (h1 (string-to-number (match-string 2 s)))
16790 (m1 (string-to-number (match-string 3 s)))
16791 (t2 (and (match-end 4) (match-string 5 s)))
16792 (h2 (and t2 (string-to-number (match-string 6 s))))
16793 (m2 (and t2 (string-to-number (match-string 7 s))))
16794 dh dm)
16795 (if (not t2)
16797 (setq dh (- h2 h1) dm (- m2 m1))
16798 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16799 (concat t1 "+" (number-to-string dh)
16800 (and (/= 0 dm) (format ":%02d" dm)))))))
16802 (defun org-time-stamp-inactive (&optional arg)
16803 "Insert an inactive time stamp.
16804 An inactive time stamp is enclosed in square brackets instead of angle
16805 brackets. It is inactive in the sense that it does not trigger agenda entries,
16806 does not link to the calendar and cannot be changed with the S-cursor keys.
16807 So these are more for recording a certain time/date."
16808 (interactive "P")
16809 (org-time-stamp arg 'inactive))
16811 (defvar org-date-ovl (make-overlay 1 1))
16812 (overlay-put org-date-ovl 'face 'org-date-selected)
16813 (delete-overlay org-date-ovl)
16815 (defvar org-ans1) ; dynamically scoped parameter
16816 (defvar org-ans2) ; dynamically scoped parameter
16818 (defvar org-plain-time-of-day-regexp) ; defined below
16820 (defvar org-overriding-default-time nil) ; dynamically scoped
16821 (defvar org-read-date-overlay nil)
16822 (defvar org-dcst nil) ; dynamically scoped
16823 (defvar org-read-date-history nil)
16824 (defvar org-read-date-final-answer nil)
16825 (defvar org-read-date-analyze-futurep nil)
16826 (defvar org-read-date-analyze-forced-year nil)
16827 (defvar org-read-date-inactive)
16829 (defvar org-read-date-minibuffer-local-map
16830 (let* ((map (make-sparse-keymap)))
16831 (set-keymap-parent map minibuffer-local-map)
16832 (org-defkey map (kbd ".")
16833 (lambda () (interactive)
16834 ;; Are we at the beginning of the prompt?
16835 (if (looking-back "^[^:]+: "
16836 (let ((inhibit-field-text-motion t))
16837 (line-beginning-position)))
16838 (org-eval-in-calendar '(calendar-goto-today))
16839 (insert "."))))
16840 (org-defkey map (kbd "C-.")
16841 (lambda () (interactive)
16842 (org-eval-in-calendar '(calendar-goto-today))))
16843 (org-defkey map [(meta shift left)]
16844 (lambda () (interactive)
16845 (org-eval-in-calendar '(calendar-backward-month 1))))
16846 (org-defkey map [(meta shift right)]
16847 (lambda () (interactive)
16848 (org-eval-in-calendar '(calendar-forward-month 1))))
16849 (org-defkey map [(meta shift up)]
16850 (lambda () (interactive)
16851 (org-eval-in-calendar '(calendar-backward-year 1))))
16852 (org-defkey map [(meta shift down)]
16853 (lambda () (interactive)
16854 (org-eval-in-calendar '(calendar-forward-year 1))))
16855 (org-defkey map [?\e (shift left)]
16856 (lambda () (interactive)
16857 (org-eval-in-calendar '(calendar-backward-month 1))))
16858 (org-defkey map [?\e (shift right)]
16859 (lambda () (interactive)
16860 (org-eval-in-calendar '(calendar-forward-month 1))))
16861 (org-defkey map [?\e (shift up)]
16862 (lambda () (interactive)
16863 (org-eval-in-calendar '(calendar-backward-year 1))))
16864 (org-defkey map [?\e (shift down)]
16865 (lambda () (interactive)
16866 (org-eval-in-calendar '(calendar-forward-year 1))))
16867 (org-defkey map [(shift up)]
16868 (lambda () (interactive)
16869 (org-eval-in-calendar '(calendar-backward-week 1))))
16870 (org-defkey map [(shift down)]
16871 (lambda () (interactive)
16872 (org-eval-in-calendar '(calendar-forward-week 1))))
16873 (org-defkey map [(shift left)]
16874 (lambda () (interactive)
16875 (org-eval-in-calendar '(calendar-backward-day 1))))
16876 (org-defkey map [(shift right)]
16877 (lambda () (interactive)
16878 (org-eval-in-calendar '(calendar-forward-day 1))))
16879 (org-defkey map "!"
16880 (lambda () (interactive)
16881 (org-eval-in-calendar '(diary-view-entries))
16882 (message "")))
16883 (org-defkey map ">"
16884 (lambda () (interactive)
16885 (org-eval-in-calendar '(calendar-scroll-left 1))))
16886 (org-defkey map "<"
16887 (lambda () (interactive)
16888 (org-eval-in-calendar '(calendar-scroll-right 1))))
16889 (org-defkey map "\C-v"
16890 (lambda () (interactive)
16891 (org-eval-in-calendar
16892 '(calendar-scroll-left-three-months 1))))
16893 (org-defkey map "\M-v"
16894 (lambda () (interactive)
16895 (org-eval-in-calendar
16896 '(calendar-scroll-right-three-months 1))))
16897 map)
16898 "Keymap for minibuffer commands when using `org-read-date'.")
16900 (defvar org-def)
16901 (defvar org-defdecode)
16902 (defvar org-with-time)
16904 (defvar calendar-setup) ; Dynamically scoped.
16905 (defun org-read-date (&optional with-time to-time from-string prompt
16906 default-time default-input inactive)
16907 "Read a date, possibly a time, and make things smooth for the user.
16908 The prompt will suggest to enter an ISO date, but you can also enter anything
16909 which will at least partially be understood by `parse-time-string'.
16910 Unrecognized parts of the date will default to the current day, month, year,
16911 hour and minute. If this command is called to replace a timestamp at point,
16912 or to enter the second timestamp of a range, the default time is taken
16913 from the existing stamp. Furthermore, the command prefers the future,
16914 so if you are giving a date where the year is not given, and the day-month
16915 combination is already past in the current year, it will assume you
16916 mean next year. For details, see the manual. A few examples:
16918 3-2-5 --> 2003-02-05
16919 feb 15 --> currentyear-02-15
16920 2/15 --> currentyear-02-15
16921 sep 12 9 --> 2009-09-12
16922 12:45 --> today 12:45
16923 22 sept 0:34 --> currentyear-09-22 0:34
16924 12 --> currentyear-currentmonth-12
16925 Fri --> nearest Friday after today
16926 -Tue --> last Tuesday
16927 etc.
16929 Furthermore you can specify a relative date by giving, as the *first* thing
16930 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16931 change in days weeks, months, years.
16932 With a single plus or minus, the date is relative to today. With a double
16933 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16934 +4d --> four days from today
16935 +4 --> same as above
16936 +2w --> two weeks from today
16937 ++5 --> five days from default date
16939 The function understands only English month and weekday abbreviations.
16941 While prompting, a calendar is popped up - you can also select the
16942 date with the mouse (button 1). The calendar shows a period of three
16943 months. To scroll it to other months, use the keys `>' and `<'.
16944 If you don't like the calendar, turn it off with
16945 (setq org-read-date-popup-calendar nil)
16947 With optional argument TO-TIME, the date will immediately be converted
16948 to an internal time.
16949 With an optional argument WITH-TIME, the prompt will suggest to
16950 also insert a time. Note that when WITH-TIME is not set, you can
16951 still enter a time, and this function will inform the calling routine
16952 about this change. The calling routine may then choose to change the
16953 format used to insert the time stamp into the buffer to include the time.
16954 With optional argument FROM-STRING, read from this string instead from
16955 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16956 the time/date that is used for everything that is not specified by the
16957 user."
16958 (require 'parse-time)
16959 (let* ((org-with-time with-time)
16960 (org-time-stamp-rounding-minutes
16961 (if (equal org-with-time '(16))
16962 '(0 0)
16963 org-time-stamp-rounding-minutes))
16964 (org-dcst org-display-custom-times)
16965 (ct (org-current-time))
16966 (org-def (or org-overriding-default-time default-time ct))
16967 (org-defdecode (decode-time org-def))
16968 (cur-frame (selected-frame))
16969 (mouse-autoselect-window nil) ; Don't let the mouse jump
16970 (calendar-setup
16971 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16972 (calendar-move-hook nil)
16973 (calendar-view-diary-initially-flag nil)
16974 (calendar-view-holidays-initially-flag nil)
16975 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16976 ;; Rationalize `org-def' and `org-defdecode', if required.
16977 (when (< (nth 2 org-defdecode) org-extend-today-until)
16978 (setf (nth 2 org-defdecode) -1)
16979 (setf (nth 1 org-defdecode) 59)
16980 (setq org-def (apply #'encode-time org-defdecode))
16981 (setq org-defdecode (decode-time org-def)))
16982 (let* ((timestr (format-time-string
16983 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16984 org-def))
16985 (prompt (concat (if prompt (concat prompt " ") "")
16986 (format "Date+time [%s]: " timestr))))
16987 (cond
16988 (from-string (setq ans from-string))
16989 (org-read-date-popup-calendar
16990 (save-excursion
16991 (save-window-excursion
16992 (calendar)
16993 (when (eq calendar-setup 'calendar-only)
16994 (setq cal-frame
16995 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16996 (select-frame cal-frame))
16997 (org-eval-in-calendar '(setq cursor-type nil) t)
16998 (unwind-protect
16999 (progn
17000 (calendar-forward-day (- (time-to-days org-def)
17001 (calendar-absolute-from-gregorian
17002 (calendar-current-date))))
17003 (org-eval-in-calendar nil t)
17004 (let* ((old-map (current-local-map))
17005 (map (copy-keymap calendar-mode-map))
17006 (minibuffer-local-map
17007 (copy-keymap org-read-date-minibuffer-local-map)))
17008 (org-defkey map (kbd "RET") 'org-calendar-select)
17009 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17010 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17011 (unwind-protect
17012 (progn
17013 (use-local-map map)
17014 (setq org-read-date-inactive inactive)
17015 (add-hook 'post-command-hook 'org-read-date-display)
17016 (setq org-ans0
17017 (read-string prompt
17018 default-input
17019 'org-read-date-history
17020 nil))
17021 ;; org-ans0: from prompt
17022 ;; org-ans1: from mouse click
17023 ;; org-ans2: from calendar motion
17024 (setq ans
17025 (concat org-ans0 " " (or org-ans1 org-ans2))))
17026 (remove-hook 'post-command-hook 'org-read-date-display)
17027 (use-local-map old-map)
17028 (when org-read-date-overlay
17029 (delete-overlay org-read-date-overlay)
17030 (setq org-read-date-overlay nil)))))
17031 (bury-buffer "*Calendar*")
17032 (when cal-frame
17033 (delete-frame cal-frame)
17034 (select-frame-set-input-focus cur-frame))))))
17036 (t ; Naked prompt only
17037 (unwind-protect
17038 (setq ans (read-string prompt default-input
17039 'org-read-date-history timestr))
17040 (when org-read-date-overlay
17041 (delete-overlay org-read-date-overlay)
17042 (setq org-read-date-overlay nil))))))
17044 (setq final (org-read-date-analyze ans org-def org-defdecode))
17046 (when org-read-date-analyze-forced-year
17047 (message "Year was forced into %s"
17048 (if org-read-date-force-compatible-dates
17049 "compatible range (1970-2037)"
17050 "range representable on this machine"))
17051 (ding))
17053 ;; One round trip to get rid of 34th of August and stuff like that....
17054 (setq final (decode-time (apply 'encode-time final)))
17056 (setq org-read-date-final-answer ans)
17058 (if to-time
17059 (apply 'encode-time final)
17060 (if (and (boundp 'org-time-was-given) org-time-was-given)
17061 (format "%04d-%02d-%02d %02d:%02d"
17062 (nth 5 final) (nth 4 final) (nth 3 final)
17063 (nth 2 final) (nth 1 final))
17064 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17066 (defun org-read-date-display ()
17067 "Display the current date prompt interpretation in the minibuffer."
17068 (when org-read-date-display-live
17069 (when org-read-date-overlay
17070 (delete-overlay org-read-date-overlay))
17071 (when (minibufferp (current-buffer))
17072 (save-excursion
17073 (end-of-line 1)
17074 (while (not (equal (buffer-substring
17075 (max (point-min) (- (point) 4)) (point))
17076 " "))
17077 (insert " ")))
17078 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17079 " " (or org-ans1 org-ans2)))
17080 (org-end-time-was-given nil)
17081 (f (org-read-date-analyze ans org-def org-defdecode))
17082 (fmts (if org-dcst
17083 org-time-stamp-custom-formats
17084 org-time-stamp-formats))
17085 (fmt (if (or org-with-time
17086 (and (boundp 'org-time-was-given) org-time-was-given))
17087 (cdr fmts)
17088 (car fmts)))
17089 (txt (format-time-string fmt (apply 'encode-time f)))
17090 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17091 (txt (concat "=> " txt)))
17092 (when (and org-end-time-was-given
17093 (string-match org-plain-time-of-day-regexp txt))
17094 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17095 org-end-time-was-given
17096 (substring txt (match-end 0)))))
17097 (when org-read-date-analyze-futurep
17098 (setq txt (concat txt " (=>F)")))
17099 (setq org-read-date-overlay
17100 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17101 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17103 (defun org-read-date-analyze (ans def defdecode)
17104 "Analyze the combined answer of the date prompt."
17105 ;; FIXME: cleanup and comment
17106 ;; Pass `current-time' result to `decode-time' (instead of calling
17107 ;; without arguments) so that only `current-time' has to be
17108 ;; overriden in tests.
17109 (let ((org-def def)
17110 (org-defdecode defdecode)
17111 (nowdecode (decode-time (current-time)))
17112 delta deltan deltaw deltadef year month day
17113 hour minute second wday pm h2 m2 tl wday1
17114 iso-year iso-weekday iso-week iso-date futurep kill-year)
17115 (setq org-read-date-analyze-futurep nil
17116 org-read-date-analyze-forced-year nil)
17117 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17118 (setq ans "+0"))
17120 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17121 (setq ans (replace-match "" t t ans)
17122 deltan (car delta)
17123 deltaw (nth 1 delta)
17124 deltadef (nth 2 delta)))
17126 ;; Check if there is an iso week date in there. If yes, store the
17127 ;; info and postpone interpreting it until the rest of the parsing
17128 ;; is done.
17129 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17130 (setq iso-year (when (match-end 1)
17131 (org-small-year-to-year
17132 (string-to-number (match-string 1 ans))))
17133 iso-weekday (when (match-end 3)
17134 (string-to-number (match-string 3 ans)))
17135 iso-week (string-to-number (match-string 2 ans)))
17136 (setq ans (replace-match "" t t ans)))
17138 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17139 (when (string-match
17140 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17141 (setq year (if (match-end 2)
17142 (string-to-number (match-string 2 ans))
17143 (progn (setq kill-year t)
17144 (string-to-number (format-time-string "%Y"))))
17145 month (string-to-number (match-string 3 ans))
17146 day (string-to-number (match-string 4 ans)))
17147 (setq year (org-small-year-to-year year))
17148 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17149 t nil ans)))
17151 ;; Help matching dotted european dates
17152 (when (string-match
17153 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17154 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17155 (setq kill-year t)
17156 (string-to-number (format-time-string "%Y")))
17157 day (string-to-number (match-string 1 ans))
17158 month (string-to-number (match-string 2 ans))
17159 ans (replace-match (format "%04d-%02d-%02d" year month day)
17160 t nil ans)))
17162 ;; Help matching american dates, like 5/30 or 5/30/7
17163 (when (string-match
17164 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17165 (setq year (if (match-end 4)
17166 (string-to-number (match-string 4 ans))
17167 (progn (setq kill-year t)
17168 (string-to-number (format-time-string "%Y"))))
17169 month (string-to-number (match-string 1 ans))
17170 day (string-to-number (match-string 2 ans)))
17171 (setq year (org-small-year-to-year year))
17172 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17173 t nil ans)))
17174 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17175 ;; If there is a time with am/pm, and *no* time without it, we convert
17176 ;; so that matching will be successful.
17177 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17178 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17179 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17180 (setq hour (string-to-number (match-string 1 ans))
17181 minute (if (match-end 3)
17182 (string-to-number (match-string 3 ans))
17184 pm (equal ?p
17185 (string-to-char (downcase (match-string 4 ans)))))
17186 (if (and (= hour 12) (not pm))
17187 (setq hour 0)
17188 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17189 (setq ans (replace-match (format "%02d:%02d" hour minute)
17190 t t ans))))
17192 ;; Check if a time range is given as a duration
17193 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17194 (setq hour (string-to-number (match-string 1 ans))
17195 h2 (+ hour (string-to-number (match-string 3 ans)))
17196 minute (string-to-number (match-string 2 ans))
17197 m2 (+ minute (if (match-end 5) (string-to-number
17198 (match-string 5 ans))0)))
17199 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17200 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17201 t t ans)))
17203 ;; Check if there is a time range
17204 (when (boundp 'org-end-time-was-given)
17205 (setq org-time-was-given nil)
17206 (when (and (string-match org-plain-time-of-day-regexp ans)
17207 (match-end 8))
17208 (setq org-end-time-was-given (match-string 8 ans))
17209 (setq ans (concat (substring ans 0 (match-beginning 7))
17210 (substring ans (match-end 7))))))
17212 (setq tl (parse-time-string ans)
17213 day (or (nth 3 tl) (nth 3 org-defdecode))
17214 month
17215 (cond ((nth 4 tl))
17216 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17217 ;; Day was specified. Make sure DAY+MONTH
17218 ;; combination happens in the future.
17219 ((nth 3 tl)
17220 (setq futurep t)
17221 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17222 (nth 4 nowdecode)))
17223 (t (nth 4 org-defdecode)))
17224 year
17225 (cond ((and (not kill-year) (nth 5 tl)))
17226 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17227 ;; Month was guessed in the future and is at least
17228 ;; equal to NOWDECODE's. Fix year accordingly.
17229 (futurep
17230 (if (or (> month (nth 4 nowdecode))
17231 (>= day (nth 3 nowdecode)))
17232 (nth 5 nowdecode)
17233 (1+ (nth 5 nowdecode))))
17234 ;; Month was specified. Make sure MONTH+YEAR
17235 ;; combination happens in the future.
17236 ((nth 4 tl)
17237 (setq futurep t)
17238 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17239 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17240 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17241 (t (nth 5 nowdecode))))
17242 (t (nth 5 org-defdecode)))
17243 hour (or (nth 2 tl) (nth 2 org-defdecode))
17244 minute (or (nth 1 tl) (nth 1 org-defdecode))
17245 second (or (nth 0 tl) 0)
17246 wday (nth 6 tl))
17248 (when (and (eq org-read-date-prefer-future 'time)
17249 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17250 (equal day (nth 3 nowdecode))
17251 (equal month (nth 4 nowdecode))
17252 (equal year (nth 5 nowdecode))
17253 (nth 2 tl)
17254 (or (< (nth 2 tl) (nth 2 nowdecode))
17255 (and (= (nth 2 tl) (nth 2 nowdecode))
17256 (nth 1 tl)
17257 (< (nth 1 tl) (nth 1 nowdecode)))))
17258 (setq day (1+ day)
17259 futurep t))
17261 ;; Special date definitions below
17262 (cond
17263 (iso-week
17264 ;; There was an iso week
17265 (require 'cal-iso)
17266 (setq futurep nil)
17267 (setq year (or iso-year year)
17268 day (or iso-weekday wday 1)
17269 wday nil ; to make sure that the trigger below does not match
17270 iso-date (calendar-gregorian-from-absolute
17271 (calendar-iso-to-absolute
17272 (list iso-week day year))))
17273 ; FIXME: Should we also push ISO weeks into the future?
17274 ; (when (and org-read-date-prefer-future
17275 ; (not iso-year)
17276 ; (< (calendar-absolute-from-gregorian iso-date)
17277 ; (time-to-days (current-time))))
17278 ; (setq year (1+ year)
17279 ; iso-date (calendar-gregorian-from-absolute
17280 ; (calendar-iso-to-absolute
17281 ; (list iso-week day year)))))
17282 (setq month (car iso-date)
17283 year (nth 2 iso-date)
17284 day (nth 1 iso-date)))
17285 (deltan
17286 (setq futurep nil)
17287 (unless deltadef
17288 ;; Pass `current-time' result to `decode-time' (instead of
17289 ;; calling without arguments) so that only `current-time' has
17290 ;; to be overriden in tests.
17291 (let ((now (decode-time (current-time))))
17292 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17293 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17294 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17295 ((equal deltaw "m") (setq month (+ month deltan)))
17296 ((equal deltaw "y") (setq year (+ year deltan)))))
17297 ((and wday (not (nth 3 tl)))
17298 ;; Weekday was given, but no day, so pick that day in the week
17299 ;; on or after the derived date.
17300 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17301 (unless (equal wday wday1)
17302 (setq day (+ day (% (- wday wday1 -7) 7))))))
17303 (when (and (boundp 'org-time-was-given)
17304 (nth 2 tl))
17305 (setq org-time-was-given t))
17306 (when (< year 100) (setq year (+ 2000 year)))
17307 ;; Check of the date is representable
17308 (if org-read-date-force-compatible-dates
17309 (progn
17310 (when (< year 1970)
17311 (setq year 1970 org-read-date-analyze-forced-year t))
17312 (when (> year 2037)
17313 (setq year 2037 org-read-date-analyze-forced-year t)))
17314 (condition-case nil
17315 (ignore (encode-time second minute hour day month year))
17316 (error
17317 (setq year (nth 5 org-defdecode))
17318 (setq org-read-date-analyze-forced-year t))))
17319 (setq org-read-date-analyze-futurep futurep)
17320 (list second minute hour day month year)))
17322 (defvar parse-time-weekdays)
17323 (defun org-read-date-get-relative (s today default)
17324 "Check string S for special relative date string.
17325 TODAY and DEFAULT are internal times, for today and for a default.
17326 Return shift list (N what def-flag)
17327 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17328 N is the number of WHATs to shift.
17329 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17330 the DEFAULT date rather than TODAY."
17331 (require 'parse-time)
17332 (when (and
17333 (string-match
17334 (concat
17335 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17336 "\\([0-9]+\\)?"
17337 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17338 "\\([ \t]\\|$\\)") s)
17339 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17340 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17341 (string-to-char (substring (match-string 1 s) -1))
17342 ?+))
17343 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17344 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17345 (what (if (match-end 3) (match-string 3 s) "d"))
17346 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17347 (date (if rel default today))
17348 (wday (nth 6 (decode-time date)))
17349 delta)
17350 (if wday1
17351 (progn
17352 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17353 (when (= delta 0) (setq delta 7))
17354 (when (= dir ?-)
17355 (setq delta (- delta 7))
17356 (when (= delta 0) (setq delta -7)))
17357 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17358 (list delta "d" rel))
17359 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17361 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17362 "Turn a user-specified date into the internal representation.
17363 The internal representation needed by the calendar is (month day year).
17364 This is a wrapper to handle the brain-dead convention in calendar that
17365 user function argument order change dependent on argument order."
17366 (pcase calendar-date-style
17367 (`american (list arg1 arg2 arg3))
17368 (`european (list arg2 arg1 arg3))
17369 (`iso (list arg2 arg3 arg1))))
17371 (defun org-eval-in-calendar (form &optional keepdate)
17372 "Eval FORM in the calendar window and return to current window.
17373 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17374 (let ((sf (selected-frame))
17375 (sw (selected-window)))
17376 (select-window (get-buffer-window "*Calendar*" t))
17377 (eval form)
17378 (when (and (not keepdate) (calendar-cursor-to-date))
17379 (let* ((date (calendar-cursor-to-date))
17380 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17381 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17382 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17383 (select-window sw)
17384 (select-frame-set-input-focus sf)))
17386 (defun org-calendar-select ()
17387 "Return to `org-read-date' with the date currently selected.
17388 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17389 (interactive)
17390 (when (calendar-cursor-to-date)
17391 (let* ((date (calendar-cursor-to-date))
17392 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17393 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17394 (when (active-minibuffer-window) (exit-minibuffer))))
17396 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17397 "Insert a date stamp for the date given by the internal TIME.
17398 See `format-time-string' for the format of TIME.
17399 WITH-HM means use the stamp format that includes the time of the day.
17400 INACTIVE means use square brackets instead of angular ones, so that the
17401 stamp will not contribute to the agenda.
17402 PRE and POST are optional strings to be inserted before and after the
17403 stamp.
17404 The command returns the inserted time stamp."
17405 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17406 stamp)
17407 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17408 (insert-before-markers (or pre ""))
17409 (when (listp extra)
17410 (setq extra (car extra))
17411 (if (and (stringp extra)
17412 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17413 (setq extra (format "-%02d:%02d"
17414 (string-to-number (match-string 1 extra))
17415 (string-to-number (match-string 2 extra))))
17416 (setq extra nil)))
17417 (when extra
17418 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17419 (insert-before-markers (setq stamp (format-time-string fmt time)))
17420 (insert-before-markers (or post ""))
17421 (setq org-last-inserted-timestamp stamp)))
17423 (defun org-toggle-time-stamp-overlays ()
17424 "Toggle the use of custom time stamp formats."
17425 (interactive)
17426 (setq org-display-custom-times (not org-display-custom-times))
17427 (unless org-display-custom-times
17428 (let ((p (point-min)) (bmp (buffer-modified-p)))
17429 (while (setq p (next-single-property-change p 'display))
17430 (when (and (get-text-property p 'display)
17431 (eq (get-text-property p 'face) 'org-date))
17432 (remove-text-properties
17433 p (setq p (next-single-property-change p 'display))
17434 '(display t))))
17435 (set-buffer-modified-p bmp)))
17436 (org-restart-font-lock)
17437 (setq org-table-may-need-update t)
17438 (if org-display-custom-times
17439 (message "Time stamps are overlaid with custom format")
17440 (message "Time stamp overlays removed")))
17442 (defun org-display-custom-time (beg end)
17443 "Overlay modified time stamp format over timestamp between BEG and END."
17444 (let* ((ts (buffer-substring beg end))
17445 t1 w1 with-hm tf time str w2 (off 0))
17446 (save-match-data
17447 (setq t1 (org-parse-time-string ts t))
17448 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17449 (setq off (- (match-end 0) (match-beginning 0)))))
17450 (setq end (- end off))
17451 (setq w1 (- end beg)
17452 with-hm (and (nth 1 t1) (nth 2 t1))
17453 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17454 time (org-fix-decoded-time t1)
17455 str (org-add-props
17456 (format-time-string
17457 (substring tf 1 -1) (apply 'encode-time time))
17458 nil 'mouse-face 'highlight)
17459 w2 (length str))
17460 (unless (= w2 w1)
17461 (add-text-properties (1+ beg) (+ 2 beg)
17462 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17463 (put-text-property beg end 'display str)))
17465 (defun org-fix-decoded-time (time)
17466 "Set 0 instead of nil for the first 6 elements of time.
17467 Don't touch the rest."
17468 (let ((n 0))
17469 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17471 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17472 "Difference between TIMESTAMP-STRING and now in days.
17473 If SECONDS is non-nil, return the difference in seconds."
17474 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17475 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17476 (funcall fdiff (current-time)))))
17478 (defun org-deadline-close-p (timestamp-string &optional ndays)
17479 "Is the time in TIMESTAMP-STRING close to the current date?"
17480 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17481 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17482 (not (org-entry-is-done-p))))
17484 (defun org-get-wdays (ts &optional delay zero-delay)
17485 "Get the deadline lead time appropriate for timestring TS.
17486 When DELAY is non-nil, get the delay time for scheduled items
17487 instead of the deadline lead time. When ZERO-DELAY is non-nil
17488 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17489 don't try to find the delay cookie in the scheduled timestamp."
17490 (let ((tv (if delay org-scheduled-delay-days
17491 org-deadline-warning-days)))
17492 (cond
17493 ((or (and delay (< tv 0))
17494 (and delay zero-delay (<= tv 0))
17495 (and (not delay) (<= tv 0)))
17496 ;; Enforce this value no matter what
17497 (- tv))
17498 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17499 ;; lead time is specified.
17500 (floor (* (string-to-number (match-string 1 ts))
17501 (cdr (assoc (match-string 2 ts)
17502 '(("d" . 1) ("w" . 7)
17503 ("m" . 30.4) ("y" . 365.25)
17504 ("h" . 0.041667)))))))
17505 ;; go for the default.
17506 (t tv))))
17508 (defun org-calendar-select-mouse (ev)
17509 "Return to `org-read-date' with the date currently selected.
17510 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17511 (interactive "e")
17512 (mouse-set-point ev)
17513 (when (calendar-cursor-to-date)
17514 (let* ((date (calendar-cursor-to-date))
17515 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17516 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17517 (when (active-minibuffer-window) (exit-minibuffer))))
17519 (defun org-check-deadlines (ndays)
17520 "Check if there are any deadlines due or past due.
17521 A deadline is considered due if it happens within `org-deadline-warning-days'
17522 days from today's date. If the deadline appears in an entry marked DONE,
17523 it is not shown. A numeric prefix argument NDAYS can be used to test that
17524 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17525 are shown."
17526 (interactive "P")
17527 (let* ((org-warn-days
17528 (cond
17529 ((equal ndays '(4)) 100000)
17530 (ndays (prefix-numeric-value ndays))
17531 (t (abs org-deadline-warning-days))))
17532 (case-fold-search nil)
17533 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17534 (callback
17535 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17536 (message "%d deadlines past-due or due within %d days"
17537 (org-occur regexp nil callback)
17538 org-warn-days)))
17540 (defsubst org-re-timestamp (type)
17541 "Return a regexp for timestamp TYPE.
17542 Allowed values for TYPE are:
17544 all: all timestamps
17545 active: only active timestamps (<...>)
17546 inactive: only inactive timestamps ([...])
17547 scheduled: only scheduled timestamps
17548 deadline: only deadline timestamps
17549 closed: only closed time-stamps
17551 When TYPE is nil, fall back on returning a regexp that matches
17552 both scheduled and deadline timestamps."
17553 (cl-case type
17554 (all org-ts-regexp-both)
17555 (active org-ts-regexp)
17556 (inactive org-ts-regexp-inactive)
17557 (scheduled org-scheduled-time-regexp)
17558 (deadline org-deadline-time-regexp)
17559 (closed org-closed-time-regexp)
17560 (otherwise
17561 (concat "\\<"
17562 (regexp-opt (list org-deadline-string org-scheduled-string))
17563 " *<\\([^>]+\\)>"))))
17565 (defun org-check-before-date (d)
17566 "Check if there are deadlines or scheduled entries before date D."
17567 (interactive (list (org-read-date)))
17568 (let* ((case-fold-search nil)
17569 (regexp (org-re-timestamp org-ts-type))
17570 (ts-type org-ts-type)
17571 (callback
17572 (lambda ()
17573 (let ((match (match-string 1)))
17574 (and (if (memq ts-type '(active inactive all))
17575 (eq (org-element-type (save-excursion
17576 (backward-char)
17577 (org-element-context)))
17578 'timestamp)
17579 (org-at-planning-p))
17580 (time-less-p
17581 (org-time-string-to-time match)
17582 (org-time-string-to-time d)))))))
17583 (message "%d entries before %s"
17584 (org-occur regexp nil callback)
17585 d)))
17587 (defun org-check-after-date (d)
17588 "Check if there are deadlines or scheduled entries after date D."
17589 (interactive (list (org-read-date)))
17590 (let* ((case-fold-search nil)
17591 (regexp (org-re-timestamp org-ts-type))
17592 (ts-type org-ts-type)
17593 (callback
17594 (lambda ()
17595 (let ((match (match-string 1)))
17596 (and (if (memq ts-type '(active inactive all))
17597 (eq (org-element-type (save-excursion
17598 (backward-char)
17599 (org-element-context)))
17600 'timestamp)
17601 (org-at-planning-p))
17602 (not (time-less-p
17603 (org-time-string-to-time match)
17604 (org-time-string-to-time d))))))))
17605 (message "%d entries after %s"
17606 (org-occur regexp nil callback)
17607 d)))
17609 (defun org-check-dates-range (start-date end-date)
17610 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17611 (interactive (list (org-read-date nil nil nil "Range starts")
17612 (org-read-date nil nil nil "Range end")))
17613 (let ((case-fold-search nil)
17614 (regexp (org-re-timestamp org-ts-type))
17615 (callback
17616 (let ((type org-ts-type))
17617 (lambda ()
17618 (let ((match (match-string 1)))
17619 (and
17620 (if (memq type '(active inactive all))
17621 (eq (org-element-type (save-excursion
17622 (backward-char)
17623 (org-element-context)))
17624 'timestamp)
17625 (org-at-planning-p))
17626 (not (time-less-p
17627 (org-time-string-to-time match)
17628 (org-time-string-to-time start-date)))
17629 (time-less-p
17630 (org-time-string-to-time match)
17631 (org-time-string-to-time end-date))))))))
17632 (message "%d entries between %s and %s"
17633 (org-occur regexp nil callback) start-date end-date)))
17635 (defun org-evaluate-time-range (&optional to-buffer)
17636 "Evaluate a time range by computing the difference between start and end.
17637 Normally the result is just printed in the echo area, but with prefix arg
17638 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17639 If the time range is actually in a table, the result is inserted into the
17640 next column.
17641 For time difference computation, a year is assumed to be exactly 365
17642 days in order to avoid rounding problems."
17643 (interactive "P")
17645 (org-clock-update-time-maybe)
17646 (save-excursion
17647 (unless (org-at-date-range-p t)
17648 (goto-char (point-at-bol))
17649 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17650 (unless (org-at-date-range-p t)
17651 (user-error "Not at a time-stamp range, and none found in current line")))
17652 (let* ((ts1 (match-string 1))
17653 (ts2 (match-string 2))
17654 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17655 (match-end (match-end 0))
17656 (time1 (org-time-string-to-time ts1))
17657 (time2 (org-time-string-to-time ts2))
17658 (t1 (float-time time1))
17659 (t2 (float-time time2))
17660 (diff (abs (- t2 t1)))
17661 (negative (< (- t2 t1) 0))
17662 ;; (ys (floor (* 365 24 60 60)))
17663 (ds (* 24 60 60))
17664 (hs (* 60 60))
17665 (fy "%dy %dd %02d:%02d")
17666 (fy1 "%dy %dd")
17667 (fd "%dd %02d:%02d")
17668 (fd1 "%dd")
17669 (fh "%02d:%02d")
17670 y d h m align)
17671 (if havetime
17672 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17674 d (floor (/ diff ds)) diff (mod diff ds)
17675 h (floor (/ diff hs)) diff (mod diff hs)
17676 m (floor (/ diff 60)))
17677 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17679 d (floor (+ (/ diff ds) 0.5))
17680 h 0 m 0))
17681 (if (not to-buffer)
17682 (message "%s" (org-make-tdiff-string y d h m))
17683 (if (org-at-table-p)
17684 (progn
17685 (goto-char match-end)
17686 (setq align t)
17687 (and (looking-at " *|") (goto-char (match-end 0))))
17688 (goto-char match-end))
17689 (when (looking-at
17690 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17691 (replace-match ""))
17692 (when negative (insert " -"))
17693 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17694 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17695 (insert " " (format fh h m))))
17696 (when align (org-table-align))
17697 (message "Time difference inserted")))))
17699 (defun org-make-tdiff-string (y d h m)
17700 (let ((fmt "")
17701 (l nil))
17702 (when (> y 0)
17703 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17704 (push y l))
17705 (when (> d 0)
17706 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17707 (push d l))
17708 (when (> h 0)
17709 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17710 (push h l))
17711 (when (> m 0)
17712 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17713 (push m l))
17714 (apply 'format fmt (nreverse l))))
17716 (defun org-time-string-to-time (s &optional buffer pos)
17717 "Convert a timestamp string into internal time."
17718 (condition-case errdata
17719 (apply 'encode-time (org-parse-time-string s))
17720 (error (error "Bad timestamp `%s'%s\nError was: %s"
17721 s (if (not (and buffer pos))
17723 (format-message " at %d in buffer `%s'" pos buffer))
17724 (cdr errdata)))))
17726 (defun org-time-string-to-seconds (s)
17727 "Convert a timestamp string to a number of seconds."
17728 (float-time (org-time-string-to-time s)))
17730 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17732 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17733 "Convert time stamp S to an absolute day number.
17735 If DAYNR in non-nil, and there is a specifier for a cyclic time
17736 stamp, get the closest date to DAYNR. If PREFER is
17737 `past' (respectively `future') return a date past (respectively
17738 after) or equal to DAYNR.
17740 POS is the location of time stamp S, as a buffer position in
17741 BUFFER.
17743 Diary sexp timestamps are matched against DAYNR, when non-nil.
17744 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17745 signalled."
17746 (cond
17747 ((string-match "\\`%%\\((.*)\\)" s)
17748 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17749 ;; only able to match individual dates. If it fails, raise an
17750 ;; error.
17751 (if (and daynr
17752 (org-diary-sexp-entry
17753 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17754 daynr
17755 (signal 'org-diary-sexp-no-match (list s))))
17756 (daynr (org-closest-date s daynr prefer))
17757 (t (time-to-days
17758 (condition-case errdata
17759 (apply #'encode-time (org-parse-time-string s))
17760 (error (error "Bad timestamp `%s'%s\nError was: %s"
17762 (if (not (and buffer pos)) ""
17763 (format-message " at %d in buffer `%s'" pos buffer))
17764 (cdr errdata))))))))
17766 (defun org-days-to-iso-week (days)
17767 "Return the iso week number."
17768 (require 'cal-iso)
17769 (car (calendar-iso-from-absolute days)))
17771 (defun org-small-year-to-year (year)
17772 "Convert 2-digit years into 4-digit years.
17773 YEAR is expanded into one of the 30 next years, if possible, or
17774 into a past one. Any year larger than 99 is returned unchanged."
17775 (if (>= year 100) year
17776 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17777 (century (/ current 100))
17778 (offset (- year (% current 100))))
17779 (cond ((> offset 30) (+ (* (1- century) 100) year))
17780 ((> offset -70) (+ (* century 100) year))
17781 (t (+ (* (1+ century) 100) year))))))
17783 (defun org-time-from-absolute (d)
17784 "Return the time corresponding to date D.
17785 D may be an absolute day number, or a calendar-type list (month day year)."
17786 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17787 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17789 (defvar org-agenda-current-date)
17790 (defun org-calendar-holiday ()
17791 "List of holidays, for Diary display in Org mode."
17792 (require 'holidays)
17793 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17794 (and hl (mapconcat #'identity hl "; "))))
17796 (defun org-diary-sexp-entry (sexp entry d)
17797 "Process a SEXP diary ENTRY for date D."
17798 (require 'diary-lib)
17799 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17800 ;; dynamically.
17801 (let* ((sexp `(let ((entry ,entry)
17802 (date ',d))
17803 ,(car (read-from-string sexp))))
17804 (result (if calendar-debug-sexp (eval sexp)
17805 (condition-case nil
17806 (eval sexp)
17807 (error
17808 (beep)
17809 (message "Bad sexp at line %d in %s: %s"
17810 (org-current-line)
17811 (buffer-file-name) sexp)
17812 (sleep-for 2))))))
17813 (cond ((stringp result) (split-string result "; "))
17814 ((and (consp result)
17815 (not (consp (cdr result)))
17816 (stringp (cdr result))) (cdr result))
17817 ((and (consp result)
17818 (stringp (car result))) result)
17819 (result entry))))
17821 (defun org-diary-to-ical-string (frombuf)
17822 "Get iCalendar entries from diary entries in buffer FROMBUF.
17823 This uses the icalendar.el library."
17824 (let* ((tmpdir temporary-file-directory)
17825 (tmpfile (make-temp-name
17826 (expand-file-name "orgics" tmpdir)))
17827 buf rtn b e)
17828 (with-current-buffer frombuf
17829 (icalendar-export-region (point-min) (point-max) tmpfile)
17830 (setq buf (find-buffer-visiting tmpfile))
17831 (set-buffer buf)
17832 (goto-char (point-min))
17833 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17834 (setq b (match-beginning 0)))
17835 (goto-char (point-max))
17836 (when (re-search-backward "^END:VEVENT" nil t)
17837 (setq e (match-end 0)))
17838 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17839 (kill-buffer buf)
17840 (delete-file tmpfile)
17841 rtn))
17843 (defun org-closest-date (start current prefer)
17844 "Return closest date to CURRENT starting from START.
17846 CURRENT and START are both time stamps.
17848 When PREFER is `past', return a date that is either CURRENT or
17849 past. When PREFER is `future', return a date that is either
17850 CURRENT or future.
17852 Only time stamps with a repeater are modified. Any other time
17853 stamp stay unchanged. In any case, return value is an absolute
17854 day number."
17855 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17856 ;; No repeater. Do not shift time stamp.
17857 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17858 (let ((value (string-to-number (match-string 1 start)))
17859 (type (match-string 2 start)))
17860 (if (= 0 value)
17861 ;; Repeater with a 0-value is considered as void.
17862 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17863 (let* ((base (org-date-to-gregorian start))
17864 (target (org-date-to-gregorian current))
17865 (sday (calendar-absolute-from-gregorian base))
17866 (cday (calendar-absolute-from-gregorian target))
17867 n1 n2)
17868 ;; If START is already past CURRENT, just return START.
17869 (if (<= cday sday) sday
17870 ;; Compute closest date before (N1) and closest date past
17871 ;; (N2) CURRENT.
17872 (pcase type
17873 ("h"
17874 (let ((missing-hours
17875 (mod (+ (- (* 24 (- cday sday))
17876 (nth 2 (org-parse-time-string start)))
17877 org-extend-today-until)
17878 value)))
17879 (setf n1 (if (= missing-hours 0) cday
17880 (- cday (1+ (/ missing-hours 24)))))
17881 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17882 ((or "d" "w")
17883 (let ((value (if (equal type "w") (* 7 value) value)))
17884 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17885 (setf n2 (+ n1 value))))
17886 ("m"
17887 (let* ((add-months
17888 (lambda (d n)
17889 ;; Add N months to gregorian date D, i.e.,
17890 ;; a list (MONTH DAY YEAR). Return a valid
17891 ;; gregorian date.
17892 (let ((m (+ (nth 0 d) n)))
17893 (list (mod m 12)
17894 (nth 1 d)
17895 (+ (/ m 12) (nth 2 d))))))
17896 (months ; Complete months to TARGET.
17897 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17898 (- (nth 0 target) (nth 0 base))
17899 ;; If START's day is greater than
17900 ;; TARGET's, remove incomplete month.
17901 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17902 value)
17903 value))
17904 (before (funcall add-months base months)))
17905 (setf n1 (calendar-absolute-from-gregorian before))
17906 (setf n2
17907 (calendar-absolute-from-gregorian
17908 (funcall add-months before value)))))
17910 (let* ((d (nth 1 base))
17911 (m (nth 0 base))
17912 (y (nth 2 base))
17913 (years ; Complete years to TARGET.
17914 (* (/ (- (nth 2 target)
17916 ;; If START's month and day are
17917 ;; greater than TARGET's, remove
17918 ;; incomplete year.
17919 (if (or (> (nth 0 target) m)
17920 (and (= (nth 0 target) m)
17921 (> (nth 1 target) d)))
17924 value)
17925 value))
17926 (before (list m d (+ y years))))
17927 (setf n1 (calendar-absolute-from-gregorian before))
17928 (setf n2 (calendar-absolute-from-gregorian
17929 (list m d (+ (nth 2 before) value)))))))
17930 ;; Handle PREFER parameter, if any.
17931 (cond
17932 ((eq prefer 'past) (if (= cday n2) n2 n1))
17933 ((eq prefer 'future) (if (= cday n1) n1 n2))
17934 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17936 (defun org-date-to-gregorian (d)
17937 "Turn any specification of date D into a Gregorian date for the calendar."
17938 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17939 ((and (listp d) (= (length d) 3)) d)
17940 ((stringp d)
17941 (let ((d (org-parse-time-string d)))
17942 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17943 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17945 (defun org-parse-time-string (s &optional nodefault zone)
17946 "Parse the standard Org time string.
17948 This should be a lot faster than the normal `parse-time-string'.
17950 If time is not given, defaults to 0:00. However, with optional
17951 NODEFAULT, hour and minute fields will be nil if not given.
17953 The optional ZONE is omitted or nil for Emacs local time, t for
17954 Universal Time, ‘wall’ for system wall clock time, or a string as
17955 in the TZ environment variable."
17956 (cond ((string-match org-ts-regexp0 s)
17957 (list 0
17958 (when (or (match-beginning 8) (not nodefault))
17959 (string-to-number (or (match-string 8 s) "0")))
17960 (when (or (match-beginning 7) (not nodefault))
17961 (string-to-number (or (match-string 7 s) "0")))
17962 (string-to-number (match-string 4 s))
17963 (string-to-number (match-string 3 s))
17964 (string-to-number (match-string 2 s))
17965 nil nil zone))
17966 ((string-match "^<[^>]+>$" s)
17967 ;; FIXME: `decode-time' needs to be called with ZONE as its
17968 ;; second argument. However, this requires at least Emacs
17969 ;; 25.1. We can do it when we switch to this version as our
17970 ;; minimal requirement.
17971 (decode-time (seconds-to-time (org-matcher-time s))))
17972 (t (error "Not a standard Org time string: %s" s))))
17974 (defun org-timestamp-up (&optional arg)
17975 "Increase the date item at the cursor by one.
17976 If the cursor is on the year, change the year. If it is on the month,
17977 the day or the time, change that.
17978 With prefix ARG, change by that many units."
17979 (interactive "p")
17980 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17982 (defun org-timestamp-down (&optional arg)
17983 "Decrease the date item at the cursor by one.
17984 If the cursor is on the year, change the year. If it is on the month,
17985 the day or the time, change that.
17986 With prefix ARG, change by that many units."
17987 (interactive "p")
17988 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17990 (defun org-timestamp-up-day (&optional arg)
17991 "Increase the date in the time stamp by one day.
17992 With prefix ARG, change that many days."
17993 (interactive "p")
17994 (if (and (not (org-at-timestamp-p t))
17995 (org-at-heading-p))
17996 (org-todo 'up)
17997 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17999 (defun org-timestamp-down-day (&optional arg)
18000 "Decrease the date in the time stamp by one day.
18001 With prefix ARG, change that many days."
18002 (interactive "p")
18003 (if (and (not (org-at-timestamp-p t))
18004 (org-at-heading-p))
18005 (org-todo 'down)
18006 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
18008 (defun org-at-timestamp-p (&optional inactive-ok)
18009 "Non-nil if point is inside a timestamp.
18011 When optional argument INACTIVE-OK is non-nil, also consider
18012 inactive timestamps.
18014 When this function returns a non-nil value, match data is set
18015 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18016 INACTIVE-OK."
18017 (interactive)
18018 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18019 (pos (point))
18020 (ans (or (looking-at tsr)
18021 (save-excursion
18022 (skip-chars-backward "^[<\n\r\t")
18023 (when (> (point) (point-min)) (backward-char 1))
18024 (and (looking-at tsr)
18025 (> (- (match-end 0) pos) -1))))))
18026 (and ans
18027 (boundp 'org-ts-what)
18028 (setq org-ts-what
18029 (cond
18030 ((= pos (match-beginning 0)) 'bracket)
18031 ;; Point is considered to be "on the bracket" whether
18032 ;; it's really on it or right after it.
18033 ((= pos (1- (match-end 0))) 'bracket)
18034 ((= pos (match-end 0)) 'after)
18035 ((org-pos-in-match-range pos 2) 'year)
18036 ((org-pos-in-match-range pos 3) 'month)
18037 ((org-pos-in-match-range pos 7) 'hour)
18038 ((org-pos-in-match-range pos 8) 'minute)
18039 ((or (org-pos-in-match-range pos 4)
18040 (org-pos-in-match-range pos 5)) 'day)
18041 ((and (> pos (or (match-end 8) (match-end 5)))
18042 (< pos (match-end 0)))
18043 (- pos (or (match-end 8) (match-end 5))))
18044 (t 'day))))
18045 ans))
18047 (defun org-toggle-timestamp-type ()
18048 "Toggle the type (<active> or [inactive]) of a time stamp."
18049 (interactive)
18050 (when (org-at-timestamp-p t)
18051 (let ((beg (match-beginning 0)) (end (match-end 0))
18052 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18053 (save-excursion
18054 (goto-char beg)
18055 (while (re-search-forward "[][<>]" end t)
18056 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18057 t t)))
18058 (message "Timestamp is now %sactive"
18059 (if (equal (char-after beg) ?<) "" "in")))))
18061 (defun org-at-clock-log-p nil
18062 "Is the cursor on the clock log line?"
18063 (save-excursion
18064 (beginning-of-line)
18065 (looking-at org-clock-line-re)))
18067 (defvar org-clock-history) ; defined in org-clock.el
18068 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18069 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18070 "Change the date in the time stamp at point.
18071 The date will be changed by N times WHAT. WHAT can be `day', `month',
18072 `year', `minute', `second'. If WHAT is not given, the cursor position
18073 in the timestamp determines what will be changed.
18074 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18075 (let ((origin (point)) origin-cat
18076 with-hm inactive
18077 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18078 org-ts-what
18079 extra rem
18080 ts time time0 fixnext clrgx)
18081 (unless (org-at-timestamp-p t)
18082 (user-error "Not at a timestamp"))
18083 (if (and (not what) (eq org-ts-what 'bracket))
18084 (org-toggle-timestamp-type)
18085 ;; Point isn't on brackets. Remember the part of the time-stamp
18086 ;; the point was in. Indeed, size of time-stamps may change,
18087 ;; but point must be kept in the same category nonetheless.
18088 (setq origin-cat org-ts-what)
18089 (when (and (not what) (not (eq org-ts-what 'day))
18090 org-display-custom-times
18091 (get-text-property (point) 'display)
18092 (not (get-text-property (1- (point)) 'display)))
18093 (setq org-ts-what 'day))
18094 (setq org-ts-what (or what org-ts-what)
18095 inactive (= (char-after (match-beginning 0)) ?\[)
18096 ts (match-string 0))
18097 (replace-match "")
18098 (when (string-match
18099 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18101 (setq extra (match-string 1 ts))
18102 (when suppress-tmp-delay
18103 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18104 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18105 (setq with-hm t))
18106 (setq time0 (org-parse-time-string ts))
18107 (when (and updown
18108 (eq org-ts-what 'minute)
18109 (not current-prefix-arg))
18110 ;; This looks like s-up and s-down. Change by one rounding step.
18111 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18112 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18113 (setcar (cdr time0) (+ (nth 1 time0)
18114 (if (> n 0) (- rem) (- dm rem))))))
18115 (setq time
18116 (apply #'encode-time
18117 (or (car time0) 0)
18118 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18119 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18120 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18121 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18122 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18123 (nthcdr 6 time0)))
18124 (when (and (member org-ts-what '(hour minute))
18125 extra
18126 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18127 (setq extra (org-modify-ts-extra
18128 extra
18129 (if (eq org-ts-what 'hour) 2 5)
18130 n dm)))
18131 (when (integerp org-ts-what)
18132 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18133 (when (eq what 'calendar)
18134 (let ((cal-date (org-get-date-from-calendar)))
18135 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18136 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18137 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18138 (setcar time0 (or (car time0) 0))
18139 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18140 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18141 (setq time (apply 'encode-time time0))))
18142 ;; Insert the new time-stamp, and ensure point stays in the same
18143 ;; category as before (i.e. not after the last position in that
18144 ;; category).
18145 (let ((pos (point)))
18146 ;; Stay before inserted string. `save-excursion' is of no use.
18147 (setq org-last-changed-timestamp
18148 (org-insert-time-stamp time with-hm inactive nil nil extra))
18149 (goto-char pos))
18150 (save-match-data
18151 (looking-at org-ts-regexp3)
18152 (goto-char
18153 (pcase origin-cat
18154 ;; `day' category ends before `hour' if any, or at the end
18155 ;; of the day name.
18156 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18157 (`hour (min (match-end 7) origin))
18158 (`minute (min (1- (match-end 8)) origin))
18159 ((pred integerp) (min (1- (match-end 0)) origin))
18160 ;; Point was right after the time-stamp. However, the
18161 ;; time-stamp length might have changed, so refer to
18162 ;; (match-end 0) instead.
18163 (`after (match-end 0))
18164 ;; `year' and `month' have both fixed size: point couldn't
18165 ;; have moved into another part.
18166 (_ origin))))
18167 ;; Update clock if on a CLOCK line.
18168 (org-clock-update-time-maybe)
18169 ;; Maybe adjust the closest clock in `org-clock-history'
18170 (when org-clock-adjust-closest
18171 (if (not (and (org-at-clock-log-p)
18172 (< 1 (length (delq nil (mapcar 'marker-position
18173 org-clock-history))))))
18174 (message "No clock to adjust")
18175 (cond ((save-excursion ; fix previous clock?
18176 (re-search-backward org-ts-regexp0 nil t)
18177 (looking-back (concat org-clock-string " \\[")
18178 (line-beginning-position)))
18179 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18180 ((save-excursion ; fix next clock?
18181 (re-search-backward org-ts-regexp0 nil t)
18182 (looking-at (concat org-ts-regexp0 "\\] =>")))
18183 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18184 (save-window-excursion
18185 ;; Find closest clock to point, adjust the previous/next one in history
18186 (let* ((p (save-excursion (org-back-to-heading t)))
18187 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18188 (clfixnth
18189 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18190 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18191 (if (not clfixpos)
18192 (message "No clock to adjust")
18193 (save-excursion
18194 (org-goto-marker-or-bmk clfixpos)
18195 (org-show-subtree)
18196 (when (re-search-forward clrgx nil t)
18197 (goto-char (match-beginning 1))
18198 (let (org-clock-adjust-closest)
18199 (org-timestamp-change n org-ts-what updown))
18200 (message "Clock adjusted in %s for heading: %s"
18201 (file-name-nondirectory (buffer-file-name))
18202 (org-get-heading t t)))))))))
18203 ;; Try to recenter the calendar window, if any.
18204 (when (and org-calendar-follow-timestamp-change
18205 (get-buffer-window "*Calendar*" t)
18206 (memq org-ts-what '(day month year)))
18207 (org-recenter-calendar (time-to-days time))))))
18209 (defun org-modify-ts-extra (s pos n dm)
18210 "Change the different parts of the lead-time and repeat fields in timestamp."
18211 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18212 ng h m new rem)
18213 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18214 (cond
18215 ((or (org-pos-in-match-range pos 2)
18216 (org-pos-in-match-range pos 3))
18217 (setq m (string-to-number (match-string 3 s))
18218 h (string-to-number (match-string 2 s)))
18219 (if (org-pos-in-match-range pos 2)
18220 (setq h (+ h n))
18221 (setq n (* dm (with-no-warnings (signum n))))
18222 (unless (= 0 (setq rem (% m dm)))
18223 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18224 (setq m (+ m n)))
18225 (when (< m 0) (setq m (+ m 60) h (1- h)))
18226 (when (> m 59) (setq m (- m 60) h (1+ h)))
18227 (setq h (mod h 24))
18228 (setq ng 1 new (format "-%02d:%02d" h m)))
18229 ((org-pos-in-match-range pos 6)
18230 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18231 ((org-pos-in-match-range pos 5)
18232 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18234 ((org-pos-in-match-range pos 9)
18235 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18236 ((org-pos-in-match-range pos 8)
18237 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18239 (when ng
18240 (setq s (concat
18241 (substring s 0 (match-beginning ng))
18243 (substring s (match-end ng))))))
18246 (defun org-recenter-calendar (d)
18247 "If the calendar is visible, recenter it to date D."
18248 (let ((cwin (get-buffer-window "*Calendar*" t)))
18249 (when cwin
18250 (let ((calendar-move-hook nil))
18251 (with-selected-window cwin
18252 (calendar-goto-date
18253 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18255 (defun org-goto-calendar (&optional arg)
18256 "Go to the Emacs calendar at the current date.
18257 If there is a time stamp in the current line, go to that date.
18258 A prefix ARG can be used to force the current date."
18259 (interactive "P")
18260 (let ((tsr org-ts-regexp) diff
18261 (calendar-move-hook nil)
18262 (calendar-view-holidays-initially-flag nil)
18263 (calendar-view-diary-initially-flag nil))
18264 (when (or (org-at-timestamp-p)
18265 (save-excursion
18266 (beginning-of-line 1)
18267 (looking-at (concat ".*" tsr))))
18268 (let ((d1 (time-to-days (current-time)))
18269 (d2 (time-to-days
18270 (org-time-string-to-time (match-string 1)))))
18271 (setq diff (- d2 d1))))
18272 (calendar)
18273 (calendar-goto-today)
18274 (when (and diff (not arg)) (calendar-forward-day diff))))
18276 (defun org-get-date-from-calendar ()
18277 "Return a list (month day year) of date at point in calendar."
18278 (with-current-buffer "*Calendar*"
18279 (save-match-data
18280 (calendar-cursor-to-date))))
18282 (defun org-date-from-calendar ()
18283 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18284 If there is already a time stamp at the cursor position, update it."
18285 (interactive)
18286 (if (org-at-timestamp-p t)
18287 (org-timestamp-change 0 'calendar)
18288 (let ((cal-date (org-get-date-from-calendar)))
18289 (org-insert-time-stamp
18290 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18292 (defcustom org-effort-durations
18293 `(("min" . 1)
18294 ("h" . 60)
18295 ("d" . ,(* 60 8))
18296 ("w" . ,(* 60 8 5))
18297 ("m" . ,(* 60 8 5 4))
18298 ("y" . ,(* 60 8 5 40)))
18299 "Conversion factor to minutes for an effort modifier.
18301 Each entry has the form (MODIFIER . MINUTES).
18303 In an effort string, a number followed by MODIFIER is multiplied
18304 by the specified number of MINUTES to obtain an effort in
18305 minutes.
18307 For example, if the value of this variable is ((\"hours\" . 60)), then an
18308 effort string \"2hours\" is equivalent to 120 minutes."
18309 :group 'org-agenda
18310 :version "26.1"
18311 :package-version '(Org . "8.3")
18312 :type '(alist :key-type (string :tag "Modifier")
18313 :value-type (number :tag "Minutes")))
18315 (defun org-minutes-to-clocksum-string (m)
18316 "Format number of minutes as a clocksum string.
18317 The format is determined by `org-time-clocksum-format',
18318 `org-time-clocksum-use-fractional' and
18319 `org-time-clocksum-fractional-format' and
18320 `org-time-clocksum-use-effort-durations'."
18321 (let ((clocksum "")
18322 (m (round m)) ; Don't allow fractions of minutes
18323 h d w mo y fmt n)
18324 (setq h (if org-time-clocksum-use-effort-durations
18325 (cdr (assoc "h" org-effort-durations)) 60)
18326 d (if org-time-clocksum-use-effort-durations
18327 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18328 w (if org-time-clocksum-use-effort-durations
18329 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18330 mo (if org-time-clocksum-use-effort-durations
18331 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18332 y (if org-time-clocksum-use-effort-durations
18333 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18334 ;; fractional format
18335 (if org-time-clocksum-use-fractional
18336 (cond
18337 ;; single format string
18338 ((stringp org-time-clocksum-fractional-format)
18339 (format org-time-clocksum-fractional-format (/ m (float h))))
18340 ;; choice of fractional formats for different time units
18341 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18342 (> (/ (truncate m) (* y d h)) 0))
18343 (format fmt (/ m (* y d (float h)))))
18344 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18345 (> (/ (truncate m) (* mo d h)) 0))
18346 (format fmt (/ m (* mo d (float h)))))
18347 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18348 (> (/ (truncate m) (* w d h)) 0))
18349 (format fmt (/ m (* w d (float h)))))
18350 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18351 (> (/ (truncate m) (* d h)) 0))
18352 (format fmt (/ m (* d (float h)))))
18353 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18354 (> (/ (truncate m) h) 0))
18355 (format fmt (/ m (float h))))
18356 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18357 (format fmt m))
18358 ;; fall back to smallest time unit with a format
18359 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18360 (format fmt (/ m (float h))))
18361 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18362 (format fmt (/ m (* d (float h)))))
18363 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18364 (format fmt (/ m (* w d (float h)))))
18365 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18366 (format fmt (/ m (* mo d (float h)))))
18367 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18368 (format fmt (/ m (* y d (float h))))))
18369 ;; standard (non-fractional) format, with single format string
18370 (if (stringp org-time-clocksum-format)
18371 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18372 ;; separate formats components
18373 (and (setq fmt (plist-get org-time-clocksum-format :years))
18374 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18375 (plist-get org-time-clocksum-format :require-years))
18376 (setq clocksum (concat clocksum (format fmt n))
18377 m (- m (* n y d h))))
18378 (and (setq fmt (plist-get org-time-clocksum-format :months))
18379 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18380 (plist-get org-time-clocksum-format :require-months))
18381 (setq clocksum (concat clocksum (format fmt n))
18382 m (- m (* n mo d h))))
18383 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18384 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18385 (plist-get org-time-clocksum-format :require-weeks))
18386 (setq clocksum (concat clocksum (format fmt n))
18387 m (- m (* n w d h))))
18388 (and (setq fmt (plist-get org-time-clocksum-format :days))
18389 (or (> (setq n (/ (truncate m) (* d h))) 0)
18390 (plist-get org-time-clocksum-format :require-days))
18391 (setq clocksum (concat clocksum (format fmt n))
18392 m (- m (* n d h))))
18393 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18394 (or (> (setq n (/ (truncate m) h)) 0)
18395 (plist-get org-time-clocksum-format :require-hours))
18396 (setq clocksum (concat clocksum (format fmt n))
18397 m (- m (* n h))))
18398 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18399 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18400 (setq clocksum (concat clocksum (format fmt m))))
18401 ;; return formatted time duration
18402 clocksum))))
18404 (defun org-hours-to-clocksum-string (n)
18405 (org-minutes-to-clocksum-string (* n 60)))
18407 (defun org-hh:mm-string-to-minutes (s)
18408 "Convert a string H:MM to a number of minutes.
18409 If the string is just a number, interpret it as minutes.
18410 In fact, the first hh:mm or number in the string will be taken,
18411 there can be extra stuff in the string.
18412 If no number is found, the return value is 0."
18413 (cond
18414 ((integerp s) s)
18415 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18416 (+ (* (string-to-number (match-string 1 s)) 60)
18417 (string-to-number (match-string 2 s))))
18418 ((string-match "\\([0-9]+\\)" s)
18419 (string-to-number (match-string 1 s)))
18420 (t 0)))
18422 (defcustom org-image-actual-width t
18423 "Should we use the actual width of images when inlining them?
18425 When set to t, always use the image width.
18427 When set to a number, use imagemagick (when available) to set
18428 the image's width to this value.
18430 When set to a number in a list, try to get the width from any
18431 #+ATTR.* keyword if it matches a width specification like
18433 #+ATTR_HTML: :width 300px
18435 and fall back on that number if none is found.
18437 When set to nil, try to get the width from an #+ATTR.* keyword
18438 and fall back on the original width if none is found.
18440 This requires Emacs >= 24.1, build with imagemagick support."
18441 :group 'org-appearance
18442 :version "24.4"
18443 :package-version '(Org . "8.0")
18444 :type '(choice
18445 (const :tag "Use the image width" t)
18446 (integer :tag "Use a number of pixels")
18447 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18448 (const :tag "Use #+ATTR* or don't resize" nil)))
18450 (defcustom org-agenda-inhibit-startup nil
18451 "Inhibit startup when preparing agenda buffers.
18452 When this variable is t, the initialization of the Org agenda
18453 buffers is inhibited: e.g. the visibility state is not set, the
18454 tables are not re-aligned, etc."
18455 :type 'boolean
18456 :version "24.3"
18457 :group 'org-agenda)
18459 (defcustom org-agenda-ignore-properties nil
18460 "Avoid updating text properties when building the agenda.
18461 Properties are used to prepare buffers for effort estimates,
18462 appointments, statistics and subtree-local categories.
18463 If you don't use these in the agenda, you can add them to this
18464 list and agenda building will be a bit faster.
18465 The value is a list, with zero or more of the symbols `effort', `appt',
18466 `stats' or `category'."
18467 :type '(set :greedy t
18468 (const effort)
18469 (const appt)
18470 (const stats)
18471 (const category))
18472 :version "26.1"
18473 :package-version '(Org . "8.3")
18474 :group 'org-agenda)
18476 (defun org-duration-string-to-minutes (s &optional output-to-string)
18477 "Convert a duration string S to minutes.
18479 A bare number is interpreted as minutes, modifiers can be set by
18480 customizing `org-effort-durations' (which see).
18482 Entries containing a colon are interpreted as H:MM by
18483 `org-hh:mm-string-to-minutes'."
18484 (let ((result 0)
18485 (re (concat "\\([0-9.]+\\) *\\("
18486 (regexp-opt (mapcar 'car org-effort-durations))
18487 "\\)")))
18488 (while (string-match re s)
18489 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18490 (string-to-number (match-string 1 s))))
18491 (setq s (replace-match "" nil t s)))
18492 (setq result (floor result))
18493 (cl-incf result (org-hh:mm-string-to-minutes s))
18494 (if output-to-string (number-to-string result) result)))
18496 ;;;; Files
18498 (defun org-save-all-org-buffers ()
18499 "Save all Org buffers without user confirmation."
18500 (interactive)
18501 (message "Saving all Org buffers...")
18502 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18503 (when (featurep 'org-id) (org-id-locations-save))
18504 (message "Saving all Org buffers... done"))
18506 (defun org-revert-all-org-buffers ()
18507 "Revert all Org buffers.
18508 Prompt for confirmation when there are unsaved changes.
18509 Be sure you know what you are doing before letting this function
18510 overwrite your changes.
18512 This function is useful in a setup where one tracks org files
18513 with a version control system, to revert on one machine after pulling
18514 changes from another. I believe the procedure must be like this:
18516 1. M-x org-save-all-org-buffers
18517 2. Pull changes from the other machine, resolve conflicts
18518 3. M-x org-revert-all-org-buffers"
18519 (interactive)
18520 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18521 (user-error "Abort"))
18522 (save-excursion
18523 (save-window-excursion
18524 (dolist (b (buffer-list))
18525 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18526 (with-current-buffer b buffer-file-name))
18527 (pop-to-buffer-same-window b)
18528 (revert-buffer t 'no-confirm)))
18529 (when (and (featurep 'org-id) org-id-track-globally)
18530 (org-id-locations-load)))))
18532 ;;;; Agenda files
18534 ;;;###autoload
18535 (defun org-switchb (&optional arg)
18536 "Switch between Org buffers.
18538 With `\\[universal-argument]' prefix, restrict available buffers to files.
18540 With `\\[universal-argument] \\[universal-argument]' \
18541 prefix, restrict available buffers to agenda files."
18542 (interactive "P")
18543 (let ((blist (org-buffer-list
18544 (cond ((equal arg '(4)) 'files)
18545 ((equal arg '(16)) 'agenda)))))
18546 (pop-to-buffer-same-window
18547 (completing-read "Org buffer: "
18548 (mapcar #'list (mapcar #'buffer-name blist))
18549 nil t))))
18551 (defun org-buffer-list (&optional predicate exclude-tmp)
18552 "Return a list of Org buffers.
18553 PREDICATE can be `export', `files' or `agenda'.
18555 export restrict the list to Export buffers.
18556 files restrict the list to buffers visiting Org files.
18557 agenda restrict the list to buffers visiting agenda files.
18559 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18560 (let* ((bfn nil)
18561 (agenda-files (and (eq predicate 'agenda)
18562 (mapcar 'file-truename (org-agenda-files t))))
18563 (filter
18564 (cond
18565 ((eq predicate 'files)
18566 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18567 ((eq predicate 'export)
18568 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18569 ((eq predicate 'agenda)
18570 (lambda (b)
18571 (with-current-buffer b
18572 (and (derived-mode-p 'org-mode)
18573 (setq bfn (buffer-file-name b))
18574 (member (file-truename bfn) agenda-files)))))
18575 (t (lambda (b) (with-current-buffer b
18576 (or (derived-mode-p 'org-mode)
18577 (string-match "\\*Org .*Export"
18578 (buffer-name b)))))))))
18579 (delq nil
18580 (mapcar
18581 (lambda(b)
18582 (if (and (funcall filter b)
18583 (or (not exclude-tmp)
18584 (not (string-match "tmp" (buffer-name b)))))
18586 nil))
18587 (buffer-list)))))
18589 (defun org-agenda-files (&optional unrestricted archives)
18590 "Get the list of agenda files.
18591 Optional UNRESTRICTED means return the full list even if a restriction
18592 is currently in place.
18593 When ARCHIVES is t, include all archive files that are really being
18594 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18595 `org-agenda-archives-mode' is t."
18596 (let ((files
18597 (cond
18598 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18599 ((stringp org-agenda-files) (org-read-agenda-file-list))
18600 ((listp org-agenda-files) org-agenda-files)
18601 (t (error "Invalid value of `org-agenda-files'")))))
18602 (setq files (apply 'append
18603 (mapcar (lambda (f)
18604 (if (file-directory-p f)
18605 (directory-files
18606 f t org-agenda-file-regexp)
18607 (list f)))
18608 files)))
18609 (when org-agenda-skip-unavailable-files
18610 (setq files (delq nil
18611 (mapcar (function
18612 (lambda (file)
18613 (and (file-readable-p file) file)))
18614 files))))
18615 (when (or (eq archives t)
18616 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18617 (setq files (org-add-archive-files files)))
18618 files))
18620 (defun org-agenda-file-p (&optional file)
18621 "Return non-nil, if FILE is an agenda file.
18622 If FILE is omitted, use the file associated with the current
18623 buffer."
18624 (let ((fname (or file (buffer-file-name))))
18625 (and fname
18626 (member (file-truename fname)
18627 (mapcar #'file-truename (org-agenda-files t))))))
18629 (defun org-edit-agenda-file-list ()
18630 "Edit the list of agenda files.
18631 Depending on setup, this either uses customize to edit the variable
18632 `org-agenda-files', or it visits the file that is holding the list. In the
18633 latter case, the buffer is set up in a way that saving it automatically kills
18634 the buffer and restores the previous window configuration."
18635 (interactive)
18636 (if (stringp org-agenda-files)
18637 (let ((cw (current-window-configuration)))
18638 (find-file org-agenda-files)
18639 (setq-local org-window-configuration cw)
18640 (add-hook 'after-save-hook
18641 (lambda ()
18642 (set-window-configuration
18643 (prog1 org-window-configuration
18644 (kill-buffer (current-buffer))))
18645 (org-install-agenda-files-menu)
18646 (message "New agenda file list installed"))
18647 nil 'local)
18648 (message "%s" (substitute-command-keys
18649 "Edit list and finish with \\[save-buffer]")))
18650 (customize-variable 'org-agenda-files)))
18652 (defun org-store-new-agenda-file-list (list)
18653 "Set new value for the agenda file list and save it correctly."
18654 (if (stringp org-agenda-files)
18655 (let ((fe (org-read-agenda-file-list t)) b u)
18656 (while (setq b (find-buffer-visiting org-agenda-files))
18657 (kill-buffer b))
18658 (with-temp-file org-agenda-files
18659 (insert
18660 (mapconcat
18661 (lambda (f) ;; Keep un-expanded entries.
18662 (if (setq u (assoc f fe))
18663 (cdr u)
18665 list "\n")
18666 "\n")))
18667 (let ((org-mode-hook nil) (org-inhibit-startup t)
18668 (org-insert-mode-line-in-empty-file nil))
18669 (setq org-agenda-files list)
18670 (customize-save-variable 'org-agenda-files org-agenda-files))))
18672 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18673 "Read the list of agenda files from a file.
18674 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18675 filenames, used by `org-store-new-agenda-file-list' to write back
18676 un-expanded file names."
18677 (when (file-directory-p org-agenda-files)
18678 (error "`org-agenda-files' cannot be a single directory"))
18679 (when (stringp org-agenda-files)
18680 (with-temp-buffer
18681 (insert-file-contents org-agenda-files)
18682 (mapcar
18683 (lambda (f)
18684 (let ((e (expand-file-name (substitute-in-file-name f)
18685 org-directory)))
18686 (if pair-with-expansion
18687 (cons e f)
18688 e)))
18689 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18691 ;;;###autoload
18692 (defun org-cycle-agenda-files ()
18693 "Cycle through the files in `org-agenda-files'.
18694 If the current buffer visits an agenda file, find the next one in the list.
18695 If the current buffer does not, find the first agenda file."
18696 (interactive)
18697 (let* ((fs (or (org-agenda-files t)
18698 (user-error "No agenda files")))
18699 (files (copy-sequence fs))
18700 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18701 file)
18702 (when tcf
18703 (while (and (setq file (pop files))
18704 (not (equal (file-truename file) tcf)))))
18705 (find-file (car (or files fs)))
18706 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18708 (defun org-agenda-file-to-front (&optional to-end)
18709 "Move/add the current file to the top of the agenda file list.
18710 If the file is not present in the list, it is added to the front. If it is
18711 present, it is moved there. With optional argument TO-END, add/move to the
18712 end of the list."
18713 (interactive "P")
18714 (let ((org-agenda-skip-unavailable-files nil)
18715 (file-alist (mapcar (lambda (x)
18716 (cons (file-truename x) x))
18717 (org-agenda-files t)))
18718 (ctf (file-truename
18719 (or buffer-file-name
18720 (user-error "Please save the current buffer to a file"))))
18721 x had)
18722 (setq x (assoc ctf file-alist) had x)
18724 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18725 (if to-end
18726 (setq file-alist (append (delq x file-alist) (list x)))
18727 (setq file-alist (cons x (delq x file-alist))))
18728 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18729 (org-install-agenda-files-menu)
18730 (message "File %s to %s of agenda file list"
18731 (if had "moved" "added") (if to-end "end" "front"))))
18733 (defun org-remove-file (&optional file)
18734 "Remove current file from the list of files in variable `org-agenda-files'.
18735 These are the files which are being checked for agenda entries.
18736 Optional argument FILE means use this file instead of the current."
18737 (interactive)
18738 (let* ((org-agenda-skip-unavailable-files nil)
18739 (file (or file buffer-file-name
18740 (user-error "Current buffer does not visit a file")))
18741 (true-file (file-truename file))
18742 (afile (abbreviate-file-name file))
18743 (files (delq nil (mapcar
18744 (lambda (x)
18745 (unless (equal true-file
18746 (file-truename x))
18748 (org-agenda-files t)))))
18749 (if (not (= (length files) (length (org-agenda-files t))))
18750 (progn
18751 (org-store-new-agenda-file-list files)
18752 (org-install-agenda-files-menu)
18753 (message "Removed from Org Agenda list: %s" afile))
18754 (message "File was not in list: %s (not removed)" afile))))
18756 (defun org-file-menu-entry (file)
18757 (vector file (list 'find-file file) t))
18759 (defun org-check-agenda-file (file)
18760 "Make sure FILE exists. If not, ask user what to do."
18761 (unless (file-exists-p file)
18762 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18763 (abbreviate-file-name file))
18764 (let ((r (downcase (read-char-exclusive))))
18765 (cond
18766 ((equal r ?r)
18767 (org-remove-file file)
18768 (throw 'nextfile t))
18769 (t (user-error "Abort"))))))
18771 (defun org-get-agenda-file-buffer (file)
18772 "Get an agenda buffer visiting FILE.
18773 If the buffer needs to be created, add it to the list of buffers
18774 which might be released later."
18775 (let ((buf (org-find-base-buffer-visiting file)))
18776 (if buf
18777 buf ; just return it
18778 ;; Make a new buffer and remember it
18779 (setq buf (find-file-noselect file))
18780 (when buf (push buf org-agenda-new-buffers))
18781 buf)))
18783 (defun org-release-buffers (blist)
18784 "Release all buffers in list, asking the user for confirmation when needed.
18785 When a buffer is unmodified, it is just killed. When modified, it is saved
18786 \(if the user agrees) and then killed."
18787 (let (file)
18788 (dolist (buf blist)
18789 (setq file (buffer-file-name buf))
18790 (when (and (buffer-modified-p buf)
18791 file
18792 (y-or-n-p (format "Save file %s? " file)))
18793 (with-current-buffer buf (save-buffer)))
18794 (kill-buffer buf))))
18796 (defun org-agenda-prepare-buffers (files)
18797 "Create buffers for all agenda files, protect archived trees and comments."
18798 (interactive)
18799 (let ((pa '(:org-archived t))
18800 (pc '(:org-comment t))
18801 (pall '(:org-archived t :org-comment t))
18802 (inhibit-read-only t)
18803 (org-inhibit-startup org-agenda-inhibit-startup)
18804 (rea (concat ":" org-archive-tag ":"))
18805 re pos)
18806 (setq org-tag-alist-for-agenda nil
18807 org-tag-groups-alist-for-agenda nil)
18808 (save-excursion
18809 (save-restriction
18810 (dolist (file files)
18811 (catch 'nextfile
18812 (if (bufferp file)
18813 (set-buffer file)
18814 (org-check-agenda-file file)
18815 (set-buffer (org-get-agenda-file-buffer file)))
18816 (widen)
18817 (org-set-regexps-and-options 'tags-only)
18818 (setq pos (point))
18819 (or (memq 'category org-agenda-ignore-properties)
18820 (org-refresh-category-properties))
18821 (or (memq 'stats org-agenda-ignore-properties)
18822 (org-refresh-stats-properties))
18823 (or (memq 'effort org-agenda-ignore-properties)
18824 (org-refresh-effort-properties))
18825 (or (memq 'appt org-agenda-ignore-properties)
18826 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18827 (setq org-todo-keywords-for-agenda
18828 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18829 (setq org-done-keywords-for-agenda
18830 (append org-done-keywords-for-agenda org-done-keywords))
18831 (setq org-todo-keyword-alist-for-agenda
18832 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18833 (setq org-tag-alist-for-agenda
18834 (org-uniquify
18835 (append org-tag-alist-for-agenda
18836 org-current-tag-alist)))
18837 ;; Merge current file's tag groups into global
18838 ;; `org-tag-groups-alist-for-agenda'.
18839 (when org-group-tags
18840 (dolist (alist org-tag-groups-alist)
18841 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18842 (if old
18843 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18844 (push alist org-tag-groups-alist-for-agenda)))))
18845 (org-with-silent-modifications
18846 (save-excursion
18847 (remove-text-properties (point-min) (point-max) pall)
18848 (when org-agenda-skip-archived-trees
18849 (goto-char (point-min))
18850 (while (re-search-forward rea nil t)
18851 (when (org-at-heading-p t)
18852 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18853 (goto-char (point-min))
18854 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18855 (while (re-search-forward re nil t)
18856 (when (save-match-data (org-in-commented-heading-p t))
18857 (add-text-properties
18858 (match-beginning 0) (org-end-of-subtree t) pc)))))
18859 (goto-char pos)))))
18860 (setq org-todo-keywords-for-agenda
18861 (org-uniquify org-todo-keywords-for-agenda))
18862 (setq org-todo-keyword-alist-for-agenda
18863 (org-uniquify org-todo-keyword-alist-for-agenda))))
18866 ;;;; CDLaTeX minor mode
18868 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18869 "Keymap for the minor `org-cdlatex-mode'.")
18871 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18872 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18873 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18874 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18875 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18877 (defvar org-cdlatex-texmathp-advice-is-done nil
18878 "Flag remembering if we have applied the advice to texmathp already.")
18880 (define-minor-mode org-cdlatex-mode
18881 "Toggle the minor `org-cdlatex-mode'.
18882 This mode supports entering LaTeX environment and math in LaTeX fragments
18883 in Org mode.
18884 \\{org-cdlatex-mode-map}"
18885 nil " OCDL" nil
18886 (when org-cdlatex-mode
18887 (require 'cdlatex)
18888 (run-hooks 'cdlatex-mode-hook)
18889 (cdlatex-compute-tables))
18890 (unless org-cdlatex-texmathp-advice-is-done
18891 (setq org-cdlatex-texmathp-advice-is-done t)
18892 (defadvice texmathp (around org-math-always-on activate)
18893 "Always return t in Org buffers.
18894 This is because we want to insert math symbols without dollars even outside
18895 the LaTeX math segments. If Org mode thinks that point is actually inside
18896 an embedded LaTeX fragment, let `texmathp' do its job.
18897 `\\[org-cdlatex-mode-map]'"
18898 (interactive)
18899 (let (p)
18900 (cond
18901 ((not (derived-mode-p 'org-mode)) ad-do-it)
18902 ((eq this-command 'cdlatex-math-symbol)
18903 (setq ad-return-value t
18904 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18906 (let ((p (org-inside-LaTeX-fragment-p)))
18907 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18908 (setq ad-return-value t
18909 texmathp-why '("Org mode embedded math" . 0))
18910 (when p ad-do-it)))))))))
18912 (defun turn-on-org-cdlatex ()
18913 "Unconditionally turn on `org-cdlatex-mode'."
18914 (org-cdlatex-mode 1))
18916 (defun org-try-cdlatex-tab ()
18917 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18918 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18919 - inside a LaTeX fragment, or
18920 - after the first word in a line, where an abbreviation expansion could
18921 insert a LaTeX environment."
18922 (when org-cdlatex-mode
18923 (cond
18924 ;; Before any word on the line: No expansion possible.
18925 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18926 ;; Just after first word on the line: Expand it. Make sure it
18927 ;; cannot happen on headlines, though.
18928 ((save-excursion
18929 (skip-chars-backward "a-zA-Z0-9*")
18930 (skip-chars-backward " \t")
18931 (and (bolp) (not (org-at-heading-p))))
18932 (cdlatex-tab) t)
18933 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18935 (defun org-cdlatex-underscore-caret (&optional _arg)
18936 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18937 Revert to the normal definition outside of these fragments."
18938 (interactive "P")
18939 (if (org-inside-LaTeX-fragment-p)
18940 (call-interactively 'cdlatex-sub-superscript)
18941 (let (org-cdlatex-mode)
18942 (call-interactively (key-binding (vector last-input-event))))))
18944 (defun org-cdlatex-math-modify (&optional _arg)
18945 "Execute `cdlatex-math-modify' in LaTeX fragments.
18946 Revert to the normal definition outside of these fragments."
18947 (interactive "P")
18948 (if (org-inside-LaTeX-fragment-p)
18949 (call-interactively 'cdlatex-math-modify)
18950 (let (org-cdlatex-mode)
18951 (call-interactively (key-binding (vector last-input-event))))))
18953 (defun org-cdlatex-environment-indent (&optional environment item)
18954 "Execute `cdlatex-environment' and indent the inserted environment.
18956 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18958 The inserted environment is indented to current indentation
18959 unless point is at the beginning of the line, in which the
18960 environment remains unintended."
18961 (interactive)
18962 ;; cdlatex-environment always return nil. Therefore, capture output
18963 ;; first and determine if an environment was selected.
18964 (let* ((beg (point-marker))
18965 (end (copy-marker (point) t))
18966 (inserted (progn
18967 (ignore-errors (cdlatex-environment environment item))
18968 (< beg end)))
18969 ;; Figure out how many lines to move forward after the
18970 ;; environment has been inserted.
18971 (lines (when inserted
18972 (save-excursion
18973 (- (cl-loop while (< beg (point))
18974 with x = 0
18975 do (forward-line -1)
18976 (cl-incf x)
18977 finally return x)
18978 (if (progn (goto-char beg)
18979 (and (progn (skip-chars-forward " \t") (eolp))
18980 (progn (skip-chars-backward " \t") (bolp))))
18981 1 0)))))
18982 (env (org-trim (delete-and-extract-region beg end))))
18983 (when inserted
18984 ;; Get indentation of next line unless at column 0.
18985 (let ((ind (if (bolp) 0
18986 (save-excursion
18987 (org-return-indent)
18988 (prog1 (org-get-indentation)
18989 (when (progn (skip-chars-forward " \t") (eolp))
18990 (delete-region beg (point)))))))
18991 (bol (progn (skip-chars-backward " \t") (bolp))))
18992 ;; Insert a newline before environment unless at column zero
18993 ;; to "escape" the current line. Insert a newline if
18994 ;; something is one the same line as \end{ENVIRONMENT}.
18995 (insert
18996 (concat (unless bol "\n") env
18997 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18998 (unless (zerop ind)
18999 (save-excursion
19000 (goto-char beg)
19001 (while (< (point) end)
19002 (unless (eolp) (indent-line-to ind))
19003 (forward-line))))
19004 (goto-char beg)
19005 (forward-line lines)
19006 (indent-line-to ind)))
19007 (set-marker beg nil)
19008 (set-marker end nil)))
19011 ;;;; LaTeX fragments
19013 (defun org-inside-LaTeX-fragment-p ()
19014 "Test if point is inside a LaTeX fragment.
19015 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19016 sequence appearing also before point.
19017 Even though the matchers for math are configurable, this function assumes
19018 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19019 delimiters are skipped when they have been removed by customization.
19020 The return value is nil, or a cons cell with the delimiter and the
19021 position of this delimiter.
19023 This function does a reasonably good job, but can locally be fooled by
19024 for example currency specifications. For example it will assume being in
19025 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19026 fragments that are properly closed, but during editing, we have to live
19027 with the uncertainty caused by missing closing delimiters. This function
19028 looks only before point, not after."
19029 (catch 'exit
19030 (let ((pos (point))
19031 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19032 (lim (progn
19033 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19034 (point)))
19035 dd-on str (start 0) m re)
19036 (goto-char pos)
19037 (when dodollar
19038 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19039 re (nth 1 (assoc "$" org-latex-regexps)))
19040 (while (string-match re str start)
19041 (cond
19042 ((= (match-end 0) (length str))
19043 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19044 ((= (match-end 0) (- (length str) 5))
19045 (throw 'exit nil))
19046 (t (setq start (match-end 0))))))
19047 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19048 (goto-char pos)
19049 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19050 (and (match-beginning 2) (throw 'exit nil))
19051 ;; count $$
19052 (while (re-search-backward "\\$\\$" lim t)
19053 (setq dd-on (not dd-on)))
19054 (goto-char pos)
19055 (when dd-on (cons "$$" m))))))
19057 (defun org-inside-latex-macro-p ()
19058 "Is point inside a LaTeX macro or its arguments?"
19059 (save-match-data
19060 (org-in-regexp
19061 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19063 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19064 "Build an overlay between BEG and END using IMAGE file.
19065 Argument IMAGETYPE is the extension of the displayed image,
19066 as a string. It defaults to \"png\"."
19067 (let ((ov (make-overlay beg end))
19068 (imagetype (or (intern imagetype) 'png)))
19069 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19070 (overlay-put ov 'evaporate t)
19071 (overlay-put ov
19072 'modification-hooks
19073 (list (lambda (o _flag _beg _end &optional _l)
19074 (delete-overlay o))))
19075 (overlay-put ov
19076 'display
19077 (list 'image :type imagetype :file image :ascent 'center))))
19079 (defun org--list-latex-overlays (&optional beg end)
19080 "List all Org LaTeX overlays in current buffer.
19081 Limit to overlays between BEG and END when those are provided."
19082 (cl-remove-if-not
19083 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19084 (overlays-in (or beg (point-min)) (or end (point-max)))))
19086 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19087 "Remove all overlays with LaTeX fragment images in current buffer.
19088 When optional arguments BEG and END are non-nil, remove all
19089 overlays between them instead. Return a non-nil value when some
19090 overlays were removed, nil otherwise."
19091 (let ((overlays (org--list-latex-overlays beg end)))
19092 (mapc #'delete-overlay overlays)
19093 overlays))
19095 (defun org-toggle-latex-fragment (&optional arg)
19096 "Preview the LaTeX fragment at point, or all locally or globally.
19098 If the cursor is on a LaTeX fragment, create the image and overlay
19099 it over the source code, if there is none. Remove it otherwise.
19100 If there is no fragment at point, display all fragments in the
19101 current section.
19103 With prefix ARG, preview or clear image for all fragments in the
19104 current subtree or in the whole buffer when used before the first
19105 headline. With a prefix ARG `\\[universal-argument] \
19106 \\[universal-argument]' preview or clear images
19107 for all fragments in the buffer."
19108 (interactive "P")
19109 (when (display-graphic-p)
19110 (catch 'exit
19111 (save-excursion
19112 (let (beg end msg)
19113 (cond
19114 ((or (equal arg '(16))
19115 (and (equal arg '(4))
19116 (org-with-limited-levels (org-before-first-heading-p))))
19117 (if (org-remove-latex-fragment-image-overlays)
19118 (progn (message "LaTeX fragments images removed from buffer")
19119 (throw 'exit nil))
19120 (setq msg "Creating images for buffer...")))
19121 ((equal arg '(4))
19122 (org-with-limited-levels (org-back-to-heading t))
19123 (setq beg (point))
19124 (setq end (progn (org-end-of-subtree t) (point)))
19125 (if (org-remove-latex-fragment-image-overlays beg end)
19126 (progn
19127 (message "LaTeX fragment images removed from subtree")
19128 (throw 'exit nil))
19129 (setq msg "Creating images for subtree...")))
19130 ((let ((datum (org-element-context)))
19131 (when (memq (org-element-type datum)
19132 '(latex-environment latex-fragment))
19133 (setq beg (org-element-property :begin datum))
19134 (setq end (org-element-property :end datum))
19135 (if (org-remove-latex-fragment-image-overlays beg end)
19136 (progn (message "LaTeX fragment image removed")
19137 (throw 'exit nil))
19138 (setq msg "Creating image...")))))
19140 (org-with-limited-levels
19141 (setq beg (if (org-at-heading-p) (line-beginning-position)
19142 (outline-previous-heading)
19143 (point)))
19144 (setq end (progn (outline-next-heading) (point)))
19145 (if (org-remove-latex-fragment-image-overlays beg end)
19146 (progn
19147 (message "LaTeX fragment images removed from section")
19148 (throw 'exit nil))
19149 (setq msg "Creating images for section...")))))
19150 (let ((file (buffer-file-name (buffer-base-buffer))))
19151 (org-format-latex
19152 (concat org-preview-latex-image-directory "org-ltximg")
19153 beg end
19154 ;; Emacs cannot overlay images from remote hosts. Create
19155 ;; it in `temporary-file-directory' instead.
19156 (if (or (not file) (file-remote-p file))
19157 temporary-file-directory
19158 default-directory)
19159 'overlays msg 'forbuffer org-preview-latex-default-process))
19160 (message (concat msg "done")))))))
19162 (defun org-format-latex
19163 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19164 "Replace LaTeX fragments with links to an image.
19166 The function takes care of creating the replacement image.
19168 Only consider fragments between BEG and END when those are
19169 provided.
19171 When optional argument OVERLAYS is non-nil, display the image on
19172 top of the fragment instead of replacing it.
19174 PROCESSING-TYPE is the conversion method to use, as a symbol.
19176 Some of the options can be changed using the variable
19177 `org-format-latex-options', which see."
19178 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19179 (unless (eq processing-type 'verbatim)
19180 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19181 (cnt 0)
19182 checkdir-flag)
19183 (goto-char (or beg (point-min)))
19184 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19185 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19186 (overlay-recenter (or end (point-max))))
19187 (while (re-search-forward math-regexp end t)
19188 (unless (and overlays
19189 (eq (get-char-property (point) 'org-overlay-type)
19190 'org-latex-overlay))
19191 (let* ((context (org-element-context))
19192 (type (org-element-type context)))
19193 (when (memq type '(latex-environment latex-fragment))
19194 (let ((block-type (eq type 'latex-environment))
19195 (value (org-element-property :value context))
19196 (beg (org-element-property :begin context))
19197 (end (save-excursion
19198 (goto-char (org-element-property :end context))
19199 (skip-chars-backward " \r\t\n")
19200 (point))))
19201 (cond
19202 ((eq processing-type 'mathjax)
19203 ;; Prepare for MathJax processing.
19204 (if (not (string-match "\\`\\$\\$?" value))
19205 (goto-char end)
19206 (delete-region beg end)
19207 (if (string= (match-string 0 value) "$$")
19208 (insert "\\[" (substring value 2 -2) "\\]")
19209 (insert "\\(" (substring value 1 -1) "\\)"))))
19210 ((assq processing-type org-preview-latex-process-alist)
19211 ;; Process to an image.
19212 (cl-incf cnt)
19213 (goto-char beg)
19214 (let* ((processing-info
19215 (cdr (assq processing-type org-preview-latex-process-alist)))
19216 (face (face-at-point))
19217 ;; Get the colors from the face at point.
19219 (let ((color (plist-get org-format-latex-options
19220 :foreground)))
19221 (if (and forbuffer (eq color 'auto))
19222 (face-attribute face :foreground nil 'default)
19223 color)))
19225 (let ((color (plist-get org-format-latex-options
19226 :background)))
19227 (if (and forbuffer (eq color 'auto))
19228 (face-attribute face :background nil 'default)
19229 color)))
19230 (hash (sha1 (prin1-to-string
19231 (list org-format-latex-header
19232 org-latex-default-packages-alist
19233 org-latex-packages-alist
19234 org-format-latex-options
19235 forbuffer value fg bg))))
19236 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19237 (absprefix (expand-file-name prefix dir))
19238 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19239 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19240 (sep (and block-type "\n\n"))
19241 (link (concat sep "[[file:" linkfile "]]" sep))
19242 (options
19243 (org-combine-plists
19244 org-format-latex-options
19245 `(:foreground ,fg :background ,bg))))
19246 (when msg (message msg cnt))
19247 (unless checkdir-flag ; Ensure the directory exists.
19248 (setq checkdir-flag t)
19249 (let ((todir (file-name-directory absprefix)))
19250 (unless (file-directory-p todir)
19251 (make-directory todir t))))
19252 (unless (file-exists-p movefile)
19253 (org-create-formula-image
19254 value movefile options forbuffer processing-type))
19255 (if overlays
19256 (progn
19257 (dolist (o (overlays-in beg end))
19258 (when (eq (overlay-get o 'org-overlay-type)
19259 'org-latex-overlay)
19260 (delete-overlay o)))
19261 (org--format-latex-make-overlay beg end movefile imagetype)
19262 (goto-char end))
19263 (delete-region beg end)
19264 (insert
19265 (org-add-props link
19266 (list 'org-latex-src
19267 (replace-regexp-in-string "\"" "" value)
19268 'org-latex-src-embed-type
19269 (if block-type 'paragraph 'character)))))))
19270 ((eq processing-type 'mathml)
19271 ;; Process to MathML.
19272 (unless (org-format-latex-mathml-available-p)
19273 (user-error "LaTeX to MathML converter not configured"))
19274 (cl-incf cnt)
19275 (when msg (message msg cnt))
19276 (goto-char beg)
19277 (delete-region beg end)
19278 (insert (org-format-latex-as-mathml
19279 value block-type prefix dir)))
19281 (error "Unknown conversion process %s for LaTeX fragments"
19282 processing-type)))))))))))
19284 (defun org-create-math-formula (latex-frag &optional mathml-file)
19285 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19286 Use `org-latex-to-mathml-convert-command'. If the conversion is
19287 sucessful, return the portion between \"<math...> </math>\"
19288 elements otherwise return nil. When MATHML-FILE is specified,
19289 write the results in to that file. When invoked as an
19290 interactive command, prompt for LATEX-FRAG, with initial value
19291 set to the current active region and echo the results for user
19292 inspection."
19293 (interactive (list (let ((frag (when (org-region-active-p)
19294 (buffer-substring-no-properties
19295 (region-beginning) (region-end)))))
19296 (read-string "LaTeX Fragment: " frag nil frag))))
19297 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19298 (let* ((tmp-in-file
19299 (let ((file (file-relative-name
19300 (make-temp-name (expand-file-name "ltxmathml-in")))))
19301 (write-region latex-frag nil file)
19302 file))
19303 (tmp-out-file (file-relative-name
19304 (make-temp-name (expand-file-name "ltxmathml-out"))))
19305 (cmd (format-spec
19306 org-latex-to-mathml-convert-command
19307 `((?j . ,(and org-latex-to-mathml-jar-file
19308 (shell-quote-argument
19309 (expand-file-name
19310 org-latex-to-mathml-jar-file))))
19311 (?I . ,(shell-quote-argument tmp-in-file))
19312 (?i . ,latex-frag)
19313 (?o . ,(shell-quote-argument tmp-out-file)))))
19314 mathml shell-command-output)
19315 (when (called-interactively-p 'any)
19316 (unless (org-format-latex-mathml-available-p)
19317 (user-error "LaTeX to MathML converter not configured")))
19318 (message "Running %s" cmd)
19319 (setq shell-command-output (shell-command-to-string cmd))
19320 (setq mathml
19321 (when (file-readable-p tmp-out-file)
19322 (with-current-buffer (find-file-noselect tmp-out-file t)
19323 (goto-char (point-min))
19324 (when (re-search-forward
19325 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19326 (regexp-quote
19327 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19328 nil t)
19329 (prog1 (match-string 0) (kill-buffer))))))
19330 (cond
19331 (mathml
19332 (setq mathml
19333 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19334 (when mathml-file
19335 (write-region mathml nil mathml-file))
19336 (when (called-interactively-p 'any)
19337 (message mathml)))
19338 ((message "LaTeX to MathML conversion failed")
19339 (message shell-command-output)))
19340 (delete-file tmp-in-file)
19341 (when (file-exists-p tmp-out-file)
19342 (delete-file tmp-out-file))
19343 mathml))
19345 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19346 prefix &optional dir)
19347 "Use `org-create-math-formula' but check local cache first."
19348 (let* ((absprefix (expand-file-name prefix dir))
19349 (print-length nil) (print-level nil)
19350 (formula-id (concat
19351 "formula-"
19352 (sha1
19353 (prin1-to-string
19354 (list latex-frag
19355 org-latex-to-mathml-convert-command)))))
19356 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19357 (formula-cache-dir (file-name-directory formula-cache)))
19359 (unless (file-directory-p formula-cache-dir)
19360 (make-directory formula-cache-dir t))
19362 (unless (file-exists-p formula-cache)
19363 (org-create-math-formula latex-frag formula-cache))
19365 (if (file-exists-p formula-cache)
19366 ;; Successful conversion. Return the link to MathML file.
19367 (org-add-props
19368 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19369 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19370 'org-latex-src-embed-type (if latex-frag-type
19371 'paragraph 'character)))
19372 ;; Failed conversion. Return the LaTeX fragment verbatim
19373 latex-frag)))
19375 (defun org--get-display-dpi ()
19376 "Get the DPI of the display.
19377 The function assumes that the display has the same pixel width in
19378 the horizontal and vertical directions."
19379 (if (display-graphic-p)
19380 (round (/ (display-pixel-height)
19381 (/ (display-mm-height) 25.4)))
19382 (error "Attempt to calculate the dpi of a non-graphic display")))
19384 (defun org-create-formula-image
19385 (string tofile options buffer &optional processing-type)
19386 "Create an image from LaTeX source using external processes.
19388 The LaTeX STRING is saved to a temporary LaTeX file, then
19389 converted to an image file by process PROCESSING-TYPE defined in
19390 `org-preview-latex-process-alist'. A nil value defaults to
19391 `org-preview-latex-default-process'.
19393 The generated image file is eventually moved to TOFILE.
19395 The OPTIONS argument controls the size, foreground color and
19396 background color of the generated image.
19398 When BUFFER non-nil, this function is used for LaTeX previewing.
19399 Otherwise, it is used to deal with LaTeX snippets showed in
19400 a HTML file."
19401 (let* ((processing-type (or processing-type
19402 org-preview-latex-default-process))
19403 (processing-info
19404 (cdr (assq processing-type org-preview-latex-process-alist)))
19405 (programs (plist-get processing-info :programs))
19406 (error-message (or (plist-get processing-info :message) ""))
19407 (use-xcolor (plist-get processing-info :use-xcolor))
19408 (image-input-type (plist-get processing-info :image-input-type))
19409 (image-output-type (plist-get processing-info :image-output-type))
19410 (post-clean (or (plist-get processing-info :post-clean)
19411 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19412 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19413 (latex-header
19414 (or (plist-get processing-info :latex-header)
19415 (org-latex-make-preamble
19416 (org-export-get-environment (org-export-get-backend 'latex))
19417 org-format-latex-header
19418 'snippet)))
19419 (latex-compiler (plist-get processing-info :latex-compiler))
19420 (image-converter (plist-get processing-info :image-converter))
19421 (tmpdir temporary-file-directory)
19422 (texfilebase (make-temp-name
19423 (expand-file-name "orgtex" tmpdir)))
19424 (texfile (concat texfilebase ".tex"))
19425 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19426 '(1.0 . 1.0)))
19427 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19428 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19429 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19430 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19431 "Black"))
19432 (bg (or (plist-get options (if buffer :background :html-background))
19433 "Transparent"))
19434 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19435 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19436 (dolist (program programs)
19437 (org-check-external-command program error-message))
19438 (if use-xcolor
19439 (progn (if (eq fg 'default)
19440 (setq fg (org-latex-color :foreground))
19441 (setq fg (org-latex-color-format fg)))
19442 (if (eq bg 'default)
19443 (setq bg (org-latex-color :background))
19444 (setq bg (org-latex-color-format
19445 (if (string= bg "Transparent") "white" bg))))
19446 (with-temp-file texfile
19447 (insert latex-header)
19448 (insert "\n\\begin{document}\n"
19449 "\\definecolor{fg}{rgb}{" fg "}\n"
19450 "\\definecolor{bg}{rgb}{" bg "}\n"
19451 "\n\\pagecolor{bg}\n"
19452 "\n{\\color{fg}\n"
19453 string
19454 "\n}\n"
19455 "\n\\end{document}\n")))
19456 (if (eq fg 'default)
19457 (setq fg (org-dvipng-color :foreground))
19458 (unless (string= fg "Transparent")
19459 (setq fg (org-dvipng-color-format fg))))
19460 (if (eq bg 'default)
19461 (setq bg (org-dvipng-color :background))
19462 (unless (string= bg "Transparent")
19463 (setq bg (org-dvipng-color-format bg))))
19464 (with-temp-file texfile
19465 (insert latex-header)
19466 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19468 (let* ((err-msg (format "Please adjust '%s' part of \
19469 `org-preview-latex-process-alist'."
19470 processing-type))
19471 (image-input-file
19472 (org-compile-file
19473 texfile latex-compiler image-input-type err-msg log-buf))
19474 (image-output-file
19475 (org-compile-file
19476 image-input-file image-converter image-output-type err-msg log-buf
19477 `((?F . ,(shell-quote-argument fg))
19478 (?B . ,(shell-quote-argument bg))
19479 (?D . ,(shell-quote-argument (format "%s" dpi)))
19480 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19481 (copy-file image-output-file tofile 'replace)
19482 (dolist (e post-clean)
19483 (when (file-exists-p (concat texfilebase e))
19484 (delete-file (concat texfilebase e))))
19485 image-output-file)))
19487 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19488 "Fill a LaTeX header template TPL.
19489 In the template, the following place holders will be recognized:
19491 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19492 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19493 [PACKAGES] \\usepackage statements for PKG
19494 [NO-PACKAGES] do not include PKG
19495 [EXTRA] the string EXTRA
19496 [NO-EXTRA] do not include EXTRA
19498 For backward compatibility, if both the positive and the negative place
19499 holder is missing, the positive one (without the \"NO-\") will be
19500 assumed to be present at the end of the template.
19501 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19502 EXTRA is a string.
19503 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19504 (let (rpl (end ""))
19505 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19506 (setq rpl (if (or (match-end 1) (not def-pkg))
19507 "" (org-latex-packages-to-string def-pkg snippets-p t))
19508 tpl (replace-match rpl t t tpl))
19509 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19511 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19512 (setq rpl (if (or (match-end 1) (not pkg))
19513 "" (org-latex-packages-to-string pkg snippets-p t))
19514 tpl (replace-match rpl t t tpl))
19515 (when pkg (setq end
19516 (concat end "\n"
19517 (org-latex-packages-to-string pkg snippets-p)))))
19519 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19520 (setq rpl (if (or (match-end 1) (not extra))
19521 "" (concat extra "\n"))
19522 tpl (replace-match rpl t t tpl))
19523 (when (and extra (string-match "\\S-" extra))
19524 (setq end (concat end "\n" extra))))
19526 (if (string-match "\\S-" end)
19527 (concat tpl "\n" end)
19528 tpl)))
19530 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19531 "Turn an alist of packages into a string with the \\usepackage macros."
19532 (setq pkg (mapconcat (lambda(p)
19533 (cond
19534 ((stringp p) p)
19535 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19536 (format "%% Package %s omitted" (cadr p)))
19537 ((equal "" (car p))
19538 (format "\\usepackage{%s}" (cadr p)))
19540 (format "\\usepackage[%s]{%s}"
19541 (car p) (cadr p)))))
19543 "\n"))
19544 (if newline (concat pkg "\n") pkg))
19546 (defun org-dvipng-color (attr)
19547 "Return a RGB color specification for dvipng."
19548 (org-dvipng-color-format (face-attribute 'default attr nil)))
19550 (defun org-dvipng-color-format (color-name)
19551 "Convert COLOR-NAME to a RGB color value for dvipng."
19552 (apply #'format "rgb %s %s %s"
19553 (mapcar 'org-normalize-color
19554 (color-values color-name))))
19556 (defun org-latex-color (attr)
19557 "Return a RGB color for the LaTeX color package."
19558 (org-latex-color-format (face-attribute 'default attr nil)))
19560 (defun org-latex-color-format (color-name)
19561 "Convert COLOR-NAME to a RGB color value."
19562 (apply #'format "%s,%s,%s"
19563 (mapcar 'org-normalize-color
19564 (color-values color-name))))
19566 (defun org-normalize-color (value)
19567 "Return string to be used as color value for an RGB component."
19568 (format "%g" (/ value 65535.0)))
19572 ;; Image display
19574 (defvar-local org-inline-image-overlays nil)
19576 (defun org-toggle-inline-images (&optional include-linked)
19577 "Toggle the display of inline images.
19578 INCLUDE-LINKED is passed to `org-display-inline-images'."
19579 (interactive "P")
19580 (if org-inline-image-overlays
19581 (progn
19582 (org-remove-inline-images)
19583 (when (called-interactively-p 'interactive)
19584 (message "Inline image display turned off")))
19585 (org-display-inline-images include-linked)
19586 (when (called-interactively-p 'interactive)
19587 (message (if org-inline-image-overlays
19588 (format "%d images displayed inline"
19589 (length org-inline-image-overlays))
19590 "No images to display inline")))))
19592 (defun org-redisplay-inline-images ()
19593 "Refresh the display of inline images."
19594 (interactive)
19595 (if (not org-inline-image-overlays)
19596 (org-toggle-inline-images)
19597 (org-toggle-inline-images)
19598 (org-toggle-inline-images)))
19600 (defun org-display-inline-images (&optional include-linked refresh beg end)
19601 "Display inline images.
19603 An inline image is a link which follows either of these
19604 conventions:
19606 1. Its path is a file with an extension matching return value
19607 from `image-file-name-regexp' and it has no contents.
19609 2. Its description consists in a single link of the previous
19610 type.
19612 When optional argument INCLUDE-LINKED is non-nil, also links with
19613 a text description part will be inlined. This can be nice for
19614 a quick look at those images, but it does not reflect what
19615 exported files will look like.
19617 When optional argument REFRESH is non-nil, refresh existing
19618 images between BEG and END. This will create new image displays
19619 only if necessary. BEG and END default to the buffer
19620 boundaries."
19621 (interactive "P")
19622 (when (display-graphic-p)
19623 (unless refresh
19624 (org-remove-inline-images)
19625 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19626 (org-with-wide-buffer
19627 (goto-char (or beg (point-min)))
19628 (let ((case-fold-search t)
19629 (file-extension-re (image-file-name-regexp)))
19630 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19631 (let ((link (save-match-data (org-element-context))))
19632 ;; Check if we're at an inline image.
19633 (when (and (equal (org-element-property :type link) "file")
19634 (or include-linked
19635 (not (org-element-property :contents-begin link)))
19636 (let ((parent (org-element-property :parent link)))
19637 (or (not (eq (org-element-type parent) 'link))
19638 (not (cdr (org-element-contents parent)))))
19639 (string-match-p file-extension-re
19640 (org-element-property :path link)))
19641 (let ((file (expand-file-name
19642 (org-link-unescape
19643 (org-element-property :path link)))))
19644 (when (file-exists-p file)
19645 (let ((width
19646 ;; Apply `org-image-actual-width' specifications.
19647 (cond
19648 ((not (image-type-available-p 'imagemagick)) nil)
19649 ((eq org-image-actual-width t) nil)
19650 ((listp org-image-actual-width)
19652 ;; First try to find a width among
19653 ;; attributes associated to the paragraph
19654 ;; containing link.
19655 (let ((paragraph
19656 (let ((e link))
19657 (while (and (setq e (org-element-property
19658 :parent e))
19659 (not (eq (org-element-type e)
19660 'paragraph))))
19661 e)))
19662 (when paragraph
19663 (save-excursion
19664 (goto-char (org-element-property :begin paragraph))
19665 (when
19666 (re-search-forward
19667 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19668 (org-element-property
19669 :post-affiliated paragraph)
19671 (string-to-number (match-string 1))))))
19672 ;; Otherwise, fall-back to provided number.
19673 (car org-image-actual-width)))
19674 ((numberp org-image-actual-width)
19675 org-image-actual-width)))
19676 (old (get-char-property-and-overlay
19677 (org-element-property :begin link)
19678 'org-image-overlay)))
19679 (if (and (car-safe old) refresh)
19680 (image-refresh (overlay-get (cdr old) 'display))
19681 (let ((image (create-image file
19682 (and width 'imagemagick)
19684 :width width)))
19685 (when image
19686 (let* ((link
19687 ;; If inline image is the description
19688 ;; of another link, be sure to
19689 ;; consider the latter as the one to
19690 ;; apply the overlay on.
19691 (let ((parent
19692 (org-element-property :parent link)))
19693 (if (eq (org-element-type parent) 'link)
19694 parent
19695 link)))
19696 (ov (make-overlay
19697 (org-element-property :begin link)
19698 (progn
19699 (goto-char
19700 (org-element-property :end link))
19701 (skip-chars-backward " \t")
19702 (point)))))
19703 (overlay-put ov 'display image)
19704 (overlay-put ov 'face 'default)
19705 (overlay-put ov 'org-image-overlay t)
19706 (overlay-put
19707 ov 'modification-hooks
19708 (list 'org-display-inline-remove-overlay))
19709 (push ov org-inline-image-overlays)))))))))))))))
19711 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19712 "Remove inline-display overlay if a corresponding region is modified."
19713 (let ((inhibit-modification-hooks t))
19714 (when (and ov after)
19715 (delete ov org-inline-image-overlays)
19716 (delete-overlay ov))))
19718 (defun org-remove-inline-images ()
19719 "Remove inline display of images."
19720 (interactive)
19721 (mapc #'delete-overlay org-inline-image-overlays)
19722 (setq org-inline-image-overlays nil))
19724 ;;;; Key bindings
19726 ;; Outline functions from `outline-mode-prefix-map'
19727 ;; that can be remapped in Org:
19728 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19729 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19730 (define-key org-mode-map [remap outline-forward-same-level]
19731 'org-forward-heading-same-level)
19732 (define-key org-mode-map [remap outline-backward-same-level]
19733 'org-backward-heading-same-level)
19734 (define-key org-mode-map [remap outline-show-branches]
19735 'org-kill-note-or-show-branches)
19736 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19737 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19738 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19739 (define-key org-mode-map [remap outline-next-visible-heading]
19740 'org-next-visible-heading)
19741 (define-key org-mode-map [remap outline-previous-visible-heading]
19742 'org-previous-visible-heading)
19743 (define-key org-mode-map [remap show-children] 'org-show-children)
19745 ;; Outline functions from `outline-mode-prefix-map' that can not
19746 ;; be remapped in Org:
19748 ;; - the column "key binding" shows whether the Outline function is still
19749 ;; available in Org mode on the same key that it has been bound to in
19750 ;; Outline mode:
19751 ;; - "overridden": key used for a different functionality in Org mode
19752 ;; - else: key still bound to the same Outline function in Org mode
19754 ;; | Outline function | key binding | Org replacement |
19755 ;; |------------------------------------+-------------+--------------------------|
19756 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19757 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19758 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19759 ;; | `show-entry' | overridden | no replacement |
19760 ;; | `show-branches' | `C-c C-k' | still same function |
19761 ;; | `show-subtree' | overridden | visibility cycling |
19762 ;; | `show-all' | overridden | no replacement |
19763 ;; | `hide-subtree' | overridden | visibility cycling |
19764 ;; | `hide-body' | overridden | no replacement |
19765 ;; | `hide-entry' | overridden | visibility cycling |
19766 ;; | `hide-leaves' | overridden | no replacement |
19767 ;; | `hide-sublevels' | overridden | no replacement |
19768 ;; | `hide-other' | overridden | no replacement |
19770 ;; Make `C-c C-x' a prefix key
19771 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19773 ;; TAB key with modifiers
19774 (org-defkey org-mode-map "\C-i" 'org-cycle)
19775 (org-defkey org-mode-map [(tab)] 'org-cycle)
19776 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19777 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19778 ;; The following line is necessary under Suse GNU/Linux
19779 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19780 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19781 (define-key org-mode-map [backtab] 'org-shifttab)
19783 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19784 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19785 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19787 ;; Cursor keys with modifiers
19788 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19789 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19790 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19791 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19793 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19794 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19795 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19796 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19797 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19798 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19800 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19801 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19802 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19803 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19805 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19806 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19807 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19808 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19810 ;; Babel keys
19811 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19812 (dolist (pair org-babel-key-bindings)
19813 (define-key org-babel-map (car pair) (cdr pair)))
19815 ;;; Extra keys for tty access.
19816 ;; We only set them when really needed because otherwise the
19817 ;; menus don't show the simple keys
19819 (when (or org-use-extra-keys (not window-system))
19820 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19821 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19822 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19823 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19824 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19825 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19826 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19827 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19828 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19829 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19830 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19831 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19832 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19833 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19834 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19835 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19836 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19837 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19838 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19839 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19840 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19841 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19842 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19843 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19844 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19845 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19846 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19847 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19849 ;; All the other keys
19851 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19852 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19853 (if (boundp 'narrow-map)
19854 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19855 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19856 (if (boundp 'narrow-map)
19857 (org-defkey narrow-map "b" 'org-narrow-to-block)
19858 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19859 (if (boundp 'narrow-map)
19860 (org-defkey narrow-map "e" 'org-narrow-to-element)
19861 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19862 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19863 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19864 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19865 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19866 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19867 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19868 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19869 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19870 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19871 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19872 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19873 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19874 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19875 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19876 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19877 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19878 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19879 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19880 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19881 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19882 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19883 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19884 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19885 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19886 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19887 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19888 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19889 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19890 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19891 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19892 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19893 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19894 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19895 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19896 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19897 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19898 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19899 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19900 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19901 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19902 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19903 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19904 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19905 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19906 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19907 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19908 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19909 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19910 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19911 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19912 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19913 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19914 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19915 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19916 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19917 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19918 (org-defkey org-mode-map "\C-c^" 'org-sort)
19919 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19920 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19921 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19922 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19923 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19924 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19925 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19926 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19927 (org-defkey org-mode-map "\C-m" 'org-return)
19928 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19929 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19930 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19931 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19932 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19933 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19934 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19935 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19936 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19937 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19938 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19939 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19940 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19941 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19942 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19943 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19944 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19945 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19946 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19947 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19948 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19949 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19950 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19951 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19952 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19954 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19955 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19956 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19958 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19959 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19960 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19961 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19962 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19963 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19964 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19965 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19966 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19967 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19968 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19969 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19970 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19971 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19972 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19973 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19974 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19975 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19976 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19977 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19978 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19979 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19981 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19982 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19983 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19984 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19985 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19987 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19989 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19991 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19992 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19994 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19997 (defconst org-speed-commands-default
19999 ("Outline Navigation")
20000 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20001 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20002 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20003 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20004 ("F" . org-next-block)
20005 ("B" . org-previous-block)
20006 ("u" . (org-speed-move-safe 'outline-up-heading))
20007 ("j" . org-goto)
20008 ("g" . (org-refile t))
20009 ("Outline Visibility")
20010 ("c" . org-cycle)
20011 ("C" . org-shifttab)
20012 (" " . org-display-outline-path)
20013 ("s" . org-narrow-to-subtree)
20014 ("=" . org-columns)
20015 ("Outline Structure Editing")
20016 ("U" . org-metaup)
20017 ("D" . org-metadown)
20018 ("r" . org-metaright)
20019 ("l" . org-metaleft)
20020 ("R" . org-shiftmetaright)
20021 ("L" . org-shiftmetaleft)
20022 ("i" . (progn (forward-char 1) (call-interactively
20023 'org-insert-heading-respect-content)))
20024 ("^" . org-sort)
20025 ("w" . org-refile)
20026 ("a" . org-archive-subtree-default-with-confirmation)
20027 ("@" . org-mark-subtree)
20028 ("#" . org-toggle-comment)
20029 ("Clock Commands")
20030 ("I" . org-clock-in)
20031 ("O" . org-clock-out)
20032 ("Meta Data Editing")
20033 ("t" . org-todo)
20034 ("," . (org-priority))
20035 ("0" . (org-priority ?\ ))
20036 ("1" . (org-priority ?A))
20037 ("2" . (org-priority ?B))
20038 ("3" . (org-priority ?C))
20039 (":" . org-set-tags-command)
20040 ("e" . org-set-effort)
20041 ("E" . org-inc-effort)
20042 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20043 (org-entry-put (point) "APPT_WARNTIME" m)))
20044 ("Agenda Views etc")
20045 ("v" . org-agenda)
20046 ("/" . org-sparse-tree)
20047 ("Misc")
20048 ("o" . org-open-at-point)
20049 ("?" . org-speed-command-help)
20050 ("<" . (org-agenda-set-restriction-lock 'subtree))
20051 (">" . (org-agenda-remove-restriction-lock))
20053 "The default speed commands.")
20055 (defun org-print-speed-command (e)
20056 (if (> (length (car e)) 1)
20057 (progn
20058 (princ "\n")
20059 (princ (car e))
20060 (princ "\n")
20061 (princ (make-string (length (car e)) ?-))
20062 (princ "\n"))
20063 (princ (car e))
20064 (princ " ")
20065 (if (symbolp (cdr e))
20066 (princ (symbol-name (cdr e)))
20067 (prin1 (cdr e)))
20068 (princ "\n")))
20070 (defun org-speed-command-help ()
20071 "Show the available speed commands."
20072 (interactive)
20073 (if (not org-use-speed-commands)
20074 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20075 (with-output-to-temp-buffer "*Help*"
20076 (princ "User-defined Speed commands\n===========================\n")
20077 (mapc #'org-print-speed-command org-speed-commands-user)
20078 (princ "\n")
20079 (princ "Built-in Speed commands\n=======================\n")
20080 (mapc #'org-print-speed-command org-speed-commands-default))
20081 (with-current-buffer "*Help*"
20082 (setq truncate-lines t))))
20084 (defun org-speed-move-safe (cmd)
20085 "Execute CMD, but make sure that the cursor always ends up in a headline.
20086 If not, return to the original position and throw an error."
20087 (interactive)
20088 (let ((pos (point)))
20089 (call-interactively cmd)
20090 (unless (and (bolp) (org-at-heading-p))
20091 (goto-char pos)
20092 (error "Boundary reached while executing %s" cmd))))
20094 (defvar org-self-insert-command-undo-counter 0)
20096 (defvar org-table-auto-blank-field) ; defined in org-table.el
20097 (defvar org-speed-command nil)
20099 (defun org-speed-command-activate (keys)
20100 "Hook for activating single-letter speed commands.
20101 `org-speed-commands-default' specifies a minimal command set.
20102 Use `org-speed-commands-user' for further customization."
20103 (when (or (and (bolp) (looking-at org-outline-regexp))
20104 (and (functionp org-use-speed-commands)
20105 (funcall org-use-speed-commands)))
20106 (cdr (assoc keys (append org-speed-commands-user
20107 org-speed-commands-default)))))
20109 (defun org-babel-speed-command-activate (keys)
20110 "Hook for activating single-letter code block commands."
20111 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20112 (cdr (assoc keys org-babel-key-bindings))))
20114 (defcustom org-speed-command-hook
20115 '(org-speed-command-default-hook org-babel-speed-command-hook)
20116 "Hook for activating speed commands at strategic locations.
20117 Hook functions are called in sequence until a valid handler is
20118 found.
20120 Each hook takes a single argument, a user-pressed command key
20121 which is also a `self-insert-command' from the global map.
20123 Within the hook, examine the cursor position and the command key
20124 and return nil or a valid handler as appropriate. Handler could
20125 be one of an interactive command, a function, or a form.
20127 Set `org-use-speed-commands' to non-nil value to enable this
20128 hook. The default setting is `org-speed-command-activate'."
20129 :group 'org-structure
20130 :version "24.1"
20131 :type 'hook)
20133 (defun org-self-insert-command (N)
20134 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20135 If the cursor is in a table looking at whitespace, the whitespace is
20136 overwritten, and the table is not marked as requiring realignment."
20137 (interactive "p")
20138 (org-check-before-invisible-edit 'insert)
20139 (cond
20140 ((and org-use-speed-commands
20141 (let ((kv (this-command-keys-vector)))
20142 (setq org-speed-command
20143 (run-hook-with-args-until-success
20144 'org-speed-command-hook
20145 (make-string 1 (aref kv (1- (length kv))))))))
20146 (cond
20147 ((commandp org-speed-command)
20148 (setq this-command org-speed-command)
20149 (call-interactively org-speed-command))
20150 ((functionp org-speed-command)
20151 (funcall org-speed-command))
20152 ((and org-speed-command (listp org-speed-command))
20153 (eval org-speed-command))
20154 (t (let (org-use-speed-commands)
20155 (call-interactively 'org-self-insert-command)))))
20156 ((and
20157 (org-at-table-p)
20158 (progn
20159 ;; Check if we blank the field, and if that triggers align.
20160 (and (featurep 'org-table) org-table-auto-blank-field
20161 (memq last-command
20162 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20163 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20164 ;; Got extra space, this field does not determine
20165 ;; column width.
20166 (let (org-table-may-need-update) (org-table-blank-field))
20167 ;; No extra space, this field may determine column
20168 ;; width.
20169 (org-table-blank-field)))
20171 (eq N 1)
20172 (looking-at "[^|\n]* \\( \\)|"))
20173 ;; There is room for insertion without re-aligning the table.
20174 (delete-region (match-beginning 1) (match-end 1))
20175 (self-insert-command N))
20177 (setq org-table-may-need-update t)
20178 (self-insert-command N)
20179 (org-fix-tags-on-the-fly)
20180 (when org-self-insert-cluster-for-undo
20181 (if (not (eq last-command 'org-self-insert-command))
20182 (setq org-self-insert-command-undo-counter 1)
20183 (if (>= org-self-insert-command-undo-counter 20)
20184 (setq org-self-insert-command-undo-counter 1)
20185 (and (> org-self-insert-command-undo-counter 0)
20186 buffer-undo-list (listp buffer-undo-list)
20187 (not (cadr buffer-undo-list)) ; remove nil entry
20188 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20189 (setq org-self-insert-command-undo-counter
20190 (1+ org-self-insert-command-undo-counter))))))))
20192 (defun org-check-before-invisible-edit (kind)
20193 "Check is editing if kind KIND would be dangerous with invisible text around.
20194 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20195 ;; First, try to get out of here as quickly as possible, to reduce overhead
20196 (when (and org-catch-invisible-edits
20197 (or (not (boundp 'visible-mode)) (not visible-mode))
20198 (or (get-char-property (point) 'invisible)
20199 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20200 ;; OK, we need to take a closer look
20201 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20202 (invisible-before-point (unless (bobp) (get-char-property
20203 (1- (point)) 'invisible)))
20204 (border-and-ok-direction
20206 ;; Check if we are acting predictably before invisible text
20207 (and invisible-at-point (not invisible-before-point)
20208 (memq kind '(insert delete-backward)))
20209 ;; Check if we are acting predictably after invisible text
20210 ;; This works not well, and I have turned it off. It seems
20211 ;; better to always show and stop after invisible text.
20212 ;; (and (not invisible-at-point) invisible-before-point
20213 ;; (memq kind '(insert delete)))
20215 (when (or (memq invisible-at-point '(outline org-hide-block t))
20216 (memq invisible-before-point '(outline org-hide-block t)))
20217 (when (eq org-catch-invisible-edits 'error)
20218 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20219 (if (and org-custom-properties-overlays
20220 (y-or-n-p "Display invisible properties in this buffer? "))
20221 (org-toggle-custom-properties-visibility)
20222 ;; Make the area visible
20223 (save-excursion
20224 (when invisible-before-point
20225 (goto-char (previous-single-char-property-change
20226 (point) 'invisible)))
20227 (outline-show-subtree))
20228 (cond
20229 ((eq org-catch-invisible-edits 'show)
20230 ;; That's it, we do the edit after showing
20231 (message
20232 "Unfolding invisible region around point before editing")
20233 (sit-for 1))
20234 ((and (eq org-catch-invisible-edits 'smart)
20235 border-and-ok-direction)
20236 (message "Unfolding invisible region around point before editing"))
20238 ;; Don't do the edit, make the user repeat it in full visibility
20239 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20241 (defun org-fix-tags-on-the-fly ()
20242 "Align tags in headline at point.
20243 Unlike to `org-set-tags', it ignores region and sorting."
20244 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
20245 (org-at-heading-p))
20246 (let ((org-ignore-region t)
20247 (org-tags-sort-function nil))
20248 (org-set-tags nil t))))
20250 (defun org-delete-backward-char (N)
20251 "Like `delete-backward-char', insert whitespace at field end in tables.
20252 When deleting backwards, in tables this function will insert whitespace in
20253 front of the next \"|\" separator, to keep the table aligned. The table will
20254 still be marked for re-alignment if the field did fill the entire column,
20255 because, in this case the deletion might narrow the column."
20256 (interactive "p")
20257 (save-match-data
20258 (org-check-before-invisible-edit 'delete-backward)
20259 (if (and (org-at-table-p)
20260 (eq N 1)
20261 (string-match "|" (buffer-substring (point-at-bol) (point)))
20262 (looking-at ".*?|"))
20263 (let ((pos (point))
20264 (noalign (looking-at "[^|\n\r]* |"))
20265 (c org-table-may-need-update))
20266 (backward-delete-char N)
20267 (unless overwrite-mode
20268 (skip-chars-forward "^|")
20269 (insert " ")
20270 (goto-char (1- pos)))
20271 ;; noalign: if there were two spaces at the end, this field
20272 ;; does not determine the width of the column.
20273 (when noalign (setq org-table-may-need-update c)))
20274 (backward-delete-char N)
20275 (org-fix-tags-on-the-fly))))
20277 (defun org-delete-char (N)
20278 "Like `delete-char', but insert whitespace at field end in tables.
20279 When deleting characters, in tables this function will insert whitespace in
20280 front of the next \"|\" separator, to keep the table aligned. The table will
20281 still be marked for re-alignment if the field did fill the entire column,
20282 because, in this case the deletion might narrow the column."
20283 (interactive "p")
20284 (save-match-data
20285 (org-check-before-invisible-edit 'delete)
20286 (if (and (org-at-table-p)
20287 (not (bolp))
20288 (not (= (char-after) ?|))
20289 (eq N 1))
20290 (if (looking-at ".*?|")
20291 (let ((pos (point))
20292 (noalign (looking-at "[^|\n\r]* |"))
20293 (c org-table-may-need-update))
20294 (replace-match
20295 (concat (substring (match-string 0) 1 -1) " |") nil t)
20296 (goto-char pos)
20297 ;; noalign: if there were two spaces at the end, this field
20298 ;; does not determine the width of the column.
20299 (when noalign (setq org-table-may-need-update c)))
20300 (delete-char N))
20301 (delete-char N)
20302 (org-fix-tags-on-the-fly))))
20304 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20305 (put 'org-self-insert-command 'delete-selection
20306 (lambda ()
20307 (not (run-hook-with-args-until-success
20308 'self-insert-uses-region-functions))))
20309 (put 'orgtbl-self-insert-command 'delete-selection
20310 (lambda ()
20311 (not (run-hook-with-args-until-success
20312 'self-insert-uses-region-functions))))
20313 (put 'org-delete-char 'delete-selection 'supersede)
20314 (put 'org-delete-backward-char 'delete-selection 'supersede)
20315 (put 'org-yank 'delete-selection 'yank)
20317 ;; Make `flyspell-mode' delay after some commands
20318 (put 'org-self-insert-command 'flyspell-delayed t)
20319 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20320 (put 'org-delete-char 'flyspell-delayed t)
20321 (put 'org-delete-backward-char 'flyspell-delayed t)
20323 ;; Make pabbrev-mode expand after Org mode commands
20324 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20325 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20327 (defun org-remap (map &rest commands)
20328 "In MAP, remap the functions given in COMMANDS.
20329 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20330 (let (new old)
20331 (while commands
20332 (setq old (pop commands) new (pop commands))
20333 (org-defkey map (vector 'remap old) new))))
20335 (defun org-transpose-words ()
20336 "Transpose words for Org.
20337 This uses the `org-mode-transpose-word-syntax-table' syntax
20338 table, which interprets characters in `org-emphasis-alist' as
20339 word constituents."
20340 (interactive)
20341 (with-syntax-table org-mode-transpose-word-syntax-table
20342 (call-interactively 'transpose-words)))
20343 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20345 (when (eq org-enable-table-editor 'optimized)
20346 ;; If the user wants maximum table support, we need to hijack
20347 ;; some standard editing functions
20348 (org-remap org-mode-map
20349 'self-insert-command 'org-self-insert-command
20350 'delete-char 'org-delete-char
20351 'delete-backward-char 'org-delete-backward-char)
20352 (org-defkey org-mode-map "|" 'org-force-self-insert))
20354 (defvar org-ctrl-c-ctrl-c-hook nil
20355 "Hook for functions attaching themselves to `C-c C-c'.
20357 This can be used to add additional functionality to the C-c C-c
20358 key which executes context-dependent commands. This hook is run
20359 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20360 run after the last test.
20362 Each function will be called with no arguments. The function
20363 must check if the context is appropriate for it to act. If yes,
20364 it should do its thing and then return a non-nil value. If the
20365 context is wrong, just do nothing and return nil.")
20367 (defvar org-ctrl-c-ctrl-c-final-hook nil
20368 "Hook for functions attaching themselves to `C-c C-c'.
20370 This can be used to add additional functionality to the C-c C-c
20371 key which executes context-dependent commands. This hook is run
20372 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20373 before the first test.
20375 Each function will be called with no arguments. The function
20376 must check if the context is appropriate for it to act. If yes,
20377 it should do its thing and then return a non-nil value. If the
20378 context is wrong, just do nothing and return nil.")
20380 (defvar org-tab-first-hook nil
20381 "Hook for functions to attach themselves to TAB.
20382 See `org-ctrl-c-ctrl-c-hook' for more information.
20383 This hook runs as the first action when TAB is pressed, even before
20384 `org-cycle' messes around with the `outline-regexp' to cater for
20385 inline tasks and plain list item folding.
20386 If any function in this hook returns t, any other actions that
20387 would have been caused by TAB (such as table field motion or visibility
20388 cycling) will not occur.")
20390 (defvar org-tab-after-check-for-table-hook nil
20391 "Hook for functions to attach themselves to TAB.
20392 See `org-ctrl-c-ctrl-c-hook' for more information.
20393 This hook runs after it has been established that the cursor is not in a
20394 table, but before checking if the cursor is in a headline or if global cycling
20395 should be done.
20396 If any function in this hook returns t, not other actions like visibility
20397 cycling will be done.")
20399 (defvar org-tab-after-check-for-cycling-hook nil
20400 "Hook for functions to attach themselves to TAB.
20401 See `org-ctrl-c-ctrl-c-hook' for more information.
20402 This hook runs after it has been established that not table field motion and
20403 not visibility should be done because of current context. This is probably
20404 the place where a package like yasnippets can hook in.")
20406 (defvar org-tab-before-tab-emulation-hook nil
20407 "Hook for functions to attach themselves to TAB.
20408 See `org-ctrl-c-ctrl-c-hook' for more information.
20409 This hook runs after every other options for TAB have been exhausted, but
20410 before indentation and \t insertion takes place.")
20412 (defvar org-metaleft-hook nil
20413 "Hook for functions attaching themselves to `M-left'.
20414 See `org-ctrl-c-ctrl-c-hook' for more information.")
20415 (defvar org-metaright-hook nil
20416 "Hook for functions attaching themselves to `M-right'.
20417 See `org-ctrl-c-ctrl-c-hook' for more information.")
20418 (defvar org-metaup-hook nil
20419 "Hook for functions attaching themselves to `M-up'.
20420 See `org-ctrl-c-ctrl-c-hook' for more information.")
20421 (defvar org-metadown-hook nil
20422 "Hook for functions attaching themselves to `M-down'.
20423 See `org-ctrl-c-ctrl-c-hook' for more information.")
20424 (defvar org-shiftmetaleft-hook nil
20425 "Hook for functions attaching themselves to `M-S-left'.
20426 See `org-ctrl-c-ctrl-c-hook' for more information.")
20427 (defvar org-shiftmetaright-hook nil
20428 "Hook for functions attaching themselves to `M-S-right'.
20429 See `org-ctrl-c-ctrl-c-hook' for more information.")
20430 (defvar org-shiftmetaup-hook nil
20431 "Hook for functions attaching themselves to `M-S-up'.
20432 See `org-ctrl-c-ctrl-c-hook' for more information.")
20433 (defvar org-shiftmetadown-hook nil
20434 "Hook for functions attaching themselves to `M-S-down'.
20435 See `org-ctrl-c-ctrl-c-hook' for more information.")
20436 (defvar org-metareturn-hook nil
20437 "Hook for functions attaching themselves to `M-RET'.
20438 See `org-ctrl-c-ctrl-c-hook' for more information.")
20439 (defvar org-shiftup-hook nil
20440 "Hook for functions attaching themselves to `S-up'.
20441 See `org-ctrl-c-ctrl-c-hook' for more information.")
20442 (defvar org-shiftup-final-hook nil
20443 "Hook for functions attaching themselves to `S-up'.
20444 This one runs after all other options except shift-select have been excluded.
20445 See `org-ctrl-c-ctrl-c-hook' for more information.")
20446 (defvar org-shiftdown-hook nil
20447 "Hook for functions attaching themselves to `S-down'.
20448 See `org-ctrl-c-ctrl-c-hook' for more information.")
20449 (defvar org-shiftdown-final-hook nil
20450 "Hook for functions attaching themselves to `S-down'.
20451 This one runs after all other options except shift-select have been excluded.
20452 See `org-ctrl-c-ctrl-c-hook' for more information.")
20453 (defvar org-shiftleft-hook nil
20454 "Hook for functions attaching themselves to `S-left'.
20455 See `org-ctrl-c-ctrl-c-hook' for more information.")
20456 (defvar org-shiftleft-final-hook nil
20457 "Hook for functions attaching themselves to `S-left'.
20458 This one runs after all other options except shift-select have been excluded.
20459 See `org-ctrl-c-ctrl-c-hook' for more information.")
20460 (defvar org-shiftright-hook nil
20461 "Hook for functions attaching themselves to `S-right'.
20462 See `org-ctrl-c-ctrl-c-hook' for more information.")
20463 (defvar org-shiftright-final-hook nil
20464 "Hook for functions attaching themselves to `S-right'.
20465 This one runs after all other options except shift-select have been excluded.
20466 See `org-ctrl-c-ctrl-c-hook' for more information.")
20468 (defun org-modifier-cursor-error ()
20469 "Throw an error, a modified cursor command was applied in wrong context."
20470 (user-error "This command is active in special context like tables, headlines or items"))
20472 (defun org-shiftselect-error ()
20473 "Throw an error because Shift-Cursor command was applied in wrong context."
20474 (if (and (boundp 'shift-select-mode) shift-select-mode)
20475 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20476 (user-error "This command works only in special context like headlines or timestamps")))
20478 (defun org-call-for-shift-select (cmd)
20479 (let ((this-command-keys-shift-translated t))
20480 (call-interactively cmd)))
20482 (defun org-shifttab (&optional arg)
20483 "Global visibility cycling or move to previous table field.
20484 Call `org-table-previous-field' within a table.
20485 When ARG is nil, cycle globally through visibility states.
20486 When ARG is a numeric prefix, show contents of this level."
20487 (interactive "P")
20488 (cond
20489 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20490 ((integerp arg)
20491 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20492 (message "Content view to level: %d" arg)
20493 (org-content (prefix-numeric-value arg2))
20494 (org-cycle-show-empty-lines t)
20495 (setq org-cycle-global-status 'overview)))
20496 (t (call-interactively 'org-global-cycle))))
20498 (defun org-shiftmetaleft ()
20499 "Promote subtree or delete table column.
20500 Calls `org-promote-subtree', `org-outdent-item-tree', or
20501 `org-table-delete-column', depending on context. See the
20502 individual commands for more information."
20503 (interactive)
20504 (cond
20505 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20506 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20507 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20508 ((if (not (org-region-active-p)) (org-at-item-p)
20509 (save-excursion (goto-char (region-beginning))
20510 (org-at-item-p)))
20511 (call-interactively 'org-outdent-item-tree))
20512 (t (org-modifier-cursor-error))))
20514 (defun org-shiftmetaright ()
20515 "Demote subtree or insert table column.
20516 Calls `org-demote-subtree', `org-indent-item-tree', or
20517 `org-table-insert-column', depending on context. See the
20518 individual commands for more information."
20519 (interactive)
20520 (cond
20521 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20522 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20523 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20524 ((if (not (org-region-active-p)) (org-at-item-p)
20525 (save-excursion (goto-char (region-beginning))
20526 (org-at-item-p)))
20527 (call-interactively 'org-indent-item-tree))
20528 (t (org-modifier-cursor-error))))
20530 (defun org-shiftmetaup (&optional _arg)
20531 "Drag the line at point up.
20532 In a table, kill the current row.
20533 On a clock timestamp, update the value of the timestamp like `S-<up>'
20534 but also adjust the previous clocked item in the clock history.
20535 Everywhere else, drag the line at point up."
20536 (interactive "P")
20537 (cond
20538 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20539 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20540 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20541 (call-interactively 'org-timestamp-up)))
20542 (t (call-interactively 'org-drag-line-backward))))
20544 (defun org-shiftmetadown (&optional _arg)
20545 "Drag the line at point down.
20546 In a table, insert an empty row at the current line.
20547 On a clock timestamp, update the value of the timestamp like `S-<down>'
20548 but also adjust the previous clocked item in the clock history.
20549 Everywhere else, drag the line at point down."
20550 (interactive "P")
20551 (cond
20552 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20553 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20554 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20555 (call-interactively 'org-timestamp-down)))
20556 (t (call-interactively 'org-drag-line-forward))))
20558 (defsubst org-hidden-tree-error ()
20559 (user-error
20560 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20562 (defun org-metaleft (&optional _arg)
20563 "Promote heading, list item at point or move table column left.
20565 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20566 depending on context. With no specific context, calls the Emacs
20567 default `backward-word'. See the individual commands for more
20568 information.
20570 This function runs the hook `org-metaleft-hook' as a first step,
20571 and returns at first non-nil value."
20572 (interactive "P")
20573 (cond
20574 ((run-hook-with-args-until-success 'org-metaleft-hook))
20575 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20576 ((org-with-limited-levels
20577 (or (org-at-heading-p)
20578 (and (org-region-active-p)
20579 (save-excursion
20580 (goto-char (region-beginning))
20581 (org-at-heading-p)))))
20582 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20583 (call-interactively 'org-do-promote))
20584 ;; At an inline task.
20585 ((org-at-heading-p)
20586 (call-interactively 'org-inlinetask-promote))
20587 ((or (org-at-item-p)
20588 (and (org-region-active-p)
20589 (save-excursion
20590 (goto-char (region-beginning))
20591 (org-at-item-p))))
20592 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20593 (call-interactively 'org-outdent-item))
20594 (t (call-interactively 'backward-word))))
20596 (defun org-metaright (&optional _arg)
20597 "Demote heading, list item at point or move table column right.
20599 In front of a drawer or a block keyword, indent it correctly.
20601 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20602 `org-indent-drawer' or `org-indent-block' depending on context.
20603 With no specific context, calls the Emacs default `forward-word'.
20604 See the individual commands for more information.
20606 This function runs the hook `org-metaright-hook' as a first step,
20607 and returns at first non-nil value."
20608 (interactive "P")
20609 (cond
20610 ((run-hook-with-args-until-success 'org-metaright-hook))
20611 ((org-at-table-p) (call-interactively 'org-table-move-column))
20612 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20613 ((org-at-block-p) (call-interactively 'org-indent-block))
20614 ((org-with-limited-levels
20615 (or (org-at-heading-p)
20616 (and (org-region-active-p)
20617 (save-excursion
20618 (goto-char (region-beginning))
20619 (org-at-heading-p)))))
20620 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20621 (call-interactively 'org-do-demote))
20622 ;; At an inline task.
20623 ((org-at-heading-p)
20624 (call-interactively 'org-inlinetask-demote))
20625 ((or (org-at-item-p)
20626 (and (org-region-active-p)
20627 (save-excursion
20628 (goto-char (region-beginning))
20629 (org-at-item-p))))
20630 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20631 (call-interactively 'org-indent-item))
20632 (t (call-interactively 'forward-word))))
20634 (defun org-check-for-hidden (what)
20635 "Check if there are hidden headlines/items in the current visual line.
20636 WHAT can be either `headlines' or `items'. If the current line is
20637 an outline or item heading and it has a folded subtree below it,
20638 this function returns t, nil otherwise."
20639 (let ((re (cond
20640 ((eq what 'headlines) org-outline-regexp-bol)
20641 ((eq what 'items) (org-item-beginning-re))
20642 (t (error "This should not happen"))))
20643 beg end)
20644 (save-excursion
20645 (catch 'exit
20646 (unless (org-region-active-p)
20647 (setq beg (point-at-bol))
20648 (beginning-of-line 2)
20649 (while (and (not (eobp)) ;; this is like `next-line'
20650 (get-char-property (1- (point)) 'invisible))
20651 (beginning-of-line 2))
20652 (setq end (point))
20653 (goto-char beg)
20654 (goto-char (point-at-eol))
20655 (setq end (max end (point)))
20656 (while (re-search-forward re end t)
20657 (when (get-char-property (match-beginning 0) 'invisible)
20658 (throw 'exit t))))
20659 nil))))
20661 (defun org-metaup (&optional _arg)
20662 "Move subtree up or move table row up.
20663 Calls `org-move-subtree-up' or `org-table-move-row' or
20664 `org-move-item-up', depending on context. See the individual commands
20665 for more information."
20666 (interactive "P")
20667 (cond
20668 ((run-hook-with-args-until-success 'org-metaup-hook))
20669 ((org-region-active-p)
20670 (let* ((a (min (region-beginning) (region-end)))
20671 (b (1- (max (region-beginning) (region-end))))
20672 (c (save-excursion (goto-char a)
20673 (move-beginning-of-line 0)))
20674 (d (save-excursion (goto-char a)
20675 (move-end-of-line 0) (point))))
20676 (transpose-regions a b c d)
20677 (goto-char c)))
20678 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20679 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20680 ((org-at-item-p) (call-interactively 'org-move-item-up))
20681 (t (org-drag-element-backward))))
20683 (defun org-metadown (&optional _arg)
20684 "Move subtree down or move table row down.
20685 Calls `org-move-subtree-down' or `org-table-move-row' or
20686 `org-move-item-down', depending on context. See the individual
20687 commands for more information."
20688 (interactive "P")
20689 (cond
20690 ((run-hook-with-args-until-success 'org-metadown-hook))
20691 ((org-region-active-p)
20692 (let* ((a (min (region-beginning) (region-end)))
20693 (b (max (region-beginning) (region-end)))
20694 (c (save-excursion (goto-char b)
20695 (move-beginning-of-line 1)))
20696 (d (save-excursion (goto-char b)
20697 (move-end-of-line 1) (1+ (point)))))
20698 (transpose-regions a b c d)
20699 (goto-char d)))
20700 ((org-at-table-p) (call-interactively 'org-table-move-row))
20701 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20702 ((org-at-item-p) (call-interactively 'org-move-item-down))
20703 (t (org-drag-element-forward))))
20705 (defun org-shiftup (&optional arg)
20706 "Increase item in timestamp or increase priority of current headline.
20707 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20708 depending on context. See the individual commands for more information."
20709 (interactive "P")
20710 (cond
20711 ((run-hook-with-args-until-success 'org-shiftup-hook))
20712 ((and org-support-shift-select (org-region-active-p))
20713 (org-call-for-shift-select 'previous-line))
20714 ((org-at-timestamp-p t)
20715 (call-interactively (if org-edit-timestamp-down-means-later
20716 'org-timestamp-down 'org-timestamp-up)))
20717 ((and (not (eq org-support-shift-select 'always))
20718 org-enable-priority-commands
20719 (org-at-heading-p))
20720 (call-interactively 'org-priority-up))
20721 ((and (not org-support-shift-select) (org-at-item-p))
20722 (call-interactively 'org-previous-item))
20723 ((org-clocktable-try-shift 'up arg))
20724 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20725 (org-support-shift-select
20726 (org-call-for-shift-select 'previous-line))
20727 (t (org-shiftselect-error))))
20729 (defun org-shiftdown (&optional arg)
20730 "Decrease item in timestamp or decrease priority of current headline.
20731 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20732 depending on context. See the individual commands for more information."
20733 (interactive "P")
20734 (cond
20735 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20736 ((and org-support-shift-select (org-region-active-p))
20737 (org-call-for-shift-select 'next-line))
20738 ((org-at-timestamp-p t)
20739 (call-interactively (if org-edit-timestamp-down-means-later
20740 'org-timestamp-up 'org-timestamp-down)))
20741 ((and (not (eq org-support-shift-select 'always))
20742 org-enable-priority-commands
20743 (org-at-heading-p))
20744 (call-interactively 'org-priority-down))
20745 ((and (not org-support-shift-select) (org-at-item-p))
20746 (call-interactively 'org-next-item))
20747 ((org-clocktable-try-shift 'down arg))
20748 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20749 (org-support-shift-select
20750 (org-call-for-shift-select 'next-line))
20751 (t (org-shiftselect-error))))
20753 (defun org-shiftright (&optional arg)
20754 "Cycle the thing at point or in the current line, depending on context.
20755 Depending on context, this does one of the following:
20757 - switch a timestamp at point one day into the future
20758 - on a headline, switch to the next TODO keyword.
20759 - on an item, switch entire list to the next bullet type
20760 - on a property line, switch to the next allowed value
20761 - on a clocktable definition line, move time block into the future"
20762 (interactive "P")
20763 (cond
20764 ((run-hook-with-args-until-success 'org-shiftright-hook))
20765 ((and org-support-shift-select (org-region-active-p))
20766 (org-call-for-shift-select 'forward-char))
20767 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20768 ((and (not (eq org-support-shift-select 'always))
20769 (org-at-heading-p))
20770 (let ((org-inhibit-logging
20771 (not org-treat-S-cursor-todo-selection-as-state-change))
20772 (org-inhibit-blocking
20773 (not org-treat-S-cursor-todo-selection-as-state-change)))
20774 (org-call-with-arg 'org-todo 'right)))
20775 ((or (and org-support-shift-select
20776 (not (eq org-support-shift-select 'always))
20777 (org-at-item-bullet-p))
20778 (and (not org-support-shift-select) (org-at-item-p)))
20779 (org-call-with-arg 'org-cycle-list-bullet nil))
20780 ((and (not (eq org-support-shift-select 'always))
20781 (org-at-property-p))
20782 (call-interactively 'org-property-next-allowed-value))
20783 ((org-clocktable-try-shift 'right arg))
20784 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20785 (org-support-shift-select
20786 (org-call-for-shift-select 'forward-char))
20787 (t (org-shiftselect-error))))
20789 (defun org-shiftleft (&optional arg)
20790 "Cycle the thing at point or in the current line, depending on context.
20791 Depending on context, this does one of the following:
20793 - switch a timestamp at point one day into the past
20794 - on a headline, switch to the previous TODO keyword.
20795 - on an item, switch entire list to the previous bullet type
20796 - on a property line, switch to the previous allowed value
20797 - on a clocktable definition line, move time block into the past"
20798 (interactive "P")
20799 (cond
20800 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20801 ((and org-support-shift-select (org-region-active-p))
20802 (org-call-for-shift-select 'backward-char))
20803 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20804 ((and (not (eq org-support-shift-select 'always))
20805 (org-at-heading-p))
20806 (let ((org-inhibit-logging
20807 (not org-treat-S-cursor-todo-selection-as-state-change))
20808 (org-inhibit-blocking
20809 (not org-treat-S-cursor-todo-selection-as-state-change)))
20810 (org-call-with-arg 'org-todo 'left)))
20811 ((or (and org-support-shift-select
20812 (not (eq org-support-shift-select 'always))
20813 (org-at-item-bullet-p))
20814 (and (not org-support-shift-select) (org-at-item-p)))
20815 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20816 ((and (not (eq org-support-shift-select 'always))
20817 (org-at-property-p))
20818 (call-interactively 'org-property-previous-allowed-value))
20819 ((org-clocktable-try-shift 'left arg))
20820 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20821 (org-support-shift-select
20822 (org-call-for-shift-select 'backward-char))
20823 (t (org-shiftselect-error))))
20825 (defun org-shiftcontrolright ()
20826 "Switch to next TODO set."
20827 (interactive)
20828 (cond
20829 ((and org-support-shift-select (org-region-active-p))
20830 (org-call-for-shift-select 'forward-word))
20831 ((and (not (eq org-support-shift-select 'always))
20832 (org-at-heading-p))
20833 (org-call-with-arg 'org-todo 'nextset))
20834 (org-support-shift-select
20835 (org-call-for-shift-select 'forward-word))
20836 (t (org-shiftselect-error))))
20838 (defun org-shiftcontrolleft ()
20839 "Switch to previous TODO set."
20840 (interactive)
20841 (cond
20842 ((and org-support-shift-select (org-region-active-p))
20843 (org-call-for-shift-select 'backward-word))
20844 ((and (not (eq org-support-shift-select 'always))
20845 (org-at-heading-p))
20846 (org-call-with-arg 'org-todo 'previousset))
20847 (org-support-shift-select
20848 (org-call-for-shift-select 'backward-word))
20849 (t (org-shiftselect-error))))
20851 (defun org-shiftcontrolup (&optional n)
20852 "Change timestamps synchronously up in CLOCK log lines.
20853 Optional argument N tells to change by that many units."
20854 (interactive "P")
20855 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20856 (let (org-support-shift-select)
20857 (org-clock-timestamps-up n))
20858 (user-error "Not at a clock log")))
20860 (defun org-shiftcontroldown (&optional n)
20861 "Change timestamps synchronously down in CLOCK log lines.
20862 Optional argument N tells to change by that many units."
20863 (interactive "P")
20864 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20865 (let (org-support-shift-select)
20866 (org-clock-timestamps-down n))
20867 (user-error "Not at a clock log")))
20869 (defun org-increase-number-at-point (&optional inc)
20870 "Increment the number at point.
20871 With an optional prefix numeric argument INC, increment using
20872 this numeric value."
20873 (interactive "p")
20874 (if (not (number-at-point))
20875 (user-error "Not on a number")
20876 (unless inc (setq inc 1))
20877 (let ((pos (point))
20878 (beg (skip-chars-backward "-+^/*0-9eE."))
20879 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20880 (setq nap (buffer-substring-no-properties
20881 (+ pos beg) (+ pos beg end)))
20882 (delete-region (+ pos beg) (+ pos beg end))
20883 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20884 (when (org-at-table-p)
20885 (org-table-align)
20886 (org-table-end-of-field 1))))
20888 (defun org-decrease-number-at-point (&optional inc)
20889 "Decrement the number at point.
20890 With an optional prefix numeric argument INC, decrement using
20891 this numeric value."
20892 (interactive "p")
20893 (org-increase-number-at-point (- (or inc 1))))
20895 (defun org-ctrl-c-ret ()
20896 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20897 (interactive)
20898 (cond
20899 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20900 (t (call-interactively 'org-insert-heading))))
20902 (defun org-find-visible ()
20903 (let ((s (point)))
20904 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20905 (get-char-property s 'invisible)))
20907 (defun org-find-invisible ()
20908 (let ((s (point)))
20909 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20910 (not (get-char-property s 'invisible))))
20913 (defun org-copy-visible (beg end)
20914 "Copy the visible parts of the region."
20915 (interactive "r")
20916 (let (snippets s)
20917 (save-excursion
20918 (save-restriction
20919 (narrow-to-region beg end)
20920 (setq s (goto-char (point-min)))
20921 (while (not (= (point) (point-max)))
20922 (goto-char (org-find-invisible))
20923 (push (buffer-substring s (point)) snippets)
20924 (setq s (goto-char (org-find-visible))))))
20925 (kill-new (apply 'concat (nreverse snippets)))))
20927 (defun org-copy-special ()
20928 "Copy region in table or copy current subtree.
20929 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20930 context. See the individual commands for more information."
20931 (interactive)
20932 (call-interactively
20933 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20935 (defun org-cut-special ()
20936 "Cut region in table or cut current subtree.
20937 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20938 context. See the individual commands for more information."
20939 (interactive)
20940 (call-interactively
20941 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20943 (defun org-paste-special (arg)
20944 "Paste rectangular region into table, or past subtree relative to level.
20945 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20946 See the individual commands for more information."
20947 (interactive "P")
20948 (if (org-at-table-p)
20949 (org-table-paste-rectangle)
20950 (org-paste-subtree arg)))
20952 (defun org-edit-special (&optional arg)
20953 "Call a special editor for the element at point.
20954 When at a table, call the formula editor with `org-table-edit-formulas'.
20955 When in a source code block, call `org-edit-src-code'.
20956 When in a fixed-width region, call `org-edit-fixed-width-region'.
20957 When in an export block, call `org-edit-export-block'.
20958 When at an #+INCLUDE keyword, visit the included file.
20959 When at a footnote reference, call `org-edit-footnote-reference'
20960 On a link, call `ffap' to visit the link at point.
20961 Otherwise, return a user error."
20962 (interactive "P")
20963 (let ((element (org-element-at-point)))
20964 (barf-if-buffer-read-only)
20965 (pcase (org-element-type element)
20966 (`src-block
20967 (if (not arg) (org-edit-src-code)
20968 (let* ((info (org-babel-get-src-block-info))
20969 (lang (nth 0 info))
20970 (params (nth 2 info))
20971 (session (cdr (assq :session params))))
20972 (if (not session) (org-edit-src-code)
20973 ;; At a src-block with a session and function called with
20974 ;; an ARG: switch to the buffer related to the inferior
20975 ;; process.
20976 (switch-to-buffer
20977 (funcall (intern (concat "org-babel-prep-session:" lang))
20978 session params))))))
20979 (`keyword
20980 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20981 (org-open-link-from-string
20982 (format "[[%s]]"
20983 (expand-file-name
20984 (let ((value (org-element-property :value element)))
20985 (cond ((not (org-string-nw-p value))
20986 (user-error "No file to edit"))
20987 ((string-match "\\`\"\\(.*?\\)\"" value)
20988 (match-string 1 value))
20989 ((string-match "\\`[^ \t\"]\\S-*" value)
20990 (match-string 0 value))
20991 (t (user-error "No valid file specified")))))))
20992 (user-error "No special environment to edit here")))
20993 (`table
20994 (if (eq (org-element-property :type element) 'table.el)
20995 (org-edit-table.el)
20996 (call-interactively 'org-table-edit-formulas)))
20997 ;; Only Org tables contain `table-row' type elements.
20998 (`table-row (call-interactively 'org-table-edit-formulas))
20999 (`example-block (org-edit-src-code))
21000 (`export-block (org-edit-export-block))
21001 (`fixed-width (org-edit-fixed-width-region))
21003 ;; No notable element at point. Though, we may be at a link or
21004 ;; a footnote reference, which are objects. Thus, scan deeper.
21005 (let ((context (org-element-context element)))
21006 (pcase (org-element-type context)
21007 (`footnote-reference (org-edit-footnote-reference))
21008 (`inline-src-block (org-edit-inline-src-code))
21009 (`link (call-interactively #'ffap))
21010 (_ (user-error "No special environment to edit here"))))))))
21012 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21013 (defun org-ctrl-c-ctrl-c (&optional arg)
21014 "Set tags in headline, or update according to changed information at point.
21016 This command does many different things, depending on context:
21018 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21019 this is what we do.
21021 - If the cursor is on a statistics cookie, update it.
21023 - If the cursor is in a headline, prompt for tags and insert them
21024 into the current line, aligned to `org-tags-column'. When called
21025 with prefix arg, realign all tags in the current buffer.
21027 - If the cursor is in one of the special #+KEYWORD lines, this
21028 triggers scanning the buffer for these lines and updating the
21029 information.
21031 - If the cursor is inside a table, realign the table. This command
21032 works even if the automatic table editor has been turned off.
21034 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21035 the entire table.
21037 - If the cursor is at a footnote reference or definition, jump to
21038 the corresponding definition or references, respectively.
21040 - If the cursor is a the beginning of a dynamic block, update it.
21042 - If the current buffer is a capture buffer, close note and file it.
21044 - If the cursor is on a <<<target>>>, update radio targets and
21045 corresponding links in this buffer.
21047 - If the cursor is on a numbered item in a plain list, renumber the
21048 ordered list.
21050 - If the cursor is on a checkbox, toggle it.
21052 - If the cursor is on a code block, evaluate it. The variable
21053 `org-confirm-babel-evaluate' can be used to control prompting
21054 before code block evaluation, by default every code block
21055 evaluation requires confirmation. Code block evaluation can be
21056 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21057 (interactive "P")
21058 (cond
21059 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
21060 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21061 (org-remove-occur-highlights)
21062 (message "Temporary highlights/overlays removed from current buffer"))
21063 ((and (local-variable-p 'org-finish-function)
21064 (fboundp org-finish-function))
21065 (funcall org-finish-function))
21066 ((org-babel-hash-at-point))
21067 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21069 (let* ((context
21070 (org-element-lineage
21071 (org-element-context)
21072 ;; Limit to supported contexts.
21073 '(babel-call clock dynamic-block footnote-definition
21074 footnote-reference inline-babel-call inline-src-block
21075 inlinetask item keyword node-property paragraph
21076 plain-list property-drawer radio-target src-block
21077 statistics-cookie table table-cell table-row
21078 timestamp)
21080 (type (org-element-type context)))
21081 ;; For convenience: at the first line of a paragraph on the same
21082 ;; line as an item, apply function on that item instead.
21083 (when (eq type 'paragraph)
21084 (let ((parent (org-element-property :parent context)))
21085 (when (and (eq (org-element-type parent) 'item)
21086 (= (line-beginning-position)
21087 (org-element-property :begin parent)))
21088 (setq context parent)
21089 (setq type 'item))))
21090 ;; Act according to type of element or object at point.
21092 ;; Do nothing on a blank line, except if it is contained in
21093 ;; a src block. Hence, we first check if point is in such
21094 ;; a block and then if it is at a blank line.
21095 (pcase type
21096 ((or `inline-src-block `src-block)
21097 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
21098 (org-babel-eval-wipe-error-buffer)
21099 (org-babel-execute-src-block
21100 current-prefix-arg (org-babel-get-src-block-info nil context))))
21101 ((guard (org-match-line "[ \t]*$"))
21102 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21103 (user-error
21104 (substitute-command-keys
21105 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
21106 ((or `babel-call `inline-babel-call)
21107 (let ((info (org-babel-lob-get-info context)))
21108 (when info (org-babel-execute-src-block nil info))))
21109 (`clock (org-clock-update-time-maybe))
21110 (`dynamic-block
21111 (save-excursion
21112 (goto-char (org-element-property :post-affiliated context))
21113 (org-update-dblock)))
21114 (`footnote-definition
21115 (goto-char (org-element-property :post-affiliated context))
21116 (call-interactively 'org-footnote-action))
21117 (`footnote-reference (call-interactively #'org-footnote-action))
21118 ((or `headline `inlinetask)
21119 (save-excursion (goto-char (org-element-property :begin context))
21120 (call-interactively #'org-set-tags)))
21121 (`item
21122 ;; At an item: `C-u C-u' sets checkbox to "[-]"
21123 ;; unconditionally, whereas `C-u' will toggle its presence.
21124 ;; Without a universal argument, if the item has a checkbox,
21125 ;; toggle it. Otherwise repair the list.
21126 (let* ((box (org-element-property :checkbox context))
21127 (struct (org-element-property :structure context))
21128 (old-struct (copy-tree struct))
21129 (parents (org-list-parents-alist struct))
21130 (prevs (org-list-prevs-alist struct))
21131 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21132 (org-list-set-checkbox
21133 (org-element-property :begin context) struct
21134 (cond ((equal arg '(16)) "[-]")
21135 ((and (not box) (equal arg '(4))) "[ ]")
21136 ((or (not box) (equal arg '(4))) nil)
21137 ((eq box 'on) "[ ]")
21138 (t "[X]")))
21139 ;; Mimic `org-list-write-struct' but with grabbing a return
21140 ;; value from `org-list-struct-fix-box'.
21141 (org-list-struct-fix-ind struct parents 2)
21142 (org-list-struct-fix-item-end struct)
21143 (org-list-struct-fix-bul struct prevs)
21144 (org-list-struct-fix-ind struct parents)
21145 (let ((block-item
21146 (org-list-struct-fix-box struct parents prevs orderedp)))
21147 (if (and box (equal struct old-struct))
21148 (if (equal arg '(16))
21149 (message "Checkboxes already reset")
21150 (user-error "Cannot toggle this checkbox: %s"
21151 (if (eq box 'on)
21152 "all subitems checked"
21153 "unchecked subitems")))
21154 (org-list-struct-apply-struct struct old-struct)
21155 (org-update-checkbox-count-maybe))
21156 (when block-item
21157 (message "Checkboxes were removed due to empty box at line %d"
21158 (org-current-line block-item))))))
21159 (`keyword
21160 (let ((org-inhibit-startup-visibility-stuff t)
21161 (org-startup-align-all-tables nil))
21162 (when (boundp 'org-table-coordinate-overlays)
21163 (mapc #'delete-overlay org-table-coordinate-overlays)
21164 (setq org-table-coordinate-overlays nil))
21165 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21166 (message "Local setup has been refreshed"))
21167 (`plain-list
21168 ;; At a plain list, with a double C-u argument, set
21169 ;; checkboxes of each item to "[-]", whereas a single one
21170 ;; will toggle their presence according to the state of the
21171 ;; first item in the list. Without an argument, repair the
21172 ;; list.
21173 (let* ((begin (org-element-property :contents-begin context))
21174 (beginm (move-marker (make-marker) begin))
21175 (struct (org-element-property :structure context))
21176 (old-struct (copy-tree struct))
21177 (first-box (save-excursion
21178 (goto-char begin)
21179 (looking-at org-list-full-item-re)
21180 (match-string-no-properties 3)))
21181 (new-box (cond ((equal arg '(16)) "[-]")
21182 ((equal arg '(4)) (unless first-box "[ ]"))
21183 ((equal first-box "[X]") "[ ]")
21184 (t "[X]"))))
21185 (cond
21186 (arg
21187 (dolist (pos
21188 (org-list-get-all-items
21189 begin struct (org-list-prevs-alist struct)))
21190 (org-list-set-checkbox pos struct new-box)))
21191 ((and first-box (eq (point) begin))
21192 ;; For convenience, when point is at bol on the first
21193 ;; item of the list and no argument is provided, simply
21194 ;; toggle checkbox of that item, if any.
21195 (org-list-set-checkbox begin struct new-box)))
21196 (org-list-write-struct
21197 struct (org-list-parents-alist struct) old-struct)
21198 (org-update-checkbox-count-maybe)
21199 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21200 ((or `property-drawer `node-property)
21201 (call-interactively #'org-property-action))
21202 (`radio-target
21203 (call-interactively #'org-update-radio-target-regexp))
21204 (`statistics-cookie
21205 (call-interactively #'org-update-statistics-cookies))
21206 ((or `table `table-cell `table-row)
21207 ;; At a table, recalculate every field and align it. Also
21208 ;; send the table if necessary. If the table has
21209 ;; a `table.el' type, just give up. At a table row or cell,
21210 ;; maybe recalculate line but always align table.
21211 (if (eq (org-element-property :type context) 'table.el)
21212 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21213 Use `\\[org-edit-special]' to edit table.el tables"))
21214 (let ((org-enable-table-editor t))
21215 (if (or (eq type 'table)
21216 ;; Check if point is at a TBLFM line.
21217 (and (eq type 'table-row)
21218 (= (point) (org-element-property :end context))))
21219 (save-excursion
21220 (if (org-at-TBLFM-p)
21221 (progn (require 'org-table)
21222 (org-table-calc-current-TBLFM))
21223 (goto-char (org-element-property :contents-begin context))
21224 (org-call-with-arg 'org-table-recalculate (or arg t))
21225 (orgtbl-send-table 'maybe)))
21226 (org-table-maybe-eval-formula)
21227 (cond (arg (call-interactively #'org-table-recalculate))
21228 ((org-table-maybe-recalculate-line))
21229 (t (org-table-align)))))))
21230 (`timestamp (org-timestamp-change 0 'day))
21231 ((and `nil (guard (org-at-heading-p)))
21232 ;; When point is on an unsupported object type, we can miss
21233 ;; the fact that it also is at a heading. Handle it here.
21234 (call-interactively #'org-set-tags))
21235 ((guard
21236 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
21238 (user-error
21239 (substitute-command-keys
21240 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
21242 (defun org-mode-restart ()
21243 (interactive)
21244 (let ((indent-status (bound-and-true-p org-indent-mode)))
21245 (funcall major-mode)
21246 (hack-local-variables)
21247 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21248 (org-indent-mode -1)))
21249 (message "%s restarted" major-mode))
21251 (defun org-kill-note-or-show-branches ()
21252 "Abort storing current note, or call `outline-show-branches'."
21253 (interactive)
21254 (if (not org-finish-function)
21255 (progn
21256 (outline-hide-subtree)
21257 (call-interactively 'outline-show-branches))
21258 (let ((org-note-abort t))
21259 (funcall org-finish-function))))
21261 (defun org-delete-indentation (&optional arg)
21262 "Join current line to previous and fix whitespace at join.
21264 If previous line is a headline add to headline title. Otherwise
21265 the function calls `delete-indentation'.
21267 With a non-nil optional argument, join it to the following one."
21268 (interactive "*P")
21269 (if (save-excursion
21270 (beginning-of-line (if arg 1 0))
21271 (let ((case-fold-search nil))
21272 (looking-at org-complex-heading-regexp)))
21273 ;; At headline.
21274 (let ((tags-column (when (match-beginning 5)
21275 (save-excursion (goto-char (match-beginning 5))
21276 (current-column))))
21277 (string (concat " " (progn (when arg (forward-line 1))
21278 (org-trim (delete-and-extract-region
21279 (line-beginning-position)
21280 (line-end-position)))))))
21281 (unless (bobp) (delete-region (point) (1- (point))))
21282 (goto-char (or (match-end 4)
21283 (match-beginning 5)
21284 (match-end 0)))
21285 (skip-chars-backward " \t")
21286 (save-excursion (insert string))
21287 ;; Adjust alignment of tags.
21288 (cond
21289 ((not tags-column)) ;no tags
21290 (org-auto-align-tags (org-set-tags nil t))
21291 (t (org--align-tags-here tags-column)))) ;preserve tags column
21292 (delete-indentation arg)))
21294 (defun org-open-line (n)
21295 "Insert a new row in tables, call `open-line' elsewhere.
21296 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21297 As a special case, when a document starts with a table, allow to
21298 call `open-line' on the very first character."
21299 (interactive "*p")
21300 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21301 (org-table-insert-row)
21302 (open-line n)))
21304 (defun org-return (&optional indent)
21305 "Goto next table row or insert a newline.
21307 Calls `org-table-next-row' or `newline', depending on context.
21309 When optional INDENT argument is non-nil, call
21310 `newline-and-indent' instead of `newline'.
21312 When `org-return-follows-link' is non-nil and point is on
21313 a timestamp or a link, call `org-open-at-point'. However, it
21314 will not happen if point is in a table or on a \"dead\"
21315 object (e.g., within a comment). In these case, you need to use
21316 `org-open-at-point' directly."
21317 (interactive)
21318 (let ((context (if org-return-follows-link (org-element-context)
21319 (org-element-at-point))))
21320 (cond
21321 ;; In a table, call `org-table-next-row'.
21322 ((or (and (eq (org-element-type context) 'table)
21323 (>= (point) (org-element-property :contents-begin context))
21324 (< (point) (org-element-property :contents-end context)))
21325 (org-element-lineage context '(table-row table-cell) t))
21326 (org-table-justify-field-maybe)
21327 (call-interactively #'org-table-next-row))
21328 ;; On a link or a timestamp, call `org-open-at-point' if
21329 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21330 ;; locations, e.g., in a comment, as `org-open-at-point'.
21331 ((and org-return-follows-link
21332 (or (org-in-regexp org-ts-regexp-both nil t)
21333 (org-in-regexp org-tsr-regexp-both nil t)
21334 (org-in-regexp org-any-link-re nil t)))
21335 (call-interactively #'org-open-at-point))
21336 ;; Insert newline in heading, but preserve tags.
21337 ((and (not (bolp))
21338 (save-excursion (beginning-of-line)
21339 (let ((case-fold-search nil))
21340 (looking-at org-complex-heading-regexp))))
21341 ;; At headline. Split line. However, if point is on keyword,
21342 ;; priority cookie or tags, do not break any of them: add
21343 ;; a newline after the headline instead.
21344 (let ((tags-column (and (match-beginning 5)
21345 (save-excursion (goto-char (match-beginning 5))
21346 (current-column))))
21347 (string
21348 (when (and (match-end 4) (org-point-in-group (point) 4))
21349 (delete-and-extract-region (point) (match-end 4)))))
21350 ;; Adjust tag alignment.
21351 (cond
21352 ((not (and tags-column string)))
21353 (org-auto-align-tags (org-set-tags nil t))
21354 (t (org--align-tags-here tags-column))) ;preserve tags column
21355 (end-of-line)
21356 (org-show-entry)
21357 (if indent (newline-and-indent) (newline))
21358 (when string (save-excursion (insert (org-trim string))))))
21359 ;; In a list, make sure indenting keeps trailing text within.
21360 ((and indent
21361 (not (eolp))
21362 (org-element-lineage context '(item)))
21363 (let ((trailing-data
21364 (delete-and-extract-region (point) (line-end-position))))
21365 (newline-and-indent)
21366 (save-excursion (insert trailing-data))))
21367 (t (if indent (newline-and-indent) (newline))))))
21369 (defun org-return-indent ()
21370 "Goto next table row or insert a newline and indent.
21371 Calls `org-table-next-row' or `newline-and-indent', depending on
21372 context. See the individual commands for more information."
21373 (interactive)
21374 (org-return t))
21376 (defun org-ctrl-c-star ()
21377 "Compute table, or change heading status of lines.
21378 Calls `org-table-recalculate' or `org-toggle-heading',
21379 depending on context."
21380 (interactive)
21381 (cond
21382 ((org-at-table-p)
21383 (call-interactively 'org-table-recalculate))
21385 ;; Convert all lines in region to list items
21386 (call-interactively 'org-toggle-heading))))
21388 (defun org-ctrl-c-minus ()
21389 "Insert separator line in table or modify bullet status of line.
21390 Also turns a plain line or a region of lines into list items.
21391 Calls `org-table-insert-hline', `org-toggle-item', or
21392 `org-cycle-list-bullet', depending on context."
21393 (interactive)
21394 (cond
21395 ((org-at-table-p)
21396 (call-interactively 'org-table-insert-hline))
21397 ((org-region-active-p)
21398 (call-interactively 'org-toggle-item))
21399 ((org-in-item-p)
21400 (call-interactively 'org-cycle-list-bullet))
21402 (call-interactively 'org-toggle-item))))
21404 (defun org-toggle-heading (&optional nstars)
21405 "Convert headings to normal text, or items or text to headings.
21406 If there is no active region, only convert the current line.
21408 With a `\\[universal-argument]' prefix, convert the whole list at
21409 point into heading.
21411 In a region:
21413 - If the first non blank line is a headline, remove the stars
21414 from all headlines in the region.
21416 - If it is a normal line, turn each and every normal line (i.e.,
21417 not an heading or an item) in the region into headings. If you
21418 want to convert only the first line of this region, use one
21419 universal prefix argument.
21421 - If it is a plain list item, turn all plain list items into headings.
21423 When converting a line into a heading, the number of stars is chosen
21424 such that the lines become children of the current entry. However,
21425 when a numeric prefix argument is given, its value determines the
21426 number of stars to add."
21427 (interactive "P")
21428 (let ((skip-blanks
21429 (function
21430 ;; Return beginning of first non-blank line, starting from
21431 ;; line at POS.
21432 (lambda (pos)
21433 (save-excursion
21434 (goto-char pos)
21435 (while (org-at-comment-p) (forward-line))
21436 (skip-chars-forward " \r\t\n")
21437 (point-at-bol)))))
21438 beg end toggled)
21439 ;; Determine boundaries of changes. If a universal prefix has
21440 ;; been given, put the list in a region. If region ends at a bol,
21441 ;; do not consider the last line to be in the region.
21443 (when (and current-prefix-arg (org-at-item-p))
21444 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21445 (org-mark-element))
21447 (if (org-region-active-p)
21448 (setq beg (funcall skip-blanks (region-beginning))
21449 end (copy-marker (save-excursion
21450 (goto-char (region-end))
21451 (if (bolp) (point) (point-at-eol)))))
21452 (setq beg (funcall skip-blanks (point-at-bol))
21453 end (copy-marker (point-at-eol))))
21454 ;; Ensure inline tasks don't count as headings.
21455 (org-with-limited-levels
21456 (save-excursion
21457 (goto-char beg)
21458 (cond
21459 ;; Case 1. Started at an heading: de-star headings.
21460 ((org-at-heading-p)
21461 (while (< (point) end)
21462 (when (org-at-heading-p t)
21463 (looking-at org-outline-regexp) (replace-match "")
21464 (setq toggled t))
21465 (forward-line)))
21466 ;; Case 2. Started at an item: change items into headlines.
21467 ;; One star will be added by `org-list-to-subtree'.
21468 ((org-at-item-p)
21469 (while (< (point) end)
21470 (when (org-at-item-p)
21471 ;; Pay attention to cases when region ends before list.
21472 (let* ((struct (org-list-struct))
21473 (list-end
21474 (min (org-list-get-bottom-point struct) (1+ end))))
21475 (save-restriction
21476 (narrow-to-region (point) list-end)
21477 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21478 (setq toggled t))
21479 (forward-line)))
21480 ;; Case 3. Started at normal text: make every line an heading,
21481 ;; skipping headlines and items.
21482 (t (let* ((stars
21483 (make-string
21484 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21485 (add-stars
21486 (cond (nstars "") ; stars from prefix only
21487 ((equal stars "") "*") ; before first heading
21488 (org-odd-levels-only "**") ; inside heading, odd
21489 (t "*"))) ; inside heading, oddeven
21490 (rpl (concat stars add-stars " "))
21491 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21492 (while (< (point) (if (equal nstars '(4)) lend end))
21493 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21494 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21495 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21496 (forward-line)))))))
21497 (unless toggled (message "Cannot toggle heading from here"))))
21499 (defun org-meta-return (&optional _arg)
21500 "Insert a new heading or wrap a region in a table.
21501 Calls `org-insert-heading' or `org-table-wrap-region', depending
21502 on context. See the individual commands for more information."
21503 (interactive)
21504 (org-check-before-invisible-edit 'insert)
21505 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21506 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21507 #'org-insert-heading))))
21509 ;;; Menu entries
21511 (defsubst org-in-subtree-not-table-p ()
21512 "Are we in a subtree and not in a table?"
21513 (and (not (org-before-first-heading-p))
21514 (not (org-at-table-p))))
21516 ;; Define the Org mode menus
21517 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21518 '("Tbl"
21519 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21520 ["Next Field" org-cycle (org-at-table-p)]
21521 ["Previous Field" org-shifttab (org-at-table-p)]
21522 ["Next Row" org-return (org-at-table-p)]
21523 "--"
21524 ["Blank Field" org-table-blank-field (org-at-table-p)]
21525 ["Edit Field" org-table-edit-field (org-at-table-p)]
21526 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21527 "--"
21528 ("Column"
21529 ["Move Column Left" org-metaleft (org-at-table-p)]
21530 ["Move Column Right" org-metaright (org-at-table-p)]
21531 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21532 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21533 ("Row"
21534 ["Move Row Up" org-metaup (org-at-table-p)]
21535 ["Move Row Down" org-metadown (org-at-table-p)]
21536 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21537 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21538 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21539 "--"
21540 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21541 ("Rectangle"
21542 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21543 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21544 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21545 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21546 "--"
21547 ("Calculate"
21548 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21549 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21550 ["Edit Formulas" org-edit-special (org-at-table-p)]
21551 "--"
21552 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21553 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21554 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21555 "--"
21556 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21557 "--"
21558 ["Sum Column/Rectangle" org-table-sum
21559 (or (org-at-table-p) (org-region-active-p))]
21560 ["Which Column?" org-table-current-column (org-at-table-p)])
21561 ["Debug Formulas"
21562 org-table-toggle-formula-debugger
21563 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21564 ["Show Col/Row Numbers"
21565 org-table-toggle-coordinate-overlays
21566 :style toggle
21567 :selected (bound-and-true-p org-table-overlay-coordinates)]
21568 "--"
21569 ["Create" org-table-create (and (not (org-at-table-p))
21570 org-enable-table-editor)]
21571 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21572 ["Import from File" org-table-import (not (org-at-table-p))]
21573 ["Export to File" org-table-export (org-at-table-p)]
21574 "--"
21575 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21576 "--"
21577 ("Plot"
21578 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21579 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21581 (easy-menu-define org-org-menu org-mode-map "Org menu"
21582 '("Org"
21583 ("Show/Hide"
21584 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21585 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21586 ["Sparse Tree..." org-sparse-tree t]
21587 ["Reveal Context" org-reveal t]
21588 ["Show All" outline-show-all t]
21589 "--"
21590 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21591 "--"
21592 ["New Heading" org-insert-heading t]
21593 ("Navigate Headings"
21594 ["Up" outline-up-heading t]
21595 ["Next" outline-next-visible-heading t]
21596 ["Previous" outline-previous-visible-heading t]
21597 ["Next Same Level" outline-forward-same-level t]
21598 ["Previous Same Level" outline-backward-same-level t]
21599 "--"
21600 ["Jump" org-goto t])
21601 ("Edit Structure"
21602 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21603 "--"
21604 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21605 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21606 "--"
21607 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21608 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21609 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21610 "--"
21611 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21612 "--"
21613 ["Copy visible text" org-copy-visible t]
21614 "--"
21615 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21616 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21617 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21618 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21619 "--"
21620 ["Sort Region/Children" org-sort t]
21621 "--"
21622 ["Convert to odd levels" org-convert-to-odd-levels t]
21623 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21624 ("Editing"
21625 ["Emphasis..." org-emphasize t]
21626 ["Edit Source Example" org-edit-special t]
21627 "--"
21628 ["Footnote new/jump" org-footnote-action t]
21629 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21630 ("Archive"
21631 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21632 "--"
21633 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21634 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21635 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21637 "--"
21638 ("Hyperlinks"
21639 ["Store Link (Global)" org-store-link t]
21640 ["Find existing link to here" org-occur-link-in-agenda-files t]
21641 ["Insert Link" org-insert-link t]
21642 ["Follow Link" org-open-at-point t]
21643 "--"
21644 ["Next link" org-next-link t]
21645 ["Previous link" org-previous-link t]
21646 "--"
21647 ["Descriptive Links"
21648 org-toggle-link-display
21649 :style radio
21650 :selected org-descriptive-links
21652 ["Literal Links"
21653 org-toggle-link-display
21654 :style radio
21655 :selected (not org-descriptive-links)])
21656 "--"
21657 ("TODO Lists"
21658 ["TODO/DONE/-" org-todo t]
21659 ("Select keyword"
21660 ["Next keyword" org-shiftright (org-at-heading-p)]
21661 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21662 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21663 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21664 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21665 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21666 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21667 "--"
21668 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21669 :selected org-enforce-todo-dependencies :style toggle :active t]
21670 "Settings for tree at point"
21671 ["Do Children sequentially" org-toggle-ordered-property :style radio
21672 :selected (org-entry-get nil "ORDERED")
21673 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21674 ["Do Children parallel" org-toggle-ordered-property :style radio
21675 :selected (not (org-entry-get nil "ORDERED"))
21676 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21677 "--"
21678 ["Set Priority" org-priority t]
21679 ["Priority Up" org-shiftup t]
21680 ["Priority Down" org-shiftdown t]
21681 "--"
21682 ["Get news from all feeds" org-feed-update-all t]
21683 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21684 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21685 ("TAGS and Properties"
21686 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21687 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21688 "--"
21689 ["Set property" org-set-property (not (org-before-first-heading-p))]
21690 ["Column view of properties" org-columns t]
21691 ["Insert Column View DBlock" org-columns-insert-dblock t])
21692 ("Dates and Scheduling"
21693 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21694 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21695 ("Change Date"
21696 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21697 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21698 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21699 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21700 ["Compute Time Range" org-evaluate-time-range t]
21701 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21702 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21703 "--"
21704 ["Custom time format" org-toggle-time-stamp-overlays
21705 :style radio :selected org-display-custom-times]
21706 "--"
21707 ["Goto Calendar" org-goto-calendar t]
21708 ["Date from Calendar" org-date-from-calendar t]
21709 "--"
21710 ["Start/Restart Timer" org-timer-start t]
21711 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21712 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21713 ["Insert Timer String" org-timer t]
21714 ["Insert Timer Item" org-timer-item t])
21715 ("Logging work"
21716 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21717 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21718 ["Clock out" org-clock-out t]
21719 ["Clock cancel" org-clock-cancel t]
21720 "--"
21721 ["Mark as default task" org-clock-mark-default-task t]
21722 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21723 ["Goto running clock" org-clock-goto t]
21724 "--"
21725 ["Display times" org-clock-display t]
21726 ["Create clock table" org-clock-report t]
21727 "--"
21728 ["Record DONE time"
21729 (progn (setq org-log-done (not org-log-done))
21730 (message "Switching to %s will %s record a timestamp"
21731 (car org-done-keywords)
21732 (if org-log-done "automatically" "not")))
21733 :style toggle :selected org-log-done])
21734 "--"
21735 ["Agenda Command..." org-agenda t]
21736 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21737 ("File List for Agenda")
21738 ("Special views current file"
21739 ["TODO Tree" org-show-todo-tree t]
21740 ["Check Deadlines" org-check-deadlines t]
21741 ["Timeline" org-timeline t]
21742 ["Tags/Property tree" org-match-sparse-tree t])
21743 "--"
21744 ["Export/Publish..." org-export-dispatch t]
21745 ("LaTeX"
21746 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21747 :selected org-cdlatex-mode]
21748 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21749 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21750 ["Modify math symbol" org-cdlatex-math-modify
21751 (org-inside-LaTeX-fragment-p)]
21752 ["Insert citation" org-reftex-citation t])
21753 "--"
21754 ("MobileOrg"
21755 ["Push Files and Views" org-mobile-push t]
21756 ["Get Captured and Flagged" org-mobile-pull t]
21757 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21758 "--"
21759 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21760 "--"
21761 ("Documentation"
21762 ["Show Version" org-version t]
21763 ["Info Documentation" org-info t])
21764 ("Customize"
21765 ["Browse Org Group" org-customize t]
21766 "--"
21767 ["Expand This Menu" org-create-customize-menu
21768 (fboundp 'customize-menu-create)])
21769 ["Send bug report" org-submit-bug-report t]
21770 "--"
21771 ("Refresh/Reload"
21772 ["Refresh setup current buffer" org-mode-restart t]
21773 ["Reload Org (after update)" org-reload t]
21774 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21777 (defun org-info (&optional node)
21778 "Read documentation for Org in the info system.
21779 With optional NODE, go directly to that node."
21780 (interactive)
21781 (info (format "(org)%s" (or node ""))))
21783 ;;;###autoload
21784 (defun org-submit-bug-report ()
21785 "Submit a bug report on Org via mail.
21787 Don't hesitate to report any problems or inaccurate documentation.
21789 If you don't have setup sending mail from (X)Emacs, please copy the
21790 output buffer into your mail program, as it gives us important
21791 information about your Org version and configuration."
21792 (interactive)
21793 (require 'reporter)
21794 (defvar reporter-prompt-for-summary-p)
21795 (org-load-modules-maybe)
21796 (org-require-autoloaded-modules)
21797 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21798 (reporter-submit-bug-report
21799 "emacs-orgmode@gnu.org"
21800 (org-version nil 'full)
21801 (let (list)
21802 (save-window-excursion
21803 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21804 (delete-other-windows)
21805 (erase-buffer)
21806 (insert "You are about to submit a bug report to the Org mailing list.
21808 We would like to add your full Org and Outline configuration to the
21809 bug report. This greatly simplifies the work of the maintainer and
21810 other experts on the mailing list.
21812 HOWEVER, some variables you have customized may contain private
21813 information. The names of customers, colleagues, or friends, might
21814 appear in the form of file names, tags, todo states, or search strings.
21815 If you answer yes to the prompt, you might want to check and remove
21816 such private information before sending the email.")
21817 (add-text-properties (point-min) (point-max) '(face org-warning))
21818 (when (yes-or-no-p "Include your Org configuration ")
21819 (mapatoms
21820 (lambda (v)
21821 (and (boundp v)
21822 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21823 (or (and (symbol-value v)
21824 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21825 (and
21826 (get v 'custom-type) (get v 'standard-value)
21827 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21828 (push v list)))))
21829 (kill-buffer (get-buffer "*Warn about privacy*"))
21830 list))
21831 nil nil
21832 "Remember to cover the basics, that is, what you expected to happen and
21833 what in fact did happen. You don't know how to make a good report? See
21835 http://orgmode.org/manual/Feedback.html#Feedback
21837 Your bug report will be posted to the Org mailing list.
21838 ------------------------------------------------------------------------")
21839 (save-excursion
21840 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21841 (replace-match "\\1Bug: \\3 [\\2]")))))
21844 (defun org-install-agenda-files-menu ()
21845 (let ((bl (buffer-list)))
21846 (save-excursion
21847 (while bl
21848 (set-buffer (pop bl))
21849 (when (derived-mode-p 'org-mode) (setq bl nil)))
21850 (when (derived-mode-p 'org-mode)
21851 (easy-menu-change
21852 '("Org") "File List for Agenda"
21853 (append
21854 (list
21855 ["Edit File List" (org-edit-agenda-file-list) t]
21856 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21857 ["Remove Current File from List" org-remove-file t]
21858 ["Cycle through agenda files" org-cycle-agenda-files t]
21859 ["Occur in all agenda files" org-occur-in-agenda-files t]
21860 "--")
21861 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21863 ;;;; Documentation
21865 (defun org-require-autoloaded-modules ()
21866 (interactive)
21867 (mapc #'require
21868 '(org-agenda org-archive org-attach org-clock org-colview org-id
21869 org-table org-timer)))
21871 ;;;###autoload
21872 (defun org-reload (&optional uncompiled)
21873 "Reload all org lisp files.
21874 With prefix arg UNCOMPILED, load the uncompiled versions."
21875 (interactive "P")
21876 (require 'loadhist)
21877 (let* ((org-dir (org-find-library-dir "org"))
21878 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21879 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21880 (remove-re (format "\\`%s\\'"
21881 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21882 (feats (delete-dups
21883 (mapcar 'file-name-sans-extension
21884 (mapcar 'file-name-nondirectory
21885 (delq nil
21886 (mapcar 'feature-file
21887 features))))))
21888 (lfeat (append
21889 (sort
21890 (setq feats
21891 (delq nil (mapcar
21892 (lambda (f)
21893 (if (and (string-match feature-re f)
21894 (not (string-match remove-re f)))
21895 f nil))
21896 feats)))
21897 'string-lessp)
21898 (list "org-version" "org")))
21899 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21900 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21901 load-uncore load-misses)
21902 (setq load-misses
21903 (delq 't
21904 (mapcar (lambda (f)
21905 (or (org-load-noerror-mustsuffix (concat org-dir f))
21906 (and (string= org-dir contrib-dir)
21907 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21908 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21909 (add-to-list 'load-uncore f 'append)
21912 lfeat)))
21913 (when load-uncore
21914 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21915 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21916 (if load-misses
21917 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21918 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21919 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21921 ;;;###autoload
21922 (defun org-customize ()
21923 "Call the customize function with org as argument."
21924 (interactive)
21925 (org-load-modules-maybe)
21926 (org-require-autoloaded-modules)
21927 (customize-browse 'org))
21929 (defun org-create-customize-menu ()
21930 "Create a full customization menu for Org mode, insert it into the menu."
21931 (interactive)
21932 (org-load-modules-maybe)
21933 (org-require-autoloaded-modules)
21934 (if (fboundp 'customize-menu-create)
21935 (progn
21936 (easy-menu-change
21937 '("Org") "Customize"
21938 `(["Browse Org group" org-customize t]
21939 "--"
21940 ,(customize-menu-create 'org)
21941 ["Set" Custom-set t]
21942 ["Save" Custom-save t]
21943 ["Reset to Current" Custom-reset-current t]
21944 ["Reset to Saved" Custom-reset-saved t]
21945 ["Reset to Standard Settings" Custom-reset-standard t]))
21946 (message "\"Org\"-menu now contains full customization menu"))
21947 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21949 ;;;; Miscellaneous stuff
21951 ;;; Generally useful functions
21953 (defun org-get-at-eol (property n)
21954 "Get text property PROPERTY at the end of line less N characters."
21955 (get-text-property (- (point-at-eol) n) property))
21957 (defun org-find-text-property-in-string (prop s)
21958 "Return the first non-nil value of property PROP in string S."
21959 (or (get-text-property 0 prop s)
21960 (get-text-property (or (next-single-property-change 0 prop s) 0)
21961 prop s)))
21963 (defun org-display-warning (message)
21964 "Display the given MESSAGE as a warning."
21965 (display-warning 'org message :warning))
21967 (defun org-eval (form)
21968 "Eval FORM and return result."
21969 (condition-case error
21970 (eval form)
21971 (error (format "%%![Error: %s]" error))))
21973 (defun org-in-clocktable-p ()
21974 "Check if the cursor is in a clocktable."
21975 (let ((pos (point)) start)
21976 (save-excursion
21977 (end-of-line 1)
21978 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21979 (setq start (match-beginning 0))
21980 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21981 (>= (match-end 0) pos)
21982 start))))
21984 (defun org-in-verbatim-emphasis ()
21985 (save-match-data
21986 (and (org-in-regexp org-emph-re 2)
21987 (>= (point) (match-beginning 3))
21988 (<= (point) (match-end 4))
21989 (member (match-string 3) '("=" "~")))))
21991 (defun org-overlay-display (ovl text &optional face evap)
21992 "Make overlay OVL display TEXT with face FACE."
21993 (overlay-put ovl 'display text)
21994 (if face (overlay-put ovl 'face face))
21995 (if evap (overlay-put ovl 'evaporate t)))
21997 (defun org-overlay-before-string (ovl text &optional face evap)
21998 "Make overlay OVL display TEXT with face FACE."
21999 (if face (org-add-props text nil 'face face))
22000 (overlay-put ovl 'before-string text)
22001 (if evap (overlay-put ovl 'evaporate t)))
22003 (defun org-find-overlays (prop &optional pos delete)
22004 "Find all overlays specifying PROP at POS or point.
22005 If DELETE is non-nil, delete all those overlays."
22006 (let (found)
22007 (dolist (ov (overlays-at (or pos (point))) found)
22008 (cond ((not (overlay-get ov prop)))
22009 (delete (delete-overlay ov))
22010 (t (push ov found))))))
22012 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22013 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22014 (if (and marker (marker-buffer marker)
22015 (buffer-live-p (marker-buffer marker)))
22016 (progn
22017 (pop-to-buffer-same-window (marker-buffer marker))
22018 (when (or (> marker (point-max)) (< marker (point-min)))
22019 (widen))
22020 (goto-char marker)
22021 (org-show-context 'org-goto))
22022 (if bookmark
22023 (bookmark-jump bookmark)
22024 (error "Cannot find location"))))
22026 (defun org-quote-csv-field (s)
22027 "Quote field for inclusion in CSV material."
22028 (if (string-match "[\",]" s)
22029 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22032 (defun org-force-self-insert (N)
22033 "Needed to enforce self-insert under remapping."
22034 (interactive "p")
22035 (self-insert-command N))
22037 (defun org-string-width (s)
22038 "Compute width of string, ignoring invisible characters.
22039 This ignores character with invisibility property `org-link', and also
22040 characters with property `org-cwidth', because these will become invisible
22041 upon the next fontification round."
22042 (let (b l)
22043 (when (or (eq t buffer-invisibility-spec)
22044 (assq 'org-link buffer-invisibility-spec))
22045 (while (setq b (text-property-any 0 (length s)
22046 'invisible 'org-link s))
22047 (setq s (concat (substring s 0 b)
22048 (substring s (or (next-single-property-change
22049 b 'invisible s)
22050 (length s)))))))
22051 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22052 (setq s (concat (substring s 0 b)
22053 (substring s (or (next-single-property-change
22054 b 'org-cwidth s)
22055 (length s))))))
22056 (setq l (string-width s) b -1)
22057 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22058 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22061 (defun org-shorten-string (s maxlength)
22062 "Shorten string S so that it is no longer than MAXLENGTH characters.
22063 If the string is shorter or has length MAXLENGTH, just return the
22064 original string. If it is longer, the functions finds a space in the
22065 string, breaks this string off at that locations and adds three dots
22066 as ellipsis. Including the ellipsis, the string will not be longer
22067 than MAXLENGTH. If finding a good breaking point in the string does
22068 not work, the string is just chopped off in the middle of a word
22069 if necessary."
22070 (if (<= (length s) maxlength)
22072 (let* ((n (max (- maxlength 4) 1))
22073 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22074 (if (string-match re s)
22075 (concat (match-string 1 s) "...")
22076 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22078 (defun org-get-indentation (&optional line)
22079 "Get the indentation of the current line, interpreting tabs.
22080 When LINE is given, assume it represents a line and compute its indentation."
22081 (if line
22082 (when (string-match "^ *" (org-remove-tabs line))
22083 (match-end 0))
22084 (save-excursion
22085 (beginning-of-line 1)
22086 (skip-chars-forward " \t")
22087 (current-column))))
22089 (defun org-get-string-indentation (s)
22090 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22091 (let ((n -1) (i 0) (w tab-width) c)
22092 (catch 'exit
22093 (while (< (setq n (1+ n)) (length s))
22094 (setq c (aref s n))
22095 (cond ((= c ?\ ) (setq i (1+ i)))
22096 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22097 (t (throw 'exit t)))))
22100 (defun org-remove-tabs (s &optional width)
22101 "Replace tabulators in S with spaces.
22102 Assumes that s is a single line, starting in column 0."
22103 (setq width (or width tab-width))
22104 (while (string-match "\t" s)
22105 (setq s (replace-match
22106 (make-string
22107 (- (* width (/ (+ (match-beginning 0) width) width))
22108 (match-beginning 0)) ?\ )
22109 t t s)))
22112 (defun org-fix-indentation (line ind)
22113 "Fix indentation in LINE.
22114 IND is a cons cell with target and minimum indentation.
22115 If the current indentation in LINE is smaller than the minimum,
22116 leave it alone. If it is larger than ind, set it to the target."
22117 (let* ((l (org-remove-tabs line))
22118 (i (org-get-indentation l))
22119 (i1 (car ind)) (i2 (cdr ind)))
22120 (when (>= i i2) (setq l (substring line i2)))
22121 (if (> i1 0)
22122 (concat (make-string i1 ?\ ) l)
22123 l)))
22125 (defun org-remove-indentation (code &optional n)
22126 "Remove maximum common indentation in string CODE and return it.
22127 N may optionally be the number of columns to remove. Return CODE
22128 as-is if removal failed."
22129 (with-temp-buffer
22130 (insert code)
22131 (if (org-do-remove-indentation n) (buffer-string) code)))
22133 (defun org-do-remove-indentation (&optional n)
22134 "Remove the maximum common indentation from the buffer.
22135 When optional argument N is a positive integer, remove exactly
22136 that much characters from indentation, if possible. Return nil
22137 if it fails."
22138 (catch :exit
22139 (goto-char (point-min))
22140 ;; Find maximum common indentation, if not specified.
22141 (let ((n (or n
22142 (let ((min-ind (point-max)))
22143 (save-excursion
22144 (while (re-search-forward "^[ \t]*\\S-" nil t)
22145 (let ((ind (1- (current-column))))
22146 (if (zerop ind) (throw :exit nil)
22147 (setq min-ind (min min-ind ind))))))
22148 min-ind))))
22149 (if (zerop n) (throw :exit nil)
22150 ;; Remove exactly N indentation, but give up if not possible.
22151 (while (not (eobp))
22152 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22153 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22154 ((< ind n) (throw :exit nil))
22155 (t (indent-line-to (- ind n))))
22156 (forward-line)))
22157 ;; Signal success.
22158 t))))
22160 (defun org-fill-template (template alist)
22161 "Find each %key of ALIST in TEMPLATE and replace it."
22162 (let ((case-fold-search nil))
22163 (dolist (entry (sort (copy-sequence alist)
22164 (lambda (a b) (< (length (car a)) (length (car b))))))
22165 (setq template
22166 (replace-regexp-in-string
22167 (concat "%" (regexp-quote (car entry)))
22168 (or (cdr entry) "") template t t)))
22169 template))
22171 (defun org-base-buffer (buffer)
22172 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22173 (if (not buffer)
22174 buffer
22175 (or (buffer-base-buffer buffer)
22176 buffer)))
22178 (defun org-wrap (string &optional width lines)
22179 "Wrap string to either a number of lines, or a width in characters.
22180 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22181 that costs. If there is a word longer than WIDTH, the text is actually
22182 wrapped to the length of that word.
22183 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22184 many lines, whatever width that takes.
22185 The return value is a list of lines, without newlines at the end."
22186 (let* ((words (org-split-string string "[ \t\n]+"))
22187 (maxword (apply 'max (mapcar 'org-string-width words)))
22188 w ll)
22189 (cond (width
22190 (org-do-wrap words (max maxword width)))
22191 (lines
22192 (setq w maxword)
22193 (setq ll (org-do-wrap words maxword))
22194 (if (<= (length ll) lines)
22196 (setq ll words)
22197 (while (> (length ll) lines)
22198 (setq w (1+ w))
22199 (setq ll (org-do-wrap words w)))
22200 ll))
22201 (t (error "Cannot wrap this")))))
22203 (defun org-do-wrap (words width)
22204 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22205 (let (lines line)
22206 (while words
22207 (setq line (pop words))
22208 (while (and words (< (+ (length line) (length (car words))) width))
22209 (setq line (concat line " " (pop words))))
22210 (setq lines (push line lines)))
22211 (nreverse lines)))
22213 (defun org-split-string (string &optional separators)
22214 "Splits STRING into substrings at SEPARATORS.
22215 SEPARATORS is a regular expression.
22216 No empty strings are returned if there are matches at the beginning
22217 and end of string."
22218 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22219 (let ((start 0) notfirst list)
22220 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22221 (if (and notfirst
22222 (= start (match-beginning 0))
22223 (< start (length string)))
22224 (1+ start) start))
22225 (< (match-beginning 0) (length string)))
22226 (setq notfirst t)
22227 (or (eq (match-beginning 0) 0)
22228 (and (eq (match-beginning 0) (match-end 0))
22229 (eq (match-beginning 0) start))
22230 (push (substring string start (match-beginning 0)) list))
22231 (setq start (match-end 0)))
22232 (or (eq start (length string))
22233 (push (substring string start) list))
22234 (nreverse list)))
22236 (defun org-quote-vert (s)
22237 "Replace \"|\" with \"\\vert\"."
22238 (while (string-match "|" s)
22239 (setq s (replace-match "\\vert" t t s)))
22242 (defun org-uuidgen-p (s)
22243 "Is S an ID created by UUIDGEN?"
22244 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22246 (defun org-in-src-block-p (&optional inside)
22247 "Whether point is in a code source block.
22248 When INSIDE is non-nil, don't consider we are within a src block
22249 when point is at #+BEGIN_SRC or #+END_SRC."
22250 (let ((case-fold-search t))
22251 (or (and (eq (get-char-property (point) 'src-block) t))
22252 (and (not inside)
22253 (save-match-data
22254 (save-excursion
22255 (beginning-of-line)
22256 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22258 (defun org-context ()
22259 "Return a list of contexts of the current cursor position.
22260 If several contexts apply, all are returned.
22261 Each context entry is a list with a symbol naming the context, and
22262 two positions indicating start and end of the context. Possible
22263 contexts are:
22265 :headline anywhere in a headline
22266 :headline-stars on the leading stars in a headline
22267 :todo-keyword on a TODO keyword (including DONE) in a headline
22268 :tags on the TAGS in a headline
22269 :priority on the priority cookie in a headline
22270 :item on the first line of a plain list item
22271 :item-bullet on the bullet/number of a plain list item
22272 :checkbox on the checkbox in a plain list item
22273 :table in an Org table
22274 :table-special on a special filed in a table
22275 :table-table in a table.el table
22276 :clocktable in a clocktable
22277 :src-block in a source block
22278 :link on a hyperlink
22279 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22280 :target on a <<target>>
22281 :radio-target on a <<<radio-target>>>
22282 :latex-fragment on a LaTeX fragment
22283 :latex-preview on a LaTeX fragment with overlaid preview image
22285 This function expects the position to be visible because it uses font-lock
22286 faces as a help to recognize the following contexts: :table-special, :link,
22287 and :keyword."
22288 (let* ((f (get-text-property (point) 'face))
22289 (faces (if (listp f) f (list f)))
22290 (case-fold-search t)
22291 (p (point)) clist o)
22292 ;; First the large context
22293 (cond
22294 ((org-at-heading-p t)
22295 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22296 (when (progn
22297 (beginning-of-line 1)
22298 (looking-at org-todo-line-tags-regexp))
22299 (push (org-point-in-group p 1 :headline-stars) clist)
22300 (push (org-point-in-group p 2 :todo-keyword) clist)
22301 (push (org-point-in-group p 4 :tags) clist))
22302 (goto-char p)
22303 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22304 (when (looking-at "\\[#[A-Z0-9]\\]")
22305 (push (org-point-in-group p 0 :priority) clist)))
22307 ((org-at-item-p)
22308 (push (org-point-in-group p 2 :item-bullet) clist)
22309 (push (list :item (point-at-bol)
22310 (save-excursion (org-end-of-item) (point)))
22311 clist)
22312 (and (org-at-item-checkbox-p)
22313 (push (org-point-in-group p 0 :checkbox) clist)))
22315 ((org-at-table-p)
22316 (push (list :table (org-table-begin) (org-table-end)) clist)
22317 (when (memq 'org-formula faces)
22318 (push (list :table-special
22319 (previous-single-property-change p 'face)
22320 (next-single-property-change p 'face)) clist)))
22321 ((org-at-table-p 'any)
22322 (push (list :table-table) clist)))
22323 (goto-char p)
22325 (let ((case-fold-search t))
22326 ;; New the "medium" contexts: clocktables, source blocks
22327 (cond ((org-in-clocktable-p)
22328 (push (list :clocktable
22329 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22330 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22331 (match-beginning 1))
22332 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22333 (match-end 0))) clist))
22334 ((org-in-src-block-p)
22335 (push (list :src-block
22336 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22337 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22338 (match-beginning 1))
22339 (and (search-forward "#+END_SRC" nil t)
22340 (match-beginning 0))) clist))))
22341 (goto-char p)
22343 ;; Now the small context
22344 (cond
22345 ((org-at-timestamp-p)
22346 (push (org-point-in-group p 0 :timestamp) clist))
22347 ((memq 'org-link faces)
22348 (push (list :link
22349 (previous-single-property-change p 'face)
22350 (next-single-property-change p 'face)) clist))
22351 ((memq 'org-special-keyword faces)
22352 (push (list :keyword
22353 (previous-single-property-change p 'face)
22354 (next-single-property-change p 'face)) clist))
22355 ((org-at-target-p)
22356 (push (org-point-in-group p 0 :target) clist)
22357 (goto-char (1- (match-beginning 0)))
22358 (when (looking-at org-radio-target-regexp)
22359 (push (org-point-in-group p 0 :radio-target) clist))
22360 (goto-char p))
22361 ((setq o (cl-some
22362 (lambda (o)
22363 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22365 (overlays-at (point))))
22366 (push (list :latex-fragment
22367 (overlay-start o) (overlay-end o)) clist)
22368 (push (list :latex-preview
22369 (overlay-start o) (overlay-end o)) clist))
22370 ((org-inside-LaTeX-fragment-p)
22371 ;; FIXME: positions wrong.
22372 (push (list :latex-fragment (point) (point)) clist)))
22374 (setq clist (nreverse (delq nil clist)))
22375 clist))
22377 (defun org-in-regexp (regexp &optional nlines visually)
22378 "Check if point is inside a match of REGEXP.
22380 Normally only the current line is checked, but you can include
22381 NLINES extra lines around point into the search. If VISUALLY is
22382 set, require that the cursor is not after the match but really
22383 on, so that the block visually is on the match.
22385 Return nil or a cons cell (BEG . END) where BEG and END are,
22386 respectively, the positions at the beginning and the end of the
22387 match."
22388 (catch :exit
22389 (let ((pos (point))
22390 (eol (line-end-position (if nlines (1+ nlines) 1))))
22391 (save-excursion
22392 (beginning-of-line (- 1 (or nlines 0)))
22393 (while (and (re-search-forward regexp eol t)
22394 (<= (match-beginning 0) pos))
22395 (let ((end (match-end 0)))
22396 (when (or (> end pos) (and (= end pos) (not visually)))
22397 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22399 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22400 "Non-nil when point is between matches of START-RE and END-RE.
22402 Also return a non-nil value when point is on one of the matches.
22404 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22405 buffer positions. Default values are the positions of headlines
22406 surrounding the point.
22408 The functions returns a cons cell whose car (resp. cdr) is the
22409 position before START-RE (resp. after END-RE)."
22410 (save-match-data
22411 (let ((pos (point))
22412 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22413 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22414 beg end)
22415 (save-excursion
22416 ;; Point is on a block when on START-RE or if START-RE can be
22417 ;; found before it...
22418 (and (or (org-in-regexp start-re)
22419 (re-search-backward start-re limit-up t))
22420 (setq beg (match-beginning 0))
22421 ;; ... and END-RE after it...
22422 (goto-char (match-end 0))
22423 (re-search-forward end-re limit-down t)
22424 (> (setq end (match-end 0)) pos)
22425 ;; ... without another START-RE in-between.
22426 (goto-char (match-beginning 0))
22427 (not (re-search-backward start-re (1+ beg) t))
22428 ;; Return value.
22429 (cons beg end))))))
22431 (defun org-in-block-p (names)
22432 "Non-nil when point belongs to a block whose name belongs to NAMES.
22434 NAMES is a list of strings containing names of blocks.
22436 Return first block name matched, or nil. Beware that in case of
22437 nested blocks, the returned name may not belong to the closest
22438 block from point."
22439 (save-match-data
22440 (catch 'exit
22441 (let ((case-fold-search t)
22442 (lim-up (save-excursion (outline-previous-heading)))
22443 (lim-down (save-excursion (outline-next-heading))))
22444 (dolist (name names)
22445 (let ((n (regexp-quote name)))
22446 (when (org-between-regexps-p
22447 (concat "^[ \t]*#\\+begin_" n)
22448 (concat "^[ \t]*#\\+end_" n)
22449 lim-up lim-down)
22450 (throw 'exit n)))))
22451 nil)))
22453 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22454 "Call `multi-occur' with buffers for all agenda files."
22455 (interactive "sOrg-files matching: ")
22456 (let* ((files (org-agenda-files))
22457 (tnames (mapcar #'file-truename files))
22458 (extra org-agenda-text-search-extra-files))
22459 (when (eq (car extra) 'agenda-archives)
22460 (setq extra (cdr extra))
22461 (setq files (org-add-archive-files files)))
22462 (dolist (f extra)
22463 (unless (member (file-truename f) tnames)
22464 (unless (member f files) (setq files (append files (list f))))
22465 (setq tnames (append tnames (list (file-truename f))))))
22466 (multi-occur
22467 (mapcar (lambda (x)
22468 (with-current-buffer
22469 ;; FIXME: Why not just (find-file-noselect x)?
22470 ;; Is it to avoid the "revert buffer" prompt?
22471 (or (get-file-buffer x) (find-file-noselect x))
22472 (widen)
22473 (current-buffer)))
22474 files)
22475 regexp)))
22477 (add-hook 'occur-mode-find-occurrence-hook
22478 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22480 (defun org-occur-link-in-agenda-files ()
22481 "Create a link and search for it in the agendas.
22482 The link is not stored in `org-stored-links', it is just created
22483 for the search purpose."
22484 (interactive)
22485 (let ((link (condition-case nil
22486 (org-store-link nil)
22487 (error "Unable to create a link to here"))))
22488 (org-occur-in-agenda-files (regexp-quote link))))
22490 (defun org-reverse-string (string)
22491 "Return the reverse of STRING."
22492 (apply 'string (reverse (string-to-list string))))
22494 ;; defsubst org-uniquify must be defined before first use
22496 (defun org-uniquify-alist (alist)
22497 "Merge elements of ALIST with the same key.
22499 For example, in this alist:
22501 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22502 => \\='((a 1 3) (b 2))
22504 merge (a 1) and (a 3) into (a 1 3).
22506 The function returns the new ALIST."
22507 (let (rtn)
22508 (dolist (e alist rtn)
22509 (let (n)
22510 (if (not (assoc (car e) rtn))
22511 (push e rtn)
22512 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22513 (setq rtn (assq-delete-all (car e) rtn))
22514 (push n rtn))))))
22516 (defun org-delete-all (elts list)
22517 "Remove all elements in ELTS from LIST.
22518 Comparison is done with `equal'. It is a destructive operation
22519 that may remove elements by altering the list structure."
22520 (while elts
22521 (setq list (delete (pop elts) list)))
22522 list)
22524 (defun org-back-over-empty-lines ()
22525 "Move backwards over whitespace, to the beginning of the first empty line.
22526 Returns the number of empty lines passed."
22527 (let ((pos (point)))
22528 (if (cdr (assq 'heading org-blank-before-new-entry))
22529 (skip-chars-backward " \t\n\r")
22530 (unless (eobp)
22531 (forward-line -1)))
22532 (beginning-of-line 2)
22533 (goto-char (min (point) pos))
22534 (count-lines (point) pos)))
22536 (defun org-skip-whitespace ()
22537 (skip-chars-forward " \t\n\r"))
22539 (defun org-point-in-group (point group &optional context)
22540 "Check if POINT is in match-group GROUP.
22541 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22542 match. If the match group does not exist or point is not inside it,
22543 return nil."
22544 (and (match-beginning group)
22545 (>= point (match-beginning group))
22546 (<= point (match-end group))
22547 (if context
22548 (list context (match-beginning group) (match-end group))
22549 t)))
22551 (defun org-switch-to-buffer-other-window (&rest args)
22552 "Switch to buffer in a second window on the current frame.
22553 In particular, do not allow pop-up frames.
22554 Returns the newly created buffer."
22555 (org-no-popups
22556 (apply 'switch-to-buffer-other-window args)))
22558 (defun org-combine-plists (&rest plists)
22559 "Create a single property list from all plists in PLISTS.
22560 The process starts by copying the first list, and then setting properties
22561 from the other lists. Settings in the last list are the most significant
22562 ones and overrule settings in the other lists."
22563 (let ((rtn (copy-sequence (pop plists)))
22564 p v ls)
22565 (while plists
22566 (setq ls (pop plists))
22567 (while ls
22568 (setq p (pop ls) v (pop ls))
22569 (setq rtn (plist-put rtn p v))))
22570 rtn))
22572 (defun org-replace-escapes (string table)
22573 "Replace %-escapes in STRING with values in TABLE.
22574 TABLE is an association list with keys like \"%a\" and string values.
22575 The sequences in STRING may contain normal field width and padding information,
22576 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22577 so values can contain further %-escapes if they are define later in TABLE."
22578 (let ((tbl (copy-alist table))
22579 (case-fold-search nil)
22580 (pchg 0)
22581 re rpl)
22582 (dolist (e tbl)
22583 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22584 (when (and (cdr e) (string-match re (cdr e)))
22585 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22586 (safe "SREF"))
22587 (add-text-properties 0 3 (list 'sref sref) safe)
22588 (setcdr e (replace-match safe t t (cdr e)))))
22589 (while (string-match re string)
22590 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22591 (cdr e)))
22592 (setq string (replace-match rpl t t string))))
22593 (while (setq pchg (next-property-change pchg string))
22594 (let ((sref (get-text-property pchg 'sref string)))
22595 (when (and sref (string-match "SREF" string pchg))
22596 (setq string (replace-match sref t t string)))))
22597 string))
22599 (defun org-find-base-buffer-visiting (file)
22600 "Like `find-buffer-visiting' but always return the base buffer and
22601 not an indirect buffer."
22602 (let ((buf (or (get-file-buffer file)
22603 (find-buffer-visiting file))))
22604 (if buf
22605 (or (buffer-base-buffer buf) buf)
22606 nil)))
22608 ;;; TODO: Only called once, from ox-odt which should probably use
22609 ;;; org-export-inline-image-p or something.
22610 (defun org-file-image-p (file)
22611 "Return non-nil if FILE is an image."
22612 (save-match-data
22613 (string-match (image-file-name-regexp) file)))
22615 (defun org-get-cursor-date (&optional with-time)
22616 "Return the date at cursor in as a time.
22617 This works in the calendar and in the agenda, anywhere else it just
22618 returns the current time.
22619 If WITH-TIME is non-nil, returns the time of the event at point (in
22620 the agenda) or the current time of the day."
22621 (let (date day defd tp hod mod)
22622 (when with-time
22623 (setq tp (get-text-property (point) 'time))
22624 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22625 (setq hod (string-to-number (match-string 1 tp))
22626 mod (string-to-number (match-string 2 tp))))
22627 (or tp (let ((now (decode-time)))
22628 (setq hod (nth 2 now)
22629 mod (nth 1 now)))))
22630 (cond
22631 ((eq major-mode 'calendar-mode)
22632 (setq date (calendar-cursor-to-date)
22633 defd (encode-time 0 (or mod 0) (or hod 0)
22634 (nth 1 date) (nth 0 date) (nth 2 date))))
22635 ((eq major-mode 'org-agenda-mode)
22636 (setq day (get-text-property (point) 'day))
22637 (when day
22638 (setq date (calendar-gregorian-from-absolute day)
22639 defd (encode-time 0 (or mod 0) (or hod 0)
22640 (nth 1 date) (nth 0 date) (nth 2 date))))))
22641 (or defd (current-time))))
22643 (defun org-mark-subtree (&optional up)
22644 "Mark the current subtree.
22645 This puts point at the start of the current subtree, and mark at
22646 the end. If a numeric prefix UP is given, move up into the
22647 hierarchy of headlines by UP levels before marking the subtree."
22648 (interactive "P")
22649 (org-with-limited-levels
22650 (cond ((org-at-heading-p) (beginning-of-line))
22651 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22652 (t (outline-previous-visible-heading 1))))
22653 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22654 (if (called-interactively-p 'any)
22655 (call-interactively 'org-mark-element)
22656 (org-mark-element)))
22658 (defun org-file-newer-than-p (file time)
22659 "Non-nil if FILE is newer than TIME.
22660 FILE is a filename, as a string, TIME is a list of integers, as
22661 returned by, e.g., `current-time'."
22662 (and (file-exists-p file)
22663 ;; Only compare times up to whole seconds as some file-systems
22664 ;; (e.g. HFS+) do not retain any finer granularity. As
22665 ;; a consequence, make sure we return non-nil when the two
22666 ;; times are equal.
22667 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22668 (cl-subseq time 0 2)))))
22670 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22671 "Compile a SOURCE file using PROCESS.
22673 PROCESS is either a function or a list of shell commands, as
22674 strings. EXT is a file extension, without the leading dot, as
22675 a string. It is used to check if the process actually succeeded.
22677 PROCESS must create a file with the same base name and directory
22678 as SOURCE, but ending with EXT. The function then returns its
22679 filename. Otherwise, it raises an error. The error message can
22680 then be refined by providing string ERR-MSG, which is appended to
22681 the standard message.
22683 If PROCESS is a function, it is called with a single argument:
22684 the SOURCE file.
22686 If it is a list of commands, each of them is called using
22687 `shell-command'. By default, in each command, %b, %f, %F, %o and
22688 %O are replaced with, respectively, SOURCE base name, name, full
22689 name, directory and absolute output file name. It is possible,
22690 however, to use more place-holders by specifying them in optional
22691 argument SPEC, as an alist following the pattern
22693 (CHARACTER . REPLACEMENT-STRING).
22695 When PROCESS is a list of commands, optional argument LOG-BUF can
22696 be set to a buffer or a buffer name. `shell-command' then uses
22697 it for output."
22698 (let* ((base-name (file-name-base source))
22699 (full-name (file-truename source))
22700 (out-dir (or (file-name-directory source) "./"))
22701 (output (expand-file-name (concat base-name "." ext) out-dir))
22702 (time (current-time))
22703 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22704 (save-window-excursion
22705 (pcase process
22706 ((pred functionp) (funcall process (shell-quote-argument source)))
22707 ((pred consp)
22708 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22709 (spec (append spec
22710 `((?b . ,(shell-quote-argument base-name))
22711 (?f . ,(shell-quote-argument source))
22712 (?F . ,(shell-quote-argument full-name))
22713 (?o . ,(shell-quote-argument out-dir))
22714 (?O . ,(shell-quote-argument output))))))
22715 (dolist (command process)
22716 (shell-command (format-spec command spec) log-buf))))
22717 (_ (error "No valid command to process %S%s" source err-msg))))
22718 ;; Check for process failure. Output file is expected to be
22719 ;; located in the same directory as SOURCE.
22720 (unless (org-file-newer-than-p output time)
22721 (error (format "File %S wasn't produced%s" output err-msg)))
22722 output))
22724 ;;; Indentation
22726 (defvar org-element-greater-elements)
22727 (defun org--get-expected-indentation (element contentsp)
22728 "Expected indentation column for current line, according to ELEMENT.
22729 ELEMENT is an element containing point. CONTENTSP is non-nil
22730 when indentation is to be computed according to contents of
22731 ELEMENT."
22732 (let ((type (org-element-type element))
22733 (start (org-element-property :begin element))
22734 (post-affiliated (org-element-property :post-affiliated element)))
22735 (org-with-wide-buffer
22736 (cond
22737 (contentsp
22738 (cl-case type
22739 ((diary-sexp footnote-definition) 0)
22740 ((headline inlinetask nil)
22741 (if (not org-adapt-indentation) 0
22742 (let ((level (org-current-level)))
22743 (if level (1+ level) 0))))
22744 ((item plain-list) (org-list-item-body-column post-affiliated))
22746 (goto-char start)
22747 (org-get-indentation))))
22748 ((memq type '(headline inlinetask nil))
22749 (if (org-match-line "[ \t]*$")
22750 (org--get-expected-indentation element t)
22752 ((memq type '(diary-sexp footnote-definition)) 0)
22753 ;; First paragraph of a footnote definition or an item.
22754 ;; Indent like parent.
22755 ((< (line-beginning-position) start)
22756 (org--get-expected-indentation
22757 (org-element-property :parent element) t))
22758 ;; At first line: indent according to previous sibling, if any,
22759 ;; ignoring footnote definitions and inline tasks, or parent's
22760 ;; contents.
22761 ((= (line-beginning-position) start)
22762 (catch 'exit
22763 (while t
22764 (if (= (point-min) start) (throw 'exit 0)
22765 (goto-char (1- start))
22766 (let* ((previous (org-element-at-point))
22767 (parent previous))
22768 (while (and parent (<= (org-element-property :end parent) start))
22769 (setq previous parent
22770 parent (org-element-property :parent parent)))
22771 (cond
22772 ((not previous) (throw 'exit 0))
22773 ((> (org-element-property :end previous) start)
22774 (throw 'exit (org--get-expected-indentation previous t)))
22775 ((memq (org-element-type previous)
22776 '(footnote-definition inlinetask))
22777 (setq start (org-element-property :begin previous)))
22778 (t (goto-char (org-element-property :begin previous))
22779 (throw 'exit
22780 (if (bolp) (org-get-indentation)
22781 ;; At first paragraph in an item or
22782 ;; a footnote definition.
22783 (org--get-expected-indentation
22784 (org-element-property :parent previous) t))))))))))
22785 ;; Otherwise, move to the first non-blank line above.
22787 (beginning-of-line)
22788 (let ((pos (point)))
22789 (skip-chars-backward " \r\t\n")
22790 (cond
22791 ;; Two blank lines end a footnote definition or a plain
22792 ;; list. When we indent an empty line after them, the
22793 ;; containing list or footnote definition is over, so it
22794 ;; qualifies as a previous sibling. Therefore, we indent
22795 ;; like its first line.
22796 ((and (memq type '(footnote-definition plain-list))
22797 (> (count-lines (point) pos) 2))
22798 (goto-char start)
22799 (org-get-indentation))
22800 ;; Line above is the first one of a paragraph at the
22801 ;; beginning of an item or a footnote definition. Indent
22802 ;; like parent.
22803 ((< (line-beginning-position) start)
22804 (org--get-expected-indentation
22805 (org-element-property :parent element) t))
22806 ;; Line above is the beginning of an element, i.e., point
22807 ;; was originally on the blank lines between element's start
22808 ;; and contents.
22809 ((= (line-beginning-position) post-affiliated)
22810 (org--get-expected-indentation element t))
22811 ;; POS is after contents in a greater element. Indent like
22812 ;; the beginning of the element.
22813 ((and (memq type org-element-greater-elements)
22814 (let ((cend (org-element-property :contents-end element)))
22815 (and cend (<= cend pos))))
22816 ;; As a special case, if point is at the end of a footnote
22817 ;; definition or an item, indent like the very last element
22818 ;; within. If that last element is an item, indent like
22819 ;; its contents.
22820 (if (memq type '(footnote-definition item plain-list))
22821 (let ((last (org-element-at-point)))
22822 (goto-char pos)
22823 (org--get-expected-indentation
22824 last (eq (org-element-type last) 'item)))
22825 (goto-char start)
22826 (org-get-indentation)))
22827 ;; In any other case, indent like the current line.
22828 (t (org-get-indentation)))))))))
22830 (defun org--align-node-property ()
22831 "Align node property at point.
22832 Alignment is done according to `org-property-format', which see."
22833 (when (save-excursion
22834 (beginning-of-line)
22835 (looking-at org-property-re))
22836 (replace-match
22837 (concat (match-string 4)
22838 (org-trim
22839 (format org-property-format (match-string 1) (match-string 3))))
22840 t t)))
22842 (defun org-indent-line ()
22843 "Indent line depending on context.
22845 Indentation is done according to the following rules:
22847 - Footnote definitions, diary sexps, headlines and inline tasks
22848 have to start at column 0.
22850 - On the very first line of an element, consider, in order, the
22851 next rules until one matches:
22853 1. If there's a sibling element before, ignoring footnote
22854 definitions and inline tasks, indent like its first line.
22856 2. If element has a parent, indent like its contents. More
22857 precisely, if parent is an item, indent after the
22858 description part, if any, or the bullet (see
22859 `org-list-description-max-indent'). Else, indent like
22860 parent's first line.
22862 3. Otherwise, indent relatively to current level, if
22863 `org-adapt-indentation' is non-nil, or to left margin.
22865 - On a blank line at the end of an element, indent according to
22866 the type of the element. More precisely
22868 1. If element is a plain list, an item, or a footnote
22869 definition, indent like the very last element within.
22871 2. If element is a paragraph, indent like its last non blank
22872 line.
22874 3. Otherwise, indent like its very first line.
22876 - In the code part of a source block, use language major mode
22877 to indent current line if `org-src-tab-acts-natively' is
22878 non-nil. If it is nil, do nothing.
22880 - Otherwise, indent like the first non-blank line above.
22882 The function doesn't indent an item as it could break the whole
22883 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22884 `\\[org-shiftmetaright]'.
22886 Also align node properties according to `org-property-format'."
22887 (interactive)
22888 (cond
22889 (orgstruct-is-++
22890 (let ((indent-line-function
22891 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22892 (indent-according-to-mode)))
22893 ((org-at-heading-p) 'noindent)
22895 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22896 (type (org-element-type element)))
22897 (cond ((and (memq type '(plain-list item))
22898 (= (line-beginning-position)
22899 (org-element-property :post-affiliated element)))
22900 'noindent)
22901 ((and (eq type 'latex-environment)
22902 (>= (point) (org-element-property :post-affiliated element))
22903 (< (point) (org-with-wide-buffer
22904 (goto-char (org-element-property :end element))
22905 (skip-chars-backward " \r\t\n")
22906 (line-beginning-position 2))))
22907 'noindent)
22908 ((and (eq type 'src-block)
22909 org-src-tab-acts-natively
22910 (> (line-beginning-position)
22911 (org-element-property :post-affiliated element))
22912 (< (line-beginning-position)
22913 (org-with-wide-buffer
22914 (goto-char (org-element-property :end element))
22915 (skip-chars-backward " \r\t\n")
22916 (line-beginning-position))))
22917 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22919 (let ((column (org--get-expected-indentation element nil)))
22920 ;; Preserve current column.
22921 (if (<= (current-column) (current-indentation))
22922 (indent-line-to column)
22923 (save-excursion (indent-line-to column))))
22924 ;; Align node property. Also preserve current column.
22925 (when (eq type 'node-property)
22926 (let ((column (current-column)))
22927 (org--align-node-property)
22928 (org-move-to-column column)))))))))
22930 (defun org-indent-region (start end)
22931 "Indent each non-blank line in the region.
22932 Called from a program, START and END specify the region to
22933 indent. The function will not indent contents of example blocks,
22934 verse blocks and export blocks as leading white spaces are
22935 assumed to be significant there."
22936 (interactive "r")
22937 (save-excursion
22938 (goto-char start)
22939 (skip-chars-forward " \r\t\n")
22940 (unless (eobp) (beginning-of-line))
22941 (let ((indent-to
22942 (lambda (ind pos)
22943 ;; Set IND as indentation for all lines between point and
22944 ;; POS. Blank lines are ignored. Leave point after POS
22945 ;; once done.
22946 (let ((limit (copy-marker pos)))
22947 (while (< (point) limit)
22948 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22949 (forward-line))
22950 (set-marker limit nil))))
22951 (end (copy-marker end)))
22952 (while (< (point) end)
22953 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22954 (let* ((element (org-element-at-point))
22955 (type (org-element-type element))
22956 (element-end (copy-marker (org-element-property :end element)))
22957 (ind (org--get-expected-indentation element nil)))
22958 (cond
22959 ;; Element indented as a single block. Example blocks
22960 ;; preserving indentation are a special case since the
22961 ;; "contents" must not be indented whereas the block
22962 ;; boundaries can.
22963 ((or (memq type '(export-block latex-environment))
22964 (and (eq type 'example-block)
22965 (not
22966 (or org-src-preserve-indentation
22967 (org-element-property :preserve-indent element)))))
22968 (let ((offset (- ind (org-get-indentation))))
22969 (unless (zerop offset)
22970 (indent-rigidly (org-element-property :begin element)
22971 (org-element-property :end element)
22972 offset)))
22973 (goto-char element-end))
22974 ;; Elements indented line wise. Be sure to exclude
22975 ;; example blocks (preserving indentation) and source
22976 ;; blocks from this category as they are treated
22977 ;; specially later.
22978 ((or (memq type '(paragraph table table-row))
22979 (not (or (org-element-property :contents-begin element)
22980 (memq type '(example-block src-block)))))
22981 (when (eq type 'node-property)
22982 (org--align-node-property)
22983 (beginning-of-line))
22984 (funcall indent-to ind (min element-end end)))
22985 ;; Elements consisting of three parts: before the
22986 ;; contents, the contents, and after the contents. The
22987 ;; contents are treated specially, according to the
22988 ;; element type, or not indented at all. Other parts are
22989 ;; indented as a single block.
22991 (let* ((post (copy-marker
22992 (org-element-property :post-affiliated element)))
22993 (cbeg
22994 (copy-marker
22995 (cond
22996 ((not (org-element-property :contents-begin element))
22997 ;; Fake contents for source blocks.
22998 (org-with-wide-buffer
22999 (goto-char post)
23000 (line-beginning-position 2)))
23001 ((memq type '(footnote-definition item plain-list))
23002 ;; Contents in these elements could start on
23003 ;; the same line as the beginning of the
23004 ;; element. Make sure we start indenting
23005 ;; from the second line.
23006 (org-with-wide-buffer
23007 (goto-char post)
23008 (end-of-line)
23009 (skip-chars-forward " \r\t\n")
23010 (if (eobp) (point) (line-beginning-position))))
23011 (t (org-element-property :contents-begin element)))))
23012 (cend (copy-marker
23013 (or (org-element-property :contents-end element)
23014 ;; Fake contents for source blocks.
23015 (org-with-wide-buffer
23016 (goto-char element-end)
23017 (skip-chars-backward " \r\t\n")
23018 (line-beginning-position)))
23019 t)))
23020 ;; Do not change items indentation individually as it
23021 ;; might break the list as a whole. On the other
23022 ;; hand, when at a plain list, indent it as a whole.
23023 (cond ((eq type 'plain-list)
23024 (let ((offset (- ind (org-get-indentation))))
23025 (unless (zerop offset)
23026 (indent-rigidly (org-element-property :begin element)
23027 (org-element-property :end element)
23028 offset))
23029 (goto-char cbeg)))
23030 ((eq type 'item) (goto-char cbeg))
23031 (t (funcall indent-to ind (min cbeg end))))
23032 (when (< (point) end)
23033 (cl-case type
23034 ((example-block verse-block))
23035 (src-block
23036 ;; In a source block, indent source code
23037 ;; according to language major mode, but only if
23038 ;; `org-src-tab-acts-natively' is non-nil.
23039 (when (and (< (point) end) org-src-tab-acts-natively)
23040 (ignore-errors
23041 (org-babel-do-in-edit-buffer
23042 (indent-region (point-min) (point-max))))))
23043 (t (org-indent-region (point) (min cend end))))
23044 (goto-char (min cend end))
23045 (when (< (point) end)
23046 (funcall indent-to ind (min element-end end))))
23047 (set-marker post nil)
23048 (set-marker cbeg nil)
23049 (set-marker cend nil))))
23050 (set-marker element-end nil))))
23051 (set-marker end nil))))
23053 (defun org-indent-drawer ()
23054 "Indent the drawer at point."
23055 (interactive)
23056 (unless (save-excursion
23057 (beginning-of-line)
23058 (looking-at-p org-drawer-regexp))
23059 (user-error "Not at a drawer"))
23060 (let ((element (org-element-at-point)))
23061 (unless (memq (org-element-type element) '(drawer property-drawer))
23062 (user-error "Not at a drawer"))
23063 (org-with-wide-buffer
23064 (org-indent-region (org-element-property :begin element)
23065 (org-element-property :end element))))
23066 (message "Drawer at point indented"))
23068 (defun org-indent-block ()
23069 "Indent the block at point."
23070 (interactive)
23071 (unless (save-excursion
23072 (beginning-of-line)
23073 (let ((case-fold-search t))
23074 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23075 (user-error "Not at a block"))
23076 (let ((element (org-element-at-point)))
23077 (unless (memq (org-element-type element)
23078 '(comment-block center-block dynamic-block example-block
23079 export-block quote-block special-block
23080 src-block verse-block))
23081 (user-error "Not at a block"))
23082 (org-with-wide-buffer
23083 (org-indent-region (org-element-property :begin element)
23084 (org-element-property :end element))))
23085 (message "Block at point indented"))
23088 ;;; Filling
23090 ;; We use our own fill-paragraph and auto-fill functions.
23092 ;; `org-fill-paragraph' relies on adaptive filling and context
23093 ;; checking. Appropriate `fill-prefix' is computed with
23094 ;; `org-adaptive-fill-function'.
23096 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23097 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23098 ;; `org-adaptive-fill-function' value. Internally,
23099 ;; `org-comment-line-break-function' breaks the line.
23101 ;; `org-setup-filling' installs filling and auto-filling related
23102 ;; variables during `org-mode' initialization.
23104 (defvar org-element-paragraph-separate) ; org-element.el
23105 (defun org-setup-filling ()
23106 (require 'org-element)
23107 ;; Prevent auto-fill from inserting unwanted new items.
23108 (when (boundp 'fill-nobreak-predicate)
23109 (setq-local
23110 fill-nobreak-predicate
23111 (org-uniquify
23112 (append fill-nobreak-predicate
23113 '(org-fill-line-break-nobreak-p
23114 org-fill-paragraph-with-timestamp-nobreak-p)))))
23115 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23116 (setq-local paragraph-start paragraph-ending)
23117 (setq-local paragraph-separate paragraph-ending))
23118 (setq-local fill-paragraph-function 'org-fill-paragraph)
23119 (setq-local auto-fill-inhibit-regexp nil)
23120 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23121 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23122 (setq-local comment-line-break-function 'org-comment-line-break-function))
23124 (defun org-fill-line-break-nobreak-p ()
23125 "Non-nil when a new line at point would create an Org line break."
23126 (save-excursion
23127 (skip-chars-backward "[ \t]")
23128 (skip-chars-backward "\\\\")
23129 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23131 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23132 "Non-nil when a new line at point would split a timestamp."
23133 (and (org-at-timestamp-p t)
23134 (not (looking-at org-ts-regexp-both))))
23136 (declare-function message-in-body-p "message" ())
23137 (defvar orgtbl-line-start-regexp) ; From org-table.el
23138 (defun org-adaptive-fill-function ()
23139 "Compute a fill prefix for the current line.
23140 Return fill prefix, as a string, or nil if current line isn't
23141 meant to be filled. For convenience, if `adaptive-fill-regexp'
23142 matches in paragraphs or comments, use it."
23143 (catch 'exit
23144 (when (derived-mode-p 'message-mode)
23145 (save-excursion
23146 (beginning-of-line)
23147 (cond ((not (message-in-body-p)) (throw 'exit nil))
23148 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23149 ((looking-at message-cite-prefix-regexp)
23150 (throw 'exit (match-string-no-properties 0)))
23151 ((looking-at org-outline-regexp)
23152 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23153 (org-with-wide-buffer
23154 (unless (org-at-heading-p)
23155 (let* ((p (line-beginning-position))
23156 (element (save-excursion
23157 (beginning-of-line)
23158 (org-element-at-point)))
23159 (type (org-element-type element))
23160 (post-affiliated (org-element-property :post-affiliated element)))
23161 (unless (< p post-affiliated)
23162 (cl-case type
23163 (comment
23164 (save-excursion
23165 (beginning-of-line)
23166 (looking-at "[ \t]*")
23167 (concat (match-string 0) "# ")))
23168 (footnote-definition "")
23169 ((item plain-list)
23170 (make-string (org-list-item-body-column post-affiliated) ?\s))
23171 (paragraph
23172 ;; Fill prefix is usually the same as the current line,
23173 ;; unless the paragraph is at the beginning of an item.
23174 (let ((parent (org-element-property :parent element)))
23175 (save-excursion
23176 (beginning-of-line)
23177 (cond ((eq (org-element-type parent) 'item)
23178 (make-string (org-list-item-body-column
23179 (org-element-property :begin parent))
23180 ?\s))
23181 ((and adaptive-fill-regexp
23182 ;; Locally disable
23183 ;; `adaptive-fill-function' to let
23184 ;; `fill-context-prefix' handle
23185 ;; `adaptive-fill-regexp' variable.
23186 (let (adaptive-fill-function)
23187 (fill-context-prefix
23188 post-affiliated
23189 (org-element-property :end element)))))
23190 ((looking-at "[ \t]+") (match-string 0))
23191 (t "")))))
23192 (comment-block
23193 ;; Only fill contents if P is within block boundaries.
23194 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23195 (forward-line)
23196 (point)))
23197 (cend (save-excursion
23198 (goto-char (org-element-property :end element))
23199 (skip-chars-backward " \r\t\n")
23200 (line-beginning-position))))
23201 (when (and (>= p cbeg) (< p cend))
23202 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23203 (match-string 0)
23204 "")))))))))))
23206 (declare-function message-goto-body "message" ())
23207 (defvar message-cite-prefix-regexp) ; From message.el
23208 (defun org-fill-paragraph (&optional justify)
23209 "Fill element at point, when applicable.
23211 This function only applies to comment blocks, comments, example
23212 blocks and paragraphs. Also, as a special case, re-align table
23213 when point is at one.
23215 If JUSTIFY is non-nil (interactively, with prefix argument),
23216 justify as well. If `sentence-end-double-space' is non-nil, then
23217 period followed by one space does not end a sentence, so don't
23218 break a line there. The variable `fill-column' controls the
23219 width for filling.
23221 For convenience, when point is at a plain list, an item or
23222 a footnote definition, try to fill the first paragraph within."
23223 (interactive)
23224 (if (and (derived-mode-p 'message-mode)
23225 (or (not (message-in-body-p))
23226 (save-excursion (move-beginning-of-line 1)
23227 (looking-at message-cite-prefix-regexp))))
23228 ;; First ensure filling is correct in message-mode.
23229 (let ((fill-paragraph-function
23230 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23231 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23232 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23233 (paragraph-separate
23234 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23235 (fill-paragraph nil))
23236 (with-syntax-table org-mode-transpose-word-syntax-table
23237 ;; Move to end of line in order to get the first paragraph
23238 ;; within a plain list or a footnote definition.
23239 (let ((element (save-excursion
23240 (end-of-line)
23241 (or (ignore-errors (org-element-at-point))
23242 (user-error "An element cannot be parsed line %d"
23243 (line-number-at-pos (point)))))))
23244 ;; First check if point is in a blank line at the beginning of
23245 ;; the buffer. In that case, ignore filling.
23246 (cl-case (org-element-type element)
23247 ;; Use major mode filling function is src blocks.
23248 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23249 ;; Align Org tables, leave table.el tables as-is.
23250 (table-row (org-table-align) t)
23251 (table
23252 (when (eq (org-element-property :type element) 'org)
23253 (save-excursion
23254 (goto-char (org-element-property :post-affiliated element))
23255 (org-table-align)))
23257 (paragraph
23258 ;; Paragraphs may contain `line-break' type objects.
23259 (let ((beg (max (point-min)
23260 (org-element-property :contents-begin element)))
23261 (end (min (point-max)
23262 (org-element-property :contents-end element))))
23263 ;; Do nothing if point is at an affiliated keyword.
23264 (if (< (line-end-position) beg) t
23265 (when (derived-mode-p 'message-mode)
23266 ;; In `message-mode', do not fill following citation
23267 ;; in current paragraph nor text before message body.
23268 (let ((body-start (save-excursion (message-goto-body))))
23269 (when body-start (setq beg (max body-start beg))))
23270 (when (save-excursion
23271 (re-search-forward
23272 (concat "^" message-cite-prefix-regexp) end t))
23273 (setq end (match-beginning 0))))
23274 ;; Fill paragraph, taking line breaks into account.
23275 (save-excursion
23276 (goto-char beg)
23277 (let ((cuts (list beg)))
23278 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23279 (when (eq 'line-break
23280 (org-element-type
23281 (save-excursion (backward-char)
23282 (org-element-context))))
23283 (push (point) cuts)))
23284 (dolist (c (delq end cuts))
23285 (fill-region-as-paragraph c end justify)
23286 (setq end c))))
23287 t)))
23288 ;; Contents of `comment-block' type elements should be
23289 ;; filled as plain text, but only if point is within block
23290 ;; markers.
23291 (comment-block
23292 (let* ((case-fold-search t)
23293 (beg (save-excursion
23294 (goto-char (org-element-property :begin element))
23295 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23296 (forward-line)
23297 (point)))
23298 (end (save-excursion
23299 (goto-char (org-element-property :end element))
23300 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23301 (line-beginning-position))))
23302 (if (or (< (point) beg) (> (point) end)) t
23303 (fill-region-as-paragraph
23304 (save-excursion (end-of-line)
23305 (re-search-backward "^[ \t]*$" beg 'move)
23306 (line-beginning-position))
23307 (save-excursion (beginning-of-line)
23308 (re-search-forward "^[ \t]*$" end 'move)
23309 (line-beginning-position))
23310 justify))))
23311 ;; Fill comments.
23312 (comment
23313 (let ((begin (org-element-property :post-affiliated element))
23314 (end (org-element-property :end element)))
23315 (when (and (>= (point) begin) (<= (point) end))
23316 (let ((begin (save-excursion
23317 (end-of-line)
23318 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23319 (progn (forward-line) (point))
23320 begin)))
23321 (end (save-excursion
23322 (end-of-line)
23323 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23324 (1- (line-beginning-position))
23325 (skip-chars-backward " \r\t\n")
23326 (line-end-position)))))
23327 ;; Do not fill comments when at a blank line.
23328 (when (> end begin)
23329 (let ((fill-prefix
23330 (save-excursion
23331 (beginning-of-line)
23332 (looking-at "[ \t]*#")
23333 (let ((comment-prefix (match-string 0)))
23334 (goto-char (match-end 0))
23335 (if (looking-at adaptive-fill-regexp)
23336 (concat comment-prefix (match-string 0))
23337 (concat comment-prefix " "))))))
23338 (save-excursion
23339 (fill-region-as-paragraph begin end justify))))))
23341 ;; Ignore every other element.
23342 (otherwise t))))))
23344 (defun org-auto-fill-function ()
23345 "Auto-fill function."
23346 ;; Check if auto-filling is meaningful.
23347 (let ((fc (current-fill-column)))
23348 (when (and fc (> (current-column) fc))
23349 (let* ((fill-prefix (org-adaptive-fill-function))
23350 ;; Enforce empty fill prefix, if required. Otherwise, it
23351 ;; will be computed again.
23352 (adaptive-fill-mode (not (equal fill-prefix ""))))
23353 (when fill-prefix (do-auto-fill))))))
23355 (defun org-comment-line-break-function (&optional soft)
23356 "Break line at point and indent, continuing comment if within one.
23357 The inserted newline is marked hard if variable
23358 `use-hard-newlines' is true, unless optional argument SOFT is
23359 non-nil."
23360 (if soft (insert-and-inherit ?\n) (newline 1))
23361 (save-excursion (forward-char -1) (delete-horizontal-space))
23362 (delete-horizontal-space)
23363 (indent-to-left-margin)
23364 (insert-before-markers-and-inherit fill-prefix))
23367 ;;; Fixed Width Areas
23369 (defun org-toggle-fixed-width ()
23370 "Toggle fixed-width markup.
23372 Add or remove fixed-width markup on current line, whenever it
23373 makes sense. Return an error otherwise.
23375 If a region is active and if it contains only fixed-width areas
23376 or blank lines, remove all fixed-width markup in it. If the
23377 region contains anything else, convert all non-fixed-width lines
23378 to fixed-width ones.
23380 Blank lines at the end of the region are ignored unless the
23381 region only contains such lines."
23382 (interactive)
23383 (if (not (org-region-active-p))
23384 ;; No region:
23386 ;; Remove fixed width marker only in a fixed-with element.
23388 ;; Add fixed width maker in paragraphs, in blank lines after
23389 ;; elements or at the beginning of a headline or an inlinetask,
23390 ;; and before any one-line elements (e.g., a clock).
23391 (progn
23392 (beginning-of-line)
23393 (let* ((element (org-element-at-point))
23394 (type (org-element-type element)))
23395 (cond
23396 ((and (eq type 'fixed-width)
23397 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23398 (replace-match
23399 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23400 ((and (memq type '(babel-call clock comment diary-sexp headline
23401 horizontal-rule keyword paragraph
23402 planning))
23403 (<= (org-element-property :post-affiliated element) (point)))
23404 (skip-chars-forward " \t")
23405 (insert ": "))
23406 ((and (looking-at-p "[ \t]*$")
23407 (or (eq type 'inlinetask)
23408 (save-excursion
23409 (skip-chars-forward " \r\t\n")
23410 (<= (org-element-property :end element) (point)))))
23411 (delete-region (point) (line-end-position))
23412 (org-indent-line)
23413 (insert ": "))
23414 (t (user-error "Cannot insert a fixed-width line here")))))
23415 ;; Region active.
23416 (let* ((begin (save-excursion
23417 (goto-char (region-beginning))
23418 (line-beginning-position)))
23419 (end (copy-marker
23420 (save-excursion
23421 (goto-char (region-end))
23422 (unless (eolp) (beginning-of-line))
23423 (if (save-excursion (re-search-backward "\\S-" begin t))
23424 (progn (skip-chars-backward " \r\t\n") (point))
23425 (point)))))
23426 (all-fixed-width-p
23427 (catch 'not-all-p
23428 (save-excursion
23429 (goto-char begin)
23430 (skip-chars-forward " \r\t\n")
23431 (when (eobp) (throw 'not-all-p nil))
23432 (while (< (point) end)
23433 (let ((element (org-element-at-point)))
23434 (if (eq (org-element-type element) 'fixed-width)
23435 (goto-char (org-element-property :end element))
23436 (throw 'not-all-p nil))))
23437 t))))
23438 (if all-fixed-width-p
23439 (save-excursion
23440 (goto-char begin)
23441 (while (< (point) end)
23442 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23443 (replace-match
23444 "" nil nil nil
23445 (if (= (line-end-position) (match-end 0)) 0 1)))
23446 (forward-line)))
23447 (let ((min-ind (point-max)))
23448 ;; Find minimum indentation across all lines.
23449 (save-excursion
23450 (goto-char begin)
23451 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23452 (setq min-ind 0)
23453 (catch 'zerop
23454 (while (< (point) end)
23455 (unless (looking-at-p "[ \t]*$")
23456 (let ((ind (org-get-indentation)))
23457 (setq min-ind (min min-ind ind))
23458 (when (zerop ind) (throw 'zerop t))))
23459 (forward-line)))))
23460 ;; Loop over all lines and add fixed-width markup everywhere
23461 ;; but in fixed-width lines.
23462 (save-excursion
23463 (goto-char begin)
23464 (while (< (point) end)
23465 (cond
23466 ((org-at-heading-p)
23467 (insert ": ")
23468 (forward-line)
23469 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23470 (insert ":")
23471 (forward-line)))
23472 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23473 (let* ((element (org-element-at-point))
23474 (element-end (org-element-property :end element)))
23475 (if (eq (org-element-type element) 'fixed-width)
23476 (progn (goto-char element-end)
23477 (skip-chars-backward " \r\t\n")
23478 (forward-line))
23479 (let ((limit (min end element-end)))
23480 (while (< (point) limit)
23481 (org-move-to-column min-ind t)
23482 (insert ": ")
23483 (forward-line))))))
23485 (org-move-to-column min-ind t)
23486 (insert ": ")
23487 (forward-line)))))))
23488 (set-marker end nil))))
23491 ;;; Comments
23493 ;; Org comments syntax is quite complex. It requires the entire line
23494 ;; to be just a comment. Also, even with the right syntax at the
23495 ;; beginning of line, some some elements (i.e. verse-block or
23496 ;; example-block) don't accept comments. Usual Emacs comment commands
23497 ;; cannot cope with those requirements. Therefore, Org replaces them.
23499 ;; Org still relies on `comment-dwim', but cannot trust
23500 ;; `comment-only-p'. So, `comment-region-function' and
23501 ;; `uncomment-region-function' both point
23502 ;; to`org-comment-or-uncomment-region'. Eventually,
23503 ;; `org-insert-comment' takes care of insertion of comments at the
23504 ;; beginning of line.
23506 ;; `org-setup-comments-handling' install comments related variables
23507 ;; during `org-mode' initialization.
23509 (defun org-setup-comments-handling ()
23510 (interactive)
23511 (setq-local comment-use-syntax nil)
23512 (setq-local comment-start "# ")
23513 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23514 (setq-local comment-insert-comment-function 'org-insert-comment)
23515 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23516 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23518 (defun org-insert-comment ()
23519 "Insert an empty comment above current line.
23520 If the line is empty, insert comment at its beginning. When
23521 point is within a source block, comment according to the related
23522 major mode."
23523 (if (let ((element (org-element-at-point)))
23524 (and (eq (org-element-type element) 'src-block)
23525 (< (save-excursion
23526 (goto-char (org-element-property :post-affiliated element))
23527 (line-end-position))
23528 (point))
23529 (> (save-excursion
23530 (goto-char (org-element-property :end element))
23531 (skip-chars-backward " \r\t\n")
23532 (line-beginning-position))
23533 (point))))
23534 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23535 (beginning-of-line)
23536 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23537 (open-line 1))
23538 (org-indent-line)
23539 (insert "# ")))
23541 (defvar comment-empty-lines) ; From newcomment.el.
23542 (defun org-comment-or-uncomment-region (beg end &rest _)
23543 "Comment or uncomment each non-blank line in the region.
23544 Uncomment each non-blank line between BEG and END if it only
23545 contains commented lines. Otherwise, comment them. If region is
23546 strictly within a source block, use appropriate comment syntax."
23547 (if (let ((element (org-element-at-point)))
23548 (and (eq (org-element-type element) 'src-block)
23549 (< (save-excursion
23550 (goto-char (org-element-property :post-affiliated element))
23551 (line-end-position))
23552 beg)
23553 (>= (save-excursion
23554 (goto-char (org-element-property :end element))
23555 (skip-chars-backward " \r\t\n")
23556 (line-beginning-position))
23557 end)))
23558 ;; Translate region boundaries for the Org buffer to the source
23559 ;; buffer.
23560 (let ((offset (- end beg)))
23561 (save-excursion
23562 (goto-char beg)
23563 (org-babel-do-in-edit-buffer
23564 (comment-or-uncomment-region (point) (+ offset (point))))))
23565 (save-restriction
23566 ;; Restrict region
23567 (narrow-to-region (save-excursion (goto-char beg)
23568 (skip-chars-forward " \r\t\n" end)
23569 (line-beginning-position))
23570 (save-excursion (goto-char end)
23571 (skip-chars-backward " \r\t\n" beg)
23572 (line-end-position)))
23573 (let ((uncommentp
23574 ;; UNCOMMENTP is non-nil when every non blank line between
23575 ;; BEG and END is a comment.
23576 (save-excursion
23577 (goto-char (point-min))
23578 (while (and (not (eobp))
23579 (let ((element (org-element-at-point)))
23580 (and (eq (org-element-type element) 'comment)
23581 (goto-char (min (point-max)
23582 (org-element-property
23583 :end element)))))))
23584 (eobp))))
23585 (if uncommentp
23586 ;; Only blank lines and comments in region: uncomment it.
23587 (save-excursion
23588 (goto-char (point-min))
23589 (while (not (eobp))
23590 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23591 (replace-match "" nil nil nil 1))
23592 (forward-line)))
23593 ;; Comment each line in region.
23594 (let ((min-indent (point-max)))
23595 ;; First find the minimum indentation across all lines.
23596 (save-excursion
23597 (goto-char (point-min))
23598 (while (and (not (eobp)) (not (zerop min-indent)))
23599 (unless (looking-at "[ \t]*$")
23600 (setq min-indent (min min-indent (current-indentation))))
23601 (forward-line)))
23602 ;; Then loop over all lines.
23603 (save-excursion
23604 (goto-char (point-min))
23605 (while (not (eobp))
23606 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23607 ;; Don't get fooled by invisible text (e.g. link path)
23608 ;; when moving to column MIN-INDENT.
23609 (let ((buffer-invisibility-spec nil))
23610 (org-move-to-column min-indent t))
23611 (insert comment-start))
23612 (forward-line)))))))))
23614 (defun org-comment-dwim (_arg)
23615 "Call `comment-dwim' within a source edit buffer if needed."
23616 (interactive "*P")
23617 (if (org-in-src-block-p)
23618 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23619 (call-interactively 'comment-dwim)))
23622 ;;; Timestamps API
23624 ;; This section contains tools to operate on timestamp objects, as
23625 ;; returned by, e.g. `org-element-context'.
23627 (defun org-timestamp--to-internal-time (timestamp &optional end)
23628 "Encode TIMESTAMP object into Emacs internal time.
23629 Use end of date range or time range when END is non-nil."
23630 (apply #'encode-time
23631 (cons 0
23632 (mapcar
23633 (lambda (prop) (or (org-element-property prop timestamp) 0))
23634 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23635 '(:minute-start :hour-start :day-start :month-start
23636 :year-start))))))
23638 (defun org-timestamp-has-time-p (timestamp)
23639 "Non-nil when TIMESTAMP has a time specified."
23640 (org-element-property :hour-start timestamp))
23642 (defun org-timestamp-format (timestamp format &optional end utc)
23643 "Format a TIMESTAMP object into a string.
23645 FORMAT is a format specifier to be passed to
23646 `format-time-string'.
23648 When optional argument END is non-nil, use end of date-range or
23649 time-range, if possible.
23651 When optional argument UTC is non-nil, time will be expressed as
23652 Universal Time."
23653 (format-time-string
23654 format (org-timestamp--to-internal-time timestamp end)
23655 (and utc t)))
23657 (defun org-timestamp-split-range (timestamp &optional end)
23658 "Extract a TIMESTAMP object from a date or time range.
23660 END, when non-nil, means extract the end of the range.
23661 Otherwise, extract its start.
23663 Return a new timestamp object."
23664 (let ((type (org-element-property :type timestamp)))
23665 (if (memq type '(active inactive diary)) timestamp
23666 (let ((split-ts (org-element-copy timestamp)))
23667 ;; Set new type.
23668 (org-element-put-property
23669 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23670 ;; Copy start properties over end properties if END is
23671 ;; non-nil. Otherwise, copy end properties over `start' ones.
23672 (let ((p-alist '((:minute-start . :minute-end)
23673 (:hour-start . :hour-end)
23674 (:day-start . :day-end)
23675 (:month-start . :month-end)
23676 (:year-start . :year-end))))
23677 (dolist (p-cell p-alist)
23678 (org-element-put-property
23679 split-ts
23680 (funcall (if end #'car #'cdr) p-cell)
23681 (org-element-property
23682 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23683 ;; Eventually refresh `:raw-value'.
23684 (org-element-put-property split-ts :raw-value nil)
23685 (org-element-put-property
23686 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23688 (defun org-timestamp-translate (timestamp &optional boundary)
23689 "Translate TIMESTAMP object to custom format.
23691 Format string is defined in `org-time-stamp-custom-formats',
23692 which see.
23694 When optional argument BOUNDARY is non-nil, it is either the
23695 symbol `start' or `end'. In this case, only translate the
23696 starting or ending part of TIMESTAMP if it is a date or time
23697 range. Otherwise, translate both parts.
23699 Return timestamp as-is if `org-display-custom-times' is nil or if
23700 it has a `diary' type."
23701 (let ((type (org-element-property :type timestamp)))
23702 (if (or (not org-display-custom-times) (eq type 'diary))
23703 (org-element-interpret-data timestamp)
23704 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23705 org-time-stamp-custom-formats)))
23706 (if (and (not boundary) (memq type '(active-range inactive-range)))
23707 (concat (org-timestamp-format timestamp fmt)
23708 "--"
23709 (org-timestamp-format timestamp fmt t))
23710 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23714 ;;; Other stuff.
23716 (defvar reftex-docstruct-symbol)
23717 (defvar org--rds)
23719 (defun org-reftex-citation ()
23720 "Use reftex-citation to insert a citation into the buffer.
23721 This looks for a line like
23723 #+BIBLIOGRAPHY: foo plain option:-d
23725 and derives from it that foo.bib is the bibliography file relevant
23726 for this document. It then installs the necessary environment for RefTeX
23727 to work in this buffer and calls `reftex-citation' to insert a citation
23728 into the buffer.
23730 Export of such citations to both LaTeX and HTML is handled by the contributed
23731 package ox-bibtex by Taru Karttunen."
23732 (interactive)
23733 (let ((reftex-docstruct-symbol 'org--rds)
23734 org--rds bib)
23735 (org-with-wide-buffer
23736 (let ((case-fold-search t)
23737 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23738 (if (not (save-excursion
23739 (or (re-search-forward re nil t)
23740 (re-search-backward re nil t))))
23741 (user-error "No bibliography defined in file")
23742 (setq bib (concat (match-string 1) ".bib")
23743 org--rds (list (list 'bib bib))))))
23744 (call-interactively 'reftex-citation)))
23746 ;;;; Functions extending outline functionality
23748 (defun org-beginning-of-line (&optional n)
23749 "Go to the beginning of the current visible line.
23751 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23752 tags on the first attempt, and only move to after the tags when
23753 the cursor is already beyond the end of the headline.
23755 With argument N not nil or 1, move forward N - 1 lines first."
23756 (interactive "^p")
23757 (let ((origin (point))
23758 (special (pcase org-special-ctrl-a/e
23759 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23760 deactivate-mark)
23761 ;; First move to a visible line.
23762 (if (bound-and-true-p visual-line-mode)
23763 (beginning-of-visual-line n)
23764 (move-beginning-of-line n)
23765 ;; `move-beginning-of-line' may leave point after invisible
23766 ;; characters if line starts with such of these (e.g., with
23767 ;; a link at column 0). Really move to the beginning of the
23768 ;; current visible line.
23769 (beginning-of-line))
23770 (cond
23771 ;; No special behavior. Point is already at the beginning of
23772 ;; a line, logical or visual.
23773 ((not special))
23774 ;; `beginning-of-visual-line' left point before logical beginning
23775 ;; of line: point is at the beginning of a visual line. Bail
23776 ;; out.
23777 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23778 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23779 ;; At a headline, special position is before the title, but
23780 ;; after any TODO keyword or priority cookie.
23781 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23782 (line-end-position)))
23783 (bol (point)))
23784 (if (eq special 'reversed)
23785 (when (and (= origin bol) (eq last-command this-command))
23786 (goto-char refpos))
23787 (when (or (> origin refpos) (= origin bol))
23788 (goto-char refpos)))))
23789 ((and (looking-at org-list-full-item-re)
23790 (memq (org-element-type (save-match-data (org-element-at-point)))
23791 '(item plain-list)))
23792 ;; Set special position at first white space character after
23793 ;; bullet, and check-box, if any.
23794 (let ((after-bullet
23795 (let ((box (match-end 3)))
23796 (cond ((not box) (match-end 1))
23797 ((eq (char-after box) ?\s) (1+ box))
23798 (t box)))))
23799 (if (eq special 'reversed)
23800 (when (and (= (point) origin) (eq last-command this-command))
23801 (goto-char after-bullet))
23802 (when (or (> origin after-bullet) (= (point) origin))
23803 (goto-char after-bullet)))))
23804 ;; No special context. Point is already at beginning of line.
23805 (t nil))))
23807 (defun org-end-of-line (&optional n)
23808 "Go to the end of the line, but before ellipsis, if any.
23810 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23811 tags on the first attempt, and only move to after the tags when
23812 the cursor is already beyond the end of the headline.
23814 With argument N not nil or 1, move forward N - 1 lines first."
23815 (interactive "^p")
23816 (let ((origin (point))
23817 (special (pcase org-special-ctrl-a/e
23818 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23819 deactivate-mark)
23820 ;; First move to a visible line.
23821 (if (bound-and-true-p visual-line-mode)
23822 (beginning-of-visual-line n)
23823 (move-beginning-of-line n))
23824 (cond
23825 ;; At a headline, with tags.
23826 ((and special
23827 (save-excursion
23828 (beginning-of-line)
23829 (let ((case-fold-search nil))
23830 (looking-at org-complex-heading-regexp)))
23831 (match-end 5))
23832 (let ((tags (save-excursion
23833 (goto-char (match-beginning 5))
23834 (skip-chars-backward " \t")
23835 (point)))
23836 (visual-end (and (bound-and-true-p visual-line-mode)
23837 (save-excursion
23838 (end-of-visual-line)
23839 (point)))))
23840 ;; If `end-of-visual-line' brings us before end of line or
23841 ;; even tags, i.e., the headline spans over multiple visual
23842 ;; lines, move there.
23843 (cond ((and visual-end
23844 (< visual-end tags)
23845 (<= origin visual-end))
23846 (goto-char visual-end))
23847 ((eq special 'reversed)
23848 (if (and (= origin (line-end-position))
23849 (eq this-command last-command))
23850 (goto-char tags)
23851 (end-of-line)))
23853 (if (or (< origin tags) (= origin (line-end-position)))
23854 (goto-char tags)
23855 (end-of-line))))))
23856 ((bound-and-true-p visual-line-mode)
23857 (let ((bol (line-beginning-position)))
23858 (end-of-visual-line)
23859 ;; If `end-of-visual-line' gets us past the ellipsis at the
23860 ;; end of a line, backtrack and use `end-of-line' instead.
23861 (when (/= bol (line-beginning-position))
23862 (goto-char bol)
23863 (end-of-line))))
23864 (t (end-of-line)))))
23866 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23867 (define-key org-mode-map "\C-e" 'org-end-of-line)
23869 (defun org-backward-sentence (&optional _arg)
23870 "Go to beginning of sentence, or beginning of table field.
23871 This will call `backward-sentence' or `org-table-beginning-of-field',
23872 depending on context."
23873 (interactive)
23874 (let* ((element (org-element-at-point))
23875 (contents-begin (org-element-property :contents-begin element))
23876 (table (org-element-lineage element '(table) t)))
23877 (if (and table
23878 (> (point) contents-begin)
23879 (<= (point) (org-element-property :contents-end table)))
23880 (call-interactively #'org-table-beginning-of-field)
23881 (save-restriction
23882 (when (and contents-begin
23883 (< (point-min) contents-begin)
23884 (> (point) contents-begin))
23885 (narrow-to-region contents-begin
23886 (org-element-property :contents-end element)))
23887 (call-interactively #'backward-sentence)))))
23889 (defun org-forward-sentence (&optional _arg)
23890 "Go to end of sentence, or end of table field.
23891 This will call `forward-sentence' or `org-table-end-of-field',
23892 depending on context."
23893 (interactive)
23894 (let* ((element (org-element-at-point))
23895 (contents-end (org-element-property :contents-end element))
23896 (table (org-element-lineage element '(table) t)))
23897 (if (and table
23898 (>= (point) (org-element-property :contents-begin table))
23899 (< (point) contents-end))
23900 (call-interactively #'org-table-end-of-field)
23901 (save-restriction
23902 (when (and contents-end
23903 (> (point-max) contents-end)
23904 ;; Skip blank lines between elements.
23905 (< (org-element-property :end element)
23906 (save-excursion (goto-char contents-end)
23907 (skip-chars-forward " \r\t\n"))))
23908 (narrow-to-region (org-element-property :contents-begin element)
23909 contents-end))
23910 (call-interactively #'forward-sentence)))))
23912 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23913 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23915 (defun org-kill-line (&optional _arg)
23916 "Kill line, to tags or end of line."
23917 (interactive)
23918 (cond
23919 ((or (not org-special-ctrl-k)
23920 (bolp)
23921 (not (org-at-heading-p)))
23922 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23923 org-ctrl-k-protect-subtree
23924 (or (eq org-ctrl-k-protect-subtree 'error)
23925 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23926 (user-error "C-k aborted as it would kill a hidden subtree"))
23927 (call-interactively
23928 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23929 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23930 (kill-region (point) (match-beginning 1))
23931 (org-set-tags nil t))
23932 (t (kill-region (point) (point-at-eol)))))
23934 (define-key org-mode-map "\C-k" 'org-kill-line)
23936 (defun org-yank (&optional arg)
23937 "Yank. If the kill is a subtree, treat it specially.
23938 This command will look at the current kill and check if is a single
23939 subtree, or a series of subtrees[1]. If it passes the test, and if the
23940 cursor is at the beginning of a line or after the stars of a currently
23941 empty headline, then the yank is handled specially. How exactly depends
23942 on the value of the following variables.
23944 `org-yank-folded-subtrees'
23945 By default, this variable is non-nil, which results in
23946 subtree(s) being folded after insertion, except if doing so
23947 would swallow text after the yanked text.
23949 `org-yank-adjusted-subtrees'
23950 When non-nil (the default value is nil), the subtree will be
23951 promoted or demoted in order to fit into the local outline tree
23952 structure, which means that the level will be adjusted so that it
23953 becomes the smaller one of the two *visible* surrounding headings.
23955 Any prefix to this command will cause `yank' to be called directly with
23956 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23957 will just
23958 plainly yank the text as it is.
23960 \[1] The test checks if the first non-white line is a heading
23961 and if there are no other headings with fewer stars."
23962 (interactive "P")
23963 (org-yank-generic 'yank arg))
23965 (defun org-yank-generic (command arg)
23966 "Perform some yank-like command.
23968 This function implements the behavior described in the `org-yank'
23969 documentation. However, it has been generalized to work for any
23970 interactive command with similar behavior."
23972 ;; pretend to be command COMMAND
23973 (setq this-command command)
23975 (if arg
23976 (call-interactively command)
23978 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23979 (and (org-kill-is-subtree-p)
23980 (or (bolp)
23981 (and (looking-at "[ \t]*$")
23982 (string-match
23983 "\\`\\*+\\'"
23984 (buffer-substring (point-at-bol) (point)))))))
23985 swallowp)
23986 (cond
23987 ((and subtreep org-yank-folded-subtrees)
23988 (let ((beg (point))
23989 end)
23990 (if (and subtreep org-yank-adjusted-subtrees)
23991 (org-paste-subtree nil nil 'for-yank)
23992 (call-interactively command))
23994 (setq end (point))
23995 (goto-char beg)
23996 (when (and (bolp) subtreep
23997 (not (setq swallowp
23998 (org-yank-folding-would-swallow-text beg end))))
23999 (org-with-limited-levels
24000 (or (looking-at org-outline-regexp)
24001 (re-search-forward org-outline-regexp-bol end t))
24002 (while (and (< (point) end) (looking-at org-outline-regexp))
24003 (outline-hide-subtree)
24004 (org-cycle-show-empty-lines 'folded)
24005 (condition-case nil
24006 (outline-forward-same-level 1)
24007 (error (goto-char end))))))
24008 (when swallowp
24009 (message
24010 "Inserted text not folded because that would swallow text"))
24012 (goto-char end)
24013 (skip-chars-forward " \t\n\r")
24014 (beginning-of-line 1)
24015 (push-mark beg 'nomsg)))
24016 ((and subtreep org-yank-adjusted-subtrees)
24017 (let ((beg (point-at-bol)))
24018 (org-paste-subtree nil nil 'for-yank)
24019 (push-mark beg 'nomsg)))
24021 (call-interactively command))))))
24023 (defun org-yank-folding-would-swallow-text (beg end)
24024 "Would hide-subtree at BEG swallow any text after END?"
24025 (let (level)
24026 (org-with-limited-levels
24027 (save-excursion
24028 (goto-char beg)
24029 (when (or (looking-at org-outline-regexp)
24030 (re-search-forward org-outline-regexp-bol end t))
24031 (setq level (org-outline-level)))
24032 (goto-char end)
24033 (skip-chars-forward " \t\r\n\v\f")
24034 (not (or (eobp)
24035 (and (bolp) (looking-at-p org-outline-regexp)
24036 (<= (org-outline-level) level))))))))
24038 (define-key org-mode-map "\C-y" 'org-yank)
24040 (defun org-truely-invisible-p ()
24041 "Check if point is at a character currently not visible.
24042 This version does not only check the character property, but also
24043 `visible-mode'."
24044 (unless (bound-and-true-p visible-mode)
24045 (org-invisible-p)))
24047 (defun org-invisible-p2 ()
24048 "Check if point is at a character currently not visible.
24050 If the point is at EOL (and not at the beginning of a buffer too),
24051 move it back by one char before doing this check."
24052 (save-excursion
24053 (when (and (eolp) (not (bobp)))
24054 (backward-char 1))
24055 (org-invisible-p)))
24057 (defun org-back-to-heading (&optional invisible-ok)
24058 "Call `outline-back-to-heading', but provide a better error message."
24059 (condition-case nil
24060 (outline-back-to-heading invisible-ok)
24061 (error (error "Before first headline at position %d in buffer %s"
24062 (point) (current-buffer)))))
24064 (defun org-before-first-heading-p ()
24065 "Before first heading?"
24066 (save-excursion
24067 (end-of-line)
24068 (null (re-search-backward org-outline-regexp-bol nil t))))
24070 (defun org-at-heading-p (&optional ignored)
24071 (outline-on-heading-p t))
24073 (defun org-in-commented-heading-p (&optional no-inheritance)
24074 "Non-nil if point is under a commented heading.
24075 This function also checks ancestors of the current headline,
24076 unless optional argument NO-INHERITANCE is non-nil."
24077 (cond
24078 ((org-before-first-heading-p) nil)
24079 ((let ((headline (nth 4 (org-heading-components))))
24080 (and headline
24081 (let ((case-fold-search nil))
24082 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24083 headline)))))
24084 (no-inheritance nil)
24086 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24088 (defun org-at-comment-p nil
24089 "Is cursor in a commented line?"
24090 (save-excursion
24091 (save-match-data
24092 (beginning-of-line)
24093 (looking-at "^[ \t]*# "))))
24095 (defun org-at-drawer-p nil
24096 "Is cursor at a drawer keyword?"
24097 (save-excursion
24098 (move-beginning-of-line 1)
24099 (looking-at org-drawer-regexp)))
24101 (defun org-at-block-p nil
24102 "Is cursor at a block keyword?"
24103 (save-excursion
24104 (move-beginning-of-line 1)
24105 (looking-at org-block-regexp)))
24107 (defun org-point-at-end-of-empty-headline ()
24108 "If point is at the end of an empty headline, return t, else nil.
24109 If the heading only contains a TODO keyword, it is still still considered
24110 empty."
24111 (let ((case-fold-search nil))
24112 (and (looking-at "[ \t]*$")
24113 org-todo-line-regexp
24114 (save-excursion
24115 (beginning-of-line)
24116 (looking-at org-todo-line-regexp)
24117 (string= (match-string 3) "")))))
24119 (defun org-at-heading-or-item-p ()
24120 (or (org-at-heading-p) (org-at-item-p)))
24122 (defun org-at-target-p ()
24123 (or (org-in-regexp org-radio-target-regexp)
24124 (org-in-regexp org-target-regexp)))
24125 ;; Compatibility alias with Org versions < 7.8.03
24126 (defalias 'org-on-target-p 'org-at-target-p)
24128 (defun org-up-heading-all (arg)
24129 "Move to the heading line of which the present line is a subheading.
24130 This function considers both visible and invisible heading lines.
24131 With argument, move up ARG levels."
24132 (outline-up-heading arg t))
24134 (defun org-up-heading-safe ()
24135 "Move to the heading line of which the present line is a subheading.
24136 This version will not throw an error. It will return the level of the
24137 headline found, or nil if no higher level is found.
24139 Also, this function will be a lot faster than `outline-up-heading',
24140 because it relies on stars being the outline starters. This can really
24141 make a significant difference in outlines with very many siblings."
24142 (when (ignore-errors (org-back-to-heading t))
24143 (let ((level-up (1- (funcall outline-level))))
24144 (and (> level-up 0)
24145 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24146 (funcall outline-level)))))
24148 (defun org-first-sibling-p ()
24149 "Is this heading the first child of its parents?"
24150 (interactive)
24151 (let ((re org-outline-regexp-bol)
24152 level l)
24153 (unless (org-at-heading-p t)
24154 (user-error "Not at a heading"))
24155 (setq level (funcall outline-level))
24156 (save-excursion
24157 (if (not (re-search-backward re nil t))
24159 (setq l (funcall outline-level))
24160 (< l level)))))
24162 (defun org-goto-sibling (&optional previous)
24163 "Goto the next sibling, even if it is invisible.
24164 When PREVIOUS is set, go to the previous sibling instead. Returns t
24165 when a sibling was found. When none is found, return nil and don't
24166 move point."
24167 (let ((fun (if previous 're-search-backward 're-search-forward))
24168 (pos (point))
24169 (re org-outline-regexp-bol)
24170 level l)
24171 (when (ignore-errors (org-back-to-heading t))
24172 (setq level (funcall outline-level))
24173 (catch 'exit
24174 (or previous (forward-char 1))
24175 (while (funcall fun re nil t)
24176 (setq l (funcall outline-level))
24177 (when (< l level) (goto-char pos) (throw 'exit nil))
24178 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24179 (goto-char pos)
24180 nil))))
24182 (defun org-show-siblings ()
24183 "Show all siblings of the current headline."
24184 (save-excursion
24185 (while (org-goto-sibling) (org-flag-heading nil)))
24186 (save-excursion
24187 (while (org-goto-sibling 'previous)
24188 (org-flag-heading nil))))
24190 (defun org-goto-first-child ()
24191 "Goto the first child, even if it is invisible.
24192 Return t when a child was found. Otherwise don't move point and
24193 return nil."
24194 (let (level (pos (point)) (re org-outline-regexp-bol))
24195 (when (ignore-errors (org-back-to-heading t))
24196 (setq level (outline-level))
24197 (forward-char 1)
24198 (if (and (re-search-forward re nil t) (> (outline-level) level))
24199 (progn (goto-char (match-beginning 0)) t)
24200 (goto-char pos) nil))))
24202 (defun org-show-hidden-entry ()
24203 "Show an entry where even the heading is hidden."
24204 (save-excursion
24205 (org-show-entry)))
24207 (defun org-flag-heading (flag &optional entry)
24208 "Flag the current heading. FLAG non-nil means make invisible.
24209 When ENTRY is non-nil, show the entire entry."
24210 (save-excursion
24211 (org-back-to-heading t)
24212 ;; Check if we should show the entire entry
24213 (if entry
24214 (progn
24215 (org-show-entry)
24216 (save-excursion
24217 (and (outline-next-heading)
24218 (org-flag-heading nil))))
24219 (outline-flag-region (max (point-min) (1- (point)))
24220 (save-excursion (outline-end-of-heading) (point))
24221 flag))))
24223 (defun org-get-next-sibling ()
24224 "Move to next heading of the same level, and return point.
24225 If there is no such heading, return nil.
24226 This is like outline-next-sibling, but invisible headings are ok."
24227 (let ((level (funcall outline-level)))
24228 (outline-next-heading)
24229 (while (and (not (eobp)) (> (funcall outline-level) level))
24230 (outline-next-heading))
24231 (unless (or (eobp) (< (funcall outline-level) level))
24232 (point))))
24234 (defun org-get-last-sibling ()
24235 "Move to previous heading of the same level, and return point.
24236 If there is no such heading, return nil."
24237 (let ((opoint (point))
24238 (level (funcall outline-level)))
24239 (outline-previous-heading)
24240 (when (and (/= (point) opoint) (outline-on-heading-p t))
24241 (while (and (> (funcall outline-level) level)
24242 (not (bobp)))
24243 (outline-previous-heading))
24244 (unless (< (funcall outline-level) level)
24245 (point)))))
24247 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24248 "Goto to the end of a subtree."
24249 ;; This contains an exact copy of the original function, but it uses
24250 ;; `org-back-to-heading', to make it work also in invisible
24251 ;; trees. And is uses an invisible-ok argument.
24252 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24253 ;; Furthermore, when used inside Org, finding the end of a large subtree
24254 ;; with many children and grandchildren etc, this can be much faster
24255 ;; than the outline version.
24256 (org-back-to-heading invisible-ok)
24257 (let ((first t)
24258 (level (funcall outline-level)))
24259 (if (and (derived-mode-p 'org-mode) (< level 1000))
24260 ;; A true heading (not a plain list item), in Org
24261 ;; This means we can easily find the end by looking
24262 ;; only for the right number of stars. Using a regexp to do
24263 ;; this is so much faster than using a Lisp loop.
24264 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24265 (forward-char 1)
24266 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24267 ;; something else, do it the slow way
24268 (while (and (not (eobp))
24269 (or first (> (funcall outline-level) level)))
24270 (setq first nil)
24271 (outline-next-heading)))
24272 (unless to-heading
24273 (when (memq (preceding-char) '(?\n ?\^M))
24274 ;; Go to end of line before heading
24275 (forward-char -1)
24276 (when (memq (preceding-char) '(?\n ?\^M))
24277 ;; leave blank line before heading
24278 (forward-char -1)))))
24279 (point))
24281 (defun org-end-of-meta-data (&optional full)
24282 "Skip planning line and properties drawer in current entry.
24283 When optional argument FULL is non-nil, also skip empty lines,
24284 clocking lines and regular drawers at the beginning of the
24285 entry."
24286 (org-back-to-heading t)
24287 (forward-line)
24288 (when (looking-at-p org-planning-line-re) (forward-line))
24289 (when (looking-at org-property-drawer-re)
24290 (goto-char (match-end 0))
24291 (forward-line))
24292 (when (and full (not (org-at-heading-p)))
24293 (catch 'exit
24294 (let ((end (save-excursion (outline-next-heading) (point)))
24295 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24296 (while (not (eobp))
24297 (cond ((looking-at-p org-drawer-regexp)
24298 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24299 (forward-line)
24300 (throw 'exit t)))
24301 ((looking-at-p re) (forward-line))
24302 (t (throw 'exit t))))))))
24304 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24305 "Move forward to the ARG'th subheading at same level as this one.
24306 Stop at the first and last subheadings of a superior heading.
24307 Normally this only looks at visible headings, but when INVISIBLE-OK is
24308 non-nil it will also look at invisible ones."
24309 (interactive "p")
24310 (let ((backward? (and arg (< arg 0))))
24311 (if (org-before-first-heading-p)
24312 (if backward? (goto-char (point-min)) (outline-next-heading))
24313 (org-back-to-heading invisible-ok)
24314 (unless backward? (end-of-line)) ;do not match current headline
24315 (let ((level (- (match-end 0) (match-beginning 0) 1))
24316 (f (if backward? #'re-search-backward #'re-search-forward))
24317 (count (if arg (abs arg) 1))
24318 (result (point)))
24319 (while (and (> count 0)
24320 (funcall f org-outline-regexp-bol nil 'move))
24321 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24322 (cond ((< l level) (setq count 0))
24323 ((and (= l level)
24324 (or invisible-ok
24325 (not (org-invisible-p
24326 (line-beginning-position)))))
24327 (cl-decf count)
24328 (when (= l level) (setq result (point)))))))
24329 (goto-char result))
24330 (beginning-of-line))))
24332 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24333 "Move backward to the ARG'th subheading at same level as this one.
24334 Stop at the first and last subheadings of a superior heading."
24335 (interactive "p")
24336 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24338 (defun org-next-visible-heading (arg)
24339 "Move to the next visible heading.
24341 This function wraps `outline-next-visible-heading' with
24342 `org-with-limited-levels' in order to skip over inline tasks and
24343 respect customization of `org-odd-levels-only'."
24344 (interactive "p")
24345 (org-with-limited-levels
24346 (outline-next-visible-heading arg)))
24348 (defun org-previous-visible-heading (arg)
24349 "Move to the previous visible heading.
24351 This function wraps `outline-previous-visible-heading' with
24352 `org-with-limited-levels' in order to skip over inline tasks and
24353 respect customization of `org-odd-levels-only'."
24354 (interactive "p")
24355 (org-with-limited-levels
24356 (outline-previous-visible-heading arg)))
24358 (defun org-next-block (arg &optional backward block-regexp)
24359 "Jump to the next block.
24361 With a prefix argument ARG, jump forward ARG many blocks.
24363 When BACKWARD is non-nil, jump to the previous block.
24365 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24366 Match data is set according to this regexp when the function
24367 returns.
24369 Return point at beginning of the opening line of found block.
24370 Throw an error if no block is found."
24371 (interactive "p")
24372 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24373 (case-fold-search t)
24374 (search-fn (if backward #'re-search-backward #'re-search-forward))
24375 (count (or arg 1))
24376 (origin (point))
24377 last-element)
24378 (if backward (beginning-of-line) (end-of-line))
24379 (while (and (> count 0) (funcall search-fn re nil t))
24380 (let ((element (save-excursion
24381 (goto-char (match-beginning 0))
24382 (save-match-data (org-element-at-point)))))
24383 (when (and (memq (org-element-type element)
24384 '(center-block comment-block dynamic-block
24385 example-block export-block quote-block
24386 special-block src-block verse-block))
24387 (<= (match-beginning 0)
24388 (org-element-property :post-affiliated element)))
24389 (setq last-element element)
24390 (cl-decf count))))
24391 (if (= count 0)
24392 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24393 (save-match-data (org-show-context)))
24394 (goto-char origin)
24395 (user-error "No %s code blocks" (if backward "previous" "further")))))
24397 (defun org-previous-block (arg &optional block-regexp)
24398 "Jump to the previous block.
24399 With a prefix argument ARG, jump backward ARG many source blocks.
24400 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24401 (interactive "p")
24402 (org-next-block arg t block-regexp))
24404 (defun org-forward-paragraph ()
24405 "Move forward to beginning of next paragraph or equivalent.
24407 The function moves point to the beginning of the next visible
24408 structural element, which can be a paragraph, a table, a list
24409 item, etc. It also provides some special moves for convenience:
24411 - On an affiliated keyword, jump to the beginning of the
24412 relative element.
24413 - On an item or a footnote definition, move to the second
24414 element inside, if any.
24415 - On a table or a property drawer, jump after it.
24416 - On a verse or source block, stop after blank lines."
24417 (interactive)
24418 (when (eobp) (user-error "Cannot move further down"))
24419 (let* ((deactivate-mark nil)
24420 (element (org-element-at-point))
24421 (type (org-element-type element))
24422 (post-affiliated (org-element-property :post-affiliated element))
24423 (contents-begin (org-element-property :contents-begin element))
24424 (contents-end (org-element-property :contents-end element))
24425 (end (let ((end (org-element-property :end element)) (parent element))
24426 (while (and (setq parent (org-element-property :parent parent))
24427 (= (org-element-property :contents-end parent) end))
24428 (setq end (org-element-property :end parent)))
24429 end)))
24430 (cond ((not element)
24431 (skip-chars-forward " \r\t\n")
24432 (or (eobp) (beginning-of-line)))
24433 ;; On affiliated keywords, move to element's beginning.
24434 ((< (point) post-affiliated)
24435 (goto-char post-affiliated))
24436 ;; At a table row, move to the end of the table. Similarly,
24437 ;; at a node property, move to the end of the property
24438 ;; drawer.
24439 ((memq type '(node-property table-row))
24440 (goto-char (org-element-property
24441 :end (org-element-property :parent element))))
24442 ((memq type '(property-drawer table)) (goto-char end))
24443 ;; Consider blank lines as separators in verse and source
24444 ;; blocks to ease editing.
24445 ((memq type '(src-block verse-block))
24446 (when (eq type 'src-block)
24447 (setq contents-end
24448 (save-excursion (goto-char end)
24449 (skip-chars-backward " \r\t\n")
24450 (line-beginning-position))))
24451 (beginning-of-line)
24452 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24453 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24454 (goto-char end)
24455 (skip-chars-forward " \r\t\n")
24456 (if (= (point) contents-end) (goto-char end)
24457 (beginning-of-line))))
24458 ;; With no contents, just skip element.
24459 ((not contents-begin) (goto-char end))
24460 ;; If contents are invisible, skip the element altogether.
24461 ((org-invisible-p (line-end-position))
24462 (cl-case type
24463 (headline
24464 (org-with-limited-levels (outline-next-visible-heading 1)))
24465 ;; At a plain list, make sure we move to the next item
24466 ;; instead of skipping the whole list.
24467 (plain-list (forward-char)
24468 (org-forward-paragraph))
24469 (otherwise (goto-char end))))
24470 ((>= (point) contents-end) (goto-char end))
24471 ((>= (point) contents-begin)
24472 ;; This can only happen on paragraphs and plain lists.
24473 (cl-case type
24474 (paragraph (goto-char end))
24475 ;; At a plain list, try to move to second element in
24476 ;; first item, if possible.
24477 (plain-list (end-of-line)
24478 (org-forward-paragraph))))
24479 ;; When contents start on the middle of a line (e.g. in
24480 ;; items and footnote definitions), try to reach first
24481 ;; element starting after current line.
24482 ((> (line-end-position) contents-begin)
24483 (end-of-line)
24484 (org-forward-paragraph))
24485 (t (goto-char contents-begin)))))
24487 (defun org-backward-paragraph ()
24488 "Move backward to start of previous paragraph or equivalent.
24490 The function moves point to the beginning of the current
24491 structural element, which can be a paragraph, a table, a list
24492 item, etc., or to the beginning of the previous visible one if
24493 point is already there. It also provides some special moves for
24494 convenience:
24496 - On an affiliated keyword, jump to the first one.
24497 - On a table or a property drawer, move to its beginning.
24498 - On a verse or source block, stop before blank lines."
24499 (interactive)
24500 (when (bobp) (user-error "Cannot move further up"))
24501 (let* ((deactivate-mark nil)
24502 (element (org-element-at-point))
24503 (type (org-element-type element))
24504 (contents-begin (org-element-property :contents-begin element))
24505 (contents-end (org-element-property :contents-end element))
24506 (post-affiliated (org-element-property :post-affiliated element))
24507 (begin (org-element-property :begin element)))
24508 (cond
24509 ((not element) (goto-char (point-min)))
24510 ((= (point) begin)
24511 (backward-char)
24512 (org-backward-paragraph))
24513 ((<= (point) post-affiliated) (goto-char begin))
24514 ((memq type '(node-property table-row))
24515 (goto-char (org-element-property
24516 :post-affiliated (org-element-property :parent element))))
24517 ((memq type '(property-drawer table)) (goto-char begin))
24518 ((memq type '(src-block verse-block))
24519 (when (eq type 'src-block)
24520 (setq contents-begin
24521 (save-excursion (goto-char begin) (forward-line) (point))))
24522 (if (= (point) contents-begin) (goto-char post-affiliated)
24523 ;; Inside a verse block, see blank lines as paragraph
24524 ;; separators.
24525 (let ((origin (point)))
24526 (skip-chars-backward " \r\t\n" contents-begin)
24527 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24528 (skip-chars-forward " \r\t\n" origin)
24529 (if (= (point) origin) (goto-char contents-begin)
24530 (beginning-of-line))))))
24531 ((not contents-begin) (goto-char (or post-affiliated begin)))
24532 ((eq type 'paragraph)
24533 (goto-char contents-begin)
24534 ;; When at first paragraph in an item or a footnote definition,
24535 ;; move directly to beginning of line.
24536 (let ((parent-contents
24537 (org-element-property
24538 :contents-begin (org-element-property :parent element))))
24539 (when (and parent-contents (= parent-contents contents-begin))
24540 (beginning-of-line))))
24541 ;; At the end of a greater element, move to the beginning of the
24542 ;; last element within.
24543 ((>= (point) contents-end)
24544 (goto-char (1- contents-end))
24545 (org-backward-paragraph))
24546 (t (goto-char (or post-affiliated begin))))
24547 ;; Ensure we never leave point invisible.
24548 (when (org-invisible-p (point)) (beginning-of-visual-line))))
24550 (defun org-forward-element ()
24551 "Move forward by one element.
24552 Move to the next element at the same level, when possible."
24553 (interactive)
24554 (cond ((eobp) (user-error "Cannot move further down"))
24555 ((org-with-limited-levels (org-at-heading-p))
24556 (let ((origin (point)))
24557 (goto-char (org-end-of-subtree nil t))
24558 (unless (org-with-limited-levels (org-at-heading-p))
24559 (goto-char origin)
24560 (user-error "Cannot move further down"))))
24562 (let* ((elem (org-element-at-point))
24563 (end (org-element-property :end elem))
24564 (parent (org-element-property :parent elem)))
24565 (cond ((and parent (= (org-element-property :contents-end parent) end))
24566 (goto-char (org-element-property :end parent)))
24567 ((integer-or-marker-p end) (goto-char end))
24568 (t (message "No element at point")))))))
24570 (defun org-backward-element ()
24571 "Move backward by one element.
24572 Move to the previous element at the same level, when possible."
24573 (interactive)
24574 (cond ((bobp) (user-error "Cannot move further up"))
24575 ((org-with-limited-levels (org-at-heading-p))
24576 ;; At a headline, move to the previous one, if any, or stay
24577 ;; here.
24578 (let ((origin (point)))
24579 (org-with-limited-levels (org-backward-heading-same-level 1))
24580 ;; When current headline has no sibling above, move to its
24581 ;; parent.
24582 (when (= (point) origin)
24583 (or (org-with-limited-levels (org-up-heading-safe))
24584 (progn (goto-char origin)
24585 (user-error "Cannot move further up"))))))
24587 (let* ((elem (org-element-at-point))
24588 (beg (org-element-property :begin elem)))
24589 (cond
24590 ;; Move to beginning of current element if point isn't
24591 ;; there already.
24592 ((null beg) (message "No element at point"))
24593 ((/= (point) beg) (goto-char beg))
24594 (t (goto-char beg)
24595 (skip-chars-backward " \r\t\n")
24596 (unless (bobp)
24597 (let ((prev (org-element-at-point)))
24598 (goto-char (org-element-property :begin prev))
24599 (while (and (setq prev (org-element-property :parent prev))
24600 (<= (org-element-property :end prev) beg))
24601 (goto-char (org-element-property :begin prev)))))))))))
24603 (defun org-up-element ()
24604 "Move to upper element."
24605 (interactive)
24606 (if (org-with-limited-levels (org-at-heading-p))
24607 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24608 (let* ((elem (org-element-at-point))
24609 (parent (org-element-property :parent elem)))
24610 (if parent (goto-char (org-element-property :begin parent))
24611 (if (org-with-limited-levels (org-before-first-heading-p))
24612 (user-error "No surrounding element")
24613 (org-with-limited-levels (org-back-to-heading)))))))
24615 (defun org-down-element ()
24616 "Move to inner element."
24617 (interactive)
24618 (let ((element (org-element-at-point)))
24619 (cond
24620 ((memq (org-element-type element) '(plain-list table))
24621 (goto-char (org-element-property :contents-begin element))
24622 (forward-char))
24623 ((memq (org-element-type element) org-element-greater-elements)
24624 ;; If contents are hidden, first disclose them.
24625 (when (org-invisible-p (line-end-position)) (org-cycle))
24626 (goto-char (or (org-element-property :contents-begin element)
24627 (user-error "No content for this element"))))
24628 (t (user-error "No inner element")))))
24630 (defun org-drag-element-backward ()
24631 "Move backward element at point."
24632 (interactive)
24633 (let ((elem (or (org-element-at-point)
24634 (user-error "No element at point"))))
24635 (if (eq (org-element-type elem) 'headline)
24636 ;; Preserve point when moving a whole tree, even if point was
24637 ;; on blank lines below the headline.
24638 (let ((offset (skip-chars-backward " \t\n")))
24639 (unwind-protect (org-move-subtree-up)
24640 (forward-char (- offset))))
24641 (let ((prev-elem
24642 (save-excursion
24643 (goto-char (org-element-property :begin elem))
24644 (skip-chars-backward " \r\t\n")
24645 (unless (bobp)
24646 (let* ((beg (org-element-property :begin elem))
24647 (prev (org-element-at-point))
24648 (up prev))
24649 (while (and (setq up (org-element-property :parent up))
24650 (<= (org-element-property :end up) beg))
24651 (setq prev up))
24652 prev)))))
24653 ;; Error out if no previous element or previous element is
24654 ;; a parent of the current one.
24655 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24656 (user-error "Cannot drag element backward")
24657 (let ((pos (point)))
24658 (org-element-swap-A-B prev-elem elem)
24659 (goto-char (+ (org-element-property :begin prev-elem)
24660 (- pos (org-element-property :begin elem))))))))))
24662 (defun org-drag-element-forward ()
24663 "Move forward element at point."
24664 (interactive)
24665 (let* ((pos (point))
24666 (elem (or (org-element-at-point)
24667 (user-error "No element at point"))))
24668 (when (= (point-max) (org-element-property :end elem))
24669 (user-error "Cannot drag element forward"))
24670 (goto-char (org-element-property :end elem))
24671 (let ((next-elem (org-element-at-point)))
24672 (when (or (org-element-nested-p elem next-elem)
24673 (and (eq (org-element-type next-elem) 'headline)
24674 (not (eq (org-element-type elem) 'headline))))
24675 (goto-char pos)
24676 (user-error "Cannot drag element forward"))
24677 ;; Compute new position of point: it's shifted by NEXT-ELEM
24678 ;; body's length (without final blanks) and by the length of
24679 ;; blanks between ELEM and NEXT-ELEM.
24680 (let ((size-next (- (save-excursion
24681 (goto-char (org-element-property :end next-elem))
24682 (skip-chars-backward " \r\t\n")
24683 (forward-line)
24684 ;; Small correction if buffer doesn't end
24685 ;; with a newline character.
24686 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24687 (org-element-property :begin next-elem)))
24688 (size-blank (- (org-element-property :end elem)
24689 (save-excursion
24690 (goto-char (org-element-property :end elem))
24691 (skip-chars-backward " \r\t\n")
24692 (forward-line)
24693 (point)))))
24694 (org-element-swap-A-B elem next-elem)
24695 (goto-char (+ pos size-next size-blank))))))
24697 (defun org-drag-line-forward (arg)
24698 "Drag the line at point ARG lines forward."
24699 (interactive "p")
24700 (dotimes (_ (abs arg))
24701 (let ((c (current-column)))
24702 (if (< 0 arg)
24703 (progn
24704 (beginning-of-line 2)
24705 (transpose-lines 1)
24706 (beginning-of-line 0))
24707 (transpose-lines 1)
24708 (beginning-of-line -1))
24709 (org-move-to-column c))))
24711 (defun org-drag-line-backward (arg)
24712 "Drag the line at point ARG lines backward."
24713 (interactive "p")
24714 (org-drag-line-forward (- arg)))
24716 (defun org-mark-element ()
24717 "Put point at beginning of this element, mark at end.
24719 Interactively, if this command is repeated or (in Transient Mark
24720 mode) if the mark is active, it marks the next element after the
24721 ones already marked."
24722 (interactive)
24723 (let (deactivate-mark)
24724 (if (and (called-interactively-p 'any)
24725 (or (and (eq last-command this-command) (mark t))
24726 (and transient-mark-mode mark-active)))
24727 (set-mark
24728 (save-excursion
24729 (goto-char (mark))
24730 (goto-char (org-element-property :end (org-element-at-point)))))
24731 (let ((element (org-element-at-point)))
24732 (end-of-line)
24733 (push-mark (org-element-property :end element) t t)
24734 (goto-char (org-element-property :begin element))))))
24736 (defun org-narrow-to-element ()
24737 "Narrow buffer to current element."
24738 (interactive)
24739 (let ((elem (org-element-at-point)))
24740 (cond
24741 ((eq (car elem) 'headline)
24742 (narrow-to-region
24743 (org-element-property :begin elem)
24744 (org-element-property :end elem)))
24745 ((memq (car elem) org-element-greater-elements)
24746 (narrow-to-region
24747 (org-element-property :contents-begin elem)
24748 (org-element-property :contents-end elem)))
24750 (narrow-to-region
24751 (org-element-property :begin elem)
24752 (org-element-property :end elem))))))
24754 (defun org-transpose-element ()
24755 "Transpose current and previous elements, keeping blank lines between.
24756 Point is moved after both elements."
24757 (interactive)
24758 (org-skip-whitespace)
24759 (let ((end (org-element-property :end (org-element-at-point))))
24760 (org-drag-element-backward)
24761 (goto-char end)))
24763 (defun org-unindent-buffer ()
24764 "Un-indent the visible part of the buffer.
24765 Relative indentation (between items, inside blocks, etc.) isn't
24766 modified."
24767 (interactive)
24768 (unless (eq major-mode 'org-mode)
24769 (user-error "Cannot un-indent a buffer not in Org mode"))
24770 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24771 (unindent-tree
24772 (lambda (contents)
24773 (dolist (element (reverse contents))
24774 (if (memq (org-element-type element) '(headline section))
24775 (funcall unindent-tree (org-element-contents element))
24776 (save-excursion
24777 (save-restriction
24778 (narrow-to-region
24779 (org-element-property :begin element)
24780 (org-element-property :end element))
24781 (org-do-remove-indentation))))))))
24782 (funcall unindent-tree (org-element-contents parse-tree))))
24784 (defun org-show-children (&optional level)
24785 "Show all direct subheadings of this heading.
24786 Prefix arg LEVEL is how many levels below the current level
24787 should be shown. Default is enough to cause the following
24788 heading to appear."
24789 (interactive "p")
24790 ;; If `orgstruct-mode' is active, use the slower version.
24791 (if orgstruct-mode (call-interactively #'outline-show-children)
24792 (save-excursion
24793 (org-back-to-heading t)
24794 (let* ((current-level (funcall outline-level))
24795 (max-level (org-get-valid-level
24796 current-level
24797 (if level (prefix-numeric-value level) 1)))
24798 (end (save-excursion (org-end-of-subtree t t)))
24799 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24800 (past-first-child nil)
24801 ;; Make sure to skip inlinetasks.
24802 (re (format regexp-fmt
24803 current-level
24804 (cond
24805 ((not (featurep 'org-inlinetask)) "")
24806 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24808 (t (1- org-inlinetask-min-level))))))
24809 ;; Display parent heading.
24810 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24811 (forward-line)
24812 ;; Display children. First child may be deeper than expected
24813 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24814 ;; MAX-LEVEL accordingly.
24815 (while (re-search-forward re end t)
24816 (unless past-first-child
24817 (setq re (format regexp-fmt
24818 current-level
24819 (max (funcall outline-level) max-level)))
24820 (setq past-first-child t))
24821 (outline-flag-region
24822 (line-end-position 0) (line-end-position) nil))))))
24824 (defun org-show-subtree ()
24825 "Show everything after this heading at deeper levels."
24826 (interactive)
24827 (outline-flag-region
24828 (point)
24829 (save-excursion
24830 (org-end-of-subtree t t))
24831 nil))
24833 (defun org-show-entry ()
24834 "Show the body directly following this heading.
24835 Show the heading too, if it is currently invisible."
24836 (interactive)
24837 (save-excursion
24838 (ignore-errors
24839 (org-back-to-heading t)
24840 (outline-flag-region
24841 (max (point-min) (1- (point)))
24842 (save-excursion
24843 (if (re-search-forward
24844 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24845 (match-beginning 1)
24846 (point-max)))
24847 nil)
24848 (org-cycle-hide-drawers 'children))))
24850 (defun org-make-options-regexp (kwds &optional extra)
24851 "Make a regular expression for keyword lines.
24852 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24853 when non-nil, is a regexp matching keywords names."
24854 (concat "^[ \t]*#\\+\\("
24855 (regexp-opt kwds)
24856 (and extra (concat (and kwds "\\|") extra))
24857 "\\):[ \t]*\\(.*\\)"))
24859 ;;;; Integration with and fixes for other packages
24861 ;;; Imenu support
24863 (defvar-local org-imenu-markers nil
24864 "All markers currently used by Imenu.")
24866 (defun org-imenu-new-marker (&optional pos)
24867 "Return a new marker for use by Imenu, and remember the marker."
24868 (let ((m (make-marker)))
24869 (move-marker m (or pos (point)))
24870 (push m org-imenu-markers)
24873 (defun org-imenu-get-tree ()
24874 "Produce the index for Imenu."
24875 (dolist (x org-imenu-markers) (move-marker x nil))
24876 (setq org-imenu-markers nil)
24877 (let* ((case-fold-search nil)
24878 (n org-imenu-depth)
24879 (re (concat "^" (org-get-limited-outline-regexp)))
24880 (subs (make-vector (1+ n) nil))
24881 (last-level 0)
24882 m level head0 head)
24883 (org-with-wide-buffer
24884 (goto-char (point-max))
24885 (while (re-search-backward re nil t)
24886 (setq level (org-reduced-level (funcall outline-level)))
24887 (when (and (<= level n)
24888 (looking-at org-complex-heading-regexp)
24889 (setq head0 (match-string-no-properties 4)))
24890 (setq head (org-link-display-format head0)
24891 m (org-imenu-new-marker))
24892 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24893 (if (>= level last-level)
24894 (push (cons head m) (aref subs level))
24895 (push (cons head (aref subs (1+ level))) (aref subs level))
24896 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24897 (setq last-level level))))
24898 (aref subs 1)))
24900 (eval-after-load "imenu"
24901 '(progn
24902 (add-hook 'imenu-after-jump-hook
24903 (lambda ()
24904 (when (derived-mode-p 'org-mode)
24905 (org-show-context 'org-goto))))))
24907 (defun org-link-display-format (s)
24908 "Replace links in string S with their description.
24909 If there is no description, use the link target."
24910 (save-match-data
24911 (replace-regexp-in-string
24912 org-bracket-link-analytic-regexp
24913 (lambda (m)
24914 (if (match-end 5) (match-string 5 m)
24915 (concat (match-string 1 m) (match-string 3 m))))
24916 s nil t)))
24918 (defun org-toggle-link-display ()
24919 "Toggle the literal or descriptive display of links."
24920 (interactive)
24921 (if org-descriptive-links
24922 (progn (org-remove-from-invisibility-spec '(org-link))
24923 (org-restart-font-lock)
24924 (setq org-descriptive-links nil))
24925 (progn (add-to-invisibility-spec '(org-link))
24926 (org-restart-font-lock)
24927 (setq org-descriptive-links t))))
24929 ;; Speedbar support
24931 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24932 "Overlay marking the agenda restriction line in speedbar.")
24933 (overlay-put org-speedbar-restriction-lock-overlay
24934 'face 'org-agenda-restriction-lock)
24935 (overlay-put org-speedbar-restriction-lock-overlay
24936 'help-echo "Agendas are currently limited to this item.")
24937 (delete-overlay org-speedbar-restriction-lock-overlay)
24939 (defun org-speedbar-set-agenda-restriction ()
24940 "Restrict future agenda commands to the location at point in speedbar.
24941 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24942 (interactive)
24943 (require 'org-agenda)
24944 (let (p m tp np dir txt)
24945 (cond
24946 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24947 'org-imenu t))
24948 (setq m (get-text-property p 'org-imenu-marker))
24949 (with-current-buffer (marker-buffer m)
24950 (goto-char m)
24951 (org-agenda-set-restriction-lock 'subtree)))
24952 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24953 'speedbar-function 'speedbar-find-file))
24954 (setq tp (previous-single-property-change
24955 (1+ p) 'speedbar-function)
24956 np (next-single-property-change
24957 tp 'speedbar-function)
24958 dir (speedbar-line-directory)
24959 txt (buffer-substring-no-properties (or tp (point-min))
24960 (or np (point-max))))
24961 (with-current-buffer (find-file-noselect
24962 (let ((default-directory dir))
24963 (expand-file-name txt)))
24964 (unless (derived-mode-p 'org-mode)
24965 (user-error "Cannot restrict to non-Org mode file"))
24966 (org-agenda-set-restriction-lock 'file)))
24967 (t (user-error "Don't know how to restrict Org mode agenda")))
24968 (move-overlay org-speedbar-restriction-lock-overlay
24969 (point-at-bol) (point-at-eol))
24970 (setq current-prefix-arg nil)
24971 (org-agenda-maybe-redo)))
24973 (defvar speedbar-file-key-map)
24974 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24975 (eval-after-load "speedbar"
24976 '(progn
24977 (speedbar-add-supported-extension ".org")
24978 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24979 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24980 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24981 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24982 (add-hook 'speedbar-visiting-tag-hook
24983 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24985 ;;; Fixes and Hacks for problems with other packages
24987 (defun org--flyspell-object-check-p (element)
24988 "Non-nil when Flyspell can check object at point.
24989 ELEMENT is the element at point."
24990 (let ((object (save-excursion
24991 (when (looking-at-p "\\>") (backward-char))
24992 (org-element-context element))))
24993 (cl-case (org-element-type object)
24994 ;; Prevent checks in links due to keybinding conflict with
24995 ;; Flyspell.
24996 ((code entity export-snippet inline-babel-call
24997 inline-src-block line-break latex-fragment link macro
24998 statistics-cookie target timestamp verbatim)
24999 nil)
25000 (footnote-reference
25001 ;; Only in inline footnotes, within the definition.
25002 (and (eq (org-element-property :type object) 'inline)
25003 (< (save-excursion
25004 (goto-char (org-element-property :begin object))
25005 (search-forward ":" nil t 2))
25006 (point))))
25007 (otherwise t))))
25009 (defun org-mode-flyspell-verify ()
25010 "Function used for `flyspell-generic-check-word-predicate'."
25011 (if (org-at-heading-p)
25012 ;; At a headline or an inlinetask, check title only. This is
25013 ;; faster than relying on `org-element-at-point'.
25014 (and (save-excursion (beginning-of-line)
25015 (and (let ((case-fold-search t))
25016 (not (looking-at-p "\\*+ END[ \t]*$")))
25017 (let ((case-fold-search nil))
25018 (looking-at org-complex-heading-regexp))))
25019 (match-beginning 4)
25020 (>= (point) (match-beginning 4))
25021 (or (not (match-beginning 5))
25022 (< (point) (match-beginning 5))))
25023 (let* ((element (org-element-at-point))
25024 (post-affiliated (org-element-property :post-affiliated element)))
25025 (cond
25026 ;; Ignore checks in all affiliated keywords but captions.
25027 ((< (point) post-affiliated)
25028 (and (save-excursion
25029 (beginning-of-line)
25030 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25031 (> (point) (match-end 0))
25032 (org--flyspell-object-check-p element)))
25033 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25034 ((let ((log (org-log-into-drawer)))
25035 (and log
25036 (let ((drawer (org-element-lineage element '(drawer))))
25037 (and drawer
25038 (eq (compare-strings
25039 log nil nil
25040 (org-element-property :drawer-name drawer) nil nil t)
25041 t)))))
25042 nil)
25044 (cl-case (org-element-type element)
25045 ((comment quote-section) t)
25046 (comment-block
25047 ;; Allow checks between block markers, not on them.
25048 (and (> (line-beginning-position) post-affiliated)
25049 (save-excursion
25050 (end-of-line)
25051 (skip-chars-forward " \r\t\n")
25052 (< (point) (org-element-property :end element)))))
25053 ;; Arbitrary list of keywords where checks are meaningful.
25054 ;; Make sure point is on the value part of the element.
25055 (keyword
25056 (and (member (org-element-property :key element)
25057 '("DESCRIPTION" "TITLE"))
25058 (save-excursion
25059 (search-backward ":" (line-beginning-position) t))))
25060 ;; Check is globally allowed in paragraphs verse blocks and
25061 ;; table rows (after affiliated keywords) but some objects
25062 ;; must not be affected.
25063 ((paragraph table-row verse-block)
25064 (let ((cbeg (org-element-property :contents-begin element))
25065 (cend (org-element-property :contents-end element)))
25066 (and cbeg (>= (point) cbeg) (< (point) cend)
25067 (org--flyspell-object-check-p element))))))))))
25068 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25070 (defun org-remove-flyspell-overlays-in (beg end)
25071 "Remove flyspell overlays in region."
25072 (and (bound-and-true-p flyspell-mode)
25073 (fboundp 'flyspell-delete-region-overlays)
25074 (flyspell-delete-region-overlays beg end)))
25076 (defvar flyspell-delayed-commands)
25077 (eval-after-load "flyspell"
25078 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25080 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25081 (eval-after-load "bookmark"
25082 '(if (boundp 'bookmark-after-jump-hook)
25083 ;; We can use the hook
25084 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25085 ;; Hook not available, use advice
25086 (defadvice bookmark-jump (after org-make-visible activate)
25087 "Make the position visible."
25088 (org-bookmark-jump-unhide))))
25090 ;; Make sure saveplace shows the location if it was hidden
25091 (eval-after-load "saveplace"
25092 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25093 "Make the position visible."
25094 (org-bookmark-jump-unhide)))
25096 ;; Make sure ecb shows the location if it was hidden
25097 (eval-after-load "ecb"
25098 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25099 "Make hierarchy visible when jumping into location from ECB tree buffer."
25100 (when (derived-mode-p 'org-mode)
25101 (org-show-context))))
25103 (defun org-bookmark-jump-unhide ()
25104 "Unhide the current position, to show the bookmark location."
25105 (and (derived-mode-p 'org-mode)
25106 (or (org-invisible-p)
25107 (save-excursion (goto-char (max (point-min) (1- (point))))
25108 (org-invisible-p)))
25109 (org-show-context 'bookmark-jump)))
25111 (defun org-mark-jump-unhide ()
25112 "Make the point visible with `org-show-context' after jumping to the mark."
25113 (when (and (derived-mode-p 'org-mode)
25114 (org-invisible-p))
25115 (org-show-context 'mark-goto)))
25117 (eval-after-load "simple"
25118 '(defadvice pop-to-mark-command (after org-make-visible activate)
25119 "Make the point visible with `org-show-context'."
25120 (org-mark-jump-unhide)))
25122 (eval-after-load "simple"
25123 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25124 "Make the point visible with `org-show-context'."
25125 (org-mark-jump-unhide)))
25127 (eval-after-load "simple"
25128 '(defadvice pop-global-mark (after org-make-visible activate)
25129 "Make the point visible with `org-show-context'."
25130 (org-mark-jump-unhide)))
25132 ;; Make session.el ignore our circular variable
25133 (defvar session-globals-exclude)
25134 (eval-after-load "session"
25135 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25137 ;;;; Finish up
25139 (provide 'org)
25141 (run-hooks 'org-load-hook)
25143 ;;; org.el ends here