org-colview: Fix failing test
[org-mode.git] / lisp / org.el
blobf4d06bc700bc19873716d576d5e45cf6a1a3074a
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 (type (cond ((eq ?< (char-after start)) 'angle)
5968 ((eq ?\[ (char-after (1+ start))) 'bracket)
5969 (t 'plain))))
5970 (when (and (memq type org-highlight-links)
5971 ;; Do not confuse plain links with tags.
5972 (not (and (eq type '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 (path (org-element-property :path link-object))
5982 (properties ;for link's visible part
5983 (list
5984 'face (pcase (org-link-get-parameter type :face)
5985 ((and (pred functionp) face) (funcall face path))
5986 ((and (pred facep) face) face)
5987 ((and (pred consp) face) face) ;anonymous
5988 (_ 'org-link))
5989 'mouse-face (or (org-link-get-parameter type :mouse-face)
5990 'highlight)
5991 'keymap (or (org-link-get-parameter type :keymap)
5992 org-mouse-map)
5993 'help-echo (pcase (org-link-get-parameter type :help-echo)
5994 ((and (pred stringp) echo) echo)
5995 ((and (pred functionp) echo) echo)
5996 (_ (concat "LINK: " link)))
5997 'htmlize-link (pcase (org-link-get-parameter type
5998 :htmlize-link)
5999 ((and (pred functionp) f) (funcall f))
6000 (_ `(:uri ,link)))
6001 'font-lock-multiline t)))
6002 (org-remove-flyspell-overlays-in start end)
6003 (org-rear-nonsticky-at end)
6004 (if (not (eq 'bracket type))
6005 (add-text-properties start end properties)
6006 ;; Handle invisible parts in bracket links.
6007 (remove-text-properties start end '(invisible nil))
6008 (let ((hidden
6009 (append `(invisible
6010 ,(or (org-link-get-parameter type :display)
6011 'org-link))
6012 properties))
6013 (visible-start (or (match-beginning 4) (match-beginning 2)))
6014 (visible-end (or (match-end 4) (match-end 2))))
6015 (add-text-properties start visible-start hidden)
6016 (add-text-properties visible-start visible-end properties)
6017 (add-text-properties visible-end end hidden)
6018 (org-rear-nonsticky-at visible-start)
6019 (org-rear-nonsticky-at visible-end)))
6020 (let ((f (org-link-get-parameter type :activate-func)))
6021 (when (functionp f)
6022 (funcall f start end path (eq type 'bracket))))
6023 (throw :exit t))))) ;signal success
6024 nil))
6026 (defun org-activate-code (limit)
6027 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
6028 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6029 (remove-text-properties (match-beginning 0) (match-end 0)
6030 '(display t invisible t intangible t))
6033 (defcustom org-src-fontify-natively t
6034 "When non-nil, fontify code in code blocks.
6035 See also the `org-block' face."
6036 :type 'boolean
6037 :version "24.4"
6038 :package-version '(Org . "8.3")
6039 :group 'org-appearance
6040 :group 'org-babel)
6042 (defcustom org-allow-promoting-top-level-subtree nil
6043 "When non-nil, allow promoting a top level subtree.
6044 The leading star of the top level headline will be replaced
6045 by a #."
6046 :type 'boolean
6047 :version "24.1"
6048 :group 'org-appearance)
6050 (defun org-fontify-meta-lines-and-blocks (limit)
6051 (condition-case nil
6052 (org-fontify-meta-lines-and-blocks-1 limit)
6053 (error (message "org-mode fontification error in %S at %d"
6054 (current-buffer)
6055 (line-number-at-pos)))))
6057 (defun org-fontify-meta-lines-and-blocks-1 (limit)
6058 "Fontify #+ lines and blocks."
6059 (let ((case-fold-search t))
6060 (when (re-search-forward
6061 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
6062 limit t)
6063 (let ((beg (match-beginning 0))
6064 (block-start (match-end 0))
6065 (block-end nil)
6066 (lang (match-string 7))
6067 (beg1 (line-beginning-position 2))
6068 (dc1 (downcase (match-string 2)))
6069 (dc3 (downcase (match-string 3)))
6070 end end1 quoting block-type)
6071 (cond
6072 ((and (match-end 4) (equal dc3 "+begin"))
6073 ;; Truly a block
6074 (setq block-type (downcase (match-string 5))
6075 quoting (member block-type org-protecting-blocks))
6076 (when (re-search-forward
6077 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
6078 nil t) ;; on purpose, we look further than LIMIT
6079 (setq end (min (point-max) (match-end 0))
6080 end1 (min (point-max) (1- (match-beginning 0))))
6081 (setq block-end (match-beginning 0))
6082 (when quoting
6083 (org-remove-flyspell-overlays-in beg1 end1)
6084 (remove-text-properties beg end
6085 '(display t invisible t intangible t)))
6086 (add-text-properties
6087 beg end '(font-lock-fontified t font-lock-multiline t))
6088 (add-text-properties beg beg1 '(face org-meta-line))
6089 (org-remove-flyspell-overlays-in beg beg1)
6090 (add-text-properties ; For end_src
6091 end1 (min (point-max) (1+ end)) '(face org-meta-line))
6092 (org-remove-flyspell-overlays-in end1 end)
6093 (cond
6094 ((and lang (not (string= lang "")) org-src-fontify-natively)
6095 (org-src-font-lock-fontify-block lang block-start block-end)
6096 (add-text-properties beg1 block-end '(src-block t)))
6097 (quoting
6098 (add-text-properties beg1 (min (point-max) (1+ end1))
6099 (list 'face
6100 (list :inherit
6101 (let ((face-name
6102 (intern (format "org-block-%s" lang))))
6103 (append (and (facep face-name) (list face-name))
6104 '(org-block))))))) ; end of source block
6105 ((not org-fontify-quote-and-verse-blocks))
6106 ((string= block-type "quote")
6107 (add-face-text-property
6108 beg1 (min (point-max) (1+ end1)) 'org-quote t))
6109 ((string= block-type "verse")
6110 (add-face-text-property
6111 beg1 (min (point-max) (1+ end1)) 'org-verse t)))
6112 (add-text-properties beg beg1 '(face org-block-begin-line))
6113 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
6114 '(face org-block-end-line))
6116 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
6117 (org-remove-flyspell-overlays-in
6118 (match-beginning 0)
6119 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
6120 (add-text-properties
6121 beg (match-end 3)
6122 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6123 '(font-lock-fontified t invisible t)
6124 '(font-lock-fontified t face org-document-info-keyword)))
6125 (add-text-properties
6126 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6127 (if (string-equal dc1 "+title:")
6128 '(font-lock-fontified t face org-document-title)
6129 '(font-lock-fontified t face org-document-info))))
6130 ((string-prefix-p "+caption" dc1)
6131 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6132 (remove-text-properties (match-beginning 0) (match-end 0)
6133 '(display t invisible t intangible t))
6134 ;; Handle short captions.
6135 (save-excursion
6136 (beginning-of-line)
6137 (looking-at "\\([ \t]*#\\+caption\\(?:\\[.*\\]\\)?:\\)[ \t]*"))
6138 (add-text-properties (line-beginning-position) (match-end 1)
6139 '(font-lock-fontified t face org-meta-line))
6140 (add-text-properties (match-end 0) (line-end-position)
6141 '(font-lock-fontified t face org-block))
6143 ((member dc3 '(" " ""))
6144 (org-remove-flyspell-overlays-in beg (match-end 0))
6145 (add-text-properties
6146 beg (match-end 0)
6147 '(font-lock-fontified t face font-lock-comment-face)))
6148 (t ;; just any other in-buffer setting, but not indented
6149 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6150 (remove-text-properties (match-beginning 0) (match-end 0)
6151 '(display t invisible t intangible t))
6152 (add-text-properties beg (match-end 0)
6153 '(font-lock-fontified t face org-meta-line))
6154 t))))))
6156 (defun org-fontify-drawers (limit)
6157 "Fontify drawers."
6158 (when (re-search-forward org-drawer-regexp limit t)
6159 (add-text-properties
6160 (match-beginning 0) (match-end 0)
6161 '(font-lock-fontified t face org-special-keyword))
6162 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6165 (defun org-fontify-macros (limit)
6166 "Fontify macros."
6167 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6168 (add-text-properties
6169 (match-beginning 0) (match-end 0)
6170 '(font-lock-fontified t face org-macro))
6171 (when org-hide-macro-markers
6172 (add-text-properties (match-end 2) (match-beginning 2)
6173 '(invisible t))
6174 (add-text-properties (match-beginning 1) (match-end 1)
6175 '(invisible t)))
6176 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6179 (defun org-activate-footnote-links (limit)
6180 "Add text properties for footnotes."
6181 (let ((fn (org-footnote-next-reference-or-definition limit)))
6182 (when fn
6183 (let* ((beg (nth 1 fn))
6184 (end (nth 2 fn))
6185 (label (car fn))
6186 (referencep (/= (line-beginning-position) beg)))
6187 (when (and referencep (nth 3 fn))
6188 (save-excursion
6189 (goto-char beg)
6190 (search-forward (or label "fn:"))
6191 (org-remove-flyspell-overlays-in beg (match-end 0))))
6192 (add-text-properties beg end
6193 (list 'mouse-face 'highlight
6194 'keymap org-mouse-map
6195 'help-echo
6196 (if referencep "Footnote reference"
6197 "Footnote definition")
6198 'font-lock-fontified t
6199 'font-lock-multiline t
6200 'face 'org-footnote))))))
6202 (defun org-activate-dates (limit)
6203 "Add text properties for dates."
6204 (when (and (re-search-forward org-tsr-regexp-both limit t)
6205 (not (equal (char-before (match-beginning 0)) 91)))
6206 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6207 (add-text-properties (match-beginning 0) (match-end 0)
6208 (list 'mouse-face 'highlight
6209 'keymap org-mouse-map))
6210 (org-rear-nonsticky-at (match-end 0))
6211 (when org-display-custom-times
6212 (if (match-end 3)
6213 (org-display-custom-time (match-beginning 3) (match-end 3))
6214 (org-display-custom-time (match-beginning 1) (match-end 1))))
6217 (defvar-local org-target-link-regexp nil
6218 "Regular expression matching radio targets in plain text.")
6220 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6221 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6222 border border border))
6223 "Regular expression matching a link target.")
6225 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6226 "Regular expression matching a radio target.")
6228 (defconst org-any-target-regexp
6229 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6230 "Regular expression matching any target.")
6232 (defun org-activate-target-links (limit)
6233 "Add text properties for target matches."
6234 (when org-target-link-regexp
6235 (let ((case-fold-search t))
6236 (when (re-search-forward org-target-link-regexp limit t)
6237 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6238 (add-text-properties (match-beginning 1) (match-end 1)
6239 (list 'mouse-face 'highlight
6240 'keymap org-mouse-map
6241 'help-echo "Radio target link"
6242 'org-linked-text t))
6243 (org-rear-nonsticky-at (match-end 1))
6244 t))))
6246 (defun org-update-radio-target-regexp ()
6247 "Find all radio targets in this file and update the regular expression.
6248 Also refresh fontification if needed."
6249 (interactive)
6250 (let ((old-regexp org-target-link-regexp)
6251 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6252 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6253 (targets
6254 (org-with-wide-buffer
6255 (goto-char (point-min))
6256 (let (rtn)
6257 (while (re-search-forward org-radio-target-regexp nil t)
6258 ;; Make sure point is really within the object.
6259 (backward-char)
6260 (let ((obj (org-element-context)))
6261 (when (eq (org-element-type obj) 'radio-target)
6262 (cl-pushnew (org-element-property :value obj) rtn
6263 :test #'equal))))
6264 rtn))))
6265 (setq org-target-link-regexp
6266 (and targets
6267 (concat before-re
6268 (mapconcat
6269 (lambda (x)
6270 (replace-regexp-in-string
6271 " +" "\\s-+" (regexp-quote x) t t))
6272 targets
6273 "\\|")
6274 after-re)))
6275 (unless (equal old-regexp org-target-link-regexp)
6276 ;; Clean-up cache.
6277 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6278 ((not org-target-link-regexp) old-regexp)
6280 (concat before-re
6281 (mapconcat
6282 (lambda (re)
6283 (substring re (length before-re)
6284 (- (length after-re))))
6285 (list old-regexp org-target-link-regexp)
6286 "\\|")
6287 after-re)))))
6288 (org-with-wide-buffer
6289 (goto-char (point-min))
6290 (while (re-search-forward regexp nil t)
6291 (org-element-cache-refresh (match-beginning 1)))))
6292 ;; Re fontify buffer.
6293 (when (memq 'radio org-highlight-links)
6294 (org-restart-font-lock)))))
6296 (defun org-hide-wide-columns (limit)
6297 (let (s e)
6298 (setq s (text-property-any (point) (or limit (point-max))
6299 'org-cwidth t))
6300 (when s
6301 (setq e (next-single-property-change s 'org-cwidth))
6302 (add-text-properties s e '(invisible org-cwidth))
6303 (goto-char e)
6304 t)))
6306 (defvar org-latex-and-related-regexp nil
6307 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6309 (defun org-compute-latex-and-related-regexp ()
6310 "Compute regular expression for LaTeX, entities and sub/superscript.
6311 Result depends on variable `org-highlight-latex-and-related'."
6312 (setq-local
6313 org-latex-and-related-regexp
6314 (let* ((re-sub
6315 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6316 ((eq org-use-sub-superscripts '{})
6317 (list org-match-substring-with-braces-regexp))
6318 (org-use-sub-superscripts (list org-match-substring-regexp))))
6319 (re-latex
6320 (when (memq 'latex org-highlight-latex-and-related)
6321 (let ((matchers (plist-get org-format-latex-options :matchers)))
6322 (delq nil
6323 (mapcar (lambda (x)
6324 (and (member (car x) matchers) (nth 1 x)))
6325 org-latex-regexps)))))
6326 (re-entities
6327 (when (memq 'entities org-highlight-latex-and-related)
6328 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6329 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6331 (defun org-do-latex-and-related (limit)
6332 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6333 LIMIT bounds the search for syntax to highlight. Stop at first
6334 highlighted object, if any. Return t if some highlighting was
6335 done, nil otherwise."
6336 (when (org-string-nw-p org-latex-and-related-regexp)
6337 (catch 'found
6338 (while (re-search-forward org-latex-and-related-regexp limit t)
6339 (unless
6340 (cl-some
6341 (lambda (f)
6342 (memq f '(org-code org-verbatim underline org-special-keyword)))
6343 (save-excursion
6344 (goto-char (1+ (match-beginning 0)))
6345 (face-at-point nil t)))
6346 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6347 '(?_ ?^))
6349 0)))
6350 (font-lock-prepend-text-property
6351 (+ offset (match-beginning 0)) (match-end 0)
6352 'face 'org-latex-and-related)
6353 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6354 '(font-lock-multiline t)))
6355 (throw 'found t)))
6356 nil)))
6358 (defun org-restart-font-lock ()
6359 "Restart `font-lock-mode', to force refontification."
6360 (when (and (boundp 'font-lock-mode) font-lock-mode)
6361 (font-lock-mode -1)
6362 (font-lock-mode 1)))
6364 (defun org-activate-tags (limit)
6365 (when (re-search-forward
6366 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6367 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6368 (add-text-properties (match-beginning 1) (match-end 1)
6369 (list 'mouse-face 'highlight
6370 'keymap org-mouse-map))
6371 (org-rear-nonsticky-at (match-end 1))
6374 (defun org-outline-level ()
6375 "Compute the outline level of the heading at point.
6377 If this is called at a normal headline, the level is the number
6378 of stars. Use `org-reduced-level' to remove the effect of
6379 `org-odd-levels'. Unlike to `org-current-level', this function
6380 takes into consideration inlinetasks."
6381 (org-with-wide-buffer
6382 (end-of-line)
6383 (if (re-search-backward org-outline-regexp-bol nil t)
6384 (1- (- (match-end 0) (match-beginning 0)))
6385 0)))
6387 (defvar org-font-lock-keywords nil)
6389 (defsubst org-re-property (property &optional literal allow-null value)
6390 "Return a regexp matching a PROPERTY line.
6392 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6393 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6394 non-nil, match properties even without a value.
6396 Match group 3 is set to the value when it exists. If there is no
6397 value and ALLOW-NULL is non-nil, it is set to the empty string.
6399 With optional argument VALUE, match only property lines with
6400 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6401 unless LITERAL is non-nil."
6402 (concat
6403 "^\\(?4:[ \t]*\\)"
6404 (format "\\(?1::\\(?2:%s\\):\\)"
6405 (if literal property (regexp-quote property)))
6406 (cond (value
6407 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6408 (if literal value (regexp-quote value))))
6409 (allow-null
6410 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6412 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6414 (defconst org-property-re
6415 (org-re-property "\\S-+" 'literal t)
6416 "Regular expression matching a property line.
6417 There are four matching groups:
6418 1: :PROPKEY: including the leading and trailing colon,
6419 2: PROPKEY without the leading and trailing colon,
6420 3: PROPVAL without leading or trailing spaces,
6421 4: the indentation of the current line,
6422 5: trailing whitespace.")
6424 (defvar org-font-lock-hook nil
6425 "Functions to be called for special font lock stuff.")
6427 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6429 (defvar org-font-lock-set-keywords-hook nil
6430 "Functions that can manipulate `org-font-lock-extra-keywords'.
6431 This is called after `org-font-lock-extra-keywords' is defined, but before
6432 it is installed to be used by font lock. This can be useful if something
6433 needs to be inserted at a specific position in the font-lock sequence.")
6435 (defun org-font-lock-hook (limit)
6436 "Run `org-font-lock-hook' within LIMIT."
6437 (run-hook-with-args 'org-font-lock-hook limit))
6439 (defun org-set-font-lock-defaults ()
6440 "Set font lock defaults for the current buffer."
6441 (let* ((em org-fontify-emphasized-text)
6442 (lk org-highlight-links)
6443 (org-font-lock-extra-keywords
6444 (list
6445 ;; Call the hook
6446 '(org-font-lock-hook)
6447 ;; Headlines
6448 `(,(if org-fontify-whole-heading-line
6449 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6450 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6451 (1 (org-get-level-face 1))
6452 (2 (org-get-level-face 2))
6453 (3 (org-get-level-face 3)))
6454 ;; Table lines
6455 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6456 (1 'org-table t))
6457 ;; Table internals
6458 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6459 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6460 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6461 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6462 ;; Drawers
6463 '(org-fontify-drawers)
6464 ;; Properties
6465 (list org-property-re
6466 '(1 'org-special-keyword t)
6467 '(3 'org-property-value t))
6468 ;; Link related fontification.
6469 '(org-activate-links)
6470 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6471 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6472 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6473 (when (memq 'footnote lk) '(org-activate-footnote-links))
6474 ;; Targets.
6475 (list org-any-target-regexp '(0 'org-target t))
6476 ;; Diary sexps.
6477 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6478 ;; Macro
6479 '(org-fontify-macros)
6480 '(org-hide-wide-columns (0 nil append))
6481 ;; TODO keyword
6482 (list (format org-heading-keyword-regexp-format
6483 org-todo-regexp)
6484 '(2 (org-get-todo-face 2) t))
6485 ;; DONE
6486 (if org-fontify-done-headline
6487 (list (format org-heading-keyword-regexp-format
6488 (concat
6489 "\\(?:"
6490 (mapconcat 'regexp-quote org-done-keywords "\\|")
6491 "\\)"))
6492 '(2 'org-headline-done t))
6493 nil)
6494 ;; Priorities
6495 '(org-font-lock-add-priority-faces)
6496 ;; Tags
6497 '(org-font-lock-add-tag-faces)
6498 ;; Tags groups
6499 (when (and org-group-tags org-tag-groups-alist)
6500 (list (concat org-outline-regexp-bol ".+\\(:"
6501 (regexp-opt (mapcar 'car org-tag-groups-alist))
6502 ":\\).*$")
6503 '(1 'org-tag-group prepend)))
6504 ;; Special keywords
6505 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6506 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6507 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6508 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6509 ;; Emphasis
6510 (when em '(org-do-emphasis-faces))
6511 ;; Checkboxes
6512 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6513 1 'org-checkbox prepend)
6514 (when (cdr (assq 'checkbox org-list-automatic-rules))
6515 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6516 (0 (org-get-checkbox-statistics-face) t)))
6517 ;; Description list items
6518 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6519 1 'org-list-dt prepend)
6520 ;; ARCHIVEd headings
6521 (list (concat
6522 org-outline-regexp-bol
6523 "\\(.*:" org-archive-tag ":.*\\)")
6524 '(1 'org-archived prepend))
6525 ;; Specials
6526 '(org-do-latex-and-related)
6527 '(org-fontify-entities)
6528 '(org-raise-scripts)
6529 ;; Code
6530 '(org-activate-code (1 'org-code t))
6531 ;; COMMENT
6532 (list (format
6533 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6534 org-todo-regexp
6535 org-comment-string)
6536 '(9 'org-special-keyword t))
6537 ;; Blocks and meta lines
6538 '(org-fontify-meta-lines-and-blocks))))
6539 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6540 (run-hooks 'org-font-lock-set-keywords-hook)
6541 ;; Now set the full font-lock-keywords
6542 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6543 (setq-local font-lock-defaults
6544 '(org-font-lock-keywords t nil nil backward-paragraph))
6545 (kill-local-variable 'font-lock-keywords)
6546 nil))
6548 (defun org-toggle-pretty-entities ()
6549 "Toggle the composition display of entities as UTF8 characters."
6550 (interactive)
6551 (setq-local org-pretty-entities (not org-pretty-entities))
6552 (org-restart-font-lock)
6553 (if org-pretty-entities
6554 (message "Entities are now displayed as UTF8 characters")
6555 (save-restriction
6556 (widen)
6557 (decompose-region (point-min) (point-max))
6558 (message "Entities are now displayed as plain text"))))
6560 (defvar-local org-custom-properties-overlays nil
6561 "List of overlays used for custom properties.")
6563 (defun org-toggle-custom-properties-visibility ()
6564 "Display or hide properties in `org-custom-properties'."
6565 (interactive)
6566 (if org-custom-properties-overlays
6567 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6568 (setq org-custom-properties-overlays nil))
6569 (when org-custom-properties
6570 (org-with-wide-buffer
6571 (goto-char (point-min))
6572 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6573 (while (re-search-forward regexp nil t)
6574 (let ((end (cdr (save-match-data (org-get-property-block)))))
6575 (when (and end (< (point) end))
6576 ;; Hide first custom property in current drawer.
6577 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6578 (overlay-put o 'invisible t)
6579 (overlay-put o 'org-custom-property t)
6580 (push o org-custom-properties-overlays))
6581 ;; Hide additional custom properties in the same drawer.
6582 (while (re-search-forward regexp end t)
6583 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6584 (overlay-put o 'invisible t)
6585 (overlay-put o 'org-custom-property t)
6586 (push o org-custom-properties-overlays)))))
6587 ;; Each entry is limited to a single property drawer.
6588 (outline-next-heading)))))))
6590 (defun org-fontify-entities (limit)
6591 "Find an entity to fontify."
6592 (let (ee)
6593 (when org-pretty-entities
6594 (catch 'match
6595 ;; "\_ "-family is left out on purpose. Only the first one,
6596 ;; i.e., "\_ ", could be fontified anyway, and it would be
6597 ;; confusing when adding a second white space character.
6598 (while (re-search-forward
6599 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6600 limit t)
6601 (when (and (not (org-at-comment-p))
6602 (setq ee (org-entity-get (match-string 1)))
6603 (= (length (nth 6 ee)) 1))
6604 (let* ((end (if (equal (match-string 2) "{}")
6605 (match-end 2)
6606 (match-end 1))))
6607 (add-text-properties
6608 (match-beginning 0) end
6609 (list 'font-lock-fontified t))
6610 (compose-region (match-beginning 0) end
6611 (nth 6 ee) nil)
6612 (backward-char 1)
6613 (throw 'match t))))
6614 nil))))
6616 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6617 "Fontify string S like in Org mode."
6618 (with-temp-buffer
6619 (insert s)
6620 (let ((org-odd-levels-only odd-levels))
6621 (org-mode)
6622 (org-font-lock-ensure)
6623 (buffer-string))))
6625 (defvar org-m nil)
6626 (defvar org-l nil)
6627 (defvar org-f nil)
6628 (defun org-get-level-face (n)
6629 "Get the right face for match N in font-lock matching of headlines."
6630 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6631 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6632 (if org-cycle-level-faces
6633 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6634 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6635 (cond
6636 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6637 ((eq n 2) org-f)
6638 (t (unless org-level-color-stars-only org-f))))
6640 (defun org-face-from-face-or-color (context inherit face-or-color)
6641 "Create a face list that inherits INHERIT, but sets the foreground color.
6642 When FACE-OR-COLOR is not a string, just return it."
6643 (if (stringp face-or-color)
6644 (list :inherit inherit
6645 (cdr (assoc context org-faces-easy-properties))
6646 face-or-color)
6647 face-or-color))
6649 (defun org-get-todo-face (kwd)
6650 "Get the right face for a TODO keyword KWD.
6651 If KWD is a number, get the corresponding match group."
6652 (when (numberp kwd) (setq kwd (match-string kwd)))
6653 (or (org-face-from-face-or-color
6654 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6655 (and (member kwd org-done-keywords) 'org-done)
6656 'org-todo))
6658 (defun org-get-priority-face (priority)
6659 "Get the right face for PRIORITY.
6660 PRIORITY is a character."
6661 (or (org-face-from-face-or-color
6662 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6663 'org-priority))
6665 (defun org-get-tag-face (tag)
6666 "Get the right face for TAG.
6667 If TAG is a number, get the corresponding match group."
6668 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6669 (or (org-face-from-face-or-color
6670 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6671 'org-tag)))
6673 (defun org-font-lock-add-priority-faces (limit)
6674 "Add the special priority faces."
6675 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6676 (add-text-properties
6677 (match-beginning 1) (match-end 1)
6678 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6679 'font-lock-fontified t))))
6681 (defun org-font-lock-add-tag-faces (limit)
6682 "Add the special tag faces."
6683 (when (and org-tag-faces org-tags-special-faces-re)
6684 (while (re-search-forward org-tags-special-faces-re limit t)
6685 (add-text-properties (match-beginning 1) (match-end 1)
6686 (list 'face (org-get-tag-face 1)
6687 'font-lock-fontified t))
6688 (backward-char 1))))
6690 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6691 "Remove fontification and activation overlays from links."
6692 (font-lock-default-unfontify-region beg end)
6693 (let* ((buffer-undo-list t)
6694 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6695 (inhibit-modification-hooks t)
6696 deactivate-mark buffer-file-name buffer-file-truename)
6697 (decompose-region beg end)
6698 (remove-text-properties beg end
6699 '(mouse-face t keymap t org-linked-text t
6700 invisible t intangible t
6701 org-emphasis t))
6702 (org-remove-font-lock-display-properties beg end)))
6704 (defconst org-script-display '(((raise -0.3) (height 0.7))
6705 ((raise 0.3) (height 0.7))
6706 ((raise -0.5))
6707 ((raise 0.5)))
6708 "Display properties for showing superscripts and subscripts.")
6710 (defun org-remove-font-lock-display-properties (beg end)
6711 "Remove specific display properties that have been added by font lock.
6712 The will remove the raise properties that are used to show superscripts
6713 and subscripts."
6714 (let (next prop)
6715 (while (< beg end)
6716 (setq next (next-single-property-change beg 'display nil end)
6717 prop (get-text-property beg 'display))
6718 (when (member prop org-script-display)
6719 (put-text-property beg next 'display nil))
6720 (setq beg next))))
6722 (defun org-raise-scripts (limit)
6723 "Add raise properties to sub/superscripts."
6724 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6725 (re-search-forward
6726 (if (eq org-use-sub-superscripts t)
6727 org-match-substring-regexp
6728 org-match-substring-with-braces-regexp)
6729 limit t))
6730 (let* ((pos (point)) table-p comment-p
6731 (mpos (match-beginning 3))
6732 (emph-p (get-text-property mpos 'org-emphasis))
6733 (link-p (get-text-property mpos 'mouse-face))
6734 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6735 (goto-char (point-at-bol))
6736 (setq table-p (looking-at-p org-table-dataline-regexp)
6737 comment-p (looking-at-p "^[ \t]*#[ +]"))
6738 (goto-char pos)
6739 ;; Handle a_b^c
6740 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6741 (unless (or comment-p emph-p link-p keyw-p)
6742 (put-text-property (match-beginning 3) (match-end 0)
6743 'display
6744 (if (equal (char-after (match-beginning 2)) ?^)
6745 (nth (if table-p 3 1) org-script-display)
6746 (nth (if table-p 2 0) org-script-display)))
6747 (add-text-properties (match-beginning 2) (match-end 2)
6748 (list 'invisible t
6749 'org-dwidth t 'org-dwidth-n 1))
6750 (if (and (eq (char-after (match-beginning 3)) ?{)
6751 (eq (char-before (match-end 3)) ?}))
6752 (progn
6753 (add-text-properties
6754 (match-beginning 3) (1+ (match-beginning 3))
6755 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6756 (add-text-properties
6757 (1- (match-end 3)) (match-end 3)
6758 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6759 t)))
6761 ;;;; Visibility cycling, including org-goto and indirect buffer
6763 ;;; Cycling
6765 (defvar-local org-cycle-global-status nil)
6766 (put 'org-cycle-global-status 'org-state t)
6767 (defvar-local org-cycle-subtree-status nil)
6768 (put 'org-cycle-subtree-status 'org-state t)
6770 (defvar org-inlinetask-min-level)
6772 (defun org-unlogged-message (&rest args)
6773 "Display a message, but avoid logging it in the *Messages* buffer."
6774 (let ((message-log-max nil))
6775 (apply 'message args)))
6777 ;;;###autoload
6778 (defun org-cycle (&optional arg)
6779 "TAB-action and visibility cycling for Org mode.
6781 This is the command invoked in Org mode by the `TAB' key. Its main
6782 purpose is outline visibility cycling, but it also invokes other actions
6783 in special contexts.
6785 When this function is called with a `\\[universal-argument]' prefix, rotate \
6786 the entire
6787 buffer through 3 states (global cycling)
6788 1. OVERVIEW: Show only top-level headlines.
6789 2. CONTENTS: Show all headlines of all levels, but no body text.
6790 3. SHOW ALL: Show everything.
6792 With a `\\[universal-argument] \\[universal-argument]' prefix argument, \
6793 switch to the startup visibility,
6794 determined by the variable `org-startup-folded', and by any VISIBILITY
6795 properties in the buffer.
6797 With a `\\[universal-argument] \\[universal-argument] \
6798 \\[universal-argument]' prefix argument, show the entire buffer, including
6799 any drawers.
6801 When inside a table, re-align the table and move to the next field.
6803 When point is at the beginning of a headline, rotate the subtree started
6804 by this line through 3 different states (local cycling)
6805 1. FOLDED: Only the main headline is shown.
6806 2. CHILDREN: The main headline and the direct children are shown.
6807 From this state, you can move to one of the children
6808 and zoom in further.
6809 3. SUBTREE: Show the entire subtree, including body text.
6810 If there is no subtree, switch directly from CHILDREN to FOLDED.
6812 When point is at the beginning of an empty headline and the variable
6813 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6814 of the headline by demoting and promoting it to likely levels. This
6815 speeds up creation document structure by pressing `TAB' once or several
6816 times right after creating a new headline.
6818 When there is a numeric prefix, go up to a heading with level ARG, do
6819 a `show-subtree' and return to the previous cursor position. If ARG
6820 is negative, go up that many levels.
6822 When point is not at the beginning of a headline, execute the global
6823 binding for `TAB', which is re-indenting the line. See the option
6824 `org-cycle-emulate-tab' for details.
6826 As a special case, if point is at the beginning of the buffer and there is
6827 no headline in line 1, this function will act as if called with prefix arg
6828 \(`\\[universal-argument] TAB', same as `S-TAB') also when called without \
6829 prefix arg, but only
6830 if the variable `org-cycle-global-at-bob' is t."
6831 (interactive "P")
6832 (org-load-modules-maybe)
6833 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6834 (and org-cycle-level-after-item/entry-creation
6835 (or (org-cycle-level)
6836 (org-cycle-item-indentation))))
6837 (let* ((limit-level
6838 (or org-cycle-max-level
6839 (and (boundp 'org-inlinetask-min-level)
6840 org-inlinetask-min-level
6841 (1- org-inlinetask-min-level))))
6842 (nstars (and limit-level
6843 (if org-odd-levels-only
6844 (and limit-level (1- (* limit-level 2)))
6845 limit-level)))
6846 (org-outline-regexp
6847 (if (not (derived-mode-p 'org-mode))
6848 outline-regexp
6849 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6850 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6851 (not (looking-at org-outline-regexp))))
6852 (org-cycle-hook
6853 (if bob-special
6854 (delq 'org-optimize-window-after-visibility-change
6855 (copy-sequence org-cycle-hook))
6856 org-cycle-hook))
6857 (pos (point)))
6859 (cond
6861 ((equal arg '(16))
6862 (setq last-command 'dummy)
6863 (org-set-startup-visibility)
6864 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6866 ((equal arg '(64))
6867 (outline-show-all)
6868 (org-unlogged-message "Entire buffer visible, including drawers"))
6870 ((equal arg '(4)) (org-cycle-internal-global))
6872 ;; Try hiding block at point.
6873 ((org-hide-block-toggle-maybe))
6875 ;; Try cdlatex TAB completion
6876 ((org-try-cdlatex-tab))
6878 ;; Table: enter it or move to the next field.
6879 ((org-at-table-p 'any)
6880 (if (org-at-table.el-p)
6881 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6882 Use `\\[org-edit-special]' to edit table.el tables"))
6883 (if arg (org-table-edit-field t)
6884 (org-table-justify-field-maybe)
6885 (call-interactively 'org-table-next-field))))
6887 ((run-hook-with-args-until-success 'org-tab-after-check-for-table-hook))
6889 ;; Global cycling: delegate to `org-cycle-internal-global'.
6890 (bob-special (org-cycle-internal-global))
6892 ;; Drawers: delegate to `org-flag-drawer'.
6893 ((save-excursion
6894 (beginning-of-line 1)
6895 (looking-at org-drawer-regexp))
6896 (org-flag-drawer ; toggle block visibility
6897 (not (get-char-property (match-end 0) 'invisible))))
6899 ;; Show-subtree, ARG levels up from here.
6900 ((integerp arg)
6901 (save-excursion
6902 (org-back-to-heading)
6903 (outline-up-heading (if (< arg 0) (- arg)
6904 (- (funcall outline-level) arg)))
6905 (org-show-subtree)))
6907 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6908 ((and (featurep 'org-inlinetask)
6909 (org-inlinetask-at-task-p)
6910 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6911 (org-inlinetask-toggle-visibility))
6913 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6914 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6915 (save-excursion (move-beginning-of-line 1)
6916 (looking-at org-outline-regexp)))
6917 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6918 (org-cycle-internal-local))
6920 ;; From there: TAB emulation and template completion.
6921 (buffer-read-only (org-back-to-heading))
6923 ((run-hook-with-args-until-success
6924 'org-tab-after-check-for-cycling-hook))
6926 ((org-try-structure-completion))
6928 ((run-hook-with-args-until-success
6929 'org-tab-before-tab-emulation-hook))
6931 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6932 (or (not (bolp))
6933 (not (looking-at org-outline-regexp))))
6934 (call-interactively (global-key-binding "\t")))
6936 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6937 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6938 (or (and (eq org-cycle-emulate-tab 'white)
6939 (= (match-end 0) (point-at-eol)))
6940 (and (eq org-cycle-emulate-tab 'whitestart)
6941 (>= (match-end 0) pos))))
6943 (eq org-cycle-emulate-tab t))
6944 (call-interactively (global-key-binding "\t")))
6946 (t (save-excursion
6947 (org-back-to-heading)
6948 (org-cycle)))))))
6950 (defun org-cycle-internal-global ()
6951 "Do the global cycling action."
6952 ;; Hack to avoid display of messages for .org attachments in Gnus
6953 (let ((ga (string-match "\\*fontification" (buffer-name))))
6954 (cond
6955 ((and (eq last-command this-command)
6956 (eq org-cycle-global-status 'overview))
6957 ;; We just created the overview - now do table of contents
6958 ;; This can be slow in very large buffers, so indicate action
6959 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6960 (unless ga (org-unlogged-message "CONTENTS..."))
6961 (org-content)
6962 (unless ga (org-unlogged-message "CONTENTS...done"))
6963 (setq org-cycle-global-status 'contents)
6964 (run-hook-with-args 'org-cycle-hook 'contents))
6966 ((and (eq last-command this-command)
6967 (eq org-cycle-global-status 'contents))
6968 ;; We just showed the table of contents - now show everything
6969 (run-hook-with-args 'org-pre-cycle-hook 'all)
6970 (outline-show-all)
6971 (unless ga (org-unlogged-message "SHOW ALL"))
6972 (setq org-cycle-global-status 'all)
6973 (run-hook-with-args 'org-cycle-hook 'all))
6976 ;; Default action: go to overview
6977 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6978 (org-overview)
6979 (unless ga (org-unlogged-message "OVERVIEW"))
6980 (setq org-cycle-global-status 'overview)
6981 (run-hook-with-args 'org-cycle-hook 'overview)))))
6983 (defvar org-called-with-limited-levels nil
6984 "Non-nil when `org-with-limited-levels' is currently active.")
6986 (defun org-cycle-internal-local ()
6987 "Do the local cycling action."
6988 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6989 ;; First, determine end of headline (EOH), end of subtree or item
6990 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6991 (save-excursion
6992 (if (org-at-item-p)
6993 (progn
6994 (beginning-of-line)
6995 (setq struct (org-list-struct))
6996 (setq eoh (point-at-eol))
6997 (setq eos (org-list-get-item-end-before-blank (point) struct))
6998 (setq has-children (org-list-has-child-p (point) struct)))
6999 (org-back-to-heading)
7000 (setq eoh (save-excursion (outline-end-of-heading) (point)))
7001 (setq eos (save-excursion (org-end-of-subtree t t)
7002 (when (bolp) (backward-char)) (point)))
7003 (setq has-children
7004 (or (save-excursion
7005 (let ((level (funcall outline-level)))
7006 (outline-next-heading)
7007 (and (org-at-heading-p t)
7008 (> (funcall outline-level) level))))
7009 (save-excursion
7010 (org-list-search-forward (org-item-beginning-re) eos t)))))
7011 ;; Determine end invisible part of buffer (EOL)
7012 (beginning-of-line 2)
7013 (while (and (not (eobp)) ;This is like `next-line'.
7014 (get-char-property (1- (point)) 'invisible))
7015 (goto-char (next-single-char-property-change (point) 'invisible))
7016 (and (eolp) (beginning-of-line 2)))
7017 (setq eol (point)))
7018 ;; Find out what to do next and set `this-command'
7019 (cond
7020 ((= eos eoh)
7021 ;; Nothing is hidden behind this heading
7022 (unless (org-before-first-heading-p)
7023 (run-hook-with-args 'org-pre-cycle-hook 'empty))
7024 (org-unlogged-message "EMPTY ENTRY")
7025 (setq org-cycle-subtree-status nil)
7026 (save-excursion
7027 (goto-char eos)
7028 (outline-next-heading)
7029 (when (outline-invisible-p) (org-flag-heading nil))))
7030 ((and (or (>= eol eos)
7031 (not (string-match "\\S-" (buffer-substring eol eos))))
7032 (or has-children
7033 (not (setq children-skipped
7034 org-cycle-skip-children-state-if-no-children))))
7035 ;; Entire subtree is hidden in one line: children view
7036 (unless (org-before-first-heading-p)
7037 (run-hook-with-args 'org-pre-cycle-hook 'children))
7038 (if (org-at-item-p)
7039 (org-list-set-item-visibility (point-at-bol) struct 'children)
7040 (org-show-entry)
7041 (org-with-limited-levels (org-show-children))
7042 ;; FIXME: This slows down the func way too much.
7043 ;; How keep drawers hidden in subtree anyway?
7044 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
7045 ;; (org-cycle-hide-drawers 'subtree))
7047 ;; Fold every list in subtree to top-level items.
7048 (when (eq org-cycle-include-plain-lists 'integrate)
7049 (save-excursion
7050 (org-back-to-heading)
7051 (while (org-list-search-forward (org-item-beginning-re) eos t)
7052 (beginning-of-line 1)
7053 (let* ((struct (org-list-struct))
7054 (prevs (org-list-prevs-alist struct))
7055 (end (org-list-get-bottom-point struct)))
7056 (dolist (e (org-list-get-all-items (point) struct prevs))
7057 (org-list-set-item-visibility e struct 'folded))
7058 (goto-char (if (< end eos) end eos)))))))
7059 (org-unlogged-message "CHILDREN")
7060 (save-excursion
7061 (goto-char eos)
7062 (outline-next-heading)
7063 (when (outline-invisible-p) (org-flag-heading nil)))
7064 (setq org-cycle-subtree-status 'children)
7065 (unless (org-before-first-heading-p)
7066 (run-hook-with-args 'org-cycle-hook 'children)))
7067 ((or children-skipped
7068 (and (eq last-command this-command)
7069 (eq org-cycle-subtree-status 'children)))
7070 ;; We just showed the children, or no children are there,
7071 ;; now show everything.
7072 (unless (org-before-first-heading-p)
7073 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
7074 (outline-flag-region eoh eos nil)
7075 (org-unlogged-message
7076 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
7077 (setq org-cycle-subtree-status 'subtree)
7078 (unless (org-before-first-heading-p)
7079 (run-hook-with-args 'org-cycle-hook 'subtree)))
7081 ;; Default action: hide the subtree.
7082 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7083 (outline-flag-region eoh eos t)
7084 (org-unlogged-message "FOLDED")
7085 (setq org-cycle-subtree-status 'folded)
7086 (unless (org-before-first-heading-p)
7087 (run-hook-with-args 'org-cycle-hook 'folded))))))
7089 ;;;###autoload
7090 (defun org-global-cycle (&optional arg)
7091 "Cycle the global visibility. For details see `org-cycle'.
7092 With `\\[universal-argument]' prefix ARG, switch to startup visibility.
7093 With a numeric prefix, show all headlines up to that level."
7094 (interactive "P")
7095 (let ((org-cycle-include-plain-lists
7096 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7097 (cond
7098 ((integerp arg)
7099 (outline-show-all)
7100 (outline-hide-sublevels arg)
7101 (setq org-cycle-global-status 'contents))
7102 ((equal arg '(4))
7103 (org-set-startup-visibility)
7104 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7106 (org-cycle '(4))))))
7108 (defun org-set-startup-visibility ()
7109 "Set the visibility required by startup options and properties."
7110 (cond
7111 ((eq org-startup-folded t)
7112 (org-overview))
7113 ((eq org-startup-folded 'content)
7114 (org-content))
7115 ((or (eq org-startup-folded 'showeverything)
7116 (eq org-startup-folded nil))
7117 (outline-show-all)))
7118 (unless (eq org-startup-folded 'showeverything)
7119 (when org-hide-block-startup (org-hide-block-all))
7120 (org-set-visibility-according-to-property 'no-cleanup)
7121 (org-cycle-hide-archived-subtrees 'all)
7122 (org-cycle-hide-drawers 'all)
7123 (org-cycle-show-empty-lines t)))
7125 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7126 "Switch subtree visibilities according to :VISIBILITY: property."
7127 (interactive)
7128 (org-with-wide-buffer
7129 (goto-char (point-min))
7130 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7131 (if (not (org-at-property-p)) (outline-next-heading)
7132 (let ((state (match-string 3)))
7133 (save-excursion
7134 (org-back-to-heading t)
7135 (outline-hide-subtree)
7136 (org-reveal)
7137 (cond
7138 ((equal state "folded")
7139 (outline-hide-subtree))
7140 ((equal state "children")
7141 (org-show-hidden-entry)
7142 (org-show-children))
7143 ((equal state "content")
7144 (save-excursion
7145 (save-restriction
7146 (org-narrow-to-subtree)
7147 (org-content))))
7148 ((member state '("all" "showall"))
7149 (outline-show-subtree)))))))
7150 (unless no-cleanup
7151 (org-cycle-hide-archived-subtrees 'all)
7152 (org-cycle-hide-drawers 'all)
7153 (org-cycle-show-empty-lines 'all))))
7155 ;; This function uses outline-regexp instead of the more fundamental
7156 ;; org-outline-regexp so that org-cycle-global works outside of Org
7157 ;; buffers, where outline-regexp is needed.
7158 (defun org-overview ()
7159 "Switch to overview mode, showing only top-level headlines.
7160 This shows all headlines with a level equal or greater than the level
7161 of the first headline in the buffer. This is important, because if the
7162 first headline is not level one, then (hide-sublevels 1) gives confusing
7163 results."
7164 (interactive)
7165 (save-excursion
7166 (let ((level
7167 (save-excursion
7168 (goto-char (point-min))
7169 (when (re-search-forward (concat "^" outline-regexp) nil t)
7170 (goto-char (match-beginning 0))
7171 (funcall outline-level)))))
7172 (and level (outline-hide-sublevels level)))))
7174 (defun org-content (&optional arg)
7175 "Show all headlines in the buffer, like a table of contents.
7176 With numerical argument N, show content up to level N."
7177 (interactive "P")
7178 (org-overview)
7179 (save-excursion
7180 ;; Visit all headings and show their offspring
7181 (and (integerp arg) (org-overview))
7182 (goto-char (point-max))
7183 (catch 'exit
7184 (while (and (progn (condition-case nil
7185 (outline-previous-visible-heading 1)
7186 (error (goto-char (point-min))))
7188 (looking-at org-outline-regexp))
7189 (if (integerp arg)
7190 (org-show-children (1- arg))
7191 (outline-show-branches))
7192 (when (bobp) (throw 'exit nil))))))
7194 (defun org-optimize-window-after-visibility-change (state)
7195 "Adjust the window after a change in outline visibility.
7196 This function is the default value of the hook `org-cycle-hook'."
7197 (when (get-buffer-window (current-buffer))
7198 (cond
7199 ((eq state 'content) nil)
7200 ((eq state 'all) nil)
7201 ((eq state 'folded) nil)
7202 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7203 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7205 (defun org-remove-empty-overlays-at (pos)
7206 "Remove outline overlays that do not contain non-white stuff."
7207 (dolist (o (overlays-at pos))
7208 (and (eq 'outline (overlay-get o 'invisible))
7209 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7210 (overlay-end o))))
7211 (delete-overlay o))))
7213 (defun org-clean-visibility-after-subtree-move ()
7214 "Fix visibility issues after moving a subtree."
7215 ;; First, find a reasonable region to look at:
7216 ;; Start two siblings above, end three below
7217 (let* ((beg (save-excursion
7218 (and (org-get-last-sibling)
7219 (org-get-last-sibling))
7220 (point)))
7221 (end (save-excursion
7222 (and (org-get-next-sibling)
7223 (org-get-next-sibling)
7224 (org-get-next-sibling))
7225 (if (org-at-heading-p)
7226 (point-at-eol)
7227 (point))))
7228 (level (looking-at "\\*+"))
7229 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7230 (save-excursion
7231 (save-restriction
7232 (narrow-to-region beg end)
7233 (when re
7234 ;; Properly fold already folded siblings
7235 (goto-char (point-min))
7236 (while (re-search-forward re nil t)
7237 (when (and (not (outline-invisible-p))
7238 (save-excursion
7239 (goto-char (point-at-eol)) (outline-invisible-p)))
7240 (outline-hide-entry))))
7241 (org-cycle-show-empty-lines 'overview)
7242 (org-cycle-hide-drawers 'overview)))))
7244 (defun org-cycle-show-empty-lines (state)
7245 "Show empty lines above all visible headlines.
7246 The region to be covered depends on STATE when called through
7247 `org-cycle-hook'. Lisp program can use t for STATE to get the
7248 entire buffer covered. Note that an empty line is only shown if there
7249 are at least `org-cycle-separator-lines' empty lines before the headline."
7250 (when (/= org-cycle-separator-lines 0)
7251 (save-excursion
7252 (let* ((n (abs org-cycle-separator-lines))
7253 (re (cond
7254 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7255 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7256 (t (let ((ns (number-to-string (- n 2))))
7257 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7258 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7259 beg end)
7260 (cond
7261 ((memq state '(overview contents t))
7262 (setq beg (point-min) end (point-max)))
7263 ((memq state '(children folded))
7264 (setq beg (point)
7265 end (progn (org-end-of-subtree t t)
7266 (line-beginning-position 2)))))
7267 (when beg
7268 (goto-char beg)
7269 (while (re-search-forward re end t)
7270 (unless (get-char-property (match-end 1) 'invisible)
7271 (let ((e (match-end 1))
7272 (b (if (>= org-cycle-separator-lines 0)
7273 (match-beginning 1)
7274 (save-excursion
7275 (goto-char (match-beginning 0))
7276 (skip-chars-backward " \t\n")
7277 (line-end-position)))))
7278 (outline-flag-region b e nil))))))))
7279 ;; Never hide empty lines at the end of the file.
7280 (save-excursion
7281 (goto-char (point-max))
7282 (outline-previous-heading)
7283 (outline-end-of-heading)
7284 (when (and (looking-at "[ \t\n]+")
7285 (= (match-end 0) (point-max)))
7286 (outline-flag-region (point) (match-end 0) nil))))
7288 (defun org-show-empty-lines-in-parent ()
7289 "Move to the parent and re-show empty lines before visible headlines."
7290 (save-excursion
7291 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7292 (org-cycle-show-empty-lines context))))
7294 (defun org-files-list ()
7295 "Return `org-agenda-files' list, plus all open Org files.
7296 This is useful for operations that need to scan all of a user's
7297 open and agenda-wise Org files."
7298 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7299 (dolist (buf (buffer-list))
7300 (with-current-buffer buf
7301 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7302 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7303 files))
7305 (defsubst org-entry-beginning-position ()
7306 "Return the beginning position of the current entry."
7307 (save-excursion (org-back-to-heading t) (point)))
7309 (defsubst org-entry-end-position ()
7310 "Return the end position of the current entry."
7311 (save-excursion (outline-next-heading) (point)))
7313 (defun org-cycle-hide-drawers (state &optional exceptions)
7314 "Re-hide all drawers after a visibility state change.
7315 When non-nil, optional argument EXCEPTIONS is a list of strings
7316 specifying which drawers should not be hidden."
7317 (when (and (derived-mode-p 'org-mode)
7318 (not (memq state '(overview folded contents))))
7319 (save-excursion
7320 (let* ((globalp (memq state '(contents all)))
7321 (beg (if globalp (point-min) (point)))
7322 (end (if globalp (point-max)
7323 (if (eq state 'children)
7324 (save-excursion (outline-next-heading) (point))
7325 (org-end-of-subtree t)))))
7326 (goto-char beg)
7327 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7328 (unless (member-ignore-case (match-string 1) exceptions)
7329 (let ((drawer (org-element-at-point)))
7330 (when (memq (org-element-type drawer) '(drawer property-drawer))
7331 (org-flag-drawer t drawer)
7332 ;; Make sure to skip drawer entirely or we might flag
7333 ;; it another time when matching its ending line with
7334 ;; `org-drawer-regexp'.
7335 (goto-char (org-element-property :end drawer))))))))))
7337 (defun org-flag-drawer (flag &optional element)
7338 "When FLAG is non-nil, hide the drawer we are at.
7339 Otherwise make it visible. When optional argument ELEMENT is
7340 a parsed drawer, as returned by `org-element-at-point', hide or
7341 show that drawer instead."
7342 (let ((drawer (or element
7343 (and (save-excursion
7344 (beginning-of-line)
7345 (looking-at-p org-drawer-regexp))
7346 (org-element-at-point)))))
7347 (when (memq (org-element-type drawer) '(drawer property-drawer))
7348 (let ((post (org-element-property :post-affiliated drawer)))
7349 (save-excursion
7350 (outline-flag-region
7351 (progn (goto-char post) (line-end-position))
7352 (progn (goto-char (org-element-property :end drawer))
7353 (skip-chars-backward " \r\t\n")
7354 (line-end-position))
7355 flag))
7356 ;; When the drawer is hidden away, make sure point lies in
7357 ;; a visible part of the buffer.
7358 (when (and flag (> (line-beginning-position) post))
7359 (goto-char post))))))
7361 (defun org-subtree-end-visible-p ()
7362 "Is the end of the current subtree visible?"
7363 (pos-visible-in-window-p
7364 (save-excursion (org-end-of-subtree t) (point))))
7366 (defun org-first-headline-recenter ()
7367 "Move cursor to the first headline and recenter the headline."
7368 (let ((window (get-buffer-window)))
7369 (when window
7370 (goto-char (point-min))
7371 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7372 (set-window-start window (line-beginning-position))))))
7374 ;;; Saving and restoring visibility
7376 (defun org-outline-overlay-data (&optional use-markers)
7377 "Return a list of the locations of all outline overlays.
7378 These are overlays with the `invisible' property value `outline'.
7379 The return value is a list of cons cells, with start and stop
7380 positions for each overlay.
7381 If USE-MARKERS is set, return the positions as markers."
7382 (let (beg end)
7383 (org-with-wide-buffer
7384 (delq nil
7385 (mapcar (lambda (o)
7386 (when (eq (overlay-get o 'invisible) 'outline)
7387 (setq beg (overlay-start o)
7388 end (overlay-end o))
7389 (and beg end (> end beg)
7390 (if use-markers
7391 (cons (copy-marker beg)
7392 (copy-marker end t))
7393 (cons beg end)))))
7394 (overlays-in (point-min) (point-max)))))))
7396 (defun org-set-outline-overlay-data (data)
7397 "Create visibility overlays for all positions in DATA.
7398 DATA should have been made by `org-outline-overlay-data'."
7399 (org-with-wide-buffer
7400 (outline-show-all)
7401 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7403 ;;; Folding of blocks
7405 (defvar-local org-hide-block-overlays nil
7406 "Overlays hiding blocks.")
7408 (defun org-block-map (function &optional start end)
7409 "Call FUNCTION at the head of all source blocks in the current buffer.
7410 Optional arguments START and END can be used to limit the range."
7411 (let ((start (or start (point-min)))
7412 (end (or end (point-max))))
7413 (save-excursion
7414 (goto-char start)
7415 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7416 (save-excursion
7417 (save-match-data
7418 (goto-char (match-beginning 0))
7419 (funcall function)))))))
7421 (defun org-hide-block-toggle-all ()
7422 "Toggle the visibility of all blocks in the current buffer."
7423 (org-block-map 'org-hide-block-toggle))
7425 (defun org-hide-block-all ()
7426 "Fold all blocks in the current buffer."
7427 (interactive)
7428 (org-show-block-all)
7429 (org-block-map 'org-hide-block-toggle-maybe))
7431 (defun org-show-block-all ()
7432 "Unfold all blocks in the current buffer."
7433 (interactive)
7434 (mapc #'delete-overlay org-hide-block-overlays)
7435 (setq org-hide-block-overlays nil))
7437 (defun org-hide-block-toggle-maybe ()
7438 "Toggle visibility of block at point.
7439 Unlike to `org-hide-block-toggle', this function does not throw
7440 an error. Return a non-nil value when toggling is successful."
7441 (interactive)
7442 (ignore-errors (org-hide-block-toggle)))
7444 (defun org-hide-block-toggle (&optional force)
7445 "Toggle the visibility of the current block.
7446 When optional argument FORCE is `off', make block visible. If it
7447 is non-nil, hide it unconditionally. Throw an error when not at
7448 a block. Return a non-nil value when toggling is successful."
7449 (interactive)
7450 (let ((element (org-element-at-point)))
7451 (unless (memq (org-element-type element)
7452 '(center-block comment-block dynamic-block example-block
7453 export-block quote-block special-block
7454 src-block verse-block))
7455 (user-error "Not at a block"))
7456 (let* ((start (save-excursion
7457 (goto-char (org-element-property :post-affiliated element))
7458 (line-end-position)))
7459 (end (save-excursion
7460 (goto-char (org-element-property :end element))
7461 (skip-chars-backward " \r\t\n")
7462 (line-end-position)))
7463 (overlays (overlays-at start)))
7464 (cond
7465 ;; Do nothing when not before or at the block opening line or
7466 ;; at the block closing line.
7467 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7468 ((and (not (eq force 'off))
7469 (not (memq t (mapcar
7470 (lambda (o)
7471 (eq (overlay-get o 'invisible) 'org-hide-block))
7472 overlays))))
7473 (let ((ov (make-overlay start end)))
7474 (overlay-put ov 'invisible 'org-hide-block)
7475 ;; Make the block accessible to `isearch'.
7476 (overlay-put
7477 ov 'isearch-open-invisible
7478 (lambda (ov)
7479 (when (memq ov org-hide-block-overlays)
7480 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7481 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7482 (delete-overlay ov))))
7483 (push ov org-hide-block-overlays)
7484 ;; When the block is hidden away, make sure point is left in
7485 ;; a visible part of the buffer.
7486 (when (> (line-beginning-position) start)
7487 (goto-char start)
7488 (beginning-of-line))
7489 ;; Signal successful toggling.
7491 ((or (not force) (eq force 'off))
7492 (dolist (ov overlays t)
7493 (when (memq ov org-hide-block-overlays)
7494 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7495 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7496 (delete-overlay ov))))))))
7498 ;; Remove overlays when changing major mode
7499 (add-hook 'org-mode-hook
7500 (lambda () (add-hook 'change-major-mode-hook
7501 'org-show-block-all 'append 'local)))
7503 ;;; Org-goto
7505 (defvar org-goto-window-configuration nil)
7506 (defvar org-goto-marker nil)
7507 (defvar org-goto-map)
7508 (defun org-goto-map ()
7509 "Set the keymap `org-goto'."
7510 (setq org-goto-map
7511 (let ((map (make-sparse-keymap)))
7512 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7513 mouse-drag-region universal-argument org-occur)))
7514 (dolist (cmd cmds)
7515 (substitute-key-definition cmd cmd map global-map)))
7516 (suppress-keymap map)
7517 (org-defkey map "\C-m" 'org-goto-ret)
7518 (org-defkey map [(return)] 'org-goto-ret)
7519 (org-defkey map [(left)] 'org-goto-left)
7520 (org-defkey map [(right)] 'org-goto-right)
7521 (org-defkey map [(control ?g)] 'org-goto-quit)
7522 (org-defkey map "\C-i" 'org-cycle)
7523 (org-defkey map [(tab)] 'org-cycle)
7524 (org-defkey map [(down)] 'outline-next-visible-heading)
7525 (org-defkey map [(up)] 'outline-previous-visible-heading)
7526 (if org-goto-auto-isearch
7527 (if (fboundp 'define-key-after)
7528 (define-key-after map [t] 'org-goto-local-auto-isearch)
7529 nil)
7530 (org-defkey map "q" 'org-goto-quit)
7531 (org-defkey map "n" 'outline-next-visible-heading)
7532 (org-defkey map "p" 'outline-previous-visible-heading)
7533 (org-defkey map "f" 'outline-forward-same-level)
7534 (org-defkey map "b" 'outline-backward-same-level)
7535 (org-defkey map "u" 'outline-up-heading))
7536 (org-defkey map "/" 'org-occur)
7537 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7538 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7539 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7540 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7541 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7542 map)))
7544 (defconst org-goto-help
7545 "Browse buffer copy, to find location or copy text.%s
7546 RET=jump to location C-g=quit and return to previous location
7547 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7549 (defvar org-goto-start-pos) ; dynamically scoped parameter
7551 (defun org-goto (&optional alternative-interface)
7552 "Look up a different location in the current file, keeping current visibility.
7554 When you want look-up or go to a different location in a
7555 document, the fastest way is often to fold the entire buffer and
7556 then dive into the tree. This method has the disadvantage, that
7557 the previous location will be folded, which may not be what you
7558 want.
7560 This command works around this by showing a copy of the current
7561 buffer in an indirect buffer, in overview mode. You can dive
7562 into the tree in that copy, use org-occur and incremental search
7563 to find a location. When pressing RET or `Q', the command
7564 returns to the original buffer in which the visibility is still
7565 unchanged. After RET it will also jump to the location selected
7566 in the indirect buffer and expose the headline hierarchy above.
7568 With a prefix argument, use the alternative interface: e.g., if
7569 `org-goto-interface' is `outline' use `outline-path-completion'."
7570 (interactive "P")
7571 (org-goto-map)
7572 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7573 (org-refile-use-outline-path t)
7574 (org-refile-target-verify-function nil)
7575 (interface
7576 (if (not alternative-interface)
7577 org-goto-interface
7578 (if (eq org-goto-interface 'outline)
7579 'outline-path-completion
7580 'outline)))
7581 (org-goto-start-pos (point))
7582 (selected-point
7583 (if (eq interface 'outline)
7584 (car (org-get-location (current-buffer) org-goto-help))
7585 (let ((pa (org-refile-get-location "Goto")))
7586 (org-refile-check-position pa)
7587 (nth 3 pa)))))
7588 (if selected-point
7589 (progn
7590 (org-mark-ring-push org-goto-start-pos)
7591 (goto-char selected-point)
7592 (when (or (outline-invisible-p) (org-invisible-p2))
7593 (org-show-context 'org-goto)))
7594 (message "Quit"))))
7596 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7597 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7598 (defvar org-goto-local-auto-isearch-map) ; defined below
7600 (defun org-get-location (_buf help)
7601 "Let the user select a location in current buffer.
7602 This function uses a recursive edit. It returns the selected position
7603 or nil."
7604 (org-no-popups
7605 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7606 (isearch-hide-immediately nil)
7607 (isearch-search-fun-function
7608 (lambda () 'org-goto-local-search-headings))
7609 (org-goto-selected-point org-goto-exit-command))
7610 (save-excursion
7611 (save-window-excursion
7612 (delete-other-windows)
7613 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7614 (pop-to-buffer-same-window
7615 (condition-case nil
7616 (make-indirect-buffer (current-buffer) "*org-goto*")
7617 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7618 (with-output-to-temp-buffer "*Org Help*"
7619 (princ (format help (if org-goto-auto-isearch
7620 " Just type for auto-isearch."
7621 " n/p/f/b/u to navigate, q to quit."))))
7622 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7623 (setq buffer-read-only nil)
7624 (let ((org-startup-truncated t)
7625 (org-startup-folded nil)
7626 (org-startup-align-all-tables nil))
7627 (org-mode)
7628 (org-overview))
7629 (setq buffer-read-only t)
7630 (if (and (boundp 'org-goto-start-pos)
7631 (integer-or-marker-p org-goto-start-pos))
7632 (progn (goto-char org-goto-start-pos)
7633 (when (outline-invisible-p)
7634 (org-show-set-visibility 'lineage)))
7635 (goto-char (point-min)))
7636 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7637 (message "Select location and press RET")
7638 (use-local-map org-goto-map)
7639 (recursive-edit)))
7640 (kill-buffer "*org-goto*")
7641 (cons org-goto-selected-point org-goto-exit-command))))
7643 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7644 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7645 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7646 (if (fboundp 'isearch-other-control-char)
7647 (progn
7648 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7649 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7650 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7651 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7652 (define-key org-goto-local-auto-isearch-map [return] nil))
7654 (defun org-goto-local-search-headings (string bound noerror)
7655 "Search and make sure that any matches are in headlines."
7656 (catch 'return
7657 (while (if isearch-forward
7658 (search-forward string bound noerror)
7659 (search-backward string bound noerror))
7660 (when (save-match-data
7661 (and (save-excursion
7662 (beginning-of-line)
7663 (looking-at org-complex-heading-regexp))
7664 (or (not (match-beginning 5))
7665 (< (point) (match-beginning 5)))))
7666 (throw 'return (point))))))
7668 (defun org-goto-local-auto-isearch ()
7669 "Start isearch."
7670 (interactive)
7671 (goto-char (point-min))
7672 (let ((keys (this-command-keys)))
7673 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7674 (isearch-mode t)
7675 (isearch-process-search-char (string-to-char keys)))))
7677 (defun org-goto-ret (&optional _arg)
7678 "Finish `org-goto' by going to the new location."
7679 (interactive "P")
7680 (setq org-goto-selected-point (point))
7681 (setq org-goto-exit-command 'return)
7682 (throw 'exit nil))
7684 (defun org-goto-left ()
7685 "Finish `org-goto' by going to the new location."
7686 (interactive)
7687 (if (org-at-heading-p)
7688 (progn
7689 (beginning-of-line 1)
7690 (setq org-goto-selected-point (point)
7691 org-goto-exit-command 'left)
7692 (throw 'exit nil))
7693 (user-error "Not on a heading")))
7695 (defun org-goto-right ()
7696 "Finish `org-goto' by going to the new location."
7697 (interactive)
7698 (if (org-at-heading-p)
7699 (progn
7700 (setq org-goto-selected-point (point)
7701 org-goto-exit-command 'right)
7702 (throw 'exit nil))
7703 (user-error "Not on a heading")))
7705 (defun org-goto-quit ()
7706 "Finish `org-goto' without cursor motion."
7707 (interactive)
7708 (setq org-goto-selected-point nil)
7709 (setq org-goto-exit-command 'quit)
7710 (throw 'exit nil))
7712 ;;; Indirect buffer display of subtrees
7714 (defvar org-indirect-dedicated-frame nil
7715 "This is the frame being used for indirect tree display.")
7716 (defvar org-last-indirect-buffer nil)
7718 (defun org-tree-to-indirect-buffer (&optional arg)
7719 "Create indirect buffer and narrow it to current subtree.
7721 With a numerical prefix ARG, go up to this level and then take that tree.
7722 If ARG is negative, go up that many levels.
7724 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7725 indirect buffer previously made with this command, to avoid proliferation of
7726 indirect buffers. However, when you call the command with a \
7727 `\\[universal-argument]' prefix, or
7728 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
7729 so that you can work with several indirect buffers at the same time. If
7730 `org-indirect-buffer-display' is `dedicated-frame', the \
7731 `\\[universal-argument]' prefix also
7732 requests that a new frame be made for the new buffer, so that the dedicated
7733 frame is not changed."
7734 (interactive "P")
7735 (let ((cbuf (current-buffer))
7736 (cwin (selected-window))
7737 (pos (point))
7738 beg end level heading ibuf)
7739 (save-excursion
7740 (org-back-to-heading t)
7741 (when (numberp arg)
7742 (setq level (org-outline-level))
7743 (when (< arg 0) (setq arg (+ level arg)))
7744 (while (> (setq level (org-outline-level)) arg)
7745 (org-up-heading-safe)))
7746 (setq beg (point)
7747 heading (org-get-heading 'no-tags))
7748 (org-end-of-subtree t t)
7749 (when (org-at-heading-p) (backward-char 1))
7750 (setq end (point)))
7751 (when (and (buffer-live-p org-last-indirect-buffer)
7752 (not (eq org-indirect-buffer-display 'new-frame))
7753 (not arg))
7754 (kill-buffer org-last-indirect-buffer))
7755 (setq ibuf (org-get-indirect-buffer cbuf heading)
7756 org-last-indirect-buffer ibuf)
7757 (cond
7758 ((or (eq org-indirect-buffer-display 'new-frame)
7759 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7760 (select-frame (make-frame))
7761 (delete-other-windows)
7762 (pop-to-buffer-same-window ibuf)
7763 (org-set-frame-title heading))
7764 ((eq org-indirect-buffer-display 'dedicated-frame)
7765 (raise-frame
7766 (select-frame (or (and org-indirect-dedicated-frame
7767 (frame-live-p org-indirect-dedicated-frame)
7768 org-indirect-dedicated-frame)
7769 (setq org-indirect-dedicated-frame (make-frame)))))
7770 (delete-other-windows)
7771 (pop-to-buffer-same-window ibuf)
7772 (org-set-frame-title (concat "Indirect: " heading)))
7773 ((eq org-indirect-buffer-display 'current-window)
7774 (pop-to-buffer-same-window ibuf))
7775 ((eq org-indirect-buffer-display 'other-window)
7776 (pop-to-buffer ibuf))
7777 (t (error "Invalid value")))
7778 (narrow-to-region beg end)
7779 (outline-show-all)
7780 (goto-char pos)
7781 (run-hook-with-args 'org-cycle-hook 'all)
7782 (and (window-live-p cwin) (select-window cwin))))
7784 (defun org-get-indirect-buffer (&optional buffer heading)
7785 (setq buffer (or buffer (current-buffer)))
7786 (let ((n 1) (base (buffer-name buffer)) bname)
7787 (while (buffer-live-p
7788 (get-buffer
7789 (setq bname
7790 (concat base "-"
7791 (if heading (concat heading "-" (number-to-string n))
7792 (number-to-string n))))))
7793 (setq n (1+ n)))
7794 (condition-case nil
7795 (make-indirect-buffer buffer bname 'clone)
7796 (error (make-indirect-buffer buffer bname)))))
7798 (defun org-set-frame-title (title)
7799 "Set the title of the current frame to the string TITLE."
7800 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7802 ;;;; Structure editing
7804 ;;; Inserting headlines
7806 (defun org--line-empty-p (n)
7807 "Is the Nth next line empty?
7809 Counts the current line as N = 1 and the previous line as N = 0;
7810 see `beginning-of-line'."
7811 (save-excursion
7812 (and (not (bobp))
7813 (or (beginning-of-line n) t)
7814 (save-match-data
7815 (looking-at "[ \t]*$")))))
7817 (defun org-previous-line-empty-p ()
7818 "Is the previous line a blank line?
7819 When NEXT is non-nil, check the next line instead."
7820 (org--line-empty-p 0))
7822 (defun org-next-line-empty-p ()
7823 "Is the previous line a blank line?
7824 When NEXT is non-nil, check the next line instead."
7825 (org--line-empty-p 2))
7827 (defun org-insert-heading (&optional arg invisible-ok top)
7828 "Insert a new heading or an item with the same depth at point.
7830 If point is at the beginning of a heading or a list item, insert
7831 a new heading or a new item above the current one. When at the
7832 beginning of a regular line of text, turn it into a heading.
7834 If point is in the middle of a line, split it and create a new
7835 headline/item with the text in the current line after point (see
7836 `org-M-RET-may-split-line' on how to modify this behavior). As
7837 a special case, on a headline, splitting can only happen on the
7838 title itself. E.g., this excludes breaking stars or tags.
7840 With a `\\[universal-argument]' prefix, set \
7841 `org-insert-heading-respect-content' to
7842 a non-nil value for the duration of the command. This forces the
7843 insertion of a heading after the current subtree, independently
7844 on the location of point.
7846 With a `\\[universal-argument] \\[universal-argument]' prefix, \
7847 insert the heading at the end of the tree
7848 above the current heading. For example, if point is within a
7849 2nd-level heading, then it will insert a 2nd-level heading at
7850 the end of the 1st-level parent subtree.
7852 When INVISIBLE-OK is set, stop at invisible headlines when going
7853 back. This is important for non-interactive uses of the
7854 command.
7856 When optional argument TOP is non-nil, insert a level 1 heading,
7857 unconditionally."
7858 (interactive "P")
7859 (let ((itemp (and (not top) (org-in-item-p)))
7860 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7861 (respect-content (or org-insert-heading-respect-content
7862 (equal arg '(4))))
7863 (initial-content ""))
7865 (cond
7867 ((or (= (buffer-size) 0)
7868 (and (not (save-excursion
7869 (and (ignore-errors (org-back-to-heading invisible-ok))
7870 (org-at-heading-p))))
7871 (or arg (not itemp))))
7872 ;; At beginning of buffer or so high up that only a heading
7873 ;; makes sense.
7874 (cond ((and (bolp) (not respect-content)) (insert "* "))
7875 ((not respect-content)
7876 (unless may-split (end-of-line))
7877 (insert "\n* "))
7878 ((re-search-forward org-outline-regexp-bol nil t)
7879 (beginning-of-line)
7880 (insert "* \n")
7881 (backward-char))
7882 (t (goto-char (point-max))
7883 (insert "\n* ")))
7884 (run-hooks 'org-insert-heading-hook))
7886 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7889 ;; Maybe move at the end of the subtree
7890 (when (equal arg '(16))
7891 (org-up-heading-safe)
7892 (org-end-of-subtree t))
7893 ;; Insert a heading
7894 (save-restriction
7895 (widen)
7896 (let* ((level nil)
7897 (on-heading (org-at-heading-p))
7898 (empty-line-p (if on-heading
7899 (org-previous-line-empty-p)
7900 ;; We will decide later
7901 nil))
7902 ;; Get a level string to fall back on.
7903 (fix-level
7904 (if (org-before-first-heading-p) "*"
7905 (save-excursion
7906 (org-back-to-heading t)
7907 (when (org-previous-line-empty-p) (setq empty-line-p t))
7908 (looking-at org-outline-regexp)
7909 (make-string (1- (length (match-string 0))) ?*))))
7910 (stars
7911 (save-excursion
7912 (condition-case nil
7913 (if top "* "
7914 (org-back-to-heading invisible-ok)
7915 (when (and (not on-heading)
7916 (featurep 'org-inlinetask)
7917 (integerp org-inlinetask-min-level)
7918 (>= (length (match-string 0))
7919 org-inlinetask-min-level))
7920 ;; Find a heading level before the inline
7921 ;; task.
7922 (while (and (setq level (org-up-heading-safe))
7923 (>= level org-inlinetask-min-level)))
7924 (if (org-at-heading-p)
7925 (org-back-to-heading invisible-ok)
7926 (error "This should not happen")))
7927 (unless (and (save-excursion
7928 (save-match-data
7929 (org-backward-heading-same-level
7930 1 invisible-ok))
7931 (= (point) (match-beginning 0)))
7932 (not (org-next-line-empty-p)))
7933 (setq empty-line-p (or empty-line-p
7934 (org-previous-line-empty-p))))
7935 (match-string 0))
7936 (error (or fix-level "* ")))))
7937 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7938 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7940 ;; If we insert after content, move there and clean up
7941 ;; whitespace.
7942 (when respect-content
7943 (if (not (org-before-first-heading-p))
7944 (org-end-of-subtree nil t)
7945 (re-search-forward org-outline-regexp-bol)
7946 (beginning-of-line 0))
7947 (skip-chars-backward " \r\t\n")
7948 (and (not (looking-back "^\\*+" (line-beginning-position)))
7949 (looking-at "[ \t]+") (replace-match ""))
7950 (unless (eobp) (forward-char 1))
7951 (when (looking-at "^\\*")
7952 (unless (bobp) (backward-char 1))
7953 (insert "\n")))
7955 ;; If we are splitting, grab the text that should be moved
7956 ;; to the new headline.
7957 (when may-split
7958 (if (org-at-heading-p)
7959 ;; This is a heading: split intelligently (keeping
7960 ;; tags).
7961 (let ((pos (point)))
7962 (beginning-of-line)
7963 (let ((case-fold-search nil))
7964 (unless (looking-at org-complex-heading-regexp)
7965 (error "This should not happen")))
7966 (when (and (match-beginning 4)
7967 (> pos (match-beginning 4))
7968 (< pos (match-end 4)))
7969 (setq initial-content (buffer-substring pos (match-end 4)))
7970 (goto-char pos)
7971 (delete-region (point) (match-end 4))
7972 (if (looking-at "[ \t]*$")
7973 (replace-match "")
7974 (insert (make-string (length initial-content) ?\s)))
7975 (setq initial-content (org-trim initial-content)))
7976 (goto-char pos))
7977 ;; A normal line.
7978 (setq initial-content
7979 (org-trim
7980 (delete-and-extract-region (point) (line-end-position))))))
7982 ;; If we are at the beginning of the line, insert before it.
7983 ;; Otherwise, after it.
7984 (cond
7985 ((and (bolp) (looking-at "[ \t]*$")))
7986 ((bolp) (save-excursion (insert "\n")))
7987 (t (end-of-line)
7988 (insert "\n")))
7990 ;; Insert the new heading
7991 (insert stars)
7992 (just-one-space)
7993 (insert initial-content)
7994 (unless (and blank (org-previous-line-empty-p))
7995 (org-N-empty-lines-before-current (if blank 1 0)))
7996 ;; Adjust visibility, which may be messed up if we removed
7997 ;; blank lines while previous entry was hidden.
7998 (let ((bol (line-beginning-position)))
7999 (dolist (o (overlays-at (1- bol)))
8000 (when (and (eq (overlay-get o 'invisible) 'outline)
8001 (eq (overlay-end o) bol))
8002 (move-overlay o (overlay-start o) (1- bol)))))
8003 (run-hooks 'org-insert-heading-hook)))))))
8005 (defun org-N-empty-lines-before-current (N)
8006 "Make the number of empty lines before current exactly N.
8007 So this will delete or add empty lines."
8008 (save-excursion
8009 (beginning-of-line)
8010 (let ((p (point)))
8011 (skip-chars-backward " \r\t\n")
8012 (unless (bolp) (forward-line))
8013 (delete-region (point) p))
8014 (when (> N 0) (insert (make-string N ?\n)))))
8016 (defun org-get-heading (&optional no-tags no-todo)
8017 "Return the heading of the current entry, without the stars.
8018 When NO-TAGS is non-nil, don't include tags.
8019 When NO-TODO is non-nil, don't include TODO keywords."
8020 (save-excursion
8021 (org-back-to-heading t)
8022 (let ((case-fold-search nil))
8023 (cond
8024 ((and no-tags no-todo)
8025 (looking-at org-complex-heading-regexp)
8026 ;; Return value has to be a string, but match group 4 is
8027 ;; optional.
8028 (or (match-string 4) ""))
8029 (no-tags
8030 (looking-at (concat org-outline-regexp
8031 "\\(.*?\\)"
8032 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8033 (match-string 1))
8034 (no-todo
8035 (looking-at org-todo-line-regexp)
8036 (match-string 3))
8037 (t (looking-at org-heading-regexp)
8038 (match-string 2))))))
8040 (defvar orgstruct-mode) ; defined below
8042 (defun org-heading-components ()
8043 "Return the components of the current heading.
8044 This is a list with the following elements:
8045 - the level as an integer
8046 - the reduced level, different if `org-odd-levels-only' is set.
8047 - the TODO keyword, or nil
8048 - the priority character, like ?A, or nil if no priority is given
8049 - the headline text itself, or the tags string if no headline text
8050 - the tags string, or nil."
8051 (save-excursion
8052 (org-back-to-heading t)
8053 (when (let (case-fold-search)
8054 (looking-at
8055 (if orgstruct-mode
8056 org-heading-regexp
8057 org-complex-heading-regexp)))
8058 (if orgstruct-mode
8059 (list (length (match-string 1))
8060 (org-reduced-level (length (match-string 1)))
8063 (match-string 2)
8064 nil)
8065 (list (length (match-string 1))
8066 (org-reduced-level (length (match-string 1)))
8067 (match-string-no-properties 2)
8068 (and (match-end 3) (aref (match-string 3) 2))
8069 (match-string-no-properties 4)
8070 (match-string-no-properties 5))))))
8072 (defun org-get-entry ()
8073 "Get the entry text, after heading, entire subtree."
8074 (save-excursion
8075 (org-back-to-heading t)
8076 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8078 (defun org-edit-headline (&optional heading)
8079 "Edit the current headline.
8080 Set it to HEADING when provided."
8081 (interactive)
8082 (org-with-wide-buffer
8083 (org-back-to-heading t)
8084 (let ((case-fold-search nil))
8085 (when (looking-at org-complex-heading-regexp)
8086 (let* ((old (match-string-no-properties 4))
8087 (new (save-match-data
8088 (org-trim (or heading (read-string "Edit: " old))))))
8089 (unless (equal old new)
8090 (if old (replace-match new t t nil 4)
8091 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8092 (insert " " new))
8093 (org-set-tags nil t)
8094 (when (looking-at "[ \t]*$") (replace-match ""))))))))
8096 (defun org-insert-heading-after-current ()
8097 "Insert a new heading with same level as current, after current subtree."
8098 (interactive)
8099 (org-back-to-heading)
8100 (org-insert-heading)
8101 (org-move-subtree-down)
8102 (end-of-line 1))
8104 (defun org-insert-heading-respect-content (&optional invisible-ok)
8105 "Insert heading with `org-insert-heading-respect-content' set to t."
8106 (interactive)
8107 (org-insert-heading '(4) invisible-ok))
8109 (defun org-insert-todo-heading-respect-content (&optional force-state)
8110 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8111 (interactive)
8112 (org-insert-todo-heading force-state '(4)))
8114 (defun org-insert-todo-heading (arg &optional force-heading)
8115 "Insert a new heading with the same level and TODO state as current heading.
8117 If the heading has no TODO state, or if the state is DONE, use
8118 the first state (TODO by default). Also with one prefix arg,
8119 force first state. With two prefix args, force inserting at the
8120 end of the parent subtree.
8122 When called at a plain list item, insert a new item with an
8123 unchecked check box."
8124 (interactive "P")
8125 (when (or force-heading (not (org-insert-item 'checkbox)))
8126 (org-insert-heading (or (and (equal arg '(16)) '(16))
8127 force-heading))
8128 (save-excursion
8129 (org-back-to-heading)
8130 (outline-previous-heading)
8131 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
8132 (let* ((new-mark-x
8133 (if (or (equal arg '(4))
8134 (not (match-beginning 2))
8135 (member (match-string 2) org-done-keywords))
8136 (car org-todo-keywords-1)
8137 (match-string 2)))
8138 (new-mark
8140 (run-hook-with-args-until-success
8141 'org-todo-get-default-hook new-mark-x nil)
8142 new-mark-x)))
8143 (beginning-of-line 1)
8144 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8145 (if org-treat-insert-todo-heading-as-state-change
8146 (org-todo new-mark)
8147 (insert new-mark " "))))
8148 (when org-provide-todo-statistics
8149 (org-update-parent-todo-statistics))))
8151 (defun org-insert-subheading (arg)
8152 "Insert a new subheading and demote it.
8153 Works for outline headings and for plain lists alike."
8154 (interactive "P")
8155 (org-insert-heading arg)
8156 (cond
8157 ((org-at-heading-p) (org-do-demote))
8158 ((org-at-item-p) (org-indent-item))))
8160 (defun org-insert-todo-subheading (arg)
8161 "Insert a new subheading with TODO keyword or checkbox and demote it.
8162 Works for outline headings and for plain lists alike."
8163 (interactive "P")
8164 (org-insert-todo-heading arg)
8165 (cond
8166 ((org-at-heading-p) (org-do-demote))
8167 ((org-at-item-p) (org-indent-item))))
8169 ;;; Promotion and Demotion
8171 (defvar org-after-demote-entry-hook nil
8172 "Hook run after an entry has been demoted.
8173 The cursor will be at the beginning of the entry.
8174 When a subtree is being demoted, the hook will be called for each node.")
8176 (defvar org-after-promote-entry-hook nil
8177 "Hook run after an entry has been promoted.
8178 The cursor will be at the beginning of the entry.
8179 When a subtree is being promoted, the hook will be called for each node.")
8181 (defun org-promote-subtree ()
8182 "Promote the entire subtree.
8183 See also `org-promote'."
8184 (interactive)
8185 (save-excursion
8186 (org-with-limited-levels (org-map-tree 'org-promote)))
8187 (org-fix-position-after-promote))
8189 (defun org-demote-subtree ()
8190 "Demote the entire subtree.
8191 See `org-demote' and `org-promote'."
8192 (interactive)
8193 (save-excursion
8194 (org-with-limited-levels (org-map-tree 'org-demote)))
8195 (org-fix-position-after-promote))
8197 (defun org-do-promote ()
8198 "Promote the current heading higher up the tree.
8199 If the region is active in `transient-mark-mode', promote all
8200 headings in the region."
8201 (interactive)
8202 (save-excursion
8203 (if (org-region-active-p)
8204 (org-map-region 'org-promote (region-beginning) (region-end))
8205 (org-promote)))
8206 (org-fix-position-after-promote))
8208 (defun org-do-demote ()
8209 "Demote the current heading lower down the tree.
8210 If the region is active in `transient-mark-mode', demote all
8211 headings in the region."
8212 (interactive)
8213 (save-excursion
8214 (if (org-region-active-p)
8215 (org-map-region 'org-demote (region-beginning) (region-end))
8216 (org-demote)))
8217 (org-fix-position-after-promote))
8219 (defun org-fix-position-after-promote ()
8220 "Fix cursor position and indentation after demoting/promoting."
8221 (let ((pos (point)))
8222 (when (save-excursion
8223 (beginning-of-line)
8224 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
8225 (or (eq pos (match-end 1)) (eq pos (match-end 2))))
8226 (cond ((eobp) (insert " "))
8227 ((eolp) (insert " "))
8228 ((equal (char-after) ?\s) (forward-char 1))))))
8230 (defun org-current-level ()
8231 "Return the level of the current entry, or nil if before the first headline.
8232 The level is the number of stars at the beginning of the
8233 headline. Use `org-reduced-level' to remove the effect of
8234 `org-odd-levels'. Unlike to `org-outline-level', this function
8235 ignores inlinetasks."
8236 (let ((level (org-with-limited-levels (org-outline-level))))
8237 (and (> level 0) level)))
8239 (defun org-get-previous-line-level ()
8240 "Return the outline depth of the last headline before the current line.
8241 Returns 0 for the first headline in the buffer, and nil if before the
8242 first headline."
8243 (and (org-current-level)
8244 (or (and (/= (line-beginning-position) (point-min))
8245 (save-excursion (beginning-of-line 0) (org-current-level)))
8246 0)))
8248 (defun org-reduced-level (l)
8249 "Compute the effective level of a heading.
8250 This takes into account the setting of `org-odd-levels-only'."
8251 (cond
8252 ((zerop l) 0)
8253 (org-odd-levels-only (1+ (floor (/ l 2))))
8254 (t l)))
8256 (defun org-level-increment ()
8257 "Return the number of stars that will be added or removed at a
8258 time to headlines when structure editing, based on the value of
8259 `org-odd-levels-only'."
8260 (if org-odd-levels-only 2 1))
8262 (defun org-get-valid-level (level &optional change)
8263 "Rectify a level change under the influence of `org-odd-levels-only'
8264 LEVEL is a current level, CHANGE is by how much the level should be
8265 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8266 even level numbers will become the next higher odd number."
8267 (if org-odd-levels-only
8268 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8269 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8270 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8271 (max 1 (+ level (or change 0)))))
8273 (defun org-promote ()
8274 "Promote the current heading higher up the tree."
8275 (org-with-wide-buffer
8276 (org-back-to-heading t)
8277 (let* ((after-change-functions (remq 'flyspell-after-change-function
8278 after-change-functions))
8279 (level (save-match-data (funcall outline-level)))
8280 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8281 (diff (abs (- level (length up-head) -1))))
8282 (cond
8283 ((and (= level 1) org-allow-promoting-top-level-subtree)
8284 (replace-match "# " nil t))
8285 ((= level 1)
8286 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8287 (t (replace-match up-head nil t)))
8288 (unless (= level 1)
8289 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8290 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8291 (run-hooks 'org-after-promote-entry-hook))))
8293 (defun org-demote ()
8294 "Demote the current heading lower down the tree."
8295 (org-with-wide-buffer
8296 (org-back-to-heading t)
8297 (let* ((after-change-functions (remq 'flyspell-after-change-function
8298 after-change-functions))
8299 (level (save-match-data (funcall outline-level)))
8300 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8301 (diff (abs (- level (length down-head) -1))))
8302 (replace-match down-head nil t)
8303 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8304 (when org-adapt-indentation (org-fixup-indentation diff))
8305 (run-hooks 'org-after-demote-entry-hook))))
8307 (defun org-cycle-level ()
8308 "Cycle the level of an empty headline through possible states.
8309 This goes first to child, then to parent, level, then up the hierarchy.
8310 After top level, it switches back to sibling level."
8311 (interactive)
8312 (let ((org-adapt-indentation nil))
8313 (when (org-point-at-end-of-empty-headline)
8314 (setq this-command 'org-cycle-level) ; Only needed for caching
8315 (let ((cur-level (org-current-level))
8316 (prev-level (org-get-previous-line-level)))
8317 (cond
8318 ;; If first headline in file, promote to top-level.
8319 ((= prev-level 0)
8320 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8321 do (org-do-promote)))
8322 ;; If same level as prev, demote one.
8323 ((= prev-level cur-level)
8324 (org-do-demote))
8325 ;; If parent is top-level, promote to top level if not already.
8326 ((= prev-level 1)
8327 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8328 do (org-do-promote)))
8329 ;; If top-level, return to prev-level.
8330 ((= cur-level 1)
8331 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8332 do (org-do-demote)))
8333 ;; If less than prev-level, promote one.
8334 ((< cur-level prev-level)
8335 (org-do-promote))
8336 ;; If deeper than prev-level, promote until higher than
8337 ;; prev-level.
8338 ((> cur-level prev-level)
8339 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8340 do (org-do-promote))))
8341 t))))
8343 (defun org-map-tree (fun)
8344 "Call FUN for every heading underneath the current one."
8345 (org-back-to-heading t)
8346 (let ((level (funcall outline-level)))
8347 (save-excursion
8348 (funcall fun)
8349 (while (and (progn
8350 (outline-next-heading)
8351 (> (funcall outline-level) level))
8352 (not (eobp)))
8353 (funcall fun)))))
8355 (defun org-map-region (fun beg end)
8356 "Call FUN for every heading between BEG and END."
8357 (let ((org-ignore-region t))
8358 (save-excursion
8359 (setq end (copy-marker end))
8360 (goto-char beg)
8361 (when (and (re-search-forward org-outline-regexp-bol nil t)
8362 (< (point) end))
8363 (funcall fun))
8364 (while (and (progn
8365 (outline-next-heading)
8366 (< (point) end))
8367 (not (eobp)))
8368 (funcall fun)))))
8370 (defun org-fixup-indentation (diff)
8371 "Change the indentation in the current entry by DIFF.
8373 DIFF is an integer. Indentation is done according to the
8374 following rules:
8376 - Planning information and property drawers are always indented
8377 according to the new level of the headline;
8379 - Footnote definitions and their contents are ignored;
8381 - Inlinetasks' boundaries are not shifted;
8383 - Empty lines are ignored;
8385 - Other lines' indentation are shifted by DIFF columns, unless
8386 it would introduce a structural change in the document, in
8387 which case no shifting is done at all.
8389 Assume point is at a heading or an inlinetask beginning."
8390 (org-with-wide-buffer
8391 (narrow-to-region (line-beginning-position)
8392 (save-excursion
8393 (if (org-with-limited-levels (org-at-heading-p))
8394 (org-with-limited-levels (outline-next-heading))
8395 (org-inlinetask-goto-end))
8396 (point)))
8397 (forward-line)
8398 ;; Indent properly planning info and property drawer.
8399 (when (looking-at-p org-planning-line-re)
8400 (org-indent-line)
8401 (forward-line))
8402 (when (looking-at org-property-drawer-re)
8403 (goto-char (match-end 0))
8404 (forward-line)
8405 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8406 (catch 'no-shift
8407 (when (zerop diff) (throw 'no-shift nil))
8408 ;; If DIFF is negative, first check if a shift is possible at all
8409 ;; (e.g., it doesn't break structure). This can only happen if
8410 ;; some contents are not properly indented.
8411 (let ((case-fold-search t))
8412 (when (< diff 0)
8413 (let ((diff (- diff))
8414 (forbidden-re (concat org-outline-regexp
8415 "\\|"
8416 (substring org-footnote-definition-re 1))))
8417 (save-excursion
8418 (while (not (eobp))
8419 (cond
8420 ((looking-at-p "[ \t]*$") (forward-line))
8421 ((and (looking-at-p org-footnote-definition-re)
8422 (let ((e (org-element-at-point)))
8423 (and (eq (org-element-type e) 'footnote-definition)
8424 (goto-char (org-element-property :end e))))))
8425 ((looking-at-p org-outline-regexp) (forward-line))
8426 ;; Give up if shifting would move before column 0 or
8427 ;; if it would introduce a headline or a footnote
8428 ;; definition.
8430 (skip-chars-forward " \t")
8431 (let ((ind (current-column)))
8432 (when (or (< ind diff)
8433 (and (= ind diff) (looking-at-p forbidden-re)))
8434 (throw 'no-shift nil)))
8435 ;; Ignore contents of example blocks and source
8436 ;; blocks if their indentation is meant to be
8437 ;; preserved. Jump to block's closing line.
8438 (beginning-of-line)
8439 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8440 (let ((e (org-element-at-point)))
8441 (and (memq (org-element-type e)
8442 '(example-block src-block))
8443 (or org-src-preserve-indentation
8444 (org-element-property :preserve-indent e))
8445 (goto-char (org-element-property :end e))
8446 (progn (skip-chars-backward " \r\t\n")
8447 (beginning-of-line)
8448 t))))
8449 (forward-line))))))))
8450 ;; Shift lines but footnote definitions, inlinetasks boundaries
8451 ;; by DIFF. Also skip contents of source or example blocks
8452 ;; when indentation is meant to be preserved.
8453 (while (not (eobp))
8454 (cond
8455 ((and (looking-at-p org-footnote-definition-re)
8456 (let ((e (org-element-at-point)))
8457 (and (eq (org-element-type e) 'footnote-definition)
8458 (goto-char (org-element-property :end e))))))
8459 ((looking-at-p org-outline-regexp) (forward-line))
8460 ((looking-at-p "[ \t]*$") (forward-line))
8462 (indent-line-to (+ (org-get-indentation) diff))
8463 (beginning-of-line)
8464 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8465 (let ((e (org-element-at-point)))
8466 (and (memq (org-element-type e)
8467 '(example-block src-block))
8468 (or org-src-preserve-indentation
8469 (org-element-property :preserve-indent e))
8470 (goto-char (org-element-property :end e))
8471 (progn (skip-chars-backward " \r\t\n")
8472 (beginning-of-line)
8473 t))))
8474 (forward-line)))))))))
8476 (defun org-convert-to-odd-levels ()
8477 "Convert an Org file with all levels allowed to one with odd levels.
8478 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8479 level 5 etc."
8480 (interactive)
8481 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8482 (let ((outline-level 'org-outline-level)
8483 (org-odd-levels-only nil) n)
8484 (save-excursion
8485 (goto-char (point-min))
8486 (while (re-search-forward "^\\*\\*+ " nil t)
8487 (setq n (- (length (match-string 0)) 2))
8488 (while (>= (setq n (1- n)) 0)
8489 (org-demote))
8490 (end-of-line 1))))))
8492 (defun org-convert-to-oddeven-levels ()
8493 "Convert an Org file with only odd levels to one with odd/even levels.
8494 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8495 file contains a section with an even level, conversion would
8496 destroy the structure of the file. An error is signaled in this
8497 case."
8498 (interactive)
8499 (goto-char (point-min))
8500 ;; First check if there are no even levels
8501 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8502 (org-show-set-visibility 'canonical)
8503 (error "Not all levels are odd in this file. Conversion not possible"))
8504 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8505 (let ((outline-regexp org-outline-regexp)
8506 (outline-level 'org-outline-level)
8507 (org-odd-levels-only nil) n)
8508 (save-excursion
8509 (goto-char (point-min))
8510 (while (re-search-forward "^\\*\\*+ " nil t)
8511 (setq n (/ (1- (length (match-string 0))) 2))
8512 (while (>= (setq n (1- n)) 0)
8513 (org-promote))
8514 (end-of-line 1))))))
8516 (defun org-tr-level (n)
8517 "Make N odd if required."
8518 (if org-odd-levels-only (1+ (/ n 2)) n))
8520 ;;; Vertical tree motion, cutting and pasting of subtrees
8522 (defun org-move-subtree-up (&optional arg)
8523 "Move the current subtree up past ARG headlines of the same level."
8524 (interactive "p")
8525 (org-move-subtree-down (- (prefix-numeric-value arg))))
8527 (defun org-move-subtree-down (&optional arg)
8528 "Move the current subtree down past ARG headlines of the same level."
8529 (interactive "p")
8530 (setq arg (prefix-numeric-value arg))
8531 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8532 'org-get-last-sibling))
8533 (ins-point (make-marker))
8534 (cnt (abs arg))
8535 (col (current-column))
8536 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8537 ;; Select the tree
8538 (org-back-to-heading)
8539 (setq beg0 (point))
8540 (save-excursion
8541 (setq ne-beg (org-back-over-empty-lines))
8542 (setq beg (point)))
8543 (save-match-data
8544 (save-excursion (outline-end-of-heading)
8545 (setq folded (outline-invisible-p)))
8546 (progn (org-end-of-subtree nil t)
8547 (unless (eobp) (backward-char))))
8548 (outline-next-heading)
8549 (setq ne-end (org-back-over-empty-lines))
8550 (setq end (point))
8551 (goto-char beg0)
8552 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8553 ;; include less whitespace
8554 (save-excursion
8555 (goto-char beg)
8556 (forward-line (- ne-beg ne-end))
8557 (setq beg (point))))
8558 ;; Find insertion point, with error handling
8559 (while (> cnt 0)
8560 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8561 (progn (goto-char beg0)
8562 (user-error "Cannot move past superior level or buffer limit")))
8563 (setq cnt (1- cnt)))
8564 (when (> arg 0)
8565 ;; Moving forward - still need to move over subtree
8566 (org-end-of-subtree t t)
8567 (save-excursion
8568 (org-back-over-empty-lines)
8569 (or (bolp) (newline))))
8570 (setq ne-ins (org-back-over-empty-lines))
8571 (move-marker ins-point (point))
8572 (setq txt (buffer-substring beg end))
8573 (org-save-markers-in-region beg end)
8574 (delete-region beg end)
8575 (org-remove-empty-overlays-at beg)
8576 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8577 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8578 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8579 (let ((bbb (point)))
8580 (insert-before-markers txt)
8581 (org-reinstall-markers-in-region bbb)
8582 (move-marker ins-point bbb))
8583 (or (bolp) (insert "\n"))
8584 (setq ins-end (point))
8585 (goto-char ins-point)
8586 (org-skip-whitespace)
8587 (when (and (< arg 0)
8588 (org-first-sibling-p)
8589 (> ne-ins ne-beg))
8590 ;; Move whitespace back to beginning
8591 (save-excursion
8592 (goto-char ins-end)
8593 (let ((kill-whole-line t))
8594 (kill-line (- ne-ins ne-beg)) (point)))
8595 (insert (make-string (- ne-ins ne-beg) ?\n)))
8596 (move-marker ins-point nil)
8597 (if folded
8598 (outline-hide-subtree)
8599 (org-show-entry)
8600 (org-show-children)
8601 (org-cycle-hide-drawers 'children))
8602 (org-clean-visibility-after-subtree-move)
8603 ;; move back to the initial column we were at
8604 (move-to-column col)))
8606 (defvar org-subtree-clip ""
8607 "Clipboard for cut and paste of subtrees.
8608 This is actually only a copy of the kill, because we use the normal kill
8609 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8611 (defvar org-subtree-clip-folded nil
8612 "Was the last copied subtree folded?
8613 This is used to fold the tree back after pasting.")
8615 (defun org-cut-subtree (&optional n)
8616 "Cut the current subtree into the clipboard.
8617 With prefix arg N, cut this many sequential subtrees.
8618 This is a short-hand for marking the subtree and then cutting it."
8619 (interactive "p")
8620 (org-copy-subtree n 'cut))
8622 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8623 "Copy the current subtree it in the clipboard.
8624 With prefix arg N, copy this many sequential subtrees.
8625 This is a short-hand for marking the subtree and then copying it.
8626 If CUT is non-nil, actually cut the subtree.
8627 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8628 of some markers in the region, even if CUT is non-nil. This is
8629 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8630 (interactive "p")
8631 (let (beg end folded (beg0 (point)))
8632 (if (called-interactively-p 'any)
8633 (org-back-to-heading nil) ; take what looks like a subtree
8634 (org-back-to-heading t)) ; take what is really there
8635 (setq beg (point))
8636 (skip-chars-forward " \t\r\n")
8637 (save-match-data
8638 (if nosubtrees
8639 (outline-next-heading)
8640 (save-excursion (outline-end-of-heading)
8641 (setq folded (outline-invisible-p)))
8642 (ignore-errors (org-forward-heading-same-level (1- n) t))
8643 (org-end-of-subtree t t)))
8644 ;; Include the end of an inlinetask
8645 (when (and (featurep 'org-inlinetask)
8646 (looking-at-p (concat (org-inlinetask-outline-regexp)
8647 "END[ \t]*$")))
8648 (end-of-line))
8649 (setq end (point))
8650 (goto-char beg0)
8651 (when (> end beg)
8652 (setq org-subtree-clip-folded folded)
8653 (when (or cut force-store-markers)
8654 (org-save-markers-in-region beg end))
8655 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8656 (setq org-subtree-clip (current-kill 0))
8657 (message "%s: Subtree(s) with %d characters"
8658 (if cut "Cut" "Copied")
8659 (length org-subtree-clip)))))
8661 (defun org-paste-subtree (&optional level tree for-yank remove)
8662 "Paste the clipboard as a subtree, with modification of headline level.
8663 The entire subtree is promoted or demoted in order to match a new headline
8664 level.
8666 If the cursor is at the beginning of a headline, the same level as
8667 that headline is used to paste the tree.
8669 If not, the new level is derived from the *visible* headings
8670 before and after the insertion point, and taken to be the inferior headline
8671 level of the two. So if the previous visible heading is level 3 and the
8672 next is level 4 (or vice versa), level 4 will be used for insertion.
8673 This makes sure that the subtree remains an independent subtree and does
8674 not swallow low level entries.
8676 You can also force a different level, either by using a numeric prefix
8677 argument, or by inserting the heading marker by hand. For example, if the
8678 cursor is after \"*****\", then the tree will be shifted to level 5.
8680 If optional TREE is given, use this text instead of the kill ring.
8682 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8683 move back over whitespace before inserting, and move point to the end of
8684 the inserted text when done.
8686 When REMOVE is non-nil, remove the subtree from the clipboard."
8687 (interactive "P")
8688 (setq tree (or tree (and kill-ring (current-kill 0))))
8689 (unless (org-kill-is-subtree-p tree)
8690 (user-error "%s"
8691 (substitute-command-keys
8692 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8693 (org-with-limited-levels
8694 (let* ((visp (not (outline-invisible-p)))
8695 (txt tree)
8696 (^re_ "\\(\\*+\\)[ \t]*")
8697 (old-level (if (string-match org-outline-regexp-bol txt)
8698 (- (match-end 0) (match-beginning 0) 1)
8699 -1))
8700 (force-level (cond (level (prefix-numeric-value level))
8701 ((and (looking-at "[ \t]*$")
8702 (string-match
8703 "^\\*+$" (buffer-substring
8704 (point-at-bol) (point))))
8705 (- (match-end 0) (match-beginning 0)))
8706 ((and (bolp)
8707 (looking-at org-outline-regexp))
8708 (- (match-end 0) (point) 1))))
8709 (previous-level (save-excursion
8710 (condition-case nil
8711 (progn
8712 (outline-previous-visible-heading 1)
8713 (if (looking-at ^re_)
8714 (- (match-end 0) (match-beginning 0) 1)
8716 (error 1))))
8717 (next-level (save-excursion
8718 (condition-case nil
8719 (progn
8720 (or (looking-at org-outline-regexp)
8721 (outline-next-visible-heading 1))
8722 (if (looking-at ^re_)
8723 (- (match-end 0) (match-beginning 0) 1)
8725 (error 1))))
8726 (new-level (or force-level (max previous-level next-level)))
8727 (shift (if (or (= old-level -1)
8728 (= new-level -1)
8729 (= old-level new-level))
8731 (- new-level old-level)))
8732 (delta (if (> shift 0) -1 1))
8733 (func (if (> shift 0) 'org-demote 'org-promote))
8734 (org-odd-levels-only nil)
8735 beg end newend)
8736 ;; Remove the forced level indicator
8737 (when force-level
8738 (delete-region (point-at-bol) (point)))
8739 ;; Paste
8740 (beginning-of-line (if (bolp) 1 2))
8741 (setq beg (point))
8742 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8743 (insert-before-markers txt)
8744 (unless (string-suffix-p "\n" txt) (insert "\n"))
8745 (setq newend (point))
8746 (org-reinstall-markers-in-region beg)
8747 (setq end (point))
8748 (goto-char beg)
8749 (skip-chars-forward " \t\n\r")
8750 (setq beg (point))
8751 (when (and (outline-invisible-p) visp)
8752 (save-excursion (outline-show-heading)))
8753 ;; Shift if necessary
8754 (unless (= shift 0)
8755 (save-restriction
8756 (narrow-to-region beg end)
8757 (while (not (= shift 0))
8758 (org-map-region func (point-min) (point-max))
8759 (setq shift (+ delta shift)))
8760 (goto-char (point-min))
8761 (setq newend (point-max))))
8762 (when (or (called-interactively-p 'interactive) for-yank)
8763 (message "Clipboard pasted as level %d subtree" new-level))
8764 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8765 kill-ring
8766 (eq org-subtree-clip (current-kill 0))
8767 org-subtree-clip-folded)
8768 ;; The tree was folded before it was killed/copied
8769 (outline-hide-subtree))
8770 (and for-yank (goto-char newend))
8771 (and remove (setq kill-ring (cdr kill-ring))))))
8773 (defun org-kill-is-subtree-p (&optional txt)
8774 "Check if the current kill is an outline subtree, or a set of trees.
8775 Returns nil if kill does not start with a headline, or if the first
8776 headline level is not the largest headline level in the tree.
8777 So this will actually accept several entries of equal levels as well,
8778 which is OK for `org-paste-subtree'.
8779 If optional TXT is given, check this string instead of the current kill."
8780 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8781 (re (org-get-limited-outline-regexp))
8782 (^re (concat "^" re))
8783 (start-level (and kill
8784 (string-match
8785 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8786 kill)
8787 (- (match-end 2) (match-beginning 2) 1)))
8788 (start (1+ (or (match-beginning 2) -1))))
8789 (if (not start-level)
8790 (progn
8791 nil) ;; does not even start with a heading
8792 (catch 'exit
8793 (while (setq start (string-match ^re kill (1+ start)))
8794 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8795 (throw 'exit nil)))
8796 t))))
8798 (defvar org-markers-to-move nil
8799 "Markers that should be moved with a cut-and-paste operation.
8800 Those markers are stored together with their positions relative to
8801 the start of the region.")
8803 (defun org-save-markers-in-region (beg end)
8804 "Check markers in region.
8805 If these markers are between BEG and END, record their position relative
8806 to BEG, so that after moving the block of text, we can put the markers back
8807 into place.
8808 This function gets called just before an entry or tree gets cut from the
8809 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8810 called immediately, to move the markers with the entries."
8811 (setq org-markers-to-move nil)
8812 (when (featurep 'org-clock)
8813 (org-clock-save-markers-for-cut-and-paste beg end))
8814 (when (featurep 'org-agenda)
8815 (org-agenda-save-markers-for-cut-and-paste beg end)))
8817 (defun org-check-and-save-marker (marker beg end)
8818 "Check if MARKER is between BEG and END.
8819 If yes, remember the marker and the distance to BEG."
8820 (when (and (marker-buffer marker)
8821 (equal (marker-buffer marker) (current-buffer))
8822 (>= marker beg) (< marker end))
8823 (push (cons marker (- marker beg)) org-markers-to-move)))
8825 (defun org-reinstall-markers-in-region (beg)
8826 "Move all remembered markers to their position relative to BEG."
8827 (dolist (x org-markers-to-move)
8828 (move-marker (car x) (+ beg (cdr x))))
8829 (setq org-markers-to-move nil))
8831 (defun org-narrow-to-subtree ()
8832 "Narrow buffer to the current subtree."
8833 (interactive)
8834 (save-excursion
8835 (save-match-data
8836 (org-with-limited-levels
8837 (narrow-to-region
8838 (progn (org-back-to-heading t) (point))
8839 (progn (org-end-of-subtree t t)
8840 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8841 (point)))))))
8843 (defun org-narrow-to-block ()
8844 "Narrow buffer to the current block."
8845 (interactive)
8846 (let* ((case-fold-search t)
8847 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8848 "^[ \t]*#\\+end_.*")))
8849 (if blockp
8850 (narrow-to-region (car blockp) (cdr blockp))
8851 (user-error "Not in a block"))))
8853 (defun org-clone-subtree-with-time-shift (n &optional shift)
8854 "Clone the task (subtree) at point N times.
8855 The clones will be inserted as siblings.
8857 In interactive use, the user will be prompted for the number of
8858 clones to be produced. If the entry has a timestamp, the user
8859 will also be prompted for a time shift, which may be a repeater
8860 as used in time stamps, for example `+3d'. To disable this,
8861 you can call the function with a universal prefix argument.
8863 When a valid repeater is given and the entry contains any time
8864 stamps, the clones will become a sequence in time, with time
8865 stamps in the subtree shifted for each clone produced. If SHIFT
8866 is nil or the empty string, time stamps will be left alone. The
8867 ID property of the original subtree is removed.
8869 In each clone, all the CLOCK entries will be removed. This
8870 prevents Org from considering that the clocked times overlap.
8872 If the original subtree did contain time stamps with a repeater,
8873 the following will happen:
8874 - the repeater will be removed in each clone
8875 - an additional clone will be produced, with the current, unshifted
8876 date(s) in the entry.
8877 - the original entry will be placed *after* all the clones, with
8878 repeater intact.
8879 - the start days in the repeater in the original entry will be shifted
8880 to past the last clone.
8881 In this way you can spell out a number of instances of a repeating task,
8882 and still retain the repeater to cover future instances of the task.
8884 As described above, N+1 clones are produced when the original
8885 subtree has a repeater. Setting N to 0, then, can be used to
8886 remove the repeater from a subtree and create a shifted clone
8887 with the original repeater."
8888 (interactive "nNumber of clones to produce: ")
8889 (unless (wholenump n) (user-error "Invalid number of replications %s" n))
8890 (when (org-before-first-heading-p) (user-error "No subtree to clone"))
8891 (let* ((beg (save-excursion (org-back-to-heading t) (point)))
8892 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
8893 (shift
8894 (or shift
8895 (if (and (not (equal current-prefix-arg '(4)))
8896 (save-excursion
8897 (goto-char beg)
8898 (re-search-forward org-ts-regexp-both end-of-tree t)))
8899 (read-from-minibuffer
8900 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8901 ""))) ;No time shift
8902 (doshift
8903 (and (org-string-nw-p shift)
8904 (or (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
8905 shift)
8906 (user-error "Invalid shift specification %s" shift)))))
8907 (goto-char end-of-tree)
8908 (unless (bolp) (insert "\n"))
8909 (let* ((end (point))
8910 (template (buffer-substring beg end))
8911 (shift-n (and doshift (string-to-number (match-string 1 shift))))
8912 (shift-what (pcase (and doshift (match-string 2 shift))
8913 (`nil nil)
8914 ("d" 'day)
8915 ("w" (setq shift-n (* 7 shift-n)) 'day)
8916 ("m" 'month)
8917 ("y" 'year)
8918 (_ (error "Unsupported time unit"))))
8919 (nmin 1)
8920 (nmax n)
8921 (n-no-remove -1)
8922 (idprop (org-entry-get nil "ID")))
8923 (when (and doshift
8924 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
8925 template))
8926 (delete-region beg end)
8927 (setq end beg)
8928 (setq nmin 0)
8929 (setq nmax (1+ nmax))
8930 (setq n-no-remove nmax))
8931 (goto-char end)
8932 (cl-loop for n from nmin to nmax do
8933 (insert
8934 ;; Prepare clone.
8935 (with-temp-buffer
8936 (insert template)
8937 (org-mode)
8938 (goto-char (point-min))
8939 (org-show-subtree)
8940 (and idprop (if org-clone-delete-id
8941 (org-entry-delete nil "ID")
8942 (org-id-get-create t)))
8943 (unless (= n 0)
8944 (while (re-search-forward org-clock-line-re nil t)
8945 (delete-region (line-beginning-position)
8946 (line-beginning-position 2)))
8947 (goto-char (point-min))
8948 (while (re-search-forward org-drawer-regexp nil t)
8949 (org-remove-empty-drawer-at (point))))
8950 (goto-char (point-min))
8951 (when doshift
8952 (while (re-search-forward org-ts-regexp-both nil t)
8953 (org-timestamp-change (* n shift-n) shift-what))
8954 (unless (= n n-no-remove)
8955 (goto-char (point-min))
8956 (while (re-search-forward org-ts-regexp nil t)
8957 (save-excursion
8958 (goto-char (match-beginning 0))
8959 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8960 (delete-region (match-beginning 1) (match-end 1)))))))
8961 (buffer-string)))))
8962 (goto-char beg)))
8964 ;;; Outline Sorting
8966 (defun org-sort (with-case)
8967 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8968 Optional argument WITH-CASE means sort case-sensitively."
8969 (interactive "P")
8970 (cond
8971 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8972 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8974 (org-call-with-arg 'org-sort-entries with-case))))
8976 (defun org-sort-remove-invisible (s)
8977 "Remove invisible links from string S."
8978 (remove-text-properties 0 (length s) org-rm-props s)
8979 (while (string-match org-bracket-link-regexp s)
8980 (setq s (replace-match (if (match-end 2)
8981 (match-string 3 s)
8982 (match-string 1 s))
8983 t t s)))
8984 (let ((st (format " %s " s)))
8985 (while (string-match org-emph-re st)
8986 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8987 (setq s (substring st 1 -1)))
8990 (defvar org-priority-regexp) ; defined later in the file
8992 (defvar org-after-sorting-entries-or-items-hook nil
8993 "Hook that is run after a bunch of entries or items have been sorted.
8994 When children are sorted, the cursor is in the parent line when this
8995 hook gets called. When a region or a plain list is sorted, the cursor
8996 will be in the first entry of the sorted region/list.")
8998 (defun org-sort-entries
8999 (&optional with-case sorting-type getkey-func compare-func property
9000 interactive?)
9001 "Sort entries on a certain level of an outline tree.
9002 If there is an active region, the entries in the region are sorted.
9003 Else, if the cursor is before the first entry, sort the top-level items.
9004 Else, the children of the entry at point are sorted.
9006 Sorting can be alphabetically, numerically, by date/time as given by
9007 a time stamp, by a property, by priority order, or by a custom function.
9009 The command prompts for the sorting type unless it has been given to the
9010 function through the SORTING-TYPE argument, which needs to be a character,
9011 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9012 the precise meaning of each character:
9014 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9015 c By creation time, which is assumed to be the first inactive time stamp
9016 at the beginning of a line.
9017 d By deadline date/time.
9018 k By clocking time.
9019 n Numerically, by converting the beginning of the entry/item to a number.
9020 o By order of TODO keywords.
9021 p By priority according to the cookie.
9022 r By the value of a property.
9023 s By scheduled date/time.
9024 t By date/time, either the first active time stamp in the entry, or, if
9025 none exist, by the first inactive one.
9027 Capital letters will reverse the sort order.
9029 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9030 called with point at the beginning of the record. It must return a
9031 value that is compatible with COMPARE-FUNC, the function used to
9032 compare entries.
9034 Comparing entries ignores case by default. However, with an optional argument
9035 WITH-CASE, the sorting considers case as well.
9037 Sorting is done against the visible part of the headlines, it ignores hidden
9038 links.
9040 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
9042 A non-nil value for INTERACTIVE? is used to signal that this
9043 function is being called interactively."
9044 (interactive (list current-prefix-arg nil nil nil nil t))
9045 (let ((case-func (if with-case 'identity 'downcase))
9046 (cmstr
9047 ;; The clock marker is lost when using `sort-subr', let's
9048 ;; store the clocking string.
9049 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9050 (save-excursion
9051 (goto-char org-clock-marker)
9052 (buffer-substring-no-properties (line-beginning-position)
9053 (point)))))
9054 start beg end stars re re2
9055 txt what tmp)
9056 ;; Find beginning and end of region to sort
9057 (cond
9058 ((org-region-active-p)
9059 ;; we will sort the region
9060 (setq end (region-end)
9061 what "region")
9062 (goto-char (region-beginning))
9063 (unless (org-at-heading-p) (outline-next-heading))
9064 (setq start (point)))
9065 ((or (org-at-heading-p)
9066 (ignore-errors (progn (org-back-to-heading) t)))
9067 ;; we will sort the children of the current headline
9068 (org-back-to-heading)
9069 (setq start (point)
9070 end (progn (org-end-of-subtree t t)
9071 (or (bolp) (insert "\n"))
9072 (when (>= (org-back-over-empty-lines) 1)
9073 (forward-line 1))
9074 (point))
9075 what "children")
9076 (goto-char start)
9077 (outline-show-subtree)
9078 (outline-next-heading))
9080 ;; we will sort the top-level entries in this file
9081 (goto-char (point-min))
9082 (or (org-at-heading-p) (outline-next-heading))
9083 (setq start (point))
9084 (goto-char (point-max))
9085 (beginning-of-line 1)
9086 (when (looking-at ".*?\\S-")
9087 ;; File ends in a non-white line
9088 (end-of-line 1)
9089 (insert "\n"))
9090 (setq end (point-max))
9091 (setq what "top-level")
9092 (goto-char start)
9093 (outline-show-all)))
9095 (setq beg (point))
9096 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9098 (looking-at "\\(\\*+\\)")
9099 (setq stars (match-string 1)
9100 re (concat "^" (regexp-quote stars) " +")
9101 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9102 txt (buffer-substring beg end))
9103 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9104 (when (and (not (equal stars "*")) (string-match re2 txt))
9105 (user-error "Region to sort contains a level above the first entry"))
9107 (unless sorting-type
9108 (message
9109 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9110 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9111 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9112 what)
9113 (setq sorting-type (read-char-exclusive)))
9115 (unless getkey-func
9116 (and (= (downcase sorting-type) ?f)
9117 (setq getkey-func
9118 (or (and interactive?
9119 (org-read-function
9120 "Function for extracting keys: "))
9121 (error "Missing key extractor")))))
9123 (and (= (downcase sorting-type) ?r)
9124 (not property)
9125 (setq property
9126 (completing-read "Property: "
9127 (mapcar #'list (org-buffer-property-keys t))
9128 nil t)))
9130 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9131 (message "Sorting entries...")
9133 (save-restriction
9134 (narrow-to-region start end)
9135 (let ((dcst (downcase sorting-type))
9136 (case-fold-search nil)
9137 (now (current-time)))
9138 (sort-subr
9139 (/= dcst sorting-type)
9140 ;; This function moves to the beginning character of the "record" to
9141 ;; be sorted.
9142 (lambda nil
9143 (if (re-search-forward re nil t)
9144 (goto-char (match-beginning 0))
9145 (goto-char (point-max))))
9146 ;; This function moves to the last character of the "record" being
9147 ;; sorted.
9148 (lambda nil
9149 (save-match-data
9150 (condition-case nil
9151 (outline-forward-same-level 1)
9152 (error
9153 (goto-char (point-max))))))
9154 ;; This function returns the value that gets sorted against.
9155 (lambda nil
9156 (cond
9157 ((= dcst ?n)
9158 (if (looking-at org-complex-heading-regexp)
9159 (string-to-number (org-sort-remove-invisible (match-string 4)))
9160 nil))
9161 ((= dcst ?a)
9162 (if (looking-at org-complex-heading-regexp)
9163 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9164 nil))
9165 ((= dcst ?k)
9166 (or (get-text-property (point) :org-clock-minutes) 0))
9167 ((= dcst ?t)
9168 (let ((end (save-excursion (outline-next-heading) (point))))
9169 (if (or (re-search-forward org-ts-regexp end t)
9170 (re-search-forward org-ts-regexp-both end t))
9171 (org-time-string-to-seconds (match-string 0))
9172 (float-time now))))
9173 ((= dcst ?c)
9174 (let ((end (save-excursion (outline-next-heading) (point))))
9175 (if (re-search-forward
9176 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9177 end t)
9178 (org-time-string-to-seconds (match-string 0))
9179 (float-time now))))
9180 ((= dcst ?s)
9181 (let ((end (save-excursion (outline-next-heading) (point))))
9182 (if (re-search-forward org-scheduled-time-regexp end t)
9183 (org-time-string-to-seconds (match-string 1))
9184 (float-time now))))
9185 ((= dcst ?d)
9186 (let ((end (save-excursion (outline-next-heading) (point))))
9187 (if (re-search-forward org-deadline-time-regexp end t)
9188 (org-time-string-to-seconds (match-string 1))
9189 (float-time now))))
9190 ((= dcst ?p)
9191 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9192 (string-to-char (match-string 2))
9193 org-default-priority))
9194 ((= dcst ?r)
9195 (or (org-entry-get nil property) ""))
9196 ((= dcst ?o)
9197 (when (looking-at org-complex-heading-regexp)
9198 (let* ((m (match-string 2))
9199 (s (if (member m org-done-keywords) '- '+)))
9200 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9201 ((= dcst ?f)
9202 (if getkey-func
9203 (progn
9204 (setq tmp (funcall getkey-func))
9205 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9206 tmp)
9207 (error "Invalid key function `%s'" getkey-func)))
9208 (t (error "Invalid sorting type `%c'" sorting-type))))
9210 (cond
9211 ((= dcst ?a) 'string<)
9212 ((= dcst ?f)
9213 (or compare-func
9214 (and interactive?
9215 (org-read-function
9216 (concat "Function for comparing keys "
9217 "(empty for default `sort-subr' predicate): ")
9218 'allow-empty))))
9219 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9220 (run-hooks 'org-after-sorting-entries-or-items-hook)
9221 ;; Reset the clock marker if needed
9222 (when cmstr
9223 (save-excursion
9224 (goto-char start)
9225 (search-forward cmstr nil t)
9226 (move-marker org-clock-marker (point))))
9227 (message "Sorting entries...done")))
9229 ;;; The orgstruct minor mode
9231 ;; Define a minor mode which can be used in other modes in order to
9232 ;; integrate the Org mode structure editing commands.
9234 ;; This is really a hack, because the Org mode structure commands use
9235 ;; keys which normally belong to the major mode. Here is how it
9236 ;; works: The minor mode defines all the keys necessary to operate the
9237 ;; structure commands, but wraps the commands into a function which
9238 ;; tests if the cursor is currently at a headline or a plain list
9239 ;; item. If that is the case, the structure command is used,
9240 ;; temporarily setting many Org mode variables like regular
9241 ;; expressions for filling etc. However, when any of those keys is
9242 ;; used at a different location, function uses `key-binding' to look
9243 ;; up if the key has an associated command in another currently active
9244 ;; keymap (minor modes, major mode, global), and executes that
9245 ;; command. There might be problems if any of the keys is otherwise
9246 ;; used as a prefix key.
9248 (defcustom orgstruct-heading-prefix-regexp ""
9249 "Regexp that matches the custom prefix of Org headlines in
9250 orgstruct(++)-mode."
9251 :group 'org
9252 :version "24.4"
9253 :package-version '(Org . "8.3")
9254 :type 'regexp)
9255 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9257 (defcustom orgstruct-setup-hook nil
9258 "Hook run after orgstruct-mode-map is filled."
9259 :group 'org
9260 :version "24.4"
9261 :package-version '(Org . "8.0")
9262 :type 'hook)
9264 (defvar orgstruct-initialized nil)
9266 (defvar org-local-vars nil
9267 "List of local variables, for use by `orgstruct-mode'.")
9269 ;;;###autoload
9270 (define-minor-mode orgstruct-mode
9271 "Toggle the minor mode `orgstruct-mode'.
9272 This mode is for using Org mode structure commands in other
9273 modes. The following keys behave as if Org mode were active, if
9274 the cursor is on a headline, or on a plain list item (both as
9275 defined by Org mode)."
9276 nil " OrgStruct" (make-sparse-keymap)
9277 (funcall (if orgstruct-mode
9278 'add-to-invisibility-spec
9279 'remove-from-invisibility-spec)
9280 '(outline . t))
9281 (when orgstruct-mode
9282 (org-load-modules-maybe)
9283 (unless orgstruct-initialized
9284 (orgstruct-setup)
9285 (setq orgstruct-initialized t))))
9287 ;;;###autoload
9288 (defun turn-on-orgstruct ()
9289 "Unconditionally turn on `orgstruct-mode'."
9290 (orgstruct-mode 1))
9292 (defvar-local orgstruct-is-++ nil
9293 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9294 (defvar-local org-fb-vars nil)
9295 (defun orgstruct++-mode (&optional arg)
9296 "Toggle `orgstruct-mode', the enhanced version of it.
9297 In addition to setting orgstruct-mode, this also exports all
9298 indentation and autofilling variables from Org mode into the
9299 buffer. It will also recognize item context in multiline items."
9300 (interactive "P")
9301 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9302 (if (< arg 1)
9303 (progn (orgstruct-mode -1)
9304 (dolist (v org-fb-vars)
9305 (set (make-local-variable (car v))
9306 (if (eq (car-safe (cadr v)) 'quote)
9307 (cl-cadadr v)
9308 (nth 1 v)))))
9309 (orgstruct-mode 1)
9310 (setq org-fb-vars nil)
9311 (unless org-local-vars
9312 (setq org-local-vars (org-get-local-variables)))
9313 (let (var val)
9314 (dolist (x org-local-vars)
9315 (when (string-match
9316 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9317 \\|fill-prefix\\|indent-\\)"
9318 (symbol-name (car x)))
9319 (setq var (car x) val (nth 1 x))
9320 (push (list var `(quote ,(eval var))) org-fb-vars)
9321 (set (make-local-variable var)
9322 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9323 (setq-local orgstruct-is-++ t))))
9325 ;;;###autoload
9326 (defun turn-on-orgstruct++ ()
9327 "Unconditionally turn on `orgstruct++-mode'."
9328 (orgstruct++-mode 1))
9330 (defun orgstruct-error ()
9331 "Error when there is no default binding for a structure key."
9332 (interactive)
9333 (funcall (if (fboundp 'user-error)
9334 'user-error
9335 'error)
9336 "This key has no function outside structure elements"))
9338 (defun orgstruct-setup ()
9339 "Setup orgstruct keymap."
9340 (dolist (cell '((org-demote . t)
9341 (org-metaleft . t)
9342 (org-metaright . t)
9343 (org-promote . t)
9344 (org-shiftmetaleft . t)
9345 (org-shiftmetaright . t)
9346 org-backward-element
9347 org-backward-heading-same-level
9348 org-ctrl-c-ret
9349 org-ctrl-c-minus
9350 org-ctrl-c-star
9351 org-cycle
9352 org-force-cycle-archived
9353 org-forward-heading-same-level
9354 org-insert-heading
9355 org-insert-heading-respect-content
9356 org-kill-note-or-show-branches
9357 org-mark-subtree
9358 org-meta-return
9359 org-metadown
9360 org-metaup
9361 org-narrow-to-subtree
9362 org-promote-subtree
9363 org-reveal
9364 org-shiftdown
9365 org-shiftleft
9366 org-shiftmetadown
9367 org-shiftmetaup
9368 org-shiftright
9369 org-shifttab
9370 org-shifttab
9371 org-shiftup
9372 org-show-children
9373 org-show-subtree
9374 org-sort
9375 org-up-element
9376 outline-demote
9377 outline-next-visible-heading
9378 outline-previous-visible-heading
9379 outline-promote
9380 outline-up-heading))
9381 (let ((f (or (car-safe cell) cell))
9382 (disable-when-heading-prefix (cdr-safe cell)))
9383 (when (fboundp f)
9384 (let ((new-bindings))
9385 (dolist (binding (nconc (where-is-internal f org-mode-map)
9386 (where-is-internal f outline-mode-map)))
9387 (push binding new-bindings)
9388 ;; TODO use local-function-key-map
9389 (dolist (rep '(("<tab>" . "TAB")
9390 ("<return>" . "RET")
9391 ("<escape>" . "ESC")
9392 ("<delete>" . "DEL")))
9393 (setq binding (read-kbd-macro
9394 (let ((case-fold-search))
9395 (replace-regexp-in-string
9396 (regexp-quote (cdr rep))
9397 (car rep)
9398 (key-description binding)))))
9399 (cl-pushnew binding new-bindings :test 'equal)))
9400 (dolist (binding new-bindings)
9401 (let ((key (lookup-key orgstruct-mode-map binding)))
9402 (when (or (not key) (numberp key))
9403 (ignore-errors
9404 (org-defkey orgstruct-mode-map
9405 binding
9406 (orgstruct-make-binding
9407 f binding disable-when-heading-prefix))))))))))
9408 (run-hooks 'orgstruct-setup-hook))
9410 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9411 "Create a function for binding in the structure minor mode.
9412 FUN is the command to call inside a table. KEY is the key that
9413 should be checked in for a command to execute outside of tables.
9414 Non-nil `disable-when-heading-prefix' means to disable the command
9415 if `orgstruct-heading-prefix-regexp' is not empty."
9416 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9417 (let ((nname name)
9418 (i 0))
9419 (while (fboundp (intern nname))
9420 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9421 (setq name (intern nname)))
9422 (eval
9423 (let ((bindings '((org-heading-regexp
9424 (concat "^"
9425 orgstruct-heading-prefix-regexp
9426 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9427 (org-outline-regexp
9428 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9429 (org-outline-regexp-bol
9430 (concat "^" org-outline-regexp))
9431 (outline-regexp org-outline-regexp)
9432 (outline-heading-end-regexp "\n")
9433 (outline-level 'org-outline-level)
9434 (outline-heading-alist))))
9435 `(defun ,name (arg)
9436 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9437 "Outside of structure, run the binding of `"
9438 (key-description key) "'."
9439 (when disable-when-heading-prefix
9440 (concat
9441 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9442 "back to the default binding due to limitations of Org's implementation of\n"
9443 "`" (symbol-name fun) "'.")))
9444 (interactive "p")
9445 (let* ((disable
9446 ,(and disable-when-heading-prefix
9447 '(not (string= orgstruct-heading-prefix-regexp ""))))
9448 (fallback
9449 (or disable
9450 (not
9451 (let* ,bindings
9452 (org-context-p 'headline 'item
9453 ,(when (memq fun
9454 '(org-insert-heading
9455 org-insert-heading-respect-content
9456 org-meta-return))
9457 '(when orgstruct-is-++
9458 'item-body))))))))
9459 (if fallback
9460 (let* ((orgstruct-mode)
9461 (binding
9462 (let ((key ,key))
9463 (catch 'exit
9464 (dolist
9465 (rep
9466 '(nil
9467 ("<\\([^>]*\\)tab>" . "\\1TAB")
9468 ("<\\([^>]*\\)return>" . "\\1RET")
9469 ("<\\([^>]*\\)escape>" . "\\1ESC")
9470 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9471 nil)
9472 (when rep
9473 (setq key (read-kbd-macro
9474 (let ((case-fold-search))
9475 (replace-regexp-in-string
9476 (car rep)
9477 (cdr rep)
9478 (key-description key))))))
9479 (when (key-binding key)
9480 (throw 'exit (key-binding key))))))))
9481 (if (keymapp binding)
9482 (org-set-transient-map binding)
9483 (let ((func (or binding
9484 (unless disable
9485 'orgstruct-error))))
9486 (when func
9487 (call-interactively func)))))
9488 (org-run-like-in-org-mode
9489 (lambda ()
9490 (interactive)
9491 (let* ,bindings
9492 (call-interactively ',fun)))))))))
9493 name))
9495 (defun org-contextualize-keys (alist contexts)
9496 "Return valid elements in ALIST depending on CONTEXTS.
9498 `org-agenda-custom-commands' or `org-capture-templates' are the
9499 values used for ALIST, and `org-agenda-custom-commands-contexts'
9500 or `org-capture-templates-contexts' are the associated contexts
9501 definitions."
9502 (let ((contexts
9503 ;; normalize contexts
9504 (mapcar
9505 (lambda(c) (cond ((listp (cadr c))
9506 (list (car c) (car c) (nth 1 c)))
9507 ((string= "" (cadr c))
9508 (list (car c) (car c) (nth 2 c)))
9509 (t c)))
9510 contexts))
9511 (a alist) r s)
9512 ;; loop over all commands or templates
9513 (dolist (c a)
9514 (let (vrules repl)
9515 (cond
9516 ((not (assoc (car c) contexts))
9517 (push c r))
9518 ((and (assoc (car c) contexts)
9519 (setq vrules (org-contextualize-validate-key
9520 (car c) contexts)))
9521 (mapc (lambda (vr)
9522 (unless (equal (car vr) (cadr vr))
9523 (setq repl vr)))
9524 vrules)
9525 (if (not repl) (push c r)
9526 (push (cadr repl) s)
9527 (push
9528 (cons (car c)
9529 (cdr (or (assoc (cadr repl) alist)
9530 (error "Undefined key `%s' as contextual replacement for `%s'"
9531 (cadr repl) (car c)))))
9532 r))))))
9533 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9534 (delq
9536 (delete-dups
9537 (mapcar (lambda (x)
9538 (let ((tpl (car x)))
9539 (unless (delq
9541 (mapcar (lambda (y)
9542 (equal y tpl))
9544 x)))
9545 (reverse r))))))
9547 (defun org-contextualize-validate-key (key contexts)
9548 "Check CONTEXTS for agenda or capture KEY."
9549 (let (res)
9550 (dolist (r contexts)
9551 (dolist (rr (car (last r)))
9552 (when
9553 (and (equal key (car r))
9554 (if (functionp rr) (funcall rr)
9555 (or (and (eq (car rr) 'in-file)
9556 (buffer-file-name)
9557 (string-match (cdr rr) (buffer-file-name)))
9558 (and (eq (car rr) 'in-mode)
9559 (string-match (cdr rr) (symbol-name major-mode)))
9560 (and (eq (car rr) 'in-buffer)
9561 (string-match (cdr rr) (buffer-name)))
9562 (when (and (eq (car rr) 'not-in-file)
9563 (buffer-file-name))
9564 (not (string-match (cdr rr) (buffer-file-name))))
9565 (when (eq (car rr) 'not-in-mode)
9566 (not (string-match (cdr rr) (symbol-name major-mode))))
9567 (when (eq (car rr) 'not-in-buffer)
9568 (not (string-match (cdr rr) (buffer-name)))))))
9569 (push r res))))
9570 (delete-dups (delq nil res))))
9572 (defun org-context-p (&rest contexts)
9573 "Check if local context is any of CONTEXTS.
9574 Possible values in the list of contexts are `table', `headline', and `item'."
9575 (let ((pos (point)))
9576 (goto-char (point-at-bol))
9577 (prog1 (or (and (memq 'table contexts)
9578 (looking-at "[ \t]*|"))
9579 (and (memq 'headline contexts)
9580 (looking-at org-outline-regexp))
9581 (and (memq 'item contexts)
9582 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9583 (and (memq 'item-body contexts)
9584 (org-in-item-p)))
9585 (goto-char pos))))
9587 (defconst org-unique-local-variables
9588 '(org-element--cache
9589 org-element--cache-objects
9590 org-element--cache-sync-keys
9591 org-element--cache-sync-requests
9592 org-element--cache-sync-timer)
9593 "List of local variables that cannot be transferred to another buffer.")
9595 (defun org-get-local-variables ()
9596 "Return a list of all local variables in an Org mode buffer."
9597 (delq nil
9598 (mapcar
9599 (lambda (x)
9600 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9601 (name (car binding)))
9602 (and (not (get name 'org-state))
9603 (not (memq name org-unique-local-variables))
9604 (string-match-p
9605 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9606 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9607 (symbol-name name))
9608 binding)))
9609 (with-temp-buffer
9610 (org-mode)
9611 (buffer-local-variables)))))
9613 (defun org-clone-local-variables (from-buffer &optional regexp)
9614 "Clone local variables from FROM-BUFFER.
9615 Optional argument REGEXP selects variables to clone."
9616 (dolist (pair (buffer-local-variables from-buffer))
9617 (pcase pair
9618 (`(,name . ,value) ;ignore unbound variables
9619 (when (and (not (memq name org-unique-local-variables))
9620 (or (null regexp) (string-match-p regexp (symbol-name name))))
9621 (set (make-local-variable name) value))))))
9623 ;;;###autoload
9624 (defun org-run-like-in-org-mode (cmd)
9625 "Run a command, pretending that the current buffer is in Org mode.
9626 This will temporarily bind local variables that are typically bound in
9627 Org mode to the values they have in Org mode, and then interactively
9628 call CMD."
9629 (org-load-modules-maybe)
9630 (unless org-local-vars
9631 (setq org-local-vars (org-get-local-variables)))
9632 (let (binds)
9633 (dolist (var org-local-vars)
9634 (when (or (not (boundp (car var)))
9635 (eq (symbol-value (car var))
9636 (default-value (car var))))
9637 (push (list (car var) `(quote ,(cadr var))) binds)))
9638 (eval `(let ,binds
9639 (call-interactively (quote ,cmd))))))
9641 (defun org-get-category (&optional pos force-refresh)
9642 "Get the category applying to position POS."
9643 (save-match-data
9644 (when force-refresh (org-refresh-category-properties))
9645 (let ((pos (or pos (point))))
9646 (or (get-text-property pos 'org-category)
9647 (progn (org-refresh-category-properties)
9648 (get-text-property pos 'org-category))))))
9650 ;;; Refresh properties
9652 (defun org-refresh-properties (dprop tprop)
9653 "Refresh buffer text properties.
9654 DPROP is the drawer property and TPROP is either the
9655 corresponding text property to set, or an alist with each element
9656 being a text property (as a symbol) and a function to apply to
9657 the value of the drawer property."
9658 (let* ((case-fold-search t)
9659 (inhibit-read-only t)
9660 (inherit? (org-property-inherit-p dprop))
9661 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
9662 (global (and inherit? (org--property-global-value dprop nil))))
9663 (org-with-silent-modifications
9664 (org-with-point-at 1
9665 ;; Set global values (e.g., values defined through
9666 ;; "#+PROPERTY:" keywords) to the whole buffer.
9667 (when global (put-text-property (point-min) (point-max) tprop global))
9668 ;; Set local values.
9669 (while (re-search-forward property-re nil t)
9670 (when (org-at-property-p)
9671 (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
9672 (outline-next-heading))))))
9674 (defun org-refresh-property (tprop p &optional inherit)
9675 "Refresh the buffer text property TPROP from the drawer property P.
9676 The refresh happens only for the current headline, or the whole
9677 sub-tree if optional argument INHERIT is non-nil."
9678 (unless (org-before-first-heading-p)
9679 (save-excursion
9680 (org-back-to-heading t)
9681 (let ((start (point))
9682 (end (save-excursion
9683 (if inherit (org-end-of-subtree t t)
9684 (or (outline-next-heading) (point-max))))))
9685 (if (symbolp tprop)
9686 ;; TPROP is a text property symbol.
9687 (put-text-property start end tprop p)
9688 ;; TPROP is an alist with (property . function) elements.
9689 (pcase-dolist (`(,prop . ,f) tprop)
9690 (put-text-property start end prop (funcall f p))))))))
9692 (defun org-refresh-category-properties ()
9693 "Refresh category text properties in the buffer."
9694 (let ((case-fold-search t)
9695 (inhibit-read-only t)
9696 (default-category
9697 (cond ((null org-category)
9698 (if buffer-file-name
9699 (file-name-sans-extension
9700 (file-name-nondirectory buffer-file-name))
9701 "???"))
9702 ((symbolp org-category) (symbol-name org-category))
9703 (t org-category))))
9704 (org-with-silent-modifications
9705 (org-with-wide-buffer
9706 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9707 ;; This is the default category for the buffer. If none is
9708 ;; found, fall-back to `org-category' or buffer file name.
9709 (put-text-property
9710 (point-min) (point-max)
9711 'org-category
9712 (catch 'buffer-category
9713 (goto-char (point-max))
9714 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9715 (let ((element (org-element-at-point)))
9716 (when (eq (org-element-type element) 'keyword)
9717 (throw 'buffer-category
9718 (org-element-property :value element)))))
9719 default-category))
9720 ;; Set sub-tree specific categories.
9721 (goto-char (point-min))
9722 (let ((regexp (org-re-property "CATEGORY")))
9723 (while (re-search-forward regexp nil t)
9724 (let ((value (match-string-no-properties 3)))
9725 (when (org-at-property-p)
9726 (put-text-property
9727 (save-excursion (org-back-to-heading t) (point))
9728 (save-excursion (org-end-of-subtree t t) (point))
9729 'org-category
9730 value)))))))))
9732 (defun org-refresh-stats-properties ()
9733 "Refresh stats text properties in the buffer."
9734 (org-with-silent-modifications
9735 (org-with-point-at 1
9736 (let ((regexp (concat org-outline-regexp-bol
9737 ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
9738 (while (re-search-forward regexp nil t)
9739 (let* ((numerator (string-to-number (match-string 1)))
9740 (denominator (and (match-end 2)
9741 (string-to-number (match-string 2))))
9742 (stats (cond ((not denominator) numerator) ;percent
9743 ((= denominator 0) 0)
9744 (t (/ (* numerator 100) denominator)))))
9745 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9746 'org-stats stats)))))))
9748 (defun org-refresh-effort-properties ()
9749 "Refresh effort properties"
9750 (org-refresh-properties
9751 org-effort-property
9752 '((effort . identity)
9753 (effort-minutes . org-duration-string-to-minutes))))
9755 ;;;; Link Stuff
9757 ;;; Link abbreviations
9759 (defun org-link-expand-abbrev (link)
9760 "Apply replacements as defined in `org-link-abbrev-alist'."
9761 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9762 (let* ((key (match-string 1 link))
9763 (as (or (assoc key org-link-abbrev-alist-local)
9764 (assoc key org-link-abbrev-alist)))
9765 (tag (and (match-end 2) (match-string 3 link)))
9766 rpl)
9767 (if (not as)
9768 link
9769 (setq rpl (cdr as))
9770 (cond
9771 ((symbolp rpl) (funcall rpl tag))
9772 ((string-match "%(\\([^)]+\\))" rpl)
9773 (replace-match
9774 (save-match-data
9775 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9776 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9777 ((string-match "%h" rpl)
9778 (replace-match (url-hexify-string (or tag "")) t t rpl))
9779 (t (concat rpl tag)))))
9780 link))
9782 ;;; Storing and inserting links
9784 (defvar org-insert-link-history nil
9785 "Minibuffer history for links inserted with `org-insert-link'.")
9787 (defvar org-stored-links nil
9788 "Contains the links stored with `org-store-link'.")
9790 (defvar org-store-link-plist nil
9791 "Plist with info about the most recently link created with `org-store-link'.")
9793 (defun org-store-link-functions ()
9794 "Return a list of functions that are called to create and store a link.
9795 The functions defined in the :store property of
9796 `org-link-parameters'.
9798 Each function will be called in turn until one returns a non-nil
9799 value. Each function should check if it is responsible for
9800 creating this link (for example by looking at the major mode).
9801 If not, it must exit and return nil. If yes, it should return
9802 a non-nil value after calling `org-store-link-props' with a list
9803 of properties and values. Special properties are:
9805 :type The link prefix, like \"http\". This must be given.
9806 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9807 This is obligatory as well.
9808 :description Optional default description for the second pair
9809 of brackets in an Org mode link. The user can still change
9810 this when inserting this link into an Org mode buffer.
9812 In addition to these, any additional properties can be specified
9813 and then used in capture templates."
9814 (cl-loop for link in org-link-parameters
9815 with store-func
9816 do (setq store-func (org-link-get-parameter (car link) :store))
9817 if store-func
9818 collect store-func))
9820 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9821 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9823 ;;;###autoload
9824 (defun org-store-link (arg)
9825 "Store an org-link to the current location.
9826 \\<org-mode-map>
9827 This link is added to `org-stored-links' and can later be inserted
9828 into an Org buffer with `org-insert-link' (`\\[org-insert-link]').
9830 For some link types, a `\\[universal-argument]' prefix ARG is interpreted. \
9831 A single
9832 `\\[universal-argument]' negates `org-context-in-file-links' for file links or
9833 `org-gnus-prefer-web-links' for links to Usenet articles.
9835 A `\\[universal-argument] \\[universal-argument]' prefix ARG forces \
9836 skipping storing functions that are not
9837 part of Org core.
9839 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
9840 prefix ARG forces storing a link for each line in the
9841 active region."
9842 (interactive "P")
9843 (org-load-modules-maybe)
9844 (if (and (equal arg '(64)) (org-region-active-p))
9845 (save-excursion
9846 (let ((end (region-end)))
9847 (goto-char (region-beginning))
9848 (set-mark (point))
9849 (while (< (point-at-eol) end)
9850 (move-end-of-line 1) (activate-mark)
9851 (let (current-prefix-arg)
9852 (call-interactively 'org-store-link))
9853 (move-beginning-of-line 2)
9854 (set-mark (point)))))
9855 (setq org-store-link-plist nil)
9856 (let (link cpltxt desc description search
9857 txt custom-id agenda-link sfuns sfunsn)
9858 (cond
9860 ;; Store a link using an external link type
9861 ((and (not (equal arg '(16)))
9862 (setq sfuns
9863 (delq
9864 nil (mapcar (lambda (f)
9865 (let (fs) (if (funcall f) (push f fs))))
9866 (org-store-link-functions)))
9867 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9868 (or (and (cdr sfuns)
9869 (funcall (intern
9870 (completing-read
9871 "Which function for creating the link? "
9872 sfunsn nil t (car sfunsn)))))
9873 (funcall (caar sfuns)))
9874 (setq link (plist-get org-store-link-plist :link)
9875 desc (or (plist-get org-store-link-plist
9876 :description)
9877 link))))
9879 ;; Store a link from a source code buffer.
9880 ((org-src-edit-buffer-p)
9881 (let ((coderef-format (org-src-coderef-format)))
9882 (cond ((save-excursion
9883 (beginning-of-line)
9884 (looking-at (org-src-coderef-regexp coderef-format)))
9885 (setq link (format "(%s)" (match-string-no-properties 3))))
9886 ((called-interactively-p 'any)
9887 (let ((label (read-string "Code line label: ")))
9888 (end-of-line)
9889 (setq link (format coderef-format label))
9890 (let ((gc (- 79 (length link))))
9891 (if (< (current-column) gc)
9892 (org-move-to-column gc t)
9893 (insert " ")))
9894 (insert link)
9895 (setq link (concat "(" label ")"))
9896 (setq desc nil)))
9897 (t (setq link nil)))))
9899 ;; We are in the agenda, link to referenced location
9900 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9901 (let ((m (or (get-text-property (point) 'org-hd-marker)
9902 (get-text-property (point) 'org-marker))))
9903 (when m
9904 (org-with-point-at m
9905 (setq agenda-link
9906 (if (called-interactively-p 'any)
9907 (call-interactively 'org-store-link)
9908 (org-store-link nil)))))))
9910 ((eq major-mode 'calendar-mode)
9911 (let ((cd (calendar-cursor-to-date)))
9912 (setq link
9913 (format-time-string
9914 (car org-time-stamp-formats)
9915 (apply 'encode-time
9916 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9917 nil nil nil))))
9918 (org-store-link-props :type "calendar" :date cd)))
9920 ((eq major-mode 'help-mode)
9921 (setq link (concat "help:" (save-excursion
9922 (goto-char (point-min))
9923 (looking-at "^[^ ]+")
9924 (match-string 0))))
9925 (org-store-link-props :type "help"))
9927 ((eq major-mode 'w3-mode)
9928 (setq cpltxt (if (and (buffer-name)
9929 (not (string-match "Untitled" (buffer-name))))
9930 (buffer-name)
9931 (url-view-url t))
9932 link (url-view-url t))
9933 (org-store-link-props :type "w3" :url (url-view-url t)))
9935 ((eq major-mode 'image-mode)
9936 (setq cpltxt (concat "file:"
9937 (abbreviate-file-name buffer-file-name))
9938 link cpltxt)
9939 (org-store-link-props :type "image" :file buffer-file-name))
9941 ;; In dired, store a link to the file of the current line
9942 ((derived-mode-p 'dired-mode)
9943 (let ((file (dired-get-filename nil t)))
9944 (setq file (if file
9945 (abbreviate-file-name
9946 (expand-file-name (dired-get-filename nil t)))
9947 ;; otherwise, no file so use current directory.
9948 default-directory))
9949 (setq cpltxt (concat "file:" file)
9950 link cpltxt)))
9952 ((setq search (run-hook-with-args-until-success
9953 'org-create-file-search-functions))
9954 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9955 "::" search))
9956 (setq cpltxt (or description link)))
9958 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9959 (org-with-limited-levels
9960 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9961 (cond
9962 ;; Store a link using the target at point
9963 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9964 (setq cpltxt
9965 (concat "file:"
9966 (abbreviate-file-name
9967 (buffer-file-name (buffer-base-buffer)))
9968 "::" (match-string 1))
9969 link cpltxt))
9970 ((and (featurep 'org-id)
9971 (or (eq org-id-link-to-org-use-id t)
9972 (and (called-interactively-p 'any)
9973 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9974 (and (eq org-id-link-to-org-use-id
9975 'create-if-interactive-and-no-custom-id)
9976 (not custom-id))))
9977 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9978 ;; Store a link using the ID at point
9979 (setq link (condition-case nil
9980 (prog1 (org-id-store-link)
9981 (setq desc (or (plist-get org-store-link-plist
9982 :description)
9983 "")))
9984 (error
9985 ;; Probably before first headline, link only to file
9986 (concat "file:"
9987 (abbreviate-file-name
9988 (buffer-file-name (buffer-base-buffer))))))))
9990 ;; Just link to current headline
9991 (setq cpltxt (concat "file:"
9992 (abbreviate-file-name
9993 (buffer-file-name (buffer-base-buffer)))))
9994 ;; Add a context search string
9995 (when (org-xor org-context-in-file-links
9996 (equal arg '(4)))
9997 (let* ((element (org-element-at-point))
9998 (name (org-element-property :name element)))
9999 (setq txt (cond
10000 ((org-at-heading-p) nil)
10001 (name)
10002 ((org-region-active-p)
10003 (buffer-substring (region-beginning) (region-end)))))
10004 (when (or (null txt) (string-match "\\S-" txt))
10005 (setq cpltxt
10006 (concat cpltxt "::"
10007 (condition-case nil
10008 (org-make-org-heading-search-string txt)
10009 (error "")))
10010 desc (or name
10011 (nth 4 (ignore-errors (org-heading-components)))
10012 "NONE")))))
10013 (when (string-match "::\\'" cpltxt)
10014 (setq cpltxt (substring cpltxt 0 -2)))
10015 (setq link cpltxt)))))
10017 ((buffer-file-name (buffer-base-buffer))
10018 ;; Just link to this file here.
10019 (setq cpltxt (concat "file:"
10020 (abbreviate-file-name
10021 (buffer-file-name (buffer-base-buffer)))))
10022 ;; Add a context string.
10023 (when (org-xor org-context-in-file-links
10024 (equal arg '(4)))
10025 (setq txt (if (org-region-active-p)
10026 (buffer-substring (region-beginning) (region-end))
10027 (buffer-substring (point-at-bol) (point-at-eol))))
10028 ;; Only use search option if there is some text.
10029 (when (string-match "\\S-" txt)
10030 (setq cpltxt
10031 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10032 desc "NONE")))
10033 (setq link cpltxt))
10035 ((called-interactively-p 'interactive)
10036 (user-error "No method for storing a link from this buffer"))
10038 (t (setq link nil)))
10040 ;; We're done setting link and desc, clean up
10041 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10042 (setq link (or link cpltxt)
10043 desc (or desc cpltxt))
10044 (cond ((not desc))
10045 ((equal desc "NONE") (setq desc nil))
10046 (t (setq desc
10047 (replace-regexp-in-string
10048 org-bracket-link-analytic-regexp
10049 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10050 desc))))
10051 ;; Return the link
10052 (if (not (and (or (called-interactively-p 'any)
10053 executing-kbd-macro)
10054 link))
10055 (or agenda-link (and link (org-make-link-string link desc)))
10056 (push (list link desc) org-stored-links)
10057 (message "Stored: %s" (or desc link))
10058 (when custom-id
10059 (setq link (concat "file:" (abbreviate-file-name
10060 (buffer-file-name)) "::#" custom-id))
10061 (push (list link desc) org-stored-links))
10062 (car org-stored-links)))))
10064 (defun org-store-link-props (&rest plist)
10065 "Store link properties, extract names, addresses and dates."
10066 (let ((x (plist-get plist :from)))
10067 (when x
10068 (let ((adr (mail-extract-address-components x)))
10069 (setq plist (plist-put plist :fromname (car adr)))
10070 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10071 (let ((x (plist-get plist :to)))
10072 (when x
10073 (let ((adr (mail-extract-address-components x)))
10074 (setq plist (plist-put plist :toname (car adr)))
10075 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10076 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10077 (when x
10078 (setq plist (plist-put plist :date-timestamp
10079 (format-time-string
10080 (org-time-stamp-format t) x)))
10081 (setq plist (plist-put plist :date-timestamp-inactive
10082 (format-time-string
10083 (org-time-stamp-format t t) x)))))
10084 (let ((from (plist-get plist :from))
10085 (to (plist-get plist :to)))
10086 (when (and from to org-from-is-user-regexp)
10087 (setq plist
10088 (plist-put plist :fromto
10089 (if (string-match org-from-is-user-regexp from)
10090 (concat "to %t")
10091 (concat "from %f"))))))
10092 (setq org-store-link-plist plist))
10094 (defun org-add-link-props (&rest plist)
10095 "Add these properties to the link property list."
10096 (let (key value)
10097 (while plist
10098 (setq key (pop plist) value (pop plist))
10099 (setq org-store-link-plist
10100 (plist-put org-store-link-plist key value)))))
10102 (defun org-email-link-description (&optional fmt)
10103 "Return the description part of an email link.
10104 This takes information from `org-store-link-plist' and formats it
10105 according to FMT (default from `org-email-link-description-format')."
10106 (setq fmt (or fmt org-email-link-description-format))
10107 (let* ((p org-store-link-plist)
10108 (to (plist-get p :toaddress))
10109 (from (plist-get p :fromaddress))
10110 (table
10111 (list
10112 (cons "%c" (plist-get p :fromto))
10113 (cons "%F" (plist-get p :from))
10114 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10115 (cons "%T" (plist-get p :to))
10116 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10117 (cons "%s" (plist-get p :subject))
10118 (cons "%d" (plist-get p :date))
10119 (cons "%m" (plist-get p :message-id)))))
10120 (when (string-match "%c" fmt)
10121 ;; Check if the user wrote this message
10122 (if (and org-from-is-user-regexp from to
10123 (save-match-data (string-match org-from-is-user-regexp from)))
10124 (setq fmt (replace-match "to %t" t t fmt))
10125 (setq fmt (replace-match "from %f" t t fmt))))
10126 (org-replace-escapes fmt table)))
10128 (defun org-make-org-heading-search-string (&optional string)
10129 "Make search string for the current headline or STRING."
10130 (let ((s (or string
10131 (and (derived-mode-p 'org-mode)
10132 (save-excursion
10133 (org-back-to-heading t)
10134 (org-element-property :raw-value (org-element-at-point))))))
10135 (lines org-context-in-file-links))
10136 (or string (setq s (concat "*" s))) ; Add * for headlines
10137 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10138 (when (and string (integerp lines) (> lines 0))
10139 (let ((slines (org-split-string s "\n")))
10140 (when (< lines (length slines))
10141 (setq s (mapconcat
10142 'identity
10143 (reverse (nthcdr (- (length slines) lines)
10144 (reverse slines))) "\n")))))
10145 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10147 (defun org-make-link-string (link &optional description)
10148 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10149 (unless (org-string-nw-p link) (error "Empty link"))
10150 (let ((uri (cond ((string-match org-link-types-re link)
10151 (concat (match-string 1 link)
10152 (org-link-escape (substring link (match-end 1)))))
10153 ;; For readability, url-encode internal links only
10154 ;; when absolutely needed (i.e, when they contain
10155 ;; square brackets). File links however, are
10156 ;; encoded since, e.g., spaces are significant.
10157 ((or (file-name-absolute-p link)
10158 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10159 (org-link-escape link))
10160 (t link)))
10161 (description
10162 (and (org-string-nw-p description)
10163 ;; Remove brackets from description, as they are fatal.
10164 (replace-regexp-in-string
10165 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10166 (org-trim description)))))
10167 (format "[[%s]%s]"
10169 (if description (format "[%s]" description) ""))))
10171 (defconst org-link-escape-chars
10172 ;;%20 %5B %5D %25
10173 '(?\s ?\[ ?\] ?%)
10174 "List of characters that should be escaped in a link when stored to Org.
10175 This is the list that is used for internal purposes.")
10177 (defun org-link-escape (text &optional table merge)
10178 "Return percent escaped representation of TEXT.
10179 TEXT is a string with the text to escape.
10180 Optional argument TABLE is a list with characters that should be
10181 escaped. When nil, `org-link-escape-chars' is used.
10182 If optional argument MERGE is set, merge TABLE into
10183 `org-link-escape-chars'."
10184 (let ((characters-to-encode
10185 (cond ((null table) org-link-escape-chars)
10186 (merge (append org-link-escape-chars table))
10187 (t table))))
10188 (mapconcat
10189 (lambda (c)
10190 (if (or (memq c characters-to-encode)
10191 (and org-url-hexify-p (or (< c 32) (> c 126))))
10192 (mapconcat (lambda (e) (format "%%%.2X" e))
10193 (or (encode-coding-char c 'utf-8)
10194 (error "Unable to percent escape character: %c" c))
10196 (char-to-string c)))
10197 text "")))
10199 (defun org-link-unescape (str)
10200 "Unhex hexified Unicode parts in string STR.
10201 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10202 reciprocal of `org-link-escape', which see."
10203 (if (org-string-nw-p str)
10204 (replace-regexp-in-string
10205 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10206 str))
10208 (defun org-link-unescape-compound (hex)
10209 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10210 Note: this function also decodes single byte encodings like
10211 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10212 (save-match-data
10213 (let* ((bytes (cdr (split-string hex "%")))
10214 (ret "")
10215 (eat 0)
10216 (sum 0))
10217 (while bytes
10218 (let* ((val (string-to-number (pop bytes) 16))
10219 (shift-xor
10220 (if (= 0 eat)
10221 (cond
10222 ((>= val 252) (cons 6 252))
10223 ((>= val 248) (cons 5 248))
10224 ((>= val 240) (cons 4 240))
10225 ((>= val 224) (cons 3 224))
10226 ((>= val 192) (cons 2 192))
10227 (t (cons 0 0)))
10228 (cons 6 128))))
10229 (when (>= val 192) (setq eat (car shift-xor)))
10230 (setq val (logxor val (cdr shift-xor)))
10231 (setq sum (+ (lsh sum (car shift-xor)) val))
10232 (when (> eat 0) (setq eat (- eat 1)))
10233 (cond
10234 ((= 0 eat) ;multi byte
10235 (setq ret (concat ret (char-to-string sum)))
10236 (setq sum 0))
10237 ((not bytes) ; single byte(s)
10238 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10239 ret)))
10241 (defun org-link-unescape-single-byte-sequence (hex)
10242 "Unhexify hex-encoded single byte character sequences."
10243 (mapconcat (lambda (byte)
10244 (char-to-string (string-to-number byte 16)))
10245 (cdr (split-string hex "%")) ""))
10247 (defun org-xor (a b)
10248 "Exclusive or."
10249 (if a (not b) b))
10251 (defun org-fixup-message-id-for-http (s)
10252 "Replace special characters in a message id, so it can be used in an http query."
10253 (when (string-match "%" s)
10254 (setq s (mapconcat (lambda (c)
10255 (if (eq c ?%)
10256 "%25"
10257 (char-to-string c)))
10258 s "")))
10259 (while (string-match "<" s)
10260 (setq s (replace-match "%3C" t t s)))
10261 (while (string-match ">" s)
10262 (setq s (replace-match "%3E" t t s)))
10263 (while (string-match "@" s)
10264 (setq s (replace-match "%40" t t s)))
10267 (defun org-link-prettify (link)
10268 "Return a human-readable representation of LINK.
10269 The car of LINK must be a raw link.
10270 The cdr of LINK must be either a link description or nil."
10271 (let ((desc (or (cadr link) "<no description>")))
10272 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10273 "<" (car link) ">")))
10275 ;;;###autoload
10276 (defun org-insert-link-global ()
10277 "Insert a link like Org mode does.
10278 This command can be called in any mode to insert a link in Org syntax."
10279 (interactive)
10280 (org-load-modules-maybe)
10281 (org-run-like-in-org-mode 'org-insert-link))
10283 (defun org-insert-all-links (arg &optional pre post)
10284 "Insert all links in `org-stored-links'.
10285 When a universal prefix, do not delete the links from `org-stored-links'.
10286 When `ARG' is a number, insert the last N link(s).
10287 `PRE' and `POST' are optional arguments to define a string to
10288 prepend or to append."
10289 (interactive "P")
10290 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10291 (links (copy-sequence org-stored-links))
10292 (pr (or pre "- "))
10293 (po (or post "\n"))
10294 (cnt 1) l)
10295 (if (null org-stored-links)
10296 (message "No link to insert")
10297 (while (and (or (listp arg) (>= arg cnt))
10298 (setq l (if (listp arg)
10299 (pop links)
10300 (pop org-stored-links))))
10301 (setq cnt (1+ cnt))
10302 (insert pr)
10303 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10304 (insert po)))))
10306 (defun org-insert-last-stored-link (arg)
10307 "Insert the last link stored in `org-stored-links'."
10308 (interactive "p")
10309 (org-insert-all-links arg "" "\n"))
10311 (defun org-link-fontify-links-to-this-file ()
10312 "Fontify links to the current file in `org-stored-links'."
10313 (let ((f (buffer-file-name)) a b)
10314 (setq a (mapcar (lambda(l)
10315 (let ((ll (car l)))
10316 (when (and (string-match "^file:\\(.+\\)::" ll)
10317 (equal f (expand-file-name (match-string 1 ll))))
10318 ll)))
10319 org-stored-links))
10320 (when (featurep 'org-id)
10321 (setq b (mapcar (lambda(l)
10322 (let ((ll (car l)))
10323 (when (and (string-match "^id:\\(.+\\)$" ll)
10324 (equal f (expand-file-name
10325 (or (org-id-find-id-file
10326 (match-string 1 ll)) ""))))
10327 ll)))
10328 org-stored-links)))
10329 (mapcar (lambda(l)
10330 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10331 (delq nil (append a b)))))
10333 (defvar org--links-history nil)
10334 (defun org-insert-link (&optional complete-file link-location default-description)
10335 "Insert a link. At the prompt, enter the link.
10337 Completion can be used to insert any of the link protocol prefixes in use.
10339 The history can be used to select a link previously stored with
10340 `org-store-link'. When the empty string is entered (i.e. if you just
10341 press `RET' at the prompt), the link defaults to the most recently
10342 stored link. As `SPC' triggers completion in the minibuffer, you need to
10343 use `M-SPC' or `C-q SPC' to force the insertion of a space character.
10345 You will also be prompted for a description, and if one is given, it will
10346 be displayed in the buffer instead of the link.
10348 If there is already a link at point, this command will allow you to edit
10349 link and description parts.
10351 With a `\\[universal-argument]' prefix, prompts for a file to link to. The \
10352 file name can be
10353 selected using completion. The path to the file will be relative to the
10354 current directory if the file is in the current directory or a subdirectory.
10355 Otherwise, the link will be the absolute path as completed in the minibuffer
10356 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10357 option `org-link-file-path-type'.
10359 With a `\\[universal-argument] \\[universal-argument]' prefix, enforce an \
10360 absolute path even if the file is in
10361 the current directory or below.
10363 A `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
10364 prefix negates `org-keep-stored-link-after-insertion'.
10366 If `org-make-link-description-function' is non-nil, this function will be
10367 called with the link target, and the result will be the default
10368 link description.
10370 If the LINK-LOCATION parameter is non-nil, this value will be used as
10371 the link location instead of reading one interactively.
10373 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will be used
10374 as the default description."
10375 (interactive "P")
10376 (let* ((wcf (current-window-configuration))
10377 (origbuf (current-buffer))
10378 (region (when (org-region-active-p)
10379 (buffer-substring (region-beginning) (region-end))))
10380 (remove (and region (list (region-beginning) (region-end))))
10381 (desc region)
10382 (link link-location)
10383 (abbrevs org-link-abbrev-alist-local)
10384 entry all-prefixes auto-desc)
10385 (cond
10386 (link-location) ; specified by arg, just use it.
10387 ((org-in-regexp org-bracket-link-regexp 1)
10388 ;; We do have a link at point, and we are going to edit it.
10389 (setq remove (list (match-beginning 0) (match-end 0)))
10390 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10391 (setq link (read-string "Link: "
10392 (org-link-unescape
10393 (match-string-no-properties 1)))))
10394 ((or (org-in-regexp org-angle-link-re)
10395 (org-in-regexp org-plain-link-re))
10396 ;; Convert to bracket link
10397 (setq remove (list (match-beginning 0) (match-end 0))
10398 link (read-string "Link: "
10399 (org-unbracket-string "<" ">" (match-string 0)))))
10400 ((member complete-file '((4) (16)))
10401 ;; Completing read for file names.
10402 (setq link (org-file-complete-link complete-file)))
10404 ;; Read link, with completion for stored links.
10405 (org-link-fontify-links-to-this-file)
10406 (org-switch-to-buffer-other-window "*Org Links*")
10407 (with-current-buffer "*Org Links*"
10408 (erase-buffer)
10409 (insert "Insert a link.
10410 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10411 (when org-stored-links
10412 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10413 (insert (mapconcat 'org-link-prettify
10414 (reverse org-stored-links) "\n")))
10415 (goto-char (point-min)))
10416 (let ((cw (selected-window)))
10417 (select-window (get-buffer-window "*Org Links*" 'visible))
10418 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10419 (unless (pos-visible-in-window-p (point-max))
10420 (org-fit-window-to-buffer))
10421 (and (window-live-p cw) (select-window cw)))
10422 (setq all-prefixes (append (mapcar 'car abbrevs)
10423 (mapcar 'car org-link-abbrev-alist)
10424 (org-link-types)))
10425 (unwind-protect
10426 ;; Fake a link history, containing the stored links.
10427 (let ((org--links-history
10428 (append (mapcar #'car org-stored-links)
10429 org-insert-link-history)))
10430 (setq link
10431 (org-completing-read
10432 "Link: "
10433 (append
10434 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10435 (mapcar #'car org-stored-links))
10436 nil nil nil
10437 'org--links-history
10438 (caar org-stored-links)))
10439 (unless (org-string-nw-p link) (user-error "No link selected"))
10440 (dolist (l org-stored-links)
10441 (when (equal link (cadr l))
10442 (setq link (car l))
10443 (setq auto-desc t)))
10444 (when (or (member link all-prefixes)
10445 (and (equal ":" (substring link -1))
10446 (member (substring link 0 -1) all-prefixes)
10447 (setq link (substring link 0 -1))))
10448 (setq link (with-current-buffer origbuf
10449 (org-link-try-special-completion link)))))
10450 (set-window-configuration wcf)
10451 (kill-buffer "*Org Links*"))
10452 (setq entry (assoc link org-stored-links))
10453 (or entry (push link org-insert-link-history))
10454 (setq desc (or desc (nth 1 entry)))))
10456 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10457 (not org-keep-stored-link-after-insertion))
10458 (setq org-stored-links (delq (assoc link org-stored-links)
10459 org-stored-links)))
10461 (when (and (string-match org-plain-link-re link)
10462 (not (string-match org-ts-regexp link)))
10463 ;; URL-like link, normalize the use of angular brackets.
10464 (setq link (org-unbracket-string "<" ">" link)))
10466 ;; Check if we are linking to the current file with a search
10467 ;; option If yes, simplify the link by using only the search
10468 ;; option.
10469 (when (and buffer-file-name
10470 (let ((case-fold-search nil))
10471 (string-match "\\`file:\\(.+?\\)::" link)))
10472 (let ((path (match-string-no-properties 1 link))
10473 (search (substring-no-properties link (match-end 0))))
10474 (save-match-data
10475 (when (equal (file-truename buffer-file-name) (file-truename path))
10476 ;; We are linking to this same file, with a search option
10477 (setq link search)))))
10479 ;; Check if we can/should use a relative path. If yes, simplify the link
10480 (let ((case-fold-search nil))
10481 (when (string-match "\\`\\(file\\|docview\\):" link)
10482 (let* ((type (match-string-no-properties 0 link))
10483 (path (substring-no-properties link (match-end 0)))
10484 (origpath path))
10485 (cond
10486 ((or (eq org-link-file-path-type 'absolute)
10487 (equal complete-file '(16)))
10488 (setq path (abbreviate-file-name (expand-file-name path))))
10489 ((eq org-link-file-path-type 'noabbrev)
10490 (setq path (expand-file-name path)))
10491 ((eq org-link-file-path-type 'relative)
10492 (setq path (file-relative-name path)))
10494 (save-match-data
10495 (if (string-match (concat "^" (regexp-quote
10496 (expand-file-name
10497 (file-name-as-directory
10498 default-directory))))
10499 (expand-file-name path))
10500 ;; We are linking a file with relative path name.
10501 (setq path (substring (expand-file-name path)
10502 (match-end 0)))
10503 (setq path (abbreviate-file-name (expand-file-name path)))))))
10504 (setq link (concat type path))
10505 (when (equal desc origpath)
10506 (setq desc path)))))
10508 (if org-make-link-description-function
10509 (setq desc
10510 (or (condition-case nil
10511 (funcall org-make-link-description-function link desc)
10512 (error (progn (message "Can't get link description from `%s'"
10513 (symbol-name org-make-link-description-function))
10514 (sit-for 2) nil)))
10515 (read-string "Description: " default-description)))
10516 (if default-description (setq desc default-description)
10517 (setq desc (or (and auto-desc desc)
10518 (read-string "Description: " desc)))))
10520 (unless (string-match "\\S-" desc) (setq desc nil))
10521 (when remove (apply 'delete-region remove))
10522 (insert (org-make-link-string link desc))
10523 ;; Redisplay so as the new link has proper invisible characters.
10524 (sit-for 0)))
10526 (defun org-link-try-special-completion (type)
10527 "If there is completion support for link type TYPE, offer it."
10528 (let ((fun (org-link-get-parameter type :complete)))
10529 (if (functionp fun)
10530 (funcall fun)
10531 (read-string "Link (no completion support): " (concat type ":")))))
10533 (defun org-file-complete-link (&optional arg)
10534 "Create a file link using completion."
10535 (let ((file (read-file-name "File: "))
10536 (pwd (file-name-as-directory (expand-file-name ".")))
10537 (pwd1 (file-name-as-directory (abbreviate-file-name
10538 (expand-file-name ".")))))
10539 (cond ((equal arg '(16))
10540 (concat "file:"
10541 (abbreviate-file-name (expand-file-name file))))
10542 ((string-match
10543 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10544 (concat "file:" (match-string 1 file)))
10545 ((string-match
10546 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10547 (expand-file-name file))
10548 (concat "file:"
10549 (match-string 1 (expand-file-name file))))
10550 (t (concat "file:" file)))))
10552 (defun org-completing-read (&rest args)
10553 "Completing-read with SPACE being a normal character."
10554 (let ((enable-recursive-minibuffers t)
10555 (minibuffer-local-completion-map
10556 (copy-keymap minibuffer-local-completion-map)))
10557 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10558 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10559 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10560 'org-time-stamp-inactive)
10561 (apply #'completing-read args)))
10563 ;;; Opening/following a link
10565 (defvar org-link-search-failed nil)
10567 (defvar org-open-link-functions nil
10568 "Hook for functions finding a plain text link.
10569 These functions must take a single argument, the link content.
10570 They will be called for links that look like [[link text][description]]
10571 when LINK TEXT does not have a protocol like \"http:\" and does not look
10572 like a filename (e.g. \"./blue.png\").
10574 These functions will be called *before* Org attempts to resolve the
10575 link by doing text searches in the current buffer - so if you want a
10576 link \"[[target]]\" to still find \"<<target>>\", your function should
10577 handle this as a special case.
10579 When the function does handle the link, it must return a non-nil value.
10580 If it decides that it is not responsible for this link, it must return
10581 nil to indicate that that Org can continue with other options like
10582 exact and fuzzy text search.")
10584 (defun org-next-link (&optional search-backward)
10585 "Move forward to the next link.
10586 If the link is in hidden text, expose it."
10587 (interactive "P")
10588 (when (and org-link-search-failed (eq this-command last-command))
10589 (goto-char (point-min))
10590 (message "Link search wrapped back to beginning of buffer"))
10591 (setq org-link-search-failed nil)
10592 (let* ((pos (point))
10593 (ct (org-context))
10594 (a (assq :link ct))
10595 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10596 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10597 ((looking-at org-any-link-re)
10598 ;; Don't stay stuck at link without an org-link face
10599 (forward-char (if search-backward -1 1))))
10600 (if (funcall srch-fun org-any-link-re nil t)
10601 (progn
10602 (goto-char (match-beginning 0))
10603 (when (outline-invisible-p) (org-show-context)))
10604 (goto-char pos)
10605 (setq org-link-search-failed t)
10606 (message "No further link found"))))
10608 (defun org-previous-link ()
10609 "Move backward to the previous link.
10610 If the link is in hidden text, expose it."
10611 (interactive)
10612 (funcall 'org-next-link t))
10614 (defun org-translate-link (s)
10615 "Translate a link string if a translation function has been defined."
10616 (with-temp-buffer
10617 (insert (org-trim s))
10618 (org-trim (org-element-interpret-data (org-element-context)))))
10620 (defun org-translate-link-from-planner (type path)
10621 "Translate a link from Emacs Planner syntax so that Org can follow it.
10622 This is still an experimental function, your mileage may vary."
10623 (cond
10624 ((member type '("http" "https" "news" "ftp"))
10625 ;; standard Internet links are the same.
10626 nil)
10627 ((and (equal type "irc") (string-match "^//" path))
10628 ;; Planner has two / at the beginning of an irc link, we have 1.
10629 ;; We should have zero, actually....
10630 (setq path (substring path 1)))
10631 ((and (equal type "lisp") (string-match "^/" path))
10632 ;; Planner has a slash, we do not.
10633 (setq type "elisp" path (substring path 1)))
10634 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10635 ;; A typical message link. Planner has the id after the final slash,
10636 ;; we separate it with a hash mark
10637 (setq path (concat (match-string 1 path) "#"
10638 (org-unbracket-string "<" ">" (match-string 2 path))))))
10639 (cons type path))
10641 (defun org-find-file-at-mouse (ev)
10642 "Open file link or URL at mouse."
10643 (interactive "e")
10644 (mouse-set-point ev)
10645 (org-open-at-point 'in-emacs))
10647 (defun org-open-at-mouse (ev)
10648 "Open file link or URL at mouse.
10649 See the docstring of `org-open-file' for details."
10650 (interactive "e")
10651 (mouse-set-point ev)
10652 (when (eq major-mode 'org-agenda-mode)
10653 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10654 (org-open-at-point))
10656 (defvar org-window-config-before-follow-link nil
10657 "The window configuration before following a link.
10658 This is saved in case the need arises to restore it.")
10660 ;;;###autoload
10661 (defun org-open-at-point-global ()
10662 "Follow a link or time-stamp like Org mode does.
10663 This command can be called in any mode to follow an external link
10664 or a time-stamp that has Org mode syntax. Its behavior is
10665 undefined when called on internal links (e.g., fuzzy links).
10666 Raise an error when there is nothing to follow. "
10667 (interactive)
10668 (cond ((org-in-regexp org-any-link-re)
10669 (org-open-link-from-string (match-string-no-properties 0)))
10670 ((or (org-in-regexp org-ts-regexp-both nil t)
10671 (org-in-regexp org-tsr-regexp-both nil t))
10672 (org-follow-timestamp-link))
10673 (t (user-error "No link found"))))
10675 ;;;###autoload
10676 (defun org-open-link-from-string (s &optional arg reference-buffer)
10677 "Open a link in the string S, as if it was in Org mode."
10678 (interactive "sLink: \nP")
10679 (let ((reference-buffer (or reference-buffer (current-buffer))))
10680 (with-temp-buffer
10681 (let ((org-inhibit-startup (not reference-buffer)))
10682 (org-mode)
10683 (insert s)
10684 (goto-char (point-min))
10685 (when reference-buffer
10686 (setq org-link-abbrev-alist-local
10687 (with-current-buffer reference-buffer
10688 org-link-abbrev-alist-local)))
10689 (org-open-at-point arg reference-buffer)))))
10691 (defvar org-open-at-point-functions nil
10692 "Hook that is run when following a link at point.
10694 Functions in this hook must return t if they identify and follow
10695 a link at point. If they don't find anything interesting at point,
10696 they must return nil.")
10698 (defvar org-link-search-inhibit-query nil)
10699 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10700 (defun org--open-doi-link (path)
10701 "Open a \"doi\" type link.
10702 PATH is a the path to search for, as a string."
10703 (browse-url (url-encode-url (concat org-doi-server-url path))))
10705 (defun org--open-elisp-link (path)
10706 "Open a \"elisp\" type link.
10707 PATH is the sexp to evaluate, as a string."
10708 (let ((cmd path))
10709 (if (or (and (org-string-nw-p
10710 org-confirm-elisp-link-not-regexp)
10711 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10712 (not org-confirm-elisp-link-function)
10713 (funcall org-confirm-elisp-link-function
10714 (format "Execute \"%s\" as elisp? "
10715 (org-add-props cmd nil 'face 'org-warning))))
10716 (message "%s => %s" cmd
10717 (if (eq (string-to-char cmd) ?\()
10718 (eval (read cmd))
10719 (call-interactively (read cmd))))
10720 (user-error "Abort"))))
10722 (defun org--open-help-link (path)
10723 "Open a \"help\" type link.
10724 PATH is a symbol name, as a string."
10725 (pcase (intern path)
10726 ((and (pred fboundp) variable) (describe-function variable))
10727 ((and (pred boundp) function) (describe-variable function))
10728 (name (user-error "Unknown function or variable: %s" name))))
10730 (defun org--open-shell-link (path)
10731 "Open a \"shell\" type link.
10732 PATH is the command to execute, as a string."
10733 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10734 (cmd path))
10735 (if (or (and (org-string-nw-p
10736 org-confirm-shell-link-not-regexp)
10737 (string-match
10738 org-confirm-shell-link-not-regexp cmd))
10739 (not org-confirm-shell-link-function)
10740 (funcall org-confirm-shell-link-function
10741 (format "Execute \"%s\" in shell? "
10742 (org-add-props cmd nil
10743 'face 'org-warning))))
10744 (progn
10745 (message "Executing %s" cmd)
10746 (shell-command cmd buf)
10747 (when (featurep 'midnight)
10748 (setq clean-buffer-list-kill-buffer-names
10749 (cons (buffer-name buf)
10750 clean-buffer-list-kill-buffer-names))))
10751 (user-error "Abort"))))
10753 (defun org-open-at-point (&optional arg reference-buffer)
10754 "Open link, timestamp, footnote or tags at point.
10756 When point is on a link, follow it. Normally, files will be
10757 opened by an appropriate application. If the optional prefix
10758 argument ARG is non-nil, Emacs will visit the file. With
10759 a double prefix argument, try to open outside of Emacs, in the
10760 application the system uses for this file type.
10762 When point is on a timestamp, open the agenda at the day
10763 specified.
10765 When point is a footnote definition, move to the first reference
10766 found. If it is on a reference, move to the associated
10767 definition.
10769 When point is on a headline, display a list of every link in the
10770 entry, so it is possible to pick one, or all, of them. If point
10771 is on a tag, call `org-tags-view' instead.
10773 When optional argument REFERENCE-BUFFER is non-nil, it should
10774 specify a buffer from where the link search should happen. This
10775 is used internally by `org-open-link-from-string'.
10777 On top of syntactically correct links, this function will open
10778 the link at point in comments or comment blocks and the first
10779 link in a property drawer line."
10780 (interactive "P")
10781 ;; On a code block, open block's results.
10782 (unless (call-interactively 'org-babel-open-src-block-result)
10783 (org-load-modules-maybe)
10784 (setq org-window-config-before-follow-link (current-window-configuration))
10785 (org-remove-occur-highlights nil nil t)
10786 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10787 (let* ((context
10788 ;; Only consider supported types, even if they are not
10789 ;; the closest one.
10790 (org-element-lineage
10791 (org-element-context)
10792 '(clock comment comment-block footnote-definition
10793 footnote-reference headline inlinetask keyword link
10794 node-property timestamp)
10796 (type (org-element-type context))
10797 (value (org-element-property :value context)))
10798 (cond
10799 ((not context) (user-error "No link found"))
10800 ;; Exception: open timestamps and links in properties
10801 ;; drawers, keywords and comments.
10802 ((memq type '(comment comment-block keyword node-property))
10803 (call-interactively #'org-open-at-point-global))
10804 ;; On a headline or an inlinetask, but not on a timestamp,
10805 ;; a link, a footnote reference or on tags.
10806 ((and (memq type '(headline inlinetask))
10807 ;; Not on tags.
10808 (let ((case-fold-search nil))
10809 (save-excursion
10810 (beginning-of-line)
10811 (looking-at org-complex-heading-regexp))
10812 (or (not (match-beginning 5))
10813 (< (point) (match-beginning 5)))))
10814 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10815 (links (car data))
10816 (links-end (cdr data)))
10817 (if links
10818 (dolist (link (if (stringp links) (list links) links))
10819 (search-forward link nil links-end)
10820 (goto-char (match-beginning 0))
10821 (org-open-at-point))
10822 (require 'org-attach)
10823 (org-attach-reveal 'if-exists))))
10824 ;; On a clock line, make sure point is on the timestamp
10825 ;; before opening it.
10826 ((and (eq type 'clock)
10827 value
10828 (>= (point) (org-element-property :begin value))
10829 (<= (point) (org-element-property :end value)))
10830 (org-follow-timestamp-link))
10831 ;; Do nothing on white spaces after an object.
10832 ((>= (point)
10833 (save-excursion
10834 (goto-char (org-element-property :end context))
10835 (skip-chars-backward " \t")
10836 (point)))
10837 (user-error "No link found"))
10838 ((eq type 'timestamp) (org-follow-timestamp-link))
10839 ;; On tags within a headline or an inlinetask.
10840 ((and (memq type '(headline inlinetask))
10841 (let ((case-fold-search nil))
10842 (save-excursion (beginning-of-line)
10843 (looking-at org-complex-heading-regexp))
10844 (and (match-beginning 5)
10845 (>= (point) (match-beginning 5)))))
10846 (org-tags-view arg (substring (match-string 5) 0 -1)))
10847 ((eq type 'link)
10848 ;; When link is located within the description of another
10849 ;; link (e.g., an inline image), always open the parent
10850 ;; link.
10851 (let* ((link (let ((up (org-element-property :parent context)))
10852 (if (eq (org-element-type up) 'link) up context)))
10853 (type (org-element-property :type link))
10854 (path (org-link-unescape (org-element-property :path link))))
10855 ;; Switch back to REFERENCE-BUFFER needed when called in
10856 ;; a temporary buffer through `org-open-link-from-string'.
10857 (with-current-buffer (or reference-buffer (current-buffer))
10858 (cond
10859 ((equal type "file")
10860 (if (string-match "[*?{]" (file-name-nondirectory path))
10861 (dired path)
10862 ;; Look into `org-link-parameters' in order to find
10863 ;; a DEDICATED-FUNCTION to open file. The function
10864 ;; will be applied on raw link instead of parsed
10865 ;; link due to the limitation in `org-add-link-type'
10866 ;; ("open" function called with a single argument).
10867 ;; If no such function is found, fallback to
10868 ;; `org-open-file'.
10869 (let* ((option (org-element-property :search-option link))
10870 (app (org-element-property :application link))
10871 (dedicated-function
10872 (org-link-get-parameter
10873 (if app (concat type "+" app) type)
10874 :follow)))
10875 (if dedicated-function
10876 (funcall dedicated-function
10877 (concat path
10878 (and option (concat "::" option))))
10879 (apply #'org-open-file
10880 path
10881 (cond (arg)
10882 ((equal app "emacs") 'emacs)
10883 ((equal app "sys") 'system))
10884 (cond ((not option) nil)
10885 ((string-match-p "\\`[0-9]+\\'" option)
10886 (list (string-to-number option)))
10887 (t (list nil
10888 (org-link-unescape option)))))))))
10889 ((functionp (org-link-get-parameter type :follow))
10890 (funcall (org-link-get-parameter type :follow) path))
10891 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10892 (unless (run-hook-with-args-until-success
10893 'org-open-link-functions path)
10894 (if (not arg) (org-mark-ring-push)
10895 (switch-to-buffer-other-window
10896 (org-get-buffer-for-internal-link (current-buffer))))
10897 (let ((destination
10898 (org-with-wide-buffer
10899 (if (equal type "radio")
10900 (org-search-radio-target
10901 (org-element-property :path link))
10902 (org-link-search
10903 (if (member type '("custom-id" "coderef"))
10904 (org-element-property :raw-link link)
10905 path)
10906 ;; Prevent fuzzy links from matching
10907 ;; themselves.
10908 (and (equal type "fuzzy")
10909 (+ 2 (org-element-property :begin link)))))
10910 (point))))
10911 (unless (and (<= (point-min) destination)
10912 (>= (point-max) destination))
10913 (widen))
10914 (goto-char destination))))
10915 (t (browse-url-at-point))))))
10916 ;; On a footnote reference or at a footnote definition's label.
10917 ((or (eq type 'footnote-reference)
10918 (and (eq type 'footnote-definition)
10919 (save-excursion
10920 ;; Do not validate action when point is on the
10921 ;; spaces right after the footnote label, in
10922 ;; order to be on par with behaviour on links.
10923 (skip-chars-forward " \t")
10924 (let ((begin
10925 (org-element-property :contents-begin context)))
10926 (if begin (< (point) begin)
10927 (= (org-element-property :post-affiliated context)
10928 (line-beginning-position)))))))
10929 (org-footnote-action))
10930 (t (user-error "No link found")))))
10931 (run-hook-with-args 'org-follow-link-hook)))
10933 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10934 "Offer links in the current entry and return the selected link.
10935 If there is only one link, return it.
10936 If NTH is an integer, return the NTH link found.
10937 If ZERO is a string, check also this string for a link, and if
10938 there is one, return it."
10939 (with-current-buffer buffer
10940 (org-with-wide-buffer
10941 (goto-char marker)
10942 (let ((cnt ?0)
10943 have-zero end links link c)
10944 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10945 (push (match-string 0 zero) links)
10946 (setq cnt (1- cnt) have-zero t))
10947 (save-excursion
10948 (org-back-to-heading t)
10949 (setq end (save-excursion (outline-next-heading) (point)))
10950 (while (re-search-forward org-any-link-re end t)
10951 (push (match-string 0) links))
10952 (setq links (org-uniquify (reverse links))))
10953 (cond
10954 ((null links)
10955 (message "No links"))
10956 ((equal (length links) 1)
10957 (setq link (car links)))
10958 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10959 (setq link (nth (if have-zero nth (1- nth)) links)))
10960 (t ; we have to select a link
10961 (save-excursion
10962 (save-window-excursion
10963 (delete-other-windows)
10964 (with-output-to-temp-buffer "*Select Link*"
10965 (dolist (l links)
10966 (cond
10967 ((not (string-match org-bracket-link-regexp l))
10968 (princ (format "[%c] %s\n" (cl-incf cnt)
10969 (org-unbracket-string "<" ">" l))))
10970 ((match-end 3)
10971 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10972 (match-string 3 l) (match-string 1 l))))
10973 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10974 (match-string 1 l)))))))
10975 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10976 (message "Select link to open, RET to open all:")
10977 (setq c (read-char-exclusive))
10978 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10979 (when (equal c ?q) (user-error "Abort"))
10980 (if (equal c ?\C-m)
10981 (setq link links)
10982 (setq nth (- c ?0))
10983 (when have-zero (setq nth (1+ nth)))
10984 (unless (and (integerp nth) (>= (length links) nth))
10985 (user-error "Invalid link selection"))
10986 (setq link (nth (1- nth) links)))))
10987 (cons link end)))))
10989 ;; TODO: These functions are deprecated since `org-open-at-point'
10990 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10991 (defun org-open-file-with-system (path)
10992 "Open file at PATH using the system way of opening it."
10993 (org-open-file path 'system))
10994 (defun org-open-file-with-emacs (path)
10995 "Open file at PATH in Emacs."
10996 (org-open-file path 'emacs))
10999 ;;; File search
11001 (defvar org-create-file-search-functions nil
11002 "List of functions to construct the right search string for a file link.
11003 These functions are called in turn with point at the location to
11004 which the link should point.
11006 A function in the hook should first test if it would like to
11007 handle this file type, for example by checking the `major-mode'
11008 or the file extension. If it decides not to handle this file, it
11009 should just return nil to give other functions a chance. If it
11010 does handle the file, it must return the search string to be used
11011 when following the link. The search string will be part of the
11012 file link, given after a double colon, and `org-open-at-point'
11013 will automatically search for it. If special measures must be
11014 taken to make the search successful, another function should be
11015 added to the companion hook `org-execute-file-search-functions',
11016 which see.
11018 A function in this hook may also use `setq' to set the variable
11019 `description' to provide a suggestion for the descriptive text to
11020 be used for this link when it gets inserted into an Org buffer
11021 with \\[org-insert-link].")
11023 (defvar org-execute-file-search-functions nil
11024 "List of functions to execute a file search triggered by a link.
11026 Functions added to this hook must accept a single argument, the
11027 search string that was part of the file link, the part after the
11028 double colon. The function must first check if it would like to
11029 handle this search, for example by checking the `major-mode' or
11030 the file extension. If it decides not to handle this search, it
11031 should just return nil to give other functions a chance. If it
11032 does handle the search, it must return a non-nil value to keep
11033 other functions from trying.
11035 Each function can access the current prefix argument through the
11036 variable `current-prefix-arg'. Note that a single prefix is used
11037 to force opening a link in Emacs, so it may be good to only use a
11038 numeric or double prefix to guide the search function.
11040 In case this is needed, a function in this hook can also restore
11041 the window configuration before `org-open-at-point' was called using:
11043 (set-window-configuration org-window-config-before-follow-link)")
11045 (defun org-search-radio-target (target)
11046 "Search a radio target matching TARGET in current buffer.
11047 White spaces are not significant."
11048 (let ((re (format "<<<%s>>>"
11049 (mapconcat #'regexp-quote
11050 (org-split-string target "[ \t\n]+")
11051 "[ \t]+\\(?:\n[ \t]*\\)?")))
11052 (origin (point)))
11053 (goto-char (point-min))
11054 (catch :radio-match
11055 (while (re-search-forward re nil t)
11056 (backward-char)
11057 (let ((object (org-element-context)))
11058 (when (eq (org-element-type object) 'radio-target)
11059 (goto-char (org-element-property :begin object))
11060 (org-show-context 'link-search)
11061 (throw :radio-match nil))))
11062 (goto-char origin)
11063 (user-error "No match for radio target: %s" target))))
11065 (defun org-link-search (s &optional avoid-pos stealth)
11066 "Search for a search string S.
11068 If S starts with \"#\", it triggers a custom ID search.
11070 If S is enclosed within parenthesis, it initiates a coderef
11071 search.
11073 If S is surrounded by forward slashes, it is interpreted as
11074 a regular expression. In Org mode files, this will create an
11075 `org-occur' sparse tree. In ordinary files, `occur' will be used
11076 to list matches. If the current buffer is in `dired-mode', grep
11077 will be used to search in all files.
11079 When AVOID-POS is given, ignore matches near that position.
11081 When optional argument STEALTH is non-nil, do not modify
11082 visibility around point, thus ignoring `org-show-context-detail'
11083 variable.
11085 Search is case-insensitive and ignores white spaces. Return type
11086 of matched result, which is either `dedicated' or `fuzzy'."
11087 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11088 (let* ((case-fold-search t)
11089 (origin (point))
11090 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11091 (starred (eq (string-to-char normalized) ?*))
11092 (words (split-string (if starred (substring s 1) s)))
11093 (s-multi-re (mapconcat #'regexp-quote words "\\(?:[ \t\n]+\\)"))
11094 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11095 type)
11096 (cond
11097 ;; Check if there are any special search functions.
11098 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11099 ((eq (string-to-char s) ?#)
11100 ;; Look for a custom ID S if S starts with "#".
11101 (let* ((id (substring normalized 1))
11102 (match (org-find-property "CUSTOM_ID" id)))
11103 (if match (progn (goto-char match) (setf type 'dedicated))
11104 (error "No match for custom ID: %s" id))))
11105 ((string-match "\\`(\\(.*\\))\\'" normalized)
11106 ;; Look for coderef targets if S is enclosed within parenthesis.
11107 (let ((coderef (match-string-no-properties 1 normalized))
11108 (re (substring s-single-re 1 -1)))
11109 (goto-char (point-min))
11110 (catch :coderef-match
11111 (while (re-search-forward re nil t)
11112 (let ((element (org-element-at-point)))
11113 (when (and (memq (org-element-type element)
11114 '(example-block src-block))
11115 ;; Build proper regexp according to current
11116 ;; block's label format.
11117 (let ((label-fmt
11118 (regexp-quote
11119 (or (org-element-property :label-fmt element)
11120 org-coderef-label-format))))
11121 (save-excursion
11122 (beginning-of-line)
11123 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11124 (format label-fmt coderef))))))
11125 (setq type 'dedicated)
11126 (goto-char (match-beginning 1))
11127 (throw :coderef-match nil))))
11128 (goto-char origin)
11129 (error "No match for coderef: %s" coderef))))
11130 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11131 ;; Look for a regular expression.
11132 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11133 (match-string 1 s)))
11134 ;; From here, we handle fuzzy links.
11136 ;; Look for targets, only if not in a headline search.
11137 ((and (not starred)
11138 (let ((target (format "<<%s>>" s-multi-re)))
11139 (catch :target-match
11140 (goto-char (point-min))
11141 (while (re-search-forward target nil t)
11142 (backward-char)
11143 (let ((context (org-element-context)))
11144 (when (eq (org-element-type context) 'target)
11145 (setq type 'dedicated)
11146 (goto-char (org-element-property :begin context))
11147 (throw :target-match t))))
11148 nil))))
11149 ;; Look for elements named after S, only if not in a headline
11150 ;; search.
11151 ((and (not starred)
11152 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11153 (catch :name-match
11154 (goto-char (point-min))
11155 (while (re-search-forward name nil t)
11156 (let ((element (org-element-at-point)))
11157 (when (equal words
11158 (split-string
11159 (org-element-property :name element)))
11160 (setq type 'dedicated)
11161 (beginning-of-line)
11162 (throw :name-match t))))
11163 nil))))
11164 ;; Regular text search. Prefer headlines in Org mode buffers.
11165 ;; Ignore COMMENT keyword, TODO keywords, priority cookies,
11166 ;; statistics cookies and tags.
11167 ((and (derived-mode-p 'org-mode)
11168 (let ((title-re
11169 (format "%s.*\\(?:%s[ \t]\\)?.*%s"
11170 org-outline-regexp-bol
11171 org-comment-string
11172 (mapconcat #'regexp-quote words ".+")))
11173 (cookie-re "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]")
11174 (comment-re (format "\\`%s[ \t]+" org-comment-string)))
11175 (goto-char (point-min))
11176 (catch :found
11177 (while (re-search-forward title-re nil t)
11178 (when (equal words
11179 (split-string
11180 (replace-regexp-in-string
11181 cookie-re ""
11182 (replace-regexp-in-string
11183 comment-re "" (org-get-heading t t)))))
11184 (throw :found t)))
11185 nil)))
11186 (beginning-of-line)
11187 (setq type 'dedicated))
11188 ;; Offer to create non-existent headline depending on
11189 ;; `org-link-search-must-match-exact-headline'.
11190 ((and (derived-mode-p 'org-mode)
11191 (not org-link-search-inhibit-query)
11192 (eq org-link-search-must-match-exact-headline 'query-to-create)
11193 (yes-or-no-p "No match - create this as a new heading? "))
11194 (goto-char (point-max))
11195 (unless (bolp) (newline))
11196 (org-insert-heading nil t t)
11197 (insert s "\n")
11198 (beginning-of-line 0))
11199 ;; Only headlines are looked after. No need to process
11200 ;; further: throw an error.
11201 ((and (derived-mode-p 'org-mode)
11202 (or starred org-link-search-must-match-exact-headline))
11203 (goto-char origin)
11204 (error "No match for fuzzy expression: %s" normalized))
11205 ;; Regular text search.
11206 ((catch :fuzzy-match
11207 (goto-char (point-min))
11208 (while (re-search-forward s-multi-re nil t)
11209 ;; Skip match if it contains AVOID-POS or it is included in
11210 ;; a link with a description but outside the description.
11211 (unless (or (and avoid-pos
11212 (<= (match-beginning 0) avoid-pos)
11213 (> (match-end 0) avoid-pos))
11214 (and (save-match-data
11215 (org-in-regexp org-bracket-link-regexp))
11216 (match-beginning 3)
11217 (or (> (match-beginning 3) (point))
11218 (<= (match-end 3) (point)))
11219 (org-element-lineage
11220 (save-match-data (org-element-context))
11221 '(link) t)))
11222 (goto-char (match-beginning 0))
11223 (setq type 'fuzzy)
11224 (throw :fuzzy-match t)))
11225 nil))
11226 ;; All failed. Throw an error.
11227 (t (goto-char origin)
11228 (error "No match for fuzzy expression: %s" normalized)))
11229 ;; Disclose surroundings of match, if appropriate.
11230 (when (and (derived-mode-p 'org-mode) (not stealth))
11231 (org-show-context 'link-search))
11232 type))
11234 (defun org-get-buffer-for-internal-link (buffer)
11235 "Return a buffer to be used for displaying the link target of internal links."
11236 (cond
11237 ((not org-display-internal-link-with-indirect-buffer)
11238 buffer)
11239 ((string-suffix-p "(Clone)" (buffer-name buffer))
11240 (message "Buffer is already a clone, not making another one")
11241 ;; we also do not modify visibility in this case
11242 buffer)
11243 (t ; make a new indirect buffer for displaying the link
11244 (let* ((bn (buffer-name buffer))
11245 (ibn (concat bn "(Clone)"))
11246 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11247 (with-current-buffer ib (org-overview))
11248 ib))))
11250 (defun org-do-occur (regexp &optional cleanup)
11251 "Call the Emacs command `occur'.
11252 If CLEANUP is non-nil, remove the printout of the regular expression
11253 in the *Occur* buffer. This is useful if the regex is long and not useful
11254 to read."
11255 (occur regexp)
11256 (when cleanup
11257 (let ((cwin (selected-window)) win beg end)
11258 (when (setq win (get-buffer-window "*Occur*"))
11259 (select-window win))
11260 (goto-char (point-min))
11261 (when (re-search-forward "match[a-z]+" nil t)
11262 (setq beg (match-end 0))
11263 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11264 (setq end (1- (match-beginning 0)))))
11265 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11266 (goto-char (point-min))
11267 (select-window cwin))))
11269 ;;; The mark ring for links jumps
11271 (defvar org-mark-ring nil
11272 "Mark ring for positions before jumps in Org mode.")
11273 (defvar org-mark-ring-last-goto nil
11274 "Last position in the mark ring used to go back.")
11275 ;; Fill and close the ring
11276 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11277 (dotimes (_ org-mark-ring-length)
11278 (push (make-marker) org-mark-ring))
11279 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11280 org-mark-ring)
11282 (defun org-mark-ring-push (&optional pos buffer)
11283 "Put the current position or POS into the mark ring and rotate it."
11284 (interactive)
11285 (setq pos (or pos (point)))
11286 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11287 (move-marker (car org-mark-ring)
11288 (or pos (point))
11289 (or buffer (current-buffer)))
11290 (message "%s"
11291 (substitute-command-keys
11292 "Position saved to mark ring, go back with \
11293 `\\[org-mark-ring-goto]'.")))
11295 (defun org-mark-ring-goto (&optional n)
11296 "Jump to the previous position in the mark ring.
11297 With prefix arg N, jump back that many stored positions. When
11298 called several times in succession, walk through the entire ring.
11299 Org mode commands jumping to a different position in the current file,
11300 or to another Org file, automatically push the old position onto the ring."
11301 (interactive "p")
11302 (let (p m)
11303 (if (eq last-command this-command)
11304 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11305 (setq p org-mark-ring))
11306 (setq org-mark-ring-last-goto p)
11307 (setq m (car p))
11308 (pop-to-buffer-same-window (marker-buffer m))
11309 (goto-char m)
11310 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11312 (defun org-add-angle-brackets (s)
11313 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11314 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11317 ;;; Following specific links
11319 (defvar org-agenda-buffer-tmp-name)
11320 (defvar org-agenda-start-on-weekday)
11321 (defun org-follow-timestamp-link ()
11322 "Open an agenda view for the time-stamp date/range at point."
11323 (cond
11324 ((org-at-date-range-p t)
11325 (let ((org-agenda-start-on-weekday)
11326 (t1 (match-string 1))
11327 (t2 (match-string 2)) tt1 tt2)
11328 (setq tt1 (time-to-days (org-time-string-to-time t1))
11329 tt2 (time-to-days (org-time-string-to-time t2)))
11330 (let ((org-agenda-buffer-tmp-name
11331 (format "*Org Agenda(a:%s)"
11332 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11333 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11334 ((org-at-timestamp-p t)
11335 (let ((org-agenda-buffer-tmp-name
11336 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11337 (org-agenda-list nil (time-to-days (org-time-string-to-time
11338 (substring (match-string 1) 0 10)))
11339 1)))
11340 (t (error "This should not happen"))))
11343 ;;; Following file links
11344 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11345 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11346 (declare-function mailcap-mime-info
11347 "mailcap" (string &optional request no-decode))
11348 (defvar org-wait nil)
11349 (defun org-open-file (path &optional in-emacs line search)
11350 "Open the file at PATH.
11351 First, this expands any special file name abbreviations. Then the
11352 configuration variable `org-file-apps' is checked if it contains an
11353 entry for this file type, and if yes, the corresponding command is launched.
11355 If no application is found, Emacs simply visits the file.
11357 With optional prefix argument IN-EMACS, Emacs will visit the file.
11358 With a double \\[universal-argument] \\[universal-argument] \
11359 prefix arg, Org tries to avoid opening in Emacs
11360 and to use an external application to visit the file.
11362 Optional LINE specifies a line to go to, optional SEARCH a string
11363 to search for. If LINE or SEARCH is given, the file will be
11364 opened in Emacs, unless an entry from org-file-apps that makes
11365 use of groups in a regexp matches.
11367 If you want to change the way frames are used when following a
11368 link, please customize `org-link-frame-setup'.
11370 If the file does not exist, an error is thrown."
11371 (let* ((file (if (equal path "")
11372 buffer-file-name
11373 (substitute-in-file-name (expand-file-name path))))
11374 (file-apps (append org-file-apps (org-default-apps)))
11375 (apps (cl-remove-if
11376 'org-file-apps-entry-match-against-dlink-p file-apps))
11377 (apps-dlink (cl-remove-if-not
11378 'org-file-apps-entry-match-against-dlink-p file-apps))
11379 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11380 (dirp (unless remp (file-directory-p file)))
11381 (file (if (and dirp org-open-directory-means-index-dot-org)
11382 (concat (file-name-as-directory file) "index.org")
11383 file))
11384 (a-m-a-p (assq 'auto-mode apps))
11385 (dfile (downcase file))
11386 ;; Reconstruct the original link from the PATH, LINE and
11387 ;; SEARCH args.
11388 (link (cond (line (concat file "::" (number-to-string line)))
11389 (search (concat file "::" search))
11390 (t file)))
11391 (dlink (downcase link))
11392 (old-buffer (current-buffer))
11393 (old-pos (point))
11394 (old-mode major-mode)
11395 (ext
11396 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11397 (match-string 1 dfile)))
11398 cmd link-match-data)
11399 (cond
11400 ((member in-emacs '((16) system))
11401 (setq cmd (cdr (assq 'system apps))))
11402 (in-emacs (setq cmd 'emacs))
11404 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11405 (and dirp (cdr (assq 'directory apps)))
11406 ;; First, try matching against apps-dlink if we
11407 ;; get a match here, store the match data for
11408 ;; later.
11409 (let ((match (assoc-default dlink apps-dlink
11410 'string-match)))
11411 (if match
11412 (progn (setq link-match-data (match-data))
11413 match)
11414 (progn (setq in-emacs (or in-emacs line search))
11415 nil))) ; if we have no match in apps-dlink,
11416 ; always open the file in emacs if line or search
11417 ; is given (for backwards compatibility)
11418 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11419 'string-match)
11420 (cdr (assoc ext apps))
11421 (cdr (assq t apps))))))
11422 (when (eq cmd 'system)
11423 (setq cmd (cdr (assq 'system apps))))
11424 (when (eq cmd 'default)
11425 (setq cmd (cdr (assoc t apps))))
11426 (when (eq cmd 'mailcap)
11427 (require 'mailcap)
11428 (mailcap-parse-mailcaps)
11429 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11430 (command (mailcap-mime-info mime-type)))
11431 (if (stringp command)
11432 (setq cmd command)
11433 (setq cmd 'emacs))))
11434 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11435 (not (file-exists-p file))
11436 (not org-open-non-existing-files))
11437 (user-error "No such file: %s" file))
11438 (cond
11439 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11440 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11441 (while (string-match "['\"]%s['\"]" cmd)
11442 (setq cmd (replace-match "%s" t t cmd)))
11443 (setq cmd (replace-regexp-in-string
11444 "%s"
11445 (shell-quote-argument (convert-standard-filename file))
11447 nil t))
11449 ;; Replace "%1", "%2" etc. in command with group matches from regex
11450 (save-match-data
11451 (let ((match-index 1)
11452 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11453 (set-match-data link-match-data)
11454 (while (<= match-index number-of-groups)
11455 (let ((regex (concat "%" (number-to-string match-index)))
11456 (replace-with (match-string match-index dlink)))
11457 (while (string-match regex cmd)
11458 (setq cmd (replace-match replace-with t t cmd))))
11459 (setq match-index (+ match-index 1)))))
11461 (save-window-excursion
11462 (message "Running %s...done" cmd)
11463 (start-process-shell-command cmd nil cmd)
11464 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11465 ((or (stringp cmd)
11466 (eq cmd 'emacs))
11467 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11468 (widen)
11469 (cond (line (org-goto-line line)
11470 (when (derived-mode-p 'org-mode) (org-reveal)))
11471 (search (org-link-search search))))
11472 ((functionp cmd)
11473 (save-match-data
11474 (set-match-data link-match-data)
11475 (condition-case nil
11476 (funcall cmd file link)
11477 ;; FIXME: Remove this check when most default installations
11478 ;; of Emacs have at least Org 9.0.
11479 ((debug wrong-number-of-arguments wrong-type-argument
11480 invalid-function)
11481 (user-error "Please see Org News for version 9.0 about \
11482 `org-file-apps'--Lisp error: %S" cmd)))))
11483 ((consp cmd)
11484 ;; FIXME: Remove this check when most default installations of
11485 ;; Emacs have at least Org 9.0.
11486 ;; Heads-up instead of silently fall back to
11487 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11488 ;; with sexp instead of a function for `cmd'.
11489 (user-error "Please see Org News for version 9.0 about \
11490 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11491 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11492 (and (derived-mode-p 'org-mode)
11493 (eq old-mode 'org-mode)
11494 (or (not (eq old-buffer (current-buffer)))
11495 (not (eq old-pos (point))))
11496 (org-mark-ring-push old-pos old-buffer))))
11498 (defun org-file-apps-entry-match-against-dlink-p (entry)
11499 "This function returns non-nil if `entry' uses a regular
11500 expression which should be matched against the whole link by
11501 org-open-file.
11503 It assumes that is the case when the entry uses a regular
11504 expression which has at least one grouping construct and the
11505 action is either a lisp form or a command string containing
11506 `%1', i.e. using at least one subexpression match as a
11507 parameter."
11508 (let ((selector (car entry))
11509 (action (cdr entry)))
11510 (if (stringp selector)
11511 (and (> (regexp-opt-depth selector) 0)
11512 (or (and (stringp action)
11513 (string-match "%[0-9]" action))
11514 (consp action)))
11515 nil)))
11517 (defun org-default-apps ()
11518 "Return the default applications for this operating system."
11519 (cond
11520 ((eq system-type 'darwin)
11521 org-file-apps-defaults-macosx)
11522 ((eq system-type 'windows-nt)
11523 org-file-apps-defaults-windowsnt)
11524 (t org-file-apps-defaults-gnu)))
11526 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11527 "Convert extensions to regular expressions in the cars of LIST.
11528 Also, weed out any non-string entries, because the return value is used
11529 only for regexp matching.
11530 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11531 point to the symbol `emacs', indicating that the file should
11532 be opened in Emacs."
11533 (append
11534 (delq nil
11535 (mapcar (lambda (x)
11536 (unless (not (stringp (car x)))
11537 (if (string-match "\\W" (car x))
11539 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11540 list))
11541 (when add-auto-mode
11542 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11544 (defvar ange-ftp-name-format)
11545 (defun org-file-remote-p (file)
11546 "Test whether FILE specifies a location on a remote system.
11547 Return non-nil if the location is indeed remote.
11549 For example, the filename \"/user@host:/foo\" specifies a location
11550 on the system \"/user@host:\"."
11551 (cond ((fboundp 'file-remote-p)
11552 (file-remote-p file))
11553 ((fboundp 'tramp-handle-file-remote-p)
11554 (tramp-handle-file-remote-p file))
11555 ((and (boundp 'ange-ftp-name-format)
11556 (string-match (car ange-ftp-name-format) file))
11557 t)))
11560 ;;;; Refiling
11562 (defun org-get-org-file ()
11563 "Read a filename, with default directory `org-directory'."
11564 (let ((default (or org-default-notes-file remember-data-file)))
11565 (read-file-name (format "File name [%s]: " default)
11566 (file-name-as-directory org-directory)
11567 default)))
11569 (defun org-notes-order-reversed-p ()
11570 "Check if the current file should receive notes in reversed order."
11571 (cond
11572 ((not org-reverse-note-order) nil)
11573 ((eq t org-reverse-note-order) t)
11574 ((not (listp org-reverse-note-order)) nil)
11575 (t (catch 'exit
11576 (dolist (entry org-reverse-note-order)
11577 (when (string-match (car entry) buffer-file-name)
11578 (throw 'exit (cdr entry))))))))
11580 (defvar org-refile-target-table nil
11581 "The list of refile targets, created by `org-refile'.")
11583 (defvar org-agenda-new-buffers nil
11584 "Buffers created to visit agenda files.")
11586 (defvar org-refile-cache nil
11587 "Cache for refile targets.")
11589 (defvar org-refile-markers nil
11590 "All the markers used for caching refile locations.")
11592 (defun org-refile-marker (pos)
11593 "Get a new refile marker, but only if caching is in use."
11594 (if (not org-refile-use-cache)
11596 (let ((m (make-marker)))
11597 (move-marker m pos)
11598 (push m org-refile-markers)
11599 m)))
11601 (defun org-refile-cache-clear ()
11602 "Clear the refile cache and disable all the markers."
11603 (dolist (m org-refile-markers) (move-marker m nil))
11604 (setq org-refile-markers nil)
11605 (setq org-refile-cache nil)
11606 (message "Refile cache has been cleared"))
11608 (defun org-refile-cache-check-set (set)
11609 "Check if all the markers in the cache still have live buffers."
11610 (let (marker)
11611 (catch 'exit
11612 (while (and set (setq marker (nth 3 (pop set))))
11613 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11614 (when (and marker (null (marker-buffer marker)))
11615 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11616 (sit-for 3)
11617 (throw 'exit nil)))
11618 t)))
11620 (defun org-refile-cache-put (set &rest identifiers)
11621 "Push the refile targets SET into the cache, under IDENTIFIERS."
11622 (let* ((key (sha1 (prin1-to-string identifiers)))
11623 (entry (assoc key org-refile-cache)))
11624 (if entry
11625 (setcdr entry set)
11626 (push (cons key set) org-refile-cache))))
11628 (defun org-refile-cache-get (&rest identifiers)
11629 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11630 (cond
11631 ((not org-refile-cache) nil)
11632 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11634 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11635 org-refile-cache))))
11636 (and set (org-refile-cache-check-set set) set)))))
11638 (defvar org-outline-path-cache nil
11639 "Alist between buffer positions and outline paths.
11640 It value is an alist (POSITION . PATH) where POSITION is the
11641 buffer position at the beginning of an entry and PATH is a list
11642 of strings describing the outline path for that entry, in reverse
11643 order.")
11645 (defun org-refile-get-targets (&optional default-buffer)
11646 "Produce a table with refile targets."
11647 (let ((case-fold-search nil)
11648 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11649 (entries (or org-refile-targets '((nil . (:level . 1)))))
11650 targets tgs files desc descre)
11651 (message "Getting targets...")
11652 (with-current-buffer (or default-buffer (current-buffer))
11653 (dolist (entry entries)
11654 (setq files (car entry) desc (cdr entry))
11655 (cond
11656 ((null files) (setq files (list (current-buffer))))
11657 ((eq files 'org-agenda-files)
11658 (setq files (org-agenda-files 'unrestricted)))
11659 ((and (symbolp files) (fboundp files))
11660 (setq files (funcall files)))
11661 ((and (symbolp files) (boundp files))
11662 (setq files (symbol-value files))))
11663 (when (stringp files) (setq files (list files)))
11664 (cond
11665 ((eq (car desc) :tag)
11666 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11667 ((eq (car desc) :todo)
11668 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11669 ((eq (car desc) :regexp)
11670 (setq descre (cdr desc)))
11671 ((eq (car desc) :level)
11672 (setq descre (concat "^\\*\\{" (number-to-string
11673 (if org-odd-levels-only
11674 (1- (* 2 (cdr desc)))
11675 (cdr desc)))
11676 "\\}[ \t]")))
11677 ((eq (car desc) :maxlevel)
11678 (setq descre (concat "^\\*\\{1," (number-to-string
11679 (if org-odd-levels-only
11680 (1- (* 2 (cdr desc)))
11681 (cdr desc)))
11682 "\\}[ \t]")))
11683 (t (error "Bad refiling target description %s" desc)))
11684 (dolist (f files)
11685 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11687 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11688 (progn
11689 (when (bufferp f)
11690 (setq f (buffer-file-name (buffer-base-buffer f))))
11691 (setq f (and f (expand-file-name f)))
11692 (when (eq org-refile-use-outline-path 'file)
11693 (push (list (file-name-nondirectory f) f nil nil) tgs))
11694 (org-with-wide-buffer
11695 (goto-char (point-min))
11696 (setq org-outline-path-cache nil)
11697 (while (re-search-forward descre nil t)
11698 (beginning-of-line)
11699 (let ((case-fold-search nil))
11700 (looking-at org-complex-heading-regexp))
11701 (let ((begin (point))
11702 (heading (match-string-no-properties 4)))
11703 (unless (or (and
11704 org-refile-target-verify-function
11705 (not
11706 (funcall org-refile-target-verify-function)))
11707 (not heading))
11708 (let ((re (format org-complex-heading-regexp-format
11709 (regexp-quote heading)))
11710 (target
11711 (if (not org-refile-use-outline-path) heading
11712 (mapconcat
11713 #'org-protect-slash
11714 (append
11715 (pcase org-refile-use-outline-path
11716 (`file (list (file-name-nondirectory
11717 (buffer-file-name
11718 (buffer-base-buffer)))))
11719 (`full-file-path
11720 (list (buffer-file-name
11721 (buffer-base-buffer))))
11722 (_ nil))
11723 (org-get-outline-path t t))
11724 "/"))))
11725 (push (list target f re (org-refile-marker (point)))
11726 tgs)))
11727 (when (= (point) begin)
11728 ;; Verification function has not moved point.
11729 (end-of-line)))))))
11730 (when org-refile-use-cache
11731 (org-refile-cache-put tgs (buffer-file-name) descre))
11732 (setq targets (append tgs targets))))))
11733 (message "Getting targets...done")
11734 (delete-dups (nreverse targets))))
11736 (defun org-protect-slash (s)
11737 (replace-regexp-in-string "/" "\\/" s nil t))
11739 (defun org--get-outline-path-1 (&optional use-cache)
11740 "Return outline path to current headline.
11742 Outline path is a list of strings, in reverse order. When
11743 optional argument USE-CACHE is non-nil, make use of a cache. See
11744 `org-get-outline-path' for details.
11746 Assume buffer is widened and point is on a headline."
11747 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11748 (let ((p (point))
11749 (heading (let ((case-fold-search nil))
11750 (looking-at org-complex-heading-regexp)
11751 (if (not (match-end 4)) ""
11752 ;; Remove statistics cookies.
11753 (org-trim
11754 (org-link-display-format
11755 (replace-regexp-in-string
11756 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11757 (match-string-no-properties 4))))))))
11758 (if (org-up-heading-safe)
11759 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11760 (when use-cache
11761 (push (cons p path) org-outline-path-cache))
11762 path)
11763 ;; This is a new root node. Since we assume we are moving
11764 ;; forward, we can drop previous cache so as to limit number
11765 ;; of associations there.
11766 (let ((path (list heading)))
11767 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11768 path)))))
11770 (defun org-get-outline-path (&optional with-self use-cache)
11771 "Return the outline path to the current entry.
11773 An outline path is a list of ancestors for current headline, as
11774 a list of strings. Statistics cookies are removed and links are
11775 replaced with their description, if any, or their path otherwise.
11777 When optional argument WITH-SELF is non-nil, the path also
11778 includes the current headline.
11780 When optional argument USE-CACHE is non-nil, cache outline paths
11781 between calls to this function so as to avoid backtracking. This
11782 argument is useful when planning to find more than one outline
11783 path in the same document. In that case, there are two
11784 conditions to satisfy:
11785 - `org-outline-path-cache' is set to nil before starting the
11786 process;
11787 - outline paths are computed by increasing buffer positions."
11788 (org-with-wide-buffer
11789 (and (or (and with-self (org-back-to-heading t))
11790 (org-up-heading-safe))
11791 (reverse (org--get-outline-path-1 use-cache)))))
11793 (defun org-format-outline-path (path &optional width prefix separator)
11794 "Format the outline path PATH for display.
11795 WIDTH is the maximum number of characters that is available.
11796 PREFIX is a prefix to be included in the returned string,
11797 such as the file name.
11798 SEPARATOR is inserted between the different parts of the path,
11799 the default is \"/\"."
11800 (setq width (or width 79))
11801 (setq path (delq nil path))
11802 (unless (> width 0)
11803 (user-error "Argument `width' must be positive"))
11804 (setq separator (or separator "/"))
11805 (let* ((org-odd-levels-only nil)
11806 (fpath (concat
11807 prefix (and prefix path separator)
11808 (mapconcat
11809 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11810 (cl-loop for head in path
11811 for n from 0
11812 collect (org-add-props
11813 head nil 'face
11814 (nth (% n org-n-level-faces) org-level-faces)))
11815 separator))))
11816 (when (> (length fpath) width)
11817 (if (< width 7)
11818 ;; It's unlikely that `width' will be this small, but don't
11819 ;; waste characters by adding ".." if it is.
11820 (setq fpath (substring fpath 0 width))
11821 (setf (substring fpath (- width 2)) "..")))
11822 fpath))
11824 (defun org-display-outline-path (&optional file current separator just-return-string)
11825 "Display the current outline path in the echo area.
11827 If FILE is non-nil, prepend the output with the file name.
11828 If CURRENT is non-nil, append the current heading to the output.
11829 SEPARATOR is passed through to `org-format-outline-path'. It separates
11830 the different parts of the path and defaults to \"/\".
11831 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11832 (interactive "P")
11833 (let* (case-fold-search
11834 (bfn (buffer-file-name (buffer-base-buffer)))
11835 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11836 res)
11837 (when current (setq path (append path
11838 (save-excursion
11839 (org-back-to-heading t)
11840 (when (looking-at org-complex-heading-regexp)
11841 (list (match-string 4)))))))
11842 (setq res
11843 (org-format-outline-path
11844 path
11845 (1- (frame-width))
11846 (and file bfn (concat (file-name-nondirectory bfn) separator))
11847 separator))
11848 (if just-return-string
11849 (org-no-properties res)
11850 (org-unlogged-message "%s" res))))
11852 (defvar org-refile-history nil
11853 "History for refiling operations.")
11855 (defvar org-after-refile-insert-hook nil
11856 "Hook run after `org-refile' has inserted its stuff at the new location.
11857 Note that this is still *before* the stuff will be removed from
11858 the *old* location.")
11860 (defvar org-capture-last-stored-marker)
11861 (defvar org-refile-keep nil
11862 "Non-nil means `org-refile' will copy instead of refile.")
11864 (defun org-copy ()
11865 "Like `org-refile', but copy."
11866 (interactive)
11867 (let ((org-refile-keep t))
11868 (funcall 'org-refile nil nil nil "Copy")))
11870 (defun org-refile (&optional arg default-buffer rfloc msg)
11871 "Move the entry or entries at point to another heading.
11873 The list of target headings is compiled using the information in
11874 `org-refile-targets', which see.
11876 At the target location, the entry is filed as a subitem of the
11877 target heading. Depending on `org-reverse-note-order', the new
11878 subitem will either be the first or the last subitem.
11880 If there is an active region, all entries in that region will be
11881 refiled. However, the region must fulfill the requirement that
11882 the first heading sets the top-level of the moved text.
11884 With a `\\[universal-argument]' ARG, the command will only visit the target \
11885 location
11886 and not actually move anything.
11888 With a prefix `\\[universal-argument] \\[universal-argument]', go to the \
11889 location where the last
11890 refiling operation has put the subtree.
11892 With a numeric prefix argument of `2', refile to the running clock.
11894 With a numeric prefix argument of `3', emulate `org-refile-keep'
11895 being set to t and copy to the target location, don't move it.
11896 Beware that keeping refiled entries may result in duplicated ID
11897 properties.
11899 RFLOC can be a refile location obtained in a different way.
11901 MSG is a string to replace \"Refile\" in the default prompt with
11902 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11904 See also `org-refile-use-outline-path'.
11906 If you are using target caching (see `org-refile-use-cache'), you
11907 have to clear the target cache in order to find new targets.
11908 This can be done with a `0' prefix (`C-0 C-c C-w') or a triple
11909 prefix argument (`C-u C-u C-u C-c C-w')."
11910 (interactive "P")
11911 (if (member arg '(0 (64)))
11912 (org-refile-cache-clear)
11913 (let* ((actionmsg (cond (msg msg)
11914 ((equal arg 3) "Refile (and keep)")
11915 (t "Refile")))
11916 (regionp (org-region-active-p))
11917 (region-start (and regionp (region-beginning)))
11918 (region-end (and regionp (region-end)))
11919 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11920 pos it nbuf file level reversed)
11921 (setq last-command nil)
11922 (when regionp
11923 (goto-char region-start)
11924 (or (bolp) (goto-char (point-at-bol)))
11925 (setq region-start (point))
11926 (unless (or (org-kill-is-subtree-p
11927 (buffer-substring region-start region-end))
11928 (prog1 org-refile-active-region-within-subtree
11929 (let ((s (point-at-eol)))
11930 (org-toggle-heading)
11931 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11932 (user-error "The region is not a (sequence of) subtree(s)")))
11933 (if (equal arg '(16))
11934 (org-refile-goto-last-stored)
11935 (when (or
11936 (and (equal arg 2)
11937 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11938 (prog1
11939 (setq it (list (or org-clock-heading "running clock")
11940 (buffer-file-name
11941 (marker-buffer org-clock-hd-marker))
11943 (marker-position org-clock-hd-marker)))
11944 (setq arg nil)))
11945 (setq it
11946 (or rfloc
11947 (let (heading-text)
11948 (save-excursion
11949 (unless (and arg (listp arg))
11950 (org-back-to-heading t)
11951 (setq heading-text
11952 (replace-regexp-in-string
11953 org-bracket-link-regexp
11954 "\\3"
11955 (or (nth 4 (org-heading-components))
11956 ""))))
11957 (org-refile-get-location
11958 (cond ((and arg (listp arg)) "Goto")
11959 (regionp (concat actionmsg " region to"))
11960 (t (concat actionmsg " subtree \""
11961 heading-text "\" to")))
11962 default-buffer
11963 (and (not (equal '(4) arg))
11964 org-refile-allow-creating-parent-nodes)))))))
11965 (setq file (nth 1 it)
11966 pos (nth 3 it))
11967 (when (and (not arg)
11969 (equal (buffer-file-name) file)
11970 (if regionp
11971 (and (>= pos region-start)
11972 (<= pos region-end))
11973 (and (>= pos (point))
11974 (< pos (save-excursion
11975 (org-end-of-subtree t t))))))
11976 (error "Cannot refile to position inside the tree or region"))
11977 (setq nbuf (or (find-buffer-visiting file)
11978 (find-file-noselect file)))
11979 (if (and arg (not (equal arg 3)))
11980 (progn
11981 (pop-to-buffer-same-window nbuf)
11982 (goto-char pos)
11983 (org-show-context 'org-goto))
11984 (if regionp
11985 (progn
11986 (org-kill-new (buffer-substring region-start region-end))
11987 (org-save-markers-in-region region-start region-end))
11988 (org-copy-subtree 1 nil t))
11989 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11990 (find-file-noselect file)))
11991 (setq reversed (org-notes-order-reversed-p))
11992 (org-with-wide-buffer
11993 (if pos
11994 (progn
11995 (goto-char pos)
11996 (looking-at org-outline-regexp)
11997 (setq level (org-get-valid-level (funcall outline-level) 1))
11998 (goto-char
11999 (if reversed
12000 (or (outline-next-heading) (point-max))
12001 (or (save-excursion (org-get-next-sibling))
12002 (org-end-of-subtree t t)
12003 (point-max)))))
12004 (setq level 1)
12005 (if (not reversed)
12006 (goto-char (point-max))
12007 (goto-char (point-min))
12008 (or (outline-next-heading) (goto-char (point-max)))))
12009 (unless (bolp) (newline))
12010 (org-paste-subtree level nil nil t)
12011 (when org-log-refile
12012 (org-add-log-setup 'refile nil nil org-log-refile)
12013 (unless (eq org-log-refile 'note)
12014 (save-excursion (org-add-log-note))))
12015 (and org-auto-align-tags
12016 (let ((org-loop-over-headlines-in-active-region nil))
12017 (org-set-tags nil t)))
12018 (let ((bookmark-name (plist-get org-bookmark-names-plist
12019 :last-refile)))
12020 (when bookmark-name
12021 (with-demoted-errors
12022 (bookmark-set bookmark-name))))
12023 ;; If we are refiling for capture, make sure that the
12024 ;; last-capture pointers point here
12025 (when (bound-and-true-p org-capture-is-refiling)
12026 (let ((bookmark-name (plist-get org-bookmark-names-plist
12027 :last-capture-marker)))
12028 (when bookmark-name
12029 (with-demoted-errors
12030 (bookmark-set bookmark-name))))
12031 (move-marker org-capture-last-stored-marker (point)))
12032 (when (fboundp 'deactivate-mark) (deactivate-mark))
12033 (run-hooks 'org-after-refile-insert-hook)))
12034 (unless org-refile-keep
12035 (if regionp
12036 (delete-region (point) (+ (point) (- region-end region-start)))
12037 (delete-region
12038 (and (org-back-to-heading t) (point))
12039 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12040 (when (featurep 'org-inlinetask)
12041 (org-inlinetask-remove-END-maybe))
12042 (setq org-markers-to-move nil)
12043 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12045 (defun org-refile-goto-last-stored ()
12046 "Go to the location where the last refile was stored."
12047 (interactive)
12048 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12049 (message "This is the location of the last refile"))
12051 (defun org-refile--get-location (refloc tbl)
12052 "When user refile to REFLOC, find the associated target in TBL.
12053 Also check `org-refile-target-table'."
12054 (car (delq
12056 (mapcar
12057 (lambda (r) (or (assoc r tbl)
12058 (assoc r org-refile-target-table)))
12059 (list (replace-regexp-in-string "/$" "" refloc)
12060 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12062 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12063 "Prompt the user for a refile location, using PROMPT.
12064 PROMPT should not be suffixed with a colon and a space, because
12065 this function appends the default value from
12066 `org-refile-history' automatically, if that is not empty."
12067 (let ((org-refile-targets org-refile-targets)
12068 (org-refile-use-outline-path org-refile-use-outline-path))
12069 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12070 (unless org-refile-target-table
12071 (user-error "No refile targets"))
12072 (let* ((cbuf (current-buffer))
12073 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12074 (cfunc (if (and org-refile-use-outline-path
12075 org-outline-path-complete-in-steps)
12076 #'org-olpath-completing-read
12077 #'completing-read))
12078 (extra (if org-refile-use-outline-path "/" ""))
12079 (cbnex (concat (buffer-name) extra))
12080 (filename (and cfn (expand-file-name cfn)))
12081 (tbl (mapcar
12082 (lambda (x)
12083 (if (and (not (member org-refile-use-outline-path
12084 '(file full-file-path)))
12085 (not (equal filename (nth 1 x))))
12086 (cons (concat (car x) extra " ("
12087 (file-name-nondirectory (nth 1 x)) ")")
12088 (cdr x))
12089 (cons (concat (car x) extra) (cdr x))))
12090 org-refile-target-table))
12091 (completion-ignore-case t)
12092 cdef
12093 (prompt (concat prompt
12094 (or (and (car org-refile-history)
12095 (concat " (default " (car org-refile-history) ")"))
12096 (and (assoc cbnex tbl) (setq cdef cbnex)
12097 (concat " (default " cbnex ")"))) ": "))
12098 pa answ parent-target child parent old-hist)
12099 (setq old-hist org-refile-history)
12100 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12101 nil 'org-refile-history (or cdef (car org-refile-history))))
12102 (if (setq pa (org-refile--get-location answ tbl))
12103 (progn
12104 (org-refile-check-position pa)
12105 (when (or (not org-refile-history)
12106 (not (eq old-hist org-refile-history))
12107 (not (equal (car pa) (car org-refile-history))))
12108 (setq org-refile-history
12109 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12110 org-refile-history
12111 (cdr org-refile-history))))
12112 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12113 (pop org-refile-history)))
12115 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12116 (progn
12117 (setq parent (match-string 1 answ)
12118 child (match-string 2 answ))
12119 (setq parent-target (org-refile--get-location parent tbl))
12120 (when (and parent-target
12121 (or (eq new-nodes t)
12122 (and (eq new-nodes 'confirm)
12123 (y-or-n-p (format "Create new node \"%s\"? "
12124 child)))))
12125 (org-refile-new-child parent-target child)))
12126 (user-error "Invalid target location")))))
12128 (declare-function org-string-nw-p "org-macs" (s))
12129 (defun org-refile-check-position (refile-pointer)
12130 "Check if the refile pointer matches the headline to which it points."
12131 (let* ((file (nth 1 refile-pointer))
12132 (re (nth 2 refile-pointer))
12133 (pos (nth 3 refile-pointer))
12134 buffer)
12135 (if (and (not (markerp pos)) (not file))
12136 (user-error "Please indicate a target file in the refile path")
12137 (when (org-string-nw-p re)
12138 (setq buffer (if (markerp pos)
12139 (marker-buffer pos)
12140 (or (find-buffer-visiting file)
12141 (find-file-noselect file))))
12142 (with-current-buffer buffer
12143 (org-with-wide-buffer
12144 (goto-char pos)
12145 (beginning-of-line 1)
12146 (unless (looking-at-p re)
12147 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling"))))))))
12149 (defun org-refile-new-child (parent-target child)
12150 "Use refile target PARENT-TARGET to add new CHILD below it."
12151 (unless parent-target
12152 (error "Cannot find parent for new node"))
12153 (let ((file (nth 1 parent-target))
12154 (pos (nth 3 parent-target))
12155 level)
12156 (with-current-buffer (or (find-buffer-visiting file)
12157 (find-file-noselect file))
12158 (org-with-wide-buffer
12159 (if pos
12160 (goto-char pos)
12161 (goto-char (point-max))
12162 (unless (bolp) (newline)))
12163 (when (looking-at org-outline-regexp)
12164 (setq level (funcall outline-level))
12165 (org-end-of-subtree t t))
12166 (org-back-over-empty-lines)
12167 (insert "\n" (make-string
12168 (if pos (org-get-valid-level level 1) 1) ?*)
12169 " " child "\n")
12170 (beginning-of-line 0)
12171 (list (concat (car parent-target) "/" child) file "" (point))))))
12173 (defun org-olpath-completing-read (prompt collection &rest args)
12174 "Read an outline path like a file name."
12175 (let ((thetable collection))
12176 (apply #'completing-read
12177 prompt
12178 (lambda (string predicate &optional flag)
12179 (cond
12180 ((eq flag nil) (try-completion string thetable))
12181 ((eq flag t)
12182 (let ((l (length string)))
12183 (mapcar (lambda (x)
12184 (let ((r (substring x l))
12185 (f (if (string-match " ([^)]*)$" x)
12186 (match-string 0 x)
12187 "")))
12188 (if (string-match "/" r)
12189 (concat string (substring r 0 (match-end 0)) f)
12190 x)))
12191 (all-completions string thetable predicate))))
12192 ;; Exact match?
12193 ((eq flag 'lambda) (assoc string thetable))))
12194 args)))
12196 ;;;; Dynamic blocks
12198 (defun org-find-dblock (name)
12199 "Find the first dynamic block with name NAME in the buffer.
12200 If not found, stay at current position and return nil."
12201 (let ((case-fold-search t) pos)
12202 (save-excursion
12203 (goto-char (point-min))
12204 (setq pos (and (re-search-forward
12205 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12206 (match-beginning 0))))
12207 (when pos (goto-char pos))
12208 pos))
12210 (defun org-create-dblock (plist)
12211 "Create a dynamic block section, with parameters taken from PLIST.
12212 PLIST must contain a :name entry which is used as the name of the block."
12213 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12214 (end-of-line 1)
12215 (newline))
12216 (let ((col (current-column))
12217 (name (plist-get plist :name)))
12218 (insert "#+BEGIN: " name)
12219 (while plist
12220 (if (eq (car plist) :name)
12221 (setq plist (cddr plist))
12222 (insert " " (prin1-to-string (pop plist)))))
12223 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12224 (beginning-of-line -2)))
12226 (defun org-prepare-dblock ()
12227 "Prepare dynamic block for refresh.
12228 This empties the block, puts the cursor at the insert position and returns
12229 the property list including an extra property :name with the block name."
12230 (unless (looking-at org-dblock-start-re)
12231 (user-error "Not at a dynamic block"))
12232 (let* ((begdel (1+ (match-end 0)))
12233 (name (org-no-properties (match-string 1)))
12234 (params (append (list :name name)
12235 (read (concat "(" (match-string 3) ")")))))
12236 (save-excursion
12237 (beginning-of-line 1)
12238 (skip-chars-forward " \t")
12239 (setq params (plist-put params :indentation-column (current-column))))
12240 (unless (re-search-forward org-dblock-end-re nil t)
12241 (error "Dynamic block not terminated"))
12242 (setq params
12243 (append params
12244 (list :content (buffer-substring
12245 begdel (match-beginning 0)))))
12246 (delete-region begdel (match-beginning 0))
12247 (goto-char begdel)
12248 (open-line 1)
12249 params))
12251 (defun org-map-dblocks (&optional command)
12252 "Apply COMMAND to all dynamic blocks in the current buffer.
12253 If COMMAND is not given, use `org-update-dblock'."
12254 (let ((cmd (or command 'org-update-dblock)))
12255 (save-excursion
12256 (goto-char (point-min))
12257 (while (re-search-forward org-dblock-start-re nil t)
12258 (goto-char (match-beginning 0))
12259 (save-excursion
12260 (condition-case nil
12261 (funcall cmd)
12262 (error (message "Error during update of dynamic block"))))
12263 (unless (re-search-forward org-dblock-end-re nil t)
12264 (error "Dynamic block not terminated"))))))
12266 (defun org-dblock-update (&optional arg)
12267 "User command for updating dynamic blocks.
12268 Update the dynamic block at point. With prefix ARG, update all dynamic
12269 blocks in the buffer."
12270 (interactive "P")
12271 (if arg
12272 (org-update-all-dblocks)
12273 (or (looking-at org-dblock-start-re)
12274 (org-beginning-of-dblock))
12275 (org-update-dblock)))
12277 (defun org-update-dblock ()
12278 "Update the dynamic block at point.
12279 This means to empty the block, parse for parameters and then call
12280 the correct writing function."
12281 (interactive)
12282 (save-excursion
12283 (let* ((win (selected-window))
12284 (pos (point))
12285 (line (org-current-line))
12286 (params (org-prepare-dblock))
12287 (name (plist-get params :name))
12288 (indent (plist-get params :indentation-column))
12289 (cmd (intern (concat "org-dblock-write:" name))))
12290 (message "Updating dynamic block `%s' at line %d..." name line)
12291 (funcall cmd params)
12292 (message "Updating dynamic block `%s' at line %d...done" name line)
12293 (goto-char pos)
12294 (when (and indent (> indent 0))
12295 (setq indent (make-string indent ?\ ))
12296 (save-excursion
12297 (select-window win)
12298 (org-beginning-of-dblock)
12299 (forward-line 1)
12300 (while (not (looking-at org-dblock-end-re))
12301 (insert indent)
12302 (beginning-of-line 2))
12303 (when (looking-at org-dblock-end-re)
12304 (and (looking-at "[ \t]+")
12305 (replace-match ""))
12306 (insert indent)))))))
12308 (defun org-beginning-of-dblock ()
12309 "Find the beginning of the dynamic block at point.
12310 Error if there is no such block at point."
12311 (let ((pos (point))
12312 beg)
12313 (end-of-line 1)
12314 (if (and (re-search-backward org-dblock-start-re nil t)
12315 (setq beg (match-beginning 0))
12316 (re-search-forward org-dblock-end-re nil t)
12317 (> (match-end 0) pos))
12318 (goto-char beg)
12319 (goto-char pos)
12320 (error "Not in a dynamic block"))))
12322 (defun org-update-all-dblocks ()
12323 "Update all dynamic blocks in the buffer.
12324 This function can be used in a hook."
12325 (interactive)
12326 (when (derived-mode-p 'org-mode)
12327 (org-map-dblocks 'org-update-dblock)))
12330 ;;;; Completion
12332 (declare-function org-export-backend-options "ox" (cl-x) t)
12333 (defun org-get-export-keywords ()
12334 "Return a list of all currently understood export keywords.
12335 Export keywords include options, block names, attributes and
12336 keywords relative to each registered export back-end."
12337 (let (keywords)
12338 (dolist (backend
12339 (bound-and-true-p org-export-registered-backends)
12340 (delq nil keywords))
12341 ;; Back-end name (for keywords, like #+LATEX:)
12342 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12343 (dolist (option-entry (org-export-backend-options backend))
12344 ;; Back-end options.
12345 (push (nth 1 option-entry) keywords)))))
12347 (defconst org-options-keywords
12348 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12349 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12350 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12351 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12352 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12354 (defcustom org-structure-template-alist
12355 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12356 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12357 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12358 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12359 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12360 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12361 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12362 ("L" "#+LaTeX: ")
12363 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12364 ("H" "#+HTML: ")
12365 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12366 ("A" "#+ASCII: ")
12367 ("i" "#+INDEX: ?")
12368 ("I" "#+INCLUDE: %file ?"))
12369 "Structure completion elements.
12370 This is a list of abbreviation keys and values. The value gets inserted
12371 if you type `<' followed by the key and then press the completion key,
12372 usually `TAB'. %file will be replaced by a file name after prompting
12373 for the file using completion. The cursor will be placed at the position
12374 of the `?' in the template.
12375 There are two templates for each key, the first uses the original Org syntax,
12376 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12377 the default when the /org-mtags.el/ module has been loaded. See also the
12378 variable `org-mtags-prefer-muse-templates'."
12379 :group 'org-completion
12380 :type '(repeat
12381 (list
12382 (string :tag "Key")
12383 (string :tag "Template")))
12384 :version "26.1"
12385 :package-version '(Org . "8.3"))
12387 (defun org-try-structure-completion ()
12388 "Try to complete a structure template before point.
12389 This looks for strings like \"<e\" on an otherwise empty line and
12390 expands them."
12391 (let ((l (buffer-substring (point-at-bol) (point)))
12393 (when (and (looking-at "[ \t]*$")
12394 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12395 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12396 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12397 (match-beginning 1)) a)
12398 t)))
12400 (defun org-complete-expand-structure-template (start cell)
12401 "Expand a structure template."
12402 (let ((rpl (nth 1 cell))
12403 (ind ""))
12404 (delete-region start (point))
12405 (when (string-match "\\`[ \t]*#\\+" rpl)
12406 (cond
12407 ((bolp))
12408 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12409 (setq ind (buffer-substring (point-at-bol) (point))))
12410 (t (newline))))
12411 (setq start (point))
12412 (when (string-match "%file" rpl)
12413 (setq rpl (replace-match
12414 (concat
12415 "\""
12416 (save-match-data
12417 (abbreviate-file-name (read-file-name "Include file: ")))
12418 "\"")
12419 t t rpl)))
12420 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12421 (concat "\n" ind)))
12422 (insert rpl)
12423 (when (re-search-backward "\\?" start t) (delete-char 1))))
12425 ;;;; TODO, DEADLINE, Comments
12427 (defun org-toggle-comment ()
12428 "Change the COMMENT state of an entry."
12429 (interactive)
12430 (save-excursion
12431 (org-back-to-heading)
12432 (let ((case-fold-search nil))
12433 (looking-at org-complex-heading-regexp))
12434 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12435 (skip-chars-forward " \t")
12436 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12437 (if (org-in-commented-heading-p t)
12438 (delete-region (point)
12439 (progn (search-forward " " (line-end-position) 'move)
12440 (skip-chars-forward " \t")
12441 (point)))
12442 (insert org-comment-string)
12443 (unless (eolp) (insert " ")))))
12445 (defvar org-last-todo-state-is-todo nil
12446 "This is non-nil when the last TODO state change led to a TODO state.
12447 If the last change removed the TODO tag or switched to DONE, then
12448 this is nil.")
12450 (defvar org-setting-tags nil) ; dynamically skipped
12452 (defvar org-todo-setup-filter-hook nil
12453 "Hook for functions that pre-filter todo specs.
12454 Each function takes a todo spec and returns either nil or the spec
12455 transformed into canonical form." )
12457 (defvar org-todo-get-default-hook nil
12458 "Hook for functions that get a default item for todo.
12459 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12460 nil or a string to be used for the todo mark." )
12462 (defvar org-agenda-headline-snapshot-before-repeat)
12464 (defun org-current-effective-time ()
12465 "Return current time adjusted for `org-extend-today-until' variable."
12466 (let* ((ct (org-current-time))
12467 (dct (decode-time ct))
12468 (ct1
12469 (cond
12470 (org-use-last-clock-out-time-as-effective-time
12471 (or (org-clock-get-last-clock-out-time) ct))
12472 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12473 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12474 (t ct))))
12475 ct1))
12477 (defun org-todo-yesterday (&optional arg)
12478 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12479 (interactive "P")
12480 (if (eq major-mode 'org-agenda-mode)
12481 (apply 'org-agenda-todo-yesterday arg)
12482 (let* ((org-use-effective-time t)
12483 (hour (nth 2 (decode-time (org-current-time))))
12484 (org-extend-today-until (1+ hour)))
12485 (org-todo arg))))
12487 (defvar org-block-entry-blocking ""
12488 "First entry preventing the TODO state change.")
12490 (defun org-cancel-repeater ()
12491 "Cancel a repeater by setting its numeric value to zero."
12492 (interactive)
12493 (save-excursion
12494 (org-back-to-heading t)
12495 (let ((bound1 (point))
12496 (bound0 (save-excursion (outline-next-heading) (point))))
12497 (when (and (re-search-forward
12498 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12499 org-deadline-time-regexp "\\)\\|\\("
12500 org-ts-regexp "\\)")
12501 bound0 t)
12502 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12503 bound1 t))
12504 (replace-match "0" t nil nil 1)))))
12506 (defvar org-state)
12507 (defvar org-blocked-by-checkboxes)
12508 (defun org-todo (&optional arg)
12509 "Change the TODO state of an item.
12511 The state of an item is given by a keyword at the start of the heading,
12512 like
12513 *** TODO Write paper
12514 *** DONE Call mom
12516 The different keywords are specified in the variable `org-todo-keywords'.
12517 By default the available states are \"TODO\" and \"DONE\". So, for this
12518 example: when the item starts with TODO, it is changed to DONE.
12519 When it starts with DONE, the DONE is removed. And when neither TODO nor
12520 DONE are present, add TODO at the beginning of the heading.
12522 With `\\[universal-argument]' prefix ARG, use completion to determine the new \
12523 state.
12524 With numeric prefix ARG, switch to that state.
12525 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
12526 next set of TODO \
12527 keywords (nextset).
12528 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
12529 prefix, circumvent any state blocking.
12530 With a numeric prefix arg of 0, inhibit note taking for the change.
12531 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12533 When called through ELisp, arg is also interpreted in the following way:
12534 `none' -> empty state
12535 \"\" -> switch to empty state
12536 `done' -> switch to DONE
12537 `nextset' -> switch to the next set of keywords
12538 `previousset' -> switch to the previous set of keywords
12539 \"WAITING\" -> switch to the specified keyword, but only if it
12540 really is a member of `org-todo-keywords'."
12541 (interactive "P")
12542 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12543 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12544 'region-start-level 'region))
12545 org-loop-over-headlines-in-active-region)
12546 (org-map-entries
12547 `(org-todo ,arg)
12548 org-loop-over-headlines-in-active-region
12549 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12550 (when (equal arg '(16)) (setq arg 'nextset))
12551 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12552 (let ((org-blocker-hook org-blocker-hook)
12553 commentp
12554 case-fold-search)
12555 (when (equal arg '(64))
12556 (setq arg nil org-blocker-hook nil))
12557 (when (and org-blocker-hook
12558 (or org-inhibit-blocking
12559 (org-entry-get nil "NOBLOCKING")))
12560 (setq org-blocker-hook nil))
12561 (save-excursion
12562 (catch 'exit
12563 (org-back-to-heading t)
12564 (when (org-in-commented-heading-p t)
12565 (org-toggle-comment)
12566 (setq commentp t))
12567 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12568 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12569 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12570 (let* ((match-data (match-data))
12571 (startpos (point-at-bol))
12572 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12573 (org-log-done org-log-done)
12574 (org-log-repeat org-log-repeat)
12575 (org-todo-log-states org-todo-log-states)
12576 (org-inhibit-logging
12577 (if (equal arg 0)
12578 (progn (setq arg nil) 'note) org-inhibit-logging))
12579 (this (match-string 1))
12580 (hl-pos (match-beginning 0))
12581 (head (org-get-todo-sequence-head this))
12582 (ass (assoc head org-todo-kwd-alist))
12583 (interpret (nth 1 ass))
12584 (done-word (nth 3 ass))
12585 (final-done-word (nth 4 ass))
12586 (org-last-state (or this ""))
12587 (completion-ignore-case t)
12588 (member (member this org-todo-keywords-1))
12589 (tail (cdr member))
12590 (org-state (cond
12591 ((and org-todo-key-trigger
12592 (or (and (equal arg '(4))
12593 (eq org-use-fast-todo-selection 'prefix))
12594 (and (not arg) org-use-fast-todo-selection
12595 (not (eq org-use-fast-todo-selection
12596 'prefix)))))
12597 ;; Use fast selection.
12598 (org-fast-todo-selection))
12599 ((and (equal arg '(4))
12600 (or (not org-use-fast-todo-selection)
12601 (not org-todo-key-trigger)))
12602 ;; Read a state with completion.
12603 (completing-read
12604 "State: " (mapcar #'list org-todo-keywords-1)
12605 nil t))
12606 ((eq arg 'right)
12607 (if this
12608 (if tail (car tail) nil)
12609 (car org-todo-keywords-1)))
12610 ((eq arg 'left)
12611 (unless (equal member org-todo-keywords-1)
12612 (if this
12613 (nth (- (length org-todo-keywords-1)
12614 (length tail) 2)
12615 org-todo-keywords-1)
12616 (org-last org-todo-keywords-1))))
12617 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12618 (setq arg nil))) ;hack to fall back to cycling
12619 (arg
12620 ;; User or caller requests a specific state.
12621 (cond
12622 ((equal arg "") nil)
12623 ((eq arg 'none) nil)
12624 ((eq arg 'done) (or done-word (car org-done-keywords)))
12625 ((eq arg 'nextset)
12626 (or (car (cdr (member head org-todo-heads)))
12627 (car org-todo-heads)))
12628 ((eq arg 'previousset)
12629 (let ((org-todo-heads (reverse org-todo-heads)))
12630 (or (car (cdr (member head org-todo-heads)))
12631 (car org-todo-heads))))
12632 ((car (member arg org-todo-keywords-1)))
12633 ((stringp arg)
12634 (user-error "State `%s' not valid in this file" arg))
12635 ((nth (1- (prefix-numeric-value arg))
12636 org-todo-keywords-1))))
12637 ((null member) (or head (car org-todo-keywords-1)))
12638 ((equal this final-done-word) nil) ;-> make empty
12639 ((null tail) nil) ;-> first entry
12640 ((memq interpret '(type priority))
12641 (if (eq this-command last-command)
12642 (car tail)
12643 (if (> (length tail) 0)
12644 (or done-word (car org-done-keywords))
12645 nil)))
12647 (car tail))))
12648 (org-state (or
12649 (run-hook-with-args-until-success
12650 'org-todo-get-default-hook org-state org-last-state)
12651 org-state))
12652 (next (if org-state (concat " " org-state " ") " "))
12653 (change-plist (list :type 'todo-state-change :from this :to org-state
12654 :position startpos))
12655 dolog now-done-p)
12656 (when org-blocker-hook
12657 (let (org-blocked-by-checkboxes block-reason)
12658 (setq org-last-todo-state-is-todo
12659 (not (member this org-done-keywords)))
12660 (unless (save-excursion
12661 (save-match-data
12662 (org-with-wide-buffer
12663 (run-hook-with-args-until-failure
12664 'org-blocker-hook change-plist))))
12665 (setq block-reason (if org-blocked-by-checkboxes
12666 "contained checkboxes"
12667 (format "\"%s\"" org-block-entry-blocking)))
12668 (if (called-interactively-p 'interactive)
12669 (user-error "TODO state change from %s to %s blocked (by %s)"
12670 this org-state block-reason)
12671 ;; Fail silently.
12672 (message "TODO state change from %s to %s blocked (by %s)"
12673 this org-state block-reason)
12674 (throw 'exit nil)))))
12675 (store-match-data match-data)
12676 (replace-match next t t)
12677 (cond ((equal this org-state)
12678 (message "TODO state was already %s" (org-trim next)))
12679 ((pos-visible-in-window-p hl-pos)
12680 (message "TODO state changed to %s" (org-trim next))))
12681 (unless head
12682 (setq head (org-get-todo-sequence-head org-state)
12683 ass (assoc head org-todo-kwd-alist)
12684 interpret (nth 1 ass)
12685 done-word (nth 3 ass)
12686 final-done-word (nth 4 ass)))
12687 (when (memq arg '(nextset previousset))
12688 (message "Keyword-Set %d/%d: %s"
12689 (- (length org-todo-sets) -1
12690 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12691 (length org-todo-sets)
12692 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12693 (setq org-last-todo-state-is-todo
12694 (not (member org-state org-done-keywords)))
12695 (setq now-done-p (and (member org-state org-done-keywords)
12696 (not (member this org-done-keywords))))
12697 (and logging (org-local-logging logging))
12698 (when (and (or org-todo-log-states org-log-done)
12699 (not (eq org-inhibit-logging t))
12700 (not (memq arg '(nextset previousset))))
12701 ;; We need to look at recording a time and note.
12702 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12703 (nth 2 (assoc this org-todo-log-states))))
12704 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12705 (setq dolog 'time))
12706 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12707 (and org-state
12708 (member org-state org-not-done-keywords)
12709 (not (member this org-not-done-keywords))))
12710 ;; This is now a todo state and was not one before
12711 ;; If there was a CLOSED time stamp, get rid of it.
12712 (org-add-planning-info nil nil 'closed))
12713 (when (and now-done-p org-log-done)
12714 ;; It is now done, and it was not done before.
12715 (org-add-planning-info 'closed (org-current-effective-time))
12716 (when (and (not dolog) (eq 'note org-log-done))
12717 (org-add-log-setup 'done org-state this 'note)))
12718 (when (and org-state dolog)
12719 ;; This is a non-nil state, and we need to log it.
12720 (org-add-log-setup 'state org-state this dolog)))
12721 ;; Fixup tag positioning.
12722 (org-todo-trigger-tag-changes org-state)
12723 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12724 (when org-provide-todo-statistics
12725 (org-update-parent-todo-statistics))
12726 (run-hooks 'org-after-todo-state-change-hook)
12727 (when (and arg (not (member org-state org-done-keywords)))
12728 (setq head (org-get-todo-sequence-head org-state)))
12729 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12730 ;; Do we need to trigger a repeat?
12731 (when now-done-p
12732 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12733 ;; This is for the agenda, take a snapshot of the headline.
12734 (save-match-data
12735 (setq org-agenda-headline-snapshot-before-repeat
12736 (org-get-heading))))
12737 (org-auto-repeat-maybe org-state))
12738 ;; Fixup cursor location if close to the keyword.
12739 (when (and (outline-on-heading-p)
12740 (not (bolp))
12741 (save-excursion (beginning-of-line 1)
12742 (looking-at org-todo-line-regexp))
12743 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12744 (goto-char (or (match-end 2) (match-end 1)))
12745 (and (looking-at " ") (just-one-space)))
12746 (when org-trigger-hook
12747 (save-excursion
12748 (run-hook-with-args 'org-trigger-hook change-plist)))
12749 (when commentp (org-toggle-comment))))))))
12751 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12752 "Block turning an entry into a TODO, using the hierarchy.
12753 This checks whether the current task should be blocked from state
12754 changes. Such blocking occurs when:
12756 1. The task has children which are not all in a completed state.
12758 2. A task has a parent with the property :ORDERED:, and there
12759 are siblings prior to the current task with incomplete
12760 status.
12762 3. The parent of the task is blocked because it has siblings that should
12763 be done first, or is child of a block grandparent TODO entry."
12765 (if (not org-enforce-todo-dependencies)
12766 t ; if locally turned off don't block
12767 (catch 'dont-block
12768 ;; If this is not a todo state change, or if this entry is already DONE,
12769 ;; do not block
12770 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12771 (member (plist-get change-plist :from)
12772 (cons 'done org-done-keywords))
12773 (member (plist-get change-plist :to)
12774 (cons 'todo org-not-done-keywords))
12775 (not (plist-get change-plist :to)))
12776 (throw 'dont-block t))
12777 ;; If this task has children, and any are undone, it's blocked
12778 (save-excursion
12779 (org-back-to-heading t)
12780 (let ((this-level (funcall outline-level)))
12781 (outline-next-heading)
12782 (let ((child-level (funcall outline-level)))
12783 (while (and (not (eobp))
12784 (> child-level this-level))
12785 ;; this todo has children, check whether they are all
12786 ;; completed
12787 (when (and (not (org-entry-is-done-p))
12788 (org-entry-is-todo-p))
12789 (setq org-block-entry-blocking (org-get-heading))
12790 (throw 'dont-block nil))
12791 (outline-next-heading)
12792 (setq child-level (funcall outline-level))))))
12793 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12794 ;; any previous siblings are undone, it's blocked
12795 (save-excursion
12796 (org-back-to-heading t)
12797 (let* ((pos (point))
12798 (parent-pos (and (org-up-heading-safe) (point)))
12799 (case-fold-search nil))
12800 (unless parent-pos (throw 'dont-block t)) ; no parent
12801 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12802 (forward-line 1)
12803 (re-search-forward org-not-done-heading-regexp pos t))
12804 (setq org-block-entry-blocking (match-string 0))
12805 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12806 ;; Search further up the hierarchy, to see if an ancestor is blocked
12807 (while t
12808 (goto-char parent-pos)
12809 (unless (looking-at org-not-done-heading-regexp)
12810 (throw 'dont-block t)) ; do not block, parent is not a TODO
12811 (setq pos (point))
12812 (setq parent-pos (and (org-up-heading-safe) (point)))
12813 (unless parent-pos (throw 'dont-block t)) ; no parent
12814 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12815 (forward-line 1)
12816 (re-search-forward org-not-done-heading-regexp pos t)
12817 (setq org-block-entry-blocking (org-get-heading)))
12818 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12820 (defcustom org-track-ordered-property-with-tag nil
12821 "Should the ORDERED property also be shown as a tag?
12822 The ORDERED property decides if an entry should require subtasks to be
12823 completed in sequence. Since a property is not very visible, setting
12824 this option means that toggling the ORDERED property with the command
12825 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12826 not relevant for the behavior, but it makes things more visible.
12828 Note that toggling the tag with tags commands will not change the property
12829 and therefore not influence behavior!
12831 This can be t, meaning the tag ORDERED should be used, It can also be a
12832 string to select a different tag for this task."
12833 :group 'org-todo
12834 :type '(choice
12835 (const :tag "No tracking" nil)
12836 (const :tag "Track with ORDERED tag" t)
12837 (string :tag "Use other tag")))
12839 (defun org-toggle-ordered-property ()
12840 "Toggle the ORDERED property of the current entry.
12841 For better visibility, you can track the value of this property with a tag.
12842 See variable `org-track-ordered-property-with-tag'."
12843 (interactive)
12844 (let* ((t1 org-track-ordered-property-with-tag)
12845 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12846 (save-excursion
12847 (org-back-to-heading)
12848 (if (org-entry-get nil "ORDERED")
12849 (progn
12850 (org-delete-property "ORDERED")
12851 (and tag (org-toggle-tag tag 'off))
12852 (message "Subtasks can be completed in arbitrary order"))
12853 (org-entry-put nil "ORDERED" "t")
12854 (and tag (org-toggle-tag tag 'on))
12855 (message "Subtasks must be completed in sequence")))))
12857 (defun org-block-todo-from-checkboxes (change-plist)
12858 "Block turning an entry into a TODO, using checkboxes.
12859 This checks whether the current task should be blocked from state
12860 changes because there are unchecked boxes in this entry."
12861 (if (not org-enforce-todo-checkbox-dependencies)
12862 t ; if locally turned off don't block
12863 (catch 'dont-block
12864 ;; If this is not a todo state change, or if this entry is already DONE,
12865 ;; do not block
12866 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12867 (member (plist-get change-plist :from)
12868 (cons 'done org-done-keywords))
12869 (member (plist-get change-plist :to)
12870 (cons 'todo org-not-done-keywords))
12871 (not (plist-get change-plist :to)))
12872 (throw 'dont-block t))
12873 ;; If this task has checkboxes that are not checked, it's blocked
12874 (save-excursion
12875 (org-back-to-heading t)
12876 (let ((beg (point)) end)
12877 (outline-next-heading)
12878 (setq end (point))
12879 (goto-char beg)
12880 (when (org-list-search-forward
12881 (concat (org-item-beginning-re)
12882 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12883 "\\[[- ]\\]")
12884 end t)
12885 (when (boundp 'org-blocked-by-checkboxes)
12886 (setq org-blocked-by-checkboxes t))
12887 (throw 'dont-block nil))))
12888 t))) ; do not block
12890 (defun org-entry-blocked-p ()
12891 "Non-nil if entry at point is blocked."
12892 (and (not (org-entry-get nil "NOBLOCKING"))
12893 (member (org-entry-get nil "TODO") org-not-done-keywords)
12894 (not (run-hook-with-args-until-failure
12895 'org-blocker-hook
12896 (list :type 'todo-state-change
12897 :position (point)
12898 :from 'todo
12899 :to 'done)))))
12901 (defun org-update-statistics-cookies (all)
12902 "Update the statistics cookie, either from TODO or from checkboxes.
12903 This should be called with the cursor in a line with a statistics
12904 cookie. When called with a \\[universal-argument] prefix, update
12905 all statistics cookies in the buffer."
12906 (interactive "P")
12907 (if all
12908 (progn
12909 (org-update-checkbox-count 'all)
12910 (org-map-entries 'org-update-parent-todo-statistics))
12911 (if (not (org-at-heading-p))
12912 (org-update-checkbox-count)
12913 (let ((pos (point-marker))
12914 end l1 l2)
12915 (ignore-errors (org-back-to-heading t))
12916 (if (not (org-at-heading-p))
12917 (org-update-checkbox-count)
12918 (setq l1 (org-outline-level))
12919 (setq end (save-excursion
12920 (outline-next-heading)
12921 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12922 (point)))
12923 (if (and (save-excursion
12924 (re-search-forward
12925 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12926 (not (save-excursion (re-search-forward
12927 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12928 (org-update-checkbox-count)
12929 (if (and l2 (> l2 l1))
12930 (progn
12931 (goto-char end)
12932 (org-update-parent-todo-statistics))
12933 (goto-char pos)
12934 (beginning-of-line 1)
12935 (while (re-search-forward
12936 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12937 (point-at-eol) t)
12938 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12939 (goto-char pos)
12940 (move-marker pos nil)))))
12942 (defvar org-entry-property-inherited-from) ;; defined below
12943 (defun org-update-parent-todo-statistics ()
12944 "Update any statistics cookie in the parent of the current headline.
12945 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12946 the entire subtree and this will travel up the hierarchy and update
12947 statistics everywhere."
12948 (let* ((prop (save-excursion (org-up-heading-safe)
12949 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12950 (recursive (or (not org-hierarchical-todo-statistics)
12951 (and prop (string-match "\\<recursive\\>" prop))))
12952 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12954 (first t)
12955 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12956 level ltoggle l1 new ndel
12957 (cnt-all 0) (cnt-done 0) is-percent kwd
12958 checkbox-beg cookie-present)
12959 (catch 'exit
12960 (save-excursion
12961 (beginning-of-line 1)
12962 (setq ltoggle (funcall outline-level))
12963 ;; Three situations are to consider:
12965 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12966 ;; to the top-level ancestor on the headline;
12968 ;; 2. If parent has "recursive" property, repeat up to the
12969 ;; headline setting that property, taking inheritance into
12970 ;; account;
12972 ;; 3. Else, move up to direct parent and proceed only once.
12973 (while (and (setq level (org-up-heading-safe))
12974 (or recursive first)
12975 (>= (point) lim))
12976 (setq first nil cookie-present nil)
12977 (unless (and level
12978 (not (string-match
12979 "\\<checkbox\\>"
12980 (downcase (or (org-entry-get nil "COOKIE_DATA")
12981 "")))))
12982 (throw 'exit nil))
12983 (while (re-search-forward box-re (point-at-eol) t)
12984 (setq cnt-all 0 cnt-done 0 cookie-present t)
12985 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12986 (save-match-data
12987 (unless (outline-next-heading) (throw 'exit nil))
12988 (while (and (looking-at org-complex-heading-regexp)
12989 (> (setq l1 (length (match-string 1))) level))
12990 (setq kwd (and (or recursive (= l1 ltoggle))
12991 (match-string 2)))
12992 (if (or (eq org-provide-todo-statistics 'all-headlines)
12993 (and (eq org-provide-todo-statistics t)
12994 (or (member kwd org-done-keywords)))
12995 (and (listp org-provide-todo-statistics)
12996 (stringp (car org-provide-todo-statistics))
12997 (or (member kwd org-provide-todo-statistics)
12998 (member kwd org-done-keywords)))
12999 (and (listp org-provide-todo-statistics)
13000 (listp (car org-provide-todo-statistics))
13001 (or (member kwd (car org-provide-todo-statistics))
13002 (and (member kwd org-done-keywords)
13003 (member kwd (cadr org-provide-todo-statistics))))))
13004 (setq cnt-all (1+ cnt-all))
13005 (and (eq org-provide-todo-statistics t)
13007 (setq cnt-all (1+ cnt-all))))
13008 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
13009 (member kwd org-done-keywords))
13010 (and (listp org-provide-todo-statistics)
13011 (listp (car org-provide-todo-statistics))
13012 (member kwd org-done-keywords)
13013 (member kwd (cadr org-provide-todo-statistics)))
13014 (and (listp org-provide-todo-statistics)
13015 (stringp (car org-provide-todo-statistics))
13016 (member kwd org-done-keywords)))
13017 (setq cnt-done (1+ cnt-done)))
13018 (outline-next-heading)))
13019 (setq new
13020 (if is-percent
13021 (format "[%d%%]" (floor (* 100.0 cnt-done)
13022 (max 1 cnt-all)))
13023 (format "[%d/%d]" cnt-done cnt-all))
13024 ndel (- (match-end 0) checkbox-beg))
13025 (goto-char checkbox-beg)
13026 (insert new)
13027 (delete-region (point) (+ (point) ndel))
13028 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
13029 (when cookie-present
13030 (run-hook-with-args 'org-after-todo-statistics-hook
13031 cnt-done (- cnt-all cnt-done))))))
13032 (run-hooks 'org-todo-statistics-hook)))
13034 (defvar org-after-todo-statistics-hook nil
13035 "Hook that is called after a TODO statistics cookie has been updated.
13036 Each function is called with two arguments: the number of not-done entries
13037 and the number of done entries.
13039 For example, the following function, when added to this hook, will switch
13040 an entry to DONE when all children are done, and back to TODO when new
13041 entries are set to a TODO status. Note that this hook is only called
13042 when there is a statistics cookie in the headline!
13044 (defun org-summary-todo (n-done n-not-done)
13045 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13046 (let (org-log-done org-log-states) ; turn off logging
13047 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13050 (defvar org-todo-statistics-hook nil
13051 "Hook that is run whenever Org thinks TODO statistics should be updated.
13052 This hook runs even if there is no statistics cookie present, in which case
13053 `org-after-todo-statistics-hook' would not run.")
13055 (defun org-todo-trigger-tag-changes (state)
13056 "Apply the changes defined in `org-todo-state-tags-triggers'."
13057 (let ((l org-todo-state-tags-triggers)
13058 changes)
13059 (when (or (not state) (equal state ""))
13060 (setq changes (append changes (cdr (assoc "" l)))))
13061 (when (and (stringp state) (> (length state) 0))
13062 (setq changes (append changes (cdr (assoc state l)))))
13063 (when (member state org-not-done-keywords)
13064 (setq changes (append changes (cdr (assq 'todo l)))))
13065 (when (member state org-done-keywords)
13066 (setq changes (append changes (cdr (assq 'done l)))))
13067 (dolist (c changes)
13068 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13070 (defun org-local-logging (value)
13071 "Get logging settings from a property VALUE."
13072 ;; Directly set the variables, they are already local.
13073 (setq org-log-done nil
13074 org-log-repeat nil
13075 org-todo-log-states nil)
13076 (dolist (w (org-split-string value))
13077 (let (a)
13078 (cond
13079 ((setq a (assoc w org-startup-options))
13080 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13081 (set (nth 1 a) (nth 2 a))))
13082 ((setq a (org-extract-log-state-settings w))
13083 (and (member (car a) org-todo-keywords-1)
13084 (push a org-todo-log-states)))))))
13086 (defun org-get-todo-sequence-head (kwd)
13087 "Return the head of the TODO sequence to which KWD belongs.
13088 If KWD is not set, check if there is a text property remembering the
13089 right sequence."
13090 (let (p)
13091 (cond
13092 ((not kwd)
13093 (or (get-text-property (point-at-bol) 'org-todo-head)
13094 (progn
13095 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13096 nil (point-at-eol)))
13097 (get-text-property p 'org-todo-head))))
13098 ((not (member kwd org-todo-keywords-1))
13099 (car org-todo-keywords-1))
13100 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13102 (defun org-fast-todo-selection ()
13103 "Fast TODO keyword selection with single keys.
13104 Returns the new TODO keyword, or nil if no state change should occur."
13105 (let* ((fulltable org-todo-key-alist)
13106 (done-keywords org-done-keywords) ;; needed for the faces.
13107 (maxlen (apply 'max (mapcar
13108 (lambda (x)
13109 (if (stringp (car x)) (string-width (car x)) 0))
13110 fulltable)))
13111 (expert nil)
13112 (fwidth (+ maxlen 3 1 3))
13113 (ncol (/ (- (window-width) 4) fwidth))
13114 tg cnt e c tbl
13115 groups ingroup)
13116 (save-excursion
13117 (save-window-excursion
13118 (if expert
13119 (set-buffer (get-buffer-create " *Org todo*"))
13120 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13121 (erase-buffer)
13122 (setq-local org-done-keywords done-keywords)
13123 (setq tbl fulltable cnt 0)
13124 (while (setq e (pop tbl))
13125 (cond
13126 ((equal e '(:startgroup))
13127 (push '() groups) (setq ingroup t)
13128 (unless (= cnt 0)
13129 (setq cnt 0)
13130 (insert "\n"))
13131 (insert "{ "))
13132 ((equal e '(:endgroup))
13133 (setq ingroup nil cnt 0)
13134 (insert "}\n"))
13135 ((equal e '(:newline))
13136 (unless (= cnt 0)
13137 (setq cnt 0)
13138 (insert "\n")
13139 (setq e (car tbl))
13140 (while (equal (car tbl) '(:newline))
13141 (insert "\n")
13142 (setq tbl (cdr tbl)))))
13144 (setq tg (car e) c (cdr e))
13145 (when ingroup (push tg (car groups)))
13146 (setq tg (org-add-props tg nil 'face
13147 (org-get-todo-face tg)))
13148 (when (and (= cnt 0) (not ingroup)) (insert " "))
13149 (insert "[" c "] " tg (make-string
13150 (- fwidth 4 (length tg)) ?\ ))
13151 (when (= (setq cnt (1+ cnt)) ncol)
13152 (insert "\n")
13153 (when ingroup (insert " "))
13154 (setq cnt 0)))))
13155 (insert "\n")
13156 (goto-char (point-min))
13157 (unless expert (org-fit-window-to-buffer))
13158 (message "[a-z..]:Set [SPC]:clear")
13159 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13160 (cond
13161 ((or (= c ?\C-g)
13162 (and (= c ?q) (not (rassoc c fulltable))))
13163 (setq quit-flag t))
13164 ((= c ?\ ) nil)
13165 ((setq e (rassoc c fulltable) tg (car e))
13167 (t (setq quit-flag t)))))))
13169 (defun org-entry-is-todo-p ()
13170 (member (org-get-todo-state) org-not-done-keywords))
13172 (defun org-entry-is-done-p ()
13173 (member (org-get-todo-state) org-done-keywords))
13175 (defun org-get-todo-state ()
13176 "Return the TODO keyword of the current subtree."
13177 (save-excursion
13178 (org-back-to-heading t)
13179 (and (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
13180 (match-end 2)
13181 (match-string 2))))
13183 (defun org-at-date-range-p (&optional inactive-ok)
13184 "Non-nil if point is inside a date range.
13186 When optional argument INACTIVE-OK is non-nil, also consider
13187 inactive time ranges.
13189 When this function returns a non-nil value, match data is set
13190 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13191 on INACTIVE-OK."
13192 (interactive)
13193 (save-excursion
13194 (catch 'exit
13195 (let ((pos (point)))
13196 (skip-chars-backward "^[<\r\n")
13197 (skip-chars-backward "<[")
13198 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13199 (>= (match-end 0) pos)
13200 (throw 'exit t))
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 nil)))
13208 (defun org-get-repeat (&optional tagline)
13209 "Check if there is a deadline/schedule with repeater in this entry."
13210 (save-match-data
13211 (save-excursion
13212 (org-back-to-heading t)
13213 (and (re-search-forward (if tagline
13214 (concat tagline "\\s-*" org-repeat-re)
13215 org-repeat-re)
13216 (org-entry-end-position) t)
13217 (match-string-no-properties 1)))))
13219 (defvar org-last-changed-timestamp)
13220 (defvar org-last-inserted-timestamp)
13221 (defvar org-log-post-message)
13222 (defvar org-log-note-purpose)
13223 (defvar org-log-note-how nil)
13224 (defvar org-log-note-extra)
13225 (defun org-auto-repeat-maybe (done-word)
13226 "Check if the current headline contains a repeated time-stamp.
13228 If yes, set TODO state back to what it was and change the base date
13229 of repeating deadline/scheduled time stamps to new date.
13231 This function is run automatically after each state change to a DONE state."
13232 (let* ((repeat (org-get-repeat))
13233 (aa (assoc org-last-state org-todo-kwd-alist))
13234 (interpret (nth 1 aa))
13235 (head (nth 2 aa))
13236 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13237 (msg "Entry repeats: ")
13238 (org-log-done nil)
13239 (org-todo-log-states nil))
13240 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13241 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13242 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13243 org-todo-repeat-to-state)))
13244 (org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
13245 to-state)
13246 ((eq interpret 'type) org-last-state)
13247 (head)
13248 (t 'none))))
13249 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13250 (org-entry-put nil "LAST_REPEAT" (format-time-string
13251 (org-time-stamp-format t t))))
13252 (when org-log-repeat
13253 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13254 (memq 'org-add-log-note post-command-hook))
13255 ;; We are already setup for some record.
13256 (when (eq org-log-repeat 'note)
13257 ;; Make sure we take a note, not only a time stamp.
13258 (setq org-log-note-how 'note))
13259 ;; Set up for taking a record.
13260 (org-add-log-setup 'state
13261 (or done-word (car org-done-keywords))
13262 org-last-state
13263 org-log-repeat)))
13264 (org-back-to-heading t)
13265 (org-add-planning-info nil nil 'closed)
13266 (let ((end (save-excursion (outline-next-heading) (point)))
13267 (planning-re (regexp-opt
13268 (list org-scheduled-string org-deadline-string))))
13269 (while (re-search-forward org-ts-regexp end t)
13270 (let* ((ts (match-string 0))
13271 (planning? (org-at-planning-p))
13272 (type (if (not planning?) "Plain:"
13273 (save-excursion
13274 (re-search-backward
13275 planning-re (line-beginning-position) t)
13276 (match-string 0)))))
13277 (cond
13278 ;; Ignore fake time-stamps (e.g., within comments).
13279 ((and (not planning?)
13280 (not (org-at-property-p))
13281 (not (eq 'timestamp
13282 (org-element-type (save-excursion
13283 (backward-char)
13284 (org-element-context)))))))
13285 ;; Time-stamps without a repeater are usually skipped.
13286 ;; However, a SCHEDULED time-stamp without one is
13287 ;; removed, as it is considered as no longer relevant.
13288 ((not (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13289 (when (equal type org-scheduled-string)
13290 (org-remove-timestamp-with-keyword type)))
13292 (let ((n (string-to-number (match-string 2 ts)))
13293 (what (match-string 3 ts)))
13294 (when (equal what "w") (setq n (* n 7) what "d"))
13295 (when (and (equal what "h")
13296 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13297 ts)))
13298 (user-error
13299 "Cannot repeat in Repeat in %d hour(s) because no hour \
13300 has been set"
13302 ;; Preparation, see if we need to modify the start
13303 ;; date for the change.
13304 (when (match-end 1)
13305 (let ((time (save-match-data (org-time-string-to-time ts))))
13306 (cond
13307 ((equal (match-string 1 ts) ".")
13308 ;; Shift starting date to today
13309 (org-timestamp-change
13310 (- (org-today) (time-to-days time))
13311 'day))
13312 ((equal (match-string 1 ts) "+")
13313 (let ((nshiftmax 10)
13314 (nshift 0))
13315 (while (or (= nshift 0)
13316 (not (time-less-p (current-time) time)))
13317 (when (= (cl-incf nshift) nshiftmax)
13318 (or (y-or-n-p
13319 (format "%d repeater intervals were not \
13320 enough to shift date past today. Continue? "
13321 nshift))
13322 (user-error "Abort")))
13323 (org-timestamp-change n (cdr (assoc what whata)))
13324 (org-at-timestamp-p t)
13325 (setq ts (match-string 1))
13326 (setq time
13327 (save-match-data
13328 (org-time-string-to-time ts)))))
13329 (org-timestamp-change (- n) (cdr (assoc what whata)))
13330 ;; Rematch, so that we have everything in place
13331 ;; for the real shift.
13332 (org-at-timestamp-p t)
13333 (setq ts (match-string 1))
13334 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13335 ts)))))
13336 (save-excursion
13337 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13338 (setq msg
13339 (concat
13340 msg type " " org-last-changed-timestamp " "))))))))
13341 (setq org-log-post-message msg)
13342 (message "%s" msg))))
13344 (defun org-show-todo-tree (arg)
13345 "Make a compact tree which shows all headlines marked with TODO.
13346 The tree will show the lines where the regexp matches, and all higher
13347 headlines above the match.
13348 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
13349 With a numeric prefix N, construct a sparse tree for the Nth element
13350 of `org-todo-keywords-1'."
13351 (interactive "P")
13352 (let ((case-fold-search nil)
13353 (kwd-re
13354 (cond ((null arg) org-not-done-regexp)
13355 ((equal arg '(4))
13356 (let ((kwd
13357 (completing-read "Keyword (or KWD1|KWD2|...): "
13358 (mapcar #'list org-todo-keywords-1))))
13359 (concat "\\("
13360 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13361 "\\)\\>")))
13362 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13363 (regexp-quote (nth (1- (prefix-numeric-value arg))
13364 org-todo-keywords-1)))
13365 (t (user-error "Invalid prefix argument: %s" arg)))))
13366 (message "%d TODO entries found"
13367 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13369 (defun org--deadline-or-schedule (arg type time)
13370 "Insert DEADLINE or SCHEDULE information in current entry.
13371 TYPE is either `deadline' or `scheduled'. See `org-deadline' or
13372 `org-schedule' for information about ARG and TIME arguments."
13373 (let* ((deadline? (eq type 'deadline))
13374 (keyword (if deadline? org-deadline-string org-scheduled-string))
13375 (log (if deadline? org-log-redeadline org-log-reschedule))
13376 (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
13377 (old-date-time (and old-date (org-time-string-to-time old-date)))
13378 ;; Save repeater cookie from either TIME or current scheduled
13379 ;; time stamp. We are going to insert it back at the end of
13380 ;; the process.
13381 (repeater (or (and (org-string-nw-p time)
13382 ;; We use `org-repeat-re' because we need
13383 ;; to tell the difference between a real
13384 ;; repeater and a time delta, e.g. "+2d".
13385 (string-match org-repeat-re time)
13386 (match-string 1 time))
13387 (and (org-string-nw-p old-date)
13388 (string-match "\\([.+-]+[0-9]+[hdwmy]\
13389 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
13390 old-date)
13391 (match-string 1 old-date)))))
13392 (pcase arg
13393 (`(4)
13394 (when (and old-date log)
13395 (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
13396 nil old-date log))
13397 (org-remove-timestamp-with-keyword keyword)
13398 (message (if deadline? "Item no longer has a deadline."
13399 "Item is no longer scheduled.")))
13400 (`(16)
13401 (save-excursion
13402 (org-back-to-heading t)
13403 (let ((regexp (if deadline? org-deadline-time-regexp
13404 org-scheduled-time-regexp)))
13405 (if (not (re-search-forward regexp (line-end-position 2) t))
13406 (user-error (if deadline? "No deadline information to update"
13407 "No scheduled information to update"))
13408 (let* ((rpl0 (match-string 1))
13409 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
13410 (msg (if deadline? "Warn starting from" "Delay until")))
13411 (replace-match
13412 (concat keyword
13413 " <" rpl
13414 (format " -%dd"
13415 (abs (- (time-to-days
13416 (save-match-data
13417 (org-read-date
13418 nil t nil msg old-date-time)))
13419 (time-to-days old-date-time))))
13420 ">") t t))))))
13422 (org-add-planning-info type time 'closed)
13423 (when (and old-date
13425 (not (equal old-date org-last-inserted-timestamp)))
13426 (org-add-log-setup (if deadline? 'redeadline 'reschedule)
13427 org-last-inserted-timestamp
13428 old-date
13429 log))
13430 (when repeater
13431 (save-excursion
13432 (org-back-to-heading t)
13433 (when (re-search-forward
13434 (concat keyword " " org-last-inserted-timestamp)
13435 (line-end-position 2)
13437 (goto-char (1- (match-end 0)))
13438 (insert " " repeater)
13439 (setq org-last-inserted-timestamp
13440 (concat (substring org-last-inserted-timestamp 0 -1)
13441 " " repeater
13442 (substring org-last-inserted-timestamp -1))))))
13443 (message (if deadline? "Deadline on %s" "Scheduled to %s")
13444 org-last-inserted-timestamp)))))
13446 (defun org-deadline (arg &optional time)
13447 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13448 With one universal prefix argument, remove any deadline from the item.
13449 With two universal prefix arguments, prompt for a warning delay.
13450 With argument TIME, set the deadline at the corresponding date. TIME
13451 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13452 (interactive "P")
13453 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13454 (org-map-entries
13455 (lambda () (org--deadline-or-schedule arg 'deadline time))
13457 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13458 'region-start-level
13459 'region)
13460 (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
13461 (org--deadline-or-schedule arg 'deadline time)))
13463 (defun org-schedule (arg &optional time)
13464 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13465 With one universal prefix argument, remove any scheduling date from the item.
13466 With two universal prefix arguments, prompt for a delay cookie.
13467 With argument TIME, scheduled at the corresponding date. TIME can
13468 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13469 (interactive "P")
13470 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13471 (org-map-entries
13472 (lambda () (org--deadline-or-schedule arg 'scheduled time))
13474 (if (eq org-loop-over-headlines-in-active-region 'start-level)
13475 'region-start-level
13476 'region)
13477 (lambda () (when (outline-invisible-p) (org-end-of-subtree nil t))))
13478 (org--deadline-or-schedule arg 'scheduled time)))
13480 (defun org-get-scheduled-time (pom &optional inherit)
13481 "Get the scheduled time as a time tuple, of a format suitable
13482 for calling org-schedule with, or if there is no scheduling,
13483 returns nil."
13484 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13485 (when time
13486 (apply 'encode-time (org-parse-time-string time)))))
13488 (defun org-get-deadline-time (pom &optional inherit)
13489 "Get the deadline as a time tuple, of a format suitable for
13490 calling org-deadline with, or if there is no scheduling, returns
13491 nil."
13492 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13493 (when time
13494 (apply 'encode-time (org-parse-time-string time)))))
13496 (defun org-remove-timestamp-with-keyword (keyword)
13497 "Remove all time stamps with KEYWORD in the current entry."
13498 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13499 beg)
13500 (save-excursion
13501 (org-back-to-heading t)
13502 (setq beg (point))
13503 (outline-next-heading)
13504 (while (re-search-backward re beg t)
13505 (replace-match "")
13506 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13507 (equal (char-before) ?\ ))
13508 (backward-delete-char 1)
13509 (when (string-match "^[ \t]*$" (buffer-substring
13510 (point-at-bol) (point-at-eol)))
13511 (delete-region (point-at-bol)
13512 (min (point-max) (1+ (point-at-eol))))))))))
13514 (defvar org-time-was-given) ; dynamically scoped parameter
13515 (defvar org-end-time-was-given) ; dynamically scoped parameter
13517 (defun org-at-planning-p ()
13518 "Non-nil when point is on a planning info line."
13519 ;; This is as accurate and faster than `org-element-at-point' since
13520 ;; planning info location is fixed in the section.
13521 (org-with-wide-buffer
13522 (beginning-of-line)
13523 (and (looking-at-p org-planning-line-re)
13524 (eq (point)
13525 (ignore-errors
13526 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13527 (org-back-to-heading t)
13528 (org-with-limited-levels (org-back-to-heading t)))
13529 (line-beginning-position 2))))))
13531 (defun org-add-planning-info (what &optional time &rest remove)
13532 "Insert new timestamp with keyword in the planning line.
13533 WHAT indicates what kind of time stamp to add. It is a symbol
13534 among `closed', `deadline', `scheduled' and nil. TIME indicates
13535 the time to use. If none is given, the user is prompted for
13536 a date. REMOVE indicates what kind of entries to remove. An old
13537 WHAT entry will also be removed."
13538 (let (org-time-was-given org-end-time-was-given default-time default-input)
13539 (catch 'exit
13540 (when (and (memq what '(scheduled deadline))
13541 (or (not time)
13542 (and (stringp time)
13543 (string-match "^[-+]+[0-9]" time))))
13544 ;; Try to get a default date/time from existing timestamp
13545 (save-excursion
13546 (org-back-to-heading t)
13547 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13548 (when (re-search-forward (if (eq what 'scheduled)
13549 org-scheduled-time-regexp
13550 org-deadline-time-regexp)
13551 end t)
13552 (setq ts (match-string 1)
13553 default-time (apply 'encode-time (org-parse-time-string ts))
13554 default-input (and ts (org-get-compact-tod ts)))))))
13555 (when what
13556 (setq time
13557 (if (stringp time)
13558 ;; This is a string (relative or absolute), set
13559 ;; proper date.
13560 (apply #'encode-time
13561 (org-read-date-analyze
13562 time default-time (decode-time default-time)))
13563 ;; If necessary, get the time from the user
13564 (or time (org-read-date nil 'to-time nil nil
13565 default-time default-input)))))
13567 (org-with-wide-buffer
13568 (org-back-to-heading t)
13569 (forward-line)
13570 (unless (bolp) (insert "\n"))
13571 (cond ((looking-at-p org-planning-line-re)
13572 ;; Move to current indentation.
13573 (skip-chars-forward " \t")
13574 ;; Check if we have to remove something.
13575 (dolist (type (if what (cons what remove) remove))
13576 (save-excursion
13577 (when (re-search-forward
13578 (cl-case type
13579 (closed org-closed-time-regexp)
13580 (deadline org-deadline-time-regexp)
13581 (scheduled org-scheduled-time-regexp)
13582 (otherwise
13583 (error "Invalid planning type: %s" type)))
13584 (line-end-position) t)
13585 ;; Delete until next keyword or end of line.
13586 (delete-region
13587 (match-beginning 0)
13588 (if (re-search-forward org-keyword-time-not-clock-regexp
13589 (line-end-position)
13591 (match-beginning 0)
13592 (line-end-position))))))
13593 ;; If there is nothing more to add and no more keyword
13594 ;; is left, remove the line completely.
13595 (if (and (looking-at-p "[ \t]*$") (not what))
13596 (delete-region (line-beginning-position)
13597 (line-beginning-position 2))
13598 ;; If we removed last keyword, do not leave trailing
13599 ;; white space at the end of line.
13600 (let ((p (point)))
13601 (save-excursion
13602 (end-of-line)
13603 (unless (= (skip-chars-backward " \t" p) 0)
13604 (delete-region (point) (line-end-position)))))))
13605 ((not what) (throw 'exit nil)) ; Nothing to do.
13606 (t (insert-before-markers "\n")
13607 (backward-char 1)
13608 (when org-adapt-indentation
13609 (indent-to-column (1+ (org-outline-level))))))
13610 (when what
13611 ;; Insert planning keyword.
13612 (insert (cl-case what
13613 (closed org-closed-string)
13614 (deadline org-deadline-string)
13615 (scheduled org-scheduled-string)
13616 (otherwise (error "Invalid planning type: %s" what)))
13617 " ")
13618 ;; Insert associated timestamp.
13619 (let ((ts (org-insert-time-stamp
13620 time
13621 (or org-time-was-given
13622 (and (eq what 'closed) org-log-done-with-time))
13623 (eq what 'closed)
13624 nil nil (list org-end-time-was-given))))
13625 (unless (eolp) (insert " "))
13626 ts))))))
13628 (defvar org-log-note-marker (make-marker)
13629 "Marker pointing at the entry where the note is to be inserted.")
13630 (defvar org-log-note-purpose nil)
13631 (defvar org-log-note-state nil)
13632 (defvar org-log-note-previous-state nil)
13633 (defvar org-log-note-extra nil)
13634 (defvar org-log-note-window-configuration nil)
13635 (defvar org-log-note-return-to (make-marker))
13636 (defvar org-log-note-effective-time nil
13637 "Remembered current time so that dynamically scoped
13638 `org-extend-today-until' affects timestamps in state change log")
13640 (defvar org-log-post-message nil
13641 "Message to be displayed after a log note has been stored.
13642 The auto-repeater uses this.")
13644 (defun org-add-note ()
13645 "Add a note to the current entry.
13646 This is done in the same way as adding a state change note."
13647 (interactive)
13648 (org-add-log-setup 'note))
13650 (defun org-log-beginning (&optional create)
13651 "Return expected start of log notes in current entry.
13652 When optional argument CREATE is non-nil, the function creates
13653 a drawer to store notes, if necessary. Returned position ignores
13654 narrowing."
13655 (org-with-wide-buffer
13656 (let ((drawer (org-log-into-drawer)))
13657 (cond
13658 (drawer
13659 (org-end-of-meta-data)
13660 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13661 (end (if (org-at-heading-p) (point)
13662 (save-excursion (outline-next-heading) (point))))
13663 (case-fold-search t))
13664 (catch 'exit
13665 ;; Try to find existing drawer.
13666 (while (re-search-forward regexp end t)
13667 (let ((element (org-element-at-point)))
13668 (when (eq (org-element-type element) 'drawer)
13669 (let ((cend (org-element-property :contents-end element)))
13670 (when (and (not org-log-states-order-reversed) cend)
13671 (goto-char cend)))
13672 (throw 'exit nil))))
13673 ;; No drawer found. Create one, if permitted.
13674 (when create
13675 (unless (bolp) (insert "\n"))
13676 (let ((beg (point)))
13677 (insert ":" drawer ":\n:END:\n")
13678 (org-indent-region beg (point)))
13679 (end-of-line -1)))))
13681 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13682 (skip-chars-forward " \t\n")
13683 (beginning-of-line)
13684 (unless org-log-states-order-reversed
13685 (org-skip-over-state-notes)
13686 (skip-chars-backward " \t\n")
13687 (forward-line)))))
13688 (if (bolp) (point) (line-beginning-position 2))))
13690 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13691 "Set up the post command hook to take a note.
13692 If this is about to TODO state change, the new state is expected in STATE.
13693 HOW is an indicator what kind of note should be created.
13694 EXTRA is additional text that will be inserted into the notes buffer."
13695 (move-marker org-log-note-marker (point))
13696 (setq org-log-note-purpose purpose
13697 org-log-note-state state
13698 org-log-note-previous-state prev-state
13699 org-log-note-how how
13700 org-log-note-extra extra
13701 org-log-note-effective-time (org-current-effective-time))
13702 (add-hook 'post-command-hook 'org-add-log-note 'append))
13704 (defun org-skip-over-state-notes ()
13705 "Skip past the list of State notes in an entry."
13706 (when (ignore-errors (goto-char (org-in-item-p)))
13707 (let* ((struct (org-list-struct))
13708 (prevs (org-list-prevs-alist struct))
13709 (regexp
13710 (concat "[ \t]*- +"
13711 (replace-regexp-in-string
13712 " +" " +"
13713 (org-replace-escapes
13714 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13715 `(("%d" . ,org-ts-regexp-inactive)
13716 ("%D" . ,org-ts-regexp)
13717 ("%s" . "\"\\S-+\"")
13718 ("%S" . "\"\\S-+\"")
13719 ("%t" . ,org-ts-regexp-inactive)
13720 ("%T" . ,org-ts-regexp)
13721 ("%u" . ".*?")
13722 ("%U" . ".*?")))))))
13723 (while (looking-at-p regexp)
13724 (goto-char (or (org-list-get-next-item (point) struct prevs)
13725 (org-list-get-item-end (point) struct)))))))
13727 (defun org-add-log-note (&optional _purpose)
13728 "Pop up a window for taking a note, and add this note later."
13729 (remove-hook 'post-command-hook 'org-add-log-note)
13730 (setq org-log-note-window-configuration (current-window-configuration))
13731 (delete-other-windows)
13732 (move-marker org-log-note-return-to (point))
13733 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13734 (goto-char org-log-note-marker)
13735 (org-switch-to-buffer-other-window "*Org Note*")
13736 (erase-buffer)
13737 (if (memq org-log-note-how '(time state))
13738 (let (current-prefix-arg) (org-store-log-note))
13739 (let ((org-inhibit-startup t)) (org-mode))
13740 (insert (format "# Insert note for %s.
13741 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13742 (cond
13743 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13744 ((eq org-log-note-purpose 'done) "closed todo item")
13745 ((eq org-log-note-purpose 'state)
13746 (format "state change from \"%s\" to \"%s\""
13747 (or org-log-note-previous-state "")
13748 (or org-log-note-state "")))
13749 ((eq org-log-note-purpose 'reschedule)
13750 "rescheduling")
13751 ((eq org-log-note-purpose 'delschedule)
13752 "no longer scheduled")
13753 ((eq org-log-note-purpose 'redeadline)
13754 "changing deadline")
13755 ((eq org-log-note-purpose 'deldeadline)
13756 "removing deadline")
13757 ((eq org-log-note-purpose 'refile)
13758 "refiling")
13759 ((eq org-log-note-purpose 'note)
13760 "this entry")
13761 (t (error "This should not happen")))))
13762 (when org-log-note-extra (insert org-log-note-extra))
13763 (setq-local org-finish-function 'org-store-log-note)
13764 (run-hooks 'org-log-buffer-setup-hook)))
13766 (defvar org-note-abort nil) ; dynamically scoped
13767 (defun org-store-log-note ()
13768 "Finish taking a log note, and insert it to where it belongs."
13769 (let ((txt (prog1 (buffer-string)
13770 (kill-buffer)))
13771 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13772 lines)
13773 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13774 (setq txt (replace-match "" t t txt)))
13775 (when (string-match "\\s-+\\'" txt)
13776 (setq txt (replace-match "" t t txt)))
13777 (setq lines (org-split-string txt "\n"))
13778 (when (org-string-nw-p note)
13779 (setq note
13780 (org-replace-escapes
13781 note
13782 (list (cons "%u" (user-login-name))
13783 (cons "%U" user-full-name)
13784 (cons "%t" (format-time-string
13785 (org-time-stamp-format 'long 'inactive)
13786 org-log-note-effective-time))
13787 (cons "%T" (format-time-string
13788 (org-time-stamp-format 'long nil)
13789 org-log-note-effective-time))
13790 (cons "%d" (format-time-string
13791 (org-time-stamp-format nil 'inactive)
13792 org-log-note-effective-time))
13793 (cons "%D" (format-time-string
13794 (org-time-stamp-format nil nil)
13795 org-log-note-effective-time))
13796 (cons "%s" (cond
13797 ((not org-log-note-state) "")
13798 ((string-match-p org-ts-regexp
13799 org-log-note-state)
13800 (format "\"[%s]\""
13801 (substring org-log-note-state 1 -1)))
13802 (t (format "\"%s\"" org-log-note-state))))
13803 (cons "%S"
13804 (cond
13805 ((not org-log-note-previous-state) "")
13806 ((string-match-p org-ts-regexp
13807 org-log-note-previous-state)
13808 (format "\"[%s]\""
13809 (substring
13810 org-log-note-previous-state 1 -1)))
13811 (t (format "\"%s\""
13812 org-log-note-previous-state)))))))
13813 (when lines (setq note (concat note " \\\\")))
13814 (push note lines))
13815 (when (and lines (not (or current-prefix-arg org-note-abort)))
13816 (with-current-buffer (marker-buffer org-log-note-marker)
13817 (org-with-wide-buffer
13818 ;; Find location for the new note.
13819 (goto-char org-log-note-marker)
13820 (set-marker org-log-note-marker nil)
13821 ;; Note associated to a clock is to be located right after
13822 ;; the clock. Do not move point.
13823 (unless (eq org-log-note-purpose 'clock-out)
13824 (goto-char (org-log-beginning t)))
13825 ;; Make sure point is at the beginning of an empty line.
13826 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13827 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13828 ;; In an existing list, add a new item at the top level.
13829 ;; Otherwise, indent line like a regular one.
13830 (let ((itemp (org-in-item-p)))
13831 (if itemp
13832 (indent-line-to
13833 (let ((struct (save-excursion
13834 (goto-char itemp) (org-list-struct))))
13835 (org-list-get-ind (org-list-get-top-point struct) struct)))
13836 (org-indent-line)))
13837 (insert (org-list-bullet-string "-") (pop lines))
13838 (let ((ind (org-list-item-body-column (line-beginning-position))))
13839 (dolist (line lines)
13840 (insert "\n")
13841 (indent-line-to ind)
13842 (insert line)))
13843 (message "Note stored")
13844 (org-back-to-heading t)
13845 (org-cycle-hide-drawers 'children))
13846 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13847 ;; from within `org-add-log-note' because `buffer-undo-list'
13848 ;; is then modified outside of `org-with-remote-undo'.
13849 (when (eq this-command 'org-agenda-todo)
13850 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13851 ;; Don't add undo information when called from `org-agenda-todo'.
13852 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13853 (set-window-configuration org-log-note-window-configuration)
13854 (with-current-buffer (marker-buffer org-log-note-return-to)
13855 (goto-char org-log-note-return-to))
13856 (move-marker org-log-note-return-to nil)
13857 (when org-log-post-message (message "%s" org-log-post-message))))
13859 (defun org-remove-empty-drawer-at (pos)
13860 "Remove an empty drawer at position POS.
13861 POS may also be a marker."
13862 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13863 (org-with-wide-buffer
13864 (goto-char pos)
13865 (let ((drawer (org-element-at-point)))
13866 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13867 (not (org-element-property :contents-begin drawer)))
13868 (delete-region (org-element-property :begin drawer)
13869 (progn (goto-char (org-element-property :end drawer))
13870 (skip-chars-backward " \r\t\n")
13871 (forward-line)
13872 (point))))))))
13874 (defvar org-ts-type nil)
13875 (defun org-sparse-tree (&optional arg type)
13876 "Create a sparse tree, prompt for the details.
13877 This command can create sparse trees. You first need to select the type
13878 of match used to create the tree:
13880 t Show all TODO entries.
13881 T Show entries with a specific TODO keyword.
13882 m Show entries selected by a tags/property match.
13883 p Enter a property name and its value (both with completion on existing
13884 names/values) and show entries with that property.
13885 r Show entries matching a regular expression (`/' can be used as well).
13886 b Show deadlines and scheduled items before a date.
13887 a Show deadlines and scheduled items after a date.
13888 d Show deadlines due within `org-deadline-warning-days'.
13889 D Show deadlines and scheduled items between a date range."
13890 (interactive "P")
13891 (setq type (or type org-sparse-tree-default-date-type))
13892 (setq org-ts-type type)
13893 (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
13894 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13895 \[c]ycle through date types: %s"
13896 (cl-case type
13897 (all "all timestamps")
13898 (scheduled "only scheduled")
13899 (deadline "only deadline")
13900 (active "only active timestamps")
13901 (inactive "only inactive timestamps")
13902 (closed "with a closed time-stamp")
13903 (otherwise "scheduled/deadline")))
13904 (let ((answer (read-char-exclusive)))
13905 (cl-case answer
13907 (org-sparse-tree
13909 (cadr
13910 (memq type '(nil all scheduled deadline active inactive closed)))))
13911 (?d (call-interactively 'org-check-deadlines))
13912 (?b (call-interactively 'org-check-before-date))
13913 (?a (call-interactively 'org-check-after-date))
13914 (?D (call-interactively 'org-check-dates-range))
13915 (?t (call-interactively 'org-show-todo-tree))
13916 (?T (org-show-todo-tree '(4)))
13917 (?m (call-interactively 'org-match-sparse-tree))
13918 ((?p ?P)
13919 (let* ((kwd (completing-read
13920 "Property: " (mapcar #'list (org-buffer-property-keys))))
13921 (value (completing-read
13922 "Value: " (mapcar #'list (org-property-values kwd)))))
13923 (unless (string-match "\\`{.*}\\'" value)
13924 (setq value (concat "\"" value "\"")))
13925 (org-match-sparse-tree arg (concat kwd "=" value))))
13926 ((?r ?R ?/) (call-interactively 'org-occur))
13927 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13929 (defvar-local org-occur-highlights nil
13930 "List of overlays used for occur matches.")
13931 (defvar-local org-occur-parameters nil
13932 "Parameters of the active org-occur calls.
13933 This is a list, each call to org-occur pushes as cons cell,
13934 containing the regular expression and the callback, onto the list.
13935 The list can contain several entries if `org-occur' has been called
13936 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13937 will only contain one set of parameters. When the highlights are
13938 removed (for example with `C-c C-c', or with the next edit (depending
13939 on `org-remove-highlights-with-change'), this variable is emptied
13940 as well.")
13942 (defun org-occur (regexp &optional keep-previous callback)
13943 "Make a compact tree which shows all matches of REGEXP.
13945 The tree will show the lines where the regexp matches, and any other context
13946 defined in `org-show-context-detail', which see.
13948 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13949 done by a previous call to `org-occur' will be kept, to allow stacking of
13950 calls to this command.
13952 Optional argument CALLBACK can be a function of no argument. In this case,
13953 it is called with point at the end of the match, match data being set
13954 accordingly. Current match is shown only if the return value is non-nil.
13955 The function must neither move point nor alter narrowing."
13956 (interactive "sRegexp: \nP")
13957 (when (equal regexp "")
13958 (user-error "Regexp cannot be empty"))
13959 (unless keep-previous
13960 (org-remove-occur-highlights nil nil t))
13961 (push (cons regexp callback) org-occur-parameters)
13962 (let ((cnt 0))
13963 (save-excursion
13964 (goto-char (point-min))
13965 (when (or (not keep-previous) ; do not want to keep
13966 (not org-occur-highlights)) ; no previous matches
13967 ;; hide everything
13968 (org-overview))
13969 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13970 (isearch-no-upper-case-p regexp t)
13971 org-occur-case-fold-search)))
13972 (while (re-search-forward regexp nil t)
13973 (when (or (not callback)
13974 (save-match-data (funcall callback)))
13975 (setq cnt (1+ cnt))
13976 (when org-highlight-sparse-tree-matches
13977 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13978 (org-show-context 'occur-tree)))))
13979 (when org-remove-highlights-with-change
13980 (add-hook 'before-change-functions 'org-remove-occur-highlights
13981 nil 'local))
13982 (unless org-sparse-tree-open-archived-trees
13983 (org-hide-archived-subtrees (point-min) (point-max)))
13984 (run-hooks 'org-occur-hook)
13985 (when (called-interactively-p 'interactive)
13986 (message "%d match(es) for regexp %s" cnt regexp))
13987 cnt))
13989 (defun org-occur-next-match (&optional n _reset)
13990 "Function for `next-error-function' to find sparse tree matches.
13991 N is the number of matches to move, when negative move backwards.
13992 This function always goes back to the starting point when no
13993 match is found."
13994 (let* ((limit (if (< n 0) (point-min) (point-max)))
13995 (search-func (if (< n 0)
13996 'previous-single-char-property-change
13997 'next-single-char-property-change))
13998 (n (abs n))
13999 (pos (point))
14001 (catch 'exit
14002 (while (setq p1 (funcall search-func (point) 'org-type))
14003 (when (equal p1 limit)
14004 (goto-char pos)
14005 (user-error "No more matches"))
14006 (when (equal (get-char-property p1 'org-type) 'org-occur)
14007 (setq n (1- n))
14008 (when (= n 0)
14009 (goto-char p1)
14010 (throw 'exit (point))))
14011 (goto-char p1))
14012 (goto-char p1)
14013 (user-error "No more matches"))))
14015 (defun org-show-context (&optional key)
14016 "Make sure point and context are visible.
14017 Optional argument KEY, when non-nil, is a symbol. See
14018 `org-show-context-detail' for allowed values and how much is to
14019 be shown."
14020 (org-show-set-visibility
14021 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14022 ((cdr (assq key org-show-context-detail)))
14023 (t (cdr (assq 'default org-show-context-detail))))))
14025 (defun org-show-set-visibility (detail)
14026 "Set visibility around point according to DETAIL.
14027 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14028 `tree', `canonical' or t. See `org-show-context-detail' for more
14029 information."
14030 ;; Show current heading and possibly its entry, following headline
14031 ;; or all children.
14032 (if (and (org-at-heading-p) (not (eq detail 'local)))
14033 (org-flag-heading nil)
14034 (org-show-entry)
14035 ;; If point is hidden within a drawer or a block, make sure to
14036 ;; expose it.
14037 (dolist (o (overlays-at (point)))
14038 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14039 (delete-overlay o)))
14040 (unless (org-before-first-heading-p)
14041 (org-with-limited-levels
14042 (cl-case detail
14043 ((tree canonical t) (org-show-children))
14044 ((nil minimal ancestors))
14045 (t (save-excursion
14046 (outline-next-heading)
14047 (org-flag-heading nil)))))))
14048 ;; Show all siblings.
14049 (when (eq detail 'lineage) (org-show-siblings))
14050 ;; Show ancestors, possibly with their children.
14051 (when (memq detail '(ancestors lineage tree canonical t))
14052 (save-excursion
14053 (while (org-up-heading-safe)
14054 (org-flag-heading nil)
14055 (when (memq detail '(canonical t)) (org-show-entry))
14056 (when (memq detail '(tree canonical t)) (org-show-children))))))
14058 (defvar org-reveal-start-hook nil
14059 "Hook run before revealing a location.")
14061 (defun org-reveal (&optional siblings)
14062 "Show current entry, hierarchy above it, and the following headline.
14064 This can be used to show a consistent set of context around
14065 locations exposed with `org-show-context'.
14067 With optional argument SIBLINGS, on each level of the hierarchy all
14068 siblings are shown. This repairs the tree structure to what it would
14069 look like when opened with hierarchical calls to `org-cycle'.
14071 With a \\[universal-argument] \\[universal-argument] prefix, \
14072 go to the parent and show the entire tree."
14073 (interactive "P")
14074 (run-hooks 'org-reveal-start-hook)
14075 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14076 ((equal siblings '(16))
14077 (save-excursion
14078 (when (org-up-heading-safe)
14079 (org-show-subtree)
14080 (run-hook-with-args 'org-cycle-hook 'subtree))))
14081 (t (org-show-set-visibility 'lineage))))
14083 (defun org-highlight-new-match (beg end)
14084 "Highlight from BEG to END and mark the highlight is an occur headline."
14085 (let ((ov (make-overlay beg end)))
14086 (overlay-put ov 'face 'secondary-selection)
14087 (overlay-put ov 'org-type 'org-occur)
14088 (push ov org-occur-highlights)))
14090 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14091 "Remove the occur highlights from the buffer.
14092 BEG and END are ignored. If NOREMOVE is nil, remove this function
14093 from the `before-change-functions' in the current buffer."
14094 (interactive)
14095 (unless org-inhibit-highlight-removal
14096 (mapc #'delete-overlay org-occur-highlights)
14097 (setq org-occur-highlights nil)
14098 (setq org-occur-parameters nil)
14099 (unless noremove
14100 (remove-hook 'before-change-functions
14101 'org-remove-occur-highlights 'local))))
14103 ;;;; Priorities
14105 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14106 "Regular expression matching the priority indicator.")
14108 (defvar org-remove-priority-next-time nil)
14110 (defun org-priority-up ()
14111 "Increase the priority of the current item."
14112 (interactive)
14113 (org-priority 'up))
14115 (defun org-priority-down ()
14116 "Decrease the priority of the current item."
14117 (interactive)
14118 (org-priority 'down))
14120 (defun org-priority (&optional action _show)
14121 "Change the priority of an item.
14122 ACTION can be `set', `up', `down', or a character."
14123 (interactive "P")
14124 (if (equal action '(4))
14125 (org-show-priority)
14126 (unless org-enable-priority-commands
14127 (user-error "Priority commands are disabled"))
14128 (setq action (or action 'set))
14129 (let (current new news have remove)
14130 (save-excursion
14131 (org-back-to-heading t)
14132 (when (looking-at org-priority-regexp)
14133 (setq current (string-to-char (match-string 2))
14134 have t))
14135 (cond
14136 ((eq action 'remove)
14137 (setq remove t new ?\ ))
14138 ((or (eq action 'set)
14139 (integerp action))
14140 (if (not (eq action 'set))
14141 (setq new action)
14142 (message "Priority %c-%c, SPC to remove: "
14143 org-highest-priority org-lowest-priority)
14144 (save-match-data
14145 (setq new (read-char-exclusive))))
14146 (when (and (= (upcase org-highest-priority) org-highest-priority)
14147 (= (upcase org-lowest-priority) org-lowest-priority))
14148 (setq new (upcase new)))
14149 (cond ((equal new ?\ ) (setq remove t))
14150 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14151 (user-error "Priority must be between `%c' and `%c'"
14152 org-highest-priority org-lowest-priority))))
14153 ((eq action 'up)
14154 (setq new (if have
14155 (1- current) ; normal cycling
14156 ;; last priority was empty
14157 (if (eq last-command this-command)
14158 org-lowest-priority ; wrap around empty to lowest
14159 ;; default
14160 (if org-priority-start-cycle-with-default
14161 org-default-priority
14162 (1- org-default-priority))))))
14163 ((eq action 'down)
14164 (setq new (if have
14165 (1+ current) ; normal cycling
14166 ;; last priority was empty
14167 (if (eq last-command this-command)
14168 org-highest-priority ; wrap around empty to highest
14169 ;; default
14170 (if org-priority-start-cycle-with-default
14171 org-default-priority
14172 (1+ org-default-priority))))))
14173 (t (user-error "Invalid action")))
14174 (when (or (< (upcase new) org-highest-priority)
14175 (> (upcase new) org-lowest-priority))
14176 (if (and (memq action '(up down))
14177 (not have) (not (eq last-command this-command)))
14178 ;; `new' is from default priority
14179 (error
14180 "The default can not be set, see `org-default-priority' why")
14181 ;; normal cycling: `new' is beyond highest/lowest priority
14182 ;; and is wrapped around to the empty priority
14183 (setq remove t)))
14184 (setq news (format "%c" new))
14185 (if have
14186 (if remove
14187 (replace-match "" t t nil 1)
14188 (replace-match news t t nil 2))
14189 (if remove
14190 (user-error "No priority cookie found in line")
14191 (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
14192 (if (match-end 2)
14193 (progn
14194 (goto-char (match-end 2))
14195 (insert " [#" news "]"))
14196 (goto-char (match-beginning 3))
14197 (insert "[#" news "] "))))
14198 (org-set-tags nil 'align))
14199 (if remove
14200 (message "Priority removed")
14201 (message "Priority of current item set to %s" news)))))
14203 (defun org-show-priority ()
14204 "Show the priority of the current item.
14205 This priority is composed of the main priority given with the [#A] cookies,
14206 and by additional input from the age of a schedules or deadline entry."
14207 (interactive)
14208 (let ((pri (if (eq major-mode 'org-agenda-mode)
14209 (org-get-at-bol 'priority)
14210 (save-excursion
14211 (save-match-data
14212 (beginning-of-line)
14213 (and (looking-at org-heading-regexp)
14214 (org-get-priority (match-string 0))))))))
14215 (message "Priority is %d" (if pri pri -1000))))
14217 (defun org-get-priority (s)
14218 "Find priority cookie and return priority."
14219 (save-match-data
14220 (if (functionp org-get-priority-function)
14221 (funcall org-get-priority-function)
14222 (if (not (string-match org-priority-regexp s))
14223 (* 1000 (- org-lowest-priority org-default-priority))
14224 (* 1000 (- org-lowest-priority
14225 (string-to-char (match-string 2 s))))))))
14227 ;;;; Tags
14229 (defvar org-agenda-archives-mode)
14230 (defvar org-map-continue-from nil
14231 "Position from where mapping should continue.
14232 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14234 (defvar org-scanner-tags nil
14235 "The current tag list while the tags scanner is running.")
14237 (defvar org-trust-scanner-tags nil
14238 "Should `org-get-tags-at' use the tags for the scanner.
14239 This is for internal dynamical scoping only.
14240 When this is non-nil, the function `org-get-tags-at' will return the value
14241 of `org-scanner-tags' instead of building the list by itself. This
14242 can lead to large speed-ups when the tags scanner is used in a file with
14243 many entries, and when the list of tags is retrieved, for example to
14244 obtain a list of properties. Building the tags list for each entry in such
14245 a file becomes an N^2 operation - but with this variable set, it scales
14246 as N.")
14248 (defvar org--matcher-tags-todo-only nil)
14250 (defun org-scan-tags (action matcher todo-only &optional start-level)
14251 "Scan headline tags with inheritance and produce output ACTION.
14253 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14254 or `agenda' to produce an entry list for an agenda view. It can also be
14255 a Lisp form or a function that should be called at each matched headline, in
14256 this case the return value is a list of all return values from these calls.
14258 MATCHER is a function accepting three arguments, returning
14259 a non-nil value whenever a given set of tags qualifies a headline
14260 for inclusion. See `org-make-tags-matcher' for more information.
14261 As a special case, it can also be set to t (respectively nil) in
14262 order to match all (respectively none) headline.
14264 When TODO-ONLY is non-nil, only lines with a not-done TODO
14265 keyword are included in the output.
14267 START-LEVEL can be a string with asterisks, reducing the scope to
14268 headlines matching this string."
14269 (require 'org-agenda)
14270 (let* ((re (concat "^"
14271 (if start-level
14272 ;; Get the correct level to match
14273 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14274 org-outline-regexp)
14275 " *\\(\\<\\("
14276 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14277 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14278 (props (list 'face 'default
14279 'done-face 'org-agenda-done
14280 'undone-face 'default
14281 'mouse-face 'highlight
14282 'org-not-done-regexp org-not-done-regexp
14283 'org-todo-regexp org-todo-regexp
14284 'org-complex-heading-regexp org-complex-heading-regexp
14285 'help-echo
14286 (format "mouse-2 or RET jump to org file %s"
14287 (abbreviate-file-name
14288 (or (buffer-file-name (buffer-base-buffer))
14289 (buffer-name (buffer-base-buffer)))))))
14290 (org-map-continue-from nil)
14291 lspos tags tags-list
14292 (tags-alist (list (cons 0 org-file-tags)))
14293 (llast 0) rtn rtn1 level category i txt
14294 todo marker entry priority
14295 ts-date ts-date-type ts-date-pair)
14296 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14297 (setq action (list 'lambda nil action)))
14298 (save-excursion
14299 (goto-char (point-min))
14300 (when (eq action 'sparse-tree)
14301 (org-overview)
14302 (org-remove-occur-highlights))
14303 (while (let (case-fold-search)
14304 (re-search-forward re nil t))
14305 (setq org-map-continue-from nil)
14306 (catch :skip
14307 (setq todo
14308 ;; TODO: is the 1-2 difference a bug?
14309 (when (match-end 1) (match-string-no-properties 2))
14310 tags (when (match-end 4) (match-string-no-properties 4)))
14311 (goto-char (setq lspos (match-beginning 0)))
14312 (setq level (org-reduced-level (org-outline-level))
14313 category (org-get-category))
14314 (when (eq action 'agenda)
14315 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14316 ts-date (car ts-date-pair)
14317 ts-date-type (cdr ts-date-pair)))
14318 (setq i llast llast level)
14319 ;; remove tag lists from same and sublevels
14320 (while (>= i level)
14321 (when (setq entry (assoc i tags-alist))
14322 (setq tags-alist (delete entry tags-alist)))
14323 (setq i (1- i)))
14324 ;; add the next tags
14325 (when tags
14326 (setq tags (org-split-string tags ":")
14327 tags-alist
14328 (cons (cons level tags) tags-alist)))
14329 ;; compile tags for current headline
14330 (setq tags-list
14331 (if org-use-tag-inheritance
14332 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14333 tags)
14334 org-scanner-tags tags-list)
14335 (when org-use-tag-inheritance
14336 (setcdr (car tags-alist)
14337 (mapcar (lambda (x)
14338 (setq x (copy-sequence x))
14339 (org-add-prop-inherited x))
14340 (cdar tags-alist))))
14341 (when (and tags org-use-tag-inheritance
14342 (or (not (eq t org-use-tag-inheritance))
14343 org-tags-exclude-from-inheritance))
14344 ;; Selective inheritance, remove uninherited ones.
14345 (setcdr (car tags-alist)
14346 (org-remove-uninherited-tags (cdar tags-alist))))
14347 (when (and
14349 ;; eval matcher only when the todo condition is OK
14350 (and (or (not todo-only) (member todo org-not-done-keywords))
14351 (if (functionp matcher)
14352 (let ((case-fold-search t) (org-trust-scanner-tags t))
14353 (funcall matcher todo tags-list level))
14354 matcher))
14356 ;; Call the skipper, but return t if it does not
14357 ;; skip, so that the `and' form continues evaluating.
14358 (progn
14359 (unless (eq action 'sparse-tree) (org-agenda-skip))
14362 ;; Check if timestamps are deselecting this entry
14363 (or (not todo-only)
14364 (and (member todo org-not-done-keywords)
14365 (or (not org-agenda-tags-todo-honor-ignore-options)
14366 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14368 ;; select this headline
14369 (cond
14370 ((eq action 'sparse-tree)
14371 (and org-highlight-sparse-tree-matches
14372 (org-get-heading) (match-end 0)
14373 (org-highlight-new-match
14374 (match-beginning 1) (match-end 1)))
14375 (org-show-context 'tags-tree))
14376 ((eq action 'agenda)
14377 (setq txt (org-agenda-format-item
14379 (concat
14380 (if (eq org-tags-match-list-sublevels 'indented)
14381 (make-string (1- level) ?.) "")
14382 (org-get-heading))
14383 (make-string level ?\s)
14384 category
14385 tags-list)
14386 priority (org-get-priority txt))
14387 (goto-char lspos)
14388 (setq marker (org-agenda-new-marker))
14389 (org-add-props txt props
14390 'org-marker marker 'org-hd-marker marker 'org-category category
14391 'todo-state todo
14392 'ts-date ts-date
14393 'priority priority
14394 'type (concat "tagsmatch" ts-date-type))
14395 (push txt rtn))
14396 ((functionp action)
14397 (setq org-map-continue-from nil)
14398 (save-excursion
14399 (setq rtn1 (funcall action))
14400 (push rtn1 rtn)))
14401 (t (user-error "Invalid action")))
14403 ;; if we are to skip sublevels, jump to end of subtree
14404 (unless org-tags-match-list-sublevels
14405 (org-end-of-subtree t)
14406 (backward-char 1))))
14407 ;; Get the correct position from where to continue
14408 (if org-map-continue-from
14409 (goto-char org-map-continue-from)
14410 (and (= (point) lspos) (end-of-line 1)))))
14411 (when (and (eq action 'sparse-tree)
14412 (not org-sparse-tree-open-archived-trees))
14413 (org-hide-archived-subtrees (point-min) (point-max)))
14414 (nreverse rtn)))
14416 (defun org-remove-uninherited-tags (tags)
14417 "Remove all tags that are not inherited from the list TAGS."
14418 (cond
14419 ((eq org-use-tag-inheritance t)
14420 (if org-tags-exclude-from-inheritance
14421 (org-delete-all org-tags-exclude-from-inheritance tags)
14422 tags))
14423 ((not org-use-tag-inheritance) nil)
14424 ((stringp org-use-tag-inheritance)
14425 (delq nil (mapcar
14426 (lambda (x)
14427 (if (and (string-match org-use-tag-inheritance x)
14428 (not (member x org-tags-exclude-from-inheritance)))
14429 x nil))
14430 tags)))
14431 ((listp org-use-tag-inheritance)
14432 (delq nil (mapcar
14433 (lambda (x)
14434 (if (member x org-use-tag-inheritance) x nil))
14435 tags)))))
14437 (defun org-match-sparse-tree (&optional todo-only match)
14438 "Create a sparse tree according to tags string MATCH.
14440 MATCH is a string with match syntax. It can contain a selection
14441 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
14442 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
14443 those. See the manual for details.
14445 If optional argument TODO-ONLY is non-nil, only select lines that
14446 are also TODO tasks."
14447 (interactive "P")
14448 (org-agenda-prepare-buffers (list (current-buffer)))
14449 (let ((org--matcher-tags-todo-only todo-only))
14450 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14451 org--matcher-tags-todo-only)))
14453 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14455 (defvar org-cached-props nil)
14456 (defun org-cached-entry-get (pom property)
14457 (if (or (eq t org-use-property-inheritance)
14458 (and (stringp org-use-property-inheritance)
14459 (let ((case-fold-search t))
14460 (string-match-p org-use-property-inheritance property)))
14461 (and (listp org-use-property-inheritance)
14462 (member-ignore-case property org-use-property-inheritance)))
14463 ;; Caching is not possible, check it directly.
14464 (org-entry-get pom property 'inherit)
14465 ;; Get all properties, so we can do complicated checks easily.
14466 (cdr (assoc-string property
14467 (or org-cached-props
14468 (setq org-cached-props (org-entry-properties pom)))
14469 t))))
14471 (defun org-global-tags-completion-table (&optional files)
14472 "Return the list of all tags in all agenda buffer/files.
14473 Optional FILES argument is a list of files which can be used
14474 instead of the agenda files."
14475 (save-excursion
14476 (org-uniquify
14477 (delq nil
14478 (apply #'append
14479 (mapcar
14480 (lambda (file)
14481 (set-buffer (find-file-noselect file))
14482 (mapcar (lambda (x)
14483 (and (stringp (car-safe x))
14484 (list (car-safe x))))
14485 (or org-current-tag-alist (org-get-buffer-tags))))
14486 (if (car-safe files) files
14487 (org-agenda-files))))))))
14489 (defun org-make-tags-matcher (match)
14490 "Create the TAGS/TODO matcher form for the selection string MATCH.
14492 Returns a cons of the selection string MATCH and a function
14493 implementing the matcher.
14495 The matcher is to be called at an Org entry, with point on the
14496 headline, and returns non-nil if the entry matches the selection
14497 string MATCH. It must be called with three arguments: the TODO
14498 keyword at the entry (or nil if none), the list of all tags at
14499 the entry including inherited ones and the reduced level of the
14500 headline. Additionally, the category of the entry, if any, must
14501 be specified as the text property `org-category' on the headline.
14503 This function sets the variable `org--matcher-tags-todo-only' to
14504 a non-nil value if the matcher restricts matching to TODO
14505 entries, otherwise it is not touched.
14507 See also `org-scan-tags'."
14508 (unless match
14509 ;; Get a new match request, with completion against the global
14510 ;; tags table and the local tags in current buffer.
14511 (let ((org-last-tags-completion-table
14512 (org-uniquify
14513 (delq nil (append (org-get-buffer-tags)
14514 (org-global-tags-completion-table))))))
14515 (setq match
14516 (completing-read
14517 "Match: "
14518 'org-tags-completion-function nil nil nil 'org-tags-history))))
14520 (let ((match0 match)
14521 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14522 (start 0)
14523 tagsmatch todomatch tagsmatcher todomatcher)
14525 ;; Expand group tags.
14526 (setq match (org-tags-expand match))
14528 ;; Check if there is a TODO part of this match, which would be the
14529 ;; part after a "/". To make sure that this slash is not part of
14530 ;; a property value to be matched against, we also check that
14531 ;; there is no / after that slash. First, find the last slash.
14532 (let ((s 0))
14533 (while (string-match "/+" match s)
14534 (setq start (match-beginning 0))
14535 (setq s (match-end 0))))
14536 (if (and (string-match "/+" match start)
14537 (not (string-match-p "\"" match start)))
14538 ;; Match contains also a TODO-matching request.
14539 (progn
14540 (setq tagsmatch (substring match 0 (match-beginning 0)))
14541 (setq todomatch (substring match (match-end 0)))
14542 (when (string-prefix-p "!" todomatch)
14543 (setq org--matcher-tags-todo-only t)
14544 (setq todomatch (substring todomatch 1)))
14545 (when (string-match "\\`\\s-*\\'" todomatch)
14546 (setq todomatch nil)))
14547 ;; Only matching tags.
14548 (setq tagsmatch match)
14549 (setq todomatch nil))
14551 ;; Make the tags matcher.
14552 (when (org-string-nw-p tagsmatch)
14553 (let ((orlist nil)
14554 (orterms (org-split-string tagsmatch "|"))
14555 term)
14556 (while (setq term (pop orterms))
14557 (while (and (equal (substring term -1) "\\") orterms)
14558 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14559 (while (string-match re term)
14560 (let* ((rest (substring term (match-end 0)))
14561 (minus (and (match-end 1)
14562 (equal (match-string 1 term) "-")))
14563 (tag (save-match-data
14564 (replace-regexp-in-string
14565 "\\\\-" "-" (match-string 2 term))))
14566 (regexp (eq (string-to-char tag) ?{))
14567 (levelp (match-end 4))
14568 (propp (match-end 5))
14570 (cond
14571 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14572 (levelp
14573 `(,(org-op-to-function (match-string 3 term))
14574 level
14575 ,(string-to-number (match-string 4 term))))
14576 (propp
14577 (let* ((gv (pcase (upcase (match-string 5 term))
14578 ("CATEGORY"
14579 '(get-text-property (point) 'org-category))
14580 ("TODO" 'todo)
14581 (p `(org-cached-entry-get nil ,p))))
14582 (pv (match-string 7 term))
14583 (regexp (eq (string-to-char pv) ?{))
14584 (strp (eq (string-to-char pv) ?\"))
14585 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14586 (po (org-op-to-function (match-string 6 term)
14587 (if timep 'time strp))))
14588 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14589 (when timep (setq pv (org-matcher-time pv)))
14590 (cond ((and regexp (eq po 'org<>))
14591 `(not (string-match ,pv (or ,gv ""))))
14592 (regexp `(string-match ,pv (or ,gv "")))
14593 (strp `(,po (or ,gv "") ,pv))
14595 `(,po
14596 (string-to-number (or ,gv ""))
14597 ,(string-to-number pv))))))
14598 (t `(member ,tag tags-list)))))
14599 (push (if minus `(not ,mm) mm) tagsmatcher)
14600 (setq term rest)))
14601 (push `(and ,@tagsmatcher) orlist)
14602 (setq tagsmatcher nil))
14603 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14605 ;; Make the TODO matcher.
14606 (when (org-string-nw-p todomatch)
14607 (let ((orlist nil))
14608 (dolist (term (org-split-string todomatch "|"))
14609 (while (string-match re term)
14610 (let* ((minus (and (match-end 1)
14611 (equal (match-string 1 term) "-")))
14612 (kwd (match-string 2 term))
14613 (regexp (eq (string-to-char kwd) ?{))
14614 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14615 `(equal todo ,kwd))))
14616 (push (if minus `(not ,mm) mm) todomatcher))
14617 (setq term (substring term (match-end 0))))
14618 (push (if (> (length todomatcher) 1)
14619 (cons 'and todomatcher)
14620 (car todomatcher))
14621 orlist)
14622 (setq todomatcher nil))
14623 (setq todomatcher (cons 'or orlist))))
14625 ;; Return the string and function of the matcher. If no
14626 ;; tags-specific or todo-specific matcher exists, match
14627 ;; everything.
14628 (let ((matcher (if (and tagsmatcher todomatcher)
14629 `(and ,tagsmatcher ,todomatcher)
14630 (or tagsmatcher todomatcher t))))
14631 (when org--matcher-tags-todo-only
14632 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14633 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14635 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14636 "Expand group tags in MATCH.
14638 This replaces every group tag in MATCH with a regexp tag search.
14639 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14640 will be replaced like this:
14642 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14643 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14644 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14646 Replacing by a regexp preserves the structure of the match.
14647 E.g., this expansion
14649 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14651 will match anything tagged with \"Lab\" and \"Home\", or tagged
14652 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14654 A group tag in MATCH can contain regular expressions of its own.
14655 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14656 will be replaced like this:
14658 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14660 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14661 assumed to be a single group tag, and the function will return
14662 the list of tags in this group.
14664 When DOWNCASE is non-nil, expand downcased TAGS."
14665 (if org-group-tags
14666 (let* ((case-fold-search t)
14667 (stable org-mode-syntax-table)
14668 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14669 (taggroups (if downcased
14670 (mapcar (lambda (tg) (mapcar #'downcase tg))
14671 taggroups)
14672 taggroups))
14673 (taggroups-keys (mapcar #'car taggroups))
14674 (return-match (if downcased (downcase match) match))
14675 (count 0)
14676 (work-already-expanded tags-already-expanded)
14677 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14678 ;; @ and _ are allowed as word-components in tags.
14679 (modify-syntax-entry ?@ "w" stable)
14680 (modify-syntax-entry ?_ "w" stable)
14681 ;; Temporarily replace regexp-expressions in the match-expression.
14682 (while (string-match "{.+?}" return-match)
14683 (cl-incf count)
14684 (push (match-string 0 return-match) regexps-in-match)
14685 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14686 (while (and taggroups-keys
14687 (with-syntax-table stable
14688 (string-match
14689 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14690 (regexp-opt taggroups-keys) "\\>\\)")
14691 return-match)))
14692 (let* ((dir (match-string 1 return-match))
14693 (tag (match-string 2 return-match))
14694 (tag (if downcased (downcase tag) tag)))
14695 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14696 (member tag work-already-expanded))
14697 (setq tags-in-group (assoc tag taggroups))
14698 (push tag work-already-expanded)
14699 ;; Recursively expand each tag in the group, if the tag hasn't
14700 ;; already been expanded. Restore the match-data after all recursive calls.
14701 (save-match-data
14702 (let (tags-expanded)
14703 (dolist (x (cdr tags-in-group))
14704 (if (and (member x taggroups-keys)
14705 (not (member x work-already-expanded)))
14706 (setq tags-expanded
14707 (delete-dups
14708 (append
14709 (org-tags-expand x t downcased
14710 work-already-expanded)
14711 tags-expanded)))
14712 (setq tags-expanded
14713 (append (list x) tags-expanded)))
14714 (setq work-already-expanded
14715 (delete-dups
14716 (append tags-expanded
14717 work-already-expanded))))
14718 (setq tags-in-group
14719 (delete-dups (cons (car tags-in-group)
14720 tags-expanded)))))
14721 ;; Filter tag-regexps from tags.
14722 (setq regexp-in-group-escaped
14723 (delq nil (mapcar (lambda (x)
14724 (if (stringp x)
14725 (and (equal "{" (substring x 0 1))
14726 (equal "}" (substring x -1))
14729 tags-in-group))
14730 regexp-in-group
14731 (mapcar (lambda (x)
14732 (substring x 1 -1))
14733 regexp-in-group-escaped)
14734 tags-in-group
14735 (delq nil (mapcar (lambda (x)
14736 (if (stringp x)
14737 (and (not (equal "{" (substring x 0 1)))
14738 (not (equal "}" (substring x -1)))
14741 tags-in-group)))
14742 ;; If single-as-list, do no more in the while-loop.
14743 (if (not single-as-list)
14744 (progn
14745 (when regexp-in-group
14746 (setq regexp-in-group
14747 (concat "\\|"
14748 (mapconcat 'identity regexp-in-group
14749 "\\|"))))
14750 (setq tags-in-group
14751 (concat dir
14752 "{\\<"
14753 (regexp-opt tags-in-group)
14754 "\\>"
14755 regexp-in-group
14756 "}"))
14757 (when (stringp tags-in-group)
14758 (org-add-props tags-in-group '(grouptag t)))
14759 (setq return-match
14760 (replace-match tags-in-group t t return-match)))
14761 (setq tags-in-group
14762 (append regexp-in-group-escaped tags-in-group))))
14763 (setq taggroups-keys (delete tag taggroups-keys))))
14764 ;; Add the regular expressions back into the match-expression again.
14765 (while regexps-in-match
14766 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14767 (pop regexps-in-match)
14768 return-match t t))
14769 (cl-decf count))
14770 (if single-as-list
14771 (if tags-in-group tags-in-group (list return-match))
14772 return-match))
14773 (if single-as-list
14774 (list (if downcased (downcase match) match))
14775 match)))
14777 (defun org-op-to-function (op &optional stringp)
14778 "Turn an operator into the appropriate function."
14779 (setq op
14780 (cond
14781 ((equal op "<" ) '(< string< org-time<))
14782 ((equal op ">" ) '(> org-string> org-time>))
14783 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14784 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14785 ((member op '("=" "==")) '(= string= org-time=))
14786 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14787 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14789 (defun org<> (a b) (not (= a b)))
14790 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14791 (defun org-string>= (a b) (not (string< a b)))
14792 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14793 (defun org-string<> (a b) (not (string= a b)))
14794 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14795 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14796 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14797 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14798 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14799 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14800 (defun org-2ft (s)
14801 "Convert S to a floating point time.
14802 If S is already a number, just return it. If it is a string, parse
14803 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14804 (cond
14805 ((numberp s) s)
14806 ((stringp s)
14807 (condition-case nil
14808 (float-time (apply 'encode-time (org-parse-time-string s)))
14809 (error 0.)))
14810 (t 0.)))
14812 (defun org-time-today ()
14813 "Time in seconds today at 0:00.
14814 Returns the float number of seconds since the beginning of the
14815 epoch to the beginning of today (00:00)."
14816 (float-time (apply 'encode-time
14817 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14819 (defun org-matcher-time (s)
14820 "Interpret a time comparison value."
14821 (save-match-data
14822 (cond
14823 ((string= s "<now>") (float-time))
14824 ((string= s "<today>") (org-time-today))
14825 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14826 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14827 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14828 (+ (org-time-today)
14829 (* (string-to-number (match-string 1 s))
14830 (cdr (assoc (match-string 2 s)
14831 '(("d" . 86400.0) ("w" . 604800.0)
14832 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14833 (t (org-2ft s)))))
14835 (defun org-match-any-p (re list)
14836 "Does re match any element of list?"
14837 (setq list (mapcar (lambda (x) (string-match re x)) list))
14838 (delq nil list))
14840 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14841 (defvar org-tags-overlay (make-overlay 1 1))
14842 (delete-overlay org-tags-overlay)
14844 (defun org-get-local-tags-at (&optional pos)
14845 "Get a list of tags defined in the current headline."
14846 (org-get-tags-at pos 'local))
14848 (defun org-get-local-tags ()
14849 "Get a list of tags defined in the current headline."
14850 (org-get-tags-at nil 'local))
14852 (defun org-get-tags-at (&optional pos local)
14853 "Get a list of all headline tags applicable at POS.
14854 POS defaults to point. If tags are inherited, the list contains
14855 the targets in the same sequence as the headlines appear, i.e.
14856 the tags of the current headline come last.
14857 When LOCAL is non-nil, only return tags from the current headline,
14858 ignore inherited ones."
14859 (interactive)
14860 (if (and org-trust-scanner-tags
14861 (or (not pos) (equal pos (point)))
14862 (not local))
14863 org-scanner-tags
14864 (let (tags ltags lastpos parent)
14865 (save-excursion
14866 (save-restriction
14867 (widen)
14868 (goto-char (or pos (point)))
14869 (save-match-data
14870 (catch 'done
14871 (condition-case nil
14872 (progn
14873 (org-back-to-heading t)
14874 (while (not (equal lastpos (point)))
14875 (setq lastpos (point))
14876 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14877 (setq ltags (org-split-string
14878 (match-string-no-properties 1) ":"))
14879 (when parent
14880 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14881 (setq tags (append
14882 (if parent
14883 (org-remove-uninherited-tags ltags)
14884 ltags)
14885 tags)))
14886 (or org-use-tag-inheritance (throw 'done t))
14887 (when local (throw 'done t))
14888 (or (org-up-heading-safe) (error nil))
14889 (setq parent t)))
14890 (error nil)))))
14891 (if local
14892 tags
14893 (reverse (delete-dups
14894 (reverse (append
14895 (org-remove-uninherited-tags
14896 org-file-tags)
14897 tags)))))))))
14899 (defun org-add-prop-inherited (s)
14900 (add-text-properties 0 (length s) '(inherited t) s)
14903 (defun org-toggle-tag (tag &optional onoff)
14904 "Toggle the tag TAG for the current line.
14905 If ONOFF is `on' or `off', don't toggle but set to this state."
14906 (let (res current)
14907 (save-excursion
14908 (org-back-to-heading t)
14909 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14910 (point-at-eol) t)
14911 (progn
14912 (setq current (match-string 1))
14913 (replace-match ""))
14914 (setq current ""))
14915 (setq current (nreverse (org-split-string current ":")))
14916 (cond
14917 ((eq onoff 'on)
14918 (setq res t)
14919 (or (member tag current) (push tag current)))
14920 ((eq onoff 'off)
14921 (or (not (member tag current)) (setq current (delete tag current))))
14922 (t (if (member tag current)
14923 (setq current (delete tag current))
14924 (setq res t)
14925 (push tag current))))
14926 (end-of-line 1)
14927 (if current
14928 (progn
14929 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14930 (org-set-tags nil t))
14931 (delete-horizontal-space))
14932 (run-hooks 'org-after-tags-change-hook))
14933 res))
14935 (defun org--align-tags-here (to-col)
14936 "Align tags on the current headline to TO-COL.
14937 Assume point is on a headline."
14938 (let ((pos (point)))
14939 (beginning-of-line)
14940 (if (or (not (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14941 (>= pos (match-beginning 2)))
14942 ;; No tags or point within tags: do not align.
14943 (goto-char pos)
14944 (goto-char (match-beginning 1))
14945 (let ((shift (max (- (if (>= to-col 0) to-col
14946 (- (abs to-col) (string-width (match-string 2))))
14947 (current-column))
14948 1)))
14949 (replace-match (make-string shift ?\s) nil nil nil 1)
14950 ;; Preserve initial position, if possible. In any case, stop
14951 ;; before tags.
14952 (when (< pos (point)) (goto-char pos))))))
14954 (defun org-set-tags-command (&optional arg just-align)
14955 "Call the set-tags command for the current entry."
14956 (interactive "P")
14957 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14958 (org-set-tags arg just-align)
14959 (save-excursion
14960 (unless (and (org-region-active-p)
14961 org-loop-over-headlines-in-active-region)
14962 (org-back-to-heading t))
14963 (org-set-tags arg just-align))))
14965 (defun org-set-tags-to (data)
14966 "Set the tags of the current entry to DATA, replacing the current tags.
14967 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14968 If DATA is nil or the empty string, any tags will be removed."
14969 (interactive "sTags: ")
14970 (setq data
14971 (cond
14972 ((eq data nil) "")
14973 ((equal data "") "")
14974 ((stringp data)
14975 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14976 ":"))
14977 ((listp data)
14978 (concat ":" (mapconcat 'identity data ":") ":"))))
14979 (when data
14980 (save-excursion
14981 (org-back-to-heading t)
14982 (when (let ((case-fold-search nil))
14983 (looking-at org-complex-heading-regexp))
14984 (if (match-end 5)
14985 (progn
14986 (goto-char (match-beginning 5))
14987 (insert data)
14988 (delete-region (point) (point-at-eol))
14989 (org-set-tags nil 'align))
14990 (goto-char (point-at-eol))
14991 (insert " " data)
14992 (org-set-tags nil 'align)))
14993 (beginning-of-line 1)
14994 (when (looking-at ".*?\\([ \t]+\\)$")
14995 (delete-region (match-beginning 1) (match-end 1))))))
14997 (defun org-align-all-tags ()
14998 "Align the tags in all headings."
14999 (interactive)
15000 (save-excursion
15001 (or (ignore-errors (org-back-to-heading t))
15002 (outline-next-heading))
15003 (if (org-at-heading-p)
15004 (org-set-tags t)
15005 (message "No headings"))))
15007 (defvar org-indent-indentation-per-level)
15008 (defun org-set-tags (&optional arg just-align)
15009 "Set the tags for the current headline.
15010 With prefix ARG, realign all tags in headings in the current buffer.
15011 When JUST-ALIGN is non-nil, only align tags."
15012 (interactive "P")
15013 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15014 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15015 'region-start-level
15016 'region))
15017 org-loop-over-headlines-in-active-region)
15018 (org-map-entries
15019 ;; We don't use ARG and JUST-ALIGN here because these args
15020 ;; are not useful when looping over headlines.
15021 #'org-set-tags
15022 org-loop-over-headlines-in-active-region
15024 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15025 (let ((org-setting-tags t))
15026 (if arg
15027 (save-excursion
15028 (goto-char (point-min))
15029 (while (re-search-forward org-outline-regexp-bol nil t)
15030 (org-set-tags nil t)
15031 (end-of-line))
15032 (message "All tags realigned to column %d" org-tags-column))
15033 (let* ((current (org-get-tags-string))
15034 (tags
15035 (if just-align current
15036 ;; Get a new set of tags from the user.
15037 (save-excursion
15038 (let* ((seen)
15039 (table
15040 (setq
15041 org-last-tags-completion-table
15042 ;; Uniquify tags in alists, yet preserve
15043 ;; structure (i.e., keywords).
15044 (delq nil
15045 (mapcar
15046 (lambda (pair)
15047 (let ((head (car pair)))
15048 (cond ((symbolp head) pair)
15049 ((member head seen) nil)
15050 (t (push head seen)
15051 pair))))
15052 (append
15053 (or org-current-tag-alist
15054 (org-get-buffer-tags))
15055 (and
15056 org-complete-tags-always-offer-all-agenda-tags
15057 (org-global-tags-completion-table
15058 (org-agenda-files))))))))
15059 (current-tags (org-split-string current ":"))
15060 (inherited-tags
15061 (nreverse (nthcdr (length current-tags)
15062 (nreverse (org-get-tags-at))))))
15063 (replace-regexp-in-string
15064 "\\([-+&]+\\|,\\)"
15066 (if (or (eq t org-use-fast-tag-selection)
15067 (and org-use-fast-tag-selection
15068 (delq nil (mapcar #'cdr table))))
15069 (org-fast-tag-selection
15070 current-tags inherited-tags table
15071 (and org-fast-tag-selection-include-todo
15072 org-todo-key-alist))
15073 (let ((org-add-colon-after-tag-completion
15074 (< 1 (length table))))
15075 (org-trim
15076 (completing-read
15077 "Tags: "
15078 #'org-tags-completion-function
15079 nil nil current 'org-tags-history))))))))))
15081 (when org-tags-sort-function
15082 (setq tags
15083 (mapconcat
15084 #'identity
15085 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15086 org-tags-sort-function)
15087 ":")))
15089 (if (or (string= ":" tags)
15090 (string= "::" tags))
15091 (setq tags ""))
15092 (if (not (org-string-nw-p tags)) (setq tags "")
15093 (unless (string-suffix-p ":" tags) (setq tags (concat tags ":")))
15094 (unless (string-prefix-p ":" tags) (setq tags (concat ":" tags))))
15096 ;; Insert new tags at the correct column.
15097 (unless (equal current tags)
15098 (save-excursion
15099 (beginning-of-line)
15100 (let ((case-fold-search nil))
15101 (looking-at org-complex-heading-regexp))
15102 ;; Remove current tags, if any.
15103 (when (match-end 5) (replace-match "" nil nil nil 5))
15104 ;; Insert new tags, if any. Otherwise, remove trailing
15105 ;; white spaces.
15106 (end-of-line)
15107 (if (not (equal tags ""))
15108 ;; When text is being inserted on an invisible
15109 ;; region boundary, it can be inadvertently sucked
15110 ;; into invisibility.
15111 (outline-flag-region (point) (progn (insert " " tags) (point)) nil)
15112 (skip-chars-backward " \t")
15113 (delete-region (point) (line-end-position)))))
15114 ;; Align tags, if any. Fix tags column if `org-indent-mode'
15115 ;; is on.
15116 (unless (equal tags "")
15117 (let* ((level (save-excursion
15118 (beginning-of-line)
15119 (skip-chars-forward "\\*")))
15120 (offset (if (bound-and-true-p org-indent-mode)
15121 (* (1- org-indent-indentation-per-level)
15122 (1- level))
15124 (tags-column
15125 (+ org-tags-column
15126 (if (> org-tags-column 0) (- offset) offset))))
15127 (org--align-tags-here tags-column))))
15128 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15130 (defun org-change-tag-in-region (beg end tag off)
15131 "Add or remove TAG for each entry in the region.
15132 This works in the agenda, and also in an Org buffer."
15133 (interactive
15134 (list (region-beginning) (region-end)
15135 (let ((org-last-tags-completion-table
15136 (if (derived-mode-p 'org-mode)
15137 (org-uniquify
15138 (delq nil (append (org-get-buffer-tags)
15139 (org-global-tags-completion-table))))
15140 (org-global-tags-completion-table))))
15141 (completing-read
15142 "Tag: " 'org-tags-completion-function nil nil nil
15143 'org-tags-history))
15144 (progn
15145 (message "[s]et or [r]emove? ")
15146 (equal (read-char-exclusive) ?r))))
15147 (when (fboundp 'deactivate-mark) (deactivate-mark))
15148 (let ((agendap (equal major-mode 'org-agenda-mode))
15149 l1 l2 m buf pos newhead (cnt 0))
15150 (goto-char end)
15151 (setq l2 (1- (org-current-line)))
15152 (goto-char beg)
15153 (setq l1 (org-current-line))
15154 (cl-loop for l from l1 to l2 do
15155 (org-goto-line l)
15156 (setq m (get-text-property (point) 'org-hd-marker))
15157 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15158 (and agendap m))
15159 (setq buf (if agendap (marker-buffer m) (current-buffer))
15160 pos (if agendap m (point)))
15161 (with-current-buffer buf
15162 (save-excursion
15163 (save-restriction
15164 (goto-char pos)
15165 (setq cnt (1+ cnt))
15166 (org-toggle-tag tag (if off 'off 'on))
15167 (setq newhead (org-get-heading)))))
15168 (and agendap (org-agenda-change-all-lines newhead m))))
15169 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15171 (defun org-tags-completion-function (string _predicate &optional flag)
15172 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15173 (confirm (lambda (x) (stringp (car x)))))
15174 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15175 (setq s1 (match-string 1 string)
15176 s2 (match-string 2 string))
15177 (setq s1 "" s2 string))
15178 (cond
15179 ((eq flag nil)
15180 ;; try completion
15181 (setq rtn (try-completion s2 ctable confirm))
15182 (when (stringp rtn)
15183 (setq rtn
15184 (concat s1 s2 (substring rtn (length s2))
15185 (if (and org-add-colon-after-tag-completion
15186 (assoc rtn ctable))
15187 ":" ""))))
15188 rtn)
15189 ((eq flag t)
15190 ;; all-completions
15191 (all-completions s2 ctable confirm))
15192 ((eq flag 'lambda)
15193 ;; exact match?
15194 (assoc s2 ctable)))))
15196 (defun org-fast-tag-insert (kwd tags face &optional end)
15197 "Insert KDW, and the TAGS, the latter with face FACE.
15198 Also insert END."
15199 (insert (format "%-12s" (concat kwd ":"))
15200 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15201 (or end "")))
15203 (defun org-fast-tag-show-exit (flag)
15204 (save-excursion
15205 (org-goto-line 3)
15206 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15207 (replace-match ""))
15208 (when flag
15209 (end-of-line 1)
15210 (org-move-to-column (- (window-width) 19) t)
15211 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15213 (defun org-set-current-tags-overlay (current prefix)
15214 "Add an overlay to CURRENT tag with PREFIX."
15215 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15216 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15217 (org-overlay-display org-tags-overlay (concat prefix s))))
15219 (defvar org-last-tag-selection-key nil)
15220 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15221 "Fast tag selection with single keys.
15222 CURRENT is the current list of tags in the headline, INHERITED is the
15223 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15224 possibly with grouping information. TODO-TABLE is a similar table with
15225 TODO keywords, should these have keys assigned to them.
15226 If the keys are nil, a-z are automatically assigned.
15227 Returns the new tags string, or nil to not change the current settings."
15228 (let* ((fulltable (append table todo-table))
15229 (maxlen (apply 'max (mapcar
15230 (lambda (x)
15231 (if (stringp (car x)) (string-width (car x)) 0))
15232 fulltable)))
15233 (buf (current-buffer))
15234 (expert (eq org-fast-tag-selection-single-key 'expert))
15235 (buffer-tags nil)
15236 (fwidth (+ maxlen 3 1 3))
15237 (ncol (/ (- (window-width) 4) fwidth))
15238 (i-face 'org-done)
15239 (c-face 'org-todo)
15240 tg cnt e c char c1 c2 ntable tbl rtn
15241 ov-start ov-end ov-prefix
15242 (exit-after-next org-fast-tag-selection-single-key)
15243 (done-keywords org-done-keywords)
15244 groups ingroup intaggroup)
15245 (save-excursion
15246 (beginning-of-line 1)
15247 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15248 (setq ov-start (match-beginning 1)
15249 ov-end (match-end 1)
15250 ov-prefix "")
15251 (setq ov-start (1- (point-at-eol))
15252 ov-end (1+ ov-start))
15253 (skip-chars-forward "^\n\r")
15254 (setq ov-prefix
15255 (concat
15256 (buffer-substring (1- (point)) (point))
15257 (if (> (current-column) org-tags-column)
15259 (make-string (- org-tags-column (current-column)) ?\ ))))))
15260 (move-overlay org-tags-overlay ov-start ov-end)
15261 (save-window-excursion
15262 (if expert
15263 (set-buffer (get-buffer-create " *Org tags*"))
15264 (delete-other-windows)
15265 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15266 (org-switch-to-buffer-other-window " *Org tags*"))
15267 (erase-buffer)
15268 (setq-local org-done-keywords done-keywords)
15269 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15270 (org-fast-tag-insert "Current" current c-face "\n\n")
15271 (org-fast-tag-show-exit exit-after-next)
15272 (org-set-current-tags-overlay current ov-prefix)
15273 (setq tbl fulltable char ?a cnt 0)
15274 (while (setq e (pop tbl))
15275 (cond
15276 ((eq (car e) :startgroup)
15277 (push '() groups) (setq ingroup t)
15278 (unless (zerop cnt)
15279 (setq cnt 0)
15280 (insert "\n"))
15281 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15282 ((eq (car e) :endgroup)
15283 (setq ingroup nil cnt 0)
15284 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15285 ((eq (car e) :startgrouptag)
15286 (setq intaggroup t)
15287 (unless (zerop cnt)
15288 (setq cnt 0)
15289 (insert "\n"))
15290 (insert "[ "))
15291 ((eq (car e) :endgrouptag)
15292 (setq intaggroup nil cnt 0)
15293 (insert "]\n"))
15294 ((equal e '(:newline))
15295 (unless (zerop cnt)
15296 (setq cnt 0)
15297 (insert "\n")
15298 (setq e (car tbl))
15299 (while (equal (car tbl) '(:newline))
15300 (insert "\n")
15301 (setq tbl (cdr tbl)))))
15302 ((equal e '(:grouptags)) (insert " : "))
15304 (setq tg (copy-sequence (car e)) c2 nil)
15305 (if (cdr e)
15306 (setq c (cdr e))
15307 ;; automatically assign a character.
15308 (setq c1 (string-to-char
15309 (downcase (substring
15310 tg (if (= (string-to-char tg) ?@) 1 0)))))
15311 (if (or (rassoc c1 ntable) (rassoc c1 table))
15312 (while (or (rassoc char ntable) (rassoc char table))
15313 (setq char (1+ char)))
15314 (setq c2 c1))
15315 (setq c (or c2 char)))
15316 (when ingroup (push tg (car groups)))
15317 (setq tg (org-add-props tg nil 'face
15318 (cond
15319 ((not (assoc tg table))
15320 (org-get-todo-face tg))
15321 ((member tg current) c-face)
15322 ((member tg inherited) i-face))))
15323 (when (equal (caar tbl) :grouptags)
15324 (org-add-props tg nil 'face 'org-tag-group))
15325 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15326 (insert "[" c "] " tg (make-string
15327 (- fwidth 4 (length tg)) ?\ ))
15328 (push (cons tg c) ntable)
15329 (when (= (cl-incf cnt) ncol)
15330 (insert "\n")
15331 (when (or ingroup intaggroup) (insert " "))
15332 (setq cnt 0)))))
15333 (setq ntable (nreverse ntable))
15334 (insert "\n")
15335 (goto-char (point-min))
15336 (unless expert (org-fit-window-to-buffer))
15337 (setq rtn
15338 (catch 'exit
15339 (while t
15340 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15341 (if (not groups) "no " "")
15342 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15343 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15344 (setq org-last-tag-selection-key c)
15345 (cond
15346 ((= c ?\r) (throw 'exit t))
15347 ((= c ?!)
15348 (setq groups (not groups))
15349 (goto-char (point-min))
15350 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15351 ((= c ?\C-c)
15352 (if (not expert)
15353 (org-fast-tag-show-exit
15354 (setq exit-after-next (not exit-after-next)))
15355 (setq expert nil)
15356 (delete-other-windows)
15357 (set-window-buffer (split-window-vertically) " *Org tags*")
15358 (org-switch-to-buffer-other-window " *Org tags*")
15359 (org-fit-window-to-buffer)))
15360 ((or (= c ?\C-g)
15361 (and (= c ?q) (not (rassoc c ntable))))
15362 (delete-overlay org-tags-overlay)
15363 (setq quit-flag t))
15364 ((= c ?\ )
15365 (setq current nil)
15366 (when exit-after-next (setq exit-after-next 'now)))
15367 ((= c ?\t)
15368 (condition-case nil
15369 (setq tg (completing-read
15370 "Tag: "
15371 (or buffer-tags
15372 (with-current-buffer buf
15373 (setq buffer-tags
15374 (org-get-buffer-tags))))))
15375 (quit (setq tg "")))
15376 (when (string-match "\\S-" tg)
15377 (cl-pushnew (list tg) buffer-tags :test #'equal)
15378 (if (member tg current)
15379 (setq current (delete tg current))
15380 (push tg current)))
15381 (when exit-after-next (setq exit-after-next 'now)))
15382 ((setq e (rassoc c todo-table) tg (car e))
15383 (with-current-buffer buf
15384 (save-excursion (org-todo tg)))
15385 (when exit-after-next (setq exit-after-next 'now)))
15386 ((setq e (rassoc c ntable) tg (car e))
15387 (if (member tg current)
15388 (setq current (delete tg current))
15389 (cl-loop for g in groups do
15390 (when (member tg g)
15391 (dolist (x g) (setq current (delete x current)))))
15392 (push tg current))
15393 (when exit-after-next (setq exit-after-next 'now))))
15395 ;; Create a sorted list
15396 (setq current
15397 (sort current
15398 (lambda (a b)
15399 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15400 (when (eq exit-after-next 'now) (throw 'exit t))
15401 (goto-char (point-min))
15402 (beginning-of-line 2)
15403 (delete-region (point) (point-at-eol))
15404 (org-fast-tag-insert "Current" current c-face)
15405 (org-set-current-tags-overlay current ov-prefix)
15406 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15407 (setq tg (match-string 1))
15408 (add-text-properties
15409 (match-beginning 1) (match-end 1)
15410 (list 'face
15411 (cond
15412 ((member tg current) c-face)
15413 ((member tg inherited) i-face)
15414 (t (get-text-property (match-beginning 1) 'face))))))
15415 (goto-char (point-min)))))
15416 (delete-overlay org-tags-overlay)
15417 (if rtn
15418 (mapconcat 'identity current ":")
15419 nil))))
15421 (defun org-get-tags-string ()
15422 "Get the TAGS string in the current headline."
15423 (unless (org-at-heading-p t)
15424 (user-error "Not on a heading"))
15425 (save-excursion
15426 (beginning-of-line 1)
15427 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15428 (match-string-no-properties 1)
15429 "")))
15431 (defun org-get-tags ()
15432 "Get the list of tags specified in the current headline."
15433 (org-split-string (org-get-tags-string) ":"))
15435 (defun org-get-buffer-tags ()
15436 "Get a table of all tags used in the buffer, for completion."
15437 (org-with-wide-buffer
15438 (goto-char (point-min))
15439 (let ((tag-re (concat org-outline-regexp-bol
15440 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15441 tags)
15442 (while (re-search-forward tag-re nil t)
15443 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15444 (push tag tags)))
15445 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15447 ;;;; The mapping API
15449 (defvar org-agenda-skip-comment-trees)
15450 (defvar org-agenda-skip-function)
15451 (defun org-map-entries (func &optional match scope &rest skip)
15452 "Call FUNC at each headline selected by MATCH in SCOPE.
15454 FUNC is a function or a lisp form. The function will be called without
15455 arguments, with the cursor positioned at the beginning of the headline.
15456 The return values of all calls to the function will be collected and
15457 returned as a list.
15459 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15460 does not need to preserve point. After evaluation, the cursor will be
15461 moved to the end of the line (presumably of the headline of the
15462 processed entry) and search continues from there. Under some
15463 circumstances, this may not produce the wanted results. For example,
15464 if you have removed (e.g. archived) the current (sub)tree it could
15465 mean that the next entry will be skipped entirely. In such cases, you
15466 can specify the position from where search should continue by making
15467 FUNC set the variable `org-map-continue-from' to the desired buffer
15468 position.
15470 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15471 Only headlines that are matched by this query will be considered during
15472 the iteration. When MATCH is nil or t, all headlines will be
15473 visited by the iteration.
15475 SCOPE determines the scope of this command. It can be any of:
15477 nil The current buffer, respecting the restriction if any
15478 tree The subtree started with the entry at point
15479 region The entries within the active region, if any
15480 region-start-level
15481 The entries within the active region, but only those at
15482 the same level than the first one.
15483 file The current buffer, without restriction
15484 file-with-archives
15485 The current buffer, and any archives associated with it
15486 agenda All agenda files
15487 agenda-with-archives
15488 All agenda files with any archive files associated with them
15489 \(file1 file2 ...)
15490 If this is a list, all files in the list will be scanned
15492 The remaining args are treated as settings for the skipping facilities of
15493 the scanner. The following items can be given here:
15495 archive skip trees with the archive tag
15496 comment skip trees with the COMMENT keyword
15497 function or Emacs Lisp form:
15498 will be used as value for `org-agenda-skip-function', so
15499 whenever the function returns a position, FUNC will not be
15500 called for that entry and search will continue from the
15501 position returned
15503 If your function needs to retrieve the tags including inherited tags
15504 at the *current* entry, you can use the value of the variable
15505 `org-scanner-tags' which will be much faster than getting the value
15506 with `org-get-tags-at'. If your function gets properties with
15507 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15508 to t around the call to `org-entry-properties' to get the same speedup.
15509 Note that if your function moves around to retrieve tags and properties at
15510 a *different* entry, you cannot use these techniques."
15511 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15512 (not (org-region-active-p)))
15513 (let* ((org-agenda-archives-mode nil) ; just to make sure
15514 (org-agenda-skip-archived-trees (memq 'archive skip))
15515 (org-agenda-skip-comment-trees (memq 'comment skip))
15516 (org-agenda-skip-function
15517 (car (org-delete-all '(comment archive) skip)))
15518 (org-tags-match-list-sublevels t)
15519 (start-level (eq scope 'region-start-level))
15520 matcher res
15521 org-todo-keywords-for-agenda
15522 org-done-keywords-for-agenda
15523 org-todo-keyword-alist-for-agenda
15524 org-tag-alist-for-agenda
15525 org--matcher-tags-todo-only)
15527 (cond
15528 ((eq match t) (setq matcher t))
15529 ((eq match nil) (setq matcher t))
15530 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15532 (save-excursion
15533 (save-restriction
15534 (cond ((eq scope 'tree)
15535 (org-back-to-heading t)
15536 (org-narrow-to-subtree)
15537 (setq scope nil))
15538 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15539 (org-region-active-p))
15540 ;; If needed, set start-level to a string like "2"
15541 (when start-level
15542 (save-excursion
15543 (goto-char (region-beginning))
15544 (unless (org-at-heading-p) (outline-next-heading))
15545 (setq start-level (org-current-level))))
15546 (narrow-to-region (region-beginning)
15547 (save-excursion
15548 (goto-char (region-end))
15549 (unless (and (bolp) (org-at-heading-p))
15550 (outline-next-heading))
15551 (point)))
15552 (setq scope nil)))
15554 (if (not scope)
15555 (progn
15556 (org-agenda-prepare-buffers
15557 (and buffer-file-name (list buffer-file-name)))
15558 (setq res
15559 (org-scan-tags
15560 func matcher org--matcher-tags-todo-only start-level)))
15561 ;; Get the right scope
15562 (cond
15563 ((and scope (listp scope) (symbolp (car scope)))
15564 (setq scope (eval scope)))
15565 ((eq scope 'agenda)
15566 (setq scope (org-agenda-files t)))
15567 ((eq scope 'agenda-with-archives)
15568 (setq scope (org-agenda-files t))
15569 (setq scope (org-add-archive-files scope)))
15570 ((eq scope 'file)
15571 (setq scope (and buffer-file-name (list buffer-file-name))))
15572 ((eq scope 'file-with-archives)
15573 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15574 (org-agenda-prepare-buffers scope)
15575 (dolist (file scope)
15576 (with-current-buffer (org-find-base-buffer-visiting file)
15577 (org-with-wide-buffer
15578 (goto-char (point-min))
15579 (setq res
15580 (append
15582 (org-scan-tags
15583 func matcher org--matcher-tags-todo-only)))))))))
15584 res)))
15586 ;;; Properties API
15588 (defconst org-special-properties
15589 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15590 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15591 "The special properties valid in Org mode.
15592 These are properties that are not defined in the property drawer,
15593 but in some other way.")
15595 (defconst org-default-properties
15596 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15597 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15598 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15599 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15600 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15601 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15602 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15603 "Some properties that are used by Org mode for various purposes.
15604 Being in this list makes sure that they are offered for completion.")
15606 (defun org--valid-property-p (property)
15607 "Non nil when string PROPERTY is a valid property name."
15608 (not
15609 (or (equal property "")
15610 (string-match-p "\\s-" property))))
15612 (defun org--update-property-plist (key val props)
15613 "Associate KEY to VAL in alist PROPS.
15614 Modifications are made by side-effect. Return new alist."
15615 (let* ((appending (string= (substring key -1) "+"))
15616 (key (if appending (substring key 0 -1) key))
15617 (old (assoc-string key props t)))
15618 (if (not old) (cons (cons key val) props)
15619 (setcdr old (if appending (concat (cdr old) " " val) val))
15620 props)))
15622 (defun org-get-property-block (&optional beg force)
15623 "Return the (beg . end) range of the body of the property drawer.
15624 BEG is the beginning of the current subtree, or of the part
15625 before the first headline. If it is not given, it will be found.
15626 If the drawer does not exist, create it if FORCE is non-nil, or
15627 return nil."
15628 (org-with-wide-buffer
15629 (when beg (goto-char beg))
15630 (unless (org-before-first-heading-p)
15631 (let ((beg (cond (beg)
15632 ((or (not (featurep 'org-inlinetask))
15633 (org-inlinetask-in-task-p))
15634 (org-back-to-heading t))
15635 (t (org-with-limited-levels (org-back-to-heading t))))))
15636 (forward-line)
15637 (when (looking-at-p org-planning-line-re) (forward-line))
15638 (cond ((looking-at org-property-drawer-re)
15639 (forward-line)
15640 (cons (point) (progn (goto-char (match-end 0))
15641 (line-beginning-position))))
15642 (force
15643 (goto-char beg)
15644 (org-insert-property-drawer)
15645 (let ((pos (save-excursion (search-forward ":END:")
15646 (line-beginning-position))))
15647 (cons pos pos))))))))
15649 (defun org-at-property-p ()
15650 "Non-nil when point is inside a property drawer.
15651 See `org-property-re' for match data, if applicable."
15652 (save-excursion
15653 (beginning-of-line)
15654 (and (looking-at org-property-re)
15655 (let ((property-drawer (save-match-data (org-get-property-block))))
15656 (and property-drawer
15657 (>= (point) (car property-drawer))
15658 (< (point) (cdr property-drawer)))))))
15660 (defun org-property-action ()
15661 "Do an action on properties."
15662 (interactive)
15663 (unless (org-at-property-p) (user-error "Not at a property"))
15664 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15665 (let ((c (read-char-exclusive)))
15666 (cl-case c
15667 (?s (call-interactively #'org-set-property))
15668 (?d (call-interactively #'org-delete-property))
15669 (?D (call-interactively #'org-delete-property-globally))
15670 (?c (call-interactively #'org-compute-property-at-point))
15671 (otherwise (user-error "No such property action %c" c)))))
15673 (defun org-inc-effort ()
15674 "Increment the value of the effort property in the current entry."
15675 (interactive)
15676 (org-set-effort nil t))
15678 (defvar org-clock-effort) ; Defined in org-clock.el.
15679 (defvar org-clock-current-task) ; Defined in org-clock.el.
15680 (defun org-set-effort (&optional value increment)
15681 "Set the effort property of the current entry.
15682 With numerical prefix arg, use the nth allowed value, 0 stands for the
15683 10th allowed value.
15685 When INCREMENT is non-nil, set the property to the next allowed value."
15686 (interactive "P")
15687 (when (equal value 0) (setq value 10))
15688 (let* ((completion-ignore-case t)
15689 (prop org-effort-property)
15690 (cur (org-entry-get nil prop))
15691 (allowed (org-property-get-allowed-values nil prop 'table))
15692 (existing (mapcar 'list (org-property-values prop)))
15693 (heading (nth 4 (org-heading-components)))
15695 (val (cond
15696 ((stringp value) value)
15697 ((and allowed (integerp value))
15698 (or (car (nth (1- value) allowed))
15699 (car (org-last allowed))))
15700 ((and allowed increment)
15701 (or (cl-caadr (member (list cur) allowed))
15702 (user-error "Allowed effort values are not set")))
15703 (allowed
15704 (message "Select 1-9,0, [RET%s]: %s"
15705 (if cur (concat "=" cur) "")
15706 (mapconcat 'car allowed " "))
15707 (setq rpl (read-char-exclusive))
15708 (if (equal rpl ?\r)
15710 (setq rpl (- rpl ?0))
15711 (when (equal rpl 0) (setq rpl 10))
15712 (if (and (> rpl 0) (<= rpl (length allowed)))
15713 (car (nth (1- rpl) allowed))
15714 (org-completing-read "Effort: " allowed nil))))
15716 (org-completing-read
15717 (concat "Effort" (and cur (string-match "\\S-" cur)
15718 (concat " [" cur "]"))
15719 ": ")
15720 existing nil nil "" nil cur)))))
15721 (unless (equal (org-entry-get nil prop) val)
15722 (org-entry-put nil prop val))
15723 (org-refresh-property
15724 '((effort . identity)
15725 (effort-minutes . org-duration-string-to-minutes))
15726 val)
15727 (when (equal heading (bound-and-true-p org-clock-current-task))
15728 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15729 (org-clock-update-mode-line))
15730 (message "%s is now %s" prop val)))
15732 (defun org-entry-properties (&optional pom which)
15733 "Get all properties of the current entry.
15735 When POM is a buffer position, get all properties from the entry
15736 there instead.
15738 This includes the TODO keyword, the tags, time strings for
15739 deadline, scheduled, and clocking, and any additional properties
15740 defined in the entry.
15742 If WHICH is nil or `all', get all properties. If WHICH is
15743 `special' or `standard', only get that subclass. If WHICH is
15744 a string, only get that property.
15746 Return value is an alist. Keys are properties, as upcased
15747 strings."
15748 (org-with-point-at pom
15749 (when (and (derived-mode-p 'org-mode)
15750 (ignore-errors (org-back-to-heading t)))
15751 (catch 'exit
15752 (let* ((beg (point))
15753 (specific (and (stringp which) (upcase which)))
15754 (which (cond ((not specific) which)
15755 ((member specific org-special-properties) 'special)
15756 (t 'standard)))
15757 props)
15758 ;; Get the special properties, like TODO and TAGS.
15759 (when (memq which '(nil all special))
15760 (when (or (not specific) (string= specific "CLOCKSUM"))
15761 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15762 (when clocksum
15763 (push (cons "CLOCKSUM"
15764 (org-minutes-to-clocksum-string clocksum))
15765 props)))
15766 (when specific (throw 'exit props)))
15767 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15768 (let ((clocksumt (get-text-property (point)
15769 :org-clock-minutes-today)))
15770 (when clocksumt
15771 (push (cons "CLOCKSUM_T"
15772 (org-minutes-to-clocksum-string clocksumt))
15773 props)))
15774 (when specific (throw 'exit props)))
15775 (when (or (not specific) (string= specific "ITEM"))
15776 (let ((case-fold-search nil))
15777 (when (looking-at org-complex-heading-regexp)
15778 (push (cons "ITEM"
15779 (let ((title (match-string-no-properties 4)))
15780 (if (org-string-nw-p title)
15781 (org-remove-tabs title)
15782 "")))
15783 props)))
15784 (when specific (throw 'exit props)))
15785 (when (or (not specific) (string= specific "TODO"))
15786 (let ((case-fold-search nil))
15787 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15788 (push (cons "TODO" (match-string-no-properties 2)) props)))
15789 (when specific (throw 'exit props)))
15790 (when (or (not specific) (string= specific "PRIORITY"))
15791 (push (cons "PRIORITY"
15792 (if (looking-at org-priority-regexp)
15793 (match-string-no-properties 2)
15794 (char-to-string org-default-priority)))
15795 props)
15796 (when specific (throw 'exit props)))
15797 (when (or (not specific) (string= specific "FILE"))
15798 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15799 props)
15800 (when specific (throw 'exit props)))
15801 (when (or (not specific) (string= specific "TAGS"))
15802 (let ((value (org-string-nw-p (org-get-tags-string))))
15803 (when value (push (cons "TAGS" value) props)))
15804 (when specific (throw 'exit props)))
15805 (when (or (not specific) (string= specific "ALLTAGS"))
15806 (let ((value (org-get-tags-at)))
15807 (when value
15808 (push (cons "ALLTAGS"
15809 (format ":%s:" (mapconcat #'identity value ":")))
15810 props)))
15811 (when specific (throw 'exit props)))
15812 (when (or (not specific) (string= specific "BLOCKED"))
15813 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15814 (when specific (throw 'exit props)))
15815 (when (or (not specific)
15816 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15817 (forward-line)
15818 (when (looking-at-p org-planning-line-re)
15819 (end-of-line)
15820 (let ((bol (line-beginning-position))
15821 ;; Backward compatibility: time keywords used to
15822 ;; be configurable (before 8.3). Make sure we
15823 ;; get the correct keyword.
15824 (key-assoc `(("CLOSED" . ,org-closed-string)
15825 ("DEADLINE" . ,org-deadline-string)
15826 ("SCHEDULED" . ,org-scheduled-string))))
15827 (dolist (pair (if specific (list (assoc specific key-assoc))
15828 key-assoc))
15829 (save-excursion
15830 (when (search-backward (cdr pair) bol t)
15831 (goto-char (match-end 0))
15832 (skip-chars-forward " \t")
15833 (and (looking-at org-ts-regexp-both)
15834 (push (cons (car pair)
15835 (match-string-no-properties 0))
15836 props)))))))
15837 (when specific (throw 'exit props)))
15838 (when (or (not specific)
15839 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15840 (let ((find-ts
15841 (lambda (end ts)
15842 ;; Fix next time-stamp before END. TS is the
15843 ;; list of time-stamps found so far.
15844 (let ((ts ts)
15845 (regexp (cond
15846 ((string= specific "TIMESTAMP")
15847 org-ts-regexp)
15848 ((string= specific "TIMESTAMP_IA")
15849 org-ts-regexp-inactive)
15850 ((assoc "TIMESTAMP_IA" ts)
15851 org-ts-regexp)
15852 ((assoc "TIMESTAMP" ts)
15853 org-ts-regexp-inactive)
15854 (t org-ts-regexp-both))))
15855 (catch 'next
15856 (while (re-search-forward regexp end t)
15857 (backward-char)
15858 (let ((object (org-element-context)))
15859 ;; Accept to match timestamps in node
15860 ;; properties, too.
15861 (when (memq (org-element-type object)
15862 '(node-property timestamp))
15863 (let ((type
15864 (org-element-property :type object)))
15865 (cond
15866 ((and (memq type '(active active-range))
15867 (not (equal specific "TIMESTAMP_IA")))
15868 (unless (assoc "TIMESTAMP" ts)
15869 (push (cons "TIMESTAMP"
15870 (org-element-property
15871 :raw-value object))
15873 (when specific (throw 'exit ts))))
15874 ((and (memq type '(inactive inactive-range))
15875 (not (string= specific "TIMESTAMP")))
15876 (unless (assoc "TIMESTAMP_IA" ts)
15877 (push (cons "TIMESTAMP_IA"
15878 (org-element-property
15879 :raw-value object))
15881 (when specific (throw 'exit ts))))))
15882 ;; Both timestamp types are found,
15883 ;; move to next part.
15884 (when (= (length ts) 2) (throw 'next ts)))))
15885 ts)))))
15886 (goto-char beg)
15887 ;; First look for timestamps within headline.
15888 (let ((ts (funcall find-ts (line-end-position) nil)))
15889 (if (= (length ts) 2) (setq props (nconc ts props))
15890 ;; Then find timestamps in the section, skipping
15891 ;; planning line.
15892 (let ((end (save-excursion (outline-next-heading))))
15893 (forward-line)
15894 (when (looking-at-p org-planning-line-re) (forward-line))
15895 (setq props (nconc (funcall find-ts end ts) props))))))))
15896 ;; Get the standard properties, like :PROP:.
15897 (when (memq which '(nil all standard))
15898 ;; If we are looking after a specific property, delegate
15899 ;; to `org-entry-get', which is faster. However, make an
15900 ;; exception for "CATEGORY", since it can be also set
15901 ;; through keywords (i.e. #+CATEGORY).
15902 (if (and specific (not (equal specific "CATEGORY")))
15903 (let ((value (org-entry-get beg specific nil t)))
15904 (throw 'exit (and value (list (cons specific value)))))
15905 (let ((range (org-get-property-block beg)))
15906 (when range
15907 (let ((end (cdr range)) seen-base)
15908 (goto-char (car range))
15909 ;; Unlike to `org--update-property-plist', we
15910 ;; handle the case where base values is found
15911 ;; after its extension. We also forbid standard
15912 ;; properties to be named as special properties.
15913 (while (re-search-forward org-property-re end t)
15914 (let* ((key (upcase (match-string-no-properties 2)))
15915 (extendp (string-match-p "\\+\\'" key))
15916 (key-base (if extendp (substring key 0 -1) key))
15917 (value (match-string-no-properties 3)))
15918 (cond
15919 ((member-ignore-case key-base org-special-properties))
15920 (extendp
15921 (setq props
15922 (org--update-property-plist key value props)))
15923 ((member key seen-base))
15924 (t (push key seen-base)
15925 (let ((p (assoc-string key props t)))
15926 (if p (setcdr p (concat value " " (cdr p)))
15927 (push (cons key value) props))))))))))))
15928 (unless (assoc "CATEGORY" props)
15929 (push (cons "CATEGORY" (org-get-category beg)) props)
15930 (when (string= specific "CATEGORY") (throw 'exit props)))
15931 ;; Return value.
15932 props)))))
15934 (defun org--property-local-values (property literal-nil)
15935 "Return value for PROPERTY in current entry.
15936 Value is a list whose car is the base value for PROPERTY and cdr
15937 a list of accumulated values. Return nil if neither is found in
15938 the entry. Also return nil when PROPERTY is set to \"nil\",
15939 unless LITERAL-NIL is non-nil."
15940 (let ((range (org-get-property-block)))
15941 (when range
15942 (goto-char (car range))
15943 (let* ((case-fold-search t)
15944 (end (cdr range))
15945 (value
15946 ;; Base value.
15947 (save-excursion
15948 (let ((v (and (re-search-forward
15949 (org-re-property property nil t) end t)
15950 (match-string-no-properties 3))))
15951 (list (if literal-nil v (org-not-nil v)))))))
15952 ;; Find additional values.
15953 (let* ((property+ (org-re-property (concat property "+") nil t)))
15954 (while (re-search-forward property+ end t)
15955 (push (match-string-no-properties 3) value)))
15956 ;; Return final values.
15957 (and (not (equal value '(nil))) (nreverse value))))))
15959 (defun org--property-global-value (property literal-nil)
15960 "Return value for PROPERTY in current buffer.
15961 Return value is a string. Return nil if property is not set
15962 globally. Also return nil when PROPERTY is set to \"nil\",
15963 unless LITERAL-NIL is non-nil."
15964 (let ((global
15965 (cdr (or (assoc-string property org-file-properties t)
15966 (assoc-string property org-global-properties t)
15967 (assoc-string property org-global-properties-fixed t)))))
15968 (if literal-nil global (org-not-nil global))))
15970 (defun org-entry-get (pom property &optional inherit literal-nil)
15971 "Get value of PROPERTY for entry or content at point-or-marker POM.
15973 If INHERIT is non-nil and the entry does not have the property,
15974 then also check higher levels of the hierarchy. If INHERIT is
15975 the symbol `selective', use inheritance only if the setting in
15976 `org-use-property-inheritance' selects PROPERTY for inheritance.
15978 If the property is present but empty, the return value is the
15979 empty string. If the property is not present at all, nil is
15980 returned. In any other case, return the value as a string.
15981 Search is case-insensitive.
15983 If LITERAL-NIL is set, return the string value \"nil\" as
15984 a string, do not interpret it as the list atom nil. This is used
15985 for inheritance when a \"nil\" value can supersede a non-nil
15986 value higher up the hierarchy."
15987 (org-with-point-at pom
15988 (cond
15989 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15990 ;; We need a special property. Use `org-entry-properties' to
15991 ;; retrieve it, but specify the wanted property.
15992 (cdr (assoc-string property (org-entry-properties nil property))))
15993 ((and inherit
15994 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15995 (org-entry-get-with-inheritance property literal-nil))
15997 (let* ((local (org--property-local-values property literal-nil))
15998 (value (and local (mapconcat #'identity (delq nil local) " "))))
15999 (if literal-nil value (org-not-nil value)))))))
16001 (defun org-property-or-variable-value (var &optional inherit)
16002 "Check if there is a property fixing the value of VAR.
16003 If yes, return this value. If not, return the current value of the variable."
16004 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
16005 (if (and prop (stringp prop) (string-match "\\S-" prop))
16006 (read prop)
16007 (symbol-value var))))
16009 (defun org-entry-delete (pom property)
16010 "Delete PROPERTY from entry at point-or-marker POM.
16011 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16012 non-nil when a property was removed."
16013 (org-with-point-at pom
16014 (pcase (org-get-property-block)
16015 (`(,begin . ,origin)
16016 (let* ((end (copy-marker origin))
16017 (re (org-re-property
16018 (concat (regexp-quote property) "\\+?") t t)))
16019 (goto-char begin)
16020 (while (re-search-forward re end t)
16021 (delete-region (match-beginning 0) (line-beginning-position 2)))
16022 ;; If drawer is empty, remove it altogether.
16023 (when (= begin end)
16024 (delete-region (line-beginning-position 0)
16025 (line-beginning-position 2)))
16026 ;; Return non-nil if some property was removed.
16027 (prog1 (/= end origin) (set-marker end nil))))
16028 (_ nil))))
16030 ;; Multi-values properties are properties that contain multiple values
16031 ;; These values are assumed to be single words, separated by whitespace.
16032 (defun org-entry-add-to-multivalued-property (pom property value)
16033 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16034 (let* ((old (org-entry-get pom property))
16035 (values (and old (org-split-string old "[ \t]"))))
16036 (setq value (org-entry-protect-space value))
16037 (unless (member value values)
16038 (setq values (append values (list value)))
16039 (org-entry-put pom property
16040 (mapconcat 'identity values " ")))))
16042 (defun org-entry-remove-from-multivalued-property (pom property value)
16043 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16044 (let* ((old (org-entry-get pom property))
16045 (values (and old (org-split-string old "[ \t]"))))
16046 (setq value (org-entry-protect-space value))
16047 (when (member value values)
16048 (setq values (delete value values))
16049 (org-entry-put pom property
16050 (mapconcat 'identity values " ")))))
16052 (defun org-entry-member-in-multivalued-property (pom property value)
16053 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16054 (let* ((old (org-entry-get pom property))
16055 (values (and old (org-split-string old "[ \t]"))))
16056 (setq value (org-entry-protect-space value))
16057 (member value values)))
16059 (defun org-entry-get-multivalued-property (pom property)
16060 "Return a list of values in a multivalued property."
16061 (let* ((value (org-entry-get pom property))
16062 (values (and value (org-split-string value "[ \t]"))))
16063 (mapcar 'org-entry-restore-space values)))
16065 (defun org-entry-put-multivalued-property (pom property &rest values)
16066 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16067 VALUES should be a list of strings. Spaces will be protected."
16068 (org-entry-put pom property
16069 (mapconcat 'org-entry-protect-space values " "))
16070 (let* ((value (org-entry-get pom property))
16071 (values (and value (org-split-string value "[ \t]"))))
16072 (mapcar 'org-entry-restore-space values)))
16074 (defun org-entry-protect-space (s)
16075 "Protect spaces and newline in string S."
16076 (while (string-match " " s)
16077 (setq s (replace-match "%20" t t s)))
16078 (while (string-match "\n" s)
16079 (setq s (replace-match "%0A" t t s)))
16082 (defun org-entry-restore-space (s)
16083 "Restore spaces and newline in string S."
16084 (while (string-match "%20" s)
16085 (setq s (replace-match " " t t s)))
16086 (while (string-match "%0A" s)
16087 (setq s (replace-match "\n" t t s)))
16090 (defvar org-entry-property-inherited-from (make-marker)
16091 "Marker pointing to the entry from where a property was inherited.
16092 Each call to `org-entry-get-with-inheritance' will set this marker to the
16093 location of the entry where the inheritance search matched. If there was
16094 no match, the marker will point nowhere.
16095 Note that also `org-entry-get' calls this function, if the INHERIT flag
16096 is set.")
16098 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16099 "Get PROPERTY of entry or content at point, search higher levels if needed.
16100 The search will stop at the first ancestor which has the property defined.
16101 If the value found is \"nil\", return nil to show that the property
16102 should be considered as undefined (this is the meaning of nil here).
16103 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16104 (move-marker org-entry-property-inherited-from nil)
16105 (org-with-wide-buffer
16106 (let (value)
16107 (catch 'exit
16108 (while t
16109 (let ((v (org--property-local-values property literal-nil)))
16110 (when v
16111 (setq value
16112 (concat (mapconcat #'identity (delq nil v) " ")
16113 (and value " ")
16114 value)))
16115 (cond
16116 ((car v)
16117 (org-back-to-heading t)
16118 (move-marker org-entry-property-inherited-from (point))
16119 (throw 'exit nil))
16120 ((org-up-heading-safe))
16122 (let ((global (org--property-global-value property literal-nil)))
16123 (cond ((not global))
16124 (value (setq value (concat global " " value)))
16125 (t (setq value global))))
16126 (throw 'exit nil))))))
16127 (if literal-nil value (org-not-nil value)))))
16129 (defvar org-property-changed-functions nil
16130 "Hook called when the value of a property has changed.
16131 Each hook function should accept two arguments, the name of the property
16132 and the new value.")
16134 (defun org-entry-put (pom property value)
16135 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16137 If the value is nil, it is converted to the empty string. If it
16138 is not a string, an error is raised. Also raise an error on
16139 invalid property names.
16141 PROPERTY can be any regular property (see
16142 `org-special-properties'). It can also be \"TODO\",
16143 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16145 For the last two properties, VALUE may have any of the special
16146 values \"earlier\" and \"later\". The function then increases or
16147 decreases scheduled or deadline date by one day."
16148 (cond ((null value) (setq value ""))
16149 ((not (stringp value)) (error "Properties values should be strings"))
16150 ((not (org--valid-property-p property))
16151 (user-error "Invalid property name: \"%s\"" property)))
16152 (org-with-point-at pom
16153 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16154 (org-back-to-heading t)
16155 (org-with-limited-levels (org-back-to-heading t)))
16156 (let ((beg (point)))
16157 (cond
16158 ((equal property "TODO")
16159 (cond ((not (org-string-nw-p value)) (setq value 'none))
16160 ((not (member value org-todo-keywords-1))
16161 (user-error "\"%s\" is not a valid TODO state" value)))
16162 (org-todo value)
16163 (org-set-tags nil 'align))
16164 ((equal property "PRIORITY")
16165 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16166 (org-set-tags nil 'align))
16167 ((equal property "SCHEDULED")
16168 (forward-line)
16169 (if (and (looking-at-p org-planning-line-re)
16170 (re-search-forward
16171 org-scheduled-time-regexp (line-end-position) t))
16172 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16173 ((string= value "later") (org-timestamp-change 1 'day))
16174 ((string= value "") (org-schedule '(4)))
16175 (t (org-schedule nil value)))
16176 (if (member value '("earlier" "later" ""))
16177 (call-interactively #'org-schedule)
16178 (org-schedule nil value))))
16179 ((equal property "DEADLINE")
16180 (forward-line)
16181 (if (and (looking-at-p org-planning-line-re)
16182 (re-search-forward
16183 org-deadline-time-regexp (line-end-position) t))
16184 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16185 ((string= value "later") (org-timestamp-change 1 'day))
16186 ((string= value "") (org-deadline '(4)))
16187 (t (org-deadline nil value)))
16188 (if (member value '("earlier" "later" ""))
16189 (call-interactively #'org-deadline)
16190 (org-deadline nil value))))
16191 ((member property org-special-properties)
16192 (error "The %s property cannot be set with `org-entry-put'" property))
16194 (let* ((range (org-get-property-block beg 'force))
16195 (end (cdr range))
16196 (case-fold-search t))
16197 (goto-char (car range))
16198 (if (re-search-forward (org-re-property property nil t) end t)
16199 (progn (delete-region (match-beginning 0) (match-end 0))
16200 (goto-char (match-beginning 0)))
16201 (goto-char end)
16202 (insert "\n")
16203 (backward-char))
16204 (insert ":" property ":")
16205 (when value (insert " " value))
16206 (org-indent-line)))))
16207 (run-hook-with-args 'org-property-changed-functions property value)))
16209 (defun org-buffer-property-keys
16210 (&optional specials defaults columns ignore-malformed)
16211 "Get all property keys in the current buffer.
16213 When SPECIALS is non-nil, also list the special properties that
16214 reflect things like tags and TODO state.
16216 When DEFAULTS is non-nil, also include properties that has
16217 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16218 DESCRIPTION, LOCATION, and LOGGING and others.
16220 When COLUMNS in non-nil, also include property names given in
16221 COLUMN formats in the current buffer.
16223 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16224 automatically performed, such drawers will be silently ignored."
16225 (let ((case-fold-search t)
16226 (props (append
16227 (and specials org-special-properties)
16228 (and defaults (cons org-effort-property org-default-properties))
16229 nil)))
16230 (org-with-wide-buffer
16231 (goto-char (point-min))
16232 (while (re-search-forward org-property-start-re nil t)
16233 (let ((range (org-get-property-block)))
16234 (catch 'skip
16235 (unless range
16236 (when (and (not ignore-malformed)
16237 (not (org-before-first-heading-p))
16238 (y-or-n-p (format "Malformed drawer at %d, repair?"
16239 (line-beginning-position))))
16240 (org-get-property-block nil t))
16241 (throw 'skip nil))
16242 (goto-char (car range))
16243 (let ((begin (car range))
16244 (end (cdr range)))
16245 ;; Make sure that found property block is not located
16246 ;; before current point, as it would generate an infloop.
16247 ;; It can happen, for example, in the following
16248 ;; situation:
16250 ;; * Headline
16251 ;; :PROPERTIES:
16252 ;; ...
16253 ;; :END:
16254 ;; *************** Inlinetask
16255 ;; #+BEGIN_EXAMPLE
16256 ;; :PROPERTIES:
16257 ;; #+END_EXAMPLE
16259 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16260 (while (< (point) end)
16261 (let ((p (progn (looking-at org-property-re)
16262 (match-string-no-properties 2))))
16263 ;; Only add true property name, not extension symbol.
16264 (push (if (not (string-match-p "\\+\\'" p)) p
16265 (substring p 0 -1))
16266 props))
16267 (forward-line))))
16268 (outline-next-heading)))
16269 (when columns
16270 (goto-char (point-min))
16271 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16272 (let ((element (org-element-at-point)))
16273 (when (memq (org-element-type element) '(keyword node-property))
16274 (let ((value (org-element-property :value element))
16275 (start 0))
16276 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16277 (setq start (match-end 0))
16278 (let ((p (match-string-no-properties 1 value)))
16279 (unless (member-ignore-case p org-special-properties)
16280 (push p props))))))))))
16281 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16283 (defun org-property-values (key)
16284 "List all non-nil values of property KEY in current buffer."
16285 (org-with-wide-buffer
16286 (goto-char (point-min))
16287 (let ((case-fold-search t)
16288 (re (org-re-property key))
16289 values)
16290 (while (re-search-forward re nil t)
16291 (push (org-entry-get (point) key) values))
16292 (delete-dups values))))
16294 (defun org-insert-property-drawer ()
16295 "Insert a property drawer into the current entry."
16296 (org-with-wide-buffer
16297 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16298 (org-back-to-heading t)
16299 (org-with-limited-levels (org-back-to-heading t)))
16300 (forward-line)
16301 (when (looking-at-p org-planning-line-re) (forward-line))
16302 (unless (looking-at-p org-property-drawer-re)
16303 ;; Make sure we start editing a line from current entry, not from
16304 ;; next one. It prevents extending text properties or overlays
16305 ;; belonging to the latter.
16306 (when (bolp) (backward-char))
16307 (let ((begin (1+ (point)))
16308 (inhibit-read-only t))
16309 (insert "\n:PROPERTIES:\n:END:")
16310 (when (eobp) (insert "\n"))
16311 (org-indent-region begin (point))))))
16313 (defun org-insert-drawer (&optional arg drawer)
16314 "Insert a drawer at point.
16316 When optional argument ARG is non-nil, insert a property drawer.
16318 Optional argument DRAWER, when non-nil, is a string representing
16319 drawer's name. Otherwise, the user is prompted for a name.
16321 If a region is active, insert the drawer around that region
16322 instead.
16324 Point is left between drawer's boundaries."
16325 (interactive "P")
16326 (let* ((drawer (if arg "PROPERTIES"
16327 (or drawer (read-from-minibuffer "Drawer: ")))))
16328 (cond
16329 ;; With C-u, fall back on `org-insert-property-drawer'
16330 (arg (org-insert-property-drawer))
16331 ;; Check validity of suggested drawer's name.
16332 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16333 (user-error "Invalid drawer name"))
16334 ;; With an active region, insert a drawer at point.
16335 ((not (org-region-active-p))
16336 (progn
16337 (unless (bolp) (insert "\n"))
16338 (insert (format ":%s:\n\n:END:\n" drawer))
16339 (forward-line -2)))
16340 ;; Otherwise, insert the drawer at point
16342 (let ((rbeg (region-beginning))
16343 (rend (copy-marker (region-end))))
16344 (unwind-protect
16345 (progn
16346 (goto-char rbeg)
16347 (beginning-of-line)
16348 (when (save-excursion
16349 (re-search-forward org-outline-regexp-bol rend t))
16350 (user-error "Drawers cannot contain headlines"))
16351 ;; Position point at the beginning of the first
16352 ;; non-blank line in region. Insert drawer's opening
16353 ;; there, then indent it.
16354 (org-skip-whitespace)
16355 (beginning-of-line)
16356 (insert ":" drawer ":\n")
16357 (forward-line -1)
16358 (indent-for-tab-command)
16359 ;; Move point to the beginning of the first blank line
16360 ;; after the last non-blank line in region. Insert
16361 ;; drawer's closing, then indent it.
16362 (goto-char rend)
16363 (skip-chars-backward " \r\t\n")
16364 (insert "\n:END:")
16365 (deactivate-mark t)
16366 (indent-for-tab-command)
16367 (unless (eolp) (insert "\n")))
16368 ;; Clear marker, whatever the outcome of insertion is.
16369 (set-marker rend nil)))))))
16371 (defvar org-property-set-functions-alist nil
16372 "Property set function alist.
16373 Each entry should have the following format:
16375 (PROPERTY . READ-FUNCTION)
16377 The read function will be called with the same argument as
16378 `org-completing-read'.")
16380 (defun org-set-property-function (property)
16381 "Get the function that should be used to set PROPERTY.
16382 This is computed according to `org-property-set-functions-alist'."
16383 (or (cdr (assoc property org-property-set-functions-alist))
16384 'org-completing-read))
16386 (defun org-read-property-value (property)
16387 "Read PROPERTY value from user."
16388 (let* ((completion-ignore-case t)
16389 (allowed (org-property-get-allowed-values nil property 'table))
16390 (cur (org-entry-get nil property))
16391 (prompt (concat property " value"
16392 (if (and cur (string-match "\\S-" cur))
16393 (concat " [" cur "]") "") ": "))
16394 (set-function (org-set-property-function property))
16395 (val (if allowed
16396 (funcall set-function prompt allowed nil
16397 (not (get-text-property 0 'org-unrestricted
16398 (caar allowed))))
16399 (funcall set-function prompt
16400 (mapcar 'list (org-property-values property))
16401 nil nil "" nil cur))))
16402 (org-trim val)))
16404 (defvar org-last-set-property nil)
16405 (defvar org-last-set-property-value nil)
16406 (defun org-read-property-name ()
16407 "Read a property name."
16408 (let ((completion-ignore-case t)
16409 (default-prop (or (and (org-at-property-p)
16410 (match-string-no-properties 2))
16411 org-last-set-property)))
16412 (org-completing-read
16413 (concat "Property"
16414 (if default-prop (concat " [" default-prop "]") "")
16415 ": ")
16416 (mapcar #'list (org-buffer-property-keys nil t t))
16417 nil nil nil nil default-prop)))
16419 (defun org-set-property-and-value (use-last)
16420 "Allow to set [PROPERTY]: [value] direction from prompt.
16421 When use-default, don't even ask, just use the last
16422 \"[PROPERTY]: [value]\" string from the history."
16423 (interactive "P")
16424 (let* ((completion-ignore-case t)
16425 (pv (or (and use-last org-last-set-property-value)
16426 (org-completing-read
16427 "Enter a \"[Property]: [value]\" pair: "
16428 nil nil nil nil nil
16429 org-last-set-property-value)))
16430 prop val)
16431 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16432 (setq prop (match-string 1 pv)
16433 val (match-string 2 pv))
16434 (org-set-property prop val))))
16436 (defun org-set-property (property value)
16437 "In the current entry, set PROPERTY to VALUE.
16439 When called interactively, this will prompt for a property name, offering
16440 completion on existing and default properties. And then it will prompt
16441 for a value, offering completion either on allowed values (via an inherited
16442 xxx_ALL property) or on existing values in other instances of this property
16443 in the current file.
16445 Throw an error when trying to set a property with an invalid name."
16446 (interactive (list nil nil))
16447 (let ((property (or property (org-read-property-name))))
16448 ;; `org-entry-put' also makes the following check, but this one
16449 ;; avoids polluting `org-last-set-property' and
16450 ;; `org-last-set-property-value' needlessly.
16451 (unless (org--valid-property-p property)
16452 (user-error "Invalid property name: \"%s\"" property))
16453 (let ((value (or value (org-read-property-value property)))
16454 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16455 (setq org-last-set-property property)
16456 (setq org-last-set-property-value (concat property ": " value))
16457 ;; Possibly postprocess the inserted value:
16458 (when fn (setq value (funcall fn value)))
16459 (unless (equal (org-entry-get nil property) value)
16460 (org-entry-put nil property value)))))
16462 (defun org-find-property (property &optional value)
16463 "Find first entry in buffer that sets PROPERTY.
16465 When optional argument VALUE is non-nil, only consider an entry
16466 if it contains PROPERTY set to this value. If PROPERTY should be
16467 explicitly set to nil, use string \"nil\" for VALUE.
16469 Return position where the entry begins, or nil if there is no
16470 such entry. If narrowing is in effect, only search the visible
16471 part of the buffer."
16472 (save-excursion
16473 (goto-char (point-min))
16474 (let ((case-fold-search t)
16475 (re (org-re-property property nil (not value) value)))
16476 (catch 'exit
16477 (while (re-search-forward re nil t)
16478 (when (if value (org-at-property-p)
16479 (org-entry-get (point) property nil t))
16480 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16482 (defun org-delete-property (property)
16483 "In the current entry, delete PROPERTY."
16484 (interactive
16485 (let* ((completion-ignore-case t)
16486 (cat (org-entry-get (point) "CATEGORY"))
16487 (props0 (org-entry-properties nil 'standard))
16488 (props (if cat props0
16489 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16490 (prop (if (< 1 (length props))
16491 (completing-read "Property: " props nil t)
16492 (caar props))))
16493 (list prop)))
16494 (if (not property)
16495 (message "No property to delete in this entry")
16496 (org-entry-delete nil property)
16497 (message "Property \"%s\" deleted" property)))
16499 (defun org-delete-property-globally (property)
16500 "Remove PROPERTY globally, from all entries.
16501 This function ignores narrowing, if any."
16502 (interactive
16503 (let* ((completion-ignore-case t)
16504 (prop (completing-read
16505 "Globally remove property: "
16506 (mapcar #'list (org-buffer-property-keys)))))
16507 (list prop)))
16508 (org-with-wide-buffer
16509 (goto-char (point-min))
16510 (let ((count 0)
16511 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16512 (while (re-search-forward re nil t)
16513 (when (org-entry-delete (point) property) (cl-incf count)))
16514 (message "Property \"%s\" removed from %d entries" property count))))
16516 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16518 (defun org-compute-property-at-point ()
16519 "Compute the property at point.
16520 This looks for an enclosing column format, extracts the operator and
16521 then applies it to the property in the column format's scope."
16522 (interactive)
16523 (unless (org-at-property-p)
16524 (user-error "Not at a property"))
16525 (let ((prop (match-string-no-properties 2)))
16526 (org-columns-get-format-and-top-level)
16527 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16528 (user-error "No operator defined for property %s" prop))
16529 (org-columns-compute prop)))
16531 (defvar org-property-allowed-value-functions nil
16532 "Hook for functions supplying allowed values for a specific property.
16533 The functions must take a single argument, the name of the property, and
16534 return a flat list of allowed values. If \":ETC\" is one of
16535 the values, this means that these values are intended as defaults for
16536 completion, but that other values should be allowed too.
16537 The functions must return nil if they are not responsible for this
16538 property.")
16540 (defun org-property-get-allowed-values (pom property &optional table)
16541 "Get allowed values for the property PROPERTY.
16542 When TABLE is non-nil, return an alist that can directly be used for
16543 completion."
16544 (let (vals)
16545 (cond
16546 ((equal property "TODO")
16547 (setq vals (org-with-point-at pom
16548 (append org-todo-keywords-1 '("")))))
16549 ((equal property "PRIORITY")
16550 (let ((n org-lowest-priority))
16551 (while (>= n org-highest-priority)
16552 (push (char-to-string n) vals)
16553 (setq n (1- n)))))
16554 ((equal property "CATEGORY"))
16555 ((member property org-special-properties))
16556 ((setq vals (run-hook-with-args-until-success
16557 'org-property-allowed-value-functions property)))
16559 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16560 (when (and vals (string-match "\\S-" vals))
16561 (setq vals (car (read-from-string (concat "(" vals ")"))))
16562 (setq vals (mapcar (lambda (x)
16563 (cond ((stringp x) x)
16564 ((numberp x) (number-to-string x))
16565 ((symbolp x) (symbol-name x))
16566 (t "???")))
16567 vals)))))
16568 (when (member ":ETC" vals)
16569 (setq vals (remove ":ETC" vals))
16570 (org-add-props (car vals) '(org-unrestricted t)))
16571 (if table (mapcar 'list vals) vals)))
16573 (defun org-property-previous-allowed-value (&optional _previous)
16574 "Switch to the next allowed value for this property."
16575 (interactive)
16576 (org-property-next-allowed-value t))
16578 (defun org-property-next-allowed-value (&optional previous)
16579 "Switch to the next allowed value for this property."
16580 (interactive)
16581 (unless (org-at-property-p)
16582 (user-error "Not at a property"))
16583 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16584 (key (match-string 2))
16585 (value (match-string 3))
16586 (allowed (or (org-property-get-allowed-values (point) key)
16587 (and (member value '("[ ]" "[-]" "[X]"))
16588 '("[ ]" "[X]"))))
16589 (heading (save-match-data (nth 4 (org-heading-components))))
16590 nval)
16591 (unless allowed
16592 (user-error "Allowed values for this property have not been defined"))
16593 (when previous (setq allowed (reverse allowed)))
16594 (when (member value allowed)
16595 (setq nval (car (cdr (member value allowed)))))
16596 (setq nval (or nval (car allowed)))
16597 (when (equal nval value)
16598 (user-error "Only one allowed value for this property"))
16599 (org-at-property-p)
16600 (replace-match (concat " :" key ": " nval) t t)
16601 (org-indent-line)
16602 (beginning-of-line 1)
16603 (skip-chars-forward " \t")
16604 (when (equal prop org-effort-property)
16605 (org-refresh-property
16606 '((effort . identity)
16607 (effort-minutes . org-duration-string-to-minutes))
16608 nval)
16609 (when (string= org-clock-current-task heading)
16610 (setq org-clock-effort nval)
16611 (org-clock-update-mode-line)))
16612 (run-hook-with-args 'org-property-changed-functions key nval)))
16614 (defun org-find-olp (path &optional this-buffer)
16615 "Return a marker pointing to the entry at outline path OLP.
16616 If anything goes wrong, throw an error.
16617 You can wrap this call to catch the error like this:
16619 (condition-case msg
16620 (org-mobile-locate-entry (match-string 4))
16621 (error (nth 1 msg)))
16623 The return value will then be either a string with the error message,
16624 or a marker if everything is OK.
16626 If THIS-BUFFER is set, the outline path does not contain a file,
16627 only headings."
16628 (let* ((file (if this-buffer buffer-file-name (pop path)))
16629 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16630 (level 1)
16631 (lmin 1)
16632 (lmax 1)
16633 end found flevel)
16634 (unless buffer (error "File not found :%s" file))
16635 (with-current-buffer buffer
16636 (org-with-wide-buffer
16637 (goto-char (point-min))
16638 (dolist (heading path)
16639 (let ((re (format org-complex-heading-regexp-format
16640 (regexp-quote heading)))
16641 (cnt 0))
16642 (while (re-search-forward re end t)
16643 (setq level (- (match-end 1) (match-beginning 1)))
16644 (when (and (>= level lmin) (<= level lmax))
16645 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16646 (when (= cnt 0)
16647 (error "Heading not found on level %d: %s" lmax heading))
16648 (when (> cnt 1)
16649 (error "Heading not unique on level %d: %s" lmax heading))
16650 (goto-char found)
16651 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16652 (setq end (save-excursion (org-end-of-subtree t t)))))
16653 (when (org-at-heading-p)
16654 (point-marker))))))
16656 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16657 "Find node HEADING in BUFFER.
16658 Return a marker to the heading if it was found, or nil if not.
16659 If POS-ONLY is set, return just the position instead of a marker.
16661 The heading text must match exact, but it may have a TODO keyword,
16662 a priority cookie and tags in the standard locations."
16663 (with-current-buffer (or buffer (current-buffer))
16664 (org-with-wide-buffer
16665 (goto-char (point-min))
16666 (let (case-fold-search)
16667 (when (re-search-forward
16668 (format org-complex-heading-regexp-format
16669 (regexp-quote heading)) nil t)
16670 (if pos-only
16671 (match-beginning 0)
16672 (move-marker (make-marker) (match-beginning 0))))))))
16674 (defun org-find-exact-heading-in-directory (heading &optional dir)
16675 "Find Org node headline HEADING in all .org files in directory DIR.
16676 When the target headline is found, return a marker to this location."
16677 (let ((files (directory-files (or dir default-directory)
16678 t "\\`[^.#].*\\.org\\'"))
16679 visiting m buffer)
16680 (catch 'found
16681 (dolist (file files)
16682 (message "trying %s" file)
16683 (setq visiting (org-find-base-buffer-visiting file))
16684 (setq buffer (or visiting (find-file-noselect file)))
16685 (setq m (org-find-exact-headline-in-buffer
16686 heading buffer))
16687 (when (and (not m) (not visiting)) (kill-buffer buffer))
16688 (and m (throw 'found m))))))
16690 (defun org-find-entry-with-id (ident)
16691 "Locate the entry that contains the ID property with exact value IDENT.
16692 IDENT can be a string, a symbol or a number, this function will search for
16693 the string representation of it.
16694 Return the position where this entry starts, or nil if there is no such entry."
16695 (interactive "sID: ")
16696 (let ((id (cond
16697 ((stringp ident) ident)
16698 ((symbolp ident) (symbol-name ident))
16699 ((numberp ident) (number-to-string ident))
16700 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16701 (org-with-wide-buffer (org-find-property "ID" id))))
16703 ;;;; Timestamps
16705 (defvar org-last-changed-timestamp nil)
16706 (defvar org-last-inserted-timestamp nil
16707 "The last time stamp inserted with `org-insert-time-stamp'.")
16708 (defvar org-ts-what) ; dynamically scoped parameter
16710 (defun org-time-stamp (arg &optional inactive)
16711 "Prompt for a date/time and insert a time stamp.
16713 If the user specifies a time like HH:MM or if this command is
16714 called with at least one prefix argument, the time stamp contains
16715 the date and the time. Otherwise, only the date is included.
16717 All parts of a date not specified by the user are filled in from
16718 the timestamp at point, if any, or the current date/time
16719 otherwise.
16721 If there is already a timestamp at the cursor, it is replaced.
16723 With two universal prefix arguments, insert an active timestamp
16724 with the current time without prompting the user.
16726 When called from lisp, the timestamp is inactive if INACTIVE is
16727 non-nil."
16728 (interactive "P")
16729 (let* ((ts (cond
16730 ((org-at-date-range-p t)
16731 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16732 ((org-at-timestamp-p t) (match-string 0))))
16733 ;; Default time is either the timestamp at point or today.
16734 ;; When entering a range, only the range start is considered.
16735 (default-time (if (not ts) (current-time)
16736 (apply #'encode-time (org-parse-time-string ts))))
16737 (default-input (and ts (org-get-compact-tod ts)))
16738 (repeater (and ts
16739 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16740 (match-string 0 ts)))
16741 org-time-was-given
16742 org-end-time-was-given
16743 (time
16744 (and (if (equal arg '(16)) (current-time)
16745 ;; Preserve `this-command' and `last-command'.
16746 (let ((this-command this-command)
16747 (last-command last-command))
16748 (org-read-date
16749 arg 'totime nil nil default-time default-input
16750 inactive))))))
16751 (cond
16752 ((and ts
16753 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16754 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16755 (insert "--")
16756 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16758 ;; Make sure we're on a timestamp. When in the middle of a date
16759 ;; range, move arbitrarily to range end.
16760 (unless (org-at-timestamp-p t)
16761 (skip-chars-forward "-")
16762 (org-at-timestamp-p t))
16763 (replace-match "")
16764 (setq org-last-changed-timestamp
16765 (org-insert-time-stamp
16766 time (or org-time-was-given arg)
16767 inactive nil nil (list org-end-time-was-given)))
16768 (when repeater
16769 (backward-char)
16770 (insert " " repeater)
16771 (setq org-last-changed-timestamp
16772 (concat (substring org-last-inserted-timestamp 0 -1)
16773 " " repeater ">")))
16774 (message "Timestamp updated"))
16775 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16776 (t (org-insert-time-stamp
16777 time (or org-time-was-given arg) inactive nil nil
16778 (list org-end-time-was-given))))))
16780 ;; FIXME: can we use this for something else, like computing time differences?
16781 (defun org-get-compact-tod (s)
16782 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16783 (let* ((t1 (match-string 1 s))
16784 (h1 (string-to-number (match-string 2 s)))
16785 (m1 (string-to-number (match-string 3 s)))
16786 (t2 (and (match-end 4) (match-string 5 s)))
16787 (h2 (and t2 (string-to-number (match-string 6 s))))
16788 (m2 (and t2 (string-to-number (match-string 7 s))))
16789 dh dm)
16790 (if (not t2)
16792 (setq dh (- h2 h1) dm (- m2 m1))
16793 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16794 (concat t1 "+" (number-to-string dh)
16795 (and (/= 0 dm) (format ":%02d" dm)))))))
16797 (defun org-time-stamp-inactive (&optional arg)
16798 "Insert an inactive time stamp.
16799 An inactive time stamp is enclosed in square brackets instead of angle
16800 brackets. It is inactive in the sense that it does not trigger agenda entries,
16801 does not link to the calendar and cannot be changed with the S-cursor keys.
16802 So these are more for recording a certain time/date."
16803 (interactive "P")
16804 (org-time-stamp arg 'inactive))
16806 (defvar org-date-ovl (make-overlay 1 1))
16807 (overlay-put org-date-ovl 'face 'org-date-selected)
16808 (delete-overlay org-date-ovl)
16810 (defvar org-ans1) ; dynamically scoped parameter
16811 (defvar org-ans2) ; dynamically scoped parameter
16813 (defvar org-plain-time-of-day-regexp) ; defined below
16815 (defvar org-overriding-default-time nil) ; dynamically scoped
16816 (defvar org-read-date-overlay nil)
16817 (defvar org-dcst nil) ; dynamically scoped
16818 (defvar org-read-date-history nil)
16819 (defvar org-read-date-final-answer nil)
16820 (defvar org-read-date-analyze-futurep nil)
16821 (defvar org-read-date-analyze-forced-year nil)
16822 (defvar org-read-date-inactive)
16824 (defvar org-read-date-minibuffer-local-map
16825 (let* ((map (make-sparse-keymap)))
16826 (set-keymap-parent map minibuffer-local-map)
16827 (org-defkey map (kbd ".")
16828 (lambda () (interactive)
16829 ;; Are we at the beginning of the prompt?
16830 (if (looking-back "^[^:]+: "
16831 (let ((inhibit-field-text-motion t))
16832 (line-beginning-position)))
16833 (org-eval-in-calendar '(calendar-goto-today))
16834 (insert "."))))
16835 (org-defkey map (kbd "C-.")
16836 (lambda () (interactive)
16837 (org-eval-in-calendar '(calendar-goto-today))))
16838 (org-defkey map [(meta shift left)]
16839 (lambda () (interactive)
16840 (org-eval-in-calendar '(calendar-backward-month 1))))
16841 (org-defkey map [(meta shift right)]
16842 (lambda () (interactive)
16843 (org-eval-in-calendar '(calendar-forward-month 1))))
16844 (org-defkey map [(meta shift up)]
16845 (lambda () (interactive)
16846 (org-eval-in-calendar '(calendar-backward-year 1))))
16847 (org-defkey map [(meta shift down)]
16848 (lambda () (interactive)
16849 (org-eval-in-calendar '(calendar-forward-year 1))))
16850 (org-defkey map [?\e (shift left)]
16851 (lambda () (interactive)
16852 (org-eval-in-calendar '(calendar-backward-month 1))))
16853 (org-defkey map [?\e (shift right)]
16854 (lambda () (interactive)
16855 (org-eval-in-calendar '(calendar-forward-month 1))))
16856 (org-defkey map [?\e (shift up)]
16857 (lambda () (interactive)
16858 (org-eval-in-calendar '(calendar-backward-year 1))))
16859 (org-defkey map [?\e (shift down)]
16860 (lambda () (interactive)
16861 (org-eval-in-calendar '(calendar-forward-year 1))))
16862 (org-defkey map [(shift up)]
16863 (lambda () (interactive)
16864 (org-eval-in-calendar '(calendar-backward-week 1))))
16865 (org-defkey map [(shift down)]
16866 (lambda () (interactive)
16867 (org-eval-in-calendar '(calendar-forward-week 1))))
16868 (org-defkey map [(shift left)]
16869 (lambda () (interactive)
16870 (org-eval-in-calendar '(calendar-backward-day 1))))
16871 (org-defkey map [(shift right)]
16872 (lambda () (interactive)
16873 (org-eval-in-calendar '(calendar-forward-day 1))))
16874 (org-defkey map "!"
16875 (lambda () (interactive)
16876 (org-eval-in-calendar '(diary-view-entries))
16877 (message "")))
16878 (org-defkey map ">"
16879 (lambda () (interactive)
16880 (org-eval-in-calendar '(calendar-scroll-left 1))))
16881 (org-defkey map "<"
16882 (lambda () (interactive)
16883 (org-eval-in-calendar '(calendar-scroll-right 1))))
16884 (org-defkey map "\C-v"
16885 (lambda () (interactive)
16886 (org-eval-in-calendar
16887 '(calendar-scroll-left-three-months 1))))
16888 (org-defkey map "\M-v"
16889 (lambda () (interactive)
16890 (org-eval-in-calendar
16891 '(calendar-scroll-right-three-months 1))))
16892 map)
16893 "Keymap for minibuffer commands when using `org-read-date'.")
16895 (defvar org-def)
16896 (defvar org-defdecode)
16897 (defvar org-with-time)
16899 (defvar calendar-setup) ; Dynamically scoped.
16900 (defun org-read-date (&optional with-time to-time from-string prompt
16901 default-time default-input inactive)
16902 "Read a date, possibly a time, and make things smooth for the user.
16903 The prompt will suggest to enter an ISO date, but you can also enter anything
16904 which will at least partially be understood by `parse-time-string'.
16905 Unrecognized parts of the date will default to the current day, month, year,
16906 hour and minute. If this command is called to replace a timestamp at point,
16907 or to enter the second timestamp of a range, the default time is taken
16908 from the existing stamp. Furthermore, the command prefers the future,
16909 so if you are giving a date where the year is not given, and the day-month
16910 combination is already past in the current year, it will assume you
16911 mean next year. For details, see the manual. A few examples:
16913 3-2-5 --> 2003-02-05
16914 feb 15 --> currentyear-02-15
16915 2/15 --> currentyear-02-15
16916 sep 12 9 --> 2009-09-12
16917 12:45 --> today 12:45
16918 22 sept 0:34 --> currentyear-09-22 0:34
16919 12 --> currentyear-currentmonth-12
16920 Fri --> nearest Friday after today
16921 -Tue --> last Tuesday
16922 etc.
16924 Furthermore you can specify a relative date by giving, as the *first* thing
16925 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16926 change in days weeks, months, years.
16927 With a single plus or minus, the date is relative to today. With a double
16928 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16929 +4d --> four days from today
16930 +4 --> same as above
16931 +2w --> two weeks from today
16932 ++5 --> five days from default date
16934 The function understands only English month and weekday abbreviations.
16936 While prompting, a calendar is popped up - you can also select the
16937 date with the mouse (button 1). The calendar shows a period of three
16938 months. To scroll it to other months, use the keys `>' and `<'.
16939 If you don't like the calendar, turn it off with
16940 (setq org-read-date-popup-calendar nil)
16942 With optional argument TO-TIME, the date will immediately be converted
16943 to an internal time.
16944 With an optional argument WITH-TIME, the prompt will suggest to
16945 also insert a time. Note that when WITH-TIME is not set, you can
16946 still enter a time, and this function will inform the calling routine
16947 about this change. The calling routine may then choose to change the
16948 format used to insert the time stamp into the buffer to include the time.
16949 With optional argument FROM-STRING, read from this string instead from
16950 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16951 the time/date that is used for everything that is not specified by the
16952 user."
16953 (require 'parse-time)
16954 (let* ((org-with-time with-time)
16955 (org-time-stamp-rounding-minutes
16956 (if (equal org-with-time '(16))
16957 '(0 0)
16958 org-time-stamp-rounding-minutes))
16959 (org-dcst org-display-custom-times)
16960 (ct (org-current-time))
16961 (org-def (or org-overriding-default-time default-time ct))
16962 (org-defdecode (decode-time org-def))
16963 (cur-frame (selected-frame))
16964 (mouse-autoselect-window nil) ; Don't let the mouse jump
16965 (calendar-setup
16966 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16967 (calendar-move-hook nil)
16968 (calendar-view-diary-initially-flag nil)
16969 (calendar-view-holidays-initially-flag nil)
16970 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16971 ;; Rationalize `org-def' and `org-defdecode', if required.
16972 (when (< (nth 2 org-defdecode) org-extend-today-until)
16973 (setf (nth 2 org-defdecode) -1)
16974 (setf (nth 1 org-defdecode) 59)
16975 (setq org-def (apply #'encode-time org-defdecode))
16976 (setq org-defdecode (decode-time org-def)))
16977 (let* ((timestr (format-time-string
16978 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16979 org-def))
16980 (prompt (concat (if prompt (concat prompt " ") "")
16981 (format "Date+time [%s]: " timestr))))
16982 (cond
16983 (from-string (setq ans from-string))
16984 (org-read-date-popup-calendar
16985 (save-excursion
16986 (save-window-excursion
16987 (calendar)
16988 (when (eq calendar-setup 'calendar-only)
16989 (setq cal-frame
16990 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16991 (select-frame cal-frame))
16992 (org-eval-in-calendar '(setq cursor-type nil) t)
16993 (unwind-protect
16994 (progn
16995 (calendar-forward-day (- (time-to-days org-def)
16996 (calendar-absolute-from-gregorian
16997 (calendar-current-date))))
16998 (org-eval-in-calendar nil t)
16999 (let* ((old-map (current-local-map))
17000 (map (copy-keymap calendar-mode-map))
17001 (minibuffer-local-map
17002 (copy-keymap org-read-date-minibuffer-local-map)))
17003 (org-defkey map (kbd "RET") 'org-calendar-select)
17004 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17005 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17006 (unwind-protect
17007 (progn
17008 (use-local-map map)
17009 (setq org-read-date-inactive inactive)
17010 (add-hook 'post-command-hook 'org-read-date-display)
17011 (setq org-ans0
17012 (read-string prompt
17013 default-input
17014 'org-read-date-history
17015 nil))
17016 ;; org-ans0: from prompt
17017 ;; org-ans1: from mouse click
17018 ;; org-ans2: from calendar motion
17019 (setq ans
17020 (concat org-ans0 " " (or org-ans1 org-ans2))))
17021 (remove-hook 'post-command-hook 'org-read-date-display)
17022 (use-local-map old-map)
17023 (when org-read-date-overlay
17024 (delete-overlay org-read-date-overlay)
17025 (setq org-read-date-overlay nil)))))
17026 (bury-buffer "*Calendar*")
17027 (when cal-frame
17028 (delete-frame cal-frame)
17029 (select-frame-set-input-focus cur-frame))))))
17031 (t ; Naked prompt only
17032 (unwind-protect
17033 (setq ans (read-string prompt default-input
17034 'org-read-date-history timestr))
17035 (when org-read-date-overlay
17036 (delete-overlay org-read-date-overlay)
17037 (setq org-read-date-overlay nil))))))
17039 (setq final (org-read-date-analyze ans org-def org-defdecode))
17041 (when org-read-date-analyze-forced-year
17042 (message "Year was forced into %s"
17043 (if org-read-date-force-compatible-dates
17044 "compatible range (1970-2037)"
17045 "range representable on this machine"))
17046 (ding))
17048 ;; One round trip to get rid of 34th of August and stuff like that....
17049 (setq final (decode-time (apply 'encode-time final)))
17051 (setq org-read-date-final-answer ans)
17053 (if to-time
17054 (apply 'encode-time final)
17055 (if (and (boundp 'org-time-was-given) org-time-was-given)
17056 (format "%04d-%02d-%02d %02d:%02d"
17057 (nth 5 final) (nth 4 final) (nth 3 final)
17058 (nth 2 final) (nth 1 final))
17059 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17061 (defun org-read-date-display ()
17062 "Display the current date prompt interpretation in the minibuffer."
17063 (when org-read-date-display-live
17064 (when org-read-date-overlay
17065 (delete-overlay org-read-date-overlay))
17066 (when (minibufferp (current-buffer))
17067 (save-excursion
17068 (end-of-line 1)
17069 (while (not (equal (buffer-substring
17070 (max (point-min) (- (point) 4)) (point))
17071 " "))
17072 (insert " ")))
17073 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17074 " " (or org-ans1 org-ans2)))
17075 (org-end-time-was-given nil)
17076 (f (org-read-date-analyze ans org-def org-defdecode))
17077 (fmts (if org-dcst
17078 org-time-stamp-custom-formats
17079 org-time-stamp-formats))
17080 (fmt (if (or org-with-time
17081 (and (boundp 'org-time-was-given) org-time-was-given))
17082 (cdr fmts)
17083 (car fmts)))
17084 (txt (format-time-string fmt (apply 'encode-time f)))
17085 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17086 (txt (concat "=> " txt)))
17087 (when (and org-end-time-was-given
17088 (string-match org-plain-time-of-day-regexp txt))
17089 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17090 org-end-time-was-given
17091 (substring txt (match-end 0)))))
17092 (when org-read-date-analyze-futurep
17093 (setq txt (concat txt " (=>F)")))
17094 (setq org-read-date-overlay
17095 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17096 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17098 (defun org-read-date-analyze (ans def defdecode)
17099 "Analyze the combined answer of the date prompt."
17100 ;; FIXME: cleanup and comment
17101 ;; Pass `current-time' result to `decode-time' (instead of calling
17102 ;; without arguments) so that only `current-time' has to be
17103 ;; overriden in tests.
17104 (let ((org-def def)
17105 (org-defdecode defdecode)
17106 (nowdecode (decode-time (current-time)))
17107 delta deltan deltaw deltadef year month day
17108 hour minute second wday pm h2 m2 tl wday1
17109 iso-year iso-weekday iso-week iso-date futurep kill-year)
17110 (setq org-read-date-analyze-futurep nil
17111 org-read-date-analyze-forced-year nil)
17112 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17113 (setq ans "+0"))
17115 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17116 (setq ans (replace-match "" t t ans)
17117 deltan (car delta)
17118 deltaw (nth 1 delta)
17119 deltadef (nth 2 delta)))
17121 ;; Check if there is an iso week date in there. If yes, store the
17122 ;; info and postpone interpreting it until the rest of the parsing
17123 ;; is done.
17124 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17125 (setq iso-year (when (match-end 1)
17126 (org-small-year-to-year
17127 (string-to-number (match-string 1 ans))))
17128 iso-weekday (when (match-end 3)
17129 (string-to-number (match-string 3 ans)))
17130 iso-week (string-to-number (match-string 2 ans)))
17131 (setq ans (replace-match "" t t ans)))
17133 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17134 (when (string-match
17135 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17136 (setq year (if (match-end 2)
17137 (string-to-number (match-string 2 ans))
17138 (progn (setq kill-year t)
17139 (string-to-number (format-time-string "%Y"))))
17140 month (string-to-number (match-string 3 ans))
17141 day (string-to-number (match-string 4 ans)))
17142 (setq year (org-small-year-to-year year))
17143 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17144 t nil ans)))
17146 ;; Help matching dotted european dates
17147 (when (string-match
17148 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17149 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17150 (setq kill-year t)
17151 (string-to-number (format-time-string "%Y")))
17152 day (string-to-number (match-string 1 ans))
17153 month (string-to-number (match-string 2 ans))
17154 ans (replace-match (format "%04d-%02d-%02d" year month day)
17155 t nil ans)))
17157 ;; Help matching american dates, like 5/30 or 5/30/7
17158 (when (string-match
17159 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17160 (setq year (if (match-end 4)
17161 (string-to-number (match-string 4 ans))
17162 (progn (setq kill-year t)
17163 (string-to-number (format-time-string "%Y"))))
17164 month (string-to-number (match-string 1 ans))
17165 day (string-to-number (match-string 2 ans)))
17166 (setq year (org-small-year-to-year year))
17167 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17168 t nil ans)))
17169 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17170 ;; If there is a time with am/pm, and *no* time without it, we convert
17171 ;; so that matching will be successful.
17172 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17173 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17174 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17175 (setq hour (string-to-number (match-string 1 ans))
17176 minute (if (match-end 3)
17177 (string-to-number (match-string 3 ans))
17179 pm (equal ?p
17180 (string-to-char (downcase (match-string 4 ans)))))
17181 (if (and (= hour 12) (not pm))
17182 (setq hour 0)
17183 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17184 (setq ans (replace-match (format "%02d:%02d" hour minute)
17185 t t ans))))
17187 ;; Check if a time range is given as a duration
17188 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17189 (setq hour (string-to-number (match-string 1 ans))
17190 h2 (+ hour (string-to-number (match-string 3 ans)))
17191 minute (string-to-number (match-string 2 ans))
17192 m2 (+ minute (if (match-end 5) (string-to-number
17193 (match-string 5 ans))0)))
17194 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17195 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17196 t t ans)))
17198 ;; Check if there is a time range
17199 (when (boundp 'org-end-time-was-given)
17200 (setq org-time-was-given nil)
17201 (when (and (string-match org-plain-time-of-day-regexp ans)
17202 (match-end 8))
17203 (setq org-end-time-was-given (match-string 8 ans))
17204 (setq ans (concat (substring ans 0 (match-beginning 7))
17205 (substring ans (match-end 7))))))
17207 (setq tl (parse-time-string ans)
17208 day (or (nth 3 tl) (nth 3 org-defdecode))
17209 month
17210 (cond ((nth 4 tl))
17211 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17212 ;; Day was specified. Make sure DAY+MONTH
17213 ;; combination happens in the future.
17214 ((nth 3 tl)
17215 (setq futurep t)
17216 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17217 (nth 4 nowdecode)))
17218 (t (nth 4 org-defdecode)))
17219 year
17220 (cond ((and (not kill-year) (nth 5 tl)))
17221 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17222 ;; Month was guessed in the future and is at least
17223 ;; equal to NOWDECODE's. Fix year accordingly.
17224 (futurep
17225 (if (or (> month (nth 4 nowdecode))
17226 (>= day (nth 3 nowdecode)))
17227 (nth 5 nowdecode)
17228 (1+ (nth 5 nowdecode))))
17229 ;; Month was specified. Make sure MONTH+YEAR
17230 ;; combination happens in the future.
17231 ((nth 4 tl)
17232 (setq futurep t)
17233 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17234 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17235 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17236 (t (nth 5 nowdecode))))
17237 (t (nth 5 org-defdecode)))
17238 hour (or (nth 2 tl) (nth 2 org-defdecode))
17239 minute (or (nth 1 tl) (nth 1 org-defdecode))
17240 second (or (nth 0 tl) 0)
17241 wday (nth 6 tl))
17243 (when (and (eq org-read-date-prefer-future 'time)
17244 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17245 (equal day (nth 3 nowdecode))
17246 (equal month (nth 4 nowdecode))
17247 (equal year (nth 5 nowdecode))
17248 (nth 2 tl)
17249 (or (< (nth 2 tl) (nth 2 nowdecode))
17250 (and (= (nth 2 tl) (nth 2 nowdecode))
17251 (nth 1 tl)
17252 (< (nth 1 tl) (nth 1 nowdecode)))))
17253 (setq day (1+ day)
17254 futurep t))
17256 ;; Special date definitions below
17257 (cond
17258 (iso-week
17259 ;; There was an iso week
17260 (require 'cal-iso)
17261 (setq futurep nil)
17262 (setq year (or iso-year year)
17263 day (or iso-weekday wday 1)
17264 wday nil ; to make sure that the trigger below does not match
17265 iso-date (calendar-gregorian-from-absolute
17266 (calendar-iso-to-absolute
17267 (list iso-week day year))))
17268 ; FIXME: Should we also push ISO weeks into the future?
17269 ; (when (and org-read-date-prefer-future
17270 ; (not iso-year)
17271 ; (< (calendar-absolute-from-gregorian iso-date)
17272 ; (time-to-days (current-time))))
17273 ; (setq year (1+ year)
17274 ; iso-date (calendar-gregorian-from-absolute
17275 ; (calendar-iso-to-absolute
17276 ; (list iso-week day year)))))
17277 (setq month (car iso-date)
17278 year (nth 2 iso-date)
17279 day (nth 1 iso-date)))
17280 (deltan
17281 (setq futurep nil)
17282 (unless deltadef
17283 ;; Pass `current-time' result to `decode-time' (instead of
17284 ;; calling without arguments) so that only `current-time' has
17285 ;; to be overriden in tests.
17286 (let ((now (decode-time (current-time))))
17287 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17288 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17289 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17290 ((equal deltaw "m") (setq month (+ month deltan)))
17291 ((equal deltaw "y") (setq year (+ year deltan)))))
17292 ((and wday (not (nth 3 tl)))
17293 ;; Weekday was given, but no day, so pick that day in the week
17294 ;; on or after the derived date.
17295 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17296 (unless (equal wday wday1)
17297 (setq day (+ day (% (- wday wday1 -7) 7))))))
17298 (when (and (boundp 'org-time-was-given)
17299 (nth 2 tl))
17300 (setq org-time-was-given t))
17301 (when (< year 100) (setq year (+ 2000 year)))
17302 ;; Check of the date is representable
17303 (if org-read-date-force-compatible-dates
17304 (progn
17305 (when (< year 1970)
17306 (setq year 1970 org-read-date-analyze-forced-year t))
17307 (when (> year 2037)
17308 (setq year 2037 org-read-date-analyze-forced-year t)))
17309 (condition-case nil
17310 (ignore (encode-time second minute hour day month year))
17311 (error
17312 (setq year (nth 5 org-defdecode))
17313 (setq org-read-date-analyze-forced-year t))))
17314 (setq org-read-date-analyze-futurep futurep)
17315 (list second minute hour day month year)))
17317 (defvar parse-time-weekdays)
17318 (defun org-read-date-get-relative (s today default)
17319 "Check string S for special relative date string.
17320 TODAY and DEFAULT are internal times, for today and for a default.
17321 Return shift list (N what def-flag)
17322 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17323 N is the number of WHATs to shift.
17324 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17325 the DEFAULT date rather than TODAY."
17326 (require 'parse-time)
17327 (when (and
17328 (string-match
17329 (concat
17330 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17331 "\\([0-9]+\\)?"
17332 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17333 "\\([ \t]\\|$\\)") s)
17334 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17335 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17336 (string-to-char (substring (match-string 1 s) -1))
17337 ?+))
17338 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17339 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17340 (what (if (match-end 3) (match-string 3 s) "d"))
17341 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17342 (date (if rel default today))
17343 (wday (nth 6 (decode-time date)))
17344 delta)
17345 (if wday1
17346 (progn
17347 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17348 (when (= delta 0) (setq delta 7))
17349 (when (= dir ?-)
17350 (setq delta (- delta 7))
17351 (when (= delta 0) (setq delta -7)))
17352 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17353 (list delta "d" rel))
17354 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17356 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17357 "Turn a user-specified date into the internal representation.
17358 The internal representation needed by the calendar is (month day year).
17359 This is a wrapper to handle the brain-dead convention in calendar that
17360 user function argument order change dependent on argument order."
17361 (pcase calendar-date-style
17362 (`american (list arg1 arg2 arg3))
17363 (`european (list arg2 arg1 arg3))
17364 (`iso (list arg2 arg3 arg1))))
17366 (defun org-eval-in-calendar (form &optional keepdate)
17367 "Eval FORM in the calendar window and return to current window.
17368 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17369 (let ((sf (selected-frame))
17370 (sw (selected-window)))
17371 (select-window (get-buffer-window "*Calendar*" t))
17372 (eval form)
17373 (when (and (not keepdate) (calendar-cursor-to-date))
17374 (let* ((date (calendar-cursor-to-date))
17375 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17376 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17377 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17378 (select-window sw)
17379 (select-frame-set-input-focus sf)))
17381 (defun org-calendar-select ()
17382 "Return to `org-read-date' with the date currently selected.
17383 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17384 (interactive)
17385 (when (calendar-cursor-to-date)
17386 (let* ((date (calendar-cursor-to-date))
17387 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17388 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17389 (when (active-minibuffer-window) (exit-minibuffer))))
17391 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17392 "Insert a date stamp for the date given by the internal TIME.
17393 See `format-time-string' for the format of TIME.
17394 WITH-HM means use the stamp format that includes the time of the day.
17395 INACTIVE means use square brackets instead of angular ones, so that the
17396 stamp will not contribute to the agenda.
17397 PRE and POST are optional strings to be inserted before and after the
17398 stamp.
17399 The command returns the inserted time stamp."
17400 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17401 stamp)
17402 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17403 (insert-before-markers (or pre ""))
17404 (when (listp extra)
17405 (setq extra (car extra))
17406 (if (and (stringp extra)
17407 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17408 (setq extra (format "-%02d:%02d"
17409 (string-to-number (match-string 1 extra))
17410 (string-to-number (match-string 2 extra))))
17411 (setq extra nil)))
17412 (when extra
17413 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17414 (insert-before-markers (setq stamp (format-time-string fmt time)))
17415 (insert-before-markers (or post ""))
17416 (setq org-last-inserted-timestamp stamp)))
17418 (defun org-toggle-time-stamp-overlays ()
17419 "Toggle the use of custom time stamp formats."
17420 (interactive)
17421 (setq org-display-custom-times (not org-display-custom-times))
17422 (unless org-display-custom-times
17423 (let ((p (point-min)) (bmp (buffer-modified-p)))
17424 (while (setq p (next-single-property-change p 'display))
17425 (when (and (get-text-property p 'display)
17426 (eq (get-text-property p 'face) 'org-date))
17427 (remove-text-properties
17428 p (setq p (next-single-property-change p 'display))
17429 '(display t))))
17430 (set-buffer-modified-p bmp)))
17431 (org-restart-font-lock)
17432 (setq org-table-may-need-update t)
17433 (if org-display-custom-times
17434 (message "Time stamps are overlaid with custom format")
17435 (message "Time stamp overlays removed")))
17437 (defun org-display-custom-time (beg end)
17438 "Overlay modified time stamp format over timestamp between BEG and END."
17439 (let* ((ts (buffer-substring beg end))
17440 t1 w1 with-hm tf time str w2 (off 0))
17441 (save-match-data
17442 (setq t1 (org-parse-time-string ts t))
17443 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17444 (setq off (- (match-end 0) (match-beginning 0)))))
17445 (setq end (- end off))
17446 (setq w1 (- end beg)
17447 with-hm (and (nth 1 t1) (nth 2 t1))
17448 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17449 time (org-fix-decoded-time t1)
17450 str (org-add-props
17451 (format-time-string
17452 (substring tf 1 -1) (apply 'encode-time time))
17453 nil 'mouse-face 'highlight)
17454 w2 (length str))
17455 (unless (= w2 w1)
17456 (add-text-properties (1+ beg) (+ 2 beg)
17457 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17458 (put-text-property beg end 'display str)))
17460 (defun org-fix-decoded-time (time)
17461 "Set 0 instead of nil for the first 6 elements of time.
17462 Don't touch the rest."
17463 (let ((n 0))
17464 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17466 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17467 "Difference between TIMESTAMP-STRING and now in days.
17468 If SECONDS is non-nil, return the difference in seconds."
17469 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17470 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17471 (funcall fdiff (current-time)))))
17473 (defun org-deadline-close-p (timestamp-string &optional ndays)
17474 "Is the time in TIMESTAMP-STRING close to the current date?"
17475 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17476 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17477 (not (org-entry-is-done-p))))
17479 (defun org-get-wdays (ts &optional delay zero-delay)
17480 "Get the deadline lead time appropriate for timestring TS.
17481 When DELAY is non-nil, get the delay time for scheduled items
17482 instead of the deadline lead time. When ZERO-DELAY is non-nil
17483 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17484 don't try to find the delay cookie in the scheduled timestamp."
17485 (let ((tv (if delay org-scheduled-delay-days
17486 org-deadline-warning-days)))
17487 (cond
17488 ((or (and delay (< tv 0))
17489 (and delay zero-delay (<= tv 0))
17490 (and (not delay) (<= tv 0)))
17491 ;; Enforce this value no matter what
17492 (- tv))
17493 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17494 ;; lead time is specified.
17495 (floor (* (string-to-number (match-string 1 ts))
17496 (cdr (assoc (match-string 2 ts)
17497 '(("d" . 1) ("w" . 7)
17498 ("m" . 30.4) ("y" . 365.25)
17499 ("h" . 0.041667)))))))
17500 ;; go for the default.
17501 (t tv))))
17503 (defun org-calendar-select-mouse (ev)
17504 "Return to `org-read-date' with the date currently selected.
17505 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17506 (interactive "e")
17507 (mouse-set-point ev)
17508 (when (calendar-cursor-to-date)
17509 (let* ((date (calendar-cursor-to-date))
17510 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17511 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17512 (when (active-minibuffer-window) (exit-minibuffer))))
17514 (defun org-check-deadlines (ndays)
17515 "Check if there are any deadlines due or past due.
17516 A deadline is considered due if it happens within `org-deadline-warning-days'
17517 days from today's date. If the deadline appears in an entry marked DONE,
17518 it is not shown. A numeric prefix argument NDAYS can be used to test that
17519 many days. If the prefix is a raw `\\[universal-argument]', all deadlines \
17520 are shown."
17521 (interactive "P")
17522 (let* ((org-warn-days
17523 (cond
17524 ((equal ndays '(4)) 100000)
17525 (ndays (prefix-numeric-value ndays))
17526 (t (abs org-deadline-warning-days))))
17527 (case-fold-search nil)
17528 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17529 (callback
17530 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17531 (message "%d deadlines past-due or due within %d days"
17532 (org-occur regexp nil callback)
17533 org-warn-days)))
17535 (defsubst org-re-timestamp (type)
17536 "Return a regexp for timestamp TYPE.
17537 Allowed values for TYPE are:
17539 all: all timestamps
17540 active: only active timestamps (<...>)
17541 inactive: only inactive timestamps ([...])
17542 scheduled: only scheduled timestamps
17543 deadline: only deadline timestamps
17544 closed: only closed time-stamps
17546 When TYPE is nil, fall back on returning a regexp that matches
17547 both scheduled and deadline timestamps."
17548 (cl-case type
17549 (all org-ts-regexp-both)
17550 (active org-ts-regexp)
17551 (inactive org-ts-regexp-inactive)
17552 (scheduled org-scheduled-time-regexp)
17553 (deadline org-deadline-time-regexp)
17554 (closed org-closed-time-regexp)
17555 (otherwise
17556 (concat "\\<"
17557 (regexp-opt (list org-deadline-string org-scheduled-string))
17558 " *<\\([^>]+\\)>"))))
17560 (defun org-check-before-date (d)
17561 "Check if there are deadlines or scheduled entries before date D."
17562 (interactive (list (org-read-date)))
17563 (let* ((case-fold-search nil)
17564 (regexp (org-re-timestamp org-ts-type))
17565 (ts-type org-ts-type)
17566 (callback
17567 (lambda ()
17568 (let ((match (match-string 1)))
17569 (and (if (memq ts-type '(active inactive all))
17570 (eq (org-element-type (save-excursion
17571 (backward-char)
17572 (org-element-context)))
17573 'timestamp)
17574 (org-at-planning-p))
17575 (time-less-p
17576 (org-time-string-to-time match)
17577 (org-time-string-to-time d)))))))
17578 (message "%d entries before %s"
17579 (org-occur regexp nil callback)
17580 d)))
17582 (defun org-check-after-date (d)
17583 "Check if there are deadlines or scheduled entries after date D."
17584 (interactive (list (org-read-date)))
17585 (let* ((case-fold-search nil)
17586 (regexp (org-re-timestamp org-ts-type))
17587 (ts-type org-ts-type)
17588 (callback
17589 (lambda ()
17590 (let ((match (match-string 1)))
17591 (and (if (memq ts-type '(active inactive all))
17592 (eq (org-element-type (save-excursion
17593 (backward-char)
17594 (org-element-context)))
17595 'timestamp)
17596 (org-at-planning-p))
17597 (not (time-less-p
17598 (org-time-string-to-time match)
17599 (org-time-string-to-time d))))))))
17600 (message "%d entries after %s"
17601 (org-occur regexp nil callback)
17602 d)))
17604 (defun org-check-dates-range (start-date end-date)
17605 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17606 (interactive (list (org-read-date nil nil nil "Range starts")
17607 (org-read-date nil nil nil "Range end")))
17608 (let ((case-fold-search nil)
17609 (regexp (org-re-timestamp org-ts-type))
17610 (callback
17611 (let ((type org-ts-type))
17612 (lambda ()
17613 (let ((match (match-string 1)))
17614 (and
17615 (if (memq type '(active inactive all))
17616 (eq (org-element-type (save-excursion
17617 (backward-char)
17618 (org-element-context)))
17619 'timestamp)
17620 (org-at-planning-p))
17621 (not (time-less-p
17622 (org-time-string-to-time match)
17623 (org-time-string-to-time start-date)))
17624 (time-less-p
17625 (org-time-string-to-time match)
17626 (org-time-string-to-time end-date))))))))
17627 (message "%d entries between %s and %s"
17628 (org-occur regexp nil callback) start-date end-date)))
17630 (defun org-evaluate-time-range (&optional to-buffer)
17631 "Evaluate a time range by computing the difference between start and end.
17632 Normally the result is just printed in the echo area, but with prefix arg
17633 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17634 If the time range is actually in a table, the result is inserted into the
17635 next column.
17636 For time difference computation, a year is assumed to be exactly 365
17637 days in order to avoid rounding problems."
17638 (interactive "P")
17640 (org-clock-update-time-maybe)
17641 (save-excursion
17642 (unless (org-at-date-range-p t)
17643 (goto-char (point-at-bol))
17644 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17645 (unless (org-at-date-range-p t)
17646 (user-error "Not at a time-stamp range, and none found in current line")))
17647 (let* ((ts1 (match-string 1))
17648 (ts2 (match-string 2))
17649 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17650 (match-end (match-end 0))
17651 (time1 (org-time-string-to-time ts1))
17652 (time2 (org-time-string-to-time ts2))
17653 (t1 (float-time time1))
17654 (t2 (float-time time2))
17655 (diff (abs (- t2 t1)))
17656 (negative (< (- t2 t1) 0))
17657 ;; (ys (floor (* 365 24 60 60)))
17658 (ds (* 24 60 60))
17659 (hs (* 60 60))
17660 (fy "%dy %dd %02d:%02d")
17661 (fy1 "%dy %dd")
17662 (fd "%dd %02d:%02d")
17663 (fd1 "%dd")
17664 (fh "%02d:%02d")
17665 y d h m align)
17666 (if havetime
17667 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17669 d (floor (/ diff ds)) diff (mod diff ds)
17670 h (floor (/ diff hs)) diff (mod diff hs)
17671 m (floor (/ diff 60)))
17672 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17674 d (floor (+ (/ diff ds) 0.5))
17675 h 0 m 0))
17676 (if (not to-buffer)
17677 (message "%s" (org-make-tdiff-string y d h m))
17678 (if (org-at-table-p)
17679 (progn
17680 (goto-char match-end)
17681 (setq align t)
17682 (and (looking-at " *|") (goto-char (match-end 0))))
17683 (goto-char match-end))
17684 (when (looking-at
17685 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17686 (replace-match ""))
17687 (when negative (insert " -"))
17688 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17689 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17690 (insert " " (format fh h m))))
17691 (when align (org-table-align))
17692 (message "Time difference inserted")))))
17694 (defun org-make-tdiff-string (y d h m)
17695 (let ((fmt "")
17696 (l nil))
17697 (when (> y 0)
17698 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17699 (push y l))
17700 (when (> d 0)
17701 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17702 (push d l))
17703 (when (> h 0)
17704 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17705 (push h l))
17706 (when (> m 0)
17707 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17708 (push m l))
17709 (apply 'format fmt (nreverse l))))
17711 (defun org-time-string-to-time (s &optional buffer pos)
17712 "Convert a timestamp string into internal time."
17713 (condition-case errdata
17714 (apply 'encode-time (org-parse-time-string s))
17715 (error (error "Bad timestamp `%s'%s\nError was: %s"
17716 s (if (not (and buffer pos))
17718 (format-message " at %d in buffer `%s'" pos buffer))
17719 (cdr errdata)))))
17721 (defun org-time-string-to-seconds (s)
17722 "Convert a timestamp string to a number of seconds."
17723 (float-time (org-time-string-to-time s)))
17725 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17727 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
17728 "Convert time stamp S to an absolute day number.
17730 If DAYNR in non-nil, and there is a specifier for a cyclic time
17731 stamp, get the closest date to DAYNR. If PREFER is
17732 `past' (respectively `future') return a date past (respectively
17733 after) or equal to DAYNR.
17735 POS is the location of time stamp S, as a buffer position in
17736 BUFFER.
17738 Diary sexp timestamps are matched against DAYNR, when non-nil.
17739 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17740 signalled."
17741 (cond
17742 ((string-match "\\`%%\\((.*)\\)" s)
17743 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17744 ;; only able to match individual dates. If it fails, raise an
17745 ;; error.
17746 (if (and daynr
17747 (org-diary-sexp-entry
17748 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17749 daynr
17750 (signal 'org-diary-sexp-no-match (list s))))
17751 (daynr (org-closest-date s daynr prefer))
17752 (t (time-to-days
17753 (condition-case errdata
17754 (apply #'encode-time (org-parse-time-string s))
17755 (error (error "Bad timestamp `%s'%s\nError was: %s"
17757 (if (not (and buffer pos)) ""
17758 (format-message " at %d in buffer `%s'" pos buffer))
17759 (cdr errdata))))))))
17761 (defun org-days-to-iso-week (days)
17762 "Return the iso week number."
17763 (require 'cal-iso)
17764 (car (calendar-iso-from-absolute days)))
17766 (defun org-small-year-to-year (year)
17767 "Convert 2-digit years into 4-digit years.
17768 YEAR is expanded into one of the 30 next years, if possible, or
17769 into a past one. Any year larger than 99 is returned unchanged."
17770 (if (>= year 100) year
17771 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17772 (century (/ current 100))
17773 (offset (- year (% current 100))))
17774 (cond ((> offset 30) (+ (* (1- century) 100) year))
17775 ((> offset -70) (+ (* century 100) year))
17776 (t (+ (* (1+ century) 100) year))))))
17778 (defun org-time-from-absolute (d)
17779 "Return the time corresponding to date D.
17780 D may be an absolute day number, or a calendar-type list (month day year)."
17781 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17782 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17784 (defvar org-agenda-current-date)
17785 (defun org-calendar-holiday ()
17786 "List of holidays, for Diary display in Org mode."
17787 (require 'holidays)
17788 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17789 (and hl (mapconcat #'identity hl "; "))))
17791 (defun org-diary-sexp-entry (sexp entry d)
17792 "Process a SEXP diary ENTRY for date D."
17793 (require 'diary-lib)
17794 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17795 ;; dynamically.
17796 (let* ((sexp `(let ((entry ,entry)
17797 (date ',d))
17798 ,(car (read-from-string sexp))))
17799 (result (if calendar-debug-sexp (eval sexp)
17800 (condition-case nil
17801 (eval sexp)
17802 (error
17803 (beep)
17804 (message "Bad sexp at line %d in %s: %s"
17805 (org-current-line)
17806 (buffer-file-name) sexp)
17807 (sleep-for 2))))))
17808 (cond ((stringp result) (split-string result "; "))
17809 ((and (consp result)
17810 (not (consp (cdr result)))
17811 (stringp (cdr result))) (cdr result))
17812 ((and (consp result)
17813 (stringp (car result))) result)
17814 (result entry))))
17816 (defun org-diary-to-ical-string (frombuf)
17817 "Get iCalendar entries from diary entries in buffer FROMBUF.
17818 This uses the icalendar.el library."
17819 (let* ((tmpdir temporary-file-directory)
17820 (tmpfile (make-temp-name
17821 (expand-file-name "orgics" tmpdir)))
17822 buf rtn b e)
17823 (with-current-buffer frombuf
17824 (icalendar-export-region (point-min) (point-max) tmpfile)
17825 (setq buf (find-buffer-visiting tmpfile))
17826 (set-buffer buf)
17827 (goto-char (point-min))
17828 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17829 (setq b (match-beginning 0)))
17830 (goto-char (point-max))
17831 (when (re-search-backward "^END:VEVENT" nil t)
17832 (setq e (match-end 0)))
17833 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17834 (kill-buffer buf)
17835 (delete-file tmpfile)
17836 rtn))
17838 (defun org-closest-date (start current prefer)
17839 "Return closest date to CURRENT starting from START.
17841 CURRENT and START are both time stamps.
17843 When PREFER is `past', return a date that is either CURRENT or
17844 past. When PREFER is `future', return a date that is either
17845 CURRENT or future.
17847 Only time stamps with a repeater are modified. Any other time
17848 stamp stay unchanged. In any case, return value is an absolute
17849 day number."
17850 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17851 ;; No repeater. Do not shift time stamp.
17852 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17853 (let ((value (string-to-number (match-string 1 start)))
17854 (type (match-string 2 start)))
17855 (if (= 0 value)
17856 ;; Repeater with a 0-value is considered as void.
17857 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17858 (let* ((base (org-date-to-gregorian start))
17859 (target (org-date-to-gregorian current))
17860 (sday (calendar-absolute-from-gregorian base))
17861 (cday (calendar-absolute-from-gregorian target))
17862 n1 n2)
17863 ;; If START is already past CURRENT, just return START.
17864 (if (<= cday sday) sday
17865 ;; Compute closest date before (N1) and closest date past
17866 ;; (N2) CURRENT.
17867 (pcase type
17868 ("h"
17869 (let ((missing-hours
17870 (mod (+ (- (* 24 (- cday sday))
17871 (nth 2 (org-parse-time-string start)))
17872 org-extend-today-until)
17873 value)))
17874 (setf n1 (if (= missing-hours 0) cday
17875 (- cday (1+ (/ missing-hours 24)))))
17876 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17877 ((or "d" "w")
17878 (let ((value (if (equal type "w") (* 7 value) value)))
17879 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17880 (setf n2 (+ n1 value))))
17881 ("m"
17882 (let* ((add-months
17883 (lambda (d n)
17884 ;; Add N months to gregorian date D, i.e.,
17885 ;; a list (MONTH DAY YEAR). Return a valid
17886 ;; gregorian date.
17887 (let ((m (+ (nth 0 d) n)))
17888 (list (mod m 12)
17889 (nth 1 d)
17890 (+ (/ m 12) (nth 2 d))))))
17891 (months ; Complete months to TARGET.
17892 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17893 (- (nth 0 target) (nth 0 base))
17894 ;; If START's day is greater than
17895 ;; TARGET's, remove incomplete month.
17896 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17897 value)
17898 value))
17899 (before (funcall add-months base months)))
17900 (setf n1 (calendar-absolute-from-gregorian before))
17901 (setf n2
17902 (calendar-absolute-from-gregorian
17903 (funcall add-months before value)))))
17905 (let* ((d (nth 1 base))
17906 (m (nth 0 base))
17907 (y (nth 2 base))
17908 (years ; Complete years to TARGET.
17909 (* (/ (- (nth 2 target)
17911 ;; If START's month and day are
17912 ;; greater than TARGET's, remove
17913 ;; incomplete year.
17914 (if (or (> (nth 0 target) m)
17915 (and (= (nth 0 target) m)
17916 (> (nth 1 target) d)))
17919 value)
17920 value))
17921 (before (list m d (+ y years))))
17922 (setf n1 (calendar-absolute-from-gregorian before))
17923 (setf n2 (calendar-absolute-from-gregorian
17924 (list m d (+ (nth 2 before) value)))))))
17925 ;; Handle PREFER parameter, if any.
17926 (cond
17927 ((eq prefer 'past) (if (= cday n2) n2 n1))
17928 ((eq prefer 'future) (if (= cday n1) n1 n2))
17929 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17931 (defun org-date-to-gregorian (d)
17932 "Turn any specification of date D into a Gregorian date for the calendar."
17933 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17934 ((and (listp d) (= (length d) 3)) d)
17935 ((stringp d)
17936 (let ((d (org-parse-time-string d)))
17937 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17938 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17940 (defun org-parse-time-string (s &optional nodefault zone)
17941 "Parse the standard Org time string.
17943 This should be a lot faster than the normal `parse-time-string'.
17945 If time is not given, defaults to 0:00. However, with optional
17946 NODEFAULT, hour and minute fields will be nil if not given.
17948 The optional ZONE is omitted or nil for Emacs local time, t for
17949 Universal Time, ‘wall’ for system wall clock time, or a string as
17950 in the TZ environment variable."
17951 (cond ((string-match org-ts-regexp0 s)
17952 (list 0
17953 (when (or (match-beginning 8) (not nodefault))
17954 (string-to-number (or (match-string 8 s) "0")))
17955 (when (or (match-beginning 7) (not nodefault))
17956 (string-to-number (or (match-string 7 s) "0")))
17957 (string-to-number (match-string 4 s))
17958 (string-to-number (match-string 3 s))
17959 (string-to-number (match-string 2 s))
17960 nil nil zone))
17961 ((string-match "^<[^>]+>$" s)
17962 (decode-time (seconds-to-time (org-matcher-time s)) zone))
17963 (t (error "Not a standard Org time string: %s" s))))
17965 (defun org-timestamp-up (&optional arg)
17966 "Increase the date item at the cursor by one.
17967 If the cursor is on the year, change the year. If it is on the month,
17968 the day or the time, change that.
17969 With prefix ARG, change by that many units."
17970 (interactive "p")
17971 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17973 (defun org-timestamp-down (&optional arg)
17974 "Decrease the date item at the cursor by one.
17975 If the cursor is on the year, change the year. If it is on the month,
17976 the day or the time, change that.
17977 With prefix ARG, change by that many units."
17978 (interactive "p")
17979 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17981 (defun org-timestamp-up-day (&optional arg)
17982 "Increase the date in the time stamp by one day.
17983 With prefix ARG, change that many days."
17984 (interactive "p")
17985 (if (and (not (org-at-timestamp-p t))
17986 (org-at-heading-p))
17987 (org-todo 'up)
17988 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17990 (defun org-timestamp-down-day (&optional arg)
17991 "Decrease 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 'down)
17997 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17999 (defun org-at-timestamp-p (&optional inactive-ok)
18000 "Non-nil if point is inside a timestamp.
18002 When optional argument INACTIVE-OK is non-nil, also consider
18003 inactive timestamps.
18005 When this function returns a non-nil value, match data is set
18006 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18007 INACTIVE-OK."
18008 (interactive)
18009 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18010 (pos (point))
18011 (ans (or (looking-at tsr)
18012 (save-excursion
18013 (skip-chars-backward "^[<\n\r\t")
18014 (when (> (point) (point-min)) (backward-char 1))
18015 (and (looking-at tsr)
18016 (> (- (match-end 0) pos) -1))))))
18017 (and ans
18018 (boundp 'org-ts-what)
18019 (setq org-ts-what
18020 (cond
18021 ((= pos (match-beginning 0)) 'bracket)
18022 ;; Point is considered to be "on the bracket" whether
18023 ;; it's really on it or right after it.
18024 ((= pos (1- (match-end 0))) 'bracket)
18025 ((= pos (match-end 0)) 'after)
18026 ((org-pos-in-match-range pos 2) 'year)
18027 ((org-pos-in-match-range pos 3) 'month)
18028 ((org-pos-in-match-range pos 7) 'hour)
18029 ((org-pos-in-match-range pos 8) 'minute)
18030 ((or (org-pos-in-match-range pos 4)
18031 (org-pos-in-match-range pos 5)) 'day)
18032 ((and (> pos (or (match-end 8) (match-end 5)))
18033 (< pos (match-end 0)))
18034 (- pos (or (match-end 8) (match-end 5))))
18035 (t 'day))))
18036 ans))
18038 (defun org-toggle-timestamp-type ()
18039 "Toggle the type (<active> or [inactive]) of a time stamp."
18040 (interactive)
18041 (when (org-at-timestamp-p t)
18042 (let ((beg (match-beginning 0)) (end (match-end 0))
18043 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18044 (save-excursion
18045 (goto-char beg)
18046 (while (re-search-forward "[][<>]" end t)
18047 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18048 t t)))
18049 (message "Timestamp is now %sactive"
18050 (if (equal (char-after beg) ?<) "" "in")))))
18052 (defun org-at-clock-log-p nil
18053 "Is the cursor on the clock log line?"
18054 (save-excursion
18055 (beginning-of-line)
18056 (looking-at org-clock-line-re)))
18058 (defvar org-clock-history) ; defined in org-clock.el
18059 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18060 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18061 "Change the date in the time stamp at point.
18062 The date will be changed by N times WHAT. WHAT can be `day', `month',
18063 `year', `minute', `second'. If WHAT is not given, the cursor position
18064 in the timestamp determines what will be changed.
18065 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18066 (let ((origin (point)) origin-cat
18067 with-hm inactive
18068 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18069 org-ts-what
18070 extra rem
18071 ts time time0 fixnext clrgx)
18072 (unless (org-at-timestamp-p t)
18073 (user-error "Not at a timestamp"))
18074 (if (and (not what) (eq org-ts-what 'bracket))
18075 (org-toggle-timestamp-type)
18076 ;; Point isn't on brackets. Remember the part of the time-stamp
18077 ;; the point was in. Indeed, size of time-stamps may change,
18078 ;; but point must be kept in the same category nonetheless.
18079 (setq origin-cat org-ts-what)
18080 (when (and (not what) (not (eq org-ts-what 'day))
18081 org-display-custom-times
18082 (get-text-property (point) 'display)
18083 (not (get-text-property (1- (point)) 'display)))
18084 (setq org-ts-what 'day))
18085 (setq org-ts-what (or what org-ts-what)
18086 inactive (= (char-after (match-beginning 0)) ?\[)
18087 ts (match-string 0))
18088 (replace-match "")
18089 (when (string-match
18090 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18092 (setq extra (match-string 1 ts))
18093 (when suppress-tmp-delay
18094 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18095 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18096 (setq with-hm t))
18097 (setq time0 (org-parse-time-string ts))
18098 (when (and updown
18099 (eq org-ts-what 'minute)
18100 (not current-prefix-arg))
18101 ;; This looks like s-up and s-down. Change by one rounding step.
18102 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18103 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18104 (setcar (cdr time0) (+ (nth 1 time0)
18105 (if (> n 0) (- rem) (- dm rem))))))
18106 (setq time
18107 (apply #'encode-time
18108 (or (car time0) 0)
18109 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18110 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18111 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18112 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18113 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18114 (nthcdr 6 time0)))
18115 (when (and (member org-ts-what '(hour minute))
18116 extra
18117 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18118 (setq extra (org-modify-ts-extra
18119 extra
18120 (if (eq org-ts-what 'hour) 2 5)
18121 n dm)))
18122 (when (integerp org-ts-what)
18123 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18124 (when (eq what 'calendar)
18125 (let ((cal-date (org-get-date-from-calendar)))
18126 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18127 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18128 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18129 (setcar time0 (or (car time0) 0))
18130 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18131 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18132 (setq time (apply 'encode-time time0))))
18133 ;; Insert the new time-stamp, and ensure point stays in the same
18134 ;; category as before (i.e. not after the last position in that
18135 ;; category).
18136 (let ((pos (point)))
18137 ;; Stay before inserted string. `save-excursion' is of no use.
18138 (setq org-last-changed-timestamp
18139 (org-insert-time-stamp time with-hm inactive nil nil extra))
18140 (goto-char pos))
18141 (save-match-data
18142 (looking-at org-ts-regexp3)
18143 (goto-char
18144 (pcase origin-cat
18145 ;; `day' category ends before `hour' if any, or at the end
18146 ;; of the day name.
18147 (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
18148 (`hour (min (match-end 7) origin))
18149 (`minute (min (1- (match-end 8)) origin))
18150 ((pred integerp) (min (1- (match-end 0)) origin))
18151 ;; Point was right after the time-stamp. However, the
18152 ;; time-stamp length might have changed, so refer to
18153 ;; (match-end 0) instead.
18154 (`after (match-end 0))
18155 ;; `year' and `month' have both fixed size: point couldn't
18156 ;; have moved into another part.
18157 (_ origin))))
18158 ;; Update clock if on a CLOCK line.
18159 (org-clock-update-time-maybe)
18160 ;; Maybe adjust the closest clock in `org-clock-history'
18161 (when org-clock-adjust-closest
18162 (if (not (and (org-at-clock-log-p)
18163 (< 1 (length (delq nil (mapcar 'marker-position
18164 org-clock-history))))))
18165 (message "No clock to adjust")
18166 (cond ((save-excursion ; fix previous clock?
18167 (re-search-backward org-ts-regexp0 nil t)
18168 (looking-back (concat org-clock-string " \\[")
18169 (line-beginning-position)))
18170 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18171 ((save-excursion ; fix next clock?
18172 (re-search-backward org-ts-regexp0 nil t)
18173 (looking-at (concat org-ts-regexp0 "\\] =>")))
18174 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18175 (save-window-excursion
18176 ;; Find closest clock to point, adjust the previous/next one in history
18177 (let* ((p (save-excursion (org-back-to-heading t)))
18178 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18179 (clfixnth
18180 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18181 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18182 (if (not clfixpos)
18183 (message "No clock to adjust")
18184 (save-excursion
18185 (org-goto-marker-or-bmk clfixpos)
18186 (org-show-subtree)
18187 (when (re-search-forward clrgx nil t)
18188 (goto-char (match-beginning 1))
18189 (let (org-clock-adjust-closest)
18190 (org-timestamp-change n org-ts-what updown))
18191 (message "Clock adjusted in %s for heading: %s"
18192 (file-name-nondirectory (buffer-file-name))
18193 (org-get-heading t t)))))))))
18194 ;; Try to recenter the calendar window, if any.
18195 (when (and org-calendar-follow-timestamp-change
18196 (get-buffer-window "*Calendar*" t)
18197 (memq org-ts-what '(day month year)))
18198 (org-recenter-calendar (time-to-days time))))))
18200 (defun org-modify-ts-extra (s pos n dm)
18201 "Change the different parts of the lead-time and repeat fields in timestamp."
18202 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18203 ng h m new rem)
18204 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18205 (cond
18206 ((or (org-pos-in-match-range pos 2)
18207 (org-pos-in-match-range pos 3))
18208 (setq m (string-to-number (match-string 3 s))
18209 h (string-to-number (match-string 2 s)))
18210 (if (org-pos-in-match-range pos 2)
18211 (setq h (+ h n))
18212 (setq n (* dm (with-no-warnings (signum n))))
18213 (unless (= 0 (setq rem (% m dm)))
18214 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18215 (setq m (+ m n)))
18216 (when (< m 0) (setq m (+ m 60) h (1- h)))
18217 (when (> m 59) (setq m (- m 60) h (1+ h)))
18218 (setq h (mod h 24))
18219 (setq ng 1 new (format "-%02d:%02d" h m)))
18220 ((org-pos-in-match-range pos 6)
18221 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18222 ((org-pos-in-match-range pos 5)
18223 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18225 ((org-pos-in-match-range pos 9)
18226 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18227 ((org-pos-in-match-range pos 8)
18228 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18230 (when ng
18231 (setq s (concat
18232 (substring s 0 (match-beginning ng))
18234 (substring s (match-end ng))))))
18237 (defun org-recenter-calendar (d)
18238 "If the calendar is visible, recenter it to date D."
18239 (let ((cwin (get-buffer-window "*Calendar*" t)))
18240 (when cwin
18241 (let ((calendar-move-hook nil))
18242 (with-selected-window cwin
18243 (calendar-goto-date
18244 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18246 (defun org-goto-calendar (&optional arg)
18247 "Go to the Emacs calendar at the current date.
18248 If there is a time stamp in the current line, go to that date.
18249 A prefix ARG can be used to force the current date."
18250 (interactive "P")
18251 (let ((tsr org-ts-regexp) diff
18252 (calendar-move-hook nil)
18253 (calendar-view-holidays-initially-flag nil)
18254 (calendar-view-diary-initially-flag nil))
18255 (when (or (org-at-timestamp-p)
18256 (save-excursion
18257 (beginning-of-line 1)
18258 (looking-at (concat ".*" tsr))))
18259 (let ((d1 (time-to-days (current-time)))
18260 (d2 (time-to-days
18261 (org-time-string-to-time (match-string 1)))))
18262 (setq diff (- d2 d1))))
18263 (calendar)
18264 (calendar-goto-today)
18265 (when (and diff (not arg)) (calendar-forward-day diff))))
18267 (defun org-get-date-from-calendar ()
18268 "Return a list (month day year) of date at point in calendar."
18269 (with-current-buffer "*Calendar*"
18270 (save-match-data
18271 (calendar-cursor-to-date))))
18273 (defun org-date-from-calendar ()
18274 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18275 If there is already a time stamp at the cursor position, update it."
18276 (interactive)
18277 (if (org-at-timestamp-p t)
18278 (org-timestamp-change 0 'calendar)
18279 (let ((cal-date (org-get-date-from-calendar)))
18280 (org-insert-time-stamp
18281 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18283 (defcustom org-effort-durations
18284 `(("min" . 1)
18285 ("h" . 60)
18286 ("d" . ,(* 60 8))
18287 ("w" . ,(* 60 8 5))
18288 ("m" . ,(* 60 8 5 4))
18289 ("y" . ,(* 60 8 5 40)))
18290 "Conversion factor to minutes for an effort modifier.
18292 Each entry has the form (MODIFIER . MINUTES).
18294 In an effort string, a number followed by MODIFIER is multiplied
18295 by the specified number of MINUTES to obtain an effort in
18296 minutes.
18298 For example, if the value of this variable is ((\"hours\" . 60)), then an
18299 effort string \"2hours\" is equivalent to 120 minutes."
18300 :group 'org-agenda
18301 :version "26.1"
18302 :package-version '(Org . "8.3")
18303 :type '(alist :key-type (string :tag "Modifier")
18304 :value-type (number :tag "Minutes")))
18306 (defun org-minutes-to-clocksum-string (m)
18307 "Format number of minutes as a clocksum string.
18308 The format is determined by `org-time-clocksum-format',
18309 `org-time-clocksum-use-fractional' and
18310 `org-time-clocksum-fractional-format' and
18311 `org-time-clocksum-use-effort-durations'."
18312 (let ((clocksum "")
18313 (m (round m)) ; Don't allow fractions of minutes
18314 h d w mo y fmt n)
18315 (setq h (if org-time-clocksum-use-effort-durations
18316 (cdr (assoc "h" org-effort-durations)) 60)
18317 d (if org-time-clocksum-use-effort-durations
18318 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18319 w (if org-time-clocksum-use-effort-durations
18320 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18321 mo (if org-time-clocksum-use-effort-durations
18322 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18323 y (if org-time-clocksum-use-effort-durations
18324 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18325 ;; fractional format
18326 (if org-time-clocksum-use-fractional
18327 (cond
18328 ;; single format string
18329 ((stringp org-time-clocksum-fractional-format)
18330 (format org-time-clocksum-fractional-format (/ m (float h))))
18331 ;; choice of fractional formats for different time units
18332 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18333 (> (/ (truncate m) (* y d h)) 0))
18334 (format fmt (/ m (* y d (float h)))))
18335 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18336 (> (/ (truncate m) (* mo d h)) 0))
18337 (format fmt (/ m (* mo d (float h)))))
18338 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18339 (> (/ (truncate m) (* w d h)) 0))
18340 (format fmt (/ m (* w d (float h)))))
18341 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18342 (> (/ (truncate m) (* d h)) 0))
18343 (format fmt (/ m (* d (float h)))))
18344 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18345 (> (/ (truncate m) h) 0))
18346 (format fmt (/ m (float h))))
18347 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18348 (format fmt m))
18349 ;; fall back to smallest time unit with a format
18350 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18351 (format fmt (/ m (float h))))
18352 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18353 (format fmt (/ m (* d (float h)))))
18354 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18355 (format fmt (/ m (* w d (float h)))))
18356 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18357 (format fmt (/ m (* mo d (float h)))))
18358 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18359 (format fmt (/ m (* y d (float h))))))
18360 ;; standard (non-fractional) format, with single format string
18361 (if (stringp org-time-clocksum-format)
18362 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18363 ;; separate formats components
18364 (and (setq fmt (plist-get org-time-clocksum-format :years))
18365 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18366 (plist-get org-time-clocksum-format :require-years))
18367 (setq clocksum (concat clocksum (format fmt n))
18368 m (- m (* n y d h))))
18369 (and (setq fmt (plist-get org-time-clocksum-format :months))
18370 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18371 (plist-get org-time-clocksum-format :require-months))
18372 (setq clocksum (concat clocksum (format fmt n))
18373 m (- m (* n mo d h))))
18374 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18375 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18376 (plist-get org-time-clocksum-format :require-weeks))
18377 (setq clocksum (concat clocksum (format fmt n))
18378 m (- m (* n w d h))))
18379 (and (setq fmt (plist-get org-time-clocksum-format :days))
18380 (or (> (setq n (/ (truncate m) (* d h))) 0)
18381 (plist-get org-time-clocksum-format :require-days))
18382 (setq clocksum (concat clocksum (format fmt n))
18383 m (- m (* n d h))))
18384 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18385 (or (> (setq n (/ (truncate m) h)) 0)
18386 (plist-get org-time-clocksum-format :require-hours))
18387 (setq clocksum (concat clocksum (format fmt n))
18388 m (- m (* n h))))
18389 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18390 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18391 (setq clocksum (concat clocksum (format fmt m))))
18392 ;; return formatted time duration
18393 clocksum))))
18395 (defun org-hours-to-clocksum-string (n)
18396 (org-minutes-to-clocksum-string (* n 60)))
18398 (defun org-hh:mm-string-to-minutes (s)
18399 "Convert a string H:MM to a number of minutes.
18400 If the string is just a number, interpret it as minutes.
18401 In fact, the first hh:mm or number in the string will be taken,
18402 there can be extra stuff in the string.
18403 If no number is found, the return value is 0."
18404 (cond
18405 ((integerp s) s)
18406 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18407 (+ (* (string-to-number (match-string 1 s)) 60)
18408 (string-to-number (match-string 2 s))))
18409 ((string-match "\\([0-9]+\\)" s)
18410 (string-to-number (match-string 1 s)))
18411 (t 0)))
18413 (defcustom org-image-actual-width t
18414 "Should we use the actual width of images when inlining them?
18416 When set to t, always use the image width.
18418 When set to a number, use imagemagick (when available) to set
18419 the image's width to this value.
18421 When set to a number in a list, try to get the width from any
18422 #+ATTR.* keyword if it matches a width specification like
18424 #+ATTR_HTML: :width 300px
18426 and fall back on that number if none is found.
18428 When set to nil, try to get the width from an #+ATTR.* keyword
18429 and fall back on the original width if none is found.
18431 This requires Emacs >= 24.1, build with imagemagick support."
18432 :group 'org-appearance
18433 :version "24.4"
18434 :package-version '(Org . "8.0")
18435 :type '(choice
18436 (const :tag "Use the image width" t)
18437 (integer :tag "Use a number of pixels")
18438 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18439 (const :tag "Use #+ATTR* or don't resize" nil)))
18441 (defcustom org-agenda-inhibit-startup nil
18442 "Inhibit startup when preparing agenda buffers.
18443 When this variable is t, the initialization of the Org agenda
18444 buffers is inhibited: e.g. the visibility state is not set, the
18445 tables are not re-aligned, etc."
18446 :type 'boolean
18447 :version "24.3"
18448 :group 'org-agenda)
18450 (defcustom org-agenda-ignore-properties nil
18451 "Avoid updating text properties when building the agenda.
18452 Properties are used to prepare buffers for effort estimates,
18453 appointments, statistics and subtree-local categories.
18454 If you don't use these in the agenda, you can add them to this
18455 list and agenda building will be a bit faster.
18456 The value is a list, with zero or more of the symbols `effort', `appt',
18457 `stats' or `category'."
18458 :type '(set :greedy t
18459 (const effort)
18460 (const appt)
18461 (const stats)
18462 (const category))
18463 :version "26.1"
18464 :package-version '(Org . "8.3")
18465 :group 'org-agenda)
18467 (defun org-duration-string-to-minutes (s &optional output-to-string)
18468 "Convert a duration string S to minutes.
18470 A bare number is interpreted as minutes, modifiers can be set by
18471 customizing `org-effort-durations' (which see).
18473 Entries containing a colon are interpreted as H:MM by
18474 `org-hh:mm-string-to-minutes'."
18475 (let ((result 0)
18476 (re (concat "\\([0-9.]+\\) *\\("
18477 (regexp-opt (mapcar 'car org-effort-durations))
18478 "\\)")))
18479 (while (string-match re s)
18480 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18481 (string-to-number (match-string 1 s))))
18482 (setq s (replace-match "" nil t s)))
18483 (setq result (floor result))
18484 (cl-incf result (org-hh:mm-string-to-minutes s))
18485 (if output-to-string (number-to-string result) result)))
18487 ;;;; Files
18489 (defun org-save-all-org-buffers ()
18490 "Save all Org buffers without user confirmation."
18491 (interactive)
18492 (message "Saving all Org buffers...")
18493 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18494 (when (featurep 'org-id) (org-id-locations-save))
18495 (message "Saving all Org buffers... done"))
18497 (defun org-revert-all-org-buffers ()
18498 "Revert all Org buffers.
18499 Prompt for confirmation when there are unsaved changes.
18500 Be sure you know what you are doing before letting this function
18501 overwrite your changes.
18503 This function is useful in a setup where one tracks org files
18504 with a version control system, to revert on one machine after pulling
18505 changes from another. I believe the procedure must be like this:
18507 1. M-x org-save-all-org-buffers
18508 2. Pull changes from the other machine, resolve conflicts
18509 3. M-x org-revert-all-org-buffers"
18510 (interactive)
18511 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18512 (user-error "Abort"))
18513 (save-excursion
18514 (save-window-excursion
18515 (dolist (b (buffer-list))
18516 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18517 (with-current-buffer b buffer-file-name))
18518 (pop-to-buffer-same-window b)
18519 (revert-buffer t 'no-confirm)))
18520 (when (and (featurep 'org-id) org-id-track-globally)
18521 (org-id-locations-load)))))
18523 ;;;; Agenda files
18525 ;;;###autoload
18526 (defun org-switchb (&optional arg)
18527 "Switch between Org buffers.
18529 With `\\[universal-argument]' prefix, restrict available buffers to files.
18531 With `\\[universal-argument] \\[universal-argument]' \
18532 prefix, restrict available buffers to agenda files."
18533 (interactive "P")
18534 (let ((blist (org-buffer-list
18535 (cond ((equal arg '(4)) 'files)
18536 ((equal arg '(16)) 'agenda)))))
18537 (pop-to-buffer-same-window
18538 (completing-read "Org buffer: "
18539 (mapcar #'list (mapcar #'buffer-name blist))
18540 nil t))))
18542 (defun org-buffer-list (&optional predicate exclude-tmp)
18543 "Return a list of Org buffers.
18544 PREDICATE can be `export', `files' or `agenda'.
18546 export restrict the list to Export buffers.
18547 files restrict the list to buffers visiting Org files.
18548 agenda restrict the list to buffers visiting agenda files.
18550 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18551 (let* ((bfn nil)
18552 (agenda-files (and (eq predicate 'agenda)
18553 (mapcar 'file-truename (org-agenda-files t))))
18554 (filter
18555 (cond
18556 ((eq predicate 'files)
18557 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18558 ((eq predicate 'export)
18559 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18560 ((eq predicate 'agenda)
18561 (lambda (b)
18562 (with-current-buffer b
18563 (and (derived-mode-p 'org-mode)
18564 (setq bfn (buffer-file-name b))
18565 (member (file-truename bfn) agenda-files)))))
18566 (t (lambda (b) (with-current-buffer b
18567 (or (derived-mode-p 'org-mode)
18568 (string-match "\\*Org .*Export"
18569 (buffer-name b)))))))))
18570 (delq nil
18571 (mapcar
18572 (lambda(b)
18573 (if (and (funcall filter b)
18574 (or (not exclude-tmp)
18575 (not (string-match "tmp" (buffer-name b)))))
18577 nil))
18578 (buffer-list)))))
18580 (defun org-agenda-files (&optional unrestricted archives)
18581 "Get the list of agenda files.
18582 Optional UNRESTRICTED means return the full list even if a restriction
18583 is currently in place.
18584 When ARCHIVES is t, include all archive files that are really being
18585 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18586 `org-agenda-archives-mode' is t."
18587 (let ((files
18588 (cond
18589 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18590 ((stringp org-agenda-files) (org-read-agenda-file-list))
18591 ((listp org-agenda-files) org-agenda-files)
18592 (t (error "Invalid value of `org-agenda-files'")))))
18593 (setq files (apply 'append
18594 (mapcar (lambda (f)
18595 (if (file-directory-p f)
18596 (directory-files
18597 f t org-agenda-file-regexp)
18598 (list f)))
18599 files)))
18600 (when org-agenda-skip-unavailable-files
18601 (setq files (delq nil
18602 (mapcar (function
18603 (lambda (file)
18604 (and (file-readable-p file) file)))
18605 files))))
18606 (when (or (eq archives t)
18607 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18608 (setq files (org-add-archive-files files)))
18609 files))
18611 (defun org-agenda-file-p (&optional file)
18612 "Return non-nil, if FILE is an agenda file.
18613 If FILE is omitted, use the file associated with the current
18614 buffer."
18615 (let ((fname (or file (buffer-file-name))))
18616 (and fname
18617 (member (file-truename fname)
18618 (mapcar #'file-truename (org-agenda-files t))))))
18620 (defun org-edit-agenda-file-list ()
18621 "Edit the list of agenda files.
18622 Depending on setup, this either uses customize to edit the variable
18623 `org-agenda-files', or it visits the file that is holding the list. In the
18624 latter case, the buffer is set up in a way that saving it automatically kills
18625 the buffer and restores the previous window configuration."
18626 (interactive)
18627 (if (stringp org-agenda-files)
18628 (let ((cw (current-window-configuration)))
18629 (find-file org-agenda-files)
18630 (setq-local org-window-configuration cw)
18631 (add-hook 'after-save-hook
18632 (lambda ()
18633 (set-window-configuration
18634 (prog1 org-window-configuration
18635 (kill-buffer (current-buffer))))
18636 (org-install-agenda-files-menu)
18637 (message "New agenda file list installed"))
18638 nil 'local)
18639 (message "%s" (substitute-command-keys
18640 "Edit list and finish with \\[save-buffer]")))
18641 (customize-variable 'org-agenda-files)))
18643 (defun org-store-new-agenda-file-list (list)
18644 "Set new value for the agenda file list and save it correctly."
18645 (if (stringp org-agenda-files)
18646 (let ((fe (org-read-agenda-file-list t)) b u)
18647 (while (setq b (find-buffer-visiting org-agenda-files))
18648 (kill-buffer b))
18649 (with-temp-file org-agenda-files
18650 (insert
18651 (mapconcat
18652 (lambda (f) ;; Keep un-expanded entries.
18653 (if (setq u (assoc f fe))
18654 (cdr u)
18656 list "\n")
18657 "\n")))
18658 (let ((org-mode-hook nil) (org-inhibit-startup t)
18659 (org-insert-mode-line-in-empty-file nil))
18660 (setq org-agenda-files list)
18661 (customize-save-variable 'org-agenda-files org-agenda-files))))
18663 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18664 "Read the list of agenda files from a file.
18665 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18666 filenames, used by `org-store-new-agenda-file-list' to write back
18667 un-expanded file names."
18668 (when (file-directory-p org-agenda-files)
18669 (error "`org-agenda-files' cannot be a single directory"))
18670 (when (stringp org-agenda-files)
18671 (with-temp-buffer
18672 (insert-file-contents org-agenda-files)
18673 (mapcar
18674 (lambda (f)
18675 (let ((e (expand-file-name (substitute-in-file-name f)
18676 org-directory)))
18677 (if pair-with-expansion
18678 (cons e f)
18679 e)))
18680 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18682 ;;;###autoload
18683 (defun org-cycle-agenda-files ()
18684 "Cycle through the files in `org-agenda-files'.
18685 If the current buffer visits an agenda file, find the next one in the list.
18686 If the current buffer does not, find the first agenda file."
18687 (interactive)
18688 (let* ((fs (or (org-agenda-files t)
18689 (user-error "No agenda files")))
18690 (files (copy-sequence fs))
18691 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18692 file)
18693 (when tcf
18694 (while (and (setq file (pop files))
18695 (not (equal (file-truename file) tcf)))))
18696 (find-file (car (or files fs)))
18697 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18699 (defun org-agenda-file-to-front (&optional to-end)
18700 "Move/add the current file to the top of the agenda file list.
18701 If the file is not present in the list, it is added to the front. If it is
18702 present, it is moved there. With optional argument TO-END, add/move to the
18703 end of the list."
18704 (interactive "P")
18705 (let ((org-agenda-skip-unavailable-files nil)
18706 (file-alist (mapcar (lambda (x)
18707 (cons (file-truename x) x))
18708 (org-agenda-files t)))
18709 (ctf (file-truename
18710 (or buffer-file-name
18711 (user-error "Please save the current buffer to a file"))))
18712 x had)
18713 (setq x (assoc ctf file-alist) had x)
18715 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18716 (if to-end
18717 (setq file-alist (append (delq x file-alist) (list x)))
18718 (setq file-alist (cons x (delq x file-alist))))
18719 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18720 (org-install-agenda-files-menu)
18721 (message "File %s to %s of agenda file list"
18722 (if had "moved" "added") (if to-end "end" "front"))))
18724 (defun org-remove-file (&optional file)
18725 "Remove current file from the list of files in variable `org-agenda-files'.
18726 These are the files which are being checked for agenda entries.
18727 Optional argument FILE means use this file instead of the current."
18728 (interactive)
18729 (let* ((org-agenda-skip-unavailable-files nil)
18730 (file (or file buffer-file-name
18731 (user-error "Current buffer does not visit a file")))
18732 (true-file (file-truename file))
18733 (afile (abbreviate-file-name file))
18734 (files (delq nil (mapcar
18735 (lambda (x)
18736 (unless (equal true-file
18737 (file-truename x))
18739 (org-agenda-files t)))))
18740 (if (not (= (length files) (length (org-agenda-files t))))
18741 (progn
18742 (org-store-new-agenda-file-list files)
18743 (org-install-agenda-files-menu)
18744 (message "Removed from Org Agenda list: %s" afile))
18745 (message "File was not in list: %s (not removed)" afile))))
18747 (defun org-file-menu-entry (file)
18748 (vector file (list 'find-file file) t))
18750 (defun org-check-agenda-file (file)
18751 "Make sure FILE exists. If not, ask user what to do."
18752 (unless (file-exists-p file)
18753 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18754 (abbreviate-file-name file))
18755 (let ((r (downcase (read-char-exclusive))))
18756 (cond
18757 ((equal r ?r)
18758 (org-remove-file file)
18759 (throw 'nextfile t))
18760 (t (user-error "Abort"))))))
18762 (defun org-get-agenda-file-buffer (file)
18763 "Get an agenda buffer visiting FILE.
18764 If the buffer needs to be created, add it to the list of buffers
18765 which might be released later."
18766 (let ((buf (org-find-base-buffer-visiting file)))
18767 (if buf
18768 buf ; just return it
18769 ;; Make a new buffer and remember it
18770 (setq buf (find-file-noselect file))
18771 (when buf (push buf org-agenda-new-buffers))
18772 buf)))
18774 (defun org-release-buffers (blist)
18775 "Release all buffers in list, asking the user for confirmation when needed.
18776 When a buffer is unmodified, it is just killed. When modified, it is saved
18777 \(if the user agrees) and then killed."
18778 (let (file)
18779 (dolist (buf blist)
18780 (setq file (buffer-file-name buf))
18781 (when (and (buffer-modified-p buf)
18782 file
18783 (y-or-n-p (format "Save file %s? " file)))
18784 (with-current-buffer buf (save-buffer)))
18785 (kill-buffer buf))))
18787 (defun org-agenda-prepare-buffers (files)
18788 "Create buffers for all agenda files, protect archived trees and comments."
18789 (interactive)
18790 (let ((pa '(:org-archived t))
18791 (pc '(:org-comment t))
18792 (pall '(:org-archived t :org-comment t))
18793 (inhibit-read-only t)
18794 (org-inhibit-startup org-agenda-inhibit-startup)
18795 (rea (concat ":" org-archive-tag ":"))
18796 re pos)
18797 (setq org-tag-alist-for-agenda nil
18798 org-tag-groups-alist-for-agenda nil)
18799 (save-excursion
18800 (save-restriction
18801 (dolist (file files)
18802 (catch 'nextfile
18803 (if (bufferp file)
18804 (set-buffer file)
18805 (org-check-agenda-file file)
18806 (set-buffer (org-get-agenda-file-buffer file)))
18807 (widen)
18808 (org-set-regexps-and-options 'tags-only)
18809 (setq pos (point))
18810 (or (memq 'category org-agenda-ignore-properties)
18811 (org-refresh-category-properties))
18812 (or (memq 'stats org-agenda-ignore-properties)
18813 (org-refresh-stats-properties))
18814 (or (memq 'effort org-agenda-ignore-properties)
18815 (org-refresh-effort-properties))
18816 (or (memq 'appt org-agenda-ignore-properties)
18817 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18818 (setq org-todo-keywords-for-agenda
18819 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18820 (setq org-done-keywords-for-agenda
18821 (append org-done-keywords-for-agenda org-done-keywords))
18822 (setq org-todo-keyword-alist-for-agenda
18823 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18824 (setq org-tag-alist-for-agenda
18825 (org-uniquify
18826 (append org-tag-alist-for-agenda
18827 org-current-tag-alist)))
18828 ;; Merge current file's tag groups into global
18829 ;; `org-tag-groups-alist-for-agenda'.
18830 (when org-group-tags
18831 (dolist (alist org-tag-groups-alist)
18832 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18833 (if old
18834 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18835 (push alist org-tag-groups-alist-for-agenda)))))
18836 (org-with-silent-modifications
18837 (save-excursion
18838 (remove-text-properties (point-min) (point-max) pall)
18839 (when org-agenda-skip-archived-trees
18840 (goto-char (point-min))
18841 (while (re-search-forward rea nil t)
18842 (when (org-at-heading-p t)
18843 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18844 (goto-char (point-min))
18845 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18846 (while (re-search-forward re nil t)
18847 (when (save-match-data (org-in-commented-heading-p t))
18848 (add-text-properties
18849 (match-beginning 0) (org-end-of-subtree t) pc)))))
18850 (goto-char pos)))))
18851 (setq org-todo-keywords-for-agenda
18852 (org-uniquify org-todo-keywords-for-agenda))
18853 (setq org-todo-keyword-alist-for-agenda
18854 (org-uniquify org-todo-keyword-alist-for-agenda))))
18857 ;;;; CDLaTeX minor mode
18859 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18860 "Keymap for the minor `org-cdlatex-mode'.")
18862 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18863 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18864 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18865 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18866 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18868 (defvar org-cdlatex-texmathp-advice-is-done nil
18869 "Flag remembering if we have applied the advice to texmathp already.")
18871 (define-minor-mode org-cdlatex-mode
18872 "Toggle the minor `org-cdlatex-mode'.
18873 This mode supports entering LaTeX environment and math in LaTeX fragments
18874 in Org mode.
18875 \\{org-cdlatex-mode-map}"
18876 nil " OCDL" nil
18877 (when org-cdlatex-mode
18878 (require 'cdlatex)
18879 (run-hooks 'cdlatex-mode-hook)
18880 (cdlatex-compute-tables))
18881 (unless org-cdlatex-texmathp-advice-is-done
18882 (setq org-cdlatex-texmathp-advice-is-done t)
18883 (defadvice texmathp (around org-math-always-on activate)
18884 "Always return t in Org buffers.
18885 This is because we want to insert math symbols without dollars even outside
18886 the LaTeX math segments. If Org mode thinks that point is actually inside
18887 an embedded LaTeX fragment, let `texmathp' do its job.
18888 `\\[org-cdlatex-mode-map]'"
18889 (interactive)
18890 (let (p)
18891 (cond
18892 ((not (derived-mode-p 'org-mode)) ad-do-it)
18893 ((eq this-command 'cdlatex-math-symbol)
18894 (setq ad-return-value t
18895 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18897 (let ((p (org-inside-LaTeX-fragment-p)))
18898 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18899 (setq ad-return-value t
18900 texmathp-why '("Org mode embedded math" . 0))
18901 (when p ad-do-it)))))))))
18903 (defun turn-on-org-cdlatex ()
18904 "Unconditionally turn on `org-cdlatex-mode'."
18905 (org-cdlatex-mode 1))
18907 (defun org-try-cdlatex-tab ()
18908 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18909 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18910 - inside a LaTeX fragment, or
18911 - after the first word in a line, where an abbreviation expansion could
18912 insert a LaTeX environment."
18913 (when org-cdlatex-mode
18914 (cond
18915 ;; Before any word on the line: No expansion possible.
18916 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18917 ;; Just after first word on the line: Expand it. Make sure it
18918 ;; cannot happen on headlines, though.
18919 ((save-excursion
18920 (skip-chars-backward "a-zA-Z0-9*")
18921 (skip-chars-backward " \t")
18922 (and (bolp) (not (org-at-heading-p))))
18923 (cdlatex-tab) t)
18924 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18926 (defun org-cdlatex-underscore-caret (&optional _arg)
18927 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18928 Revert to the normal definition outside of these fragments."
18929 (interactive "P")
18930 (if (org-inside-LaTeX-fragment-p)
18931 (call-interactively 'cdlatex-sub-superscript)
18932 (let (org-cdlatex-mode)
18933 (call-interactively (key-binding (vector last-input-event))))))
18935 (defun org-cdlatex-math-modify (&optional _arg)
18936 "Execute `cdlatex-math-modify' 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-math-modify)
18941 (let (org-cdlatex-mode)
18942 (call-interactively (key-binding (vector last-input-event))))))
18944 (defun org-cdlatex-environment-indent (&optional environment item)
18945 "Execute `cdlatex-environment' and indent the inserted environment.
18947 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18949 The inserted environment is indented to current indentation
18950 unless point is at the beginning of the line, in which the
18951 environment remains unintended."
18952 (interactive)
18953 ;; cdlatex-environment always return nil. Therefore, capture output
18954 ;; first and determine if an environment was selected.
18955 (let* ((beg (point-marker))
18956 (end (copy-marker (point) t))
18957 (inserted (progn
18958 (ignore-errors (cdlatex-environment environment item))
18959 (< beg end)))
18960 ;; Figure out how many lines to move forward after the
18961 ;; environment has been inserted.
18962 (lines (when inserted
18963 (save-excursion
18964 (- (cl-loop while (< beg (point))
18965 with x = 0
18966 do (forward-line -1)
18967 (cl-incf x)
18968 finally return x)
18969 (if (progn (goto-char beg)
18970 (and (progn (skip-chars-forward " \t") (eolp))
18971 (progn (skip-chars-backward " \t") (bolp))))
18972 1 0)))))
18973 (env (org-trim (delete-and-extract-region beg end))))
18974 (when inserted
18975 ;; Get indentation of next line unless at column 0.
18976 (let ((ind (if (bolp) 0
18977 (save-excursion
18978 (org-return-indent)
18979 (prog1 (org-get-indentation)
18980 (when (progn (skip-chars-forward " \t") (eolp))
18981 (delete-region beg (point)))))))
18982 (bol (progn (skip-chars-backward " \t") (bolp))))
18983 ;; Insert a newline before environment unless at column zero
18984 ;; to "escape" the current line. Insert a newline if
18985 ;; something is one the same line as \end{ENVIRONMENT}.
18986 (insert
18987 (concat (unless bol "\n") env
18988 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18989 (unless (zerop ind)
18990 (save-excursion
18991 (goto-char beg)
18992 (while (< (point) end)
18993 (unless (eolp) (indent-line-to ind))
18994 (forward-line))))
18995 (goto-char beg)
18996 (forward-line lines)
18997 (indent-line-to ind)))
18998 (set-marker beg nil)
18999 (set-marker end nil)))
19002 ;;;; LaTeX fragments
19004 (defun org-inside-LaTeX-fragment-p ()
19005 "Test if point is inside a LaTeX fragment.
19006 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19007 sequence appearing also before point.
19008 Even though the matchers for math are configurable, this function assumes
19009 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19010 delimiters are skipped when they have been removed by customization.
19011 The return value is nil, or a cons cell with the delimiter and the
19012 position of this delimiter.
19014 This function does a reasonably good job, but can locally be fooled by
19015 for example currency specifications. For example it will assume being in
19016 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19017 fragments that are properly closed, but during editing, we have to live
19018 with the uncertainty caused by missing closing delimiters. This function
19019 looks only before point, not after."
19020 (catch 'exit
19021 (let ((pos (point))
19022 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19023 (lim (progn
19024 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19025 (point)))
19026 dd-on str (start 0) m re)
19027 (goto-char pos)
19028 (when dodollar
19029 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19030 re (nth 1 (assoc "$" org-latex-regexps)))
19031 (while (string-match re str start)
19032 (cond
19033 ((= (match-end 0) (length str))
19034 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19035 ((= (match-end 0) (- (length str) 5))
19036 (throw 'exit nil))
19037 (t (setq start (match-end 0))))))
19038 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19039 (goto-char pos)
19040 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19041 (and (match-beginning 2) (throw 'exit nil))
19042 ;; count $$
19043 (while (re-search-backward "\\$\\$" lim t)
19044 (setq dd-on (not dd-on)))
19045 (goto-char pos)
19046 (when dd-on (cons "$$" m))))))
19048 (defun org-inside-latex-macro-p ()
19049 "Is point inside a LaTeX macro or its arguments?"
19050 (save-match-data
19051 (org-in-regexp
19052 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19054 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19055 "Build an overlay between BEG and END using IMAGE file.
19056 Argument IMAGETYPE is the extension of the displayed image,
19057 as a string. It defaults to \"png\"."
19058 (let ((ov (make-overlay beg end))
19059 (imagetype (or (intern imagetype) 'png)))
19060 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19061 (overlay-put ov 'evaporate t)
19062 (overlay-put ov
19063 'modification-hooks
19064 (list (lambda (o _flag _beg _end &optional _l)
19065 (delete-overlay o))))
19066 (overlay-put ov
19067 'display
19068 (list 'image :type imagetype :file image :ascent 'center))))
19070 (defun org--list-latex-overlays (&optional beg end)
19071 "List all Org LaTeX overlays in current buffer.
19072 Limit to overlays between BEG and END when those are provided."
19073 (cl-remove-if-not
19074 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19075 (overlays-in (or beg (point-min)) (or end (point-max)))))
19077 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19078 "Remove all overlays with LaTeX fragment images in current buffer.
19079 When optional arguments BEG and END are non-nil, remove all
19080 overlays between them instead. Return a non-nil value when some
19081 overlays were removed, nil otherwise."
19082 (let ((overlays (org--list-latex-overlays beg end)))
19083 (mapc #'delete-overlay overlays)
19084 overlays))
19086 (defun org-toggle-latex-fragment (&optional arg)
19087 "Preview the LaTeX fragment at point, or all locally or globally.
19089 If the cursor is on a LaTeX fragment, create the image and overlay
19090 it over the source code, if there is none. Remove it otherwise.
19091 If there is no fragment at point, display all fragments in the
19092 current section.
19094 With prefix ARG, preview or clear image for all fragments in the
19095 current subtree or in the whole buffer when used before the first
19096 headline. With a prefix ARG `\\[universal-argument] \
19097 \\[universal-argument]' preview or clear images
19098 for all fragments in the buffer."
19099 (interactive "P")
19100 (when (display-graphic-p)
19101 (catch 'exit
19102 (save-excursion
19103 (let (beg end msg)
19104 (cond
19105 ((or (equal arg '(16))
19106 (and (equal arg '(4))
19107 (org-with-limited-levels (org-before-first-heading-p))))
19108 (if (org-remove-latex-fragment-image-overlays)
19109 (progn (message "LaTeX fragments images removed from buffer")
19110 (throw 'exit nil))
19111 (setq msg "Creating images for buffer...")))
19112 ((equal arg '(4))
19113 (org-with-limited-levels (org-back-to-heading t))
19114 (setq beg (point))
19115 (setq end (progn (org-end-of-subtree t) (point)))
19116 (if (org-remove-latex-fragment-image-overlays beg end)
19117 (progn
19118 (message "LaTeX fragment images removed from subtree")
19119 (throw 'exit nil))
19120 (setq msg "Creating images for subtree...")))
19121 ((let ((datum (org-element-context)))
19122 (when (memq (org-element-type datum)
19123 '(latex-environment latex-fragment))
19124 (setq beg (org-element-property :begin datum))
19125 (setq end (org-element-property :end datum))
19126 (if (org-remove-latex-fragment-image-overlays beg end)
19127 (progn (message "LaTeX fragment image removed")
19128 (throw 'exit nil))
19129 (setq msg "Creating image...")))))
19131 (org-with-limited-levels
19132 (setq beg (if (org-at-heading-p) (line-beginning-position)
19133 (outline-previous-heading)
19134 (point)))
19135 (setq end (progn (outline-next-heading) (point)))
19136 (if (org-remove-latex-fragment-image-overlays beg end)
19137 (progn
19138 (message "LaTeX fragment images removed from section")
19139 (throw 'exit nil))
19140 (setq msg "Creating images for section...")))))
19141 (let ((file (buffer-file-name (buffer-base-buffer))))
19142 (org-format-latex
19143 (concat org-preview-latex-image-directory "org-ltximg")
19144 beg end
19145 ;; Emacs cannot overlay images from remote hosts. Create
19146 ;; it in `temporary-file-directory' instead.
19147 (if (or (not file) (file-remote-p file))
19148 temporary-file-directory
19149 default-directory)
19150 'overlays msg 'forbuffer org-preview-latex-default-process))
19151 (message (concat msg "done")))))))
19153 (defun org-format-latex
19154 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19155 "Replace LaTeX fragments with links to an image.
19157 The function takes care of creating the replacement image.
19159 Only consider fragments between BEG and END when those are
19160 provided.
19162 When optional argument OVERLAYS is non-nil, display the image on
19163 top of the fragment instead of replacing it.
19165 PROCESSING-TYPE is the conversion method to use, as a symbol.
19167 Some of the options can be changed using the variable
19168 `org-format-latex-options', which see."
19169 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19170 (unless (eq processing-type 'verbatim)
19171 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19172 (cnt 0)
19173 checkdir-flag)
19174 (goto-char (or beg (point-min)))
19175 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19176 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19177 (overlay-recenter (or end (point-max))))
19178 (while (re-search-forward math-regexp end t)
19179 (unless (and overlays
19180 (eq (get-char-property (point) 'org-overlay-type)
19181 'org-latex-overlay))
19182 (let* ((context (org-element-context))
19183 (type (org-element-type context)))
19184 (when (memq type '(latex-environment latex-fragment))
19185 (let ((block-type (eq type 'latex-environment))
19186 (value (org-element-property :value context))
19187 (beg (org-element-property :begin context))
19188 (end (save-excursion
19189 (goto-char (org-element-property :end context))
19190 (skip-chars-backward " \r\t\n")
19191 (point))))
19192 (cond
19193 ((eq processing-type 'mathjax)
19194 ;; Prepare for MathJax processing.
19195 (if (not (string-match "\\`\\$\\$?" value))
19196 (goto-char end)
19197 (delete-region beg end)
19198 (if (string= (match-string 0 value) "$$")
19199 (insert "\\[" (substring value 2 -2) "\\]")
19200 (insert "\\(" (substring value 1 -1) "\\)"))))
19201 ((assq processing-type org-preview-latex-process-alist)
19202 ;; Process to an image.
19203 (cl-incf cnt)
19204 (goto-char beg)
19205 (let* ((processing-info
19206 (cdr (assq processing-type org-preview-latex-process-alist)))
19207 (face (face-at-point))
19208 ;; Get the colors from the face at point.
19210 (let ((color (plist-get org-format-latex-options
19211 :foreground)))
19212 (if (and forbuffer (eq color 'auto))
19213 (face-attribute face :foreground nil 'default)
19214 color)))
19216 (let ((color (plist-get org-format-latex-options
19217 :background)))
19218 (if (and forbuffer (eq color 'auto))
19219 (face-attribute face :background nil 'default)
19220 color)))
19221 (hash (sha1 (prin1-to-string
19222 (list org-format-latex-header
19223 org-latex-default-packages-alist
19224 org-latex-packages-alist
19225 org-format-latex-options
19226 forbuffer value fg bg))))
19227 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19228 (absprefix (expand-file-name prefix dir))
19229 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19230 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19231 (sep (and block-type "\n\n"))
19232 (link (concat sep "[[file:" linkfile "]]" sep))
19233 (options
19234 (org-combine-plists
19235 org-format-latex-options
19236 `(:foreground ,fg :background ,bg))))
19237 (when msg (message msg cnt))
19238 (unless checkdir-flag ; Ensure the directory exists.
19239 (setq checkdir-flag t)
19240 (let ((todir (file-name-directory absprefix)))
19241 (unless (file-directory-p todir)
19242 (make-directory todir t))))
19243 (unless (file-exists-p movefile)
19244 (org-create-formula-image
19245 value movefile options forbuffer processing-type))
19246 (if overlays
19247 (progn
19248 (dolist (o (overlays-in beg end))
19249 (when (eq (overlay-get o 'org-overlay-type)
19250 'org-latex-overlay)
19251 (delete-overlay o)))
19252 (org--format-latex-make-overlay beg end movefile imagetype)
19253 (goto-char end))
19254 (delete-region beg end)
19255 (insert
19256 (org-add-props link
19257 (list 'org-latex-src
19258 (replace-regexp-in-string "\"" "" value)
19259 'org-latex-src-embed-type
19260 (if block-type 'paragraph 'character)))))))
19261 ((eq processing-type 'mathml)
19262 ;; Process to MathML.
19263 (unless (org-format-latex-mathml-available-p)
19264 (user-error "LaTeX to MathML converter not configured"))
19265 (cl-incf cnt)
19266 (when msg (message msg cnt))
19267 (goto-char beg)
19268 (delete-region beg end)
19269 (insert (org-format-latex-as-mathml
19270 value block-type prefix dir)))
19272 (error "Unknown conversion process %s for LaTeX fragments"
19273 processing-type)))))))))))
19275 (defun org-create-math-formula (latex-frag &optional mathml-file)
19276 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19277 Use `org-latex-to-mathml-convert-command'. If the conversion is
19278 sucessful, return the portion between \"<math...> </math>\"
19279 elements otherwise return nil. When MATHML-FILE is specified,
19280 write the results in to that file. When invoked as an
19281 interactive command, prompt for LATEX-FRAG, with initial value
19282 set to the current active region and echo the results for user
19283 inspection."
19284 (interactive (list (let ((frag (when (org-region-active-p)
19285 (buffer-substring-no-properties
19286 (region-beginning) (region-end)))))
19287 (read-string "LaTeX Fragment: " frag nil frag))))
19288 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19289 (let* ((tmp-in-file
19290 (let ((file (file-relative-name
19291 (make-temp-name (expand-file-name "ltxmathml-in")))))
19292 (write-region latex-frag nil file)
19293 file))
19294 (tmp-out-file (file-relative-name
19295 (make-temp-name (expand-file-name "ltxmathml-out"))))
19296 (cmd (format-spec
19297 org-latex-to-mathml-convert-command
19298 `((?j . ,(and org-latex-to-mathml-jar-file
19299 (shell-quote-argument
19300 (expand-file-name
19301 org-latex-to-mathml-jar-file))))
19302 (?I . ,(shell-quote-argument tmp-in-file))
19303 (?i . ,latex-frag)
19304 (?o . ,(shell-quote-argument tmp-out-file)))))
19305 mathml shell-command-output)
19306 (when (called-interactively-p 'any)
19307 (unless (org-format-latex-mathml-available-p)
19308 (user-error "LaTeX to MathML converter not configured")))
19309 (message "Running %s" cmd)
19310 (setq shell-command-output (shell-command-to-string cmd))
19311 (setq mathml
19312 (when (file-readable-p tmp-out-file)
19313 (with-current-buffer (find-file-noselect tmp-out-file t)
19314 (goto-char (point-min))
19315 (when (re-search-forward
19316 (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
19317 (regexp-quote
19318 "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
19319 nil t)
19320 (prog1 (match-string 0) (kill-buffer))))))
19321 (cond
19322 (mathml
19323 (setq mathml
19324 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19325 (when mathml-file
19326 (write-region mathml nil mathml-file))
19327 (when (called-interactively-p 'any)
19328 (message mathml)))
19329 ((message "LaTeX to MathML conversion failed")
19330 (message shell-command-output)))
19331 (delete-file tmp-in-file)
19332 (when (file-exists-p tmp-out-file)
19333 (delete-file tmp-out-file))
19334 mathml))
19336 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19337 prefix &optional dir)
19338 "Use `org-create-math-formula' but check local cache first."
19339 (let* ((absprefix (expand-file-name prefix dir))
19340 (print-length nil) (print-level nil)
19341 (formula-id (concat
19342 "formula-"
19343 (sha1
19344 (prin1-to-string
19345 (list latex-frag
19346 org-latex-to-mathml-convert-command)))))
19347 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19348 (formula-cache-dir (file-name-directory formula-cache)))
19350 (unless (file-directory-p formula-cache-dir)
19351 (make-directory formula-cache-dir t))
19353 (unless (file-exists-p formula-cache)
19354 (org-create-math-formula latex-frag formula-cache))
19356 (if (file-exists-p formula-cache)
19357 ;; Successful conversion. Return the link to MathML file.
19358 (org-add-props
19359 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19360 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19361 'org-latex-src-embed-type (if latex-frag-type
19362 'paragraph 'character)))
19363 ;; Failed conversion. Return the LaTeX fragment verbatim
19364 latex-frag)))
19366 (defun org--get-display-dpi ()
19367 "Get the DPI of the display.
19368 The function assumes that the display has the same pixel width in
19369 the horizontal and vertical directions."
19370 (if (display-graphic-p)
19371 (round (/ (display-pixel-height)
19372 (/ (display-mm-height) 25.4)))
19373 (error "Attempt to calculate the dpi of a non-graphic display")))
19375 (defun org-create-formula-image
19376 (string tofile options buffer &optional processing-type)
19377 "Create an image from LaTeX source using external processes.
19379 The LaTeX STRING is saved to a temporary LaTeX file, then
19380 converted to an image file by process PROCESSING-TYPE defined in
19381 `org-preview-latex-process-alist'. A nil value defaults to
19382 `org-preview-latex-default-process'.
19384 The generated image file is eventually moved to TOFILE.
19386 The OPTIONS argument controls the size, foreground color and
19387 background color of the generated image.
19389 When BUFFER non-nil, this function is used for LaTeX previewing.
19390 Otherwise, it is used to deal with LaTeX snippets showed in
19391 a HTML file."
19392 (let* ((processing-type (or processing-type
19393 org-preview-latex-default-process))
19394 (processing-info
19395 (cdr (assq processing-type org-preview-latex-process-alist)))
19396 (programs (plist-get processing-info :programs))
19397 (error-message (or (plist-get processing-info :message) ""))
19398 (use-xcolor (plist-get processing-info :use-xcolor))
19399 (image-input-type (plist-get processing-info :image-input-type))
19400 (image-output-type (plist-get processing-info :image-output-type))
19401 (post-clean (or (plist-get processing-info :post-clean)
19402 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19403 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19404 (latex-header
19405 (or (plist-get processing-info :latex-header)
19406 (org-latex-make-preamble
19407 (org-export-get-environment (org-export-get-backend 'latex))
19408 org-format-latex-header
19409 'snippet)))
19410 (latex-compiler (plist-get processing-info :latex-compiler))
19411 (image-converter (plist-get processing-info :image-converter))
19412 (tmpdir temporary-file-directory)
19413 (texfilebase (make-temp-name
19414 (expand-file-name "orgtex" tmpdir)))
19415 (texfile (concat texfilebase ".tex"))
19416 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19417 '(1.0 . 1.0)))
19418 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19419 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19420 (dpi (* scale (if buffer (org--get-display-dpi) 140.0)))
19421 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19422 "Black"))
19423 (bg (or (plist-get options (if buffer :background :html-background))
19424 "Transparent"))
19425 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19426 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19427 (dolist (program programs)
19428 (org-check-external-command program error-message))
19429 (if use-xcolor
19430 (progn (if (eq fg 'default)
19431 (setq fg (org-latex-color :foreground))
19432 (setq fg (org-latex-color-format fg)))
19433 (if (eq bg 'default)
19434 (setq bg (org-latex-color :background))
19435 (setq bg (org-latex-color-format
19436 (if (string= bg "Transparent") "white" bg))))
19437 (with-temp-file texfile
19438 (insert latex-header)
19439 (insert "\n\\begin{document}\n"
19440 "\\definecolor{fg}{rgb}{" fg "}\n"
19441 "\\definecolor{bg}{rgb}{" bg "}\n"
19442 "\n\\pagecolor{bg}\n"
19443 "\n{\\color{fg}\n"
19444 string
19445 "\n}\n"
19446 "\n\\end{document}\n")))
19447 (if (eq fg 'default)
19448 (setq fg (org-dvipng-color :foreground))
19449 (unless (string= fg "Transparent")
19450 (setq fg (org-dvipng-color-format fg))))
19451 (if (eq bg 'default)
19452 (setq bg (org-dvipng-color :background))
19453 (unless (string= bg "Transparent")
19454 (setq bg (org-dvipng-color-format bg))))
19455 (with-temp-file texfile
19456 (insert latex-header)
19457 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19459 (let* ((err-msg (format "Please adjust '%s' part of \
19460 `org-preview-latex-process-alist'."
19461 processing-type))
19462 (image-input-file
19463 (org-compile-file
19464 texfile latex-compiler image-input-type err-msg log-buf))
19465 (image-output-file
19466 (org-compile-file
19467 image-input-file image-converter image-output-type err-msg log-buf
19468 `((?F . ,(shell-quote-argument fg))
19469 (?B . ,(shell-quote-argument bg))
19470 (?D . ,(shell-quote-argument (format "%s" dpi)))
19471 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19472 (copy-file image-output-file tofile 'replace)
19473 (dolist (e post-clean)
19474 (when (file-exists-p (concat texfilebase e))
19475 (delete-file (concat texfilebase e))))
19476 image-output-file)))
19478 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19479 "Fill a LaTeX header template TPL.
19480 In the template, the following place holders will be recognized:
19482 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19483 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19484 [PACKAGES] \\usepackage statements for PKG
19485 [NO-PACKAGES] do not include PKG
19486 [EXTRA] the string EXTRA
19487 [NO-EXTRA] do not include EXTRA
19489 For backward compatibility, if both the positive and the negative place
19490 holder is missing, the positive one (without the \"NO-\") will be
19491 assumed to be present at the end of the template.
19492 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19493 EXTRA is a string.
19494 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19495 (let (rpl (end ""))
19496 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19497 (setq rpl (if (or (match-end 1) (not def-pkg))
19498 "" (org-latex-packages-to-string def-pkg snippets-p t))
19499 tpl (replace-match rpl t t tpl))
19500 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19502 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19503 (setq rpl (if (or (match-end 1) (not pkg))
19504 "" (org-latex-packages-to-string pkg snippets-p t))
19505 tpl (replace-match rpl t t tpl))
19506 (when pkg (setq end
19507 (concat end "\n"
19508 (org-latex-packages-to-string pkg snippets-p)))))
19510 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19511 (setq rpl (if (or (match-end 1) (not extra))
19512 "" (concat extra "\n"))
19513 tpl (replace-match rpl t t tpl))
19514 (when (and extra (string-match "\\S-" extra))
19515 (setq end (concat end "\n" extra))))
19517 (if (string-match "\\S-" end)
19518 (concat tpl "\n" end)
19519 tpl)))
19521 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19522 "Turn an alist of packages into a string with the \\usepackage macros."
19523 (setq pkg (mapconcat (lambda(p)
19524 (cond
19525 ((stringp p) p)
19526 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19527 (format "%% Package %s omitted" (cadr p)))
19528 ((equal "" (car p))
19529 (format "\\usepackage{%s}" (cadr p)))
19531 (format "\\usepackage[%s]{%s}"
19532 (car p) (cadr p)))))
19534 "\n"))
19535 (if newline (concat pkg "\n") pkg))
19537 (defun org-dvipng-color (attr)
19538 "Return a RGB color specification for dvipng."
19539 (org-dvipng-color-format (face-attribute 'default attr nil)))
19541 (defun org-dvipng-color-format (color-name)
19542 "Convert COLOR-NAME to a RGB color value for dvipng."
19543 (apply #'format "rgb %s %s %s"
19544 (mapcar 'org-normalize-color
19545 (color-values color-name))))
19547 (defun org-latex-color (attr)
19548 "Return a RGB color for the LaTeX color package."
19549 (org-latex-color-format (face-attribute 'default attr nil)))
19551 (defun org-latex-color-format (color-name)
19552 "Convert COLOR-NAME to a RGB color value."
19553 (apply #'format "%s,%s,%s"
19554 (mapcar 'org-normalize-color
19555 (color-values color-name))))
19557 (defun org-normalize-color (value)
19558 "Return string to be used as color value for an RGB component."
19559 (format "%g" (/ value 65535.0)))
19563 ;; Image display
19565 (defvar-local org-inline-image-overlays nil)
19567 (defun org-toggle-inline-images (&optional include-linked)
19568 "Toggle the display of inline images.
19569 INCLUDE-LINKED is passed to `org-display-inline-images'."
19570 (interactive "P")
19571 (if org-inline-image-overlays
19572 (progn
19573 (org-remove-inline-images)
19574 (when (called-interactively-p 'interactive)
19575 (message "Inline image display turned off")))
19576 (org-display-inline-images include-linked)
19577 (when (called-interactively-p 'interactive)
19578 (message (if org-inline-image-overlays
19579 (format "%d images displayed inline"
19580 (length org-inline-image-overlays))
19581 "No images to display inline")))))
19583 (defun org-redisplay-inline-images ()
19584 "Refresh the display of inline images."
19585 (interactive)
19586 (if (not org-inline-image-overlays)
19587 (org-toggle-inline-images)
19588 (org-toggle-inline-images)
19589 (org-toggle-inline-images)))
19591 (defun org-display-inline-images (&optional include-linked refresh beg end)
19592 "Display inline images.
19594 An inline image is a link which follows either of these
19595 conventions:
19597 1. Its path is a file with an extension matching return value
19598 from `image-file-name-regexp' and it has no contents.
19600 2. Its description consists in a single link of the previous
19601 type.
19603 When optional argument INCLUDE-LINKED is non-nil, also links with
19604 a text description part will be inlined. This can be nice for
19605 a quick look at those images, but it does not reflect what
19606 exported files will look like.
19608 When optional argument REFRESH is non-nil, refresh existing
19609 images between BEG and END. This will create new image displays
19610 only if necessary. BEG and END default to the buffer
19611 boundaries."
19612 (interactive "P")
19613 (when (display-graphic-p)
19614 (unless refresh
19615 (org-remove-inline-images)
19616 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19617 (org-with-wide-buffer
19618 (goto-char (or beg (point-min)))
19619 (let ((case-fold-search t)
19620 (file-extension-re (image-file-name-regexp)))
19621 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19622 (let ((link (save-match-data (org-element-context))))
19623 ;; Check if we're at an inline image.
19624 (when (and (equal (org-element-property :type link) "file")
19625 (or include-linked
19626 (not (org-element-property :contents-begin link)))
19627 (let ((parent (org-element-property :parent link)))
19628 (or (not (eq (org-element-type parent) 'link))
19629 (not (cdr (org-element-contents parent)))))
19630 (string-match-p file-extension-re
19631 (org-element-property :path link)))
19632 (let ((file (expand-file-name
19633 (org-link-unescape
19634 (org-element-property :path link)))))
19635 (when (file-exists-p file)
19636 (let ((width
19637 ;; Apply `org-image-actual-width' specifications.
19638 (cond
19639 ((not (image-type-available-p 'imagemagick)) nil)
19640 ((eq org-image-actual-width t) nil)
19641 ((listp org-image-actual-width)
19643 ;; First try to find a width among
19644 ;; attributes associated to the paragraph
19645 ;; containing link.
19646 (let ((paragraph
19647 (let ((e link))
19648 (while (and (setq e (org-element-property
19649 :parent e))
19650 (not (eq (org-element-type e)
19651 'paragraph))))
19652 e)))
19653 (when paragraph
19654 (save-excursion
19655 (goto-char (org-element-property :begin paragraph))
19656 (when
19657 (re-search-forward
19658 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19659 (org-element-property
19660 :post-affiliated paragraph)
19662 (string-to-number (match-string 1))))))
19663 ;; Otherwise, fall-back to provided number.
19664 (car org-image-actual-width)))
19665 ((numberp org-image-actual-width)
19666 org-image-actual-width)))
19667 (old (get-char-property-and-overlay
19668 (org-element-property :begin link)
19669 'org-image-overlay)))
19670 (if (and (car-safe old) refresh)
19671 (image-refresh (overlay-get (cdr old) 'display))
19672 (let ((image (create-image file
19673 (and width 'imagemagick)
19675 :width width)))
19676 (when image
19677 (let* ((link
19678 ;; If inline image is the description
19679 ;; of another link, be sure to
19680 ;; consider the latter as the one to
19681 ;; apply the overlay on.
19682 (let ((parent
19683 (org-element-property :parent link)))
19684 (if (eq (org-element-type parent) 'link)
19685 parent
19686 link)))
19687 (ov (make-overlay
19688 (org-element-property :begin link)
19689 (progn
19690 (goto-char
19691 (org-element-property :end link))
19692 (skip-chars-backward " \t")
19693 (point)))))
19694 (overlay-put ov 'display image)
19695 (overlay-put ov 'face 'default)
19696 (overlay-put ov 'org-image-overlay t)
19697 (overlay-put
19698 ov 'modification-hooks
19699 (list 'org-display-inline-remove-overlay))
19700 (push ov org-inline-image-overlays)))))))))))))))
19702 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19703 "Remove inline-display overlay if a corresponding region is modified."
19704 (let ((inhibit-modification-hooks t))
19705 (when (and ov after)
19706 (delete ov org-inline-image-overlays)
19707 (delete-overlay ov))))
19709 (defun org-remove-inline-images ()
19710 "Remove inline display of images."
19711 (interactive)
19712 (mapc #'delete-overlay org-inline-image-overlays)
19713 (setq org-inline-image-overlays nil))
19715 ;;;; Key bindings
19717 ;; Outline functions from `outline-mode-prefix-map'
19718 ;; that can be remapped in Org:
19719 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19720 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19721 (define-key org-mode-map [remap outline-forward-same-level]
19722 'org-forward-heading-same-level)
19723 (define-key org-mode-map [remap outline-backward-same-level]
19724 'org-backward-heading-same-level)
19725 (define-key org-mode-map [remap outline-show-branches]
19726 'org-kill-note-or-show-branches)
19727 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19728 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19729 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19730 (define-key org-mode-map [remap outline-next-visible-heading]
19731 'org-next-visible-heading)
19732 (define-key org-mode-map [remap outline-previous-visible-heading]
19733 'org-previous-visible-heading)
19734 (define-key org-mode-map [remap show-children] 'org-show-children)
19736 ;; Outline functions from `outline-mode-prefix-map' that can not
19737 ;; be remapped in Org:
19739 ;; - the column "key binding" shows whether the Outline function is still
19740 ;; available in Org mode on the same key that it has been bound to in
19741 ;; Outline mode:
19742 ;; - "overridden": key used for a different functionality in Org mode
19743 ;; - else: key still bound to the same Outline function in Org mode
19745 ;; | Outline function | key binding | Org replacement |
19746 ;; |------------------------------------+-------------+--------------------------|
19747 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19748 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19749 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19750 ;; | `show-entry' | overridden | no replacement |
19751 ;; | `show-branches' | `C-c C-k' | still same function |
19752 ;; | `show-subtree' | overridden | visibility cycling |
19753 ;; | `show-all' | overridden | no replacement |
19754 ;; | `hide-subtree' | overridden | visibility cycling |
19755 ;; | `hide-body' | overridden | no replacement |
19756 ;; | `hide-entry' | overridden | visibility cycling |
19757 ;; | `hide-leaves' | overridden | no replacement |
19758 ;; | `hide-sublevels' | overridden | no replacement |
19759 ;; | `hide-other' | overridden | no replacement |
19761 ;; Make `C-c C-x' a prefix key
19762 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19764 ;; TAB key with modifiers
19765 (org-defkey org-mode-map "\C-i" 'org-cycle)
19766 (org-defkey org-mode-map [(tab)] 'org-cycle)
19767 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19768 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19769 ;; The following line is necessary under Suse GNU/Linux
19770 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19771 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19772 (define-key org-mode-map [backtab] 'org-shifttab)
19774 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19775 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19776 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19778 ;; Cursor keys with modifiers
19779 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19780 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19781 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19782 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19784 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19785 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19786 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19787 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19788 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19789 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19791 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19792 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19793 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19794 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19796 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19797 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19798 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19799 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19801 ;; Babel keys
19802 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19803 (dolist (pair org-babel-key-bindings)
19804 (define-key org-babel-map (car pair) (cdr pair)))
19806 ;;; Extra keys for tty access.
19807 ;; We only set them when really needed because otherwise the
19808 ;; menus don't show the simple keys
19810 (when (or org-use-extra-keys (not window-system))
19811 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19812 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19813 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19814 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19815 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19816 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19817 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19818 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19819 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19820 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19821 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19822 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19823 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19824 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19825 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19826 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19827 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19828 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19829 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19830 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19831 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19832 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19833 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19834 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19835 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19836 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19837 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19838 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19840 ;; All the other keys
19842 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19843 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19844 (if (boundp 'narrow-map)
19845 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19846 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19847 (if (boundp 'narrow-map)
19848 (org-defkey narrow-map "b" 'org-narrow-to-block)
19849 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19850 (if (boundp 'narrow-map)
19851 (org-defkey narrow-map "e" 'org-narrow-to-element)
19852 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19853 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19854 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19855 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19856 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19857 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19858 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19859 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19860 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19861 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19862 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19863 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19864 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19865 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19866 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19867 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19868 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19869 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19870 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19871 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19872 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19873 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19874 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19875 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19876 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19877 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19878 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19879 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19880 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19881 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19882 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19883 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19884 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19885 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19886 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19887 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19888 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19889 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19890 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19891 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19892 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19893 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19894 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19895 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19896 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19897 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19898 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19899 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19900 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19901 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19902 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19903 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19904 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19905 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19906 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19907 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19908 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19909 (org-defkey org-mode-map "\C-c^" 'org-sort)
19910 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19911 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19912 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19913 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19914 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19915 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19916 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19917 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19918 (org-defkey org-mode-map "\C-m" 'org-return)
19919 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19920 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19921 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19922 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19923 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19924 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19925 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19926 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19927 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19928 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19929 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19930 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19931 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19932 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19933 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19934 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19935 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19936 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19937 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19938 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19939 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19940 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19941 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19942 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19943 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19945 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19946 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19947 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19949 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19950 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19951 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19952 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19953 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19954 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19955 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19956 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19957 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19958 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19959 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19960 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19961 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19962 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19963 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19964 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19965 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19966 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19967 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19968 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19969 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19970 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19972 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19973 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19974 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19975 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19976 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19978 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19980 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19982 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19983 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19985 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19988 (defconst org-speed-commands-default
19990 ("Outline Navigation")
19991 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19992 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19993 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19994 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19995 ("F" . org-next-block)
19996 ("B" . org-previous-block)
19997 ("u" . (org-speed-move-safe 'outline-up-heading))
19998 ("j" . org-goto)
19999 ("g" . (org-refile t))
20000 ("Outline Visibility")
20001 ("c" . org-cycle)
20002 ("C" . org-shifttab)
20003 (" " . org-display-outline-path)
20004 ("s" . org-narrow-to-subtree)
20005 ("=" . org-columns)
20006 ("Outline Structure Editing")
20007 ("U" . org-metaup)
20008 ("D" . org-metadown)
20009 ("r" . org-metaright)
20010 ("l" . org-metaleft)
20011 ("R" . org-shiftmetaright)
20012 ("L" . org-shiftmetaleft)
20013 ("i" . (progn (forward-char 1) (call-interactively
20014 'org-insert-heading-respect-content)))
20015 ("^" . org-sort)
20016 ("w" . org-refile)
20017 ("a" . org-archive-subtree-default-with-confirmation)
20018 ("@" . org-mark-subtree)
20019 ("#" . org-toggle-comment)
20020 ("Clock Commands")
20021 ("I" . org-clock-in)
20022 ("O" . org-clock-out)
20023 ("Meta Data Editing")
20024 ("t" . org-todo)
20025 ("," . (org-priority))
20026 ("0" . (org-priority ?\ ))
20027 ("1" . (org-priority ?A))
20028 ("2" . (org-priority ?B))
20029 ("3" . (org-priority ?C))
20030 (":" . org-set-tags-command)
20031 ("e" . org-set-effort)
20032 ("E" . org-inc-effort)
20033 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20034 (org-entry-put (point) "APPT_WARNTIME" m)))
20035 ("Agenda Views etc")
20036 ("v" . org-agenda)
20037 ("/" . org-sparse-tree)
20038 ("Misc")
20039 ("o" . org-open-at-point)
20040 ("?" . org-speed-command-help)
20041 ("<" . (org-agenda-set-restriction-lock 'subtree))
20042 (">" . (org-agenda-remove-restriction-lock))
20044 "The default speed commands.")
20046 (defun org-print-speed-command (e)
20047 (if (> (length (car e)) 1)
20048 (progn
20049 (princ "\n")
20050 (princ (car e))
20051 (princ "\n")
20052 (princ (make-string (length (car e)) ?-))
20053 (princ "\n"))
20054 (princ (car e))
20055 (princ " ")
20056 (if (symbolp (cdr e))
20057 (princ (symbol-name (cdr e)))
20058 (prin1 (cdr e)))
20059 (princ "\n")))
20061 (defun org-speed-command-help ()
20062 "Show the available speed commands."
20063 (interactive)
20064 (if (not org-use-speed-commands)
20065 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20066 (with-output-to-temp-buffer "*Help*"
20067 (princ "User-defined Speed commands\n===========================\n")
20068 (mapc #'org-print-speed-command org-speed-commands-user)
20069 (princ "\n")
20070 (princ "Built-in Speed commands\n=======================\n")
20071 (mapc #'org-print-speed-command org-speed-commands-default))
20072 (with-current-buffer "*Help*"
20073 (setq truncate-lines t))))
20075 (defun org-speed-move-safe (cmd)
20076 "Execute CMD, but make sure that the cursor always ends up in a headline.
20077 If not, return to the original position and throw an error."
20078 (interactive)
20079 (let ((pos (point)))
20080 (call-interactively cmd)
20081 (unless (and (bolp) (org-at-heading-p))
20082 (goto-char pos)
20083 (error "Boundary reached while executing %s" cmd))))
20085 (defvar org-self-insert-command-undo-counter 0)
20087 (defvar org-table-auto-blank-field) ; defined in org-table.el
20088 (defvar org-speed-command nil)
20090 (defun org-speed-command-activate (keys)
20091 "Hook for activating single-letter speed commands.
20092 `org-speed-commands-default' specifies a minimal command set.
20093 Use `org-speed-commands-user' for further customization."
20094 (when (or (and (bolp) (looking-at org-outline-regexp))
20095 (and (functionp org-use-speed-commands)
20096 (funcall org-use-speed-commands)))
20097 (cdr (assoc keys (append org-speed-commands-user
20098 org-speed-commands-default)))))
20100 (defun org-babel-speed-command-activate (keys)
20101 "Hook for activating single-letter code block commands."
20102 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20103 (cdr (assoc keys org-babel-key-bindings))))
20105 (defcustom org-speed-command-hook
20106 '(org-speed-command-default-hook org-babel-speed-command-hook)
20107 "Hook for activating speed commands at strategic locations.
20108 Hook functions are called in sequence until a valid handler is
20109 found.
20111 Each hook takes a single argument, a user-pressed command key
20112 which is also a `self-insert-command' from the global map.
20114 Within the hook, examine the cursor position and the command key
20115 and return nil or a valid handler as appropriate. Handler could
20116 be one of an interactive command, a function, or a form.
20118 Set `org-use-speed-commands' to non-nil value to enable this
20119 hook. The default setting is `org-speed-command-activate'."
20120 :group 'org-structure
20121 :version "24.1"
20122 :type 'hook)
20124 (defun org-self-insert-command (N)
20125 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20126 If the cursor is in a table looking at whitespace, the whitespace is
20127 overwritten, and the table is not marked as requiring realignment."
20128 (interactive "p")
20129 (org-check-before-invisible-edit 'insert)
20130 (cond
20131 ((and org-use-speed-commands
20132 (let ((kv (this-command-keys-vector)))
20133 (setq org-speed-command
20134 (run-hook-with-args-until-success
20135 'org-speed-command-hook
20136 (make-string 1 (aref kv (1- (length kv))))))))
20137 (cond
20138 ((commandp org-speed-command)
20139 (setq this-command org-speed-command)
20140 (call-interactively org-speed-command))
20141 ((functionp org-speed-command)
20142 (funcall org-speed-command))
20143 ((and org-speed-command (listp org-speed-command))
20144 (eval org-speed-command))
20145 (t (let (org-use-speed-commands)
20146 (call-interactively 'org-self-insert-command)))))
20147 ((and
20148 (org-at-table-p)
20149 (progn
20150 ;; Check if we blank the field, and if that triggers align.
20151 (and (featurep 'org-table) org-table-auto-blank-field
20152 (memq last-command
20153 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20154 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20155 ;; Got extra space, this field does not determine
20156 ;; column width.
20157 (let (org-table-may-need-update) (org-table-blank-field))
20158 ;; No extra space, this field may determine column
20159 ;; width.
20160 (org-table-blank-field)))
20162 (eq N 1)
20163 (looking-at "[^|\n]* \\( \\)|"))
20164 ;; There is room for insertion without re-aligning the table.
20165 (delete-region (match-beginning 1) (match-end 1))
20166 (self-insert-command N))
20168 (setq org-table-may-need-update t)
20169 (self-insert-command N)
20170 (org-fix-tags-on-the-fly)
20171 (when org-self-insert-cluster-for-undo
20172 (if (not (eq last-command 'org-self-insert-command))
20173 (setq org-self-insert-command-undo-counter 1)
20174 (if (>= org-self-insert-command-undo-counter 20)
20175 (setq org-self-insert-command-undo-counter 1)
20176 (and (> org-self-insert-command-undo-counter 0)
20177 buffer-undo-list (listp buffer-undo-list)
20178 (not (cadr buffer-undo-list)) ; remove nil entry
20179 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20180 (setq org-self-insert-command-undo-counter
20181 (1+ org-self-insert-command-undo-counter))))))))
20183 (defun org-check-before-invisible-edit (kind)
20184 "Check is editing if kind KIND would be dangerous with invisible text around.
20185 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20186 ;; First, try to get out of here as quickly as possible, to reduce overhead
20187 (when (and org-catch-invisible-edits
20188 (or (not (boundp 'visible-mode)) (not visible-mode))
20189 (or (get-char-property (point) 'invisible)
20190 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20191 ;; OK, we need to take a closer look
20192 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20193 (invisible-before-point (unless (bobp) (get-char-property
20194 (1- (point)) 'invisible)))
20195 (border-and-ok-direction
20197 ;; Check if we are acting predictably before invisible text
20198 (and invisible-at-point (not invisible-before-point)
20199 (memq kind '(insert delete-backward)))
20200 ;; Check if we are acting predictably after invisible text
20201 ;; This works not well, and I have turned it off. It seems
20202 ;; better to always show and stop after invisible text.
20203 ;; (and (not invisible-at-point) invisible-before-point
20204 ;; (memq kind '(insert delete)))
20206 (when (or (memq invisible-at-point '(outline org-hide-block t))
20207 (memq invisible-before-point '(outline org-hide-block t)))
20208 (when (eq org-catch-invisible-edits 'error)
20209 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20210 (if (and org-custom-properties-overlays
20211 (y-or-n-p "Display invisible properties in this buffer? "))
20212 (org-toggle-custom-properties-visibility)
20213 ;; Make the area visible
20214 (save-excursion
20215 (when invisible-before-point
20216 (goto-char (previous-single-char-property-change
20217 (point) 'invisible)))
20218 (outline-show-subtree))
20219 (cond
20220 ((eq org-catch-invisible-edits 'show)
20221 ;; That's it, we do the edit after showing
20222 (message
20223 "Unfolding invisible region around point before editing")
20224 (sit-for 1))
20225 ((and (eq org-catch-invisible-edits 'smart)
20226 border-and-ok-direction)
20227 (message "Unfolding invisible region around point before editing"))
20229 ;; Don't do the edit, make the user repeat it in full visibility
20230 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20232 (defun org-fix-tags-on-the-fly ()
20233 "Align tags in headline at point.
20234 Unlike to `org-set-tags', it ignores region and sorting."
20235 (when (and (eq (char-after (line-beginning-position)) ?*) ;short-circuit
20236 (org-at-heading-p))
20237 (let ((org-ignore-region t)
20238 (org-tags-sort-function nil))
20239 (org-set-tags nil t))))
20241 (defun org-delete-backward-char (N)
20242 "Like `delete-backward-char', insert whitespace at field end in tables.
20243 When deleting backwards, in tables this function will insert whitespace in
20244 front of the next \"|\" separator, to keep the table aligned. The table will
20245 still be marked for re-alignment if the field did fill the entire column,
20246 because, in this case the deletion might narrow the column."
20247 (interactive "p")
20248 (save-match-data
20249 (org-check-before-invisible-edit 'delete-backward)
20250 (if (and (org-at-table-p)
20251 (eq N 1)
20252 (string-match "|" (buffer-substring (point-at-bol) (point)))
20253 (looking-at ".*?|"))
20254 (let ((pos (point))
20255 (noalign (looking-at "[^|\n\r]* |"))
20256 (c org-table-may-need-update))
20257 (backward-delete-char N)
20258 (unless overwrite-mode
20259 (skip-chars-forward "^|")
20260 (insert " ")
20261 (goto-char (1- pos)))
20262 ;; noalign: if there were two spaces at the end, this field
20263 ;; does not determine the width of the column.
20264 (when noalign (setq org-table-may-need-update c)))
20265 (backward-delete-char N)
20266 (org-fix-tags-on-the-fly))))
20268 (defun org-delete-char (N)
20269 "Like `delete-char', but insert whitespace at field end in tables.
20270 When deleting characters, in tables this function will insert whitespace in
20271 front of the next \"|\" separator, to keep the table aligned. The table will
20272 still be marked for re-alignment if the field did fill the entire column,
20273 because, in this case the deletion might narrow the column."
20274 (interactive "p")
20275 (save-match-data
20276 (org-check-before-invisible-edit 'delete)
20277 (if (and (org-at-table-p)
20278 (not (bolp))
20279 (not (= (char-after) ?|))
20280 (eq N 1))
20281 (if (looking-at ".*?|")
20282 (let ((pos (point))
20283 (noalign (looking-at "[^|\n\r]* |"))
20284 (c org-table-may-need-update))
20285 (replace-match
20286 (concat (substring (match-string 0) 1 -1) " |") nil t)
20287 (goto-char pos)
20288 ;; noalign: if there were two spaces at the end, this field
20289 ;; does not determine the width of the column.
20290 (when noalign (setq org-table-may-need-update c)))
20291 (delete-char N))
20292 (delete-char N)
20293 (org-fix-tags-on-the-fly))))
20295 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
20296 (put 'org-self-insert-command 'delete-selection
20297 (lambda ()
20298 (not (run-hook-with-args-until-success
20299 'self-insert-uses-region-functions))))
20300 (put 'orgtbl-self-insert-command 'delete-selection
20301 (lambda ()
20302 (not (run-hook-with-args-until-success
20303 'self-insert-uses-region-functions))))
20304 (put 'org-delete-char 'delete-selection 'supersede)
20305 (put 'org-delete-backward-char 'delete-selection 'supersede)
20306 (put 'org-yank 'delete-selection 'yank)
20308 ;; Make `flyspell-mode' delay after some commands
20309 (put 'org-self-insert-command 'flyspell-delayed t)
20310 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20311 (put 'org-delete-char 'flyspell-delayed t)
20312 (put 'org-delete-backward-char 'flyspell-delayed t)
20314 ;; Make pabbrev-mode expand after Org mode commands
20315 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20316 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20318 (defun org-remap (map &rest commands)
20319 "In MAP, remap the functions given in COMMANDS.
20320 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20321 (let (new old)
20322 (while commands
20323 (setq old (pop commands) new (pop commands))
20324 (org-defkey map (vector 'remap old) new))))
20326 (defun org-transpose-words ()
20327 "Transpose words for Org.
20328 This uses the `org-mode-transpose-word-syntax-table' syntax
20329 table, which interprets characters in `org-emphasis-alist' as
20330 word constituents."
20331 (interactive)
20332 (with-syntax-table org-mode-transpose-word-syntax-table
20333 (call-interactively 'transpose-words)))
20334 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20336 (when (eq org-enable-table-editor 'optimized)
20337 ;; If the user wants maximum table support, we need to hijack
20338 ;; some standard editing functions
20339 (org-remap org-mode-map
20340 'self-insert-command 'org-self-insert-command
20341 'delete-char 'org-delete-char
20342 'delete-backward-char 'org-delete-backward-char)
20343 (org-defkey org-mode-map "|" 'org-force-self-insert))
20345 (defvar org-ctrl-c-ctrl-c-hook nil
20346 "Hook for functions attaching themselves to `C-c C-c'.
20348 This can be used to add additional functionality to the C-c C-c
20349 key which executes context-dependent commands. This hook is run
20350 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20351 run after the last test.
20353 Each function will be called with no arguments. The function
20354 must check if the context is appropriate for it to act. If yes,
20355 it should do its thing and then return a non-nil value. If the
20356 context is wrong, just do nothing and return nil.")
20358 (defvar org-ctrl-c-ctrl-c-final-hook nil
20359 "Hook for functions attaching themselves to `C-c C-c'.
20361 This can be used to add additional functionality to the C-c C-c
20362 key which executes context-dependent commands. This hook is run
20363 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20364 before the first test.
20366 Each function will be called with no arguments. The function
20367 must check if the context is appropriate for it to act. If yes,
20368 it should do its thing and then return a non-nil value. If the
20369 context is wrong, just do nothing and return nil.")
20371 (defvar org-tab-first-hook nil
20372 "Hook for functions to attach themselves to TAB.
20373 See `org-ctrl-c-ctrl-c-hook' for more information.
20374 This hook runs as the first action when TAB is pressed, even before
20375 `org-cycle' messes around with the `outline-regexp' to cater for
20376 inline tasks and plain list item folding.
20377 If any function in this hook returns t, any other actions that
20378 would have been caused by TAB (such as table field motion or visibility
20379 cycling) will not occur.")
20381 (defvar org-tab-after-check-for-table-hook nil
20382 "Hook for functions to attach themselves to TAB.
20383 See `org-ctrl-c-ctrl-c-hook' for more information.
20384 This hook runs after it has been established that the cursor is not in a
20385 table, but before checking if the cursor is in a headline or if global cycling
20386 should be done.
20387 If any function in this hook returns t, not other actions like visibility
20388 cycling will be done.")
20390 (defvar org-tab-after-check-for-cycling-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 not table field motion and
20394 not visibility should be done because of current context. This is probably
20395 the place where a package like yasnippets can hook in.")
20397 (defvar org-tab-before-tab-emulation-hook nil
20398 "Hook for functions to attach themselves to TAB.
20399 See `org-ctrl-c-ctrl-c-hook' for more information.
20400 This hook runs after every other options for TAB have been exhausted, but
20401 before indentation and \t insertion takes place.")
20403 (defvar org-metaleft-hook nil
20404 "Hook for functions attaching themselves to `M-left'.
20405 See `org-ctrl-c-ctrl-c-hook' for more information.")
20406 (defvar org-metaright-hook nil
20407 "Hook for functions attaching themselves to `M-right'.
20408 See `org-ctrl-c-ctrl-c-hook' for more information.")
20409 (defvar org-metaup-hook nil
20410 "Hook for functions attaching themselves to `M-up'.
20411 See `org-ctrl-c-ctrl-c-hook' for more information.")
20412 (defvar org-metadown-hook nil
20413 "Hook for functions attaching themselves to `M-down'.
20414 See `org-ctrl-c-ctrl-c-hook' for more information.")
20415 (defvar org-shiftmetaleft-hook nil
20416 "Hook for functions attaching themselves to `M-S-left'.
20417 See `org-ctrl-c-ctrl-c-hook' for more information.")
20418 (defvar org-shiftmetaright-hook nil
20419 "Hook for functions attaching themselves to `M-S-right'.
20420 See `org-ctrl-c-ctrl-c-hook' for more information.")
20421 (defvar org-shiftmetaup-hook nil
20422 "Hook for functions attaching themselves to `M-S-up'.
20423 See `org-ctrl-c-ctrl-c-hook' for more information.")
20424 (defvar org-shiftmetadown-hook nil
20425 "Hook for functions attaching themselves to `M-S-down'.
20426 See `org-ctrl-c-ctrl-c-hook' for more information.")
20427 (defvar org-metareturn-hook nil
20428 "Hook for functions attaching themselves to `M-RET'.
20429 See `org-ctrl-c-ctrl-c-hook' for more information.")
20430 (defvar org-shiftup-hook nil
20431 "Hook for functions attaching themselves to `S-up'.
20432 See `org-ctrl-c-ctrl-c-hook' for more information.")
20433 (defvar org-shiftup-final-hook nil
20434 "Hook for functions attaching themselves to `S-up'.
20435 This one runs after all other options except shift-select have been excluded.
20436 See `org-ctrl-c-ctrl-c-hook' for more information.")
20437 (defvar org-shiftdown-hook nil
20438 "Hook for functions attaching themselves to `S-down'.
20439 See `org-ctrl-c-ctrl-c-hook' for more information.")
20440 (defvar org-shiftdown-final-hook nil
20441 "Hook for functions attaching themselves to `S-down'.
20442 This one runs after all other options except shift-select have been excluded.
20443 See `org-ctrl-c-ctrl-c-hook' for more information.")
20444 (defvar org-shiftleft-hook nil
20445 "Hook for functions attaching themselves to `S-left'.
20446 See `org-ctrl-c-ctrl-c-hook' for more information.")
20447 (defvar org-shiftleft-final-hook nil
20448 "Hook for functions attaching themselves to `S-left'.
20449 This one runs after all other options except shift-select have been excluded.
20450 See `org-ctrl-c-ctrl-c-hook' for more information.")
20451 (defvar org-shiftright-hook nil
20452 "Hook for functions attaching themselves to `S-right'.
20453 See `org-ctrl-c-ctrl-c-hook' for more information.")
20454 (defvar org-shiftright-final-hook nil
20455 "Hook for functions attaching themselves to `S-right'.
20456 This one runs after all other options except shift-select have been excluded.
20457 See `org-ctrl-c-ctrl-c-hook' for more information.")
20459 (defun org-modifier-cursor-error ()
20460 "Throw an error, a modified cursor command was applied in wrong context."
20461 (user-error "This command is active in special context like tables, headlines or items"))
20463 (defun org-shiftselect-error ()
20464 "Throw an error because Shift-Cursor command was applied in wrong context."
20465 (if (and (boundp 'shift-select-mode) shift-select-mode)
20466 (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
20467 (user-error "This command works only in special context like headlines or timestamps")))
20469 (defun org-call-for-shift-select (cmd)
20470 (let ((this-command-keys-shift-translated t))
20471 (call-interactively cmd)))
20473 (defun org-shifttab (&optional arg)
20474 "Global visibility cycling or move to previous table field.
20475 Call `org-table-previous-field' within a table.
20476 When ARG is nil, cycle globally through visibility states.
20477 When ARG is a numeric prefix, show contents of this level."
20478 (interactive "P")
20479 (cond
20480 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20481 ((integerp arg)
20482 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20483 (message "Content view to level: %d" arg)
20484 (org-content (prefix-numeric-value arg2))
20485 (org-cycle-show-empty-lines t)
20486 (setq org-cycle-global-status 'overview)))
20487 (t (call-interactively 'org-global-cycle))))
20489 (defun org-shiftmetaleft ()
20490 "Promote subtree or delete table column.
20491 Calls `org-promote-subtree', `org-outdent-item-tree', or
20492 `org-table-delete-column', depending on context. See the
20493 individual commands for more information."
20494 (interactive)
20495 (cond
20496 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20497 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20498 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20499 ((if (not (org-region-active-p)) (org-at-item-p)
20500 (save-excursion (goto-char (region-beginning))
20501 (org-at-item-p)))
20502 (call-interactively 'org-outdent-item-tree))
20503 (t (org-modifier-cursor-error))))
20505 (defun org-shiftmetaright ()
20506 "Demote subtree or insert table column.
20507 Calls `org-demote-subtree', `org-indent-item-tree', or
20508 `org-table-insert-column', depending on context. See the
20509 individual commands for more information."
20510 (interactive)
20511 (cond
20512 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20513 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20514 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20515 ((if (not (org-region-active-p)) (org-at-item-p)
20516 (save-excursion (goto-char (region-beginning))
20517 (org-at-item-p)))
20518 (call-interactively 'org-indent-item-tree))
20519 (t (org-modifier-cursor-error))))
20521 (defun org-shiftmetaup (&optional _arg)
20522 "Drag the line at point up.
20523 In a table, kill the current row.
20524 On a clock timestamp, update the value of the timestamp like `S-<up>'
20525 but also adjust the previous clocked item in the clock history.
20526 Everywhere else, drag the line at point up."
20527 (interactive "P")
20528 (cond
20529 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20530 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20531 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20532 (call-interactively 'org-timestamp-up)))
20533 (t (call-interactively 'org-drag-line-backward))))
20535 (defun org-shiftmetadown (&optional _arg)
20536 "Drag the line at point down.
20537 In a table, insert an empty row at the current line.
20538 On a clock timestamp, update the value of the timestamp like `S-<down>'
20539 but also adjust the previous clocked item in the clock history.
20540 Everywhere else, drag the line at point down."
20541 (interactive "P")
20542 (cond
20543 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20544 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20545 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20546 (call-interactively 'org-timestamp-down)))
20547 (t (call-interactively 'org-drag-line-forward))))
20549 (defsubst org-hidden-tree-error ()
20550 (user-error
20551 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20553 (defun org-metaleft (&optional _arg)
20554 "Promote heading, list item at point or move table column left.
20556 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20557 depending on context. With no specific context, calls the Emacs
20558 default `backward-word'. See the individual commands for more
20559 information.
20561 This function runs the hook `org-metaleft-hook' as a first step,
20562 and returns at first non-nil value."
20563 (interactive "P")
20564 (cond
20565 ((run-hook-with-args-until-success 'org-metaleft-hook))
20566 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20567 ((org-with-limited-levels
20568 (or (org-at-heading-p)
20569 (and (org-region-active-p)
20570 (save-excursion
20571 (goto-char (region-beginning))
20572 (org-at-heading-p)))))
20573 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20574 (call-interactively 'org-do-promote))
20575 ;; At an inline task.
20576 ((org-at-heading-p)
20577 (call-interactively 'org-inlinetask-promote))
20578 ((or (org-at-item-p)
20579 (and (org-region-active-p)
20580 (save-excursion
20581 (goto-char (region-beginning))
20582 (org-at-item-p))))
20583 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20584 (call-interactively 'org-outdent-item))
20585 (t (call-interactively 'backward-word))))
20587 (defun org-metaright (&optional _arg)
20588 "Demote heading, list item at point or move table column right.
20590 In front of a drawer or a block keyword, indent it correctly.
20592 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20593 `org-indent-drawer' or `org-indent-block' depending on context.
20594 With no specific context, calls the Emacs default `forward-word'.
20595 See the individual commands for more information.
20597 This function runs the hook `org-metaright-hook' as a first step,
20598 and returns at first non-nil value."
20599 (interactive "P")
20600 (cond
20601 ((run-hook-with-args-until-success 'org-metaright-hook))
20602 ((org-at-table-p) (call-interactively 'org-table-move-column))
20603 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20604 ((org-at-block-p) (call-interactively 'org-indent-block))
20605 ((org-with-limited-levels
20606 (or (org-at-heading-p)
20607 (and (org-region-active-p)
20608 (save-excursion
20609 (goto-char (region-beginning))
20610 (org-at-heading-p)))))
20611 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20612 (call-interactively 'org-do-demote))
20613 ;; At an inline task.
20614 ((org-at-heading-p)
20615 (call-interactively 'org-inlinetask-demote))
20616 ((or (org-at-item-p)
20617 (and (org-region-active-p)
20618 (save-excursion
20619 (goto-char (region-beginning))
20620 (org-at-item-p))))
20621 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20622 (call-interactively 'org-indent-item))
20623 (t (call-interactively 'forward-word))))
20625 (defun org-check-for-hidden (what)
20626 "Check if there are hidden headlines/items in the current visual line.
20627 WHAT can be either `headlines' or `items'. If the current line is
20628 an outline or item heading and it has a folded subtree below it,
20629 this function returns t, nil otherwise."
20630 (let ((re (cond
20631 ((eq what 'headlines) org-outline-regexp-bol)
20632 ((eq what 'items) (org-item-beginning-re))
20633 (t (error "This should not happen"))))
20634 beg end)
20635 (save-excursion
20636 (catch 'exit
20637 (unless (org-region-active-p)
20638 (setq beg (point-at-bol))
20639 (beginning-of-line 2)
20640 (while (and (not (eobp)) ;; this is like `next-line'
20641 (get-char-property (1- (point)) 'invisible))
20642 (beginning-of-line 2))
20643 (setq end (point))
20644 (goto-char beg)
20645 (goto-char (point-at-eol))
20646 (setq end (max end (point)))
20647 (while (re-search-forward re end t)
20648 (when (get-char-property (match-beginning 0) 'invisible)
20649 (throw 'exit t))))
20650 nil))))
20652 (defun org-metaup (&optional _arg)
20653 "Move subtree up or move table row up.
20654 Calls `org-move-subtree-up' or `org-table-move-row' or
20655 `org-move-item-up', depending on context. See the individual commands
20656 for more information."
20657 (interactive "P")
20658 (cond
20659 ((run-hook-with-args-until-success 'org-metaup-hook))
20660 ((org-region-active-p)
20661 (let* ((a (min (region-beginning) (region-end)))
20662 (b (1- (max (region-beginning) (region-end))))
20663 (c (save-excursion (goto-char a)
20664 (move-beginning-of-line 0)))
20665 (d (save-excursion (goto-char a)
20666 (move-end-of-line 0) (point))))
20667 (transpose-regions a b c d)
20668 (goto-char c)))
20669 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20670 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20671 ((org-at-item-p) (call-interactively 'org-move-item-up))
20672 (t (org-drag-element-backward))))
20674 (defun org-metadown (&optional _arg)
20675 "Move subtree down or move table row down.
20676 Calls `org-move-subtree-down' or `org-table-move-row' or
20677 `org-move-item-down', depending on context. See the individual
20678 commands for more information."
20679 (interactive "P")
20680 (cond
20681 ((run-hook-with-args-until-success 'org-metadown-hook))
20682 ((org-region-active-p)
20683 (let* ((a (min (region-beginning) (region-end)))
20684 (b (max (region-beginning) (region-end)))
20685 (c (save-excursion (goto-char b)
20686 (move-beginning-of-line 1)))
20687 (d (save-excursion (goto-char b)
20688 (move-end-of-line 1) (1+ (point)))))
20689 (transpose-regions a b c d)
20690 (goto-char d)))
20691 ((org-at-table-p) (call-interactively 'org-table-move-row))
20692 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20693 ((org-at-item-p) (call-interactively 'org-move-item-down))
20694 (t (org-drag-element-forward))))
20696 (defun org-shiftup (&optional arg)
20697 "Increase item in timestamp or increase priority of current headline.
20698 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20699 depending on context. See the individual commands for more information."
20700 (interactive "P")
20701 (cond
20702 ((run-hook-with-args-until-success 'org-shiftup-hook))
20703 ((and org-support-shift-select (org-region-active-p))
20704 (org-call-for-shift-select 'previous-line))
20705 ((org-at-timestamp-p t)
20706 (call-interactively (if org-edit-timestamp-down-means-later
20707 'org-timestamp-down 'org-timestamp-up)))
20708 ((and (not (eq org-support-shift-select 'always))
20709 org-enable-priority-commands
20710 (org-at-heading-p))
20711 (call-interactively 'org-priority-up))
20712 ((and (not org-support-shift-select) (org-at-item-p))
20713 (call-interactively 'org-previous-item))
20714 ((org-clocktable-try-shift 'up arg))
20715 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20716 (org-support-shift-select
20717 (org-call-for-shift-select 'previous-line))
20718 (t (org-shiftselect-error))))
20720 (defun org-shiftdown (&optional arg)
20721 "Decrease item in timestamp or decrease priority of current headline.
20722 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20723 depending on context. See the individual commands for more information."
20724 (interactive "P")
20725 (cond
20726 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20727 ((and org-support-shift-select (org-region-active-p))
20728 (org-call-for-shift-select 'next-line))
20729 ((org-at-timestamp-p t)
20730 (call-interactively (if org-edit-timestamp-down-means-later
20731 'org-timestamp-up 'org-timestamp-down)))
20732 ((and (not (eq org-support-shift-select 'always))
20733 org-enable-priority-commands
20734 (org-at-heading-p))
20735 (call-interactively 'org-priority-down))
20736 ((and (not org-support-shift-select) (org-at-item-p))
20737 (call-interactively 'org-next-item))
20738 ((org-clocktable-try-shift 'down arg))
20739 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20740 (org-support-shift-select
20741 (org-call-for-shift-select 'next-line))
20742 (t (org-shiftselect-error))))
20744 (defun org-shiftright (&optional arg)
20745 "Cycle the thing at point or in the current line, depending on context.
20746 Depending on context, this does one of the following:
20748 - switch a timestamp at point one day into the future
20749 - on a headline, switch to the next TODO keyword.
20750 - on an item, switch entire list to the next bullet type
20751 - on a property line, switch to the next allowed value
20752 - on a clocktable definition line, move time block into the future"
20753 (interactive "P")
20754 (cond
20755 ((run-hook-with-args-until-success 'org-shiftright-hook))
20756 ((and org-support-shift-select (org-region-active-p))
20757 (org-call-for-shift-select 'forward-char))
20758 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20759 ((and (not (eq org-support-shift-select 'always))
20760 (org-at-heading-p))
20761 (let ((org-inhibit-logging
20762 (not org-treat-S-cursor-todo-selection-as-state-change))
20763 (org-inhibit-blocking
20764 (not org-treat-S-cursor-todo-selection-as-state-change)))
20765 (org-call-with-arg 'org-todo 'right)))
20766 ((or (and org-support-shift-select
20767 (not (eq org-support-shift-select 'always))
20768 (org-at-item-bullet-p))
20769 (and (not org-support-shift-select) (org-at-item-p)))
20770 (org-call-with-arg 'org-cycle-list-bullet nil))
20771 ((and (not (eq org-support-shift-select 'always))
20772 (org-at-property-p))
20773 (call-interactively 'org-property-next-allowed-value))
20774 ((org-clocktable-try-shift 'right arg))
20775 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20776 (org-support-shift-select
20777 (org-call-for-shift-select 'forward-char))
20778 (t (org-shiftselect-error))))
20780 (defun org-shiftleft (&optional arg)
20781 "Cycle the thing at point or in the current line, depending on context.
20782 Depending on context, this does one of the following:
20784 - switch a timestamp at point one day into the past
20785 - on a headline, switch to the previous TODO keyword.
20786 - on an item, switch entire list to the previous bullet type
20787 - on a property line, switch to the previous allowed value
20788 - on a clocktable definition line, move time block into the past"
20789 (interactive "P")
20790 (cond
20791 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20792 ((and org-support-shift-select (org-region-active-p))
20793 (org-call-for-shift-select 'backward-char))
20794 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20795 ((and (not (eq org-support-shift-select 'always))
20796 (org-at-heading-p))
20797 (let ((org-inhibit-logging
20798 (not org-treat-S-cursor-todo-selection-as-state-change))
20799 (org-inhibit-blocking
20800 (not org-treat-S-cursor-todo-selection-as-state-change)))
20801 (org-call-with-arg 'org-todo 'left)))
20802 ((or (and org-support-shift-select
20803 (not (eq org-support-shift-select 'always))
20804 (org-at-item-bullet-p))
20805 (and (not org-support-shift-select) (org-at-item-p)))
20806 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20807 ((and (not (eq org-support-shift-select 'always))
20808 (org-at-property-p))
20809 (call-interactively 'org-property-previous-allowed-value))
20810 ((org-clocktable-try-shift 'left arg))
20811 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20812 (org-support-shift-select
20813 (org-call-for-shift-select 'backward-char))
20814 (t (org-shiftselect-error))))
20816 (defun org-shiftcontrolright ()
20817 "Switch to next TODO set."
20818 (interactive)
20819 (cond
20820 ((and org-support-shift-select (org-region-active-p))
20821 (org-call-for-shift-select 'forward-word))
20822 ((and (not (eq org-support-shift-select 'always))
20823 (org-at-heading-p))
20824 (org-call-with-arg 'org-todo 'nextset))
20825 (org-support-shift-select
20826 (org-call-for-shift-select 'forward-word))
20827 (t (org-shiftselect-error))))
20829 (defun org-shiftcontrolleft ()
20830 "Switch to previous TODO set."
20831 (interactive)
20832 (cond
20833 ((and org-support-shift-select (org-region-active-p))
20834 (org-call-for-shift-select 'backward-word))
20835 ((and (not (eq org-support-shift-select 'always))
20836 (org-at-heading-p))
20837 (org-call-with-arg 'org-todo 'previousset))
20838 (org-support-shift-select
20839 (org-call-for-shift-select 'backward-word))
20840 (t (org-shiftselect-error))))
20842 (defun org-shiftcontrolup (&optional n)
20843 "Change timestamps synchronously up in CLOCK log lines.
20844 Optional argument N tells to change by that many units."
20845 (interactive "P")
20846 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20847 (let (org-support-shift-select)
20848 (org-clock-timestamps-up n))
20849 (user-error "Not at a clock log")))
20851 (defun org-shiftcontroldown (&optional n)
20852 "Change timestamps synchronously down 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-down n))
20858 (user-error "Not at a clock log")))
20860 (defun org-increase-number-at-point (&optional inc)
20861 "Increment the number at point.
20862 With an optional prefix numeric argument INC, increment using
20863 this numeric value."
20864 (interactive "p")
20865 (if (not (number-at-point))
20866 (user-error "Not on a number")
20867 (unless inc (setq inc 1))
20868 (let ((pos (point))
20869 (beg (skip-chars-backward "-+^/*0-9eE."))
20870 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20871 (setq nap (buffer-substring-no-properties
20872 (+ pos beg) (+ pos beg end)))
20873 (delete-region (+ pos beg) (+ pos beg end))
20874 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20875 (when (org-at-table-p)
20876 (org-table-align)
20877 (org-table-end-of-field 1))))
20879 (defun org-decrease-number-at-point (&optional inc)
20880 "Decrement the number at point.
20881 With an optional prefix numeric argument INC, decrement using
20882 this numeric value."
20883 (interactive "p")
20884 (org-increase-number-at-point (- (or inc 1))))
20886 (defun org-ctrl-c-ret ()
20887 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20888 (interactive)
20889 (cond
20890 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20891 (t (call-interactively 'org-insert-heading))))
20893 (defun org-find-visible ()
20894 (let ((s (point)))
20895 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20896 (get-char-property s 'invisible)))
20898 (defun org-find-invisible ()
20899 (let ((s (point)))
20900 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20901 (not (get-char-property s 'invisible))))
20904 (defun org-copy-visible (beg end)
20905 "Copy the visible parts of the region."
20906 (interactive "r")
20907 (let (snippets s)
20908 (save-excursion
20909 (save-restriction
20910 (narrow-to-region beg end)
20911 (setq s (goto-char (point-min)))
20912 (while (not (= (point) (point-max)))
20913 (goto-char (org-find-invisible))
20914 (push (buffer-substring s (point)) snippets)
20915 (setq s (goto-char (org-find-visible))))))
20916 (kill-new (apply 'concat (nreverse snippets)))))
20918 (defun org-copy-special ()
20919 "Copy region in table or copy current subtree.
20920 Calls `org-table-copy-region' or `org-copy-subtree', depending on
20921 context. See the individual commands for more information."
20922 (interactive)
20923 (call-interactively
20924 (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
20926 (defun org-cut-special ()
20927 "Cut region in table or cut current subtree.
20928 Calls `org-table-cut-region' or `org-cut-subtree', depending on
20929 context. See the individual commands for more information."
20930 (interactive)
20931 (call-interactively
20932 (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
20934 (defun org-paste-special (arg)
20935 "Paste rectangular region into table, or past subtree relative to level.
20936 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20937 See the individual commands for more information."
20938 (interactive "P")
20939 (if (org-at-table-p)
20940 (org-table-paste-rectangle)
20941 (org-paste-subtree arg)))
20943 (defun org-edit-special (&optional arg)
20944 "Call a special editor for the element at point.
20945 When at a table, call the formula editor with `org-table-edit-formulas'.
20946 When in a source code block, call `org-edit-src-code'.
20947 When in a fixed-width region, call `org-edit-fixed-width-region'.
20948 When in an export block, call `org-edit-export-block'.
20949 When at an #+INCLUDE keyword, visit the included file.
20950 When at a footnote reference, call `org-edit-footnote-reference'
20951 On a link, call `ffap' to visit the link at point.
20952 Otherwise, return a user error."
20953 (interactive "P")
20954 (let ((element (org-element-at-point)))
20955 (barf-if-buffer-read-only)
20956 (pcase (org-element-type element)
20957 (`src-block
20958 (if (not arg) (org-edit-src-code)
20959 (let* ((info (org-babel-get-src-block-info))
20960 (lang (nth 0 info))
20961 (params (nth 2 info))
20962 (session (cdr (assq :session params))))
20963 (if (not session) (org-edit-src-code)
20964 ;; At a src-block with a session and function called with
20965 ;; an ARG: switch to the buffer related to the inferior
20966 ;; process.
20967 (switch-to-buffer
20968 (funcall (intern (concat "org-babel-prep-session:" lang))
20969 session params))))))
20970 (`keyword
20971 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20972 (org-open-link-from-string
20973 (format "[[%s]]"
20974 (expand-file-name
20975 (let ((value (org-element-property :value element)))
20976 (cond ((not (org-string-nw-p value))
20977 (user-error "No file to edit"))
20978 ((string-match "\\`\"\\(.*?\\)\"" value)
20979 (match-string 1 value))
20980 ((string-match "\\`[^ \t\"]\\S-*" value)
20981 (match-string 0 value))
20982 (t (user-error "No valid file specified")))))))
20983 (user-error "No special environment to edit here")))
20984 (`table
20985 (if (eq (org-element-property :type element) 'table.el)
20986 (org-edit-table.el)
20987 (call-interactively 'org-table-edit-formulas)))
20988 ;; Only Org tables contain `table-row' type elements.
20989 (`table-row (call-interactively 'org-table-edit-formulas))
20990 (`example-block (org-edit-src-code))
20991 (`export-block (org-edit-export-block))
20992 (`fixed-width (org-edit-fixed-width-region))
20994 ;; No notable element at point. Though, we may be at a link or
20995 ;; a footnote reference, which are objects. Thus, scan deeper.
20996 (let ((context (org-element-context element)))
20997 (pcase (org-element-type context)
20998 (`footnote-reference (org-edit-footnote-reference))
20999 (`inline-src-block (org-edit-inline-src-code))
21000 (`link (call-interactively #'ffap))
21001 (_ (user-error "No special environment to edit here"))))))))
21003 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21004 (defun org-ctrl-c-ctrl-c (&optional arg)
21005 "Set tags in headline, or update according to changed information at point.
21007 This command does many different things, depending on context:
21009 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21010 this is what we do.
21012 - If the cursor is on a statistics cookie, update it.
21014 - If the cursor is in a headline, prompt for tags and insert them
21015 into the current line, aligned to `org-tags-column'. When called
21016 with prefix arg, realign all tags in the current buffer.
21018 - If the cursor is in one of the special #+KEYWORD lines, this
21019 triggers scanning the buffer for these lines and updating the
21020 information.
21022 - If the cursor is inside a table, realign the table. This command
21023 works even if the automatic table editor has been turned off.
21025 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21026 the entire table.
21028 - If the cursor is at a footnote reference or definition, jump to
21029 the corresponding definition or references, respectively.
21031 - If the cursor is a the beginning of a dynamic block, update it.
21033 - If the current buffer is a capture buffer, close note and file it.
21035 - If the cursor is on a <<<target>>>, update radio targets and
21036 corresponding links in this buffer.
21038 - If the cursor is on a numbered item in a plain list, renumber the
21039 ordered list.
21041 - If the cursor is on a checkbox, toggle it.
21043 - If the cursor is on a code block, evaluate it. The variable
21044 `org-confirm-babel-evaluate' can be used to control prompting
21045 before code block evaluation, by default every code block
21046 evaluation requires confirmation. Code block evaluation can be
21047 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21048 (interactive "P")
21049 (cond
21050 ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
21051 (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21052 (org-remove-occur-highlights)
21053 (message "Temporary highlights/overlays removed from current buffer"))
21054 ((and (local-variable-p 'org-finish-function)
21055 (fboundp org-finish-function))
21056 (funcall org-finish-function))
21057 ((org-babel-hash-at-point))
21058 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21060 (let* ((context
21061 (org-element-lineage
21062 (org-element-context)
21063 ;; Limit to supported contexts.
21064 '(babel-call clock dynamic-block footnote-definition
21065 footnote-reference inline-babel-call inline-src-block
21066 inlinetask item keyword node-property paragraph
21067 plain-list property-drawer radio-target src-block
21068 statistics-cookie table table-cell table-row
21069 timestamp)
21071 (type (org-element-type context)))
21072 ;; For convenience: at the first line of a paragraph on the same
21073 ;; line as an item, apply function on that item instead.
21074 (when (eq type 'paragraph)
21075 (let ((parent (org-element-property :parent context)))
21076 (when (and (eq (org-element-type parent) 'item)
21077 (= (line-beginning-position)
21078 (org-element-property :begin parent)))
21079 (setq context parent)
21080 (setq type 'item))))
21081 ;; Act according to type of element or object at point.
21083 ;; Do nothing on a blank line, except if it is contained in
21084 ;; a src block. Hence, we first check if point is in such
21085 ;; a block and then if it is at a blank line.
21086 (pcase type
21087 ((or `inline-src-block `src-block)
21088 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
21089 (org-babel-eval-wipe-error-buffer)
21090 (org-babel-execute-src-block
21091 current-prefix-arg (org-babel-get-src-block-info nil context))))
21092 ((guard (org-match-line "[ \t]*$"))
21093 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21094 (user-error
21095 (substitute-command-keys
21096 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
21097 ((or `babel-call `inline-babel-call)
21098 (let ((info (org-babel-lob-get-info context)))
21099 (when info (org-babel-execute-src-block nil info))))
21100 (`clock (org-clock-update-time-maybe))
21101 (`dynamic-block
21102 (save-excursion
21103 (goto-char (org-element-property :post-affiliated context))
21104 (org-update-dblock)))
21105 (`footnote-definition
21106 (goto-char (org-element-property :post-affiliated context))
21107 (call-interactively 'org-footnote-action))
21108 (`footnote-reference (call-interactively #'org-footnote-action))
21109 ((or `headline `inlinetask)
21110 (save-excursion (goto-char (org-element-property :begin context))
21111 (call-interactively #'org-set-tags)))
21112 (`item
21113 ;; At an item: `C-u C-u' sets checkbox to "[-]"
21114 ;; unconditionally, whereas `C-u' will toggle its presence.
21115 ;; Without a universal argument, if the item has a checkbox,
21116 ;; toggle it. Otherwise repair the list.
21117 (let* ((box (org-element-property :checkbox context))
21118 (struct (org-element-property :structure context))
21119 (old-struct (copy-tree struct))
21120 (parents (org-list-parents-alist struct))
21121 (prevs (org-list-prevs-alist struct))
21122 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21123 (org-list-set-checkbox
21124 (org-element-property :begin context) struct
21125 (cond ((equal arg '(16)) "[-]")
21126 ((and (not box) (equal arg '(4))) "[ ]")
21127 ((or (not box) (equal arg '(4))) nil)
21128 ((eq box 'on) "[ ]")
21129 (t "[X]")))
21130 ;; Mimic `org-list-write-struct' but with grabbing a return
21131 ;; value from `org-list-struct-fix-box'.
21132 (org-list-struct-fix-ind struct parents 2)
21133 (org-list-struct-fix-item-end struct)
21134 (org-list-struct-fix-bul struct prevs)
21135 (org-list-struct-fix-ind struct parents)
21136 (let ((block-item
21137 (org-list-struct-fix-box struct parents prevs orderedp)))
21138 (if (and box (equal struct old-struct))
21139 (if (equal arg '(16))
21140 (message "Checkboxes already reset")
21141 (user-error "Cannot toggle this checkbox: %s"
21142 (if (eq box 'on)
21143 "all subitems checked"
21144 "unchecked subitems")))
21145 (org-list-struct-apply-struct struct old-struct)
21146 (org-update-checkbox-count-maybe))
21147 (when block-item
21148 (message "Checkboxes were removed due to empty box at line %d"
21149 (org-current-line block-item))))))
21150 (`keyword
21151 (let ((org-inhibit-startup-visibility-stuff t)
21152 (org-startup-align-all-tables nil))
21153 (when (boundp 'org-table-coordinate-overlays)
21154 (mapc #'delete-overlay org-table-coordinate-overlays)
21155 (setq org-table-coordinate-overlays nil))
21156 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21157 (message "Local setup has been refreshed"))
21158 (`plain-list
21159 ;; At a plain list, with a double C-u argument, set
21160 ;; checkboxes of each item to "[-]", whereas a single one
21161 ;; will toggle their presence according to the state of the
21162 ;; first item in the list. Without an argument, repair the
21163 ;; list.
21164 (let* ((begin (org-element-property :contents-begin context))
21165 (beginm (move-marker (make-marker) begin))
21166 (struct (org-element-property :structure context))
21167 (old-struct (copy-tree struct))
21168 (first-box (save-excursion
21169 (goto-char begin)
21170 (looking-at org-list-full-item-re)
21171 (match-string-no-properties 3)))
21172 (new-box (cond ((equal arg '(16)) "[-]")
21173 ((equal arg '(4)) (unless first-box "[ ]"))
21174 ((equal first-box "[X]") "[ ]")
21175 (t "[X]"))))
21176 (cond
21177 (arg
21178 (dolist (pos
21179 (org-list-get-all-items
21180 begin struct (org-list-prevs-alist struct)))
21181 (org-list-set-checkbox pos struct new-box)))
21182 ((and first-box (eq (point) begin))
21183 ;; For convenience, when point is at bol on the first
21184 ;; item of the list and no argument is provided, simply
21185 ;; toggle checkbox of that item, if any.
21186 (org-list-set-checkbox begin struct new-box)))
21187 (org-list-write-struct
21188 struct (org-list-parents-alist struct) old-struct)
21189 (org-update-checkbox-count-maybe)
21190 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21191 ((or `property-drawer `node-property)
21192 (call-interactively #'org-property-action))
21193 (`radio-target
21194 (call-interactively #'org-update-radio-target-regexp))
21195 (`statistics-cookie
21196 (call-interactively #'org-update-statistics-cookies))
21197 ((or `table `table-cell `table-row)
21198 ;; At a table, recalculate every field and align it. Also
21199 ;; send the table if necessary. If the table has
21200 ;; a `table.el' type, just give up. At a table row or cell,
21201 ;; maybe recalculate line but always align table.
21202 (if (eq (org-element-property :type context) 'table.el)
21203 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21204 Use `\\[org-edit-special]' to edit table.el tables"))
21205 (let ((org-enable-table-editor t))
21206 (if (or (eq type 'table)
21207 ;; Check if point is at a TBLFM line.
21208 (and (eq type 'table-row)
21209 (= (point) (org-element-property :end context))))
21210 (save-excursion
21211 (if (org-at-TBLFM-p)
21212 (progn (require 'org-table)
21213 (org-table-calc-current-TBLFM))
21214 (goto-char (org-element-property :contents-begin context))
21215 (org-call-with-arg 'org-table-recalculate (or arg t))
21216 (orgtbl-send-table 'maybe)))
21217 (org-table-maybe-eval-formula)
21218 (cond (arg (call-interactively #'org-table-recalculate))
21219 ((org-table-maybe-recalculate-line))
21220 (t (org-table-align)))))))
21221 (`timestamp (org-timestamp-change 0 'day))
21222 ((and `nil (guard (org-at-heading-p)))
21223 ;; When point is on an unsupported object type, we can miss
21224 ;; the fact that it also is at a heading. Handle it here.
21225 (call-interactively #'org-set-tags))
21226 ((guard
21227 (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
21229 (user-error
21230 (substitute-command-keys
21231 "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
21233 (defun org-mode-restart ()
21234 (interactive)
21235 (let ((indent-status (bound-and-true-p org-indent-mode)))
21236 (funcall major-mode)
21237 (hack-local-variables)
21238 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21239 (org-indent-mode -1)))
21240 (message "%s restarted" major-mode))
21242 (defun org-kill-note-or-show-branches ()
21243 "Abort storing current note, or call `outline-show-branches'."
21244 (interactive)
21245 (if (not org-finish-function)
21246 (progn
21247 (outline-hide-subtree)
21248 (call-interactively 'outline-show-branches))
21249 (let ((org-note-abort t))
21250 (funcall org-finish-function))))
21252 (defun org-delete-indentation (&optional arg)
21253 "Join current line to previous and fix whitespace at join.
21255 If previous line is a headline add to headline title. Otherwise
21256 the function calls `delete-indentation'.
21258 With a non-nil optional argument, join it to the following one."
21259 (interactive "*P")
21260 (if (save-excursion
21261 (beginning-of-line (if arg 1 0))
21262 (let ((case-fold-search nil))
21263 (looking-at org-complex-heading-regexp)))
21264 ;; At headline.
21265 (let ((tags-column (when (match-beginning 5)
21266 (save-excursion (goto-char (match-beginning 5))
21267 (current-column))))
21268 (string (concat " " (progn (when arg (forward-line 1))
21269 (org-trim (delete-and-extract-region
21270 (line-beginning-position)
21271 (line-end-position)))))))
21272 (unless (bobp) (delete-region (point) (1- (point))))
21273 (goto-char (or (match-end 4)
21274 (match-beginning 5)
21275 (match-end 0)))
21276 (skip-chars-backward " \t")
21277 (save-excursion (insert string))
21278 ;; Adjust alignment of tags.
21279 (cond
21280 ((not tags-column)) ;no tags
21281 (org-auto-align-tags (org-set-tags nil t))
21282 (t (org--align-tags-here tags-column)))) ;preserve tags column
21283 (delete-indentation arg)))
21285 (defun org-open-line (n)
21286 "Insert a new row in tables, call `open-line' elsewhere.
21287 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
21288 As a special case, when a document starts with a table, allow to
21289 call `open-line' on the very first character."
21290 (interactive "*p")
21291 (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
21292 (org-table-insert-row)
21293 (open-line n)))
21295 (defun org-return (&optional indent)
21296 "Goto next table row or insert a newline.
21298 Calls `org-table-next-row' or `newline', depending on context.
21300 When optional INDENT argument is non-nil, call
21301 `newline-and-indent' instead of `newline'.
21303 When `org-return-follows-link' is non-nil and point is on
21304 a timestamp or a link, call `org-open-at-point'. However, it
21305 will not happen if point is in a table or on a \"dead\"
21306 object (e.g., within a comment). In these case, you need to use
21307 `org-open-at-point' directly."
21308 (interactive)
21309 (let ((context (if org-return-follows-link (org-element-context)
21310 (org-element-at-point))))
21311 (cond
21312 ;; In a table, call `org-table-next-row'.
21313 ((or (and (eq (org-element-type context) 'table)
21314 (>= (point) (org-element-property :contents-begin context))
21315 (< (point) (org-element-property :contents-end context)))
21316 (org-element-lineage context '(table-row table-cell) t))
21317 (org-table-justify-field-maybe)
21318 (call-interactively #'org-table-next-row))
21319 ;; On a link or a timestamp, call `org-open-at-point' if
21320 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21321 ;; locations, e.g., in a comment, as `org-open-at-point'.
21322 ((and org-return-follows-link
21323 (or (org-in-regexp org-ts-regexp-both nil t)
21324 (org-in-regexp org-tsr-regexp-both nil t)
21325 (org-in-regexp org-any-link-re nil t)))
21326 (call-interactively #'org-open-at-point))
21327 ;; Insert newline in heading, but preserve tags.
21328 ((and (not (bolp))
21329 (save-excursion (beginning-of-line)
21330 (let ((case-fold-search nil))
21331 (looking-at org-complex-heading-regexp))))
21332 ;; At headline. Split line. However, if point is on keyword,
21333 ;; priority cookie or tags, do not break any of them: add
21334 ;; a newline after the headline instead.
21335 (let ((tags-column (and (match-beginning 5)
21336 (save-excursion (goto-char (match-beginning 5))
21337 (current-column))))
21338 (string
21339 (when (and (match-end 4) (org-point-in-group (point) 4))
21340 (delete-and-extract-region (point) (match-end 4)))))
21341 ;; Adjust tag alignment.
21342 (cond
21343 ((not (and tags-column string)))
21344 (org-auto-align-tags (org-set-tags nil t))
21345 (t (org--align-tags-here tags-column))) ;preserve tags column
21346 (end-of-line)
21347 (org-show-entry)
21348 (if indent (newline-and-indent) (newline))
21349 (when string (save-excursion (insert (org-trim string))))))
21350 ;; In a list, make sure indenting keeps trailing text within.
21351 ((and indent
21352 (not (eolp))
21353 (org-element-lineage context '(item)))
21354 (let ((trailing-data
21355 (delete-and-extract-region (point) (line-end-position))))
21356 (newline-and-indent)
21357 (save-excursion (insert trailing-data))))
21358 (t (if indent (newline-and-indent) (newline))))))
21360 (defun org-return-indent ()
21361 "Goto next table row or insert a newline and indent.
21362 Calls `org-table-next-row' or `newline-and-indent', depending on
21363 context. See the individual commands for more information."
21364 (interactive)
21365 (org-return t))
21367 (defun org-ctrl-c-star ()
21368 "Compute table, or change heading status of lines.
21369 Calls `org-table-recalculate' or `org-toggle-heading',
21370 depending on context."
21371 (interactive)
21372 (cond
21373 ((org-at-table-p)
21374 (call-interactively 'org-table-recalculate))
21376 ;; Convert all lines in region to list items
21377 (call-interactively 'org-toggle-heading))))
21379 (defun org-ctrl-c-minus ()
21380 "Insert separator line in table or modify bullet status of line.
21381 Also turns a plain line or a region of lines into list items.
21382 Calls `org-table-insert-hline', `org-toggle-item', or
21383 `org-cycle-list-bullet', depending on context."
21384 (interactive)
21385 (cond
21386 ((org-at-table-p)
21387 (call-interactively 'org-table-insert-hline))
21388 ((org-region-active-p)
21389 (call-interactively 'org-toggle-item))
21390 ((org-in-item-p)
21391 (call-interactively 'org-cycle-list-bullet))
21393 (call-interactively 'org-toggle-item))))
21395 (defun org-toggle-heading (&optional nstars)
21396 "Convert headings to normal text, or items or text to headings.
21397 If there is no active region, only convert the current line.
21399 With a `\\[universal-argument]' prefix, convert the whole list at
21400 point into heading.
21402 In a region:
21404 - If the first non blank line is a headline, remove the stars
21405 from all headlines in the region.
21407 - If it is a normal line, turn each and every normal line (i.e.,
21408 not an heading or an item) in the region into headings. If you
21409 want to convert only the first line of this region, use one
21410 universal prefix argument.
21412 - If it is a plain list item, turn all plain list items into headings.
21414 When converting a line into a heading, the number of stars is chosen
21415 such that the lines become children of the current entry. However,
21416 when a numeric prefix argument is given, its value determines the
21417 number of stars to add."
21418 (interactive "P")
21419 (let ((skip-blanks
21420 (function
21421 ;; Return beginning of first non-blank line, starting from
21422 ;; line at POS.
21423 (lambda (pos)
21424 (save-excursion
21425 (goto-char pos)
21426 (while (org-at-comment-p) (forward-line))
21427 (skip-chars-forward " \r\t\n")
21428 (point-at-bol)))))
21429 beg end toggled)
21430 ;; Determine boundaries of changes. If a universal prefix has
21431 ;; been given, put the list in a region. If region ends at a bol,
21432 ;; do not consider the last line to be in the region.
21434 (when (and current-prefix-arg (org-at-item-p))
21435 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21436 (org-mark-element))
21438 (if (org-region-active-p)
21439 (setq beg (funcall skip-blanks (region-beginning))
21440 end (copy-marker (save-excursion
21441 (goto-char (region-end))
21442 (if (bolp) (point) (point-at-eol)))))
21443 (setq beg (funcall skip-blanks (point-at-bol))
21444 end (copy-marker (point-at-eol))))
21445 ;; Ensure inline tasks don't count as headings.
21446 (org-with-limited-levels
21447 (save-excursion
21448 (goto-char beg)
21449 (cond
21450 ;; Case 1. Started at an heading: de-star headings.
21451 ((org-at-heading-p)
21452 (while (< (point) end)
21453 (when (org-at-heading-p t)
21454 (looking-at org-outline-regexp) (replace-match "")
21455 (setq toggled t))
21456 (forward-line)))
21457 ;; Case 2. Started at an item: change items into headlines.
21458 ;; One star will be added by `org-list-to-subtree'.
21459 ((org-at-item-p)
21460 (while (< (point) end)
21461 (when (org-at-item-p)
21462 ;; Pay attention to cases when region ends before list.
21463 (let* ((struct (org-list-struct))
21464 (list-end
21465 (min (org-list-get-bottom-point struct) (1+ end))))
21466 (save-restriction
21467 (narrow-to-region (point) list-end)
21468 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21469 (setq toggled t))
21470 (forward-line)))
21471 ;; Case 3. Started at normal text: make every line an heading,
21472 ;; skipping headlines and items.
21473 (t (let* ((stars
21474 (make-string
21475 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21476 (add-stars
21477 (cond (nstars "") ; stars from prefix only
21478 ((equal stars "") "*") ; before first heading
21479 (org-odd-levels-only "**") ; inside heading, odd
21480 (t "*"))) ; inside heading, oddeven
21481 (rpl (concat stars add-stars " "))
21482 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21483 (while (< (point) (if (equal nstars '(4)) lend end))
21484 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21485 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21486 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21487 (forward-line)))))))
21488 (unless toggled (message "Cannot toggle heading from here"))))
21490 (defun org-meta-return (&optional _arg)
21491 "Insert a new heading or wrap a region in a table.
21492 Calls `org-insert-heading' or `org-table-wrap-region', depending
21493 on context. See the individual commands for more information."
21494 (interactive)
21495 (org-check-before-invisible-edit 'insert)
21496 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21497 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21498 #'org-insert-heading))))
21500 ;;; Menu entries
21502 (defsubst org-in-subtree-not-table-p ()
21503 "Are we in a subtree and not in a table?"
21504 (and (not (org-before-first-heading-p))
21505 (not (org-at-table-p))))
21507 ;; Define the Org mode menus
21508 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21509 '("Tbl"
21510 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21511 ["Next Field" org-cycle (org-at-table-p)]
21512 ["Previous Field" org-shifttab (org-at-table-p)]
21513 ["Next Row" org-return (org-at-table-p)]
21514 "--"
21515 ["Blank Field" org-table-blank-field (org-at-table-p)]
21516 ["Edit Field" org-table-edit-field (org-at-table-p)]
21517 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21518 "--"
21519 ("Column"
21520 ["Move Column Left" org-metaleft (org-at-table-p)]
21521 ["Move Column Right" org-metaright (org-at-table-p)]
21522 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21523 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21524 ("Row"
21525 ["Move Row Up" org-metaup (org-at-table-p)]
21526 ["Move Row Down" org-metadown (org-at-table-p)]
21527 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21528 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21529 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21530 "--"
21531 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21532 ("Rectangle"
21533 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21534 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21535 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21536 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21537 "--"
21538 ("Calculate"
21539 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21540 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21541 ["Edit Formulas" org-edit-special (org-at-table-p)]
21542 "--"
21543 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21544 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21545 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21546 "--"
21547 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21548 "--"
21549 ["Sum Column/Rectangle" org-table-sum
21550 (or (org-at-table-p) (org-region-active-p))]
21551 ["Which Column?" org-table-current-column (org-at-table-p)])
21552 ["Debug Formulas"
21553 org-table-toggle-formula-debugger
21554 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21555 ["Show Col/Row Numbers"
21556 org-table-toggle-coordinate-overlays
21557 :style toggle
21558 :selected (bound-and-true-p org-table-overlay-coordinates)]
21559 "--"
21560 ["Create" org-table-create (and (not (org-at-table-p))
21561 org-enable-table-editor)]
21562 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21563 ["Import from File" org-table-import (not (org-at-table-p))]
21564 ["Export to File" org-table-export (org-at-table-p)]
21565 "--"
21566 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21567 "--"
21568 ("Plot"
21569 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21570 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21572 (easy-menu-define org-org-menu org-mode-map "Org menu"
21573 '("Org"
21574 ("Show/Hide"
21575 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21576 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21577 ["Sparse Tree..." org-sparse-tree t]
21578 ["Reveal Context" org-reveal t]
21579 ["Show All" outline-show-all t]
21580 "--"
21581 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21582 "--"
21583 ["New Heading" org-insert-heading t]
21584 ("Navigate Headings"
21585 ["Up" outline-up-heading t]
21586 ["Next" outline-next-visible-heading t]
21587 ["Previous" outline-previous-visible-heading t]
21588 ["Next Same Level" outline-forward-same-level t]
21589 ["Previous Same Level" outline-backward-same-level t]
21590 "--"
21591 ["Jump" org-goto t])
21592 ("Edit Structure"
21593 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21594 "--"
21595 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21596 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21597 "--"
21598 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21599 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21600 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21601 "--"
21602 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21603 "--"
21604 ["Copy visible text" org-copy-visible t]
21605 "--"
21606 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21607 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21608 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21609 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21610 "--"
21611 ["Sort Region/Children" org-sort t]
21612 "--"
21613 ["Convert to odd levels" org-convert-to-odd-levels t]
21614 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21615 ("Editing"
21616 ["Emphasis..." org-emphasize t]
21617 ["Edit Source Example" org-edit-special t]
21618 "--"
21619 ["Footnote new/jump" org-footnote-action t]
21620 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21621 ("Archive"
21622 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21623 "--"
21624 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21625 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21626 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21628 "--"
21629 ("Hyperlinks"
21630 ["Store Link (Global)" org-store-link t]
21631 ["Find existing link to here" org-occur-link-in-agenda-files t]
21632 ["Insert Link" org-insert-link t]
21633 ["Follow Link" org-open-at-point t]
21634 "--"
21635 ["Next link" org-next-link t]
21636 ["Previous link" org-previous-link t]
21637 "--"
21638 ["Descriptive Links"
21639 org-toggle-link-display
21640 :style radio
21641 :selected org-descriptive-links
21643 ["Literal Links"
21644 org-toggle-link-display
21645 :style radio
21646 :selected (not org-descriptive-links)])
21647 "--"
21648 ("TODO Lists"
21649 ["TODO/DONE/-" org-todo t]
21650 ("Select keyword"
21651 ["Next keyword" org-shiftright (org-at-heading-p)]
21652 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21653 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21654 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21655 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21656 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21657 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21658 "--"
21659 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21660 :selected org-enforce-todo-dependencies :style toggle :active t]
21661 "Settings for tree at point"
21662 ["Do Children sequentially" org-toggle-ordered-property :style radio
21663 :selected (org-entry-get nil "ORDERED")
21664 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21665 ["Do Children parallel" org-toggle-ordered-property :style radio
21666 :selected (not (org-entry-get nil "ORDERED"))
21667 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21668 "--"
21669 ["Set Priority" org-priority t]
21670 ["Priority Up" org-shiftup t]
21671 ["Priority Down" org-shiftdown t]
21672 "--"
21673 ["Get news from all feeds" org-feed-update-all t]
21674 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21675 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21676 ("TAGS and Properties"
21677 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21678 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21679 "--"
21680 ["Set property" org-set-property (not (org-before-first-heading-p))]
21681 ["Column view of properties" org-columns t]
21682 ["Insert Column View DBlock" org-columns-insert-dblock t])
21683 ("Dates and Scheduling"
21684 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21685 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21686 ("Change Date"
21687 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21688 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21689 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21690 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21691 ["Compute Time Range" org-evaluate-time-range t]
21692 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21693 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21694 "--"
21695 ["Custom time format" org-toggle-time-stamp-overlays
21696 :style radio :selected org-display-custom-times]
21697 "--"
21698 ["Goto Calendar" org-goto-calendar t]
21699 ["Date from Calendar" org-date-from-calendar t]
21700 "--"
21701 ["Start/Restart Timer" org-timer-start t]
21702 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21703 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21704 ["Insert Timer String" org-timer t]
21705 ["Insert Timer Item" org-timer-item t])
21706 ("Logging work"
21707 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21708 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21709 ["Clock out" org-clock-out t]
21710 ["Clock cancel" org-clock-cancel t]
21711 "--"
21712 ["Mark as default task" org-clock-mark-default-task t]
21713 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21714 ["Goto running clock" org-clock-goto t]
21715 "--"
21716 ["Display times" org-clock-display t]
21717 ["Create clock table" org-clock-report t]
21718 "--"
21719 ["Record DONE time"
21720 (progn (setq org-log-done (not org-log-done))
21721 (message "Switching to %s will %s record a timestamp"
21722 (car org-done-keywords)
21723 (if org-log-done "automatically" "not")))
21724 :style toggle :selected org-log-done])
21725 "--"
21726 ["Agenda Command..." org-agenda t]
21727 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21728 ("File List for Agenda")
21729 ("Special views current file"
21730 ["TODO Tree" org-show-todo-tree t]
21731 ["Check Deadlines" org-check-deadlines t]
21732 ["Timeline" org-timeline t]
21733 ["Tags/Property tree" org-match-sparse-tree t])
21734 "--"
21735 ["Export/Publish..." org-export-dispatch t]
21736 ("LaTeX"
21737 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21738 :selected org-cdlatex-mode]
21739 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21740 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21741 ["Modify math symbol" org-cdlatex-math-modify
21742 (org-inside-LaTeX-fragment-p)]
21743 ["Insert citation" org-reftex-citation t])
21744 "--"
21745 ("MobileOrg"
21746 ["Push Files and Views" org-mobile-push t]
21747 ["Get Captured and Flagged" org-mobile-pull t]
21748 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21749 "--"
21750 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21751 "--"
21752 ("Documentation"
21753 ["Show Version" org-version t]
21754 ["Info Documentation" org-info t])
21755 ("Customize"
21756 ["Browse Org Group" org-customize t]
21757 "--"
21758 ["Expand This Menu" org-create-customize-menu
21759 (fboundp 'customize-menu-create)])
21760 ["Send bug report" org-submit-bug-report t]
21761 "--"
21762 ("Refresh/Reload"
21763 ["Refresh setup current buffer" org-mode-restart t]
21764 ["Reload Org (after update)" org-reload t]
21765 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21768 (defun org-info (&optional node)
21769 "Read documentation for Org in the info system.
21770 With optional NODE, go directly to that node."
21771 (interactive)
21772 (info (format "(org)%s" (or node ""))))
21774 ;;;###autoload
21775 (defun org-submit-bug-report ()
21776 "Submit a bug report on Org via mail.
21778 Don't hesitate to report any problems or inaccurate documentation.
21780 If you don't have setup sending mail from (X)Emacs, please copy the
21781 output buffer into your mail program, as it gives us important
21782 information about your Org version and configuration."
21783 (interactive)
21784 (require 'reporter)
21785 (defvar reporter-prompt-for-summary-p)
21786 (org-load-modules-maybe)
21787 (org-require-autoloaded-modules)
21788 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21789 (reporter-submit-bug-report
21790 "emacs-orgmode@gnu.org"
21791 (org-version nil 'full)
21792 (let (list)
21793 (save-window-excursion
21794 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21795 (delete-other-windows)
21796 (erase-buffer)
21797 (insert "You are about to submit a bug report to the Org mailing list.
21799 We would like to add your full Org and Outline configuration to the
21800 bug report. This greatly simplifies the work of the maintainer and
21801 other experts on the mailing list.
21803 HOWEVER, some variables you have customized may contain private
21804 information. The names of customers, colleagues, or friends, might
21805 appear in the form of file names, tags, todo states, or search strings.
21806 If you answer yes to the prompt, you might want to check and remove
21807 such private information before sending the email.")
21808 (add-text-properties (point-min) (point-max) '(face org-warning))
21809 (when (yes-or-no-p "Include your Org configuration ")
21810 (mapatoms
21811 (lambda (v)
21812 (and (boundp v)
21813 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21814 (or (and (symbol-value v)
21815 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21816 (and
21817 (get v 'custom-type) (get v 'standard-value)
21818 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21819 (push v list)))))
21820 (kill-buffer (get-buffer "*Warn about privacy*"))
21821 list))
21822 nil nil
21823 "Remember to cover the basics, that is, what you expected to happen and
21824 what in fact did happen. You don't know how to make a good report? See
21826 http://orgmode.org/manual/Feedback.html#Feedback
21828 Your bug report will be posted to the Org mailing list.
21829 ------------------------------------------------------------------------")
21830 (save-excursion
21831 (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21832 (replace-match "\\1Bug: \\3 [\\2]")))))
21835 (defun org-install-agenda-files-menu ()
21836 (let ((bl (buffer-list)))
21837 (save-excursion
21838 (while bl
21839 (set-buffer (pop bl))
21840 (when (derived-mode-p 'org-mode) (setq bl nil)))
21841 (when (derived-mode-p 'org-mode)
21842 (easy-menu-change
21843 '("Org") "File List for Agenda"
21844 (append
21845 (list
21846 ["Edit File List" (org-edit-agenda-file-list) t]
21847 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21848 ["Remove Current File from List" org-remove-file t]
21849 ["Cycle through agenda files" org-cycle-agenda-files t]
21850 ["Occur in all agenda files" org-occur-in-agenda-files t]
21851 "--")
21852 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21854 ;;;; Documentation
21856 (defun org-require-autoloaded-modules ()
21857 (interactive)
21858 (mapc #'require
21859 '(org-agenda org-archive org-attach org-clock org-colview org-id
21860 org-table org-timer)))
21862 ;;;###autoload
21863 (defun org-reload (&optional uncompiled)
21864 "Reload all org lisp files.
21865 With prefix arg UNCOMPILED, load the uncompiled versions."
21866 (interactive "P")
21867 (require 'loadhist)
21868 (let* ((org-dir (org-find-library-dir "org"))
21869 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21870 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21871 (remove-re (format "\\`%s\\'"
21872 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21873 (feats (delete-dups
21874 (mapcar 'file-name-sans-extension
21875 (mapcar 'file-name-nondirectory
21876 (delq nil
21877 (mapcar 'feature-file
21878 features))))))
21879 (lfeat (append
21880 (sort
21881 (setq feats
21882 (delq nil (mapcar
21883 (lambda (f)
21884 (if (and (string-match feature-re f)
21885 (not (string-match remove-re f)))
21886 f nil))
21887 feats)))
21888 'string-lessp)
21889 (list "org-version" "org")))
21890 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21891 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21892 load-uncore load-misses)
21893 (setq load-misses
21894 (delq 't
21895 (mapcar (lambda (f)
21896 (or (org-load-noerror-mustsuffix (concat org-dir f))
21897 (and (string= org-dir contrib-dir)
21898 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21899 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21900 (add-to-list 'load-uncore f 'append)
21903 lfeat)))
21904 (when load-uncore
21905 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21906 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21907 (if load-misses
21908 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21909 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21910 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21912 ;;;###autoload
21913 (defun org-customize ()
21914 "Call the customize function with org as argument."
21915 (interactive)
21916 (org-load-modules-maybe)
21917 (org-require-autoloaded-modules)
21918 (customize-browse 'org))
21920 (defun org-create-customize-menu ()
21921 "Create a full customization menu for Org mode, insert it into the menu."
21922 (interactive)
21923 (org-load-modules-maybe)
21924 (org-require-autoloaded-modules)
21925 (if (fboundp 'customize-menu-create)
21926 (progn
21927 (easy-menu-change
21928 '("Org") "Customize"
21929 `(["Browse Org group" org-customize t]
21930 "--"
21931 ,(customize-menu-create 'org)
21932 ["Set" Custom-set t]
21933 ["Save" Custom-save t]
21934 ["Reset to Current" Custom-reset-current t]
21935 ["Reset to Saved" Custom-reset-saved t]
21936 ["Reset to Standard Settings" Custom-reset-standard t]))
21937 (message "\"Org\"-menu now contains full customization menu"))
21938 (error "Cannot expand menu (outdated version of cus-edit.el)")))
21940 ;;;; Miscellaneous stuff
21942 ;;; Generally useful functions
21944 (defun org-get-at-eol (property n)
21945 "Get text property PROPERTY at the end of line less N characters."
21946 (get-text-property (- (point-at-eol) n) property))
21948 (defun org-find-text-property-in-string (prop s)
21949 "Return the first non-nil value of property PROP in string S."
21950 (or (get-text-property 0 prop s)
21951 (get-text-property (or (next-single-property-change 0 prop s) 0)
21952 prop s)))
21954 (defun org-display-warning (message)
21955 "Display the given MESSAGE as a warning."
21956 (display-warning 'org message :warning))
21958 (defun org-eval (form)
21959 "Eval FORM and return result."
21960 (condition-case error
21961 (eval form)
21962 (error (format "%%![Error: %s]" error))))
21964 (defun org-in-clocktable-p ()
21965 "Check if the cursor is in a clocktable."
21966 (let ((pos (point)) start)
21967 (save-excursion
21968 (end-of-line 1)
21969 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
21970 (setq start (match-beginning 0))
21971 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
21972 (>= (match-end 0) pos)
21973 start))))
21975 (defun org-in-verbatim-emphasis ()
21976 (save-match-data
21977 (and (org-in-regexp org-emph-re 2)
21978 (>= (point) (match-beginning 3))
21979 (<= (point) (match-end 4))
21980 (member (match-string 3) '("=" "~")))))
21982 (defun org-overlay-display (ovl text &optional face evap)
21983 "Make overlay OVL display TEXT with face FACE."
21984 (overlay-put ovl 'display text)
21985 (if face (overlay-put ovl 'face face))
21986 (if evap (overlay-put ovl 'evaporate t)))
21988 (defun org-overlay-before-string (ovl text &optional face evap)
21989 "Make overlay OVL display TEXT with face FACE."
21990 (if face (org-add-props text nil 'face face))
21991 (overlay-put ovl 'before-string text)
21992 (if evap (overlay-put ovl 'evaporate t)))
21994 (defun org-find-overlays (prop &optional pos delete)
21995 "Find all overlays specifying PROP at POS or point.
21996 If DELETE is non-nil, delete all those overlays."
21997 (let (found)
21998 (dolist (ov (overlays-at (or pos (point))) found)
21999 (cond ((not (overlay-get ov prop)))
22000 (delete (delete-overlay ov))
22001 (t (push ov found))))))
22003 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22004 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22005 (if (and marker (marker-buffer marker)
22006 (buffer-live-p (marker-buffer marker)))
22007 (progn
22008 (pop-to-buffer-same-window (marker-buffer marker))
22009 (when (or (> marker (point-max)) (< marker (point-min)))
22010 (widen))
22011 (goto-char marker)
22012 (org-show-context 'org-goto))
22013 (if bookmark
22014 (bookmark-jump bookmark)
22015 (error "Cannot find location"))))
22017 (defun org-quote-csv-field (s)
22018 "Quote field for inclusion in CSV material."
22019 (if (string-match "[\",]" s)
22020 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22023 (defun org-force-self-insert (N)
22024 "Needed to enforce self-insert under remapping."
22025 (interactive "p")
22026 (self-insert-command N))
22028 (defun org-string-width (s)
22029 "Compute width of string, ignoring invisible characters.
22030 This ignores character with invisibility property `org-link', and also
22031 characters with property `org-cwidth', because these will become invisible
22032 upon the next fontification round."
22033 (let (b l)
22034 (when (or (eq t buffer-invisibility-spec)
22035 (assq 'org-link buffer-invisibility-spec))
22036 (while (setq b (text-property-any 0 (length s)
22037 'invisible 'org-link s))
22038 (setq s (concat (substring s 0 b)
22039 (substring s (or (next-single-property-change
22040 b 'invisible s)
22041 (length s)))))))
22042 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22043 (setq s (concat (substring s 0 b)
22044 (substring s (or (next-single-property-change
22045 b 'org-cwidth s)
22046 (length s))))))
22047 (setq l (string-width s) b -1)
22048 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22049 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22052 (defun org-shorten-string (s maxlength)
22053 "Shorten string S so that it is no longer than MAXLENGTH characters.
22054 If the string is shorter or has length MAXLENGTH, just return the
22055 original string. If it is longer, the functions finds a space in the
22056 string, breaks this string off at that locations and adds three dots
22057 as ellipsis. Including the ellipsis, the string will not be longer
22058 than MAXLENGTH. If finding a good breaking point in the string does
22059 not work, the string is just chopped off in the middle of a word
22060 if necessary."
22061 (if (<= (length s) maxlength)
22063 (let* ((n (max (- maxlength 4) 1))
22064 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22065 (if (string-match re s)
22066 (concat (match-string 1 s) "...")
22067 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22069 (defun org-get-indentation (&optional line)
22070 "Get the indentation of the current line, interpreting tabs.
22071 When LINE is given, assume it represents a line and compute its indentation."
22072 (if line
22073 (when (string-match "^ *" (org-remove-tabs line))
22074 (match-end 0))
22075 (save-excursion
22076 (beginning-of-line 1)
22077 (skip-chars-forward " \t")
22078 (current-column))))
22080 (defun org-get-string-indentation (s)
22081 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22082 (let ((n -1) (i 0) (w tab-width) c)
22083 (catch 'exit
22084 (while (< (setq n (1+ n)) (length s))
22085 (setq c (aref s n))
22086 (cond ((= c ?\ ) (setq i (1+ i)))
22087 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22088 (t (throw 'exit t)))))
22091 (defun org-remove-tabs (s &optional width)
22092 "Replace tabulators in S with spaces.
22093 Assumes that s is a single line, starting in column 0."
22094 (setq width (or width tab-width))
22095 (while (string-match "\t" s)
22096 (setq s (replace-match
22097 (make-string
22098 (- (* width (/ (+ (match-beginning 0) width) width))
22099 (match-beginning 0)) ?\ )
22100 t t s)))
22103 (defun org-fix-indentation (line ind)
22104 "Fix indentation in LINE.
22105 IND is a cons cell with target and minimum indentation.
22106 If the current indentation in LINE is smaller than the minimum,
22107 leave it alone. If it is larger than ind, set it to the target."
22108 (let* ((l (org-remove-tabs line))
22109 (i (org-get-indentation l))
22110 (i1 (car ind)) (i2 (cdr ind)))
22111 (when (>= i i2) (setq l (substring line i2)))
22112 (if (> i1 0)
22113 (concat (make-string i1 ?\ ) l)
22114 l)))
22116 (defun org-remove-indentation (code &optional n)
22117 "Remove maximum common indentation in string CODE and return it.
22118 N may optionally be the number of columns to remove. Return CODE
22119 as-is if removal failed."
22120 (with-temp-buffer
22121 (insert code)
22122 (if (org-do-remove-indentation n) (buffer-string) code)))
22124 (defun org-do-remove-indentation (&optional n)
22125 "Remove the maximum common indentation from the buffer.
22126 When optional argument N is a positive integer, remove exactly
22127 that much characters from indentation, if possible. Return nil
22128 if it fails."
22129 (catch :exit
22130 (goto-char (point-min))
22131 ;; Find maximum common indentation, if not specified.
22132 (let ((n (or n
22133 (let ((min-ind (point-max)))
22134 (save-excursion
22135 (while (re-search-forward "^[ \t]*\\S-" nil t)
22136 (let ((ind (1- (current-column))))
22137 (if (zerop ind) (throw :exit nil)
22138 (setq min-ind (min min-ind ind))))))
22139 min-ind))))
22140 (if (zerop n) (throw :exit nil)
22141 ;; Remove exactly N indentation, but give up if not possible.
22142 (while (not (eobp))
22143 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22144 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22145 ((< ind n) (throw :exit nil))
22146 (t (indent-line-to (- ind n))))
22147 (forward-line)))
22148 ;; Signal success.
22149 t))))
22151 (defun org-fill-template (template alist)
22152 "Find each %key of ALIST in TEMPLATE and replace it."
22153 (let ((case-fold-search nil))
22154 (dolist (entry (sort (copy-sequence alist)
22155 (lambda (a b) (< (length (car a)) (length (car b))))))
22156 (setq template
22157 (replace-regexp-in-string
22158 (concat "%" (regexp-quote (car entry)))
22159 (or (cdr entry) "") template t t)))
22160 template))
22162 (defun org-base-buffer (buffer)
22163 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22164 (if (not buffer)
22165 buffer
22166 (or (buffer-base-buffer buffer)
22167 buffer)))
22169 (defun org-wrap (string &optional width lines)
22170 "Wrap string to either a number of lines, or a width in characters.
22171 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22172 that costs. If there is a word longer than WIDTH, the text is actually
22173 wrapped to the length of that word.
22174 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22175 many lines, whatever width that takes.
22176 The return value is a list of lines, without newlines at the end."
22177 (let* ((words (org-split-string string "[ \t\n]+"))
22178 (maxword (apply 'max (mapcar 'org-string-width words)))
22179 w ll)
22180 (cond (width
22181 (org-do-wrap words (max maxword width)))
22182 (lines
22183 (setq w maxword)
22184 (setq ll (org-do-wrap words maxword))
22185 (if (<= (length ll) lines)
22187 (setq ll words)
22188 (while (> (length ll) lines)
22189 (setq w (1+ w))
22190 (setq ll (org-do-wrap words w)))
22191 ll))
22192 (t (error "Cannot wrap this")))))
22194 (defun org-do-wrap (words width)
22195 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22196 (let (lines line)
22197 (while words
22198 (setq line (pop words))
22199 (while (and words (< (+ (length line) (length (car words))) width))
22200 (setq line (concat line " " (pop words))))
22201 (setq lines (push line lines)))
22202 (nreverse lines)))
22204 (defun org-split-string (string &optional separators)
22205 "Splits STRING into substrings at SEPARATORS.
22206 SEPARATORS is a regular expression.
22207 No empty strings are returned if there are matches at the beginning
22208 and end of string."
22209 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22210 (let ((start 0) notfirst list)
22211 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22212 (if (and notfirst
22213 (= start (match-beginning 0))
22214 (< start (length string)))
22215 (1+ start) start))
22216 (< (match-beginning 0) (length string)))
22217 (setq notfirst t)
22218 (or (eq (match-beginning 0) 0)
22219 (and (eq (match-beginning 0) (match-end 0))
22220 (eq (match-beginning 0) start))
22221 (push (substring string start (match-beginning 0)) list))
22222 (setq start (match-end 0)))
22223 (or (eq start (length string))
22224 (push (substring string start) list))
22225 (nreverse list)))
22227 (defun org-quote-vert (s)
22228 "Replace \"|\" with \"\\vert\"."
22229 (while (string-match "|" s)
22230 (setq s (replace-match "\\vert" t t s)))
22233 (defun org-uuidgen-p (s)
22234 "Is S an ID created by UUIDGEN?"
22235 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22237 (defun org-in-src-block-p (&optional inside)
22238 "Whether point is in a code source block.
22239 When INSIDE is non-nil, don't consider we are within a src block
22240 when point is at #+BEGIN_SRC or #+END_SRC."
22241 (let ((case-fold-search t))
22242 (or (and (eq (get-char-property (point) 'src-block) t))
22243 (and (not inside)
22244 (save-match-data
22245 (save-excursion
22246 (beginning-of-line)
22247 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22249 (defun org-context ()
22250 "Return a list of contexts of the current cursor position.
22251 If several contexts apply, all are returned.
22252 Each context entry is a list with a symbol naming the context, and
22253 two positions indicating start and end of the context. Possible
22254 contexts are:
22256 :headline anywhere in a headline
22257 :headline-stars on the leading stars in a headline
22258 :todo-keyword on a TODO keyword (including DONE) in a headline
22259 :tags on the TAGS in a headline
22260 :priority on the priority cookie in a headline
22261 :item on the first line of a plain list item
22262 :item-bullet on the bullet/number of a plain list item
22263 :checkbox on the checkbox in a plain list item
22264 :table in an Org table
22265 :table-special on a special filed in a table
22266 :table-table in a table.el table
22267 :clocktable in a clocktable
22268 :src-block in a source block
22269 :link on a hyperlink
22270 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22271 :target on a <<target>>
22272 :radio-target on a <<<radio-target>>>
22273 :latex-fragment on a LaTeX fragment
22274 :latex-preview on a LaTeX fragment with overlaid preview image
22276 This function expects the position to be visible because it uses font-lock
22277 faces as a help to recognize the following contexts: :table-special, :link,
22278 and :keyword."
22279 (let* ((f (get-text-property (point) 'face))
22280 (faces (if (listp f) f (list f)))
22281 (case-fold-search t)
22282 (p (point)) clist o)
22283 ;; First the large context
22284 (cond
22285 ((org-at-heading-p t)
22286 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22287 (when (progn
22288 (beginning-of-line 1)
22289 (looking-at org-todo-line-tags-regexp))
22290 (push (org-point-in-group p 1 :headline-stars) clist)
22291 (push (org-point-in-group p 2 :todo-keyword) clist)
22292 (push (org-point-in-group p 4 :tags) clist))
22293 (goto-char p)
22294 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22295 (when (looking-at "\\[#[A-Z0-9]\\]")
22296 (push (org-point-in-group p 0 :priority) clist)))
22298 ((org-at-item-p)
22299 (push (org-point-in-group p 2 :item-bullet) clist)
22300 (push (list :item (point-at-bol)
22301 (save-excursion (org-end-of-item) (point)))
22302 clist)
22303 (and (org-at-item-checkbox-p)
22304 (push (org-point-in-group p 0 :checkbox) clist)))
22306 ((org-at-table-p)
22307 (push (list :table (org-table-begin) (org-table-end)) clist)
22308 (when (memq 'org-formula faces)
22309 (push (list :table-special
22310 (previous-single-property-change p 'face)
22311 (next-single-property-change p 'face)) clist)))
22312 ((org-at-table-p 'any)
22313 (push (list :table-table) clist)))
22314 (goto-char p)
22316 (let ((case-fold-search t))
22317 ;; New the "medium" contexts: clocktables, source blocks
22318 (cond ((org-in-clocktable-p)
22319 (push (list :clocktable
22320 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22321 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22322 (match-beginning 1))
22323 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22324 (match-end 0))) clist))
22325 ((org-in-src-block-p)
22326 (push (list :src-block
22327 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22328 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22329 (match-beginning 1))
22330 (and (search-forward "#+END_SRC" nil t)
22331 (match-beginning 0))) clist))))
22332 (goto-char p)
22334 ;; Now the small context
22335 (cond
22336 ((org-at-timestamp-p)
22337 (push (org-point-in-group p 0 :timestamp) clist))
22338 ((memq 'org-link faces)
22339 (push (list :link
22340 (previous-single-property-change p 'face)
22341 (next-single-property-change p 'face)) clist))
22342 ((memq 'org-special-keyword faces)
22343 (push (list :keyword
22344 (previous-single-property-change p 'face)
22345 (next-single-property-change p 'face)) clist))
22346 ((org-at-target-p)
22347 (push (org-point-in-group p 0 :target) clist)
22348 (goto-char (1- (match-beginning 0)))
22349 (when (looking-at org-radio-target-regexp)
22350 (push (org-point-in-group p 0 :radio-target) clist))
22351 (goto-char p))
22352 ((setq o (cl-some
22353 (lambda (o)
22354 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22356 (overlays-at (point))))
22357 (push (list :latex-fragment
22358 (overlay-start o) (overlay-end o)) clist)
22359 (push (list :latex-preview
22360 (overlay-start o) (overlay-end o)) clist))
22361 ((org-inside-LaTeX-fragment-p)
22362 ;; FIXME: positions wrong.
22363 (push (list :latex-fragment (point) (point)) clist)))
22365 (setq clist (nreverse (delq nil clist)))
22366 clist))
22368 (defun org-in-regexp (regexp &optional nlines visually)
22369 "Check if point is inside a match of REGEXP.
22371 Normally only the current line is checked, but you can include
22372 NLINES extra lines around point into the search. If VISUALLY is
22373 set, require that the cursor is not after the match but really
22374 on, so that the block visually is on the match.
22376 Return nil or a cons cell (BEG . END) where BEG and END are,
22377 respectively, the positions at the beginning and the end of the
22378 match."
22379 (catch :exit
22380 (let ((pos (point))
22381 (eol (line-end-position (if nlines (1+ nlines) 1))))
22382 (save-excursion
22383 (beginning-of-line (- 1 (or nlines 0)))
22384 (while (and (re-search-forward regexp eol t)
22385 (<= (match-beginning 0) pos))
22386 (let ((end (match-end 0)))
22387 (when (or (> end pos) (and (= end pos) (not visually)))
22388 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22390 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22391 "Non-nil when point is between matches of START-RE and END-RE.
22393 Also return a non-nil value when point is on one of the matches.
22395 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22396 buffer positions. Default values are the positions of headlines
22397 surrounding the point.
22399 The functions returns a cons cell whose car (resp. cdr) is the
22400 position before START-RE (resp. after END-RE)."
22401 (save-match-data
22402 (let ((pos (point))
22403 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22404 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22405 beg end)
22406 (save-excursion
22407 ;; Point is on a block when on START-RE or if START-RE can be
22408 ;; found before it...
22409 (and (or (org-in-regexp start-re)
22410 (re-search-backward start-re limit-up t))
22411 (setq beg (match-beginning 0))
22412 ;; ... and END-RE after it...
22413 (goto-char (match-end 0))
22414 (re-search-forward end-re limit-down t)
22415 (> (setq end (match-end 0)) pos)
22416 ;; ... without another START-RE in-between.
22417 (goto-char (match-beginning 0))
22418 (not (re-search-backward start-re (1+ beg) t))
22419 ;; Return value.
22420 (cons beg end))))))
22422 (defun org-in-block-p (names)
22423 "Non-nil when point belongs to a block whose name belongs to NAMES.
22425 NAMES is a list of strings containing names of blocks.
22427 Return first block name matched, or nil. Beware that in case of
22428 nested blocks, the returned name may not belong to the closest
22429 block from point."
22430 (save-match-data
22431 (catch 'exit
22432 (let ((case-fold-search t)
22433 (lim-up (save-excursion (outline-previous-heading)))
22434 (lim-down (save-excursion (outline-next-heading))))
22435 (dolist (name names)
22436 (let ((n (regexp-quote name)))
22437 (when (org-between-regexps-p
22438 (concat "^[ \t]*#\\+begin_" n)
22439 (concat "^[ \t]*#\\+end_" n)
22440 lim-up lim-down)
22441 (throw 'exit n)))))
22442 nil)))
22444 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22445 "Call `multi-occur' with buffers for all agenda files."
22446 (interactive "sOrg-files matching: ")
22447 (let* ((files (org-agenda-files))
22448 (tnames (mapcar #'file-truename files))
22449 (extra org-agenda-text-search-extra-files))
22450 (when (eq (car extra) 'agenda-archives)
22451 (setq extra (cdr extra))
22452 (setq files (org-add-archive-files files)))
22453 (dolist (f extra)
22454 (unless (member (file-truename f) tnames)
22455 (unless (member f files) (setq files (append files (list f))))
22456 (setq tnames (append tnames (list (file-truename f))))))
22457 (multi-occur
22458 (mapcar (lambda (x)
22459 (with-current-buffer
22460 ;; FIXME: Why not just (find-file-noselect x)?
22461 ;; Is it to avoid the "revert buffer" prompt?
22462 (or (get-file-buffer x) (find-file-noselect x))
22463 (widen)
22464 (current-buffer)))
22465 files)
22466 regexp)))
22468 (add-hook 'occur-mode-find-occurrence-hook
22469 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22471 (defun org-occur-link-in-agenda-files ()
22472 "Create a link and search for it in the agendas.
22473 The link is not stored in `org-stored-links', it is just created
22474 for the search purpose."
22475 (interactive)
22476 (let ((link (condition-case nil
22477 (org-store-link nil)
22478 (error "Unable to create a link to here"))))
22479 (org-occur-in-agenda-files (regexp-quote link))))
22481 (defun org-reverse-string (string)
22482 "Return the reverse of STRING."
22483 (apply 'string (reverse (string-to-list string))))
22485 ;; defsubst org-uniquify must be defined before first use
22487 (defun org-uniquify-alist (alist)
22488 "Merge elements of ALIST with the same key.
22490 For example, in this alist:
22492 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22493 => \\='((a 1 3) (b 2))
22495 merge (a 1) and (a 3) into (a 1 3).
22497 The function returns the new ALIST."
22498 (let (rtn)
22499 (dolist (e alist rtn)
22500 (let (n)
22501 (if (not (assoc (car e) rtn))
22502 (push e rtn)
22503 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22504 (setq rtn (assq-delete-all (car e) rtn))
22505 (push n rtn))))))
22507 (defun org-delete-all (elts list)
22508 "Remove all elements in ELTS from LIST.
22509 Comparison is done with `equal'. It is a destructive operation
22510 that may remove elements by altering the list structure."
22511 (while elts
22512 (setq list (delete (pop elts) list)))
22513 list)
22515 (defun org-back-over-empty-lines ()
22516 "Move backwards over whitespace, to the beginning of the first empty line.
22517 Returns the number of empty lines passed."
22518 (let ((pos (point)))
22519 (if (cdr (assq 'heading org-blank-before-new-entry))
22520 (skip-chars-backward " \t\n\r")
22521 (unless (eobp)
22522 (forward-line -1)))
22523 (beginning-of-line 2)
22524 (goto-char (min (point) pos))
22525 (count-lines (point) pos)))
22527 (defun org-skip-whitespace ()
22528 (skip-chars-forward " \t\n\r"))
22530 (defun org-point-in-group (point group &optional context)
22531 "Check if POINT is in match-group GROUP.
22532 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22533 match. If the match group does not exist or point is not inside it,
22534 return nil."
22535 (and (match-beginning group)
22536 (>= point (match-beginning group))
22537 (<= point (match-end group))
22538 (if context
22539 (list context (match-beginning group) (match-end group))
22540 t)))
22542 (defun org-switch-to-buffer-other-window (&rest args)
22543 "Switch to buffer in a second window on the current frame.
22544 In particular, do not allow pop-up frames.
22545 Returns the newly created buffer."
22546 (org-no-popups
22547 (apply 'switch-to-buffer-other-window args)))
22549 (defun org-combine-plists (&rest plists)
22550 "Create a single property list from all plists in PLISTS.
22551 The process starts by copying the first list, and then setting properties
22552 from the other lists. Settings in the last list are the most significant
22553 ones and overrule settings in the other lists."
22554 (let ((rtn (copy-sequence (pop plists)))
22555 p v ls)
22556 (while plists
22557 (setq ls (pop plists))
22558 (while ls
22559 (setq p (pop ls) v (pop ls))
22560 (setq rtn (plist-put rtn p v))))
22561 rtn))
22563 (defun org-replace-escapes (string table)
22564 "Replace %-escapes in STRING with values in TABLE.
22565 TABLE is an association list with keys like \"%a\" and string values.
22566 The sequences in STRING may contain normal field width and padding information,
22567 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22568 so values can contain further %-escapes if they are define later in TABLE."
22569 (let ((tbl (copy-alist table))
22570 (case-fold-search nil)
22571 (pchg 0)
22572 re rpl)
22573 (dolist (e tbl)
22574 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22575 (when (and (cdr e) (string-match re (cdr e)))
22576 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22577 (safe "SREF"))
22578 (add-text-properties 0 3 (list 'sref sref) safe)
22579 (setcdr e (replace-match safe t t (cdr e)))))
22580 (while (string-match re string)
22581 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22582 (cdr e)))
22583 (setq string (replace-match rpl t t string))))
22584 (while (setq pchg (next-property-change pchg string))
22585 (let ((sref (get-text-property pchg 'sref string)))
22586 (when (and sref (string-match "SREF" string pchg))
22587 (setq string (replace-match sref t t string)))))
22588 string))
22590 (defun org-find-base-buffer-visiting (file)
22591 "Like `find-buffer-visiting' but always return the base buffer and
22592 not an indirect buffer."
22593 (let ((buf (or (get-file-buffer file)
22594 (find-buffer-visiting file))))
22595 (if buf
22596 (or (buffer-base-buffer buf) buf)
22597 nil)))
22599 ;;; TODO: Only called once, from ox-odt which should probably use
22600 ;;; org-export-inline-image-p or something.
22601 (defun org-file-image-p (file)
22602 "Return non-nil if FILE is an image."
22603 (save-match-data
22604 (string-match (image-file-name-regexp) file)))
22606 (defun org-get-cursor-date (&optional with-time)
22607 "Return the date at cursor in as a time.
22608 This works in the calendar and in the agenda, anywhere else it just
22609 returns the current time.
22610 If WITH-TIME is non-nil, returns the time of the event at point (in
22611 the agenda) or the current time of the day."
22612 (let (date day defd tp hod mod)
22613 (when with-time
22614 (setq tp (get-text-property (point) 'time))
22615 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22616 (setq hod (string-to-number (match-string 1 tp))
22617 mod (string-to-number (match-string 2 tp))))
22618 (or tp (let ((now (decode-time)))
22619 (setq hod (nth 2 now)
22620 mod (nth 1 now)))))
22621 (cond
22622 ((eq major-mode 'calendar-mode)
22623 (setq date (calendar-cursor-to-date)
22624 defd (encode-time 0 (or mod 0) (or hod 0)
22625 (nth 1 date) (nth 0 date) (nth 2 date))))
22626 ((eq major-mode 'org-agenda-mode)
22627 (setq day (get-text-property (point) 'day))
22628 (when day
22629 (setq date (calendar-gregorian-from-absolute day)
22630 defd (encode-time 0 (or mod 0) (or hod 0)
22631 (nth 1 date) (nth 0 date) (nth 2 date))))))
22632 (or defd (current-time))))
22634 (defun org-mark-subtree (&optional up)
22635 "Mark the current subtree.
22636 This puts point at the start of the current subtree, and mark at
22637 the end. If a numeric prefix UP is given, move up into the
22638 hierarchy of headlines by UP levels before marking the subtree."
22639 (interactive "P")
22640 (org-with-limited-levels
22641 (cond ((org-at-heading-p) (beginning-of-line))
22642 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22643 (t (outline-previous-visible-heading 1))))
22644 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22645 (if (called-interactively-p 'any)
22646 (call-interactively 'org-mark-element)
22647 (org-mark-element)))
22649 (defun org-file-newer-than-p (file time)
22650 "Non-nil if FILE is newer than TIME.
22651 FILE is a filename, as a string, TIME is a list of integers, as
22652 returned by, e.g., `current-time'."
22653 (and (file-exists-p file)
22654 ;; Only compare times up to whole seconds as some file-systems
22655 ;; (e.g. HFS+) do not retain any finer granularity. As
22656 ;; a consequence, make sure we return non-nil when the two
22657 ;; times are equal.
22658 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22659 (cl-subseq time 0 2)))))
22661 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22662 "Compile a SOURCE file using PROCESS.
22664 PROCESS is either a function or a list of shell commands, as
22665 strings. EXT is a file extension, without the leading dot, as
22666 a string. It is used to check if the process actually succeeded.
22668 PROCESS must create a file with the same base name and directory
22669 as SOURCE, but ending with EXT. The function then returns its
22670 filename. Otherwise, it raises an error. The error message can
22671 then be refined by providing string ERR-MSG, which is appended to
22672 the standard message.
22674 If PROCESS is a function, it is called with a single argument:
22675 the SOURCE file.
22677 If it is a list of commands, each of them is called using
22678 `shell-command'. By default, in each command, %b, %f, %F, %o and
22679 %O are replaced with, respectively, SOURCE base name, name, full
22680 name, directory and absolute output file name. It is possible,
22681 however, to use more place-holders by specifying them in optional
22682 argument SPEC, as an alist following the pattern
22684 (CHARACTER . REPLACEMENT-STRING).
22686 When PROCESS is a list of commands, optional argument LOG-BUF can
22687 be set to a buffer or a buffer name. `shell-command' then uses
22688 it for output."
22689 (let* ((base-name (file-name-base source))
22690 (full-name (file-truename source))
22691 (out-dir (or (file-name-directory source) "./"))
22692 (output (expand-file-name (concat base-name "." ext) out-dir))
22693 (time (current-time))
22694 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22695 (save-window-excursion
22696 (pcase process
22697 ((pred functionp) (funcall process (shell-quote-argument source)))
22698 ((pred consp)
22699 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22700 (spec (append spec
22701 `((?b . ,(shell-quote-argument base-name))
22702 (?f . ,(shell-quote-argument source))
22703 (?F . ,(shell-quote-argument full-name))
22704 (?o . ,(shell-quote-argument out-dir))
22705 (?O . ,(shell-quote-argument output))))))
22706 (dolist (command process)
22707 (shell-command (format-spec command spec) log-buf))))
22708 (_ (error "No valid command to process %S%s" source err-msg))))
22709 ;; Check for process failure. Output file is expected to be
22710 ;; located in the same directory as SOURCE.
22711 (unless (org-file-newer-than-p output time)
22712 (error (format "File %S wasn't produced%s" output err-msg)))
22713 output))
22715 ;;; Indentation
22717 (defvar org-element-greater-elements)
22718 (defun org--get-expected-indentation (element contentsp)
22719 "Expected indentation column for current line, according to ELEMENT.
22720 ELEMENT is an element containing point. CONTENTSP is non-nil
22721 when indentation is to be computed according to contents of
22722 ELEMENT."
22723 (let ((type (org-element-type element))
22724 (start (org-element-property :begin element))
22725 (post-affiliated (org-element-property :post-affiliated element)))
22726 (org-with-wide-buffer
22727 (cond
22728 (contentsp
22729 (cl-case type
22730 ((diary-sexp footnote-definition) 0)
22731 ((headline inlinetask nil)
22732 (if (not org-adapt-indentation) 0
22733 (let ((level (org-current-level)))
22734 (if level (1+ level) 0))))
22735 ((item plain-list) (org-list-item-body-column post-affiliated))
22737 (goto-char start)
22738 (org-get-indentation))))
22739 ((memq type '(headline inlinetask nil))
22740 (if (org-match-line "[ \t]*$")
22741 (org--get-expected-indentation element t)
22743 ((memq type '(diary-sexp footnote-definition)) 0)
22744 ;; First paragraph of a footnote definition or an item.
22745 ;; Indent like parent.
22746 ((< (line-beginning-position) start)
22747 (org--get-expected-indentation
22748 (org-element-property :parent element) t))
22749 ;; At first line: indent according to previous sibling, if any,
22750 ;; ignoring footnote definitions and inline tasks, or parent's
22751 ;; contents.
22752 ((= (line-beginning-position) start)
22753 (catch 'exit
22754 (while t
22755 (if (= (point-min) start) (throw 'exit 0)
22756 (goto-char (1- start))
22757 (let* ((previous (org-element-at-point))
22758 (parent previous))
22759 (while (and parent (<= (org-element-property :end parent) start))
22760 (setq previous parent
22761 parent (org-element-property :parent parent)))
22762 (cond
22763 ((not previous) (throw 'exit 0))
22764 ((> (org-element-property :end previous) start)
22765 (throw 'exit (org--get-expected-indentation previous t)))
22766 ((memq (org-element-type previous)
22767 '(footnote-definition inlinetask))
22768 (setq start (org-element-property :begin previous)))
22769 (t (goto-char (org-element-property :begin previous))
22770 (throw 'exit
22771 (if (bolp) (org-get-indentation)
22772 ;; At first paragraph in an item or
22773 ;; a footnote definition.
22774 (org--get-expected-indentation
22775 (org-element-property :parent previous) t))))))))))
22776 ;; Otherwise, move to the first non-blank line above.
22778 (beginning-of-line)
22779 (let ((pos (point)))
22780 (skip-chars-backward " \r\t\n")
22781 (cond
22782 ;; Two blank lines end a footnote definition or a plain
22783 ;; list. When we indent an empty line after them, the
22784 ;; containing list or footnote definition is over, so it
22785 ;; qualifies as a previous sibling. Therefore, we indent
22786 ;; like its first line.
22787 ((and (memq type '(footnote-definition plain-list))
22788 (> (count-lines (point) pos) 2))
22789 (goto-char start)
22790 (org-get-indentation))
22791 ;; Line above is the first one of a paragraph at the
22792 ;; beginning of an item or a footnote definition. Indent
22793 ;; like parent.
22794 ((< (line-beginning-position) start)
22795 (org--get-expected-indentation
22796 (org-element-property :parent element) t))
22797 ;; Line above is the beginning of an element, i.e., point
22798 ;; was originally on the blank lines between element's start
22799 ;; and contents.
22800 ((= (line-beginning-position) post-affiliated)
22801 (org--get-expected-indentation element t))
22802 ;; POS is after contents in a greater element. Indent like
22803 ;; the beginning of the element.
22804 ((and (memq type org-element-greater-elements)
22805 (let ((cend (org-element-property :contents-end element)))
22806 (and cend (<= cend pos))))
22807 ;; As a special case, if point is at the end of a footnote
22808 ;; definition or an item, indent like the very last element
22809 ;; within. If that last element is an item, indent like
22810 ;; its contents.
22811 (if (memq type '(footnote-definition item plain-list))
22812 (let ((last (org-element-at-point)))
22813 (goto-char pos)
22814 (org--get-expected-indentation
22815 last (eq (org-element-type last) 'item)))
22816 (goto-char start)
22817 (org-get-indentation)))
22818 ;; In any other case, indent like the current line.
22819 (t (org-get-indentation)))))))))
22821 (defun org--align-node-property ()
22822 "Align node property at point.
22823 Alignment is done according to `org-property-format', which see."
22824 (when (save-excursion
22825 (beginning-of-line)
22826 (looking-at org-property-re))
22827 (replace-match
22828 (concat (match-string 4)
22829 (org-trim
22830 (format org-property-format (match-string 1) (match-string 3))))
22831 t t)))
22833 (defun org-indent-line ()
22834 "Indent line depending on context.
22836 Indentation is done according to the following rules:
22838 - Footnote definitions, diary sexps, headlines and inline tasks
22839 have to start at column 0.
22841 - On the very first line of an element, consider, in order, the
22842 next rules until one matches:
22844 1. If there's a sibling element before, ignoring footnote
22845 definitions and inline tasks, indent like its first line.
22847 2. If element has a parent, indent like its contents. More
22848 precisely, if parent is an item, indent after the
22849 description part, if any, or the bullet (see
22850 `org-list-description-max-indent'). Else, indent like
22851 parent's first line.
22853 3. Otherwise, indent relatively to current level, if
22854 `org-adapt-indentation' is non-nil, or to left margin.
22856 - On a blank line at the end of an element, indent according to
22857 the type of the element. More precisely
22859 1. If element is a plain list, an item, or a footnote
22860 definition, indent like the very last element within.
22862 2. If element is a paragraph, indent like its last non blank
22863 line.
22865 3. Otherwise, indent like its very first line.
22867 - In the code part of a source block, use language major mode
22868 to indent current line if `org-src-tab-acts-natively' is
22869 non-nil. If it is nil, do nothing.
22871 - Otherwise, indent like the first non-blank line above.
22873 The function doesn't indent an item as it could break the whole
22874 list structure. Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
22875 `\\[org-shiftmetaright]'.
22877 Also align node properties according to `org-property-format'."
22878 (interactive)
22879 (cond
22880 (orgstruct-is-++
22881 (let ((indent-line-function
22882 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22883 (indent-according-to-mode)))
22884 ((org-at-heading-p) 'noindent)
22886 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22887 (type (org-element-type element)))
22888 (cond ((and (memq type '(plain-list item))
22889 (= (line-beginning-position)
22890 (org-element-property :post-affiliated element)))
22891 'noindent)
22892 ((and (eq type 'latex-environment)
22893 (>= (point) (org-element-property :post-affiliated element))
22894 (< (point) (org-with-wide-buffer
22895 (goto-char (org-element-property :end element))
22896 (skip-chars-backward " \r\t\n")
22897 (line-beginning-position 2))))
22898 'noindent)
22899 ((and (eq type 'src-block)
22900 org-src-tab-acts-natively
22901 (> (line-beginning-position)
22902 (org-element-property :post-affiliated element))
22903 (< (line-beginning-position)
22904 (org-with-wide-buffer
22905 (goto-char (org-element-property :end element))
22906 (skip-chars-backward " \r\t\n")
22907 (line-beginning-position))))
22908 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22910 (let ((column (org--get-expected-indentation element nil)))
22911 ;; Preserve current column.
22912 (if (<= (current-column) (current-indentation))
22913 (indent-line-to column)
22914 (save-excursion (indent-line-to column))))
22915 ;; Align node property. Also preserve current column.
22916 (when (eq type 'node-property)
22917 (let ((column (current-column)))
22918 (org--align-node-property)
22919 (org-move-to-column column)))))))))
22921 (defun org-indent-region (start end)
22922 "Indent each non-blank line in the region.
22923 Called from a program, START and END specify the region to
22924 indent. The function will not indent contents of example blocks,
22925 verse blocks and export blocks as leading white spaces are
22926 assumed to be significant there."
22927 (interactive "r")
22928 (save-excursion
22929 (goto-char start)
22930 (skip-chars-forward " \r\t\n")
22931 (unless (eobp) (beginning-of-line))
22932 (let ((indent-to
22933 (lambda (ind pos)
22934 ;; Set IND as indentation for all lines between point and
22935 ;; POS. Blank lines are ignored. Leave point after POS
22936 ;; once done.
22937 (let ((limit (copy-marker pos)))
22938 (while (< (point) limit)
22939 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
22940 (forward-line))
22941 (set-marker limit nil))))
22942 (end (copy-marker end)))
22943 (while (< (point) end)
22944 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
22945 (let* ((element (org-element-at-point))
22946 (type (org-element-type element))
22947 (element-end (copy-marker (org-element-property :end element)))
22948 (ind (org--get-expected-indentation element nil)))
22949 (cond
22950 ;; Element indented as a single block. Example blocks
22951 ;; preserving indentation are a special case since the
22952 ;; "contents" must not be indented whereas the block
22953 ;; boundaries can.
22954 ((or (memq type '(export-block latex-environment))
22955 (and (eq type 'example-block)
22956 (not
22957 (or org-src-preserve-indentation
22958 (org-element-property :preserve-indent element)))))
22959 (let ((offset (- ind (org-get-indentation))))
22960 (unless (zerop offset)
22961 (indent-rigidly (org-element-property :begin element)
22962 (org-element-property :end element)
22963 offset)))
22964 (goto-char element-end))
22965 ;; Elements indented line wise. Be sure to exclude
22966 ;; example blocks (preserving indentation) and source
22967 ;; blocks from this category as they are treated
22968 ;; specially later.
22969 ((or (memq type '(paragraph table table-row))
22970 (not (or (org-element-property :contents-begin element)
22971 (memq type '(example-block src-block)))))
22972 (when (eq type 'node-property)
22973 (org--align-node-property)
22974 (beginning-of-line))
22975 (funcall indent-to ind (min element-end end)))
22976 ;; Elements consisting of three parts: before the
22977 ;; contents, the contents, and after the contents. The
22978 ;; contents are treated specially, according to the
22979 ;; element type, or not indented at all. Other parts are
22980 ;; indented as a single block.
22982 (let* ((post (copy-marker
22983 (org-element-property :post-affiliated element)))
22984 (cbeg
22985 (copy-marker
22986 (cond
22987 ((not (org-element-property :contents-begin element))
22988 ;; Fake contents for source blocks.
22989 (org-with-wide-buffer
22990 (goto-char post)
22991 (line-beginning-position 2)))
22992 ((memq type '(footnote-definition item plain-list))
22993 ;; Contents in these elements could start on
22994 ;; the same line as the beginning of the
22995 ;; element. Make sure we start indenting
22996 ;; from the second line.
22997 (org-with-wide-buffer
22998 (goto-char post)
22999 (end-of-line)
23000 (skip-chars-forward " \r\t\n")
23001 (if (eobp) (point) (line-beginning-position))))
23002 (t (org-element-property :contents-begin element)))))
23003 (cend (copy-marker
23004 (or (org-element-property :contents-end element)
23005 ;; Fake contents for source blocks.
23006 (org-with-wide-buffer
23007 (goto-char element-end)
23008 (skip-chars-backward " \r\t\n")
23009 (line-beginning-position)))
23010 t)))
23011 ;; Do not change items indentation individually as it
23012 ;; might break the list as a whole. On the other
23013 ;; hand, when at a plain list, indent it as a whole.
23014 (cond ((eq type 'plain-list)
23015 (let ((offset (- ind (org-get-indentation))))
23016 (unless (zerop offset)
23017 (indent-rigidly (org-element-property :begin element)
23018 (org-element-property :end element)
23019 offset))
23020 (goto-char cbeg)))
23021 ((eq type 'item) (goto-char cbeg))
23022 (t (funcall indent-to ind (min cbeg end))))
23023 (when (< (point) end)
23024 (cl-case type
23025 ((example-block verse-block))
23026 (src-block
23027 ;; In a source block, indent source code
23028 ;; according to language major mode, but only if
23029 ;; `org-src-tab-acts-natively' is non-nil.
23030 (when (and (< (point) end) org-src-tab-acts-natively)
23031 (ignore-errors
23032 (org-babel-do-in-edit-buffer
23033 (indent-region (point-min) (point-max))))))
23034 (t (org-indent-region (point) (min cend end))))
23035 (goto-char (min cend end))
23036 (when (< (point) end)
23037 (funcall indent-to ind (min element-end end))))
23038 (set-marker post nil)
23039 (set-marker cbeg nil)
23040 (set-marker cend nil))))
23041 (set-marker element-end nil))))
23042 (set-marker end nil))))
23044 (defun org-indent-drawer ()
23045 "Indent the drawer at point."
23046 (interactive)
23047 (unless (save-excursion
23048 (beginning-of-line)
23049 (looking-at-p org-drawer-regexp))
23050 (user-error "Not at a drawer"))
23051 (let ((element (org-element-at-point)))
23052 (unless (memq (org-element-type element) '(drawer property-drawer))
23053 (user-error "Not at a drawer"))
23054 (org-with-wide-buffer
23055 (org-indent-region (org-element-property :begin element)
23056 (org-element-property :end element))))
23057 (message "Drawer at point indented"))
23059 (defun org-indent-block ()
23060 "Indent the block at point."
23061 (interactive)
23062 (unless (save-excursion
23063 (beginning-of-line)
23064 (let ((case-fold-search t))
23065 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23066 (user-error "Not at a block"))
23067 (let ((element (org-element-at-point)))
23068 (unless (memq (org-element-type element)
23069 '(comment-block center-block dynamic-block example-block
23070 export-block quote-block special-block
23071 src-block verse-block))
23072 (user-error "Not at a block"))
23073 (org-with-wide-buffer
23074 (org-indent-region (org-element-property :begin element)
23075 (org-element-property :end element))))
23076 (message "Block at point indented"))
23079 ;;; Filling
23081 ;; We use our own fill-paragraph and auto-fill functions.
23083 ;; `org-fill-paragraph' relies on adaptive filling and context
23084 ;; checking. Appropriate `fill-prefix' is computed with
23085 ;; `org-adaptive-fill-function'.
23087 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23088 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23089 ;; `org-adaptive-fill-function' value. Internally,
23090 ;; `org-comment-line-break-function' breaks the line.
23092 ;; `org-setup-filling' installs filling and auto-filling related
23093 ;; variables during `org-mode' initialization.
23095 (defvar org-element-paragraph-separate) ; org-element.el
23096 (defun org-setup-filling ()
23097 (require 'org-element)
23098 ;; Prevent auto-fill from inserting unwanted new items.
23099 (when (boundp 'fill-nobreak-predicate)
23100 (setq-local
23101 fill-nobreak-predicate
23102 (org-uniquify
23103 (append fill-nobreak-predicate
23104 '(org-fill-line-break-nobreak-p
23105 org-fill-paragraph-with-timestamp-nobreak-p)))))
23106 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23107 (setq-local paragraph-start paragraph-ending)
23108 (setq-local paragraph-separate paragraph-ending))
23109 (setq-local fill-paragraph-function 'org-fill-paragraph)
23110 (setq-local auto-fill-inhibit-regexp nil)
23111 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23112 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23113 (setq-local comment-line-break-function 'org-comment-line-break-function))
23115 (defun org-fill-line-break-nobreak-p ()
23116 "Non-nil when a new line at point would create an Org line break."
23117 (save-excursion
23118 (skip-chars-backward "[ \t]")
23119 (skip-chars-backward "\\\\")
23120 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23122 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23123 "Non-nil when a new line at point would split a timestamp."
23124 (and (org-at-timestamp-p t)
23125 (not (looking-at org-ts-regexp-both))))
23127 (declare-function message-in-body-p "message" ())
23128 (defvar orgtbl-line-start-regexp) ; From org-table.el
23129 (defun org-adaptive-fill-function ()
23130 "Compute a fill prefix for the current line.
23131 Return fill prefix, as a string, or nil if current line isn't
23132 meant to be filled. For convenience, if `adaptive-fill-regexp'
23133 matches in paragraphs or comments, use it."
23134 (catch 'exit
23135 (when (derived-mode-p 'message-mode)
23136 (save-excursion
23137 (beginning-of-line)
23138 (cond ((not (message-in-body-p)) (throw 'exit nil))
23139 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23140 ((looking-at message-cite-prefix-regexp)
23141 (throw 'exit (match-string-no-properties 0)))
23142 ((looking-at org-outline-regexp)
23143 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23144 (org-with-wide-buffer
23145 (unless (org-at-heading-p)
23146 (let* ((p (line-beginning-position))
23147 (element (save-excursion
23148 (beginning-of-line)
23149 (org-element-at-point)))
23150 (type (org-element-type element))
23151 (post-affiliated (org-element-property :post-affiliated element)))
23152 (unless (< p post-affiliated)
23153 (cl-case type
23154 (comment
23155 (save-excursion
23156 (beginning-of-line)
23157 (looking-at "[ \t]*")
23158 (concat (match-string 0) "# ")))
23159 (footnote-definition "")
23160 ((item plain-list)
23161 (make-string (org-list-item-body-column post-affiliated) ?\s))
23162 (paragraph
23163 ;; Fill prefix is usually the same as the current line,
23164 ;; unless the paragraph is at the beginning of an item.
23165 (let ((parent (org-element-property :parent element)))
23166 (save-excursion
23167 (beginning-of-line)
23168 (cond ((eq (org-element-type parent) 'item)
23169 (make-string (org-list-item-body-column
23170 (org-element-property :begin parent))
23171 ?\s))
23172 ((and adaptive-fill-regexp
23173 ;; Locally disable
23174 ;; `adaptive-fill-function' to let
23175 ;; `fill-context-prefix' handle
23176 ;; `adaptive-fill-regexp' variable.
23177 (let (adaptive-fill-function)
23178 (fill-context-prefix
23179 post-affiliated
23180 (org-element-property :end element)))))
23181 ((looking-at "[ \t]+") (match-string 0))
23182 (t "")))))
23183 (comment-block
23184 ;; Only fill contents if P is within block boundaries.
23185 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23186 (forward-line)
23187 (point)))
23188 (cend (save-excursion
23189 (goto-char (org-element-property :end element))
23190 (skip-chars-backward " \r\t\n")
23191 (line-beginning-position))))
23192 (when (and (>= p cbeg) (< p cend))
23193 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23194 (match-string 0)
23195 "")))))))))))
23197 (declare-function message-goto-body "message" ())
23198 (defvar message-cite-prefix-regexp) ; From message.el
23199 (defun org-fill-paragraph (&optional justify)
23200 "Fill element at point, when applicable.
23202 This function only applies to comment blocks, comments, example
23203 blocks and paragraphs. Also, as a special case, re-align table
23204 when point is at one.
23206 If JUSTIFY is non-nil (interactively, with prefix argument),
23207 justify as well. If `sentence-end-double-space' is non-nil, then
23208 period followed by one space does not end a sentence, so don't
23209 break a line there. The variable `fill-column' controls the
23210 width for filling.
23212 For convenience, when point is at a plain list, an item or
23213 a footnote definition, try to fill the first paragraph within."
23214 (interactive)
23215 (if (and (derived-mode-p 'message-mode)
23216 (or (not (message-in-body-p))
23217 (save-excursion (move-beginning-of-line 1)
23218 (looking-at message-cite-prefix-regexp))))
23219 ;; First ensure filling is correct in message-mode.
23220 (let ((fill-paragraph-function
23221 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23222 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23223 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23224 (paragraph-separate
23225 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23226 (fill-paragraph nil))
23227 (with-syntax-table org-mode-transpose-word-syntax-table
23228 ;; Move to end of line in order to get the first paragraph
23229 ;; within a plain list or a footnote definition.
23230 (let ((element (save-excursion
23231 (end-of-line)
23232 (or (ignore-errors (org-element-at-point))
23233 (user-error "An element cannot be parsed line %d"
23234 (line-number-at-pos (point)))))))
23235 ;; First check if point is in a blank line at the beginning of
23236 ;; the buffer. In that case, ignore filling.
23237 (cl-case (org-element-type element)
23238 ;; Use major mode filling function is src blocks.
23239 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23240 ;; Align Org tables, leave table.el tables as-is.
23241 (table-row (org-table-align) t)
23242 (table
23243 (when (eq (org-element-property :type element) 'org)
23244 (save-excursion
23245 (goto-char (org-element-property :post-affiliated element))
23246 (org-table-align)))
23248 (paragraph
23249 ;; Paragraphs may contain `line-break' type objects.
23250 (let ((beg (max (point-min)
23251 (org-element-property :contents-begin element)))
23252 (end (min (point-max)
23253 (org-element-property :contents-end element))))
23254 ;; Do nothing if point is at an affiliated keyword.
23255 (if (< (line-end-position) beg) t
23256 (when (derived-mode-p 'message-mode)
23257 ;; In `message-mode', do not fill following citation
23258 ;; in current paragraph nor text before message body.
23259 (let ((body-start (save-excursion (message-goto-body))))
23260 (when body-start (setq beg (max body-start beg))))
23261 (when (save-excursion
23262 (re-search-forward
23263 (concat "^" message-cite-prefix-regexp) end t))
23264 (setq end (match-beginning 0))))
23265 ;; Fill paragraph, taking line breaks into account.
23266 (save-excursion
23267 (goto-char beg)
23268 (let ((cuts (list beg)))
23269 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23270 (when (eq 'line-break
23271 (org-element-type
23272 (save-excursion (backward-char)
23273 (org-element-context))))
23274 (push (point) cuts)))
23275 (dolist (c (delq end cuts))
23276 (fill-region-as-paragraph c end justify)
23277 (setq end c))))
23278 t)))
23279 ;; Contents of `comment-block' type elements should be
23280 ;; filled as plain text, but only if point is within block
23281 ;; markers.
23282 (comment-block
23283 (let* ((case-fold-search t)
23284 (beg (save-excursion
23285 (goto-char (org-element-property :begin element))
23286 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23287 (forward-line)
23288 (point)))
23289 (end (save-excursion
23290 (goto-char (org-element-property :end element))
23291 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23292 (line-beginning-position))))
23293 (if (or (< (point) beg) (> (point) end)) t
23294 (fill-region-as-paragraph
23295 (save-excursion (end-of-line)
23296 (re-search-backward "^[ \t]*$" beg 'move)
23297 (line-beginning-position))
23298 (save-excursion (beginning-of-line)
23299 (re-search-forward "^[ \t]*$" end 'move)
23300 (line-beginning-position))
23301 justify))))
23302 ;; Fill comments.
23303 (comment
23304 (let ((begin (org-element-property :post-affiliated element))
23305 (end (org-element-property :end element)))
23306 (when (and (>= (point) begin) (<= (point) end))
23307 (let ((begin (save-excursion
23308 (end-of-line)
23309 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23310 (progn (forward-line) (point))
23311 begin)))
23312 (end (save-excursion
23313 (end-of-line)
23314 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23315 (1- (line-beginning-position))
23316 (skip-chars-backward " \r\t\n")
23317 (line-end-position)))))
23318 ;; Do not fill comments when at a blank line.
23319 (when (> end begin)
23320 (let ((fill-prefix
23321 (save-excursion
23322 (beginning-of-line)
23323 (looking-at "[ \t]*#")
23324 (let ((comment-prefix (match-string 0)))
23325 (goto-char (match-end 0))
23326 (if (looking-at adaptive-fill-regexp)
23327 (concat comment-prefix (match-string 0))
23328 (concat comment-prefix " "))))))
23329 (save-excursion
23330 (fill-region-as-paragraph begin end justify))))))
23332 ;; Ignore every other element.
23333 (otherwise t))))))
23335 (defun org-auto-fill-function ()
23336 "Auto-fill function."
23337 ;; Check if auto-filling is meaningful.
23338 (let ((fc (current-fill-column)))
23339 (when (and fc (> (current-column) fc))
23340 (let* ((fill-prefix (org-adaptive-fill-function))
23341 ;; Enforce empty fill prefix, if required. Otherwise, it
23342 ;; will be computed again.
23343 (adaptive-fill-mode (not (equal fill-prefix ""))))
23344 (when fill-prefix (do-auto-fill))))))
23346 (defun org-comment-line-break-function (&optional soft)
23347 "Break line at point and indent, continuing comment if within one.
23348 The inserted newline is marked hard if variable
23349 `use-hard-newlines' is true, unless optional argument SOFT is
23350 non-nil."
23351 (if soft (insert-and-inherit ?\n) (newline 1))
23352 (save-excursion (forward-char -1) (delete-horizontal-space))
23353 (delete-horizontal-space)
23354 (indent-to-left-margin)
23355 (insert-before-markers-and-inherit fill-prefix))
23358 ;;; Fixed Width Areas
23360 (defun org-toggle-fixed-width ()
23361 "Toggle fixed-width markup.
23363 Add or remove fixed-width markup on current line, whenever it
23364 makes sense. Return an error otherwise.
23366 If a region is active and if it contains only fixed-width areas
23367 or blank lines, remove all fixed-width markup in it. If the
23368 region contains anything else, convert all non-fixed-width lines
23369 to fixed-width ones.
23371 Blank lines at the end of the region are ignored unless the
23372 region only contains such lines."
23373 (interactive)
23374 (if (not (org-region-active-p))
23375 ;; No region:
23377 ;; Remove fixed width marker only in a fixed-with element.
23379 ;; Add fixed width maker in paragraphs, in blank lines after
23380 ;; elements or at the beginning of a headline or an inlinetask,
23381 ;; and before any one-line elements (e.g., a clock).
23382 (progn
23383 (beginning-of-line)
23384 (let* ((element (org-element-at-point))
23385 (type (org-element-type element)))
23386 (cond
23387 ((and (eq type 'fixed-width)
23388 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23389 (replace-match
23390 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23391 ((and (memq type '(babel-call clock comment diary-sexp headline
23392 horizontal-rule keyword paragraph
23393 planning))
23394 (<= (org-element-property :post-affiliated element) (point)))
23395 (skip-chars-forward " \t")
23396 (insert ": "))
23397 ((and (looking-at-p "[ \t]*$")
23398 (or (eq type 'inlinetask)
23399 (save-excursion
23400 (skip-chars-forward " \r\t\n")
23401 (<= (org-element-property :end element) (point)))))
23402 (delete-region (point) (line-end-position))
23403 (org-indent-line)
23404 (insert ": "))
23405 (t (user-error "Cannot insert a fixed-width line here")))))
23406 ;; Region active.
23407 (let* ((begin (save-excursion
23408 (goto-char (region-beginning))
23409 (line-beginning-position)))
23410 (end (copy-marker
23411 (save-excursion
23412 (goto-char (region-end))
23413 (unless (eolp) (beginning-of-line))
23414 (if (save-excursion (re-search-backward "\\S-" begin t))
23415 (progn (skip-chars-backward " \r\t\n") (point))
23416 (point)))))
23417 (all-fixed-width-p
23418 (catch 'not-all-p
23419 (save-excursion
23420 (goto-char begin)
23421 (skip-chars-forward " \r\t\n")
23422 (when (eobp) (throw 'not-all-p nil))
23423 (while (< (point) end)
23424 (let ((element (org-element-at-point)))
23425 (if (eq (org-element-type element) 'fixed-width)
23426 (goto-char (org-element-property :end element))
23427 (throw 'not-all-p nil))))
23428 t))))
23429 (if all-fixed-width-p
23430 (save-excursion
23431 (goto-char begin)
23432 (while (< (point) end)
23433 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23434 (replace-match
23435 "" nil nil nil
23436 (if (= (line-end-position) (match-end 0)) 0 1)))
23437 (forward-line)))
23438 (let ((min-ind (point-max)))
23439 ;; Find minimum indentation across all lines.
23440 (save-excursion
23441 (goto-char begin)
23442 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23443 (setq min-ind 0)
23444 (catch 'zerop
23445 (while (< (point) end)
23446 (unless (looking-at-p "[ \t]*$")
23447 (let ((ind (org-get-indentation)))
23448 (setq min-ind (min min-ind ind))
23449 (when (zerop ind) (throw 'zerop t))))
23450 (forward-line)))))
23451 ;; Loop over all lines and add fixed-width markup everywhere
23452 ;; but in fixed-width lines.
23453 (save-excursion
23454 (goto-char begin)
23455 (while (< (point) end)
23456 (cond
23457 ((org-at-heading-p)
23458 (insert ": ")
23459 (forward-line)
23460 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23461 (insert ":")
23462 (forward-line)))
23463 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23464 (let* ((element (org-element-at-point))
23465 (element-end (org-element-property :end element)))
23466 (if (eq (org-element-type element) 'fixed-width)
23467 (progn (goto-char element-end)
23468 (skip-chars-backward " \r\t\n")
23469 (forward-line))
23470 (let ((limit (min end element-end)))
23471 (while (< (point) limit)
23472 (org-move-to-column min-ind t)
23473 (insert ": ")
23474 (forward-line))))))
23476 (org-move-to-column min-ind t)
23477 (insert ": ")
23478 (forward-line)))))))
23479 (set-marker end nil))))
23482 ;;; Comments
23484 ;; Org comments syntax is quite complex. It requires the entire line
23485 ;; to be just a comment. Also, even with the right syntax at the
23486 ;; beginning of line, some some elements (i.e. verse-block or
23487 ;; example-block) don't accept comments. Usual Emacs comment commands
23488 ;; cannot cope with those requirements. Therefore, Org replaces them.
23490 ;; Org still relies on `comment-dwim', but cannot trust
23491 ;; `comment-only-p'. So, `comment-region-function' and
23492 ;; `uncomment-region-function' both point
23493 ;; to`org-comment-or-uncomment-region'. Eventually,
23494 ;; `org-insert-comment' takes care of insertion of comments at the
23495 ;; beginning of line.
23497 ;; `org-setup-comments-handling' install comments related variables
23498 ;; during `org-mode' initialization.
23500 (defun org-setup-comments-handling ()
23501 (interactive)
23502 (setq-local comment-use-syntax nil)
23503 (setq-local comment-start "# ")
23504 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23505 (setq-local comment-insert-comment-function 'org-insert-comment)
23506 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23507 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23509 (defun org-insert-comment ()
23510 "Insert an empty comment above current line.
23511 If the line is empty, insert comment at its beginning. When
23512 point is within a source block, comment according to the related
23513 major mode."
23514 (if (let ((element (org-element-at-point)))
23515 (and (eq (org-element-type element) 'src-block)
23516 (< (save-excursion
23517 (goto-char (org-element-property :post-affiliated element))
23518 (line-end-position))
23519 (point))
23520 (> (save-excursion
23521 (goto-char (org-element-property :end element))
23522 (skip-chars-backward " \r\t\n")
23523 (line-beginning-position))
23524 (point))))
23525 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23526 (beginning-of-line)
23527 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23528 (open-line 1))
23529 (org-indent-line)
23530 (insert "# ")))
23532 (defvar comment-empty-lines) ; From newcomment.el.
23533 (defun org-comment-or-uncomment-region (beg end &rest _)
23534 "Comment or uncomment each non-blank line in the region.
23535 Uncomment each non-blank line between BEG and END if it only
23536 contains commented lines. Otherwise, comment them. If region is
23537 strictly within a source block, use appropriate comment syntax."
23538 (if (let ((element (org-element-at-point)))
23539 (and (eq (org-element-type element) 'src-block)
23540 (< (save-excursion
23541 (goto-char (org-element-property :post-affiliated element))
23542 (line-end-position))
23543 beg)
23544 (>= (save-excursion
23545 (goto-char (org-element-property :end element))
23546 (skip-chars-backward " \r\t\n")
23547 (line-beginning-position))
23548 end)))
23549 ;; Translate region boundaries for the Org buffer to the source
23550 ;; buffer.
23551 (let ((offset (- end beg)))
23552 (save-excursion
23553 (goto-char beg)
23554 (org-babel-do-in-edit-buffer
23555 (comment-or-uncomment-region (point) (+ offset (point))))))
23556 (save-restriction
23557 ;; Restrict region
23558 (narrow-to-region (save-excursion (goto-char beg)
23559 (skip-chars-forward " \r\t\n" end)
23560 (line-beginning-position))
23561 (save-excursion (goto-char end)
23562 (skip-chars-backward " \r\t\n" beg)
23563 (line-end-position)))
23564 (let ((uncommentp
23565 ;; UNCOMMENTP is non-nil when every non blank line between
23566 ;; BEG and END is a comment.
23567 (save-excursion
23568 (goto-char (point-min))
23569 (while (and (not (eobp))
23570 (let ((element (org-element-at-point)))
23571 (and (eq (org-element-type element) 'comment)
23572 (goto-char (min (point-max)
23573 (org-element-property
23574 :end element)))))))
23575 (eobp))))
23576 (if uncommentp
23577 ;; Only blank lines and comments in region: uncomment it.
23578 (save-excursion
23579 (goto-char (point-min))
23580 (while (not (eobp))
23581 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23582 (replace-match "" nil nil nil 1))
23583 (forward-line)))
23584 ;; Comment each line in region.
23585 (let ((min-indent (point-max)))
23586 ;; First find the minimum indentation across all lines.
23587 (save-excursion
23588 (goto-char (point-min))
23589 (while (and (not (eobp)) (not (zerop min-indent)))
23590 (unless (looking-at "[ \t]*$")
23591 (setq min-indent (min min-indent (current-indentation))))
23592 (forward-line)))
23593 ;; Then loop over all lines.
23594 (save-excursion
23595 (goto-char (point-min))
23596 (while (not (eobp))
23597 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23598 ;; Don't get fooled by invisible text (e.g. link path)
23599 ;; when moving to column MIN-INDENT.
23600 (let ((buffer-invisibility-spec nil))
23601 (org-move-to-column min-indent t))
23602 (insert comment-start))
23603 (forward-line)))))))))
23605 (defun org-comment-dwim (_arg)
23606 "Call `comment-dwim' within a source edit buffer if needed."
23607 (interactive "*P")
23608 (if (org-in-src-block-p)
23609 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23610 (call-interactively 'comment-dwim)))
23613 ;;; Timestamps API
23615 ;; This section contains tools to operate on timestamp objects, as
23616 ;; returned by, e.g. `org-element-context'.
23618 (defun org-timestamp--to-internal-time (timestamp &optional end)
23619 "Encode TIMESTAMP object into Emacs internal time.
23620 Use end of date range or time range when END is non-nil."
23621 (apply #'encode-time
23622 (cons 0
23623 (mapcar
23624 (lambda (prop) (or (org-element-property prop timestamp) 0))
23625 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23626 '(:minute-start :hour-start :day-start :month-start
23627 :year-start))))))
23629 (defun org-timestamp-has-time-p (timestamp)
23630 "Non-nil when TIMESTAMP has a time specified."
23631 (org-element-property :hour-start timestamp))
23633 (defun org-timestamp-format (timestamp format &optional end utc)
23634 "Format a TIMESTAMP object into a string.
23636 FORMAT is a format specifier to be passed to
23637 `format-time-string'.
23639 When optional argument END is non-nil, use end of date-range or
23640 time-range, if possible.
23642 When optional argument UTC is non-nil, time will be expressed as
23643 Universal Time."
23644 (format-time-string
23645 format (org-timestamp--to-internal-time timestamp end)
23646 (and utc t)))
23648 (defun org-timestamp-split-range (timestamp &optional end)
23649 "Extract a TIMESTAMP object from a date or time range.
23651 END, when non-nil, means extract the end of the range.
23652 Otherwise, extract its start.
23654 Return a new timestamp object."
23655 (let ((type (org-element-property :type timestamp)))
23656 (if (memq type '(active inactive diary)) timestamp
23657 (let ((split-ts (org-element-copy timestamp)))
23658 ;; Set new type.
23659 (org-element-put-property
23660 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23661 ;; Copy start properties over end properties if END is
23662 ;; non-nil. Otherwise, copy end properties over `start' ones.
23663 (let ((p-alist '((:minute-start . :minute-end)
23664 (:hour-start . :hour-end)
23665 (:day-start . :day-end)
23666 (:month-start . :month-end)
23667 (:year-start . :year-end))))
23668 (dolist (p-cell p-alist)
23669 (org-element-put-property
23670 split-ts
23671 (funcall (if end #'car #'cdr) p-cell)
23672 (org-element-property
23673 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23674 ;; Eventually refresh `:raw-value'.
23675 (org-element-put-property split-ts :raw-value nil)
23676 (org-element-put-property
23677 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23679 (defun org-timestamp-translate (timestamp &optional boundary)
23680 "Translate TIMESTAMP object to custom format.
23682 Format string is defined in `org-time-stamp-custom-formats',
23683 which see.
23685 When optional argument BOUNDARY is non-nil, it is either the
23686 symbol `start' or `end'. In this case, only translate the
23687 starting or ending part of TIMESTAMP if it is a date or time
23688 range. Otherwise, translate both parts.
23690 Return timestamp as-is if `org-display-custom-times' is nil or if
23691 it has a `diary' type."
23692 (let ((type (org-element-property :type timestamp)))
23693 (if (or (not org-display-custom-times) (eq type 'diary))
23694 (org-element-interpret-data timestamp)
23695 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23696 org-time-stamp-custom-formats)))
23697 (if (and (not boundary) (memq type '(active-range inactive-range)))
23698 (concat (org-timestamp-format timestamp fmt)
23699 "--"
23700 (org-timestamp-format timestamp fmt t))
23701 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23705 ;;; Other stuff.
23707 (defvar reftex-docstruct-symbol)
23708 (defvar org--rds)
23710 (defun org-reftex-citation ()
23711 "Use reftex-citation to insert a citation into the buffer.
23712 This looks for a line like
23714 #+BIBLIOGRAPHY: foo plain option:-d
23716 and derives from it that foo.bib is the bibliography file relevant
23717 for this document. It then installs the necessary environment for RefTeX
23718 to work in this buffer and calls `reftex-citation' to insert a citation
23719 into the buffer.
23721 Export of such citations to both LaTeX and HTML is handled by the contributed
23722 package ox-bibtex by Taru Karttunen."
23723 (interactive)
23724 (let ((reftex-docstruct-symbol 'org--rds)
23725 org--rds bib)
23726 (org-with-wide-buffer
23727 (let ((case-fold-search t)
23728 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23729 (if (not (save-excursion
23730 (or (re-search-forward re nil t)
23731 (re-search-backward re nil t))))
23732 (user-error "No bibliography defined in file")
23733 (setq bib (concat (match-string 1) ".bib")
23734 org--rds (list (list 'bib bib))))))
23735 (call-interactively 'reftex-citation)))
23737 ;;;; Functions extending outline functionality
23739 (defun org-beginning-of-line (&optional n)
23740 "Go to the beginning of the current visible line.
23742 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23743 tags on the first attempt, and only move to after the tags when
23744 the cursor is already beyond the end of the headline.
23746 With argument N not nil or 1, move forward N - 1 lines first."
23747 (interactive "^p")
23748 (let ((origin (point))
23749 (special (pcase org-special-ctrl-a/e
23750 (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
23751 deactivate-mark)
23752 ;; First move to a visible line.
23753 (if (bound-and-true-p visual-line-mode)
23754 (beginning-of-visual-line n)
23755 (move-beginning-of-line n)
23756 ;; `move-beginning-of-line' may leave point after invisible
23757 ;; characters if line starts with such of these (e.g., with
23758 ;; a link at column 0). Really move to the beginning of the
23759 ;; current visible line.
23760 (beginning-of-line))
23761 (cond
23762 ;; No special behavior. Point is already at the beginning of
23763 ;; a line, logical or visual.
23764 ((not special))
23765 ;; `beginning-of-visual-line' left point before logical beginning
23766 ;; of line: point is at the beginning of a visual line. Bail
23767 ;; out.
23768 ((and (bound-and-true-p visual-line-mode) (not (bolp))))
23769 ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
23770 ;; At a headline, special position is before the title, but
23771 ;; after any TODO keyword or priority cookie.
23772 (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23773 (line-end-position)))
23774 (bol (point)))
23775 (if (eq special 'reversed)
23776 (when (and (= origin bol) (eq last-command this-command))
23777 (goto-char refpos))
23778 (when (or (> origin refpos) (= origin bol))
23779 (goto-char refpos)))))
23780 ((and (looking-at org-list-full-item-re)
23781 (memq (org-element-type (save-match-data (org-element-at-point)))
23782 '(item plain-list)))
23783 ;; Set special position at first white space character after
23784 ;; bullet, and check-box, if any.
23785 (let ((after-bullet
23786 (let ((box (match-end 3)))
23787 (cond ((not box) (match-end 1))
23788 ((eq (char-after box) ?\s) (1+ box))
23789 (t box)))))
23790 (if (eq special 'reversed)
23791 (when (and (= (point) origin) (eq last-command this-command))
23792 (goto-char after-bullet))
23793 (when (or (> origin after-bullet) (= (point) origin))
23794 (goto-char after-bullet)))))
23795 ;; No special context. Point is already at beginning of line.
23796 (t nil))))
23798 (defun org-end-of-line (&optional n)
23799 "Go to the end of the line, but before ellipsis, if any.
23801 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23802 tags on the first attempt, and only move to after the tags when
23803 the cursor is already beyond the end of the headline.
23805 With argument N not nil or 1, move forward N - 1 lines first."
23806 (interactive "^p")
23807 (let ((origin (point))
23808 (special (pcase org-special-ctrl-a/e
23809 (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
23810 deactivate-mark)
23811 ;; First move to a visible line.
23812 (if (bound-and-true-p visual-line-mode)
23813 (beginning-of-visual-line n)
23814 (move-beginning-of-line n))
23815 (cond
23816 ;; At a headline, with tags.
23817 ((and special
23818 (save-excursion
23819 (beginning-of-line)
23820 (let ((case-fold-search nil))
23821 (looking-at org-complex-heading-regexp)))
23822 (match-end 5))
23823 (let ((tags (save-excursion
23824 (goto-char (match-beginning 5))
23825 (skip-chars-backward " \t")
23826 (point)))
23827 (visual-end (and (bound-and-true-p visual-line-mode)
23828 (save-excursion
23829 (end-of-visual-line)
23830 (point)))))
23831 ;; If `end-of-visual-line' brings us before end of line or
23832 ;; even tags, i.e., the headline spans over multiple visual
23833 ;; lines, move there.
23834 (cond ((and visual-end
23835 (< visual-end tags)
23836 (<= origin visual-end))
23837 (goto-char visual-end))
23838 ((eq special 'reversed)
23839 (if (and (= origin (line-end-position))
23840 (eq this-command last-command))
23841 (goto-char tags)
23842 (end-of-line)))
23844 (if (or (< origin tags) (= origin (line-end-position)))
23845 (goto-char tags)
23846 (end-of-line))))))
23847 ((bound-and-true-p visual-line-mode)
23848 (let ((bol (line-beginning-position)))
23849 (end-of-visual-line)
23850 ;; If `end-of-visual-line' gets us past the ellipsis at the
23851 ;; end of a line, backtrack and use `end-of-line' instead.
23852 (when (/= bol (line-beginning-position))
23853 (goto-char bol)
23854 (end-of-line))))
23855 (t (end-of-line)))))
23857 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23858 (define-key org-mode-map "\C-e" 'org-end-of-line)
23860 (defun org-backward-sentence (&optional _arg)
23861 "Go to beginning of sentence, or beginning of table field.
23862 This will call `backward-sentence' or `org-table-beginning-of-field',
23863 depending on context."
23864 (interactive)
23865 (let* ((element (org-element-at-point))
23866 (contents-begin (org-element-property :contents-begin element))
23867 (table (org-element-lineage element '(table) t)))
23868 (if (and table
23869 (> (point) contents-begin)
23870 (<= (point) (org-element-property :contents-end table)))
23871 (call-interactively #'org-table-beginning-of-field)
23872 (save-restriction
23873 (when (and contents-begin
23874 (< (point-min) contents-begin)
23875 (> (point) contents-begin))
23876 (narrow-to-region contents-begin
23877 (org-element-property :contents-end element)))
23878 (call-interactively #'backward-sentence)))))
23880 (defun org-forward-sentence (&optional _arg)
23881 "Go to end of sentence, or end of table field.
23882 This will call `forward-sentence' or `org-table-end-of-field',
23883 depending on context."
23884 (interactive)
23885 (let* ((element (org-element-at-point))
23886 (contents-end (org-element-property :contents-end element))
23887 (table (org-element-lineage element '(table) t)))
23888 (if (and table
23889 (>= (point) (org-element-property :contents-begin table))
23890 (< (point) contents-end))
23891 (call-interactively #'org-table-end-of-field)
23892 (save-restriction
23893 (when (and contents-end
23894 (> (point-max) contents-end)
23895 ;; Skip blank lines between elements.
23896 (< (org-element-property :end element)
23897 (save-excursion (goto-char contents-end)
23898 (skip-chars-forward " \r\t\n"))))
23899 (narrow-to-region (org-element-property :contents-begin element)
23900 contents-end))
23901 (call-interactively #'forward-sentence)))))
23903 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23904 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23906 (defun org-kill-line (&optional _arg)
23907 "Kill line, to tags or end of line."
23908 (interactive)
23909 (cond
23910 ((or (not org-special-ctrl-k)
23911 (bolp)
23912 (not (org-at-heading-p)))
23913 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23914 org-ctrl-k-protect-subtree
23915 (or (eq org-ctrl-k-protect-subtree 'error)
23916 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23917 (user-error "C-k aborted as it would kill a hidden subtree"))
23918 (call-interactively
23919 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23920 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23921 (kill-region (point) (match-beginning 1))
23922 (org-set-tags nil t))
23923 (t (kill-region (point) (point-at-eol)))))
23925 (define-key org-mode-map "\C-k" 'org-kill-line)
23927 (defun org-yank (&optional arg)
23928 "Yank. If the kill is a subtree, treat it specially.
23929 This command will look at the current kill and check if is a single
23930 subtree, or a series of subtrees[1]. If it passes the test, and if the
23931 cursor is at the beginning of a line or after the stars of a currently
23932 empty headline, then the yank is handled specially. How exactly depends
23933 on the value of the following variables.
23935 `org-yank-folded-subtrees'
23936 By default, this variable is non-nil, which results in
23937 subtree(s) being folded after insertion, except if doing so
23938 would swallow text after the yanked text.
23940 `org-yank-adjusted-subtrees'
23941 When non-nil (the default value is nil), the subtree will be
23942 promoted or demoted in order to fit into the local outline tree
23943 structure, which means that the level will be adjusted so that it
23944 becomes the smaller one of the two *visible* surrounding headings.
23946 Any prefix to this command will cause `yank' to be called directly with
23947 no special treatment. In particular, a simple `\\[universal-argument]' prefix \
23948 will just
23949 plainly yank the text as it is.
23951 \[1] The test checks if the first non-white line is a heading
23952 and if there are no other headings with fewer stars."
23953 (interactive "P")
23954 (org-yank-generic 'yank arg))
23956 (defun org-yank-generic (command arg)
23957 "Perform some yank-like command.
23959 This function implements the behavior described in the `org-yank'
23960 documentation. However, it has been generalized to work for any
23961 interactive command with similar behavior."
23963 ;; pretend to be command COMMAND
23964 (setq this-command command)
23966 (if arg
23967 (call-interactively command)
23969 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
23970 (and (org-kill-is-subtree-p)
23971 (or (bolp)
23972 (and (looking-at "[ \t]*$")
23973 (string-match
23974 "\\`\\*+\\'"
23975 (buffer-substring (point-at-bol) (point)))))))
23976 swallowp)
23977 (cond
23978 ((and subtreep org-yank-folded-subtrees)
23979 (let ((beg (point))
23980 end)
23981 (if (and subtreep org-yank-adjusted-subtrees)
23982 (org-paste-subtree nil nil 'for-yank)
23983 (call-interactively command))
23985 (setq end (point))
23986 (goto-char beg)
23987 (when (and (bolp) subtreep
23988 (not (setq swallowp
23989 (org-yank-folding-would-swallow-text beg end))))
23990 (org-with-limited-levels
23991 (or (looking-at org-outline-regexp)
23992 (re-search-forward org-outline-regexp-bol end t))
23993 (while (and (< (point) end) (looking-at org-outline-regexp))
23994 (outline-hide-subtree)
23995 (org-cycle-show-empty-lines 'folded)
23996 (condition-case nil
23997 (outline-forward-same-level 1)
23998 (error (goto-char end))))))
23999 (when swallowp
24000 (message
24001 "Inserted text not folded because that would swallow text"))
24003 (goto-char end)
24004 (skip-chars-forward " \t\n\r")
24005 (beginning-of-line 1)
24006 (push-mark beg 'nomsg)))
24007 ((and subtreep org-yank-adjusted-subtrees)
24008 (let ((beg (point-at-bol)))
24009 (org-paste-subtree nil nil 'for-yank)
24010 (push-mark beg 'nomsg)))
24012 (call-interactively command))))))
24014 (defun org-yank-folding-would-swallow-text (beg end)
24015 "Would hide-subtree at BEG swallow any text after END?"
24016 (let (level)
24017 (org-with-limited-levels
24018 (save-excursion
24019 (goto-char beg)
24020 (when (or (looking-at org-outline-regexp)
24021 (re-search-forward org-outline-regexp-bol end t))
24022 (setq level (org-outline-level)))
24023 (goto-char end)
24024 (skip-chars-forward " \t\r\n\v\f")
24025 (not (or (eobp)
24026 (and (bolp) (looking-at-p org-outline-regexp)
24027 (<= (org-outline-level) level))))))))
24029 (define-key org-mode-map "\C-y" 'org-yank)
24031 (defun org-truely-invisible-p ()
24032 "Check if point is at a character currently not visible.
24033 This version does not only check the character property, but also
24034 `visible-mode'."
24035 ;; Early versions of noutline don't have `outline-invisible-p'.
24036 (unless (bound-and-true-p visible-mode)
24037 (outline-invisible-p)))
24039 (defun org-invisible-p2 ()
24040 "Check if point is at a character currently not visible."
24041 (save-excursion
24042 (when (and (eolp) (not (bobp))) (backward-char 1))
24043 ;; Early versions of noutline don't have `outline-invisible-p'.
24044 (outline-invisible-p)))
24046 (defun org-back-to-heading (&optional invisible-ok)
24047 "Call `outline-back-to-heading', but provide a better error message."
24048 (condition-case nil
24049 (outline-back-to-heading invisible-ok)
24050 (error (error "Before first headline at position %d in buffer %s"
24051 (point) (current-buffer)))))
24053 (defun org-before-first-heading-p ()
24054 "Before first heading?"
24055 (save-excursion
24056 (end-of-line)
24057 (null (re-search-backward org-outline-regexp-bol nil t))))
24059 (defun org-at-heading-p (&optional ignored)
24060 (outline-on-heading-p t))
24062 (defun org-in-commented-heading-p (&optional no-inheritance)
24063 "Non-nil if point is under a commented heading.
24064 This function also checks ancestors of the current headline,
24065 unless optional argument NO-INHERITANCE is non-nil."
24066 (cond
24067 ((org-before-first-heading-p) nil)
24068 ((let ((headline (nth 4 (org-heading-components))))
24069 (and headline
24070 (let ((case-fold-search nil))
24071 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24072 headline)))))
24073 (no-inheritance nil)
24075 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24077 (defun org-at-comment-p nil
24078 "Is cursor in a commented line?"
24079 (save-excursion
24080 (save-match-data
24081 (beginning-of-line)
24082 (looking-at "^[ \t]*# "))))
24084 (defun org-at-drawer-p nil
24085 "Is cursor at a drawer keyword?"
24086 (save-excursion
24087 (move-beginning-of-line 1)
24088 (looking-at org-drawer-regexp)))
24090 (defun org-at-block-p nil
24091 "Is cursor at a block keyword?"
24092 (save-excursion
24093 (move-beginning-of-line 1)
24094 (looking-at org-block-regexp)))
24096 (defun org-point-at-end-of-empty-headline ()
24097 "If point is at the end of an empty headline, return t, else nil.
24098 If the heading only contains a TODO keyword, it is still still considered
24099 empty."
24100 (let ((case-fold-search nil))
24101 (and (looking-at "[ \t]*$")
24102 org-todo-line-regexp
24103 (save-excursion
24104 (beginning-of-line)
24105 (looking-at org-todo-line-regexp)
24106 (string= (match-string 3) "")))))
24108 (defun org-at-heading-or-item-p ()
24109 (or (org-at-heading-p) (org-at-item-p)))
24111 (defun org-at-target-p ()
24112 (or (org-in-regexp org-radio-target-regexp)
24113 (org-in-regexp org-target-regexp)))
24114 ;; Compatibility alias with Org versions < 7.8.03
24115 (defalias 'org-on-target-p 'org-at-target-p)
24117 (defun org-up-heading-all (arg)
24118 "Move to the heading line of which the present line is a subheading.
24119 This function considers both visible and invisible heading lines.
24120 With argument, move up ARG levels."
24121 (outline-up-heading arg t))
24123 (defun org-up-heading-safe ()
24124 "Move to the heading line of which the present line is a subheading.
24125 This version will not throw an error. It will return the level of the
24126 headline found, or nil if no higher level is found.
24128 Also, this function will be a lot faster than `outline-up-heading',
24129 because it relies on stars being the outline starters. This can really
24130 make a significant difference in outlines with very many siblings."
24131 (when (ignore-errors (org-back-to-heading t))
24132 (let ((level-up (1- (funcall outline-level))))
24133 (and (> level-up 0)
24134 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24135 (funcall outline-level)))))
24137 (defun org-first-sibling-p ()
24138 "Is this heading the first child of its parents?"
24139 (interactive)
24140 (let ((re org-outline-regexp-bol)
24141 level l)
24142 (unless (org-at-heading-p t)
24143 (user-error "Not at a heading"))
24144 (setq level (funcall outline-level))
24145 (save-excursion
24146 (if (not (re-search-backward re nil t))
24148 (setq l (funcall outline-level))
24149 (< l level)))))
24151 (defun org-goto-sibling (&optional previous)
24152 "Goto the next sibling, even if it is invisible.
24153 When PREVIOUS is set, go to the previous sibling instead. Returns t
24154 when a sibling was found. When none is found, return nil and don't
24155 move point."
24156 (let ((fun (if previous 're-search-backward 're-search-forward))
24157 (pos (point))
24158 (re org-outline-regexp-bol)
24159 level l)
24160 (when (ignore-errors (org-back-to-heading t))
24161 (setq level (funcall outline-level))
24162 (catch 'exit
24163 (or previous (forward-char 1))
24164 (while (funcall fun re nil t)
24165 (setq l (funcall outline-level))
24166 (when (< l level) (goto-char pos) (throw 'exit nil))
24167 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24168 (goto-char pos)
24169 nil))))
24171 (defun org-show-siblings ()
24172 "Show all siblings of the current headline."
24173 (save-excursion
24174 (while (org-goto-sibling) (org-flag-heading nil)))
24175 (save-excursion
24176 (while (org-goto-sibling 'previous)
24177 (org-flag-heading nil))))
24179 (defun org-goto-first-child ()
24180 "Goto the first child, even if it is invisible.
24181 Return t when a child was found. Otherwise don't move point and
24182 return nil."
24183 (let (level (pos (point)) (re org-outline-regexp-bol))
24184 (when (ignore-errors (org-back-to-heading t))
24185 (setq level (outline-level))
24186 (forward-char 1)
24187 (if (and (re-search-forward re nil t) (> (outline-level) level))
24188 (progn (goto-char (match-beginning 0)) t)
24189 (goto-char pos) nil))))
24191 (defun org-show-hidden-entry ()
24192 "Show an entry where even the heading is hidden."
24193 (save-excursion
24194 (org-show-entry)))
24196 (defun org-flag-heading (flag &optional entry)
24197 "Flag the current heading. FLAG non-nil means make invisible.
24198 When ENTRY is non-nil, show the entire entry."
24199 (save-excursion
24200 (org-back-to-heading t)
24201 ;; Check if we should show the entire entry
24202 (if entry
24203 (progn
24204 (org-show-entry)
24205 (save-excursion
24206 (and (outline-next-heading)
24207 (org-flag-heading nil))))
24208 (outline-flag-region (max (point-min) (1- (point)))
24209 (save-excursion (outline-end-of-heading) (point))
24210 flag))))
24212 (defun org-get-next-sibling ()
24213 "Move to next heading of the same level, and return point.
24214 If there is no such heading, return nil.
24215 This is like outline-next-sibling, but invisible headings are ok."
24216 (let ((level (funcall outline-level)))
24217 (outline-next-heading)
24218 (while (and (not (eobp)) (> (funcall outline-level) level))
24219 (outline-next-heading))
24220 (unless (or (eobp) (< (funcall outline-level) level))
24221 (point))))
24223 (defun org-get-last-sibling ()
24224 "Move to previous heading of the same level, and return point.
24225 If there is no such heading, return nil."
24226 (let ((opoint (point))
24227 (level (funcall outline-level)))
24228 (outline-previous-heading)
24229 (when (and (/= (point) opoint) (outline-on-heading-p t))
24230 (while (and (> (funcall outline-level) level)
24231 (not (bobp)))
24232 (outline-previous-heading))
24233 (unless (< (funcall outline-level) level)
24234 (point)))))
24236 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24237 "Goto to the end of a subtree."
24238 ;; This contains an exact copy of the original function, but it uses
24239 ;; `org-back-to-heading', to make it work also in invisible
24240 ;; trees. And is uses an invisible-ok argument.
24241 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24242 ;; Furthermore, when used inside Org, finding the end of a large subtree
24243 ;; with many children and grandchildren etc, this can be much faster
24244 ;; than the outline version.
24245 (org-back-to-heading invisible-ok)
24246 (let ((first t)
24247 (level (funcall outline-level)))
24248 (if (and (derived-mode-p 'org-mode) (< level 1000))
24249 ;; A true heading (not a plain list item), in Org
24250 ;; This means we can easily find the end by looking
24251 ;; only for the right number of stars. Using a regexp to do
24252 ;; this is so much faster than using a Lisp loop.
24253 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24254 (forward-char 1)
24255 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24256 ;; something else, do it the slow way
24257 (while (and (not (eobp))
24258 (or first (> (funcall outline-level) level)))
24259 (setq first nil)
24260 (outline-next-heading)))
24261 (unless to-heading
24262 (when (memq (preceding-char) '(?\n ?\^M))
24263 ;; Go to end of line before heading
24264 (forward-char -1)
24265 (when (memq (preceding-char) '(?\n ?\^M))
24266 ;; leave blank line before heading
24267 (forward-char -1)))))
24268 (point))
24270 (defun org-end-of-meta-data (&optional full)
24271 "Skip planning line and properties drawer in current entry.
24272 When optional argument FULL is non-nil, also skip empty lines,
24273 clocking lines and regular drawers at the beginning of the
24274 entry."
24275 (org-back-to-heading t)
24276 (forward-line)
24277 (when (looking-at-p org-planning-line-re) (forward-line))
24278 (when (looking-at org-property-drawer-re)
24279 (goto-char (match-end 0))
24280 (forward-line))
24281 (when (and full (not (org-at-heading-p)))
24282 (catch 'exit
24283 (let ((end (save-excursion (outline-next-heading) (point)))
24284 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24285 (while (not (eobp))
24286 (cond ((looking-at-p org-drawer-regexp)
24287 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24288 (forward-line)
24289 (throw 'exit t)))
24290 ((looking-at-p re) (forward-line))
24291 (t (throw 'exit t))))))))
24293 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24294 "Move forward to the ARG'th subheading at same level as this one.
24295 Stop at the first and last subheadings of a superior heading.
24296 Normally this only looks at visible headings, but when INVISIBLE-OK is
24297 non-nil it will also look at invisible ones."
24298 (interactive "p")
24299 (let ((backward? (and arg (< arg 0))))
24300 (if (org-before-first-heading-p)
24301 (if backward? (goto-char (point-min)) (outline-next-heading))
24302 (org-back-to-heading invisible-ok)
24303 (unless backward? (end-of-line)) ;do not match current headline
24304 (let ((level (- (match-end 0) (match-beginning 0) 1))
24305 (f (if backward? #'re-search-backward #'re-search-forward))
24306 (count (if arg (abs arg) 1))
24307 (result (point)))
24308 (while (and (> count 0)
24309 (funcall f org-outline-regexp-bol nil 'move))
24310 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24311 (cond ((< l level) (setq count 0))
24312 ((and (= l level)
24313 (or invisible-ok
24314 (not (outline-invisible-p
24315 (line-beginning-position)))))
24316 (cl-decf count)
24317 (when (= l level) (setq result (point)))))))
24318 (goto-char result))
24319 (beginning-of-line))))
24321 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24322 "Move backward to the ARG'th subheading at same level as this one.
24323 Stop at the first and last subheadings of a superior heading."
24324 (interactive "p")
24325 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24327 (defun org-next-visible-heading (arg)
24328 "Move to the next visible heading.
24330 This function wraps `outline-next-visible-heading' with
24331 `org-with-limited-levels' in order to skip over inline tasks and
24332 respect customization of `org-odd-levels-only'."
24333 (interactive "p")
24334 (org-with-limited-levels
24335 (outline-next-visible-heading arg)))
24337 (defun org-previous-visible-heading (arg)
24338 "Move to the previous visible heading.
24340 This function wraps `outline-previous-visible-heading' with
24341 `org-with-limited-levels' in order to skip over inline tasks and
24342 respect customization of `org-odd-levels-only'."
24343 (interactive "p")
24344 (org-with-limited-levels
24345 (outline-previous-visible-heading arg)))
24347 (defun org-next-block (arg &optional backward block-regexp)
24348 "Jump to the next block.
24350 With a prefix argument ARG, jump forward ARG many blocks.
24352 When BACKWARD is non-nil, jump to the previous block.
24354 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24355 Match data is set according to this regexp when the function
24356 returns.
24358 Return point at beginning of the opening line of found block.
24359 Throw an error if no block is found."
24360 (interactive "p")
24361 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24362 (case-fold-search t)
24363 (search-fn (if backward #'re-search-backward #'re-search-forward))
24364 (count (or arg 1))
24365 (origin (point))
24366 last-element)
24367 (if backward (beginning-of-line) (end-of-line))
24368 (while (and (> count 0) (funcall search-fn re nil t))
24369 (let ((element (save-excursion
24370 (goto-char (match-beginning 0))
24371 (save-match-data (org-element-at-point)))))
24372 (when (and (memq (org-element-type element)
24373 '(center-block comment-block dynamic-block
24374 example-block export-block quote-block
24375 special-block src-block verse-block))
24376 (<= (match-beginning 0)
24377 (org-element-property :post-affiliated element)))
24378 (setq last-element element)
24379 (cl-decf count))))
24380 (if (= count 0)
24381 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24382 (save-match-data (org-show-context)))
24383 (goto-char origin)
24384 (user-error "No %s code blocks" (if backward "previous" "further")))))
24386 (defun org-previous-block (arg &optional block-regexp)
24387 "Jump to the previous block.
24388 With a prefix argument ARG, jump backward ARG many source blocks.
24389 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24390 (interactive "p")
24391 (org-next-block arg t block-regexp))
24393 (defun org-forward-paragraph ()
24394 "Move forward to beginning of next paragraph or equivalent.
24396 The function moves point to the beginning of the next visible
24397 structural element, which can be a paragraph, a table, a list
24398 item, etc. It also provides some special moves for convenience:
24400 - On an affiliated keyword, jump to the beginning of the
24401 relative element.
24402 - On an item or a footnote definition, move to the second
24403 element inside, if any.
24404 - On a table or a property drawer, jump after it.
24405 - On a verse or source block, stop after blank lines."
24406 (interactive)
24407 (when (eobp) (user-error "Cannot move further down"))
24408 (let* ((deactivate-mark nil)
24409 (element (org-element-at-point))
24410 (type (org-element-type element))
24411 (post-affiliated (org-element-property :post-affiliated element))
24412 (contents-begin (org-element-property :contents-begin element))
24413 (contents-end (org-element-property :contents-end element))
24414 (end (let ((end (org-element-property :end element)) (parent element))
24415 (while (and (setq parent (org-element-property :parent parent))
24416 (= (org-element-property :contents-end parent) end))
24417 (setq end (org-element-property :end parent)))
24418 end)))
24419 (cond ((not element)
24420 (skip-chars-forward " \r\t\n")
24421 (or (eobp) (beginning-of-line)))
24422 ;; On affiliated keywords, move to element's beginning.
24423 ((< (point) post-affiliated)
24424 (goto-char post-affiliated))
24425 ;; At a table row, move to the end of the table. Similarly,
24426 ;; at a node property, move to the end of the property
24427 ;; drawer.
24428 ((memq type '(node-property table-row))
24429 (goto-char (org-element-property
24430 :end (org-element-property :parent element))))
24431 ((memq type '(property-drawer table)) (goto-char end))
24432 ;; Consider blank lines as separators in verse and source
24433 ;; blocks to ease editing.
24434 ((memq type '(src-block verse-block))
24435 (when (eq type 'src-block)
24436 (setq contents-end
24437 (save-excursion (goto-char end)
24438 (skip-chars-backward " \r\t\n")
24439 (line-beginning-position))))
24440 (beginning-of-line)
24441 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24442 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24443 (goto-char end)
24444 (skip-chars-forward " \r\t\n")
24445 (if (= (point) contents-end) (goto-char end)
24446 (beginning-of-line))))
24447 ;; With no contents, just skip element.
24448 ((not contents-begin) (goto-char end))
24449 ;; If contents are invisible, skip the element altogether.
24450 ((outline-invisible-p (line-end-position))
24451 (cl-case type
24452 (headline
24453 (org-with-limited-levels (outline-next-visible-heading 1)))
24454 ;; At a plain list, make sure we move to the next item
24455 ;; instead of skipping the whole list.
24456 (plain-list (forward-char)
24457 (org-forward-paragraph))
24458 (otherwise (goto-char end))))
24459 ((>= (point) contents-end) (goto-char end))
24460 ((>= (point) contents-begin)
24461 ;; This can only happen on paragraphs and plain lists.
24462 (cl-case type
24463 (paragraph (goto-char end))
24464 ;; At a plain list, try to move to second element in
24465 ;; first item, if possible.
24466 (plain-list (end-of-line)
24467 (org-forward-paragraph))))
24468 ;; When contents start on the middle of a line (e.g. in
24469 ;; items and footnote definitions), try to reach first
24470 ;; element starting after current line.
24471 ((> (line-end-position) contents-begin)
24472 (end-of-line)
24473 (org-forward-paragraph))
24474 (t (goto-char contents-begin)))))
24476 (defun org-backward-paragraph ()
24477 "Move backward to start of previous paragraph or equivalent.
24479 The function moves point to the beginning of the current
24480 structural element, which can be a paragraph, a table, a list
24481 item, etc., or to the beginning of the previous visible one if
24482 point is already there. It also provides some special moves for
24483 convenience:
24485 - On an affiliated keyword, jump to the first one.
24486 - On a table or a property drawer, move to its beginning.
24487 - On a verse or source block, stop before blank lines."
24488 (interactive)
24489 (when (bobp) (user-error "Cannot move further up"))
24490 (let* ((deactivate-mark nil)
24491 (element (org-element-at-point))
24492 (type (org-element-type element))
24493 (contents-begin (org-element-property :contents-begin element))
24494 (contents-end (org-element-property :contents-end element))
24495 (post-affiliated (org-element-property :post-affiliated element))
24496 (begin (org-element-property :begin element)))
24497 (cond
24498 ((not element) (goto-char (point-min)))
24499 ((= (point) begin)
24500 (backward-char)
24501 (org-backward-paragraph))
24502 ((<= (point) post-affiliated) (goto-char begin))
24503 ((memq type '(node-property table-row))
24504 (goto-char (org-element-property
24505 :post-affiliated (org-element-property :parent element))))
24506 ((memq type '(property-drawer table)) (goto-char begin))
24507 ((memq type '(src-block verse-block))
24508 (when (eq type 'src-block)
24509 (setq contents-begin
24510 (save-excursion (goto-char begin) (forward-line) (point))))
24511 (if (= (point) contents-begin) (goto-char post-affiliated)
24512 ;; Inside a verse block, see blank lines as paragraph
24513 ;; separators.
24514 (let ((origin (point)))
24515 (skip-chars-backward " \r\t\n" contents-begin)
24516 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24517 (skip-chars-forward " \r\t\n" origin)
24518 (if (= (point) origin) (goto-char contents-begin)
24519 (beginning-of-line))))))
24520 ((not contents-begin) (goto-char (or post-affiliated begin)))
24521 ((eq type 'paragraph)
24522 (goto-char contents-begin)
24523 ;; When at first paragraph in an item or a footnote definition,
24524 ;; move directly to beginning of line.
24525 (let ((parent-contents
24526 (org-element-property
24527 :contents-begin (org-element-property :parent element))))
24528 (when (and parent-contents (= parent-contents contents-begin))
24529 (beginning-of-line))))
24530 ;; At the end of a greater element, move to the beginning of the
24531 ;; last element within.
24532 ((>= (point) contents-end)
24533 (goto-char (1- contents-end))
24534 (org-backward-paragraph))
24535 (t (goto-char (or post-affiliated begin))))
24536 ;; Ensure we never leave point invisible.
24537 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24539 (defun org-forward-element ()
24540 "Move forward by one element.
24541 Move to the next element at the same level, when possible."
24542 (interactive)
24543 (cond ((eobp) (user-error "Cannot move further down"))
24544 ((org-with-limited-levels (org-at-heading-p))
24545 (let ((origin (point)))
24546 (goto-char (org-end-of-subtree nil t))
24547 (unless (org-with-limited-levels (org-at-heading-p))
24548 (goto-char origin)
24549 (user-error "Cannot move further down"))))
24551 (let* ((elem (org-element-at-point))
24552 (end (org-element-property :end elem))
24553 (parent (org-element-property :parent elem)))
24554 (cond ((and parent (= (org-element-property :contents-end parent) end))
24555 (goto-char (org-element-property :end parent)))
24556 ((integer-or-marker-p end) (goto-char end))
24557 (t (message "No element at point")))))))
24559 (defun org-backward-element ()
24560 "Move backward by one element.
24561 Move to the previous element at the same level, when possible."
24562 (interactive)
24563 (cond ((bobp) (user-error "Cannot move further up"))
24564 ((org-with-limited-levels (org-at-heading-p))
24565 ;; At a headline, move to the previous one, if any, or stay
24566 ;; here.
24567 (let ((origin (point)))
24568 (org-with-limited-levels (org-backward-heading-same-level 1))
24569 ;; When current headline has no sibling above, move to its
24570 ;; parent.
24571 (when (= (point) origin)
24572 (or (org-with-limited-levels (org-up-heading-safe))
24573 (progn (goto-char origin)
24574 (user-error "Cannot move further up"))))))
24576 (let* ((elem (org-element-at-point))
24577 (beg (org-element-property :begin elem)))
24578 (cond
24579 ;; Move to beginning of current element if point isn't
24580 ;; there already.
24581 ((null beg) (message "No element at point"))
24582 ((/= (point) beg) (goto-char beg))
24583 (t (goto-char beg)
24584 (skip-chars-backward " \r\t\n")
24585 (unless (bobp)
24586 (let ((prev (org-element-at-point)))
24587 (goto-char (org-element-property :begin prev))
24588 (while (and (setq prev (org-element-property :parent prev))
24589 (<= (org-element-property :end prev) beg))
24590 (goto-char (org-element-property :begin prev)))))))))))
24592 (defun org-up-element ()
24593 "Move to upper element."
24594 (interactive)
24595 (if (org-with-limited-levels (org-at-heading-p))
24596 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24597 (let* ((elem (org-element-at-point))
24598 (parent (org-element-property :parent elem)))
24599 (if parent (goto-char (org-element-property :begin parent))
24600 (if (org-with-limited-levels (org-before-first-heading-p))
24601 (user-error "No surrounding element")
24602 (org-with-limited-levels (org-back-to-heading)))))))
24604 (defun org-down-element ()
24605 "Move to inner element."
24606 (interactive)
24607 (let ((element (org-element-at-point)))
24608 (cond
24609 ((memq (org-element-type element) '(plain-list table))
24610 (goto-char (org-element-property :contents-begin element))
24611 (forward-char))
24612 ((memq (org-element-type element) org-element-greater-elements)
24613 ;; If contents are hidden, first disclose them.
24614 (when (outline-invisible-p (line-end-position)) (org-cycle))
24615 (goto-char (or (org-element-property :contents-begin element)
24616 (user-error "No content for this element"))))
24617 (t (user-error "No inner element")))))
24619 (defun org-drag-element-backward ()
24620 "Move backward element at point."
24621 (interactive)
24622 (let ((elem (or (org-element-at-point)
24623 (user-error "No element at point"))))
24624 (if (eq (org-element-type elem) 'headline)
24625 ;; Preserve point when moving a whole tree, even if point was
24626 ;; on blank lines below the headline.
24627 (let ((offset (skip-chars-backward " \t\n")))
24628 (unwind-protect (org-move-subtree-up)
24629 (forward-char (- offset))))
24630 (let ((prev-elem
24631 (save-excursion
24632 (goto-char (org-element-property :begin elem))
24633 (skip-chars-backward " \r\t\n")
24634 (unless (bobp)
24635 (let* ((beg (org-element-property :begin elem))
24636 (prev (org-element-at-point))
24637 (up prev))
24638 (while (and (setq up (org-element-property :parent up))
24639 (<= (org-element-property :end up) beg))
24640 (setq prev up))
24641 prev)))))
24642 ;; Error out if no previous element or previous element is
24643 ;; a parent of the current one.
24644 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24645 (user-error "Cannot drag element backward")
24646 (let ((pos (point)))
24647 (org-element-swap-A-B prev-elem elem)
24648 (goto-char (+ (org-element-property :begin prev-elem)
24649 (- pos (org-element-property :begin elem))))))))))
24651 (defun org-drag-element-forward ()
24652 "Move forward element at point."
24653 (interactive)
24654 (let* ((pos (point))
24655 (elem (or (org-element-at-point)
24656 (user-error "No element at point"))))
24657 (when (= (point-max) (org-element-property :end elem))
24658 (user-error "Cannot drag element forward"))
24659 (goto-char (org-element-property :end elem))
24660 (let ((next-elem (org-element-at-point)))
24661 (when (or (org-element-nested-p elem next-elem)
24662 (and (eq (org-element-type next-elem) 'headline)
24663 (not (eq (org-element-type elem) 'headline))))
24664 (goto-char pos)
24665 (user-error "Cannot drag element forward"))
24666 ;; Compute new position of point: it's shifted by NEXT-ELEM
24667 ;; body's length (without final blanks) and by the length of
24668 ;; blanks between ELEM and NEXT-ELEM.
24669 (let ((size-next (- (save-excursion
24670 (goto-char (org-element-property :end next-elem))
24671 (skip-chars-backward " \r\t\n")
24672 (forward-line)
24673 ;; Small correction if buffer doesn't end
24674 ;; with a newline character.
24675 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24676 (org-element-property :begin next-elem)))
24677 (size-blank (- (org-element-property :end elem)
24678 (save-excursion
24679 (goto-char (org-element-property :end elem))
24680 (skip-chars-backward " \r\t\n")
24681 (forward-line)
24682 (point)))))
24683 (org-element-swap-A-B elem next-elem)
24684 (goto-char (+ pos size-next size-blank))))))
24686 (defun org-drag-line-forward (arg)
24687 "Drag the line at point ARG lines forward."
24688 (interactive "p")
24689 (dotimes (_ (abs arg))
24690 (let ((c (current-column)))
24691 (if (< 0 arg)
24692 (progn
24693 (beginning-of-line 2)
24694 (transpose-lines 1)
24695 (beginning-of-line 0))
24696 (transpose-lines 1)
24697 (beginning-of-line -1))
24698 (org-move-to-column c))))
24700 (defun org-drag-line-backward (arg)
24701 "Drag the line at point ARG lines backward."
24702 (interactive "p")
24703 (org-drag-line-forward (- arg)))
24705 (defun org-mark-element ()
24706 "Put point at beginning of this element, mark at end.
24708 Interactively, if this command is repeated or (in Transient Mark
24709 mode) if the mark is active, it marks the next element after the
24710 ones already marked."
24711 (interactive)
24712 (let (deactivate-mark)
24713 (if (and (called-interactively-p 'any)
24714 (or (and (eq last-command this-command) (mark t))
24715 (and transient-mark-mode mark-active)))
24716 (set-mark
24717 (save-excursion
24718 (goto-char (mark))
24719 (goto-char (org-element-property :end (org-element-at-point)))))
24720 (let ((element (org-element-at-point)))
24721 (end-of-line)
24722 (push-mark (org-element-property :end element) t t)
24723 (goto-char (org-element-property :begin element))))))
24725 (defun org-narrow-to-element ()
24726 "Narrow buffer to current element."
24727 (interactive)
24728 (let ((elem (org-element-at-point)))
24729 (cond
24730 ((eq (car elem) 'headline)
24731 (narrow-to-region
24732 (org-element-property :begin elem)
24733 (org-element-property :end elem)))
24734 ((memq (car elem) org-element-greater-elements)
24735 (narrow-to-region
24736 (org-element-property :contents-begin elem)
24737 (org-element-property :contents-end elem)))
24739 (narrow-to-region
24740 (org-element-property :begin elem)
24741 (org-element-property :end elem))))))
24743 (defun org-transpose-element ()
24744 "Transpose current and previous elements, keeping blank lines between.
24745 Point is moved after both elements."
24746 (interactive)
24747 (org-skip-whitespace)
24748 (let ((end (org-element-property :end (org-element-at-point))))
24749 (org-drag-element-backward)
24750 (goto-char end)))
24752 (defun org-unindent-buffer ()
24753 "Un-indent the visible part of the buffer.
24754 Relative indentation (between items, inside blocks, etc.) isn't
24755 modified."
24756 (interactive)
24757 (unless (eq major-mode 'org-mode)
24758 (user-error "Cannot un-indent a buffer not in Org mode"))
24759 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24760 (unindent-tree
24761 (lambda (contents)
24762 (dolist (element (reverse contents))
24763 (if (memq (org-element-type element) '(headline section))
24764 (funcall unindent-tree (org-element-contents element))
24765 (save-excursion
24766 (save-restriction
24767 (narrow-to-region
24768 (org-element-property :begin element)
24769 (org-element-property :end element))
24770 (org-do-remove-indentation))))))))
24771 (funcall unindent-tree (org-element-contents parse-tree))))
24773 (defun org-show-children (&optional level)
24774 "Show all direct subheadings of this heading.
24775 Prefix arg LEVEL is how many levels below the current level
24776 should be shown. Default is enough to cause the following
24777 heading to appear."
24778 (interactive "p")
24779 ;; If `orgstruct-mode' is active, use the slower version.
24780 (if orgstruct-mode (call-interactively #'outline-show-children)
24781 (save-excursion
24782 (org-back-to-heading t)
24783 (let* ((current-level (funcall outline-level))
24784 (max-level (org-get-valid-level
24785 current-level
24786 (if level (prefix-numeric-value level) 1)))
24787 (end (save-excursion (org-end-of-subtree t t)))
24788 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24789 (past-first-child nil)
24790 ;; Make sure to skip inlinetasks.
24791 (re (format regexp-fmt
24792 current-level
24793 (cond
24794 ((not (featurep 'org-inlinetask)) "")
24795 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24797 (t (1- org-inlinetask-min-level))))))
24798 ;; Display parent heading.
24799 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24800 (forward-line)
24801 ;; Display children. First child may be deeper than expected
24802 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24803 ;; MAX-LEVEL accordingly.
24804 (while (re-search-forward re end t)
24805 (unless past-first-child
24806 (setq re (format regexp-fmt
24807 current-level
24808 (max (funcall outline-level) max-level)))
24809 (setq past-first-child t))
24810 (outline-flag-region
24811 (line-end-position 0) (line-end-position) nil))))))
24813 (defun org-show-subtree ()
24814 "Show everything after this heading at deeper levels."
24815 (interactive)
24816 (outline-flag-region
24817 (point)
24818 (save-excursion
24819 (org-end-of-subtree t t))
24820 nil))
24822 (defun org-show-entry ()
24823 "Show the body directly following this heading.
24824 Show the heading too, if it is currently invisible."
24825 (interactive)
24826 (save-excursion
24827 (ignore-errors
24828 (org-back-to-heading t)
24829 (outline-flag-region
24830 (max (point-min) (1- (point)))
24831 (save-excursion
24832 (if (re-search-forward
24833 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24834 (match-beginning 1)
24835 (point-max)))
24836 nil)
24837 (org-cycle-hide-drawers 'children))))
24839 (defun org-make-options-regexp (kwds &optional extra)
24840 "Make a regular expression for keyword lines.
24841 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24842 when non-nil, is a regexp matching keywords names."
24843 (concat "^[ \t]*#\\+\\("
24844 (regexp-opt kwds)
24845 (and extra (concat (and kwds "\\|") extra))
24846 "\\):[ \t]*\\(.*\\)"))
24848 ;;;; Integration with and fixes for other packages
24850 ;;; Imenu support
24852 (defvar-local org-imenu-markers nil
24853 "All markers currently used by Imenu.")
24855 (defun org-imenu-new-marker (&optional pos)
24856 "Return a new marker for use by Imenu, and remember the marker."
24857 (let ((m (make-marker)))
24858 (move-marker m (or pos (point)))
24859 (push m org-imenu-markers)
24862 (defun org-imenu-get-tree ()
24863 "Produce the index for Imenu."
24864 (dolist (x org-imenu-markers) (move-marker x nil))
24865 (setq org-imenu-markers nil)
24866 (let* ((case-fold-search nil)
24867 (n org-imenu-depth)
24868 (re (concat "^" (org-get-limited-outline-regexp)))
24869 (subs (make-vector (1+ n) nil))
24870 (last-level 0)
24871 m level head0 head)
24872 (org-with-wide-buffer
24873 (goto-char (point-max))
24874 (while (re-search-backward re nil t)
24875 (setq level (org-reduced-level (funcall outline-level)))
24876 (when (and (<= level n)
24877 (looking-at org-complex-heading-regexp)
24878 (setq head0 (match-string-no-properties 4)))
24879 (setq head (org-link-display-format head0)
24880 m (org-imenu-new-marker))
24881 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24882 (if (>= level last-level)
24883 (push (cons head m) (aref subs level))
24884 (push (cons head (aref subs (1+ level))) (aref subs level))
24885 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24886 (setq last-level level))))
24887 (aref subs 1)))
24889 (eval-after-load "imenu"
24890 '(progn
24891 (add-hook 'imenu-after-jump-hook
24892 (lambda ()
24893 (when (derived-mode-p 'org-mode)
24894 (org-show-context 'org-goto))))))
24896 (defun org-link-display-format (s)
24897 "Replace links in string S with their description.
24898 If there is no description, use the link target."
24899 (save-match-data
24900 (replace-regexp-in-string
24901 org-bracket-link-analytic-regexp
24902 (lambda (m)
24903 (if (match-end 5) (match-string 5 m)
24904 (concat (match-string 1 m) (match-string 3 m))))
24905 s nil t)))
24907 (defun org-toggle-link-display ()
24908 "Toggle the literal or descriptive display of links."
24909 (interactive)
24910 (if org-descriptive-links
24911 (progn (org-remove-from-invisibility-spec '(org-link))
24912 (org-restart-font-lock)
24913 (setq org-descriptive-links nil))
24914 (progn (add-to-invisibility-spec '(org-link))
24915 (org-restart-font-lock)
24916 (setq org-descriptive-links t))))
24918 ;; Speedbar support
24920 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24921 "Overlay marking the agenda restriction line in speedbar.")
24922 (overlay-put org-speedbar-restriction-lock-overlay
24923 'face 'org-agenda-restriction-lock)
24924 (overlay-put org-speedbar-restriction-lock-overlay
24925 'help-echo "Agendas are currently limited to this item.")
24926 (delete-overlay org-speedbar-restriction-lock-overlay)
24928 (defun org-speedbar-set-agenda-restriction ()
24929 "Restrict future agenda commands to the location at point in speedbar.
24930 To get rid of the restriction, use `\\[org-agenda-remove-restriction-lock]'."
24931 (interactive)
24932 (require 'org-agenda)
24933 (let (p m tp np dir txt)
24934 (cond
24935 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24936 'org-imenu t))
24937 (setq m (get-text-property p 'org-imenu-marker))
24938 (with-current-buffer (marker-buffer m)
24939 (goto-char m)
24940 (org-agenda-set-restriction-lock 'subtree)))
24941 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24942 'speedbar-function 'speedbar-find-file))
24943 (setq tp (previous-single-property-change
24944 (1+ p) 'speedbar-function)
24945 np (next-single-property-change
24946 tp 'speedbar-function)
24947 dir (speedbar-line-directory)
24948 txt (buffer-substring-no-properties (or tp (point-min))
24949 (or np (point-max))))
24950 (with-current-buffer (find-file-noselect
24951 (let ((default-directory dir))
24952 (expand-file-name txt)))
24953 (unless (derived-mode-p 'org-mode)
24954 (user-error "Cannot restrict to non-Org mode file"))
24955 (org-agenda-set-restriction-lock 'file)))
24956 (t (user-error "Don't know how to restrict Org mode agenda")))
24957 (move-overlay org-speedbar-restriction-lock-overlay
24958 (point-at-bol) (point-at-eol))
24959 (setq current-prefix-arg nil)
24960 (org-agenda-maybe-redo)))
24962 (defvar speedbar-file-key-map)
24963 (declare-function speedbar-add-supported-extension "speedbar" (extension))
24964 (eval-after-load "speedbar"
24965 '(progn
24966 (speedbar-add-supported-extension ".org")
24967 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
24968 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
24969 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
24970 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
24971 (add-hook 'speedbar-visiting-tag-hook
24972 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
24974 ;;; Fixes and Hacks for problems with other packages
24976 (defun org--flyspell-object-check-p (element)
24977 "Non-nil when Flyspell can check object at point.
24978 ELEMENT is the element at point."
24979 (let ((object (save-excursion
24980 (when (looking-at-p "\\>") (backward-char))
24981 (org-element-context element))))
24982 (cl-case (org-element-type object)
24983 ;; Prevent checks in links due to keybinding conflict with
24984 ;; Flyspell.
24985 ((code entity export-snippet inline-babel-call
24986 inline-src-block line-break latex-fragment link macro
24987 statistics-cookie target timestamp verbatim)
24988 nil)
24989 (footnote-reference
24990 ;; Only in inline footnotes, within the definition.
24991 (and (eq (org-element-property :type object) 'inline)
24992 (< (save-excursion
24993 (goto-char (org-element-property :begin object))
24994 (search-forward ":" nil t 2))
24995 (point))))
24996 (otherwise t))))
24998 (defun org-mode-flyspell-verify ()
24999 "Function used for `flyspell-generic-check-word-predicate'."
25000 (if (org-at-heading-p)
25001 ;; At a headline or an inlinetask, check title only. This is
25002 ;; faster than relying on `org-element-at-point'.
25003 (and (save-excursion (beginning-of-line)
25004 (and (let ((case-fold-search t))
25005 (not (looking-at-p "\\*+ END[ \t]*$")))
25006 (let ((case-fold-search nil))
25007 (looking-at org-complex-heading-regexp))))
25008 (match-beginning 4)
25009 (>= (point) (match-beginning 4))
25010 (or (not (match-beginning 5))
25011 (< (point) (match-beginning 5))))
25012 (let* ((element (org-element-at-point))
25013 (post-affiliated (org-element-property :post-affiliated element)))
25014 (cond
25015 ;; Ignore checks in all affiliated keywords but captions.
25016 ((< (point) post-affiliated)
25017 (and (save-excursion
25018 (beginning-of-line)
25019 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25020 (> (point) (match-end 0))
25021 (org--flyspell-object-check-p element)))
25022 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25023 ((let ((log (org-log-into-drawer)))
25024 (and log
25025 (let ((drawer (org-element-lineage element '(drawer))))
25026 (and drawer
25027 (eq (compare-strings
25028 log nil nil
25029 (org-element-property :drawer-name drawer) nil nil t)
25030 t)))))
25031 nil)
25033 (cl-case (org-element-type element)
25034 ((comment quote-section) t)
25035 (comment-block
25036 ;; Allow checks between block markers, not on them.
25037 (and (> (line-beginning-position) post-affiliated)
25038 (save-excursion
25039 (end-of-line)
25040 (skip-chars-forward " \r\t\n")
25041 (< (point) (org-element-property :end element)))))
25042 ;; Arbitrary list of keywords where checks are meaningful.
25043 ;; Make sure point is on the value part of the element.
25044 (keyword
25045 (and (member (org-element-property :key element)
25046 '("DESCRIPTION" "TITLE"))
25047 (save-excursion
25048 (search-backward ":" (line-beginning-position) t))))
25049 ;; Check is globally allowed in paragraphs verse blocks and
25050 ;; table rows (after affiliated keywords) but some objects
25051 ;; must not be affected.
25052 ((paragraph table-row verse-block)
25053 (let ((cbeg (org-element-property :contents-begin element))
25054 (cend (org-element-property :contents-end element)))
25055 (and cbeg (>= (point) cbeg) (< (point) cend)
25056 (org--flyspell-object-check-p element))))))))))
25057 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25059 (defun org-remove-flyspell-overlays-in (beg end)
25060 "Remove flyspell overlays in region."
25061 (and (bound-and-true-p flyspell-mode)
25062 (fboundp 'flyspell-delete-region-overlays)
25063 (flyspell-delete-region-overlays beg end)))
25065 (defvar flyspell-delayed-commands)
25066 (eval-after-load "flyspell"
25067 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25069 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25070 (eval-after-load "bookmark"
25071 '(if (boundp 'bookmark-after-jump-hook)
25072 ;; We can use the hook
25073 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25074 ;; Hook not available, use advice
25075 (defadvice bookmark-jump (after org-make-visible activate)
25076 "Make the position visible."
25077 (org-bookmark-jump-unhide))))
25079 ;; Make sure saveplace shows the location if it was hidden
25080 (eval-after-load "saveplace"
25081 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25082 "Make the position visible."
25083 (org-bookmark-jump-unhide)))
25085 ;; Make sure ecb shows the location if it was hidden
25086 (eval-after-load "ecb"
25087 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25088 "Make hierarchy visible when jumping into location from ECB tree buffer."
25089 (when (derived-mode-p 'org-mode)
25090 (org-show-context))))
25092 (defun org-bookmark-jump-unhide ()
25093 "Unhide the current position, to show the bookmark location."
25094 (and (derived-mode-p 'org-mode)
25095 (or (outline-invisible-p)
25096 (save-excursion (goto-char (max (point-min) (1- (point))))
25097 (outline-invisible-p)))
25098 (org-show-context 'bookmark-jump)))
25100 (defun org-mark-jump-unhide ()
25101 "Make the point visible with `org-show-context' after jumping to the mark."
25102 (when (and (derived-mode-p 'org-mode)
25103 (outline-invisible-p))
25104 (org-show-context 'mark-goto)))
25106 (eval-after-load "simple"
25107 '(defadvice pop-to-mark-command (after org-make-visible activate)
25108 "Make the point visible with `org-show-context'."
25109 (org-mark-jump-unhide)))
25111 (eval-after-load "simple"
25112 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25113 "Make the point visible with `org-show-context'."
25114 (org-mark-jump-unhide)))
25116 (eval-after-load "simple"
25117 '(defadvice pop-global-mark (after org-make-visible activate)
25118 "Make the point visible with `org-show-context'."
25119 (org-mark-jump-unhide)))
25121 ;; Make session.el ignore our circular variable
25122 (defvar session-globals-exclude)
25123 (eval-after-load "session"
25124 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25126 ;;;; Finish up
25128 (provide 'org)
25130 (run-hooks 'org-load-hook)
25132 ;;; org.el ends here